text stringlengths 14 6.51M |
|---|
{$mode objfpc}{$H+}{$J-}
{$R+} // включаем проверку на диапазон величин, очень полезно для отладки
var
MyArray: array [0..9] of Integer;
I: Integer;
begin
// инициализация
for I := 0 to 9 do
MyArray[I] := I * I;
// отображение
for I := 0 to 9 do
WriteLn('Квадрат составляет ', MyArray[I]);
// делает то же самое, что и предыдущий вариант
for I := Low(MyArray) to High(MyArray) do
WriteLn('Квадрат составляет ', MyArray[I]);
// делает то же самое
I := 0;
while I < 10 do
begin
WriteLn('Квадрат составляет ', MyArray[I]);
I := I + 1; // это идентично "I += 1" или "Inc(I)"
end;
// делает то же самое
I := 0;
repeat
WriteLn('Квадрат составляет ', MyArray[I]);
Inc(I);
until I = 10;
// делает то же самое
// обратите внимание, тут переменная I перечисляет значения элементов массива, а не его индексы
for I in MyArray do
WriteLn('Квадрат составляет ', I);
end. |
unit caTrayIcon;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
Classes,
Windows,
Messages,
Sysutils,
SyncObjs,
Controls,
Forms,
ShellAPI,
Graphics,
Menus,
// ca utils
caTypes,
caUtils,
caFormHook;
const
WM_TRAYICON = WM_USER + 1;
type
//----------------------------------------------------------------------------
// TcaTrayIcon
//----------------------------------------------------------------------------
TcaTrayIcon = class(TcaFormHook)
private
// Private fields
FConfirmShutdown: Boolean;
FDefaultMenuItemsAdded: Boolean;
FIcon: TIcon;
FIconSection: TCriticalSection;
FIconVisible: Boolean;
FOKToClose: Boolean;
// Property fields
FIconHint: string;
FImageIndex: Integer;
FImages: TImageList;
FPopupMenu: TPopupMenu;
FShowMenuItemVisible: Boolean;
FShutdownMenuItemVisible: Boolean;
// Event property fields
FOnShowApplication: TNotifyEvent;
FOnShowPopupMenu: TNotifyEvent;
// Property methods
procedure SetIconHint(const Value: string);
procedure SetImageIndex(const Value: Integer);
procedure SetImages(const Value: TImageList);
// Private methods
function GetIconHandle: HICON;
function OwnerForm: TForm;
function OwnerFormHandle: HWND;
procedure AddDefaultSeparator;
procedure AddDefaultShowMenuItem;
procedure AddDefaultShutdownMenuItem;
procedure CheckDefaultMenuItems;
procedure CleanupSystemTray;
procedure CreateCriticalSection;
procedure FreeCriticalSection;
procedure FormClosing;
procedure FormHiding;
procedure FormShowing;
procedure Minimize;
procedure MouseDoubleClick;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState);
procedure MouseUp(Button: TMouseButton; Shift: TShiftState);
procedure RemoveTrayIcon;
procedure ShowApplication;
procedure ShowPopupMenu;
procedure UpdateTrayIcon;
// Event handlers
procedure MenuItemShowEvent(Sender: TObject);
procedure MenuItemShutdownEvent(Sender: TObject);
protected
// Protected methods
procedure DoFormReceiveMessage(Msg: TMessage; var Handled: Boolean); override;
procedure DoReceiveMessage(Msg: TMessage; var Handled: Boolean); override;
procedure DoShowPopupMenu; virtual;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
public
// Create/Destroy
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
// Public methods
procedure SendToSystemTray;
procedure Shutdown;
// Public properties
property OKToClose: Boolean read FOKToClose write FOKToClose;
property ShowMenuItemVisible: Boolean read FShowMenuItemVisible write FShowMenuItemVisible;
property ShutdownMenuItemVisible: Boolean read FShutdownMenuItemVisible write FShutdownMenuItemVisible;
published
// Published properties
property ConfirmShutdown: Boolean read FConfirmShutdown write FConfirmShutdown;
property IconHint: string read FIconHint write SetIconHint;
property ImageIndex: Integer read FImageIndex write SetImageIndex;
property Images: TImageList read FImages write SetImages;
property PopupMenu: TPopupMenu read FPopupMenu write FPopupMenu;
// Event properties
property OnShowApplication: TNotifyEvent read FOnShowApplication write FOnShowApplication;
property OnShowPopupMenu: TNotifyEvent read FOnShowPopupMenu write FOnShowPopupMenu;
end;
implementation
{$R caTrayIcon.res}
//----------------------------------------------------------------------------
// TcaTrayIcon
//----------------------------------------------------------------------------
// Create/Destroy
constructor TcaTrayIcon.Create(AOwner: TComponent);
begin
inherited;
FShowMenuItemVisible := True;
FShutdownMenuItemVisible := True;
Application.ShowMainForm := False;
CreateCriticalSection;
FIcon := TIcon.Create;
end;
destructor TcaTrayIcon.Destroy;
begin
FreeCriticalSection;
FIcon.Free;
inherited;
end;
// Public methods
procedure TcaTrayIcon.SendToSystemTray;
begin
ShowWindow(OwnerFormHandle, SW_HIDE);
OwnerForm.Visible := False;
end;
procedure TcaTrayIcon.Shutdown;
var
Response: TcaMsgDialogResponse;
begin
FOKToClose := True;
if FConfirmShutdown then
begin
Response := Utils.QueryCloseApp(OwnerFormHandle, 'shutdown');
case Response of
mgYes: FOKToClose := True;
mgNo: FOKToClose := False;
else
FOKToClose := False;
end;
end;
if FOKToClose then
SendMessage(OwnerFormHandle, WM_CLOSE, 0, 0);
end;
// Protected methods
procedure TcaTrayIcon.DoFormReceiveMessage(Msg: TMessage; var Handled: Boolean);
begin
inherited;
case Msg.Msg of
WM_SHOWWINDOW:
begin
if Boolean(Msg.WParam) then
FormShowing
else
FormHiding;
end;
WM_CLOSE:
begin
if FOKToClose then
begin
Unhook;
FormClosing;
RemoveTrayIcon;
CleanupSystemTray;
Application.ProcessMessages;
end
else
begin
SendToSystemTray;
UpdateTrayIcon;
Handled := True;
end;
end;
WM_SYSCOMMAND:
if (Msg.wParam = SC_MINIMIZE) then
begin
Minimize;
Handled := True;
end;
end;
end;
procedure TcaTrayIcon.DoReceiveMessage(Msg: TMessage; var Handled: Boolean);
var
Shift: TShiftState;
Down: Boolean;
Button: TMouseButton;
function IsMouseMessage(AMsg: Word): Boolean;
begin
Result := (AMsg = WM_LBUTTONDOWN) or (AMsg = WM_MBUTTONDOWN) or (AMsg = WM_RBUTTONDOWN) or
(AMsg = WM_LBUTTONUP) or (AMsg = WM_MBUTTONUP) or (AMsg = WM_RBUTTONUP) or (AMsg = WM_LBUTTONDBLCLK);
end;
begin
inherited;
Handled := False;
Button := mbLeft;
Down := False;
if (Msg.Msg = WM_TRAYICON) then
begin
if IsMouseMessage(Msg.lParam) then
begin
Handled := True;
case Msg.lParam of
WM_LBUTTONDOWN, WM_LBUTTONUP, WM_LBUTTONDBLCLK:
Button := mbLeft;
WM_MBUTTONDOWN, WM_MBUTTONUP:
Button := mbMiddle;
WM_RBUTTONDOWN, WM_RBUTTONUP:
Button := mbRight;
end;
case Msg.lParam of
WM_LBUTTONDOWN, WM_MBUTTONDOWN, WM_RBUTTONDOWN:
Down := True;
WM_LBUTTONUP, WM_MBUTTONUP, WM_RBUTTONUP, WM_LBUTTONDBLCLK:
Down := False;
end;
if Msg.lParam = WM_LBUTTONDBLCLK then
begin
if FShowMenuItemVisible then
MouseDoubleClick
else
Handled := False;
end;
Shift := KeysToShiftState(Msg.WParam);
if Down then
MouseDown(Button, Shift)
else
MouseUp(Button, Shift);
end;
end;
end;
procedure TcaTrayIcon.DoShowPopupMenu;
begin
if Assigned(FOnShowPopupMenu) then
FOnShowPopupMenu(Self);
end;
procedure TcaTrayIcon.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FPopupMenu) then
FPopupMenu := nil;
if (Operation = opRemove) and (AComponent = FImages) then
FImages := nil;
end;
// Private methods
function TcaTrayIcon.OwnerForm: TForm;
begin
Result := Owner as TForm;
end;
function TcaTrayIcon.GetIconHandle: HICON;
begin
Result := 0;
if not (csDestroying in ComponentState) then
begin
if Assigned(FImages) and (FImageIndex >= 0) and (FImageIndex < FImages.Count) then
begin
FImages.GetIcon(FImageIndex, FIcon);
// Result := FIcon.ReleaseHandle;
Result := FIcon.Handle;
end;
end;
end;
function TcaTrayIcon.OwnerFormHandle: HWND;
begin
Result := (Owner as TForm).Handle;
end;
procedure TcaTrayIcon.AddDefaultSeparator;
var
MenuItem: TMenuItem;
begin
MenuItem := TMenuItem.Create(FPopupMenu);
MenuItem.Caption := '-';
FPopupMenu.Items.Insert(0, MenuItem);
end;
procedure TcaTrayIcon.AddDefaultShowMenuItem;
var
MenuItem: TMenuItem;
begin
MenuItem := TMenuItem.Create(FPopupMenu);
MenuItem.Caption := 'Show...';
MenuItem.Default := True;
MenuItem.OnClick := MenuItemShowEvent;
MenuItem.Visible := FShowMenuItemVisible;
FPopupMenu.Items.Insert(0, MenuItem);
end;
procedure TcaTrayIcon.AddDefaultShutdownMenuItem;
var
MenuItem: TMenuItem;
begin
MenuItem := TMenuItem.Create(FPopupMenu);
MenuItem.Caption := 'Shutdown';
MenuItem.OnClick := MenuItemShutdownEvent;
MenuItem.Visible := FShutdownMenuItemVisible;
FPopupMenu.Items.Insert(0, MenuItem);
end;
procedure TcaTrayIcon.CheckDefaultMenuItems;
begin
if Assigned(FPopupMenu) and (not FDefaultMenuItemsAdded) then
begin
AddDefaultSeparator;
AddDefaultShutdownMenuItem;
AddDefaultShowMenuItem;
FDefaultMenuItemsAdded := True;
end;
end;
function SystemTrayEnumFunc(AHandle: HWND; lParam: Integer): Boolean;
var
R: TRect;
X: Integer;
Y: Integer;
Buf: array[0..7] of Char;
begin
if GetClientRect(AHandle, R) then
begin
GetClassName(AHandle, Buf, SizeOf(Buf));
if Buf[0] = 'T' then
begin
X := 0;
while X < R.Right do
begin
Y := 2;
while Y < R.Bottom do
begin
PostMessage(AHandle, WM_MOUSEMOVE, 0, MakeLParam(X, Y));
Inc(Y, 8);
end;
Inc(X, 8);
end;
end;
end;
Result := True;
end;
procedure TcaTrayIcon.CleanupSystemTray;
var
TaskbarHandle: HWND;
begin
TaskbarHandle := FindWindow('Shell_TrayWnd', nil);
if TaskbarHandle <> 0 then
EnumChildWindows(TaskbarHandle, @SystemTrayEnumFunc, 0);
end;
procedure TcaTrayIcon.CreateCriticalSection;
begin
FIconSection := TCriticalSection.Create;
end;
procedure TcaTrayIcon.FreeCriticalSection;
begin
FIconSection.Free;
end;
procedure TcaTrayIcon.FormClosing;
begin
end;
procedure TcaTrayIcon.FormHiding;
begin
UpdateTrayIcon;
end;
procedure TcaTrayIcon.FormShowing;
begin
end;
procedure TcaTrayIcon.Minimize;
begin
end;
procedure TcaTrayIcon.MouseDoubleClick;
begin
ShowApplication;
end;
procedure TcaTrayIcon.MouseDown(Button: TMouseButton; Shift: TShiftState);
begin
if Button = mbRight then
ShowPopupMenu
else
begin
end;
end;
procedure TcaTrayIcon.MouseUp(Button: TMouseButton; Shift: TShiftState);
begin
end;
procedure TcaTrayIcon.RemoveTrayIcon;
var
IconData: TNotifyIconData;
begin
FIconSection.Enter;
try
IconData.cbSize := SizeOf(IconData);
IconData.Wnd := Handle;
IconData.uID := Tag;
IconData.uFlags := (NIF_ICON or NIF_TIP or NIF_MESSAGE);
IconData.uCallbackMessage := WM_TRAYICON;
if Shell_NotifyIcon(NIM_DELETE, @IconData) then
FIconVisible := False;
finally
FIconSection.Leave;
end;
end;
procedure TcaTrayIcon.ShowApplication;
var
FormHandle: HWND;
begin
FormHandle := OwnerFormHandle;
if FormHandle <> 0 then
begin
ShowWindow(FormHandle, SW_SHOW);
OwnerForm.Visible := True;
if Assigned(FOnShowApplication) then
FOnShowApplication(Self);
end;
end;
procedure TcaTrayIcon.ShowPopupMenu;
var
MousePos: TPoint;
begin
if Assigned(FPopupMenu) then
begin
DoShowPopupMenu;
CheckDefaultMenuItems;
GetCursorPos(MousePos);
SetForegroundWindow(OwnerFormHandle);
PopupMenu.Popup(MousePos.X, MousePos.Y);
end;
end;
procedure TcaTrayIcon.UpdateTrayIcon;
var
IconData: TNotifyIconData;
begin
if not (csDesigning in ComponentState) and (not FOKToClose) then
begin
FIconSection.Enter;
try
IconData.cbSize := SizeOf(IconData);
IconData.Wnd := Handle;
IconData.uID := Tag;
IconData.uFlags := (NIF_ICON or NIF_TIP or NIF_MESSAGE);
IconData.uCallbackMessage := WM_TRAYICON;
StrPCopy(IconData.szTip, FIconHint);
IconData.hIcon := GetIconHandle;
if FIconVisible then
Shell_NotifyIcon(NIM_MODIFY, @IconData)
else
begin
if Shell_NotifyIcon(NIM_ADD, @IconData) then
FIconVisible := True;
end;
finally
FIconSection.Leave;
end;
end;
end;
// Event handlers
procedure TcaTrayIcon.MenuItemShowEvent(Sender: TObject);
begin
ShowApplication;
end;
procedure TcaTrayIcon.MenuItemShutdownEvent(Sender: TObject);
begin
ShowApplication;
Shutdown;
end;
// Property methods
procedure TcaTrayIcon.SetIconHint(const Value: string);
begin
if Value <> FIconHint then
begin
FIconHint := Value;
UpdateTrayIcon;
end;
end;
procedure TcaTrayIcon.SetImageIndex(const Value: Integer);
begin
if Value <> FImageIndex then
begin
FImageIndex := Value;
UpdateTrayIcon;
end;
end;
procedure TcaTrayIcon.SetImages(const Value: TImageList);
begin
if Value <> FImages then
begin
FImages := Value;
UpdateTrayIcon;
end;
end;
end.
|
unit IdGopherConsts;
interface
uses IdGlobal;
const
IdGopherItem_Document = '0'; // Item is a file
IdGopherItem_Directory = '1'; // Item is a directory
IdGopherItem_CSO = '2'; // Item is a CSO phone-book server
IdGopherItem_Error = '3'; // Error
IdGopherItem_BinHex = '4'; // Item is a BinHexed Macintosh file.
IdGopherItem_BinDOS = '5'; // Item is DOS binary archive of some sort.
// Client must read until the TCP connection closes.
IdGopherItem_UUE = '6'; // Item is a UNIX uuencoded file.
IdGopherItem_Search = '7'; // Item is an Index-Search server.
IdGopherItem_Telnet = '8'; // Item points to a text-based telnet session.
IdGopherItem_Binary = '9'; // Item is a binary file.
// Client must read until the TCP connection closes.
IdGopherItem_Redundant = '+'; // Item is a redundant server
IdGopherItem_TN3270 = 'T'; // Item points to a text-based tn3270 session.
IdGopherItem_GIF = 'g'; // Item is a GIF format graphics file.
IdGopherItem_Image = ':'; // Item is some kind of image file.
// Client decides how to display. Was 'I', but depracted
IdGopherItem_Image2 = 'I'; //Item is some kind of image file -
{"Gopher RFC + - extensions etc}
IdGopherItem_Sound = '<'; //Was 'S', but deprecated
IdGopherItem_Sound2 = 'S';
//This was depreciated but should be used with clients
IdGopherItem_Movie = ';'; //Was 'M', but deprecated
IdGopherItem_HTML = 'h';
IdGopherItem_MIME = 'M'; //See above for a potential conflict with Movie
IdGopherItem_Information = 'i'; // Not a file - just information
IdGopherPlusIndicator = IdGopherItem_Redundant;
IdGopherPlusInformation = '!'; // Formatted information
IdGopherPlusDirectoryInformation = '$';
IdGopherPlusInfo = '+INFO: ';
IdGopherPlusAdmin = '+ADMIN:' + EOL;
IdGopherPlusViews = '+VIEWS:' + EOL;
IdGopherPlusAbstract = '+ABSTRACT:' + EOL;
IdGopherPlusAsk = '+ASK:';
//Questions for +ASK section:
IdGopherPlusAskPassword = 'AskP: ';
IdGopherPlusAskLong = 'AskL: ';
IdGopherPlusAskFileName = 'AskF: ';
// Prompted responses for +ASK section:
IdGopherPlusSelect = 'Select: '; // Multi-choice, multi-selection
IdGopherPlusChoose = 'Choose: '; // Multi-choice, single-selection
IdGopherPlusChooseFile = 'ChooseF: '; //Multi-choice, single-selection
//Known response types:
IdGopherPlusData_BeginSign = '+-1' + EOL;
IdGopherPlusData_EndSign = EOL + '.' + EOL;
IdGopherPlusData_UnknownSize = '+-2' + EOL;
IdGopherPlusData_ErrorBeginSign = '--1' + EOL;
IdGopherPlusData_ErrorUnknownSize = '--2' + EOL;
IdGopherPlusError_NotAvailable = '1';
IdGopherPlusError_TryLater = '2';
IdGopherPlusError_ItemMoved = '3';
implementation
end.
|
unit Samples.Providers.Frames.User;
interface
uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls,
FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Objects, FMX.Layouts, FMX.Controls.Presentation;
type
TUserFrame = class(TFrame)
Layout1: TLayout;
Layout2: TLayout;
imgUser: TImage;
Label1: TLabel;
Label2: TLabel;
lblNome: TLabel;
lblEmail: TLabel;
Rectangle1: TRectangle;
end;
implementation
{$R *.fmx}
end.
|
{
@html(<b>)
ISAPI Application Component
@html(</b>)
- Copyright (c) Danijel Tkalcec
@html(<br><br>)
Partial Copyright (c) Borland Inc.
- TApplication interface compatibility
- Exception Handling
- Component creation
@exclude
}
unit rtcISAPIApp;
{$INCLUDE rtcDefs.inc}
interface
uses
Windows, Classes, SysUtils,
ComObj, ActiveX, Isapi2,
rtcSyncObjs;
type
TRtcISAPIApplication = class(TComponent)
private
FTitle: string;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure CreateForm(InstanceClass: TComponentClass; var Reference); virtual;
procedure Initialize; virtual;
procedure Run; virtual;
// ISAPI entry points ->
function GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL;
function HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD;
function TerminateExtension(dwFlags: DWORD): BOOL;
// <- ISAPI entry points
property Title: string read FTitle write FTitle;
end;
THandleShutdownException = procedure(E: Exception);
var
HandleShutdownException: THandleShutdownException = nil;
Application: TRtcISAPIApplication = nil;
function GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL; stdcall; export;
function HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD; stdcall; export;
function TerminateExtension(dwFlags: DWORD): BOOL; stdcall; export;
exports
GetExtensionVersion,
HttpExtensionProc,
TerminateExtension;
implementation
uses
rtcISAPISrv;
// ISAPI interface
function GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL;
begin
Result := Application.GetExtensionVersion(Ver);
end;
function HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD;
begin
Result := Application.HttpExtensionProc(ECB);
end;
function TerminateExtension(dwFlags: DWORD): BOOL;
begin
Result := Application.TerminateExtension(dwFlags);
end;
{ TRtcISAPIApplication }
type
TDLLProc = procedure (Reason: Integer);
var
OldDllProc: TDLLProc;
rtcLoaded:boolean=False;
procedure DoneVCLApplication;
begin
try
Application.Free;
Application := nil;
except
on E:Exception do
if Assigned(HandleShutdownException) then
begin
Application := nil;
// Classes.ApplicationHandleException := nil;
HandleShutdownException(E);
end;
end;
end;
procedure DLLExitProc(Reason: Integer);
begin
{$IFDEF MSWINDOWS}
if Reason = DLL_PROCESS_DETACH then
DoneVCLApplication;
{$ENDIF}
if Assigned(OldDllProc) then
OldDllProc(Reason);
end;
procedure HandleServerException(E: Exception; var ECB: TEXTENSION_CONTROL_BLOCK);
var
ResultText,
ResultHeaders: string;
Size: DWORD;
begin
ResultText := '<html><h1>Internal Server Error</h1><br>'+
E.ClassName+': '+E.Message;
Size := Length(ResultText);
ECB.dwHTTPStatusCode := 500;
ResultHeaders := 'Content-Type: text/html'#13#10 +
'Content-Length: '+IntToStr(length(ResultText))+#13#10+
#13#10;
ECB.ServerSupportFunction(ECB.ConnID, HSE_REQ_SEND_RESPONSE_HEADER,
PChar('500 ' + E.Message), @Size, LPDWORD(ResultHeaders));
ECB.WriteClient(ECB.ConnID, Pointer(ResultText), Size, 0);
end;
constructor TRtcISAPIApplication.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
if IsLibrary then
begin
IsMultiThread := True;
OldDllProc := DLLProc;
DLLProc := @DLLExitProc;
end
else
AddExitProc(DoneVCLApplication);
end;
destructor TRtcISAPIApplication.Destroy;
begin
if rtcLoaded then
begin
rtcLoaded:=False;
TRtcISAPIServer.UnLoad;
end;
inherited;
end;
function TRtcISAPIApplication.GetExtensionVersion(var Ver: THSE_VERSION_INFO): BOOL;
begin
try
Ver.dwExtensionVersion := MakeLong(HSE_VERSION_MINOR, HSE_VERSION_MAJOR);
StrLCopy(Ver.lpszExtensionDesc, PChar(Title), HSE_MAX_EXT_DLL_NAME_LEN);
Integer(Result) := 1;
except
Result := False;
end;
end;
function TRtcISAPIApplication.HttpExtensionProc(var ECB: TEXTENSION_CONTROL_BLOCK): DWORD;
begin
try
Result:=TRtcISAPIServer.HttpExtensionProc(ECB);
if Result=HSE_STATUS_ERROR then
raise Exception.Create('TRtcISAPIServer.HttpExtensionProc() returned with STATUS_ERROR.<br>'#13#10+
'Please check if you have created the TDataModule with one TRtcISAPIServer component.');
except
if ExceptObject is Exception then
HandleServerException(Exception(ExceptObject), ECB);
Result := HSE_STATUS_ERROR;
end;
end;
function TRtcISAPIApplication.TerminateExtension(dwFlags: DWORD): BOOL;
begin
if rtcLoaded then
begin
rtcLoaded:=False;
TRtcISAPIServer.UnLoad;
end;
Integer(Result) := 1;
end;
procedure TRtcISAPIApplication.CreateForm(InstanceClass: TComponentClass; var Reference);
var
Instance: TComponent;
begin
Instance := TComponent(InstanceClass.NewInstance);
TComponent(Reference) := Instance;
try
Instance.Create(Self);
except
TComponent(Reference) := nil;
raise;
end;
end;
procedure TRtcISAPIApplication.Initialize;
begin
if InitProc <> nil then TProcedure(InitProc);
end;
procedure TRtcISAPIApplication.Run;
begin
TRtcISAPIServer.Load;
rtcLoaded:=True;
end;
procedure InitApplication;
begin
CoInitFlags := COINIT_MULTITHREADED;
Application := TRtcISAPIApplication.Create(nil);
end;
initialization
InitApplication;
end.
|
//
// This unit is part of the GLScene Project, http://glscene.org
//
{ : FPlugInManagerEditor<p>
Need a short description of what it does here.<p>
<b>History : </b><font size=-1><ul>
<li>17/11/14 - PW - Renamed from PlugInManagerPropEditor.pas to FPlugInManagerEditor.pas
<li>16/10/08 - UweR - Compatibility fix for Delphi 2009
<li>02/04/07 - DaStr - Added $I GLScene.inc
<li>28/07/01 - EG - Creation
</ul></font>
}
unit FPlugInManagerEditor;
interface
{$I GLScene.inc}
uses
System.Classes, System.SysUtils, System.ImageList,
VCL.Forms, VCL.Dialogs, VCL.StdCtrls,
VCL.Controls, VCL.Buttons, Vcl.ExtCtrls, Vcl.ImgList, Vcl.ComCtrls, Vcl.ToolWin,
//GLS
GLPlugInIntf, GLPlugInManager;
type
TPlugInManagerEditor = class(TForm)
OpenDialog: TOpenDialog;
ListBox: TListBox;
Label1: TLabel;
GroupBox: TGroupBox;
DescriptionMemo: TMemo;
Label2: TLabel;
Label3: TLabel;
DateLabel: TLabel;
SizeLabel: TLabel;
Label4: TLabel;
Label5: TLabel;
ServiceBox: TComboBox;
NameBox: TComboBox;
ToolBar1: TToolBar;
ToolButton1: TToolButton;
ToolButton2: TToolButton;
ToolButton3: TToolButton;
ImageList: TImageList;
procedure OKButtonClick(Sender: TObject);
procedure LoadButtonClick(Sender: TObject);
procedure ListBoxClick(Sender: TObject);
procedure UnloadButtonClick(Sender: TObject);
procedure ServiceBoxChange(Sender: TObject);
private
{ Private declarations }
FManager: TPlugInManager;
public
{ Public declarations }
class procedure EditPlugIns(AManager: TPlugInManager);
end;
var
PlugInManagerEditor: TPlugInManagerEditor;
// ------------------------------------------------------------------------------
implementation
{$R *.DFM}
// ------------------------------------------------------------------------------
procedure TPlugInManagerEditor.OKButtonClick(Sender: TObject);
begin
Close;
end;
// ------------------------------------------------------------------------------
procedure TPlugInManagerEditor.LoadButtonClick(Sender: TObject);
var
I, Index: Integer;
begin
with OpenDialog do
if Execute then
for I := 0 to Files.Count - 1 do
begin
Index := FManager.AddPlugIn(Files[I]);
if Index > -1 then
if Index >= ListBox.Items.Count then
begin
FManager.PlugIns.Objects[Index];
ListBox.Items.Add(FManager.PlugIns.Strings[I]);
end
else
else
MessageDlg(Format('Error while loading %s' + #13 +
'not a valid GLScene plug-in', [Files[I]]), mtError, [mbOK], 0);
end;
end;
// ------------------------------------------------------------------------------
class procedure TPlugInManagerEditor.EditPlugIns(AManager: TPlugInManager);
begin
// ensure only one instance
if assigned(PlugInManagerEditor) then
PlugInManagerEditor.Free;
PlugInManagerEditor := TPlugInManagerEditor.Create(Application);
with PlugInManagerEditor do
begin
ListBox.Items := AManager.PlugIns;
FManager := AManager;
ShowModal;
Free;
end;
PlugInManagerEditor := nil;
end;
// ------------------------------------------------------------------------------
procedure TPlugInManagerEditor.ListBoxClick(Sender: TObject);
var
Entry: Integer;
Service: TPIServiceType;
Services: TPIServices;
begin
Entry := ListBox.ItemIndex;
if Entry > -1 then
begin
SizeLabel.Caption := Format('%n KB',
[FManager.PlugIns[Entry].FileSize / 1000]);
SizeLabel.Enabled := True;
DateLabel.Caption := DateToStr(FManager.PlugIns[Entry].FileDate);
DateLabel.Enabled := True;
DescriptionMemo.Lines.Text :=
string(FManager.PlugIns[Entry].GetDescription);
ServiceBox.Items.Clear;
ServiceBox.Enabled := True;
Services := FManager.PlugIns[Entry].GetServices;
for Service := Low(TPIServiceType) to High(TPIServiceType) do
if Service in Services then
case Service of
stRaw:
begin
Entry := ServiceBox.Items.Add('Raw');
ServiceBox.Items.Objects[Entry] := Pointer(stRaw);
end;
stObject:
begin
Entry := ServiceBox.Items.Add('Object');
ServiceBox.Items.Objects[Entry] := Pointer(stObject);
end;
stBitmap:
begin
Entry := ServiceBox.Items.Add('Bitmap');
ServiceBox.Items.Objects[Entry] := Pointer(stBitmap);
end;
stTexture:
begin
Entry := ServiceBox.Items.Add('Texture');
ServiceBox.Items.Objects[Entry] := Pointer(stTexture);
end;
stImport:
begin
Entry := ServiceBox.Items.Add('Import');
ServiceBox.Items.Objects[Entry] := Pointer(stImport);
end;
stExport:
begin
Entry := ServiceBox.Items.Add('Export');
ServiceBox.Items.Objects[Entry] := Pointer(stExport);
end;
end;
ServiceBox.ItemIndex := 0;
ServiceBox.OnChange(ServiceBox);
end;
end;
// ------------------------------------------------------------------------------
procedure TPlugInManagerEditor.UnloadButtonClick(Sender: TObject);
var
I: Integer;
begin
for I := 0 to ListBox.Items.Count - 1 do
if ListBox.Selected[I] then
begin
FManager.RemovePlugIn(I);
ListBox.Items.Delete(I);
end;
DescriptionMemo.Clear;
DateLabel.Caption := '???';
DateLabel.Enabled := False;
SizeLabel.Caption := '???';
SizeLabel.Enabled := False;
ServiceBox.ItemIndex := -1;
ServiceBox.Enabled := False;
NameBox.ItemIndex := -1;
NameBox.Enabled := False;
end;
// ------------------------------------------------------------------------------
procedure NameCallback(Name: PAnsiChar); stdcall;
begin
PlugInManagerEditor.NameBox.Items.Add(String(Name));
end;
// ------------------------------------------------------------------------------
procedure TPlugInManagerEditor.ServiceBoxChange(Sender: TObject);
begin
NameBox.Items.Clear;
with ServiceBox, Items do
FManager.PlugIns[ListBox.ItemIndex].EnumResourceNames
(TPIServiceType(Objects[ItemIndex]), NameCallback);
NameBox.ItemIndex := 0;
NameBox.Enabled := True;
end;
// ------------------------------------------------------------------------------
end.
|
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// 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.
//
{$POINTERMATH ON}
unit RN_DetourNavMesh;
interface
uses
Classes, Math, RN_DetourNode, RN_DetourNavMeshHelper, RN_DetourCommon, RN_DetourStatus;
/// The maximum number of vertices per navigation polygon.
/// @ingroup detour
const DT_VERTS_PER_POLYGON = 6;
/// @{
/// @name Tile Serialization Constants
/// These constants are used to detect whether a navigation tile's data
/// and state format is compatible with the current build.
///
/// A magic number used to detect compatibility of navigation tile data.
const DT_NAVMESH_MAGIC = Ord('D') shl 24 or Ord('N') shl 16 or Ord('A') shl 8 or Ord('V');
/// A version number used to detect compatibility of navigation tile data.
const DT_NAVMESH_VERSION = 7;
/// A magic number used to detect the compatibility of navigation tile states.
const DT_NAVMESH_STATE_MAGIC = Ord('D') shl 24 or Ord('N') shl 16 or Ord('M') shl 8 or Ord('S');
/// A version number used to detect compatibility of navigation tile states.
const DT_NAVMESH_STATE_VERSION = 1;
/// @}
/// A flag that indicates that an entity links to an external entity.
/// (E.g. A polygon edge is a portal that links to another polygon.)
const DT_EXT_LINK = $8000;
/// A value that indicates the entity does not link to anything.
const DT_NULL_LINK = $ffffffff;
/// A flag that indicates that an off-mesh connection can be traversed in both directions. (Is bidirectional.)
const DT_OFFMESH_CON_BIDIR = 1;
/// The maximum number of user defined area ids.
/// @ingroup detour
const DT_MAX_AREAS = 64;
/// Tile flags used for various functions and fields.
/// For an example, see dtNavMesh::addTile().
//TdtTileFlags =
/// The navigation mesh owns the tile memory and is responsible for freeing it.
DT_TILE_FREE_DATA = $01;
type
/// Vertex flags returned by dtNavMeshQuery::findStraightPath.
TdtStraightPathFlags =
(
DT_STRAIGHTPATH_START = $01, ///< The vertex is the start position in the path.
DT_STRAIGHTPATH_END = $02, ///< The vertex is the end position in the path.
DT_STRAIGHTPATH_OFFMESH_CONNECTION = $04 ///< The vertex is the start of an off-mesh connection.
);
/// Options for dtNavMeshQuery::findStraightPath.
TdtStraightPathOptions =
(
DT_STRAIGHTPATH_AREA_CROSSINGS = $01, ///< Add a vertex at every polygon edge crossing where area changes.
DT_STRAIGHTPATH_ALL_CROSSINGS = $02 ///< Add a vertex at every polygon edge crossing.
);
/// Options for dtNavMeshQuery::findPath
TdtFindPathOptions =
(
DT_FINDPATH_LOW_QUALITY_FAR = $01, ///< [provisional] trade quality for performance far from the origin. The idea is that by then a new query will be issued
DT_FINDPATH_ANY_ANGLE = $02 ///< use raycasts during pathfind to "shortcut" (raycast still consider costs)
);
/// Options for dtNavMeshQuery::raycast
TdtRaycastOptions =
(
DT_RAYCAST_USE_COSTS = $01 ///< Raycast should calculate movement cost along the ray and fill RaycastHit::cost
);
/// Limit raycasting during any angle pahfinding
/// The limit is given as a multiple of the character radius
const DT_RAY_CAST_LIMIT_PROPORTIONS = 50.0;
/// Flags representing the type of a navigation mesh polygon.
//dtPolyTypes =
/// The polygon is a standard convex polygon that is part of the surface of the mesh.
DT_POLYTYPE_GROUND = 0;
/// The polygon is an off-mesh connection consisting of two vertices.
DT_POLYTYPE_OFFMESH_CONNECTION = 1;
type
/// Defines a polyogn within a dtMeshTile object.
/// @ingroup detour
PPdtPoly = ^PdtPoly;
PdtPoly = ^TdtPoly;
TdtPoly = record
/// Index to first link in linked list. (Or #DT_NULL_LINK if there is no link.)
firstLink: Cardinal;
/// The indices of the polygon's vertices.
/// The actual vertices are located in dtMeshTile::verts.
verts: array [0..DT_VERTS_PER_POLYGON-1] of Word;
/// Packed data representing neighbor polygons references and flags for each edge.
neis: array [0..DT_VERTS_PER_POLYGON-1] of Word;
/// The user defined polygon flags.
flags: Word;
/// The number of vertices in the polygon.
vertCount: Byte;
/// The bit packed area id and polygon type.
/// @note Use the structure's set and get methods to acess this value.
areaAndtype: Byte;
/// Sets the user defined area id. [Limit: < #DT_MAX_AREAS]
procedure setArea(a: Byte);
/// Sets the polygon type. (See: #dtPolyTypes.)
procedure setType(t: Byte);
/// Gets the user defined area id.
function getArea(): Byte;
/// Gets the polygon type. (See: #dtPolyTypes)
function getType(): Byte;
end;
/// Defines the location of detail sub-mesh data within a dtMeshTile.
PdtPolyDetail = ^TdtPolyDetail;
TdtPolyDetail = record
vertBase: Cardinal; ///< The offset of the vertices in the dtMeshTile::detailVerts array.
triBase: Cardinal; ///< The offset of the triangles in the dtMeshTile::detailTris array.
vertCount: Byte; ///< The number of vertices in the sub-mesh.
triCount: Byte; ///< The number of triangles in the sub-mesh.
end;
/// Defines a link between polygons.
/// @note This structure is rarely if ever used by the end user.
/// @see dtMeshTile
PdtLink = ^TdtLink;
TdtLink = record
ref: TdtPolyRef; ///< Neighbour reference. (The neighbor that is linked to.)
next: Cardinal; ///< Index of the next link.
edge: Byte; ///< Index of the polygon edge that owns this link.
side: Byte; ///< If a boundary link, defines on which side the link is.
bmin: Byte; ///< If a boundary link, defines the minimum sub-edge area.
bmax: Byte; ///< If a boundary link, defines the maximum sub-edge area.
end;
/// Bounding volume node.
/// @note This structure is rarely if ever used by the end user.
/// @see dtMeshTile
PdtBVNode = ^TdtBVNode;
TdtBVNode = record
bmin: array [0..2] of Word; ///< Minimum bounds of the node's AABB. [(x, y, z)]
bmax: array [0..2] of Word; ///< Maximum bounds of the node's AABB. [(x, y, z)]
i: Integer; ///< The node's index. (Negative for escape sequence.)
end;
/// Defines an navigation mesh off-mesh connection within a dtMeshTile object.
/// An off-mesh connection is a user defined traversable connection made up to two vertices.
PdtOffMeshConnection = ^TdtOffMeshConnection;
TdtOffMeshConnection = record
/// The endpoints of the connection. [(ax, ay, az, bx, by, bz)]
pos: array [0..5] of Single;
/// The radius of the endpoints. [Limit: >= 0]
rad: Single;
/// The polygon reference of the connection within the tile.
poly: Word;
/// Link flags.
/// @note These are not the connection's user defined flags. Those are assigned via the
/// connection's dtPoly definition. These are link flags used for internal purposes.
flags: Byte;
/// End point side.
side: Byte;
/// The id of the offmesh connection. (User assigned when the navigation mesh is built.)
userId: Cardinal;
end;
/// Provides high level information related to a dtMeshTile object.
/// @ingroup detour
PdtMeshHeader = ^TdtMeshHeader;
TdtMeshHeader = record
magic: Integer; ///< Tile magic number. (Used to identify the data format.)
version: Integer; ///< Tile data format version number.
x: Integer; ///< The x-position of the tile within the dtNavMesh tile grid. (x, y, layer)
y: Integer; ///< The y-position of the tile within the dtNavMesh tile grid. (x, y, layer)
layer: Integer; ///< The layer of the tile within the dtNavMesh tile grid. (x, y, layer)
userId: Cardinal; ///< The user defined id of the tile.
polyCount: Integer; ///< The number of polygons in the tile.
vertCount: Integer; ///< The number of vertices in the tile.
maxLinkCount: Integer; ///< The number of allocated links.
detailMeshCount: Integer; ///< The number of sub-meshes in the detail mesh.
/// The number of unique vertices in the detail mesh. (In addition to the polygon vertices.)
detailVertCount: Integer;
detailTriCount: Integer; ///< The number of triangles in the detail mesh.
bvNodeCount: Integer; ///< The number of bounding volume nodes. (Zero if bounding volumes are disabled.)
offMeshConCount: Integer; ///< The number of off-mesh connections.
offMeshBase: Integer; ///< The index of the first polygon which is an off-mesh connection.
walkableHeight: Single; ///< The height of the agents using the tile.
walkableRadius: Single; ///< The radius of the agents using the tile.
walkableClimb: Single; ///< The maximum climb height of the agents using the tile.
bmin: array [0..2] of Single; ///< The minimum bounds of the tile's AABB. [(x, y, z)]
bmax: array [0..2] of Single; ///< The maximum bounds of the tile's AABB. [(x, y, z)]
/// The bounding volume quantization factor.
bvQuantFactor: Single;
end;
/// Defines a navigation mesh tile.
/// @ingroup detour
PPdtMeshTile = ^PdtMeshTile;
PdtMeshTile = ^TdtMeshTile;
TdtMeshTile = record
salt: Cardinal; ///< Counter describing modifications to the tile.
linksFreeList: Cardinal; ///< Index to the next free link.
header: PdtMeshHeader; ///< The tile header.
polys: PdtPoly; ///< The tile polygons. [Size: dtMeshHeader::polyCount]
verts: PSingle; ///< The tile vertices. [Size: dtMeshHeader::vertCount]
links: PdtLink; ///< The tile links. [Size: dtMeshHeader::maxLinkCount]
detailMeshes: PdtPolyDetail; ///< The tile's detail sub-meshes. [Size: dtMeshHeader::detailMeshCount]
/// The detail mesh's unique vertices. [(x, y, z) * dtMeshHeader::detailVertCount]
detailVerts: PSingle;
/// The detail mesh's triangles. [(vertA, vertB, vertC) * dtMeshHeader::detailTriCount]
detailTris: PByte;
/// The tile bounding volume nodes. [Size: dtMeshHeader::bvNodeCount]
/// (Will be null if bounding volumes are disabled.)
bvTree: PdtBVNode;
offMeshCons: PdtOffMeshConnection; ///< The tile off-mesh connections. [Size: dtMeshHeader::offMeshConCount]
data: PByte; ///< The tile data. (Not directly accessed under normal situations.)
dataSize: Integer; ///< Size of the tile data.
flags: Integer; ///< Tile flags. (See: #dtTileFlags)
next: PdtMeshTile; ///< The next free tile, or the next tile in the spatial grid.
end;
/// Configuration parameters used to define multi-tile navigation meshes.
/// The values are used to allocate space during the initialization of a navigation mesh.
/// @see dtNavMesh::init()
/// @ingroup detour
PdtNavMeshParams = ^TdtNavMeshParams;
TdtNavMeshParams = record
orig: array [0..2] of Single; ///< The world space origin of the navigation mesh's tile space. [(x, y, z)]
tileWidth: Single; ///< The width of each tile. (Along the x-axis.)
tileHeight: Single; ///< The height of each tile. (Along the z-axis.)
maxTiles: Integer; ///< The maximum number of tiles the navigation mesh can contain.
maxPolys: Integer; ///< The maximum number of polygons each tile can contain.
end;
/// A navigation mesh based on tiles of convex polygons.
/// @ingroup detour
TdtNavMesh = class
public
constructor Create();
destructor Destroy; override;
/// @{
/// @name Initialization and Tile Management
/// Initializes the navigation mesh for tiled use.
/// @param[in] params Initialization parameters.
/// @return The status flags for the operation.
function init(params: PdtNavMeshParams): TdtStatus; overload;
/// Initializes the navigation mesh for single tile use.
/// @param[in] data Data of the new tile. (See: #dtCreateNavMeshData)
/// @param[in] dataSize The data size of the new tile.
/// @param[in] flags The tile flags. (See: #dtTileFlags)
/// @return The status flags for the operation.
/// @see dtCreateNavMeshData
function init(data: PByte; dataSize, flags: Integer): TdtStatus; overload;
/// The navigation mesh initialization params.
function getParams(): PdtNavMeshParams;
/// Adds a tile to the navigation mesh.
/// @param[in] data Data for the new tile mesh. (See: #dtCreateNavMeshData)
/// @param[in] dataSize Data size of the new tile mesh.
/// @param[in] flags Tile flags. (See: #dtTileFlags)
/// @param[in] lastRef The desired reference for the tile. (When reloading a tile.) [opt] [Default: 0]
/// @param[out] result The tile reference. (If the tile was succesfully added.) [opt]
/// @return The status flags for the operation.
function addTile(data: PByte; dataSize, flags: Integer; lastRef: TdtTileRef; reslt: PdtTileRef): TdtStatus;
/// Removes the specified tile from the navigation mesh.
/// @param[in] ref The reference of the tile to remove.
/// @param[out] data Data associated with deleted tile.
/// @param[out] dataSize Size of the data associated with deleted tile.
/// @return The status flags for the operation.
function removeTile(ref: TdtTileRef; data: PPointer; dataSize: PInteger): TdtStatus;
/// @}
/// @{
/// @name Query Functions
/// Calculates the tile grid location for the specified world position.
/// @param[in] pos The world position for the query. [(x, y, z)]
/// @param[out] tx The tile's x-location. (x, y)
/// @param[out] ty The tile's y-location. (x, y)
procedure calcTileLoc(pos: PSingle; tx, ty: PInteger);
/// Gets the tile at the specified grid location.
/// @param[in] x The tile's x-location. (x, y, layer)
/// @param[in] y The tile's y-location. (x, y, layer)
/// @param[in] layer The tile's layer. (x, y, layer)
/// @return The tile, or null if the tile does not exist.
function getTileAt(x, y, layer: Integer): PdtMeshTile;
/// Gets all tiles at the specified grid location. (All layers.)
/// @param[in] x The tile's x-location. (x, y)
/// @param[in] y The tile's y-location. (x, y)
/// @param[out] tiles A pointer to an array of tiles that will hold the result.
/// @param[in] maxTiles The maximum tiles the tiles parameter can hold.
/// @return The number of tiles returned in the tiles array.
function getTilesAt(x, y: Integer; tiles: PPdtMeshTile; maxTiles: Integer): Integer;
/// Gets the tile reference for the tile at specified grid location.
/// @param[in] x The tile's x-location. (x, y, layer)
/// @param[in] y The tile's y-location. (x, y, layer)
/// @param[in] layer The tile's layer. (x, y, layer)
/// @return The tile reference of the tile, or 0 if there is none.
function getTileRefAt(x, y, layer: Integer): TdtTileRef;
/// Gets the tile reference for the specified tile.
/// @param[in] tile The tile.
/// @return The tile reference of the tile.
function getTileRef(tile: PdtMeshTile): TdtTileRef;
/// Gets the tile for the specified tile reference.
/// @param[in] ref The tile reference of the tile to retrieve.
/// @return The tile for the specified reference, or null if the
/// reference is invalid.
function getTileByRef(ref: TdtTileRef): PdtMeshTile;
/// The maximum number of tiles supported by the navigation mesh.
/// @return The maximum number of tiles supported by the navigation mesh.
function getMaxTiles(): Integer;
/// Gets the tile at the specified index.
/// @param[in] i The tile index. [Limit: 0 >= index < #getMaxTiles()]
/// @return The tile at the specified index.
function getTile(i: Integer): PdtMeshTile;
/// Gets the tile and polygon for the specified polygon reference.
/// @param[in] ref The reference for the a polygon.
/// @param[out] tile The tile containing the polygon.
/// @param[out] poly The polygon.
/// @return The status flags for the operation.
function getTileAndPolyByRef(ref: TdtPolyRef; tile: PPdtMeshTile; poly: PPdtPoly): TdtStatus;
/// Returns the tile and polygon for the specified polygon reference.
/// @param[in] ref A known valid reference for a polygon.
/// @param[out] tile The tile containing the polygon.
/// @param[out] poly The polygon.
procedure getTileAndPolyByRefUnsafe(ref: TdtPolyRef; tile: PPdtMeshTile; poly: PPdtPoly);
/// Checks the validity of a polygon reference.
/// @param[in] ref The polygon reference to check.
/// @return True if polygon reference is valid for the navigation mesh.
function isValidPolyRef(ref: TdtPolyRef): Boolean;
/// Gets the polygon reference for the tile's base polygon.
/// @param[in] tile The tile.
/// @return The polygon reference for the base polygon in the specified tile.
function getPolyRefBase(tile: PdtMeshTile): TdtPolyRef;
/// Gets the endpoints for an off-mesh connection, ordered by "direction of travel".
/// @param[in] prevRef The reference of the polygon before the connection.
/// @param[in] polyRef The reference of the off-mesh connection polygon.
/// @param[out] startPos The start position of the off-mesh connection. [(x, y, z)]
/// @param[out] endPos The end position of the off-mesh connection. [(x, y, z)]
/// @return The status flags for the operation.
function getOffMeshConnectionPolyEndPoints(prevRef, polyRef: TdtPolyRef; startPos, endPos: PSingle): TdtStatus;
/// Gets the specified off-mesh connection.
/// @param[in] ref The polygon reference of the off-mesh connection.
/// @return The specified off-mesh connection, or null if the polygon reference is not valid.
function getOffMeshConnectionByRef(ref: TdtPolyRef): PdtOffMeshConnection;
/// @}
/// @{
/// @name State Management
/// These functions do not effect #dtTileRef or #dtPolyRef's.
/// Sets the user defined flags for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[in] flags The new flags for the polygon.
/// @return The status flags for the operation.
function setPolyFlags(ref: TdtPolyRef; flags: Word): TdtStatus;
/// Gets the user defined flags for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[out] resultFlags The polygon flags.
/// @return The status flags for the operation.
function getPolyFlags(ref: TdtPolyRef; resultFlags: PWord): TdtStatus;
/// Sets the user defined area for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[in] area The new area id for the polygon. [Limit: < #DT_MAX_AREAS]
/// @return The status flags for the operation.
function setPolyArea(ref: TdtPolyRef; area: Byte): TdtStatus;
/// Gets the user defined area for the specified polygon.
/// @param[in] ref The polygon reference.
/// @param[out] resultArea The area id for the polygon.
/// @return The status flags for the operation.
function getPolyArea(ref: TdtPolyRef; resultArea: PByte): TdtStatus;
/// Gets the size of the buffer required by #storeTileState to store the specified tile's state.
/// @param[in] tile The tile.
/// @return The size of the buffer required to store the state.
function getTileStateSize(tile: PdtMeshTile): Integer;
/// Stores the non-structural state of the tile in the specified buffer. (Flags, area ids, etc.)
/// @param[in] tile The tile.
/// @param[out] data The buffer to store the tile's state in.
/// @param[in] maxDataSize The size of the data buffer. [Limit: >= #getTileStateSize]
/// @return The status flags for the operation.
function storeTileState(tile: PdtMeshTile; data: PByte; maxDataSize: Integer): TdtStatus;
/// Restores the state of the tile.
/// @param[in] tile The tile.
/// @param[in] data The new state. (Obtained from #storeTileState.)
/// @param[in] maxDataSize The size of the state within the data buffer.
/// @return The status flags for the operation.
function restoreTileState(tile: PdtMeshTile; data: PByte; maxDataSize: Integer): TdtStatus;
/// @}
/// @{
/// @name Encoding and Decoding
/// These functions are generally meant for internal use only.
/// Derives a standard polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] salt The tile's salt value.
/// @param[in] it The index of the tile.
/// @param[in] ip The index of the polygon within the tile.
function encodePolyId(salt, it, ip: Cardinal): TdtPolyRef;
/// Decodes a standard polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference to decode.
/// @param[out] salt The tile's salt value.
/// @param[out] it The index of the tile.
/// @param[out] ip The index of the polygon within the tile.
/// @see #encodePolyId
procedure decodePolyId(ref: TdtPolyRef; salt, it, ip: PCardinal);
/// Extracts a tile's salt value from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function decodePolyIdSalt(ref: TdtPolyRef): Cardinal;
/// Extracts the tile's index from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function decodePolyIdTile(ref: TdtPolyRef): Cardinal;
/// Extracts the polygon's index (within its tile) from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function decodePolyIdPoly(ref: TdtPolyRef): Cardinal;
/// @end;
procedure SaveToStream(aStream: TMemoryStream);
private
m_params: TdtNavMeshParams; ///< Current initialization params. TODO: do not store this info twice.
m_orig: array [0..2] of Single; ///< Origin of the tile (0,0)
m_tileWidth, m_tileHeight: Single; ///< Dimensions of each tile.
m_maxTiles: Integer; ///< Max number of tiles.
m_tileLutSize: Integer; ///< Tile hash lookup size (must be pot).
m_tileLutMask: Integer; ///< Tile hash lookup mask.
m_posLookup: PPointer; ///< Tile hash lookup.
m_nextFree: PdtMeshTile; ///< Freelist of tiles.
m_tiles: PdtMeshTile; ///< List of tiles.
{$ifndef DT_POLYREF64}
m_saltBits: Cardinal; ///< Number of salt bits in the tile ID.
m_tileBits: Cardinal; ///< Number of tile bits in the tile ID.
m_polyBits: Cardinal; ///< Number of poly bits in the tile ID.
{$endif}
/// Returns pointer to tile in the tile array.
//function getTile(i: Integer): PdtMeshTile;
/// Returns neighbour tile based on side.
//function getTilesAt(x, y: Integer; tiles: Pointer; maxTiles: Integer): Integer;
/// Returns neighbour tile based on side.
function getNeighbourTilesAt(x, y, side: Integer; tiles: PPdtMeshTile; maxTiles: Integer): Integer;
/// Returns all polygons in neighbour tile based on portal defined by the segment.
function findConnectingPolys(va, vb: PSingle;
tile: PdtMeshTile; side: Integer;
con: PdtPolyRef; conarea: PSingle; maxcon: Integer): Integer;
/// Builds internal polygons links for a tile.
procedure connectIntLinks(tile: PdtMeshTile);
/// Builds internal polygons links for a tile.
procedure baseOffMeshLinks(tile: PdtMeshTile);
/// Builds external polygon links for a tile.
procedure connectExtLinks(tile, target: PdtMeshTile; side: Integer);
/// Builds external polygon links for a tile.
procedure connectExtOffMeshLinks(tile, target: PdtMeshTile; side: Integer);
/// Removes external links at specified side.
procedure unconnectExtLinks(tile, target: PdtMeshTile);
// TODO: These methods are duplicates from dtNavMeshQuery, but are needed for off-mesh connection finding.
/// Queries polygons within a tile.
function queryPolygonsInTile(tile: PdtMeshTile; qmin, qmax: PSingle; polys: PdtPolyRef; maxPolys: Integer): Integer;
/// Find nearest polygon within a tile.
function findNearestPolyInTile(tile: PdtMeshTile; center, extents, nearestPt: PSingle): TdtPolyRef;
/// Returns closest point on polygon.
procedure closestPointOnPoly(ref: TdtPolyRef; pos, closest: PSingle; posOverPoly: PBoolean);
end;
/// Allocates a navigation mesh object using the Detour allocator.
/// @return A navigation mesh that is ready for initialization, or null on failure.
/// @ingroup detour
//dtNavMesh* dtAllocNavMesh();
/// Frees the specified navigation mesh object using the Detour allocator.
/// @param[in] navmesh A navigation mesh allocated using #dtAllocNavMesh
/// @ingroup detour
//void dtFreeNavMesh(dtNavMesh* navmesh);
implementation
/// Sets the user defined area id. [Limit: < #DT_MAX_AREAS]
procedure TdtPoly.setArea(a: Byte); begin areaAndtype := (areaAndtype and $c0) or (a and $3f); end;
/// Sets the polygon type. (See: #dtPolyTypes.)
procedure TdtPoly.setType(t: Byte); begin areaAndtype := (areaAndtype and $3f) or (t shl 6); end;
/// Gets the user defined area id.
function TdtPoly.getArea(): Byte; begin Result := areaAndtype and $3f; end;
/// Gets the polygon type. (See: #dtPolyTypes)
function TdtPoly.getType(): Byte; begin Result := areaAndtype shr 6; end;
///////////////////////////////////////////////////////////////////////////
// This section contains detailed documentation for members that don't have
// a source file. It reduces clutter in the main section of the header.
(**
@typedef dtPolyRef
@par
Polygon references are subject to the same invalidate/preserve/restore
rules that apply to #dtTileRef's. If the #dtTileRef for the polygon's
tile changes, the polygon reference becomes invalid.
Changing a polygon's flags, area id, etc. does not impact its polygon
reference.
@typedef dtTileRef
@par
The following changes will invalidate a tile reference:
- The referenced tile has been removed from the navigation mesh.
- The navigation mesh has been initialized using a different set
of #dtNavMeshParams.
A tile reference is preserved/restored if the tile is added to a navigation
mesh initialized with the original #dtNavMeshParams and is added at the
original reference location. (E.g. The lastRef parameter is used with
dtNavMesh::addTile.)
Basically, if the storage structure of a tile changes, its associated
tile reference changes.
@var unsigned short dtPoly::neis[DT_VERTS_PER_POLYGON]
@par
Each entry represents data for the edge starting at the vertex of the same index.
E.g. The entry at index n represents the edge data for vertex[n] to vertex[n+1].
A value of zero indicates the edge has no polygon connection. (It makes up the
border of the navigation mesh.)
The information can be extracted as follows:
@code
neighborRef = neis[n] & 0xff; // Get the neighbor polygon reference.
if (neis[n] & #DT_EX_LINK)
begin
// The edge is an external (portal) edge.
end;
@endcode
@var float dtMeshHeader::bvQuantFactor
@par
This value is used for converting between world and bounding volume coordinates.
For example:
@code
const float cs = 1.0f / tile.header.bvQuantFactor;
const dtBVNode* n = &tile.bvTree[i];
if (n.i >= 0)
begin
// This is a leaf node.
float worldMinX = tile.header.bmin[0] + n.bmin[0]*cs;
float worldMinY = tile.header.bmin[0] + n.bmin[1]*cs;
// Etc...
end;
@endcode
@struct dtMeshTile
@par
Tiles generally only exist within the context of a dtNavMesh object.
Some tile content is optional. For example, a tile may not contain any
off-mesh connections. In this case the associated pointer will be null.
If a detail mesh exists it will share vertices with the base polygon mesh.
Only the vertices unique to the detail mesh will be stored in #detailVerts.
@warning Tiles returned by a dtNavMesh object are not guarenteed to be populated.
For example: The tile at a location might not have been loaded yet, or may have been removed.
In this case, pointers will be null. So if in doubt, check the polygon count in the
tile's header to determine if a tile has polygons defined.
@var float dtOffMeshConnection::pos[6]
@par
For a properly built navigation mesh, vertex A will always be within the bounds of the mesh.
Vertex B is not required to be within the bounds of the mesh.
*)
function overlapSlabs(amin, amax, bmin, bmax: PSingle; px, py: Single): Boolean;
var minx,maxx,ad,ak,bd,bk,aminy,amaxy,bminy,bmaxy,dmin,dmax,thr: Single;
begin
// Check for horizontal overlap.
// The segment is shrunken a little so that slabs which touch
// at end points are not connected.
minx := dtMax(amin[0]+px,bmin[0]+px);
maxx := dtMin(amax[0]-px,bmax[0]-px);
if (minx > maxx) then
Exit(false);
// Check vertical overlap.
ad := (amax[1]-amin[1]) / (amax[0]-amin[0]);
ak := amin[1] - ad*amin[0];
bd := (bmax[1]-bmin[1]) / (bmax[0]-bmin[0]);
bk := bmin[1] - bd*bmin[0];
aminy := ad*minx + ak;
amaxy := ad*maxx + ak;
bminy := bd*minx + bk;
bmaxy := bd*maxx + bk;
dmin := bminy - aminy;
dmax := bmaxy - amaxy;
// Crossing segments always overlap.
if (dmin*dmax < 0) then
Exit(true);
// Check for overlap at endpoints.
thr := Sqr(py*2);
if (dmin*dmin <= thr) or (dmax*dmax <= thr) then
Exit(true);
Result := false;
end;
function getSlabCoord(va: PSingle; side: Integer): Single;
begin
if (side = 0) or (side = 4) then
Exit(va[0])
else if (side = 2) or (side = 6) then
Exit(va[2]);
Result := 0;
end;
procedure calcSlabEndPoints(va, vb, bmin,bmax: PSingle; side: Integer);
begin
if (side = 0) or (side = 4) then
begin
if (va[2] < vb[2]) then
begin
bmin[0] := va[2];
bmin[1] := va[1];
bmax[0] := vb[2];
bmax[1] := vb[1];
end
else
begin
bmin[0] := vb[2];
bmin[1] := vb[1];
bmax[0] := va[2];
bmax[1] := va[1];
end;
end
else if (side = 2) or (side = 6) then
begin
if (va[0] < vb[0]) then
begin
bmin[0] := va[0];
bmin[1] := va[1];
bmax[0] := vb[0];
bmax[1] := vb[1];
end
else
begin
bmin[0] := vb[0];
bmin[1] := vb[1];
bmax[0] := va[0];
bmax[1] := va[1];
end;
end;
end;
function computeTileHash(x, y, mask: Integer): Integer;
const h1: Cardinal = $8da6b343; // Large multiplicative constants;
const h2: Cardinal = $d8163841; // here arbitrarily chosen primes
var n: Int64;
begin
{$Q-}
n := h1 * x + h2 * y;
Result := Integer(n and mask);
{$Q+}
end;
function allocLink(tile: PdtMeshTile): Cardinal;
var link: Cardinal;
begin
if (tile.linksFreeList = DT_NULL_LINK) then
Exit(DT_NULL_LINK);
link := tile.linksFreeList;
tile.linksFreeList := tile.links[link].next;
Result := link;
end;
procedure freeLink(tile: PdtMeshTile; link: Cardinal);
begin
tile.links[link].next := tile.linksFreeList;
tile.linksFreeList := link;
end;
{function dtAllocNavMesh(): PdtNavMesh;
begin
void* mem := dtAlloc(sizeof(dtNavMesh), DT_ALLOC_PERM);
if (!mem) return 0;
return new(mem) dtNavMesh;
end;
/// @par
///
/// This function will only free the memory for tiles with the #DT_TILE_FREE_DATA
/// flag set.
procedure dtFreeNavMesh(dtNavMesh* navmesh);
begin
if (!navmesh) return;
navmesh.~dtNavMesh();
dtFree(navmesh);
end;}
//////////////////////////////////////////////////////////////////////////////////////////
(**
@class dtNavMesh
The navigation mesh consists of one or more tiles defining three primary types of structural data:
A polygon mesh which defines most of the navigation graph. (See rcPolyMesh for its structure.)
A detail mesh used for determining surface height on the polygon mesh. (See rcPolyMeshDetail for its structure.)
Off-mesh connections, which define custom point-to-point edges within the navigation graph.
The general build process is as follows:
-# Create rcPolyMesh and rcPolyMeshDetail data using the Recast build pipeline.
-# Optionally, create off-mesh connection data.
-# Combine the source data into a dtNavMeshCreateParams structure.
-# Create a tile data array using dtCreateNavMeshData().
-# Allocate at dtNavMesh object and initialize it. (For single tile navigation meshes,
the tile data is loaded during this step.)
-# For multi-tile navigation meshes, load the tile data using dtNavMesh::addTile().
Notes:
- This class is usually used in conjunction with the dtNavMeshQuery class for pathfinding.
- Technically, all navigation meshes are tiled. A 'solo' mesh is simply a navigation mesh initialized
to have only a single tile.
- This class does not implement any asynchronous methods. So the ::dtStatus result of all methods will
always contain either a success or failure flag.
@see dtNavMeshQuery, dtCreateNavMeshData, dtNavMeshCreateParams, #dtAllocNavMesh, #dtFreeNavMesh
*)
constructor TdtNavMesh.Create();
begin
FillChar(m_params, sizeof(TdtNavMeshParams), 0);
end;
destructor TdtNavMesh.Destroy;
var i: Integer;
begin
for i := 0 to m_maxTiles - 1 do
begin
if (m_tiles[i].flags and DT_TILE_FREE_DATA) <> 0 then
begin
FreeMem(m_tiles[i].data);
m_tiles[i].data := nil;
m_tiles[i].dataSize := 0;
end;
end;
FreeMem(m_posLookup);
FreeMem(m_tiles);
inherited;
end;
function TdtNavMesh.init(params: PdtNavMeshParams): TdtStatus;
var i: Integer;
begin
Move(params^, m_params, sizeof(TdtNavMeshParams));
dtVcopy(@m_orig[0], @params.orig[0]);
m_tileWidth := params.tileWidth;
m_tileHeight := params.tileHeight;
// Init tiles
m_maxTiles := params.maxTiles;
m_tileLutSize := dtNextPow2(params.maxTiles div 4);
if (m_tileLutSize = 0) then m_tileLutSize := 1;
m_tileLutMask := m_tileLutSize-1;
GetMem(m_tiles, sizeof(TdtMeshTile)*m_maxTiles);
GetMem(m_posLookup, sizeof(PdtMeshTile)*m_tileLutSize);
FillChar(m_tiles[0], sizeof(TdtMeshTile)*m_maxTiles, 0);
FillChar(m_posLookup[0], sizeof(PdtMeshTile)*m_tileLutSize, 0);
m_nextFree := nil;
for i := m_maxTiles-1 downto 0 do
begin
m_tiles[i].salt := 1;
m_tiles[i].next := m_nextFree;
m_nextFree := @m_tiles[i];
end;
// Init ID generator values.
{$ifndef DT_POLYREF64}
m_tileBits := dtIlog2(dtNextPow2(Cardinal(params.maxTiles)));
m_polyBits := dtIlog2(dtNextPow2(Cardinal(params.maxPolys)));
// Only allow 31 salt bits, since the salt mask is calculated using 32bit uint and it will overflow.
m_saltBits := dtMin(Cardinal(31), 32 - m_tileBits - m_polyBits);
if (m_saltBits < 10) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
{$endif}
Result := DT_SUCCESS;
end;
function TdtNavMesh.init(data: PByte; dataSize, flags: Integer): TdtStatus;
var header: PdtMeshHeader; params: TdtNavMeshParams; status: TdtStatus;
begin
// Make sure the data is in right format.
header := PdtMeshHeader(data);
if (header.magic <> DT_NAVMESH_MAGIC) then
Exit(DT_FAILURE or DT_WRONG_MAGIC);
if (header.version <> DT_NAVMESH_VERSION) then
Exit(DT_FAILURE or DT_WRONG_VERSION);
dtVcopy(@params.orig[0], @header.bmin[0]);
params.tileWidth := header.bmax[0] - header.bmin[0];
params.tileHeight := header.bmax[2] - header.bmin[2];
params.maxTiles := 1;
params.maxPolys := header.polyCount;
status := init(@params);
if (dtStatusFailed(status)) then
Exit(status);
Result := addTile(data, dataSize, flags, 0, nil);
end;
/// @par
///
/// @note The parameters are created automatically when the single tile
/// initialization is performed.
function TdtNavMesh.getParams(): PdtNavMeshParams;
begin
Result := @m_params;
end;
//////////////////////////////////////////////////////////////////////////////////////////
function TdtNavMesh.findConnectingPolys(va, vb: PSingle;
tile: PdtMeshTile; side: Integer;
con: PdtPolyRef; conarea: PSingle; maxcon: Integer): Integer;
var amin, amax,bmin,bmax: array [0..2] of Single; apos: Single; m: Word; i,j,n,nv: Integer; base: TdtPolyRef; poly: PdtPoly;
vc,vd: PSingle; bpos: Single;
begin
if (tile = nil) then Exit(0);
calcSlabEndPoints(va, vb, @amin[0], @amax[0], side);
apos := getSlabCoord(va, side);
// Remove links pointing to 'side' and compact the links array.
m := DT_EXT_LINK or Word(side);
n := 0;
base := getPolyRefBase(tile);
for i := 0 to tile.header.polyCount - 1 do
begin
poly := @tile.polys[i];
nv := poly.vertCount;
for j := 0 to nv - 1 do
begin
// Skip edges which do not point to the right side.
if (poly.neis[j] <> m) then continue;
vc := @tile.verts[poly.verts[j]*3];
vd := @tile.verts[poly.verts[(j+1) mod nv]*3];
bpos := getSlabCoord(vc, side);
// Segments are not close enough.
if (Abs(apos-bpos) > 0.01) then
continue;
// Check if the segments touch.
calcSlabEndPoints(vc,vd, @bmin[0],@bmax[0], side);
if (not overlapSlabs(@amin[0],@amax[0], @bmin[0],@bmax[0], 0.01, tile.header.walkableClimb)) then continue;
// Add return value.
if (n < maxcon) then
begin
conarea[n*2+0] := dtMax(amin[0], bmin[0]);
conarea[n*2+1] := dtMin(amax[0], bmax[0]);
con[n] := base or TdtPolyRef(i);
Inc(n);
end;
break;
end;
end;
Result := n;
end;
procedure TdtNavMesh.unconnectExtLinks(tile, target: PdtMeshTile);
var targetNum: Cardinal; i: Integer; poly: PdtPoly; j,pj,nj: Cardinal;
begin
if (tile = nil) or (target = nil) then Exit;
targetNum := decodePolyIdTile(getTileRef(target));
for i := 0 to tile.header.polyCount - 1 do
begin
poly := @tile.polys[i];
j := poly.firstLink;
pj := DT_NULL_LINK;
while (j <> DT_NULL_LINK) do
begin
if (tile.links[j].side <> $ff) and
(decodePolyIdTile(tile.links[j].ref) = targetNum) then
begin
// Revove link.
nj := tile.links[j].next;
if (pj = DT_NULL_LINK) then
poly.firstLink := nj
else
tile.links[pj].next := nj;
freeLink(tile, j);
j := nj;
end
else
begin
// Advance
pj := j;
j := tile.links[j].next;
end;
end;
end;
end;
procedure TdtNavMesh.connectExtLinks(tile, target: PdtMeshTile; side: Integer);
var i,j,k: Integer; poly: PdtPoly; nv,dir: Integer; va,vb: PSingle; nei: array [0..3] of TdtPolyRef; neia: array [0..7] of Single;
nnei: Integer; idx: Cardinal; link: PdtLink; tmin,tmax: Single;
begin
if (tile = nil) then Exit;
// Connect border links.
for i := 0 to tile.header.polyCount - 1 do
begin
poly := @tile.polys[i];
// Create new links.
// unsigned short m := DT_EXT_LINK | (unsigned short)side;
nv := poly.vertCount;
for j := 0 to nv - 1 do
begin
// Skip non-portal edges.
if ((poly.neis[j] and DT_EXT_LINK) = 0) then
continue;
dir := Integer(poly.neis[j] and $ff);
if (side <> -1) and (dir <> side) then
continue;
// Create new links
va := @tile.verts[poly.verts[j]*3];
vb := @tile.verts[poly.verts[(j+1) mod nv]*3];
nnei := findConnectingPolys(va,vb, target, dtOppositeTile(dir), @nei[0],@neia[0],4);
for k := 0 to nnei - 1 do
begin
idx := allocLink(tile);
if (idx <> DT_NULL_LINK) then
begin
link := @tile.links[idx];
link.ref := nei[k];
link.edge := Byte(j);
link.side := Byte(dir);
link.next := poly.firstLink;
poly.firstLink := idx;
// Compress portal limits to a byte value.
if (dir = 0) or (dir = 4) then
begin
tmin := (neia[k*2+0]-va[2]) / (vb[2]-va[2]);
tmax := (neia[k*2+1]-va[2]) / (vb[2]-va[2]);
if (tmin > tmax) then
dtSwap(tmin,tmax);
link.bmin := Byte(Trunc(dtClamp(tmin, 0.0, 1.0)*255.0));
link.bmax := Byte(Trunc(dtClamp(tmax, 0.0, 1.0)*255.0));
end
else if (dir = 2) or (dir = 6) then
begin
tmin := (neia[k*2+0]-va[0]) / (vb[0]-va[0]);
tmax := (neia[k*2+1]-va[0]) / (vb[0]-va[0]);
if (tmin > tmax) then
dtSwap(tmin,tmax);
link.bmin := Byte(Trunc(dtClamp(tmin, 0.0, 1.0)*255.0));
link.bmax := Byte(Trunc(dtClamp(tmax, 0.0, 1.0)*255.0));
end;
end;
end;
end;
end;
end;
procedure TdtNavMesh.connectExtOffMeshLinks(tile, target: PdtMeshTile; side: Integer);
var oppositeSide: Byte; i: Integer; targetCon: PdtOffMeshConnection; targetPoly: PdtPoly; ext,nearestPt: array [0..2] of Single;
p,v: PSingle; ref: TdtPolyRef; idx,tidx: Cardinal; link: PdtLink; landPolyIdx: Word; landPoly: PdtPoly;
begin
if (tile = nil) then Exit;
// Connect off-mesh links.
// We are interested on links which land from target tile to this tile.
if (side = -1) then oppositeSide := $ff else oppositeSide := Byte(dtOppositeTile(side));
for i := 0 to target.header.offMeshConCount - 1 do
begin
targetCon := @target.offMeshCons[i];
if (targetCon.side <> oppositeSide) then
continue;
targetPoly := @target.polys[targetCon.poly];
// Skip off-mesh connections which start location could not be connected at all.
if (targetPoly.firstLink = DT_NULL_LINK) then
continue;
ext[0] := targetCon.rad; ext[1] := target.header.walkableClimb; ext[2] := targetCon.rad;
// Find polygon to connect to.
p := @targetCon.pos[3];
ref := findNearestPolyInTile(tile, p, @ext[0], @nearestPt[0]);
if (ref = 0) then
continue;
// findNearestPoly may return too optimistic results, further check to make sure.
if (Sqr(nearestPt[0]-p[0])+Sqr(nearestPt[2]-p[2]) > Sqr(targetCon.rad)) then
continue;
// Make sure the location is on current mesh.
v := @target.verts[targetPoly.verts[1]*3];
dtVcopy(v, @nearestPt[0]);
// Link off-mesh connection to target poly.
idx := allocLink(target);
if (idx <> DT_NULL_LINK) then
begin
link := @target.links[idx];
link.ref := ref;
link.edge := Byte(1);
link.side := oppositeSide;
link.bmin := 0; link.bmax := 0;
// Add to linked list.
link.next := targetPoly.firstLink;
targetPoly.firstLink := idx;
end;
// Link target poly to off-mesh connection.
if (targetCon.flags and DT_OFFMESH_CON_BIDIR <> 0) then
begin
tidx := allocLink(tile);
if (tidx <> DT_NULL_LINK) then
begin
landPolyIdx := Word(decodePolyIdPoly(ref));
landPoly := @tile.polys[landPolyIdx];
link := @tile.links[tidx];
link.ref := getPolyRefBase(target) or TdtPolyRef(targetCon.poly);
link.edge := $ff;
link.side := Byte(IfThen(side = -1, $ff, side));
link.bmin := 0; link.bmax := 0;
// Add to linked list.
link.next := landPoly.firstLink;
landPoly.firstLink := tidx;
end;
end;
end;
end;
procedure TdtNavMesh.connectIntLinks(tile: PdtMeshTile);
var base: TdtPolyRef; i,j: Integer; poly: PdtPoly; idx: Cardinal; link: PdtLink;
begin
if (tile = nil) then Exit;
base := getPolyRefBase(tile);
for i := 0 to tile.header.polyCount - 1 do
begin
poly := @tile.polys[i];
poly.firstLink := DT_NULL_LINK;
if (poly.getType() = DT_POLYTYPE_OFFMESH_CONNECTION) then
continue;
// Build edge links backwards so that the links will be
// in the linked list from lowest index to highest.
for j := poly.vertCount-1 downto 0 do
begin
// Skip hard and non-internal edges.
if (poly.neis[j] = 0) or ((poly.neis[j] and DT_EXT_LINK) <> 0) then continue;
idx := allocLink(tile);
if (idx <> DT_NULL_LINK) then
begin
link := @tile.links[idx];
link.ref := base or TdtPolyRef(poly.neis[j]-1);
link.edge := Byte(j);
link.side := $ff;
link.bmin := 0; link.bmax := 0;
// Add to linked list.
link.next := poly.firstLink;
poly.firstLink := idx;
end;
end;
end;
end;
procedure TdtNavMesh.baseOffMeshLinks(tile: PdtMeshTile);
var base: TdtPolyRef; i: Integer; con: PdtOffMeshConnection; poly: PdtPoly; ext,nearestPt: array [0..2] of Single;
p,v: PSingle; ref: TdtPolyRef; idx,tidx: Cardinal; link: PdtLink; landPolyIdx: Word; landPoly: PdtPoly;
begin
if (tile = nil) then Exit;
base := getPolyRefBase(tile);
// Base off-mesh connection start points.
for i := 0 to tile.header.offMeshConCount - 1 do
begin
con := @tile.offMeshCons[i];
poly := @tile.polys[con.poly];
ext[0] := con.rad; ext[1] := tile.header.walkableClimb; ext[2] := con.rad;
// Find polygon to connect to.
p := @con.pos[0]; // First vertex
ref := findNearestPolyInTile(tile, p, @ext[0], @nearestPt[0]);
if (ref = 0) then continue;
// findNearestPoly may return too optimistic results, further check to make sure.
if (Sqr(nearestPt[0]-p[0])+Sqr(nearestPt[2]-p[2]) > Sqr(con.rad)) then
continue;
// Make sure the location is on current mesh.
v := @tile.verts[poly.verts[0]*3];
dtVcopy(v, @nearestPt[0]);
// Link off-mesh connection to target poly.
idx := allocLink(tile);
if (idx <> DT_NULL_LINK) then
begin
link := @tile.links[idx];
link.ref := ref;
link.edge := 0;
link.side := $ff;
link.bmin := 0; link.bmax := 0;
// Add to linked list.
link.next := poly.firstLink;
poly.firstLink := idx;
end;
// Start end-point is always connect back to off-mesh connection.
tidx := allocLink(tile);
if (tidx <> DT_NULL_LINK) then
begin
landPolyIdx := Word(decodePolyIdPoly(ref));
landPoly := @tile.polys[landPolyIdx];
link := @tile.links[tidx];
link.ref := base or TdtPolyRef(con.poly);
link.edge := $ff;
link.side := $ff;
link.bmin := 0; link.bmax := 0;
// Add to linked list.
link.next := landPoly.firstLink;
landPoly.firstLink := tidx;
end;
end;
end;
procedure TdtNavMesh.closestPointOnPoly(ref: TdtPolyRef; pos, closest: PSingle; posOverPoly: PBoolean);
var tile: PdtMeshTile; poly: PdtPoly; v0,v1,va,vb: PSingle; d0,d1,u: Single; ip: Cardinal; pd: PdtPolyDetail;
verts: array [0..DT_VERTS_PER_POLYGON*3-1] of Single; edged,edget: array [0..DT_VERTS_PER_POLYGON-1] of Single;
nv,i,imin,j,k: Integer; dmin,h: Single; t: PByte; v: array [0..2] of PSingle;
begin
tile := nil;
poly := nil;
getTileAndPolyByRefUnsafe(ref, @tile, @poly);
// Off-mesh connections don't have detail polygons.
if (poly.getType() = DT_POLYTYPE_OFFMESH_CONNECTION) then
begin
v0 := @tile.verts[poly.verts[0]*3];
v1 := @tile.verts[poly.verts[1]*3];
d0 := dtVdist(pos, v0);
d1 := dtVdist(pos, v1);
u := d0 / (d0+d1);
dtVlerp(closest, v0, v1, u);
if (posOverPoly <> nil) then
posOverPoly^ := false;
Exit;
end;
ip := Cardinal(poly - tile.polys);
pd := @tile.detailMeshes[ip];
// Clamp point to be inside the polygon.
nv := poly.vertCount;
for i := 0 to nv - 1 do
dtVcopy(@verts[i*3], @tile.verts[poly.verts[i]*3]);
dtVcopy(closest, pos);
if (not dtDistancePtPolyEdgesSqr(pos, @verts[0], nv, @edged[0], @edget[0])) then
begin
// Point is outside the polygon, dtClamp to nearest edge.
dmin := MaxSingle;
imin := -1;
for i := 0 to nv - 1 do
begin
if (edged[i] < dmin) then
begin
dmin := edged[i];
imin := i;
end;
end;
va := @verts[imin*3];
vb := @verts[((imin+1) mod nv)*3];
dtVlerp(closest, va, vb, edget[imin]);
if (posOverPoly <> nil) then
posOverPoly^ := false;
end
else
begin
if (posOverPoly <> nil) then
posOverPoly^ := true;
end;
// Find height at the location.
for j := 0 to pd.triCount - 1 do
begin
t := @tile.detailTris[(pd.triBase+j)*4];
for k := 0 to 2 do
begin
if (t[k] < poly.vertCount) then
v[k] := @tile.verts[poly.verts[t[k]]*3]
else
v[k] := @tile.detailVerts[(pd.vertBase+(t[k]-poly.vertCount))*3];
end;
if (dtClosestHeightPointTriangle(pos, v[0], v[1], v[2], @h)) then
begin
closest[1] := h;
break;
end;
end;
end;
function TdtNavMesh.findNearestPolyInTile(tile: PdtMeshTile; center, extents, nearestPt: PSingle): TdtPolyRef;
var bmin,bmax,closestPtPoly,diff: array [0..2] of Single; polys: array[0..127] of TdtPolyRef; polyCount,i: Integer; nearest: TdtPolyRef;
nearestDistanceSqr: Single; ref: TdtPolyRef; posOverPoly: Boolean; d: Single;
begin
dtVsub(@bmin[0], center, extents);
dtVadd(@bmax[0], center, extents);
// Get nearby polygons from proximity grid.
polyCount := queryPolygonsInTile(tile, @bmin[0], @bmax[0], @polys[0], 128);
// Find nearest polygon amongst the nearby polygons.
nearest := 0;
nearestDistanceSqr := MaxSingle;
for i := 0 to polyCount - 1 do
begin
ref := polys[i];
posOverPoly := false;
closestPointOnPoly(ref, center, @closestPtPoly[0], @posOverPoly);
// If a point is directly over a polygon and closer than
// climb height, favor that instead of straight line nearest point.
dtVsub(@diff[0], center, @closestPtPoly[0]);
if (posOverPoly) then
begin
d := Abs(diff[1]) - tile.header.walkableClimb;
d := IfThen(d > 0, d*d, 0);
end
else
begin
d := dtVlenSqr(@diff[0]);
end;
if (d < nearestDistanceSqr) then
begin
dtVcopy(nearestPt, @closestPtPoly[0]);
nearestDistanceSqr := d;
nearest := ref;
end;
end;
Result := nearest;
end;
function TdtNavMesh.queryPolygonsInTile(tile: PdtMeshTile; qmin, qmax: PSingle; polys: PdtPolyRef; maxPolys: Integer): Integer;
var node: PdtBVNode; &end: PdtBVNode; tbmin,tbmax: Psingle; qfac: Single; bmin,bmax: array [0..2] of Word; bminf,bmaxf: array [0..2] of Single;
minx,miny,minz,maxx,maxy,maxz: Single; base: TdtPolyRef; i,j,n,escapeIndex: Integer; overlap,isLeafNode: Boolean; p: PdtPoly;
v: PSingle;
begin
if (tile.bvTree <> nil) then
begin
node := @tile.bvTree[0];
&end := @tile.bvTree[tile.header.bvNodeCount];
tbmin := @tile.header.bmin[0];
tbmax := @tile.header.bmax[0];
qfac := tile.header.bvQuantFactor;
// Calculate quantized box
// dtClamp query box to world box.
minx := dtClamp(qmin[0], tbmin[0], tbmax[0]) - tbmin[0];
miny := dtClamp(qmin[1], tbmin[1], tbmax[1]) - tbmin[1];
minz := dtClamp(qmin[2], tbmin[2], tbmax[2]) - tbmin[2];
maxx := dtClamp(qmax[0], tbmin[0], tbmax[0]) - tbmin[0];
maxy := dtClamp(qmax[1], tbmin[1], tbmax[1]) - tbmin[1];
maxz := dtClamp(qmax[2], tbmin[2], tbmax[2]) - tbmin[2];
// Quantize
bmin[0] := Word(Trunc(qfac * minx)) and $fffe;
bmin[1] := Word(Trunc(qfac * miny)) and $fffe;
bmin[2] := Word(Trunc(qfac * minz)) and $fffe;
bmax[0] := Word(Trunc(qfac * maxx + 1)) or 1;
bmax[1] := Word(Trunc(qfac * maxy + 1)) or 1;
bmax[2] := Word(Trunc(qfac * maxz + 1)) or 1;
// Traverse tree
base := getPolyRefBase(tile);
n := 0;
while (node < &end) do
begin
overlap := dtOverlapQuantBounds(@bmin[0], @bmax[0], @node.bmin[0], @node.bmax[0]);
isLeafNode := node.i >= 0;
if (isLeafNode and overlap) then
begin
if (n < maxPolys) then
begin
polys[n] := base or TdtPolyRef(node.i);
Inc(n);
end;
end;
if (overlap) or (isLeafNode) then
Inc(node)
else
begin
escapeIndex := -node.i;
Inc(node, escapeIndex);
end;
end;
Exit(n);
end
else
begin
n := 0;
base := getPolyRefBase(tile);
for i := 0 to tile.header.polyCount - 1 do
begin
p := @tile.polys[i];
// Do not return off-mesh connection polygons.
if (p.getType() = DT_POLYTYPE_OFFMESH_CONNECTION) then
continue;
// Calc polygon bounds.
v := @tile.verts[p.verts[0]*3];
dtVcopy(@bminf[0], v);
dtVcopy(@bmaxf[0], v);
for j := 1 to p.vertCount - 1 do
begin
v := @tile.verts[p.verts[j]*3];
dtVmin(@bminf[0], v);
dtVmax(@bmaxf[0], v);
end;
if (dtOverlapBounds(qmin,qmax, @bminf[0],@bmaxf[0])) then
begin
if (n < maxPolys) then
begin
polys[n] := base or TdtPolyRef(i);
Inc(n);
end;
end;
end;
Exit(n);
end;
end;
/// @par
///
/// The add operation will fail if the data is in the wrong format, the allocated tile
/// space is full, or there is a tile already at the specified reference.
///
/// The lastRef parameter is used to restore a tile with the same tile
/// reference it had previously used. In this case the #dtPolyRef's for the
/// tile will be restored to the same values they were before the tile was
/// removed.
///
/// @see dtCreateNavMeshData, #removeTile
function TdtNavMesh.addTile(data: PByte; dataSize, flags: Integer; lastRef: TdtTileRef; reslt: PdtTileRef): TdtStatus;
const MAX_NEIS = 32;
var header: PdtMeshHeader; tile: PdtMeshTile; tileIndex,h: Integer; target, prev: PdtMeshTile;
headerSize, vertsSize, polysSize, linksSize, detailMeshesSize, detailVertsSize, detailTrisSize, bvtreeSize, offMeshLinksSize: Integer;
d: PByte; i,j,nneis: Integer; neis: array [0..MAX_NEIS-1] of PdtMeshTile;
begin
// Make sure the data is in right format.
header := PdtMeshHeader(data);
if (header.magic <> DT_NAVMESH_MAGIC) then
Exit(DT_FAILURE or DT_WRONG_MAGIC);
if (header.version <> DT_NAVMESH_VERSION) then
Exit(DT_FAILURE or DT_WRONG_VERSION);
// Make sure the location is free.
if (getTileAt(header.x, header.y, header.layer) <> nil) then
Exit(DT_FAILURE);
// Allocate a tile.
tile := nil;
if (lastRef = 0) then
begin
if (m_nextFree <> nil) then
begin
tile := m_nextFree;
m_nextFree := tile.next;
tile.next := nil;
end;
end
else
begin
// Try to relocate the tile to specific index with same salt.
tileIndex := Integer(decodePolyIdTile(TdtPolyRef(lastRef)));
if (tileIndex >= m_maxTiles) then
Exit(DT_FAILURE or DT_OUT_OF_MEMORY);
// Try to find the specific tile id from the free list.
target := @m_tiles[tileIndex];
prev := nil;
tile := m_nextFree;
while (tile <> nil) and (tile <> target) do
begin
prev := tile;
tile := tile.next;
end;
// Could not find the correct location.
if (tile <> target) then
Exit(DT_FAILURE or DT_OUT_OF_MEMORY);
// Remove from freelist
if (prev = nil) then
m_nextFree := tile.next
else
prev.next := tile.next;
// Restore salt.
tile.salt := decodePolyIdSalt(TdtPolyRef(lastRef));
end;
// Make sure we could allocate a tile.
if (tile = nil) then
Exit(DT_FAILURE or DT_OUT_OF_MEMORY);
// Insert tile into the position lut.
h := computeTileHash(header.x, header.y, m_tileLutMask);
tile.next := PdtMeshTile(m_posLookup[h]);
m_posLookup[h] := tile;
// Patch header pointers.
headerSize := dtAlign4(sizeof(TdtMeshHeader));
vertsSize := dtAlign4(sizeof(Single)*3*header.vertCount);
polysSize := dtAlign4(sizeof(TdtPoly)*header.polyCount);
linksSize := dtAlign4(sizeof(TdtLink)*(header.maxLinkCount));
detailMeshesSize := dtAlign4(sizeof(TdtPolyDetail)*header.detailMeshCount);
detailVertsSize := dtAlign4(sizeof(Single)*3*header.detailVertCount);
detailTrisSize := dtAlign4(sizeof(Byte)*4*header.detailTriCount);
bvtreeSize := dtAlign4(sizeof(TdtBVNode)*header.bvNodeCount);
offMeshLinksSize := dtAlign4(sizeof(TdtOffMeshConnection)*header.offMeshConCount);
d := data + headerSize;
tile.verts := PSingle(d); Inc(d, vertsSize);
tile.polys := PdtPoly(d); Inc(d, polysSize);
tile.links := PdtLink(d); Inc(d, linksSize);
tile.detailMeshes := PdtPolyDetail(d); Inc(d, detailMeshesSize);
tile.detailVerts := PSingle(d); Inc(d, detailVertsSize);
tile.detailTris := PByte(d); Inc(d, detailTrisSize);
tile.bvTree := PdtBVNode(d); Inc(d, bvtreeSize);
tile.offMeshCons := PdtOffMeshConnection(d); Inc(d, offMeshLinksSize);
// If there are no items in the bvtree, reset the tree pointer.
if (bvtreeSize = 0) then
tile.bvTree := nil;
// Build links freelist
tile.linksFreeList := 0;
tile.links[header.maxLinkCount-1].next := DT_NULL_LINK;
for i := 0 to header.maxLinkCount-1 - 1 do
tile.links[i].next := i+1;
// Init tile.
tile.header := header;
tile.data := data;
tile.dataSize := dataSize;
tile.flags := flags;
connectIntLinks(tile);
baseOffMeshLinks(tile);
// Create connections with neighbour tiles.
// Connect with layers in current tile.
nneis := getTilesAt(header.x, header.y, @neis[0], MAX_NEIS);
for j := 0 to nneis - 1 do
begin
if (neis[j] <> tile) then
begin
connectExtLinks(tile, neis[j], -1);
connectExtLinks(neis[j], tile, -1);
end;
connectExtOffMeshLinks(tile, neis[j], -1);
connectExtOffMeshLinks(neis[j], tile, -1);
end;
// Connect with neighbour tiles.
for i := 0 to 7 do
begin
nneis := getNeighbourTilesAt(header.x, header.y, i, @neis[0], MAX_NEIS);
for j := 0 to nneis - 1 do
begin
connectExtLinks(tile, neis[j], i);
connectExtLinks(neis[j], tile, dtOppositeTile(i));
connectExtOffMeshLinks(tile, neis[j], i);
connectExtOffMeshLinks(neis[j], tile, dtOppositeTile(i));
end;
end;
if (reslt <> nil) then
reslt^ := getTileRef(tile);
Result := DT_SUCCESS;
end;
function TdtNavMesh.getTileAt(x, y, layer: Integer): PdtMeshTile;
var h: Integer; tile: PdtMeshTile;
begin
// Find tile based on hash.
h := computeTileHash(x,y,m_tileLutMask);
tile := m_posLookup[h];
while (tile <> nil) do
begin
if (tile.header <> nil) and
(tile.header.x = x) and
(tile.header.y = y) and
(tile.header.layer = layer) then
begin
Exit(tile);
end;
tile := tile.next;
end;
Result := nil;
end;
function TdtNavMesh.getNeighbourTilesAt(x, y, side: Integer; tiles: PPdtMeshTile; maxTiles: Integer): Integer;
var nx,ny: Integer;
begin
nx := x; ny := y;
case side of
0: begin Inc(nx); end;
1: begin Inc(nx); Inc(ny); end;
2: begin Inc(ny); end;
3: begin Dec(nx); Inc(ny); end;
4: begin Dec(nx); end;
5: begin Dec(nx); Dec(ny); end;
6: begin Dec(ny); end;
7: begin Inc(nx); Dec(ny); end;
end;
Result := getTilesAt(nx, ny, tiles, maxTiles);
end;
function TdtNavMesh.getTilesAt(x, y: Integer; tiles: PPdtMeshTile; maxTiles: Integer): Integer;
var n,h: Integer; tile: PdtMeshTile;
begin
n := 0;
// Find tile based on hash.
h := computeTileHash(x,y,m_tileLutMask);
tile := m_posLookup[h];
while (tile <> nil) do
begin
if (tile.header <> nil) and
(tile.header.x = x) and
(tile.header.y = y) then
begin
if (n < maxTiles) then
begin
tiles[n] := tile;
Inc(n);
end;
end;
tile := tile.next;
end;
Result := n;
end;
function TdtNavMesh.getTileRefAt(x, y, layer: Integer): TdtTileRef;
var h: Integer; tile: PdtMeshTile;
begin
// Find tile based on hash.
h := computeTileHash(x,y,m_tileLutMask);
tile := m_posLookup[h];
while (tile <> nil) do
begin
if (tile.header <> nil) and
(tile.header.x = x) and
(tile.header.y = y) and
(tile.header.layer = layer) then
begin
Exit(getTileRef(tile));
end;
tile := tile.next;
end;
Result := 0;
end;
function TdtNavMesh.getTileByRef(ref: TdtTileRef): PdtMeshTile;
var tileIndex, tileSalt: Cardinal; tile: PdtMeshTile;
begin
if (ref = 0) then
Exit(nil);
tileIndex := decodePolyIdTile(TdtPolyRef(ref));
tileSalt := decodePolyIdSalt(TdtPolyRef(ref));
if (Integer(tileIndex) >= m_maxTiles) then
Exit(nil);
tile := @m_tiles[tileIndex];
if (tile.salt <> tileSalt) then
Exit(nil);
Result := tile;
end;
function TdtNavMesh.getMaxTiles(): Integer;
begin
Result := m_maxTiles;
end;
function TdtNavMesh.getTile(i: Integer): PdtMeshTile;
begin
Result := @m_tiles[i];
end;
procedure TdtNavMesh.calcTileLoc(pos: PSingle; tx, ty: PInteger);
begin
tx^ := floor((pos[0]-m_orig[0]) / m_tileWidth);
ty^ := floor((pos[2]-m_orig[2]) / m_tileHeight);
end;
function TdtNavMesh.getTileAndPolyByRef(ref: TdtPolyRef; tile: PPdtMeshTile; poly: PPdtPoly): TdtStatus;
var salt, it, ip: Cardinal;
begin
if (ref = 0) then Exit(DT_FAILURE);
decodePolyId(ref, @salt, @it, @ip);
if (it >= m_maxTiles) then Exit(DT_FAILURE or DT_INVALID_PARAM);
if (m_tiles[it].salt <> salt) or (m_tiles[it].header = nil) then Exit(DT_FAILURE or DT_INVALID_PARAM);
if (ip >= m_tiles[it].header.polyCount) then Exit(DT_FAILURE or DT_INVALID_PARAM);
tile^ := @m_tiles[it];
poly^ := @m_tiles[it].polys[ip];
Result := DT_SUCCESS;
end;
/// @par
///
/// @warning Only use this function if it is known that the provided polygon
/// reference is valid. This function is faster than #getTileAndPolyByRef, but
/// it does not validate the reference.
procedure TdtNavMesh.getTileAndPolyByRefUnsafe(ref: TdtPolyRef; tile: PPdtMeshTile; poly: PPdtPoly);
var salt, it, ip: Cardinal;
begin
decodePolyId(ref, @salt, @it, @ip);
tile^ := @m_tiles[it];
poly^ := @m_tiles[it].polys[ip];
end;
function TdtNavMesh.isValidPolyRef(ref: TdtPolyRef): Boolean;
var salt, it, ip: Cardinal;
begin
if (ref = 0) then Exit(false);
decodePolyId(ref, @salt, @it, @ip);
if (it >= m_maxTiles) then Exit(false);
if (m_tiles[it].salt <> salt) or (m_tiles[it].header = nil) then Exit(false);
if (ip >= m_tiles[it].header.polyCount) then Exit(false);
Result := true;
end;
/// @par
///
/// This function returns the data for the tile so that, if desired,
/// it can be added back to the navigation mesh at a later point.
///
/// @see #addTile
function TdtNavMesh.removeTile(ref: TdtTileRef; data: PPointer; dataSize: PInteger): TdtStatus;
const MAX_NEIS = 32;
var tileIndex, tileSalt: Cardinal; tile,prev,cur: PdtMeshTile; i,j,h,nneis: Integer; neis: array [0..MAX_NEIS-1] of PdtMeshTile;
begin
if (ref = 0) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
tileIndex := decodePolyIdTile(TdtPolyRef(ref));
tileSalt := decodePolyIdSalt(TdtPolyRef(ref));
if (tileIndex >= m_maxTiles) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
tile := @m_tiles[tileIndex];
if (tile.salt <> tileSalt) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Remove tile from hash lookup.
h := computeTileHash(tile.header.x,tile.header.y,m_tileLutMask);
prev := nil;
cur := m_posLookup[h];
while (cur <> nil) do
begin
if (cur = tile) then
begin
if (prev <> nil) then
prev.next := cur.next
else
m_posLookup[h] := cur.next;
break;
end;
prev := cur;
cur := cur.next;
end;
// Remove connections to neighbour tiles.
// Create connections with neighbour tiles.
// Connect with layers in current tile.
nneis := getTilesAt(tile.header.x, tile.header.y, @neis[0], MAX_NEIS);
for j := 0 to nneis - 1 do
begin
if (neis[j] = tile) then continue;
unconnectExtLinks(neis[j], tile);
end;
// Connect with neighbour tiles.
for i := 0 to 7 do
begin
nneis := getNeighbourTilesAt(tile.header.x, tile.header.y, i, @neis[0], MAX_NEIS);
for j := 0 to nneis - 1 do
unconnectExtLinks(neis[j], tile);
end;
// Reset tile.
if (tile.flags and DT_TILE_FREE_DATA <> 0) then
begin
// Owns data
FreeMem(tile.data);
tile.data := nil;
tile.dataSize := 0;
//todo: Doublecheck this
if (data <> nil) then data^ := nil;
if (dataSize <> nil) then dataSize^ := 0;
end
else
begin
//todo: Doublecheck this
if (data <> nil) then data^ := tile.data;
if (dataSize <> nil) then dataSize^ := tile.dataSize;
end;
tile.header := nil;
tile.flags := 0;
tile.linksFreeList := 0;
tile.polys := nil;
tile.verts := nil;
tile.links := nil;
tile.detailMeshes := nil;
tile.detailVerts := nil;
tile.detailTris := nil;
tile.bvTree := nil;
tile.offMeshCons := nil;
// Update salt, salt should never be zero.
{$ifdef DT_POLYREF64}
tile.salt := (tile.salt+1) and ((1<<DT_SALT_BITS)-1);
{$else}
tile.salt := (tile.salt+1) and ((1 shl m_saltBits)-1);
{$endif}
if (tile.salt = 0) then
Inc(tile.salt);
// Add to free list.
tile.next := m_nextFree;
m_nextFree := tile;
Result := DT_SUCCESS;
end;
function TdtNavMesh.getTileRef(tile: PdtMeshTile): TdtTileRef;
var it: Cardinal;
begin
if (tile = nil) then Exit(0);
it := Cardinal(tile - m_tiles);
Result := TdtTileRef(encodePolyId(tile.salt, it, 0));
end;
/// @par
///
/// Example use case:
/// @code
///
/// const dtPolyRef base := navmesh.getPolyRefBase(tile);
/// for i := 0 to tile.header.polyCount - 1 do
/// begin
/// const dtPoly* p := &tile.polys[i];
/// const dtPolyRef ref := base | (dtPolyRef)i;
///
/// // Use the reference to access the polygon data.
/// end;
/// @endcode
function TdtNavMesh.getPolyRefBase(tile: PdtMeshTile): TdtPolyRef;
var it: Cardinal;
begin
if (tile = nil) then Exit(0);
it := (tile - m_tiles);
Result := encodePolyId(tile.salt, it, 0);
end;
type
PdtTileState = ^TdtTileState;
TdtTileState = record
magic: Integer; // Magic number, used to identify the data.
version: Integer; // Data version number.
ref: TdtTileRef; // Tile ref at the time of storing the data.
end;
PdtPolyState = ^TdtPolyState;
TdtPolyState = record
flags: Word; // Flags (see dtPolyFlags).
area: Byte; // Area ID of the polygon.
end;
/// @see #storeTileState
function TdtNavMesh.getTileStateSize(tile: PdtMeshTile): Integer;
var headerSize,polyStateSize: Integer;
begin
if (tile = nil) then Exit(0);
headerSize := dtAlign4(sizeof(TdtTileState));
polyStateSize := dtAlign4(sizeof(TdtPolyState) * tile.header.polyCount);
Result := headerSize + polyStateSize;
end;
/// @par
///
/// Tile state includes non-structural data such as polygon flags, area ids, etc.
/// @note The state data is only valid until the tile reference changes.
/// @see #getTileStateSize, #restoreTileState
function TdtNavMesh.storeTileState(tile: PdtMeshTile; data: PByte; maxDataSize: Integer): TdtStatus;
var sizeReq: Integer; tileState: PdtTileState; polyStates: PdtPolyState; i: Integer; p: PdtPoly; s: PdtPolyState;
begin
// Make sure there is enough space to store the state.
sizeReq := getTileStateSize(tile);
if (maxDataSize < sizeReq) then
Exit(DT_FAILURE or DT_BUFFER_TOO_SMALL);
tileState := PdtTileState(data); Inc(data, dtAlign4(sizeof(TdtTileState)));
polyStates := PdtPolyState(data); Inc(data, dtAlign4(sizeof(TdtPolyState) * tile.header.polyCount));
// Store tile state.
tileState.magic := DT_NAVMESH_STATE_MAGIC;
tileState.version := DT_NAVMESH_STATE_VERSION;
tileState.ref := getTileRef(tile);
// Store per poly state.
for i := 0 to tile.header.polyCount - 1 do
begin
p := @tile.polys[i];
s := @polyStates[i];
s.flags := p.flags;
s.area := p.getArea();
end;
Result := DT_SUCCESS;
end;
/// @par
///
/// Tile state includes non-structural data such as polygon flags, area ids, etc.
/// @note This function does not impact the tile's #dtTileRef and #dtPolyRef's.
/// @see #storeTileState
function TdtNavMesh.restoreTileState(tile: PdtMeshTile; data: PByte; maxDataSize: Integer): TdtStatus;
var sizeReq: Integer; tileState: PdtTileState; polyStates: PdtPolyState; i: Integer; p: PdtPoly; s: PdtPolyState;
begin
// Make sure there is enough space to store the state.
sizeReq := getTileStateSize(tile);
if (maxDataSize < sizeReq) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
tileState := PdtTileState(data); Inc(data, dtAlign4(sizeof(TdtTileState)));
polyStates := PdtPolyState(data); Inc(data, dtAlign4(sizeof(TdtPolyState) * tile.header.polyCount));
// Check that the restore is possible.
if (tileState.magic <> DT_NAVMESH_STATE_MAGIC) then
Exit(DT_FAILURE or DT_WRONG_MAGIC);
if (tileState.version <> DT_NAVMESH_STATE_VERSION) then
Exit(DT_FAILURE or DT_WRONG_VERSION);
if (tileState.ref <> getTileRef(tile)) then
Exit(DT_FAILURE or DT_INVALID_PARAM);
// Restore per poly state.
for i := 0 to tile.header.polyCount - 1 do
begin
p := @tile.polys[i];
s := @polyStates[i];
p.flags := s.flags;
p.setArea(s.area);
end;
Result := DT_SUCCESS;
end;
/// @par
///
/// Off-mesh connections are stored in the navigation mesh as special 2-vertex
/// polygons with a single edge. At least one of the vertices is expected to be
/// inside a normal polygon. So an off-mesh connection is "entered" from a
/// normal polygon at one of its endpoints. This is the polygon identified by
/// the prevRef parameter.
function TdtNavMesh.getOffMeshConnectionPolyEndPoints(prevRef, polyRef: TdtPolyRef; startPos, endPos: PSingle): TdtStatus;
var salt, it, ip: Cardinal; tile: PdtMeshTile; poly: PdtPoly; idx0,idx1: Integer; i: Cardinal;
begin
if (polyRef = 0) then
Exit(DT_FAILURE);
// Get current polygon
decodePolyId(polyRef, @salt, @it, @ip);
if (it >= m_maxTiles) then Exit(DT_FAILURE or DT_INVALID_PARAM);
if (m_tiles[it].salt <> salt) or (m_tiles[it].header = nil) then Exit(DT_FAILURE or DT_INVALID_PARAM);
tile := @m_tiles[it];
if (ip >= tile.header.polyCount) then Exit(DT_FAILURE or DT_INVALID_PARAM);
poly := @tile.polys[ip];
// Make sure that the current poly is indeed off-mesh link.
if (poly.getType() <> DT_POLYTYPE_OFFMESH_CONNECTION) then
Exit(DT_FAILURE);
// Figure out which way to hand out the vertices.
idx0 := 0; idx1 := 1;
// Find link that points to first vertex.
i := poly.firstLink;
while (i <> DT_NULL_LINK) do
begin
if (tile.links[i].edge = 0) then
begin
if (tile.links[i].ref <> prevRef) then
begin
idx0 := 1;
idx1 := 0;
end;
break;
end;
i := tile.links[i].next;
end;
dtVcopy(startPos, @tile.verts[poly.verts[idx0]*3]);
dtVcopy(endPos, @tile.verts[poly.verts[idx1]*3]);
Result := DT_SUCCESS;
end;
function TdtNavMesh.getOffMeshConnectionByRef(ref: TdtPolyRef): PdtOffMeshConnection;
var salt, it, ip: Cardinal; tile: PdtMeshTile; poly: PdtPoly; idx: Cardinal;
begin
if (ref = 0) then
Exit(nil);
// Get current polygon
decodePolyId(ref, @salt, @it, @ip);
if (it >= m_maxTiles) then Exit(nil);
if (m_tiles[it].salt <> salt) or (m_tiles[it].header = nil) then Exit(nil);
tile := @m_tiles[it];
if (ip >= tile.header.polyCount) then Exit(nil);
poly := @tile.polys[ip];
// Make sure that the current poly is indeed off-mesh link.
if (poly.getType() <> DT_POLYTYPE_OFFMESH_CONNECTION) then
Exit(nil);
idx := ip - tile.header.offMeshBase;
Assert(idx < tile.header.offMeshConCount);
Result := @tile.offMeshCons[idx];
end;
function TdtNavMesh.setPolyFlags(ref: TdtPolyRef; flags: Word): TdtStatus;
var salt, it, ip: Cardinal; tile: PdtMeshTile; poly: PdtPoly;
begin
if (ref = 0) then Exit(DT_FAILURE);
decodePolyId(ref, @salt, @it, @ip);
if (it >= m_maxTiles) then Exit(DT_FAILURE or DT_INVALID_PARAM);
if (m_tiles[it].salt <> salt) or (m_tiles[it].header = nil) then Exit(DT_FAILURE or DT_INVALID_PARAM);
tile := @m_tiles[it];
if (ip >= tile.header.polyCount) then Exit(DT_FAILURE or DT_INVALID_PARAM);
poly := @tile.polys[ip];
// Change flags.
poly.flags := flags;
Result := DT_SUCCESS;
end;
function TdtNavMesh.getPolyFlags(ref: TdtPolyRef; resultFlags: PWord): TdtStatus;
var salt, it, ip: Cardinal; tile: PdtMeshTile; poly: PdtPoly;
begin
if (ref = 0) then Exit(DT_FAILURE);
decodePolyId(ref, @salt, @it, @ip);
if (it >= m_maxTiles) then Exit(DT_FAILURE or DT_INVALID_PARAM);
if (m_tiles[it].salt <> salt) or (m_tiles[it].header = nil) then Exit(DT_FAILURE or DT_INVALID_PARAM);
tile := @m_tiles[it];
if (ip >= tile.header.polyCount) then Exit(DT_FAILURE or DT_INVALID_PARAM);
poly := @tile.polys[ip];
resultFlags^ := poly.flags;
Result := DT_SUCCESS;
end;
function TdtNavMesh.setPolyArea(ref: TdtPolyRef; area: Byte): TdtStatus;
var salt, it, ip: Cardinal; tile: PdtMeshTile; poly: PdtPoly;
begin
if (ref = 0) then Exit(DT_FAILURE);
decodePolyId(ref, @salt, @it, @ip);
if (it >= m_maxTiles) then Exit(DT_FAILURE or DT_INVALID_PARAM);
if (m_tiles[it].salt <> salt) or (m_tiles[it].header = nil) then Exit(DT_FAILURE or DT_INVALID_PARAM);
tile := @m_tiles[it];
if (ip >= tile.header.polyCount) then Exit(DT_FAILURE or DT_INVALID_PARAM);
poly := @tile.polys[ip];
poly.setArea(area);
Result := DT_SUCCESS;
end;
function TdtNavMesh.getPolyArea(ref: TdtPolyRef; resultArea: PByte): TdtStatus;
var salt, it, ip: Cardinal; tile: PdtMeshTile; poly: PdtPoly;
begin
if (ref = 0) then Exit(DT_FAILURE);
decodePolyId(ref, @salt, @it, @ip);
if (it >= m_maxTiles) then Exit(DT_FAILURE or DT_INVALID_PARAM);
if (m_tiles[it].salt <> salt) or (m_tiles[it].header = nil) then Exit(DT_FAILURE or DT_INVALID_PARAM);
tile := @m_tiles[it];
if (ip >= tile.header.polyCount) then Exit(DT_FAILURE or DT_INVALID_PARAM);
poly := @tile.polys[ip];
resultArea^ := poly.getArea();
Result := DT_SUCCESS;
end;
function TdtNavMesh.encodePolyId(salt, it, ip: Cardinal): TdtPolyRef;
begin
{$ifdef DT_POLYREF64}
Result := ((dtPolyRef)salt << (DT_POLY_BITS+DT_TILE_BITS)) | ((dtPolyRef)it << DT_POLY_BITS) | (dtPolyRef)ip;
{$else}
Result := (TdtPolyRef(salt) shl (m_polyBits+m_tileBits)) or (TdtPolyRef(it) shl m_polyBits) or TdtPolyRef(ip);
{$endif}
end;
/// Decodes a standard polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference to decode.
/// @param[out] salt The tile's salt value.
/// @param[out] it The index of the tile.
/// @param[out] ip The index of the polygon within the tile.
/// @see #encodePolyId
procedure TdtNavMesh.decodePolyId(ref: TdtPolyRef; salt, it, ip: PCardinal);
var saltMask, tileMask, polyMask: TdtPolyRef;
begin
{$ifdef DT_POLYREF64}
const dtPolyRef saltMask = ((dtPolyRef)1<<DT_SALT_BITS)-1;
const dtPolyRef tileMask = ((dtPolyRef)1<<DT_TILE_BITS)-1;
const dtPolyRef polyMask = ((dtPolyRef)1<<DT_POLY_BITS)-1;
salt = (unsigned int)((ref >> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask);
it = (unsigned int)((ref >> DT_POLY_BITS) & tileMask);
ip = (unsigned int)(ref & polyMask);
{$else}
saltMask := (TdtPolyRef(1) shl m_saltBits)-1;
tileMask := (TdtPolyRef(1) shl m_tileBits)-1;
polyMask := (TdtPolyRef(1) shl m_polyBits)-1;
salt^ := ((ref shr (m_polyBits+m_tileBits)) and saltMask);
it^ := ((ref shr m_polyBits) and tileMask);
ip^ := (ref and polyMask);
{$endif}
end;
/// Extracts a tile's salt value from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function TdtNavMesh.decodePolyIdSalt(ref: TdtPolyRef): Cardinal;
var saltMask: TdtPolyRef;
begin
{$ifdef DT_POLYREF64}
const dtPolyRef saltMask = ((dtPolyRef)1<<DT_SALT_BITS)-1;
Result := (unsigned int)((ref >> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask);
{$else}
saltMask := (TdtPolyRef(1) shl m_saltBits)-1;
Result := Cardinal((ref shr (m_polyBits+m_tileBits)) and saltMask);
{$endif}
end;
/// Extracts the tile's index from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function TdtNavMesh.decodePolyIdTile(ref: TdtPolyRef): Cardinal;
var tileMask: TdtPolyRef;
begin
{$ifdef DT_POLYREF64}
const dtPolyRef tileMask = ((dtPolyRef)1<<DT_TILE_BITS)-1;
Result := (unsigned int)((ref >> DT_POLY_BITS) & tileMask);
{$else}
tileMask := (TdtPolyRef(1) shl m_tileBits)-1;
Result := Cardinal((ref shr m_polyBits) and tileMask);
{$endif}
end;
/// Extracts the polygon's index (within its tile) from the specified polygon reference.
/// @note This function is generally meant for internal use only.
/// @param[in] ref The polygon reference.
/// @see #encodePolyId
function TdtNavMesh.decodePolyIdPoly(ref: TdtPolyRef): Cardinal;
var polyMask: TdtPolyRef;
begin
{$ifdef DT_POLYREF64}
const dtPolyRef polyMask = ((dtPolyRef)1<<DT_POLY_BITS)-1;
Result := (unsigned int)(ref & polyMask);
{$else}
polyMask := (TdtPolyRef(1) shl m_polyBits)-1;
Result := Cardinal(ref and polyMask);
{$endif}
end;
procedure TdtNavMesh.SaveToStream(aStream: TMemoryStream);
var
I: Integer;
mt: PdtMeshTile;
mh: TdtMeshHeader;
//eol: Word;
begin
//eol := $0D0A;
aStream.Write(m_params, SizeOf(m_params));
aStream.Write(m_orig[0], SizeOf(m_orig));
aStream.Write(m_tileWidth, SizeOf(m_tileWidth));
aStream.Write(m_tileHeight, SizeOf(m_tileHeight));
aStream.Write(m_maxTiles, SizeOf(m_maxTiles));
aStream.Write(m_tileLutSize, SizeOf(m_tileLutSize));
aStream.Write(m_tileLutMask, SizeOf(m_tileLutMask));
//m_posLookup: PPointer;
for I := 0 to m_tileLutSize - 1 do
begin
aStream.Write(I, SizeOf(Integer));
if m_posLookup[I] <> nil then
begin
mt := PdtMeshTile(m_posLookup[I]);
aStream.Write(mt.salt, SizeOf(mt.salt));
aStream.Write(mt.linksFreeList, SizeOf(mt.linksFreeList));
// ..
end;
end;
//m_nextFree: PdtMeshTile;
if m_nextFree <> nil then
begin
aStream.Write(m_nextFree.salt, SizeOf(m_nextFree.salt));
aStream.Write(m_nextFree.linksFreeList, SizeOf(m_nextFree.linksFreeList));
// ..
end;
//m_tiles: PdtMeshTile;
for I := 0 to m_tileLutSize - 1 do
begin
mt := @m_tiles[I];
aStream.Write(mt.salt, SizeOf(mt.salt));
aStream.Write(mt.linksFreeList, SizeOf(mt.linksFreeList));
mh := mt.header^;
aStream.Write(mh, SizeOf(mh));
aStream.Write(mt.polys^, SizeOf(TdtPoly) * mh.polyCount);
aStream.Write(mt.verts^, SizeOf(Single) * 3 * mh.vertCount);
aStream.Write(mt.links^, SizeOf(TdtLink) * mh.maxLinkCount);
aStream.Write(mt.detailMeshes^, SizeOf(TdtPolyDetail) * mh.detailMeshCount);
aStream.Write(mt.detailVerts^, SizeOf(Single) * 3 * mh.detailVertCount);
aStream.Write(mt.detailTris^, SizeOf(Byte) * 4 * mh.detailTriCount);
aStream.Write(mt.bvTree^, SizeOf(TdtBVNode) * mh.bvNodeCount);
aStream.Write(mt.offMeshCons^, SizeOf(TdtOffMeshConnection) * mh.offMeshConCount);
aStream.Write(mt.data^, mt.dataSize);
aStream.Write(mt.dataSize, SizeOf(mt.dataSize));
aStream.Write(mt.flags, SizeOf(mt.flags));
//next: PdtMeshTile;
if mt.next <> nil then
begin
aStream.Write(mt.next.salt, SizeOf(mt.next.salt));
aStream.Write(mt.next.linksFreeList, SizeOf(mt.next.linksFreeList));
end;
end;
{$ifndef DT_POLYREF64}
aStream.Write(m_saltBits, SizeOf(m_saltBits));
aStream.Write(m_tileBits, SizeOf(m_tileBits));
aStream.Write(m_polyBits, SizeOf(m_polyBits));
{$endif}
end;
end.
|
unit WrapDelphiVCL;
{
Helper unit that will register all the wrappers for the VCL.
Instead of including WrapDelphiClasses, WrapDelphiControls... into your uses
clause, simply add WrapDelphiVCL.
}
interface
implementation
uses
WrapDelphiTypes,
WrapDelphiClasses,
WrapDelphiWindows,
WrapDelphiControls,
WrapDelphiGraphics,
WrapDelphiForms,
WrapDelphiActnList,
WrapDelphiStdCtrls,
WrapDelphiComCtrls,
WrapDelphiExtCtrls,
WrapDelphiButtons,
WrapDelphiGrids,
WrapDelphiSamplesSpin;
end.
|
unit FC.StockChart.UnitTask.Bars.DataGridDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, FC.Dialogs.DockedDialogCloseAndAppWindow_B, JvDockControlForm, ImgList, JvComponentBase, JvCaptionButton, StdCtrls,
ExtendControls, ExtCtrls,StockChart.Definitions,StockChart.Definitions.Units, FC.Definitions, Grids, DBGrids,
MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid, DB,FC.StockData.InputDataCollectionToDataSetMediator,
FC.StockChart.CustomDialog_B;
type
TfmBarsDataGridDialog = class(TfmStockChartCustomDialog_B)
dsData: TDataSource;
grData: TEditDBGrid;
private
FDataSet : TStockInputDataCollectionToDataSetMediator;
FIndicator : ISCIndicatorBars;
protected
public
constructor Create(const aExpert: ISCIndicatorBars; const aStockChart: IStockChart); reintroduce;
class procedure Run(const aExpert: ISCIndicatorBars; const aStockChart: IStockChart);
end;
implementation
uses ufmDialog_B,DateUtils, Application.Definitions;
{$R *.dfm}
{ TfmBarsDataGridDialog }
constructor TfmBarsDataGridDialog.Create(const aExpert: ISCIndicatorBars; const aStockChart: IStockChart);
begin
inherited Create(aStockChart);
FIndicator:=aExpert;
FDataSet:=TStockInputDataCollectionToDataSetMediator.Create(self);
FDataSet.InputDataCollection:=StockChart.GetInputData;
dsData.DataSet:=FDataSet;
Caption:=IndicatorFactory.GetIndicatorInfo(FIndicator.GetIID).Name+': '+Caption;
end;
class procedure TfmBarsDataGridDialog.Run(const aExpert: ISCIndicatorBars; const aStockChart: IStockChart);
begin
with TfmBarsDataGridDialog.Create(aExpert,aStockChart) do
Show;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{*******************************************************}
{ Picture Editor Dialog }
{*******************************************************}
unit PicEdit;
interface
uses Winapi.Windows, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.Dialogs, Vcl.Buttons, DesignIntf,
DesignEditors, Vcl.StdCtrls, Vcl.ExtCtrls, Vcl.ExtDlgs;
type
TPictureEditorDlg = class(TForm)
OpenDialog: TOpenPictureDialog;
SaveDialog: TSavePictureDialog;
OKButton: TButton;
CancelButton: TButton;
HelpButton: TButton;
GroupBox1: TGroupBox;
ImagePanel: TPanel;
Load: TButton;
Save: TButton;
Clear: TButton;
ImagePaintBox: TPaintBox;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure LoadClick(Sender: TObject);
procedure SaveClick(Sender: TObject);
procedure ClearClick(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
procedure ImagePaintBoxPaint(Sender: TObject);
private
Pic: TPicture;
end;
TPictureEditor = class(TComponent)
private
FGraphicClass: TGraphicClass;
FPicture: TPicture;
FPicDlg: TPictureEditorDlg;
procedure SetPicture(Value: TPicture);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function Execute: Boolean;
property GraphicClass: TGraphicClass read FGraphicClass write FGraphicClass;
property Picture: TPicture read FPicture write SetPicture;
end;
{ TPictureProperty
Property editor the TPicture properties (e.g. the Picture property). Brings
up a file open dialog allowing loading a picture file. }
TPictureProperty = class(TPropertyEditor)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TGraphicProperty }
TGraphicProperty = class(TClassProperty)
public
procedure Edit; override;
function GetAttributes: TPropertyAttributes; override;
function GetValue: string; override;
procedure SetValue(const Value: string); override;
end;
{ TGraphicEditor }
TGraphicEditor = class(TDefaultEditor)
public
procedure EditProperty(const Prop: IProperty;
var Continue: Boolean); override;
end;
implementation
uses System.TypInfo, System.SysUtils, DesignConst, LibHelp;
{$R *.dfm}
{ TPictureEditorDlg }
procedure TPictureEditorDlg.FormCreate(Sender: TObject);
begin
HelpContext := hcDPictureEditor;
Pic := TPicture.Create;
Save.Enabled := False;
end;
procedure TPictureEditorDlg.FormDestroy(Sender: TObject);
begin
Pic.Free;
end;
procedure TPictureEditorDlg.LoadClick(Sender: TObject);
begin
OpenDialog.Title := SLoadPictureTitle;
if OpenDialog.Execute then
begin
Pic.LoadFromFile(OpenDialog.Filename);
ImagePaintBox.Invalidate;
Save.Enabled := (Pic.Graphic <> nil) and not Pic.Graphic.Empty;
Clear.Enabled := (Pic.Graphic <> nil) and not Pic.Graphic.Empty;
end;
end;
procedure TPictureEditorDlg.SaveClick(Sender: TObject);
begin
if Pic.Graphic <> nil then
begin
SaveDialog.Title := SSavePictureTitle;
with SaveDialog do
begin
DefaultExt := GraphicExtension(TGraphicClass(Pic.Graphic.ClassType));
Filter := GraphicFilter(TGraphicClass(Pic.Graphic.ClassType));
if Execute then Pic.SaveToFile(Filename);
end;
end;
end;
procedure TPictureEditorDlg.ImagePaintBoxPaint(Sender: TObject);
var
DrawRect: TRect;
SNone: string;
begin
with TPaintBox(Sender) do
begin
Canvas.Brush.Color := {Self.}Color;
DrawRect := ClientRect;//Rect(Left, Top, Left + Width, Top + Height);
if Pic.Width > 0 then
begin
with DrawRect do
if (Pic.Width > Right - Left) or (Pic.Height > Bottom - Top) then
begin
if Pic.Width > Pic.Height then
Bottom := Top + MulDiv(Pic.Height, Right - Left, Pic.Width)
else
Right := Left + MulDiv(Pic.Width, Bottom - Top, Pic.Height);
Canvas.StretchDraw(DrawRect, Pic.Graphic);
end
else
with DrawRect do
Canvas.Draw(Left + (Right - Left - Pic.Width) div 2, Top + (Bottom - Top -
Pic.Height) div 2, Pic.Graphic);
end
else
with DrawRect, Canvas do
begin
SNone := srNone;
TextOut(Left + (Right - Left - TextWidth(SNone)) div 2, Top + (Bottom -
Top - TextHeight(SNone)) div 2, SNone);
end;
end;
end;
procedure TPictureEditorDlg.ClearClick(Sender: TObject);
begin
Pic.Graphic := nil;
ImagePaintBox.Invalidate;
Save.Enabled := False;
Clear.Enabled := False;
end;
{ TPictureEditor }
constructor TPictureEditor.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FPicture := TPicture.Create;
FPicDlg := TPictureEditorDlg.Create(Self);
FGraphicClass := TGraphic;
end;
destructor TPictureEditor.Destroy;
begin
FPicture.Free;
inherited Destroy;
end;
function TPictureEditor.Execute: Boolean;
begin
FPicDlg.Pic.Assign(FPicture);
with FPicDlg.OpenDialog do
begin
Options := [ofHideReadOnly, ofFileMustExist, ofShowHelp];
DefaultExt := GraphicExtension(GraphicClass);
Filter := GraphicFilter(GraphicClass);
HelpContext := hcDLoadPicture;
end;
with FPicDlg.SaveDialog do
begin
Options := [ofHideReadOnly, ofFileMustExist, ofShowHelp];
DefaultExt := GraphicExtension(GraphicClass);
Filter := GraphicFilter(GraphicClass);
HelpContext := hcDSavePicture;
end;
FPicDlg.Save.Enabled := (FPicture.Graphic <> nil) and not FPicture.Graphic.Empty;
FPicDlg.Clear.Enabled := (FPicture.Graphic <> nil) and not FPicture.Graphic.Empty;
Result := FPicDlg.ShowModal = mrOK;
if Result then FPicture.Assign(FPicDlg.Pic);
end;
procedure TPictureEditor.SetPicture(Value: TPicture);
begin
FPicture.Assign(Value);
end;
{ TPictureProperty }
procedure TPictureProperty.Edit;
var
PictureEditor: TPictureEditor;
begin
PictureEditor := TPictureEditor.Create(nil);
try
PictureEditor.Picture := TPicture(Pointer(GetOrdValue));
if PictureEditor.Execute then
SetOrdValue(Longint(PictureEditor.Picture));
finally
PictureEditor.Free;
end;
end;
function TPictureProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
function TPictureProperty.GetValue: string;
var
Picture: TPicture;
begin
Picture := TPicture(GetOrdValue);
if Picture.Graphic = nil then
Result := srNone else
Result := '(' + Picture.Graphic.ClassName + ')';
end;
procedure TPictureProperty.SetValue(const Value: string);
begin
if Value = '' then SetOrdValue(0);
end;
{ TGraphicProperty }
procedure TGraphicProperty.Edit;
var
PictureEditor: TPictureEditor;
begin
PictureEditor := TPictureEditor.Create(nil);
try
PictureEditor.GraphicClass := TGraphicClass(GetTypeData(GetPropType)^.ClassType);
PictureEditor.Picture.Graphic := TGraphic(Pointer(GetOrdValue));
if PictureEditor.Execute then
if (PictureEditor.Picture.Graphic = nil) or
(PictureEditor.Picture.Graphic is PictureEditor.GraphicClass) then
SetOrdValue(LongInt(PictureEditor.Picture.Graphic))
else
raise Exception.CreateRes(@SInvalidFormat);
finally
PictureEditor.Free;
end;
end;
function TGraphicProperty.GetAttributes: TPropertyAttributes;
begin
Result := [paDialog];
end;
function TGraphicProperty.GetValue: string;
var
Graphic: TGraphic;
begin
Graphic := TGraphic(GetOrdValue);
if (Graphic = nil) or Graphic.Empty then
Result := srNone else
Result := '(' + Graphic.ClassName + ')';
end;
procedure TGraphicProperty.SetValue(const Value: string);
begin
if Value = '' then SetOrdValue(0);
end;
{ TPictureEditor }
procedure TGraphicEditor.EditProperty(const Prop: IProperty;
var Continue: Boolean);
var
PropName: string;
begin
PropName := Prop.GetName;
if SameText(PropName, 'PICTURE') or
SameText(PropName, 'IMAGE') then
begin
Prop.Edit;
Continue := False;
end;
end;
procedure TPictureEditorDlg.HelpButtonClick(Sender: TObject);
begin
Application.HelpContext(HelpContext);
end;
end.
|
unit FrameDensityBase;
(*
FrameDensityBase.pas/dfm
----------------------
Begin: 2008/02/15
Last revision: $Date: 2008-12-10 21:03:31 $ $Author: areeves $
Version number: $Revision: 1.3 $
Project: APHI General Purpose Delphi Libary
Website: http://www.naadsm.org/opensource/delphi/
Author: Shaun Case <Shaun.Case@colostate.edu>
--------------------------------------------------
Copyright (C) 2005 - 2008 Animal Population Health Institute, Colorado State University
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 2 of the License, or
(at your option) any later version.
*)
interface
uses
Windows,
Messages,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
FrameEpiCurveDensityPlot
;
type TFrameDensityBase = class( TFrame )
protected
_graph: TFrameSummaryEpiCurvesDensityPlot;
function getGraphWidth(): integer;
function getGraphHeight(): integer;
public
constructor create( AOwner: TComponent ); override;
destructor destroy(); override;
function createMetafile(): TMetaFile;
function saveGraphToFile( fileName: string ): boolean;
function copyGraphToClipboard(): boolean;
function printGraph(): boolean;
property graphWidth: integer read getGraphWidth;
property graphHeight: integer read getGraphHeight;
end
;
implementation
{$R *.dfm}
uses
SysUtils,
ClipBrd,
MyStrUtils,
DebugWindow
;
const
DBSHOWMSG: boolean = true; // Set to true to enable debugging messages for this unit
//-----------------------------------------------------------------------------
// Construction/destruction
//-----------------------------------------------------------------------------
constructor TFrameDensityBase.create( AOwner: TComponent );
var
chartCount: integer;
procedure lookForGraph( cntnr: TWinControl );
var
i: integer;
begin
for i := 0 to cntnr.ControlCount - 1 do
begin
if( cntnr.Controls[i] is TFrameSummaryEpiCurvesDensityPlot ) then
begin
inc( chartCount );
_graph := cntnr.Controls[i] as TFrameSummaryEpiCurvesDensityPlot;
end
;
if( cntnr.Controls[i] is TWinControl ) then
begin
if( 0 < (cntnr.Controls[i] as TWinControl).controlCount ) then
lookForGraph( cntnr.Controls[i] as TWinControl )
;
end
;
end
;
end
;
begin
inherited create( AOwner );
chartCount := 0;
_graph := nil;
lookForGraph( self );
if( 1 <> chartCount ) then
begin
raise exception.Create( 'Wrong number of main graphs (' + intToStr(chartCount) + ') in TFrameDensityBase' );
_graph := nil;
end
;
end
;
destructor TFrameDensityBase.destroy();
begin
inherited destroy();
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Meta file creation
//-----------------------------------------------------------------------------
function TFrameDensityBase.createMetafile(): TMetaFile;
begin
dbcout( '_graph is nil: ' + booltoText( nil = _graph), true );
if( nil <> _graph ) then
// result := _graph.TeeCreateMetafile( False, Rect(0, 0, _chart.Width, _chart.Height ) )
else
result := nil
;
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Chart handling
//-----------------------------------------------------------------------------
function TFrameDensityBase.saveGraphToFile( fileName: string ): boolean;
Var
m: TMetafile;
begin
m := nil;
try
try
m := createMetaFile();
m.SaveToFile( fileName );
result := true;
except
result := false;
end;
finally
freeAndNil( m );
end;
end
;
function TFrameDensityBase.copyGraphToClipboard(): boolean;
var
m: TMetafile;
AFormat: word;
AData: Cardinal;
APalette: HPALETTE;
begin
m := nil;
try
try
m := createMetaFile();
m.SaveToClipboardFormat( AFormat, AData, aPalette );
ClipBoard.SetAsHandle( AFormat, AData );
result := true;
except
result := false;
end;
finally
freeAndNil( m );
end;
end
;
function TFrameDensityBase.printGraph(): boolean;
begin
try
try
Screen.Cursor := crHourGlass;
// _graph.PrintLandscape();
result := true;
except
result := false;
end;
finally
Screen.Cursor := crDefault;
end;
end
;
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Chart properties
//-----------------------------------------------------------------------------
function TFrameDensityBase.getGraphWidth(): integer;
begin
if( nil <> _graph ) then
result := _graph.Width
else
result := -1
;
end
;
function TFrameDensityBase.getGraphHeight(): integer;
begin
if( nil <> _graph ) then
result := _graph.Height
else
result := -1
;
end
;
//-----------------------------------------------------------------------------
end.
|
unit h_Files;
interface
uses winapi.windows, system.SysUtils, h_Functions, shellapi, classes, variants;
type
TFile = class
public
class function Move(pSource, pDestination: string): string;
class function Copy(pSource, pDestination: string): string;
class procedure Open(pFile: string);
class procedure Delete(pFile: string);
class function Rename(pOldName, pNewName: string): string;
class function Create(AbsoluteFileName: string): TFile;
class function readAll(AbsoluteFileName: string): string;
class function Append(FilePath, Content: string): string;
class procedure CpacDpac(pFile, pPathDestination: string; pCompacFiles: Boolean = true; const sw_state: integer = SW_HIDE);
class function quotedPath(path: string): string;
private
class procedure PathWork(Origem, Destino: string; work: integer); overload;
class procedure PathWork(Origem: string; work: integer = FO_DELETE); overload;
class function whiteSpaceResolver(path: string): pwidechar;
end;
implementation
uses v_Dir;
class function TFile.Move(pSource, pDestination: string): string;
begin
if not SameFileName(pSource, tdir.system) then
begin
if ExtractFileExt(pDestination) <> '' then
begin
if FileExists(pDestination) then
self.Delete(quotedPath(pDestination));
winapi.windows.MoveFile(pchar(pSource), pchar(pDestination));
end
else
PathWork(pSource, pDestination, FO_MOVE);
result := pDestination;
end;
end;
class procedure TFile.Open(pFile: string);
begin
if not FileExists(pFile) then
raise Exception.Create(Format('Arquivo [%s] não encontrado!', [pFile]));
ShellExecute(0, 'open', pchar(quotedPath(pFile)), nil, nil, SW_SHOWNORMAL);
end;
class procedure TFile.PathWork(Origem: string; work: integer);
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := work;
fFlags := FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR + FOF_NO_UI + FOF_RENAMEONCOLLISION + FOF_SILENT;
pFrom := pchar(Origem + #0);
end;
ShFileOperation(fos);
end;
class function TFile.quotedPath(path: string): string;
begin
result := '"' + path + '"';
end;
class function TFile.readAll(AbsoluteFileName: string): string;
var
log: TStringList;
begin
try
log := TStringList.Create;
if not FileExists(AbsoluteFileName) then
TFile.Create(AbsoluteFileName);
log.LoadFromFile(AbsoluteFileName);
result := log.Text;
except
exit
end;
end;
class procedure TFile.PathWork(Origem, Destino: string; work: integer);
var
fos: TSHFileOpStruct;
begin
ZeroMemory(@fos, SizeOf(fos));
with fos do
begin
wFunc := work;
fFlags := FOF_NOCONFIRMATION + FOF_NOCONFIRMMKDIR + FOF_NO_UI + FOF_RENAMEONCOLLISION + FOF_SILENT;
pFrom := pchar(Origem + #0);
pTo := pchar(Destino)
end;
ShFileOperation(fos);
end;
class function TFile.Rename(pOldName, pNewName: string): string;
{
Ex:
pOldName := D:/pasta1/arquivo.xml
pNewName := D/pasta1/novo_nome.xml
}
var
b: Boolean;
begin
if not SameFileName(pOldName, tdir.system) then
begin
if ExtractFileExt(pOldName) <> '' then
begin
if FileExists(pOldName) then
b := RenameFile(pOldName, pNewName);
end
else
self.PathWork(quotedPath(pOldName), quotedPath(pNewName), FO_RENAME);
result := pNewName;
end;
end;
class function TFile.whiteSpaceResolver(path: string): pwidechar;
begin
result := pwidechar(VarToStr(tfunctions.replace(path, ' ', char(32))))
end;
class procedure TFile.Delete(pFile: string);
begin
if not SameFileName(pFile, tdir.system) then
PathWork(pFile, FO_DELETE);
end;
class function TFile.Append(FilePath, Content: string): string;
var
log: TStringList;
begin
try
log := TStringList.Create;
if not FileExists(FilePath) then
TFile.Create(FilePath);
log.LoadFromFile(FilePath);
log.Add(Content);
log.SaveToFile(FilePath);
result := FilePath;
except
exit
end;
end;
class function TFile.Copy(pSource, pDestination: string): string;
begin
if ExtractFileExt(pDestination) <> '' then
begin
if FileExists(pDestination) then
self.Delete(quotedPath(pDestination));
winapi.windows.CopyFile(pchar(pSource), pchar(pDestination), true);
end
else
self.PathWork(pSource, pDestination, FO_COPY);
result := pDestination;
end;
class procedure TFile.CpacDpac(pFile, pPathDestination: string; pCompacFiles: Boolean = true; const sw_state: integer = SW_HIDE);
var
LibHandle: THandle;
function p(a: string): string;
var
l, w: string;
begin
l := tfunctions.getSubRegex(a, '[A-Za-z]:');
result := l + quotedPath(tfunctions.replace(a, l));
end;
begin
LibHandle := LoadLibrary(pwidechar(tdir._7zDLL));
if pCompacFiles then
tfunctions.ExecuteCommand(tdir._7z + ' -tzip a ' + p(pPathDestination) + ' ' + p(pFile), sw_state)
else
tfunctions.ExecuteCommand(tdir._7z + ' x ' + p(pFile) + ' -o' + p(pPathDestination) + ' -y', sw_state);
FreeLibrary(LibHandle);
end;
class function TFile.Create(AbsoluteFileName: string): TFile;
begin
if ExtractFileExt(AbsoluteFileName) <> '' then
TStringList.Create.SaveToFile(AbsoluteFileName)
else
begin
if not DirectoryExists(AbsoluteFileName) then
ForceDirectories(StringToOleStr(AbsoluteFileName));
end;
result := self.ClassInfo;
end;
end.
|
unit Warnbox;
interface
uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, Buttons,
StdCtrls, ExtCtrls, DB, DBTables, Wwtable, Wwdatsrc, Grids, Wwdbigrd,
Wwdbgrid, Sysutils, Types;
type
TWarningMessageDialog = class(TForm)
OKBtn: TBitBtn;
CaptionLabel1: TLabel;
Panel1: TPanel;
WarningsStringGrid: TStringGrid;
CancelButton: TBitBtn;
Label2: TLabel;
CaptionLabel2: TLabel;
procedure OKBtnClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
UnitName : String;
Cancelled : Boolean;
Procedure DisplayWarnings(AssessmentYear : String;
SwisSBLKey : String;
WarningCodeList,
WarningDescList : TStringList);
end;
var
WarningMessageDialog: TWarningMessageDialog;
implementation
uses Utilitys, PASUTILS, UTILEXSD, GlblCnst, Glblvars, WinUtils;
{$R *.DFM}
{================================================================}
Procedure TWarningMessageDialog.FormShow(Sender: TObject);
begin
UnitName := 'WARNBOX';
end; {FormShow}
{================================================================}
Procedure TWarningMessageDialog.DisplayWarnings(AssessmentYear : String;
SwisSBLKey : String;
WarningCodeList,
WarningDescList : TStringList);
var
I : Integer;
begin
Cancelled := False;
ClearStringGrid(WarningsStringGrid);
WarningMessageDialog.Caption := 'Warning messages for ' + ConvertSwisSBLToDashDot(SwisSBLKey);
CaptionLabel1.Caption := 'The following warning messages were received for parcel ' +
ConvertSwisSBLToDashDot(SwisSBLKey);
CaptionLabel2.Caption := 'for assessment year ' + AssessmentYear + ':';
with WarningsStringGrid do
begin
Cells[0, 0] := ' #';
Cells[1, 0] := 'Description';
end;
For I := 0 to (WarningCodeList.Count - 1) do
with WarningsStringGrid do
begin
Cells[0, (I + 1)] := WarningCodeList[I];
Cells[1, (I + 1)] := WarningDescList[I];
end;
end; {DisplayWarnings}
{================================================================}
Procedure TWarningMessageDialog.OKBtnClick(Sender: TObject);
begin
Close;
end;
{===================================================}
Procedure TWarningMessageDialog.CancelButtonClick(Sender: TObject);
begin
Cancelled := True;
Close;
end;
end.
|
unit AioTests;
interface
uses
Greenlets,
Classes,
SyncObjs,
SysUtils,
AsyncThread,
GreenletsImpl,
Generics.Collections,
Winapi.Windows,
GInterfaces,
Aio,
AioImpl,
Hub,
TestFramework;
type
TTestData = class(TComponent)
strict private
FX: Integer;
FY: Single;
FZ: string;
FArr: TBytes;
procedure ReadStreamParams(Stream: TStream);
procedure WriteStreamParams(Stream: TStream);
protected
procedure DefineProperties(Filer: TFiler); override;
public
property Arr: TBytes read FArr write FArr;
function IsEqual(Other: TTestData): Boolean;
published
property X: Integer read FX write FX;
property Y: Single read FY write FY;
property Z: string read FZ write FZ;
end;
TFakeOSProvider = class(TAioProvider)
strict private
FStream: TMemoryStream;
public
constructor Create;
destructor Destroy; override;
function Write(Buf: Pointer; Len: Integer): LongWord; override;
function Read(Buf: Pointer; Len: Integer): LongWord; override;
property Stream: TMemoryStream read FStream;
procedure Clear;
end;
tArrayOfString = array of string;
TAioTests = class(TTestCase)
private
FReadData: AnsiString;
FDataSz: Integer;
FAioList, FFSList: TList<string>;
FCliOutput: TStrings;
FServOutput: TStrings;
FOutput: TStrings;
procedure GWriteFile(const A: array of const);
procedure GReadFile(const A: array of const);
procedure RandomPosWrite(const A: array of const);
procedure SeekAndWrite(const A: array of const);
procedure SeekAndRead(const A: array of const);
function ReadAStrFromFile(const FName: string): AnsiString;
procedure WriteAToFile(const FName: string; const S: AnsiString);
procedure RunAsync(const Routine: TSymmetricArgsRoutine; const A: array of const);
procedure ReadWriteByStream(const A: array of const);
procedure ReadComp(const A: array of const);
procedure WriteComp(const A: array of const);
procedure EchoCliRoutine(const A: array of const);
procedure EchoTCPServRoutine;
procedure TCPSockEventsRoutine(const A: array of const);
procedure TcpWriter(const A: array of const);
procedure TcpReader(const A: array of const);
procedure NamedPipeEchoClient(const PipeName: string);
//
procedure ReadThreaded(const S: IAioTcpSocket; const Log: tArrayOfString);
procedure WriteThreaded(const S: IAioTcpSocket; const Data: TStrings; const SendTimeout: Integer);
//
procedure TcpStressClient(const Count: Integer;
const Port: Integer; const Index: Integer);
procedure TcpConnect(const Address: string; const Port: Integer; const Index: Integer);
protected
procedure SetUp; override;
procedure TearDown; override;
// soundcard (temporary hide this test)
procedure SoundCard;
published
procedure CreateAioFile;
procedure WriteAioFile;
procedure ReadAioFile;
procedure CompareAioFileAndStdFStream;
procedure ReadWriteComponent;
// tcp
procedure AioSocksCreateDestroy;
procedure AioTCPServerRunStop;
procedure AioProvFormatter;
procedure MBCSEncMemLeak;
procedure AioTCPConn;
procedure AioTCPConnNonRoot;
procedure AioTCPConnFalse;
procedure AioTCPConnFalseNonRoot;
procedure AioTCPConDisconn;
procedure AioTCPSocketEvents;
procedure AioTCPSocketConnect;
procedure AioTCPReaderWriter;
procedure AioTcpStress;
procedure AioTcpConnStress;
// aio потокобезопасны
procedure ReadWriteMultithreaded;
// udp
procedure AioUdpRoundBobin;
// named pipes
procedure CreateNamedPipe;
procedure NamedPipePingPong;
// console applications
procedure ConsoleApp;
procedure Console;
end;
implementation
{ TAioTests }
procedure TAioTests.AioProvFormatter;
var
Prov: TFakeOSProvider;
B: Byte;
Bytes: TBytes;
Int, Ps: Integer;
Utf8DataExpected, Utf8Terminator: string;
S, Tmp: string;
List: TStringList;
ExceptionClass: TClass;
begin
Prov := TFakeOSProvider.Create;
try
// 1
SetLength(Bytes, 3);
Bytes[0] := 0; Bytes[1] := 1; Bytes[2] := 2;
Prov.Clear;
Prov.WriteBytes(Bytes);
Prov.Stream.Position := 0;
SetLength(Bytes, 0);
Prov.ReadBytes(Bytes);
Check(Length(Bytes) = 3);
Check(Bytes[0] = 0); Check(Bytes[1] = 1); Check(Bytes[2] = 2);
// 2
Prov.Clear;
Prov.WriteString(TEncoding.ASCII, '1234567890');
Prov.Stream.Position := 0;
Prov.ReadString(TEncoding.ASCII, S);
Check(S = '1234567890');
// 3
Prov.Clear;
Prov.WriteString(TEncoding.ASCII, '0987654321', 'xyz');
Prov.Stream.Position := 0;
Prov.ReadString(TEncoding.ASCII, S, 'xyz');
Check(S = '0987654321');
// 4
Prov.Clear;
Prov.WriteByte(253);
Prov.Stream.Position := 0;
Prov.ReadByte(B);
Check(B = 253);
// 5
Prov.Clear;
Prov.WriteInteger(1986);
Prov.Stream.Position := 0;
Prov.ReadInteger(Int);
Check(Int = 1986);
// 6
Utf8DataExpected := 'тестовая строка ла-ла-ла';
Utf8Terminator := 'конец*';
Prov.Clear;
Prov.WriteString(TEncoding.UTF8, Utf8DataExpected, Utf8Terminator);
Prov.WriteString(TEncoding.UTF8, 'advanced', '');
Prov.Stream.Position := 0;
Check(Prov.ReadString(TEncoding.UTF8, S, Utf8Terminator));
Check(S = Utf8DataExpected);
CheckFalse(Prov.ReadString(TEncoding.UTF8, S, Utf8Terminator));
// 7
Prov.Clear;
Prov.WriteString(TEncoding.Unicode, 'testxyz_suffix', 'xyz');
Prov.Stream.Position := 0;
Check(Prov.ReadString(TEncoding.Unicode, S, 'xyz'));
Check(S = 'test');
// 8
List := TStringList.Create;
try
Prov.Clear;
Prov.WriteLn('msg1');
Prov.WriteLn('msg2');
Prov.WriteLn('msg3');
for S in Prov.ReadLns do begin
List.Add(S);
end;
Check(List.CommaText = '');
Prov.Stream.Position := 0;
for S in Prov.ReadLns do begin
List.Add(S);
end;
Check(List.CommaText = 'msg1,msg2,msg3');
finally
List.Free;
end;
// 9
Prov.Clear;
S := 'hallo' + Prov.GetEOL;
Bytes := Prov.GetEncoding.GetBytes(S);
for Int := 0 to High(Bytes) do begin
B := Bytes[Int];
Prov.WriteByte(B);
Prov.Stream.Position := Prov.Stream.Position - 1;
try
Tmp := Prov.ReadLn;
except
Tmp := '';
end;
if Int < High(Bytes) then
Check(Tmp = '')
else
Check(Tmp = 'hallo');
end;
Ps := Prov.Stream.Position;
Prov.WriteLn('world');
Prov.Stream.Position := Ps;
S := Prov.ReadLn;
Check(S = 'world');
Check(Prov.Stream.Position = Prov.Stream.Size);
// 10
Prov.Clear;
Prov.WriteLn('Delphi <a href="tdlite.exe">download</a> ');
Prov.Stream.Position := 0;
Check(Prov.ReadRegEx('href="(.*?)"', S));
// 11
List := TStringList.Create;
try
Prov.Clear;
Prov.WriteLn('<msg1> trash...');
Prov.WriteLn('<msg2> lololo');
Prov.WriteLn('<msg3 bla-bla-bla');
Prov.Stream.Position := 0;
for S in Prov.ReadRegEx('<.*>') do
List.Add(S);
Check(List.CommaText = '<msg1>,<msg2>');
finally
List.Free;
end;
// 12
Prov.Clear;
Prov.WriteLn('1');
Prov.WriteLn('');
Prov.WriteLn('');
Prov.Stream.Position := 0;
S := Prov.ReadLn;
Check(S = '1');
S := Prov.ReadLn;
Check(S = '');
S := Prov.ReadLn;
Check(S = '');
ExceptionClass := nil;
try
Prov.ReadLn;
except
on E: TAioProvider.AEOF do begin
ExceptionClass := TAioProvider.AEOF
end;
end;
Check(ExceptionClass = TAioProvider.AEOF, 'EOF error');
finally
Prov.Free
end;
end;
procedure TAioTests.RandomPosWrite(const A: array of const);
var
F: IAioFile;
FileName, Chunk: AnsiString;
begin
FileName := A[0].AsAnsiString;
Chunk := A[1].AsAnsiString;
F := MakeAioFile(string(FileName), fmCreate);
try
F.Write(Pointer(Chunk), Length(Chunk));
F.Write(Pointer(Chunk), Length(Chunk));
F.SetPosition(F.GetPosition - 3);
F.Write(Pointer(Chunk), Length(Chunk));
finally
//F.Free;
end;
end;
procedure TAioTests.AioTCPConDisconn;
const
cTestMsg = 'test message';
var
Server: TGreenlet;
S: IAioTCPSocket;
Str: string;
begin
Server := TGreenlet.Spawn(EchoTCPServRoutine);
S := MakeAioTcpSocket;
S.SetEncoding(TEncoding.ANSI);
Check(S.Connect('localhost', 1986, INFINITE));
S.WriteLn(cTestMsg);
Str := S.ReadLn;
FCliOutput.Add(string(Str));
Check(FServOutput[0] = 'listen');
Check(FServOutput[1] = 'listen');
Check(FCliOutput[0] = cTestMsg);
Check(FCliOutput[1] = cTestMsg);
S.Disconnect;
GreenSleep(100);
Check(FCliOutput.Count >= 3);
Check(FCliOutput[2] = 'cli disconnect');
FServOutput.Clear;
Check(S.Connect('localhost', 1986, 1000));
GreenSleep(100);
Check(FServOutput.Count > 0);
Check(FServOutput[0] = 'listen');
end;
procedure TAioTests.AioTCPConn;
var
Server: TGreenlet;
S: IAioTCPSocket;
begin
Server := TGreenlet.Spawn(EchoTCPServRoutine);
S := MakeAioTcpSocket;
Check(S.Connect('127.0.0.1', 1986, 1000));
// дадим серверному сокету отработать disconnect
GreenSleep(500);
end;
procedure TAioTests.AioTCPConnFalse;
var
Server: TGreenlet;
S: IAioTCPSocket;
begin
Server := TGreenlet.Spawn(EchoTCPServRoutine);
S := MakeAioTcpSocket;
CheckFalse(S.Connect('localhost', 1987, 500));
end;
procedure TAioTests.AioTCPConnFalseNonRoot;
var
G: IRawGreenlet;
begin
G := TGreenlet.Spawn(AioTCPConnFalse);
try
G.Join
finally
end;
end;
procedure TAioTests.AioTCPConnNonRoot;
var
G: IRawGreenlet;
begin
G := TGreenlet.Spawn(AioTCPConn);
try
G.Join
finally
end;
end;
procedure TAioTests.AioTcpConnStress;
const
CLI_COUNT = 50;
STRESS_FACTOR = 100;
var
Clients: TGreenGroup<Integer>;
I: Integer;
begin
for I := 1 to CLI_COUNT do begin
Clients[I] := TSymmetric<string, Integer, Integer>.Spawn(TcpConnect, 'aio.fun', 80, I);
end;
Check(Clients.Join(INFINITE, True), 'Clients.Join');
end;
procedure TAioTests.AioTCPReaderWriter;
var
Server, R, W: IRawGreenlet;
S: IAioTCPSocket;
begin
Server := TGreenlet.Spawn(EchoTCPServRoutine);
S := MakeAioTcpSocket;
S.SetEncoding(TEncoding.ASCII);
R := TGreenlet.Create(TcpReader, [S]);
Check(S.Connect('localhost', 1986, 500), 'connection timeout');
R.Switch;
W := TGreenlet.Create(TcpWriter, [S, 'first', 'second', 'third']);
W.Join;
// дадим ридеру поработать
GreenSleep(300);
CheckEqualsString('first,second,third', FOutput.CommaText);
end;
procedure TAioTests.AioSocksCreateDestroy;
var
TCP: IAioTCPSocket;
UDP: IAioUDPSocket;
begin
TCP := MakeAioTcpSocket;
TCP := nil;
UDP := MakeAioUdpSocket;
UDP := nil;
end;
procedure TAioTests.AioTCPServerRunStop;
var
Server: TGreenlet;
begin
Server := TGreenlet.Spawn(EchoTCPServRoutine);
Join([Server], 100)
end;
procedure TAioTests.AioTCPSocketConnect;
var
Sock: IAioTCPSocket;
A: string;
begin
Sock := MakeAioTcpSocket;
Check(Sock.Connect('uranus.dfpost.ru', 80, 1000), 'connection timeout');
Sock.SetEncoding(TEncoding.ANSI);
Sock.SetEOL(LF);
Sock.WriteLn('GET /');
A := Sock.ReadLn;
Check(Sock.Read(nil, 0) > 0);
Check(A <> '');
end;
procedure TAioTests.AioTCPSocketEvents;
var
C: IAioTCPSocket;
Server, Events: TGreenlet;
begin
C := MakeAioTcpSocket;
Server := TGreenlet.Spawn(EchoTCPServRoutine);
Events := TGreenlet.Spawn(TCPSockEventsRoutine, [C]);
Check(C.Connect('localhost', 1986, 1000));
GreenSleep(100);
Check(FOutput.Count = 1);
Check(FOutput[0] = '0');
FOutput.Clear;
C.Disconnect;
GreenSleep(100);
Check(FOutput.Count > 0);
Check(FOutput[0] = '1');
Check(FCliOutput.Count = 1);
Check(FCliOutput[0] = 'cli disconnect');
end;
procedure TAioTests.AioTcpStress;
const
CLI_COUNT = 50;
STRESS_FACTOR = 100;
var
Server: IRawGreenlet;
Clients: TGreenGroup<Integer>;
I: Integer;
begin
Server := TSymmetric.Spawn(EchoTCPServRoutine);
for I := 1 to CLI_COUNT do begin
Clients[I] := TSymmetric<Integer, Integer, Integer>.Spawn(TcpStressClient, STRESS_FACTOR, 1986, I);
end;
Check(Clients.Join(INFINITE, True), 'Clients.Join');
end;
procedure TAioTests.AioUdpRoundBobin;
var
S1, S2: IAioUDPSocket;
G1: IRawGreenlet;
Str: string;
begin
S1 := MakeAioUdpSocket;
S1.Bind('0.0.0.0', 1986);
G1 := TGreenlet.Spawn(EchoCliRoutine, [S1]);
S2 := MakeAioUdpSocket;
S2.SetRemoteAddress(TAddress.Create('localhost', 1986));
S2.WriteLn('hallo1');
Str := S2.ReadLn;
CheckEquals('hallo1', Str);
S2.WriteLn('hallo2');
Str := S2.ReadLn;
CheckEquals('hallo2', Str);
end;
procedure TAioTests.CompareAioFileAndStdFStream;
const
cFileName = 'aio_fs_test.txt';
cEtalon1 = 'chunk_chuchunk_';
cEtalon2_1 = '0_1_2_3_4_5_6_7_8_9';
cEtalon2_2 = '0_1x2_x_4x5_x_7x8_x';
cEtalon3_1 = '123456789';
cEtalon3_2 = '6789';
cTestSequence = '123456789';
var
Test: AnsiString;
S: TStream;
AioFile: IAioFile;
I: Integer;
begin
FAioList := TList<string>.Create;
FFSList := TList<string>.Create;
try
// test 1
RunAsync(RandomPosWrite, [cFileName, 'chunk_']);
Test := ReadAStrFromFile(cFileName);
Check(Test = cEtalon1, 'test 1 problem');
// test 2
WriteAToFile(cFileName, cEtalon2_1);
RunAsync(SeekAndWrite, [cFileName]);
Test := ReadAStrFromFile(cFileName);
Check(Test = cEtalon2_2, 'test 2 problem');
// test 3
WriteAToFile(cFileName, cEtalon3_1);
RunAsync(SeekAndRead, [cFileName, 5]);
Check(FReadData = cEtalon3_2);
Check(FDataSz = 4);
// big megatest
S := TFileStream.Create(cFileName, fmCreate);
RunAsync(ReadWriteByStream, [S, FFSList, cTestSequence]);
S.Free;
AioFile := MakeAioFile(cFileName, fmCreate);
S := AioFile.AsStream;
RunAsync(ReadWriteByStream, [S, FAioList, cTestSequence]);
AioFile := nil;
Check(FFSList.Count = FAioList.Count);
for I := 0 to FFSList.Count-1 do begin
Check(FFSList[I] = FAioList[I], Format('megacheck error on %d iteration', [I]));
end
finally
DeleteFile(cFileName);
FAioList.Free;
FFSList.Free;
end;
end;
procedure TAioTests.Console;
var
Console: IAioConsole;
begin
Console := MakeAioConsole;
Check(Console.StdIn <> nil);
Check(Console.StdOut <> nil);
Check(Console.StdError <> nil);
end;
procedure TAioTests.ConsoleApp;
var
App: IAioConsoleApplication;
Str: string;
Cnt: Integer;
Encoding: TEncoding;
begin
Encoding := TEncoding.ANSI.GetEncoding(866);
try
App := MakeAioConsoleApp('cmd', []);
App.SetEncoding(Encoding);
for Str in App.StdOut.ReadLns([CRLF, '>']) do begin
if Str = '' then
Break;
FOutput.Add(Str)
end;
Check(FOutput.Count > 0);
FOutput.Clear;
App.StdIn.WriteLn('help');
Cnt := 0;
for Str in App.StdOut.ReadLns do begin
FOutput.Add(Str);
Inc(Cnt);
if Cnt > 5 then
Break;
end;
Check(FOutput.Count > 0);
App.Terminate(-123);
Check(App.GetExitCode = -123)
finally
Encoding.Free
end;
end;
procedure TAioTests.CreateAioFile;
const
cFileName = 'AioCreateTest.txt';
var
F: IAioFile;
FS: TFileStream;
begin
DeleteFile(cFileName);
F := MakeAioFile(cFileName, fmCreate);
Check(FileExists(cFileName));
F := nil;
FS := TFileStream.Create(cFileName, fmOpenRead);
try
Check(FS.Size = 0)
finally
FS.Free;
end;
try
Check(FileExists(cFileName));
finally
DeleteFile(cFileName)
end;
end;
procedure TAioTests.CreateNamedPipe;
var
Pipe: IAioNamedPipe;
begin
Pipe := MakeAioNamedPipe('test');
Pipe.SetEncoding(TEncoding.ANSI);
Pipe.MakeServer;
TSymmetric<string>.Spawn(NamedPipeEchoClient, 'test');
Pipe.WaitConnection;
Pipe.WriteLn('hallo');
GreenSleep(100);
Check(FCliOutput.CommaText = 'hallo');
end;
procedure TAioTests.EchoCliRoutine(const A: array of const);
var
Sock: IAioProvider;
Msg: string;
begin
Sock := A[0].AsInterface as IAioProvider;
Sock.SetEncoding(TEncoding.ASCII);
try
while Sock.ReadLn(Msg) do begin
FCliOutput.Add(Msg);
Sock.WriteLn(Msg);
end;
finally
FCliOutput.Add('cli disconnect')
end;
end;
procedure TAioTests.EchoTCPServRoutine;
var
S, C: IAioTCPSocket;
Clients: TGreenGroup<Integer>;
begin
S := MakeAioTcpSocket;
S.Bind('localhost', 1986);
while True do begin
FServOutput.Add('listen');
S.Listen;
C := S.Accept;
Clients[Clients.Count] := TGreenlet.Spawn(EchoCliRoutine, [C])
end;
end;
procedure TAioTests.WriteAioFile;
const
cChars: AnsiString = 'test_data_for_write_';
var
F: IAioFile;
G: IRawGreenlet;
FName: string;
Rand: Int64;
Enthropy: Double;
I, Iter, Sz: Integer;
vReadData, TestData: AnsiString;
FS: TFileStream;
begin
SetLength(TestData, 1024*100);
Iter := 0;
for I := 1 to High(TestData) do begin
TestData[I] := cChars[Iter+1];
Iter := (Iter + 1) mod Length(cChars);
end;
Enthropy := Now;
Move(Enthropy, Rand, SizeOf(Rand));
FName := Format('TestWriteFile%d.txt', [Rand and $FFFF]);
F := MakeAioFile(FName, fmCreate);
G := TGreenlet.Spawn(GWriteFile, [F, TestData]);
try
G.Join
finally
F := nil
end;
FS := TFileStream.Create(FName, fmOpenRead);
try
SetLength(vReadData, Length(TestData));
FS.Seek(0, soFromBeginning);
Sz := FS.Read(Pointer(vReadData)^, Length(vReadData));
Check(Sz = Length(TestData));
Check(vReadData = TestData, 'write test data broked after read');
Check(FDataSz = Length(TestData), 'Returned datasize problems');
finally
FS.Free;
DeleteFile(PChar(FName));
end;
end;
procedure TAioTests.WriteAToFile(const FName: string; const S: AnsiString);
var
FS: TFileStream;
begin
FS := TFileStream.Create(FName, fmCreate);
try
FS.Write(Pointer(S)^, Length(S));
finally
FS.Free;
end;
end;
procedure TAioTests.WriteComp(const A: array of const);
var
S: TStream;
Comp: TComponent;
begin
S := TStream(A[0].AsObject);
Comp := TComponent(A[1].AsObject);
S.WriteComponent(Comp)
end;
procedure TAioTests.WriteThreaded(const S: IAioTcpSocket; const Data: TStrings; const SendTimeout: Integer);
var
I: Integer;
begin
BeginThread;
for I := 0 to Data.Count-1 do begin
S.WriteLn(Data[I]);
GreenSleep(SendTimeout);
end;
EndThread;
end;
procedure TAioTests.GReadFile(const A: array of const);
var
F: IAioFile;
Sz: Integer;
begin
F := A[0].AsInterface as IAioFile;
Sz := A[1].AsInteger;
SetLength(FReadData, Sz);
FDataSz := F.Read(Pointer(FReadData), Sz);
end;
procedure TAioTests.GWriteFile(const A: array of const);
var
F: IAioFile;
S: AnsiString;
begin
F := A[0].AsInterface as IAioFile;
S := AnsiString(A[1].AsAnsiString);
FDataSz := F.Write(Pointer(S), Length(S));
end;
procedure TAioTests.MBCSEncMemLeak;
var
Prov: TFakeOSProvider;
Encoding: TEncoding;
begin
Encoding := TEncoding.ANSI.GetEncoding(1201);
try
Prov := TFakeOSProvider.Create;
try
Prov.SetEncoding(Encoding);
Prov.WriteLn('message1');
Prov.WriteLn('message2');
Prov.Stream.Position := 0;
CheckEquals('message1', Prov.ReadLn);
CheckEquals('message2', Prov.ReadLn);
finally
Prov.Free
end;
finally
Encoding.Free
end;
end;
procedure TAioTests.NamedPipeEchoClient(const PipeName: string);
var
Pipe: IAioNamedPipe;
Msg: string;
begin
GreenSleep(100);
Pipe := MakeAioNamedPipe(PipeName);
Pipe.SetEncoding(TEncoding.ANSI);
try
Pipe.Open;
while Pipe.ReadLn(Msg) do begin
FCliOutput.Add(Msg);
Pipe.WriteLn(Msg);
end;
finally
FCliOutput.Add('cli disconnect')
end;
end;
procedure TAioTests.NamedPipePingPong;
const
PIPE_NAME = 'test_server';
var
Pipe: IAioNamedPipe;
Msg: string;
begin
Pipe := MakeAioNamedPipe(PIPE_NAME);
Pipe.SetEncoding(TEncoding.ANSI);
Pipe.MakeServer;
TSymmetric<string>.Spawn(NamedPipeEchoClient, PIPE_NAME);
Pipe.WaitConnection;
Pipe.WriteLn('message1');
Check(Pipe.ReadLn(Msg));
Check(Msg = 'message1');
Pipe.WriteLn('message2');
Check(Pipe.ReadLn(Msg));
Check(Msg = 'message2');
Pipe.WriteLn('message3');
Check(Pipe.ReadLn(Msg));
Check(Msg = 'message3');
end;
procedure TAioTests.ReadAioFile;
var
Rand: Int64;
Enthropy: Double;
FName: string;
F: IAioFile;
G: IRawGreenlet;
TestData: AnsiString;
FS: TFileStream;
begin
Enthropy := Now;
Move(Enthropy, Rand, SizeOf(Rand));
FName := Format('TestReadFile%d.txt', [Rand and $FFFF]);
TestData := 'test_read_data_';
FS := TFileStream.Create(FName, fmCreate);
with FS do try
Write(Pointer(TestData)^, Length(TestData));
finally
Free;
end;
F := MakeAioFile(FName, fmOpenRead);
G := TGreenlet.Spawn(GReadFile, [F, Length(TestData)]);
try
G.Join;
Check(FReadData = TestData, 'Test data broked on reading');
Check(FDataSz = Length(TestData), 'Returned datasize problems');
finally
F := nil;
DeleteFile(PChar(FName));
end;
end;
function TAioTests.ReadAStrFromFile(const FName: string): AnsiString;
var
FS: TFileStream;
begin
FS := TFileStream.Create(FName, fmOpenRead);
try
SetLength(Result, FS.Seek(0, soFromEnd));
FS.Position := 0;
FS.Read(Pointer(Result)^, Length(Result));
finally
FS.Free;
end;
end;
procedure TAioTests.ReadComp(const A: array of const);
var
S: TStream;
Comp: TComponent;
begin
S := TStream(A[0].AsObject);
Comp := TComponent(A[1].AsObject);
S.ReadComponent(Comp)
end;
procedure TAioTests.ReadThreaded(const S: IAioTcpSocket; const Log: tArrayOfString);
var
Msg: string;
Cnt: Integer;
begin
BeginThread;
Cnt := 0;
while S.ReadLn(Msg) do begin
//Log.Add(Msg);
Log[Cnt] := Msg;
Inc(Cnt);
end;
EndThread;
end;
procedure TAioTests.ReadWriteByStream(const A: array of const);
var
Stream: TStream;
List: TList<string>;
Chunk, Readed: AnsiString;
procedure ReadAndAddToList;
var
ReadLen: Integer;
begin
ReadLen := Stream.Read(Pointer(Readed)^, Length(Readed));
List.Add(Copy(string(Readed), 1, ReadLen));
end;
begin
Stream := TStream(A[0].AsObject);
List := TList<string>(A[1].AsObject);
Chunk := A[2].AsAnsiString;
SetLength(Readed, Length(Chunk)*10);
Stream.Write(Pointer(Chunk)^, Length(Chunk));
Stream.Write(Pointer(Chunk)^, Length(Chunk));
Stream.Seek(Length(Chunk) div 2 + 1, soFromBeginning);
// 1
ReadAndAddToList;
Stream.Seek(-(Length(Chunk) div 3), soFromCurrent);
// 2
ReadAndAddToList;
Stream.Write(Pointer(Chunk)^, Length(Chunk));
Stream.Position := 3;
// 3
ReadAndAddToList;
Stream.Seek(-5, soFromCurrent);
// 4
ReadAndAddToList;
Stream.Seek(5, soFromEnd);
// 5
ReadAndAddToList;
Stream.Seek(-5, soFromEnd);
// 6
ReadAndAddToList;
Stream.Position := Length(Chunk) div 2;
// 7
ReadAndAddToList;
Stream.Position := -1000;
// 8
ReadAndAddToList;
//9
Stream.Position := 1000;
ReadAndAddToList;
//10
Stream.Seek(-1000, soFromCurrent);
ReadAndAddToList;
//10
Stream.Seek(1000, soFromCurrent);
ReadAndAddToList;
//11
Stream.Seek(1000, soFromBeginning);
ReadAndAddToList;
//12
Stream.Seek(1, soFromBeginning);
ReadAndAddToList;
//13
Stream.Seek(100, soFromEnd);
ReadAndAddToList;
//14
Stream.Seek(-100, soFromEnd);
ReadAndAddToList;
//15
Stream.Seek(2, soFromBeginning);
Stream.Seek(3, soFromCurrent);
Stream.Seek(-1, soFromCurrent);
Stream.Seek(10, soFromCurrent);
ReadAndAddToList;
end;
procedure TAioTests.ReadWriteComponent;
const
cTestFile = 'read_write_comp.bin';
var
F: IAioFile;
FS: TFileStream;
Etalon, Test: TTestData;
I: Integer;
Arr: TBytes;
FileSz: Integer;
begin
Etalon := TTestData.Create(nil);
Etalon.X := 123;
Etalon.Y := 432.654;
Etalon.Z := 'test_string';
SetLength(Arr, 100);
for I := 0 to High(Arr) do
Arr[I] := I;
Etalon.Arr := Arr;
try
// read component
FS := TFileStream.Create(cTestFile, fmCreate);
try
FS.WriteComponent(Etalon);
FileSz := FS.Size;
finally
FS.Free;
end;
F := MakeAioFile(cTestFile, fmOpenRead);
Test := TTestData.Create(nil);
try
F.AsStream.ReadComponent(Test);
Check(F.AsStream.Size = FileSz, 'filesize');
F.Seek(0, soBeginning);
RunAsync(ReadComp, [F.AsStream, Test]);
finally
F := nil
end;
try
Check(Test.IsEqual(Etalon), 'reading component problems');
finally
Test.Free;
end;
// write component
F := MakeAioFile(cTestFile, fmCreate);
try
RunAsync(WriteComp, [F.AsStream, Etalon]);
F.AsStream.WriteComponent(Etalon);
finally
F := nil
end;
Test := TTestData.Create(nil);
FS := TFileStream.Create(cTestFile, fmOpenRead);
try
FS.ReadComponent(Test);
finally
FS.Free;
end;
try
Check(Test.IsEqual(Etalon), 'writing component problems')
finally
Test.Free
end;
finally
Etalon.Free;
DeleteFile(cTestFile)
end;
end;
procedure TAioTests.ReadWriteMultithreaded;
const
SND_TIMEOUT = 300;
var
Server: TGreenlet;
Sock: IAioTCPSocket;
Reader: TSymmetric<IAioTcpSocket, tArrayOfString>;
Writer: TSymmetric<IAioTcpSocket, TStrings, Integer>;
Data, Tmp: TStrings;
Log: tArrayOfString;
I: Integer;
begin
Data := TStringList.Create;
Tmp := TStringList.Create;
Sock := MakeAioTcpSocket;
try
Server := TGreenlet.Spawn(EchoTCPServRoutine);
Check(Sock.Connect('localhost', 1986, 1000));
for I := 1 to 3 do
Data.Add(Format('message%d', [I]));
SetLength(Log, Data.Count);
Reader := TSymmetric<IAioTcpSocket, tArrayOfString>.Spawn(ReadThreaded, Sock, Log);
Writer := TSymmetric<IAioTcpSocket, TStrings, Integer>.Spawn(WriteThreaded, Sock, Data, SND_TIMEOUT);
Join([Server, Reader, Writer], SND_TIMEOUT * Data.Count * 2);
for I := 0 to High(Log) do
Tmp.Add(Log[I]);
CheckEquals(Data.CommaText, Tmp.CommaText);
finally
Data.Free;
Tmp.Free;
end;
end;
procedure TAioTests.RunAsync(const Routine: TSymmetricArgsRoutine;
const A: array of const);
var
G: IRawGreenlet;
begin
G := TGreenlet.Spawn(Routine, A);
try
G.Join
finally
end;
end;
procedure TAioTests.SeekAndRead(const A: array of const);
var
F: IAioFile;
SeekPos: Integer;
begin
F := MakeAioFile(A[0].AsString, fmOpenReadWrite);
SeekPos := A[1].AsInteger;
SetLength(FReadData, F.Seek(0, soEnd) - SeekPos + 1);
F.Seek(SeekPos, soBeginning);
FDataSz := F.Read(Pointer(FReadData), Length(FReadData))
end;
procedure TAioTests.SeekAndWrite(const A: array of const);
var
F: IAioFile;
CurPos, Sz: Int64;
begin
F := MakeAioFile(A[0].AsString, fmOpenReadWrite);
F.Seek(0, soEnd);
Sz := F.GetPosition+1;
F.Seek(0, soBeginning);
CurPos := 3;
F.SetPosition(CurPos);
while F.GetPosition < Sz do begin
F.WriteString(TEncoding.ANSI, 'x', '');
F.SetPosition(F.GetPosition + 2)
end;
end;
procedure TAioTests.SetUp;
begin
inherited;
JoinAll(0);
FCliOutput := TStringList.Create;
FServOutput := TStringList.Create;
FOutput := TStringList.Create;
{$IFDEF DEBUG}
GreenletCounter := 0;
GeventCounter := 0;
IOEventTupleCounter := 0;
IOFdTupleCounter := 0;
IOTimeTupleCounter := 0;
{$ENDIF}
end;
procedure TAioTests.SoundCard;
var
SC: IAioSoundCard;
Buffer: array of SmallInt;
Readed, Writed, I: LongWord;
NonZero: Boolean;
begin
SC := MakeAioSoundCard(16000);
SetLength(Buffer, 16000);
Readed := SC.Read(@Buffer[0], Length(Buffer)*SizeOf(SmallInt));
Check(Readed = 16000*SizeOf(SmallInt));
NonZero := False;
for I := 0 to High(Buffer) do
if Buffer[I] <> 0 then begin
NonZero := True;
Break;
end;
Writed := SC.Write(@Buffer[0], Readed);
CheckEquals(Readed, Writed);
end;
procedure TAioTests.TcpConnect(const Address: string; const Port: Integer; const Index: Integer);
var
Sock: IAioTcpSocket;
begin
Sock := MakeAioTcpSocket;
Check(Sock.Connect(Address, Port, 1000), 'conn timeout Index = ' + IntToStr(Index));
end;
procedure TAioTests.TcpReader(const A: array of const);
var
S: IAioTCPSocket;
Str: string;
begin
S := A[0].AsInterface as IAioTcpSocket;
while S.ReadLn(Str) do begin
FOutput.Add(Str)
end;
end;
procedure TAioTests.TCPSockEventsRoutine(const A: array of const);
var
S: IAioTCPSocket;
Index: Integer;
begin
S := A[0].AsInterface as IAioTcpSocket;
while True do begin
if S.OnDisconnect.WaitFor(0) = wrSignaled then
Select([S.OnConnect], Index)
else
Select([S.OnConnect, S.OnDisconnect], Index);
FOutput.Add(IntToStr(Index))
end;
end;
procedure TAioTests.TcpStressClient(const Count: Integer;
const Port: Integer; const Index: Integer);
var
Actual, Expected: string;
I: Integer;
Sock: IAioTcpSocket;
begin
Sock := MakeAioTcpSocket;
Check(Sock.Connect('localhost', Port, 1000), 'conn timeout for ' + IntToStr(Index));
{$IFDEF DEBUG}
DebugString(Format('Connected socket[%d]', [Index]));
{$ENDIF}
for I := 1 to Count do begin
Expected := Format('message[%d][%d]', [Index, I]);
Sock.WriteLn(Expected);
Actual := Sock.ReadLn;
CheckEquals(Expected, Actual);
end;
end;
procedure TAioTests.TcpWriter(const A: array of const);
var
S: IAioTCPSocket;
I: Integer;
begin
S := A[0].AsInterface as IAioTcpSocket;
for I := 1 to High(A) do
S.WriteString(TEncoding.ANSI, A[I].AsString);
end;
procedure TAioTests.TearDown;
begin
inherited;
FCliOutput.Free;
FServOutput.Free;
FOutput.Free;
{$IFDEF DEBUG}
// некоторые тесты привоят к вызову DoSomethingLater
DefHub.Serve(0);
Check(GreenletCounter = 0, 'GreenletCore.RefCount problems');
Check(GeventCounter = 0, 'Gevent.RefCount problems');
JoinAll;
Check(IOEventTupleCounter = 0, 'IOEventTupleCounter problems');
Check(IOFdTupleCounter = 0, 'IOFdTupleCounter problems');
Check(IOTimeTupleCounter = 0, 'IOTimeTupleCounter problems');
{$ENDIF}
end;
{ TTestData }
procedure TTestData.DefineProperties(Filer: TFiler);
begin
inherited;
Filer.DefineBinaryProperty('StreamProps', ReadStreamParams,
WriteStreamParams, True);
end;
function TTestData.IsEqual(Other: TTestData): Boolean;
var
I: Integer;
begin
Result := (Self.FX = Other.FX) and (Self.FY = Other.FY)
and (Self.FZ = Other.FZ) and (Length(Self.FArr) = Length(Other.FArr));
if Result then begin
for I := 0 to High(Self.FArr) do
if Self.FArr[I] <> Other.FArr[I] then
Exit(False);
end;
end;
procedure TTestData.ReadStreamParams(Stream: TStream);
var
Sz: Integer;
begin
Stream.Read(Sz, SizeOf(Sz));
SetLength(FArr, Sz);
Stream.Read(FArr[0], Sz);
end;
procedure TTestData.WriteStreamParams(Stream: TStream);
var
Sz: Integer;
begin
Sz := Length(FArr);
Stream.Write(Sz, SizeOf(Sz));
Stream.Write(FArr[0], Sz)
end;
{ TFakeOSProvider }
procedure TFakeOSProvider.Clear;
begin
FStream.Clear;
SetLength(FInternalBuf, 0);
end;
constructor TFakeOSProvider.Create;
begin
inherited;
FStream := TMemoryStream.Create
end;
destructor TFakeOSProvider.Destroy;
begin
FStream.Free;
inherited;
end;
function TFakeOSProvider.Read(Buf: Pointer; Len: Integer): LongWord;
begin
if Len = 0 then
Exit(FStream.Size);
Result := FStream.Read(Buf^, Abs(Len));
end;
function TFakeOSProvider.Write(Buf: Pointer; Len: Integer): LongWord;
begin
Result := FStream.Write(Buf^, Len);
end;
initialization
RegisterTest('AioTests', TAioTests.Suite);
end.
|
unit TestUnit2;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.SysUtils, Vcl.Graphics, Vcl.StdCtrls, Winapi.Windows,
System.Variants, Vcl.Dialogs, Unit2, Vcl.Controls, Vcl.Forms, Winapi.Messages,
System.Classes;
type
// Test methods for class TForm2
TestTForm2 = class(TTestCase)
strict private
FForm2: TForm2;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestisPrimo;
procedure TestisMultiplo;
procedure Testmedia;
procedure TestreverterString;
end;
implementation
procedure TestTForm2.SetUp;
begin
FForm2 := TForm2.Create(nil);
end;
procedure TestTForm2.TearDown;
begin
FForm2.Free;
FForm2 := nil;
end;
procedure TestTForm2.TestisPrimo;
var
ReturnValue: Boolean;
valor: Integer;
begin
// TODO: Setup method call parameters
valor := 1;
ReturnValue := FForm2.isPrimo(valor);
// TODO: Validate method results
CheckEquals(false,ReturnValue);
end;
procedure TestTForm2.Testmedia;
var
ReturnValue: double;
a,b,c:double;
begin
a := 2;
b := 2;
c := 2;
ReturnValue := FForm2.media(a,b,c);
CheckEquals(2,ReturnValue);
end;
procedure TestTForm2.TestreverterString;
var
ReturnValue: string;
s:string;
begin
s := 'ovo';
ReturnValue := FForm2.reverterString(s);
CheckEquals('ovo',ReturnValue);
end;
procedure TestTForm2.TestisMultiplo;
var
ReturnValue: Boolean;
y: Integer;
x: Integer;
begin
// TODO: Setup method call parameters
ReturnValue := FForm2.isMultiplo(x, y);
// TODO: Validate method results
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTForm2.Suite);
end.
|
unit NtUtils.Lsa.Security;
interface
uses
Winapi.WinNt, Winapi.ntlsa, NtUtils.Exceptions, NtUtils.Security.Acl,
NtUtils.Security.Sid;
type
TAce = NtUtils.Security.Acl.TAce;
IAcl = NtUtils.Security.Acl.IAcl;
TAcl = NtUtils.Security.Acl.TAcl;
ISid = NtUtils.Security.Sid.ISid;
{ Query security }
// Security descriptor (free with LsaFreeMemory)
function LsaxQuerySecurityObject(LsaHandle: TLsaHandle; SecurityInformation:
TSecurityInformation; out SecDesc: PSecurityDescriptor): TNtxStatus;
// Owner
function LsaxQueryOwnerObject(LsaHandle: TLsaHandle; out Owner: ISid):
TNtxStatus;
// Primary group
function LsaxQueryPrimaryGroupObject(LsaHandle: TLsaHandle;
out PrimaryGroup: ISid): TNtxStatus;
// DACL
function LsaxQueryDaclObject(LsaHandle: TLsaHandle; out Dacl: IAcl): TNtxStatus;
// SACL
function LsaxQuerySaclObject(LsaHandle: TLsaHandle; out Sacl: IAcl): TNtxStatus;
// Mandatory label
function LsaxQueryLabelObject(LsaHandle: TLsaHandle; out Sacl: IAcl):
TNtxStatus;
{ Set security }
// Security descriptor
function LsaxSetSecurityObject(LsaHandle: TLsaHandle; SecInfo:
TSecurityInformation; const SecDesc: TSecurityDescriptor): TNtxStatus;
// Owner
function LsaxSetOwnerObject(LsaHandle: TLsaHandle; Owner: ISid): TNtxStatus;
// Primary group
function LsaxSetPrimaryGroupObject(LsaHandle: TLsaHandle; Group: ISid):
TNtxStatus;
// DACL
function LsaxSetDaclObject(LsaHandle: TLsaHandle; Dacl: IAcl): TNtxStatus;
// SACL
function LsaxSetSaclObject(LsaHandle: TLsaHandle; Sacl: IAcl): TNtxStatus;
// Mandatory label
function LsaxSetLabelObject(LsaHandle: TLsaHandle; Sacl: IAcl): TNtxStatus;
implementation
uses
Ntapi.ntrtl;
{ Query security }
function LsaxQuerySecurityObject(LsaHandle: TLsaHandle; SecurityInformation:
TSecurityInformation; out SecDesc: PSecurityDescriptor): TNtxStatus;
begin
Result.Location := 'LsaQuerySecurityObject';
Result.LastCall.Expects(RtlxComputeReadAccess(SecurityInformation),
@NonSpecificAccessType);
Result.Status := LsaQuerySecurityObject(LsaHandle, SecurityInformation,
SecDesc);
end;
// Owner
function LsaxQueryOwnerObject(LsaHandle: TLsaHandle; out Owner: ISid):
TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := LsaxQuerySecurityObject(LsaHandle, OWNER_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetOwnerSD(pSD, Owner);
LsaFreeMemory(pSD);
end;
// Primary group
function LsaxQueryPrimaryGroupObject(LsaHandle: TLsaHandle;
out PrimaryGroup: ISid): TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := LsaxQuerySecurityObject(LsaHandle, GROUP_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetPrimaryGroupSD(pSD, PrimaryGroup);
LsaFreeMemory(pSD);
end;
// DACL
function LsaxQueryDaclObject(LsaHandle: TLsaHandle; out Dacl: IAcl): TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := LsaxQuerySecurityObject(LsaHandle, DACL_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetDaclSD(pSD, Dacl);
LsaFreeMemory(pSD);
end;
// SACL
function LsaxQuerySaclObject(LsaHandle: TLsaHandle; out Sacl: IAcl): TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := LsaxQuerySecurityObject(LsaHandle, SACL_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetSaclSD(pSD, Sacl);
LsaFreeMemory(pSD);
end;
// Mandatory label
function LsaxQueryLabelObject(LsaHandle: TLsaHandle; out Sacl: IAcl):
TNtxStatus;
var
pSD: PSecurityDescriptor;
begin
Result := LsaxQuerySecurityObject(LsaHandle, LABEL_SECURITY_INFORMATION, pSD);
if not Result.IsSuccess then
Exit;
Result := RtlxGetSaclSD(pSD, Sacl);
LsaFreeMemory(pSD);
end;
{ Set security }
function LsaxSetSecurityObject(LsaHandle: TLsaHandle; SecInfo:
TSecurityInformation; const SecDesc: TSecurityDescriptor): TNtxStatus;
begin
Result.Location := 'LsaSetSecurityObject';
Result.LastCall.Expects(RtlxComputeWriteAccess(SecInfo),
@NonSpecificAccessType);
Result.Status := LsaSetSecurityObject(LsaHandle, SecInfo, SecDesc);
end;
// Owner
function LsaxSetOwnerObject(LsaHandle: TLsaHandle; Owner: ISid): TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPrepareOwnerSD(SD, Owner);
if Result.IsSuccess then
Result := LsaxSetSecurityObject(LsaHandle, OWNER_SECURITY_INFORMATION, SD);
end;
// Primary group
function LsaxSetPrimaryGroupObject(LsaHandle: TLsaHandle; Group: ISid):
TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPreparePrimaryGroupSD(SD, Group);
if Result.IsSuccess then
Result := LsaxSetSecurityObject(LsaHandle, GROUP_SECURITY_INFORMATION, SD);
end;
// DACL
function LsaxSetDaclObject(LsaHandle: TLsaHandle; Dacl: IAcl): TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPrepareDaclSD(SD, Dacl);
if Result.IsSuccess then
Result := LsaxSetSecurityObject(LsaHandle, DACL_SECURITY_INFORMATION, SD);
end;
// SACL
function LsaxSetSaclObject(LsaHandle: TLsaHandle; Sacl: IAcl): TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPrepareSaclSD(SD, Sacl);
if Result.IsSuccess then
Result := LsaxSetSecurityObject(LsaHandle, SACL_SECURITY_INFORMATION, SD);
end;
// Mandatory label
function LsaxSetLabelObject(LsaHandle: TLsaHandle; Sacl: IAcl): TNtxStatus;
var
SD: TSecurityDescriptor;
begin
Result := RtlxPrepareSaclSD(SD, Sacl);
if Result.IsSuccess then
Result := LsaxSetSecurityObject(LsaHandle, LABEL_SECURITY_INFORMATION, SD);
end;
end.
|
unit NtUtils.Lsa.Logon;
interface
uses
Winapi.WinNt, Winapi.ntsecapi, NtUtils.Exceptions, NtUtils.Security.Sid,
DelphiUtils.Strings;
const
LogonFlags: array [0..18] of TFlagName = (
(Value: LOGON_GUEST; Name: 'Guest'),
(Value: LOGON_NOENCRYPTION; Name: 'No Encryption'),
(Value: LOGON_CACHED_ACCOUNT; Name: 'Cached Account'),
(Value: LOGON_USED_LM_PASSWORD; Name: 'Used LM Password'),
(Value: LOGON_EXTRA_SIDS; Name: 'Extra SIDs'),
(Value: LOGON_SUBAUTH_SESSION_KEY; Name: 'Subauth Session Key'),
(Value: LOGON_SERVER_TRUST_ACCOUNT; Name: 'Server Trust Account'),
(Value: LOGON_NTLMV2_ENABLED; Name: 'NTLMv2 Enabled'),
(Value: LOGON_RESOURCE_GROUPS; Name: 'Resource Groups'),
(Value: LOGON_PROFILE_PATH_RETURNED; Name: 'Profile Path Returned'),
(Value: LOGON_NT_V2; Name: 'NTv2'),
(Value: LOGON_LM_V2; Name: 'LMv2'),
(Value: LOGON_NTLM_V2; Name: 'NTLMv2'),
(Value: LOGON_OPTIMIZED; Name: 'Optimized'),
(Value: LOGON_WINLOGON; Name: 'Winlogon'),
(Value: LOGON_PKINIT; Name: 'PKINIT'),
(Value: LOGON_NO_OPTIMIZED; Name: 'Not Optimized'),
(Value: LOGON_NO_ELEVATION; Name: 'No Elevation'),
(Value: LOGON_MANAGED_SERVICE; Name: 'Managed Service')
);
type
TLogonDataClass = (lsLogonId, lsSecurityIdentifier, lsUserName, lsLogonDomain,
lsAuthPackage, lsLogonType, lsSession, lsLogonTime, lsLogonServer,
lsDnsDomainName, lsUpn, lsUserFlags, lsLastSuccessfulLogon,
lsLastFailedLogon, lsFailedAttemptSinceSuccess, lsLogonScript,
lsProfilePath, lsHomeDirectory, lsHomeDirectoryDrive, lsLogoffTime,
lsKickOffTime, lsPasswordLastSet, lsPasswordCanChange, lsPasswordMustChange
);
ILogonSession = interface
function LogonId: TLuid;
function RawData: PSecurityLogonSessionData;
function User: ISid;
function QueryString(InfoClass: TLogonDataClass): String;
end;
// Enumerate logon sessions
function LsaxEnumerateLogonSessions(out Luids: TArray<TLuid>): TNtxStatus;
// Query logon session information; always returns LogonSession parameter
function LsaxQueryLogonSession(LogonId: TLuid; out LogonSession: ILogonSession):
TNtxStatus;
implementation
uses
NtUtils.Processes, NtUtils.Strings, System.SysUtils, NtUtils.Lsa.Sid;
type
TLogonSession = class(TInterfacedObject, ILogonSession)
private
FLuid: TLuid;
FSid: ISid;
Data: PSecurityLogonSessionData;
public
constructor Create(Id: TLuid; Buffer: PSecurityLogonSessionData);
function LogonId: TLuid;
function RawData: PSecurityLogonSessionData;
function User: ISid;
function QueryString(InfoClass: TLogonDataClass): String;
destructor Destroy; override;
end;
{ TLogonSession }
constructor TLogonSession.Create(Id: TLuid; Buffer: PSecurityLogonSessionData);
begin
FLuid := Id;
Data := Buffer;
// Construct well known SIDs
if not Assigned(Data) then
case FLuid of
SYSTEM_LUID:
FSid := TSid.CreateNew(SECURITY_NT_AUTHORITY, 1,
SECURITY_LOCAL_SYSTEM_RID);
ANONYMOUS_LOGON_LUID:
FSid := TSid.CreateNew(SECURITY_NT_AUTHORITY, 1,
SECURITY_ANONYMOUS_LOGON_RID);
LOCALSERVICE_LUID:
FSid := TSid.CreateNew(SECURITY_NT_AUTHORITY, 1,
SECURITY_LOCAL_SERVICE_RID);
NETWORKSERVICE_LUID:
FSid := TSid.CreateNew(SECURITY_NT_AUTHORITY, 1,
SECURITY_NETWORK_SERVICE_RID);
end
else if not RtlxCaptureCopySid(Data.Sid, FSid).IsSuccess then
FSid := nil;
end;
destructor TLogonSession.Destroy;
begin
if Assigned(Data) then
LsaFreeReturnBuffer(Data);
inherited;
end;
function TLogonSession.LogonId: TLuid;
begin
Result := FLuid;
end;
function TLogonSession.QueryString(InfoClass: TLogonDataClass): String;
begin
Result := 'Unknown';
// Only a few data classes are available when the query failed
case InfoClass of
lsLogonId:
Result := IntToHexEx(FLuid);
lsSecurityIdentifier:
if Assigned(FSid) then
Result := LsaxSidToString(FSid.Sid)
else if Assigned(Data) then
Result := 'No User';
end;
if not Assigned(Data) then
Exit;
case InfoClass of
lsUserName:
Result := Data.UserName.ToString;
lsLogonDomain:
Result := Data.LogonDomain.ToString;
lsAuthPackage:
Result := Data.AuthenticationPackage.ToString;
lsLogonType:
Result := PrettifyCamelCaseEnum(TypeInfo(TSecurityLogonType),
Integer(Data.LogonType), 'LogonType');
lsSession:
Result := Data.Session.ToString;
lsLogonTime:
Result := NativeTimeToString(Data.LogonTime);
lsLogonServer:
Result := Data.LogonServer.ToString;
lsDnsDomainName:
Result := Data.DnsDomainName.ToString;
lsUpn:
Result := Data.Upn.ToString;
lsUserFlags:
Result := MapFlags(Data.UserFlags, LogonFlags);
lsLastSuccessfulLogon:
Result := NativeTimeToString(Data.LastLogonInfo.LastSuccessfulLogon);
lsLastFailedLogon:
Result := NativeTimeToString(Data.LastLogonInfo.LastFailedLogon);
lsFailedAttemptSinceSuccess:
Result := Data.LastLogonInfo.FailedAttemptCountSinceLastSuccessfulLogon.
ToString;
lsLogonScript:
Result := Data.LogonScript.ToString;
lsProfilePath:
Result := Data.ProfilePath.ToString;
lsHomeDirectory:
Result := Data.HomeDirectory.ToString;
lsHomeDirectoryDrive:
Result := Data.HomeDirectoryDrive.ToString;
lsLogoffTime:
Result := NativeTimeToString(Data.LogoffTime);
lsKickOffTime:
Result := NativeTimeToString(Data.KickOffTime);
lsPasswordLastSet:
Result := NativeTimeToString(Data.PasswordLastSet);
lsPasswordCanChange:
Result := NativeTimeToString(Data.PasswordCanChange);
lsPasswordMustChange:
Result := NativeTimeToString(Data.PasswordMustChange);
end;
end;
function TLogonSession.RawData: PSecurityLogonSessionData;
begin
Result := Data;
end;
function TLogonSession.User: ISid;
begin
Result := FSid;
end;
{ Functions }
function LsaxEnumerateLogonSessions(out Luids: TArray<TLuid>): TNtxStatus;
var
Count, i: Integer;
Buffer: PLuidArray;
HasAnonymousLogon: Boolean;
begin
Result.Location := 'LsaEnumerateLogonSessions';
Result.Status := LsaEnumerateLogonSessions(Count, Buffer);
if not Result.IsSuccess then
Exit;
SetLength(Luids, Count);
// Invert the order so that later logons appear later in the list
for i := 0 to High(Luids) do
Luids[i] := Buffer{$R-}[Count - 1 - i]{$R+};
LsaFreeReturnBuffer(Buffer);
// Make sure anonymous logon is in the list (most likely it is not)
HasAnonymousLogon := False;
for i := 0 to High(Luids) do
if Luids[i] = ANONYMOUS_LOGON_LUID then
begin
HasAnonymousLogon := True;
Break;
end;
if not HasAnonymousLogon then
Insert(ANONYMOUS_LOGON_LUID, Luids, 0);
end;
function LsaxQueryLogonSession(LogonId: TLuid; out LogonSession: ILogonSession):
TNtxStatus;
var
Buffer: PSecurityLogonSessionData;
begin
{$IFDEF Win32}
// TODO -c WoW64: LsaGetLogonSessionData returns a weird pointer
if RtlxAssertNotWoW64(Result) then
Exit;
{$ENDIF}
Result.Location := 'LsaGetLogonSessionData';
Result.Status := LsaGetLogonSessionData(LogonId, Buffer);
if not Result.IsSuccess then
Buffer := nil;
LogonSession := TLogonSession.Create(LogonId, Buffer)
end;
end.
|
unit uresmain;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,
dummy;
{$INCLUDE 'sxmlpad_language.inc'}
{$IFDEF sxmlpad_language_english}
resourcestring
// --> menu bar*s captions:
resmiMainFile_Caption = '&File';
resmiMainEdit_Caption = '&Edit';
resmiMainSearch_Caption = '&Search';
resmiMainView_Caption = '&View';
resmiMainTools_Caption = '&Tools';
resmiMainTreeview_Caption = 'Treeview';
resmiMainTags_Caption = 'Tags';
resmiMainHelp_Caption = 'Help';
// --> menu bar*s file captions:
resmiFileNew_Caption = 'New ...';
resmiFileNewAs_Caption = 'New with Template ...';
resmiFileOpen_Caption = 'Open ...';
resmiFileSave_Caption = 'Save ...';
resmiFileSaveAs_Caption = 'Save As ...';
resmiFileSavePreview_Caption = 'Save Preview ...';
resmiFileSaveRename_Caption = 'Rename File As ...';
resmiFileSaveCopyAs_Caption = 'Save a Copy As ...';
resmiFileProperties_Caption = 'File &Properties...';
resmiFileClose_Caption = 'Close';
resmiFileExit_Caption = 'Exit';
// --> menu bar*s file hints:
resmiFileNew_Hint = 'New ...';
resmiFileNewAs_Hint = 'New with Template ...';
resmiFileOpen_Hint = 'Open ...';
resmiFileSave_Hint = 'Save ...';
resmiFileSaveAs_Hint = 'Save As ...';
resmiFileSavePreview_Hint = 'Save Preview ...';
resmiFileSaveRename_Hint = 'Rename File As ...';
resmiFileSaveCopyAs_Hint = 'Save a Copy As ...';
resmiFileProperties_Hint = 'File &Properties...';
resmiFileClose_Hint = 'Close';
resmiFileExit_Hint = 'Exit';
// --> menu bar*s "edit" menu captions:
resmiEditUndo_Caption = 'Undo';
resmiEditRedo_Caption = 'Redo';
resmiEditSelectAll_Caption = 'Select All';
resmiEditSelectNone_Caption = 'Cancel Selection';
resmiEditCut_Caption = 'Cut';
resmiEditCopy_Caption = 'Copy';
resmiEditPaste_Caption = 'Paste';
resmiEditDuplicate_Caption = 'Paste Duplicate';
resmiEditClearClipboard_Caption = 'Clear Clipboard';
// --> menu bar*s "search" menu captions:
miSearchFind.Caption := resmiSearchFind_Caption;
miSearchFindAgain.Caption := resmiSearchFindAgain_Caption;
miSearchReplace.Caption := resmiSearchReplace_Caption;
miSearchReplaceAgain.Caption := resmiSearchReplaceAgain_Caption;
// --> menu bar*s "view" menu captions:
resmiViewToolBarsConfigure_Caption = 'Configure ToolBars...';
resmiViewToolBarQuick_Caption = 'Toggle Quick ToolBar';
resmiViewToolBarFile_Caption = 'Toggle File ToolBar';
resmiViewToolBarEditSearch_Caption = 'Toggle EditSearch ToolBar';
resmiViewToolBarTreeview_Caption = 'Toogle Treeview ToolBar';
resmiViewFontSizeReduce_Caption = 'Reduce Font Size';
resmiViewFontSizeIncrease_Caption = 'Increase Font Size';
resmiViewToggleAddressbar_Caption = 'Toggle Addressbar';
// --> menu bar*s "tools" menu captions:
resmiToolsConfigureTools_Caption = 'Configure Tools ...';
resmiToolsExportPreview_Caption = 'Export Preview ...';
// --> menu bar*s "treeview" menu captions:
resmiTreeviewExplore_Caption = 'Explore Treeview';
resmiTreeviewExpand_Caption = 'Expand Treeview';
resmiTreeviewCollapse_Caption = 'Collapse Treeview';
resmiTreeviewEmpty_Caption = 'Empty Treeview';
resmiTreeviewItemSelectOff_Caption = 'Treeview Item Select Off';
resmiTreeviewItemSelectOn_Caption = 'Treeview Item Select On';
resmiTreeviewItemInsertLast_Caption = 'Insert Last Item to Treeview ...';
resmiTreeviewItemDelete_Caption = 'Delete Item from Treeview ...';
resmiTreeviewItemProperties_Caption = 'Edit Properties from Treeview Item...';
resmiTreeviewItemInsertBefore_Caption = 'Insert Item Before ...';
resmiTreeviewItemInsertAfter_Caption = 'Insert Item After ...';
// --> menu bar*s "tags" menu captions:
resmiTagsNewBlockTag_Caption = 'New Block Tag...';
resmiTagsNewSingleTag_Caption = 'New Single Tag...';
resmiTagsNewCommentTag_Caption = 'New Comment Tag...';
resmiTagsNewTextTag_Caption = 'New Text Tag...';
// --> menu bar*s "help" menu captions:
resmiHelpAbout_Caption = 'About ...';
resAddressLabel_Caption = 'Path:';
resCannotRemoveNode = 'Cannot remove this node';
resAbout_Contents = 'About sxmlpad.';
resTagsWithoutDelimiters = 'Tags without Delimiters';
resCommentWithoutDelimiters = 'Comment without Delimiters';
resNewElementTitle = 'New Element';
resNewElementContents = 'Select Element Type:';
resTagBlockInsert = 'Insert Block Tag';
resTagBlockEdit = 'Edit Block Tag';
resTagSingleInsert = 'Insert Single Tag';
resTagSingleEdit = 'Edit Single Tag';
resTagCommentInsert = 'Insert Comment Tag';
resTagCommentEdit = 'Edit Comment Tag';
resTagTextInsert = 'Insert Text';
resTagTextEdit = 'Edit Text';
resTagTextCapture = 'Capture Text';
// --> Dialogs:
resOpenDialog_Title = 'Open an existing file';
resNewAsDialog_Title = 'Create New file with a template';
resSaveDialog_Title = 'Save file as';
resRenameAsDialog_Title = 'Rename file as';
resSaveCopyAsDialog_Title = 'Save a copy of file as';
{$ENDIF}
{$IFDEF sxmlpad_language_spanisheurope}
resourcestring
// --> menu bar*s captions:
resmiMainFile_Caption = '&Fichero';
resmiMainEdit_Caption = '&Edicion';
resmiMainSearch_Caption = 'Bu&squeda';
resmiMainView_Caption = '&Ver';
resmiMainTools_Caption = 'Herramien&tas';
resmiMainTreeview_Caption = 'Vistaarbol';
resmiMainTags_Caption = 'Marcadores';
resmiMainHelp_Caption = 'Ayuda';
// --> menu bar*s file captions:
resmiFileNew_Caption = 'Nuevo ...';
resmiFileNewAs_Caption = 'Nuevo con Plantilla ...';
resmiFileOpen_Caption = 'Abrir ...';
resmiFileSave_Caption = 'Guardar ...';
resmiFileSaveAs_Caption = 'Guardar Como ...';
resmiFileSavePreview_Caption = 'Vista Previa de Guardar ...';
resmiFileSaveRename_Caption = 'Guardar Fichero Como ...';
resmiFileSaveCopyAs_Caption = 'Guardar una copia Como ...';
resmiFileProperties_Caption = '&Propiedades de Fichero...';
resmiFileClose_Caption = 'Cerrar';
resmiFileExit_Caption = 'Salir';
// --> menu bar*s file hints:
resmiFileNew_Hint = 'Nuevo ...';
resmiFileNewAs_Hint = 'Nuevo con Plantilla ...';
resmiFileOpen_Hint = 'Abrir ...';
resmiFileSave_Hint = 'Guardar ...';
resmiFileSaveAs_Hint = 'Guardar Como ...';
resmiFileSavePreview_Hint = 'Vista Previa de Guardar ...';
resmiFileSaveRename_Hint = 'Guardar Fichero Como ...';
resmiFileSaveCopyAs_Hint = 'Guardar una copia Como ...';
resmiFileProperties_Hint = '&Propiedades de Fichero...';
resmiFileClose_Hint = 'Cerrar';
resmiFileExit_Hint = 'Salir';
// --> menu bar*s "edit" menu captions:
resmiEditUndo_Caption = 'Deshacer';
resmiEditRedo_Caption = 'Rehacer';
resmiEditSelectAll_Caption = 'Seleccionar Todo';
resmiEditSelectNone_Caption = 'Cancelar Seleccion';
resmiEditCut_Caption = 'Cortar';
resmiEditCopy_Caption = 'Copiar';
resmiEditPaste_Caption = 'Pegar';
resmiEditDuplicate_Caption = 'Pegar Duplicado';
resmiEditClearClipboard_Caption = 'Limpiar Portapapeles';
// --> menu bar*s "search" menu captions:
resmiSearchFind_Caption = 'Buscar ...';
resmiSearchFindAgain_Caption = 'Buscar de nuevo ...';
resmiSearchReplace_Caption = 'Reemplazar ...';
resmiSearchReplaceAgain_Caption = 'Reemplazar de nuevo ...';
// --> menu bar*s "view" menu captions:
resmiViewToolBarsConfigure_Caption = 'Configurar Barras Herramientas...';
resmiViewToolBarQuick_Caption = 'Mostrar/Ocultar Barra Rapida';
resmiViewToolBarFile_Caption = 'Mostrar/Ocultar Barra Archivo';
resmiViewToolBarEditSearch_Caption = 'Mostrar/Ocultar Barra EdicionBusqueda';
resmiViewToolBarTreeview_Caption = 'Mostrar/Ocultar Barra VistaArbol';
resmiViewFontSizeReduce_Caption = 'Reducir Tamaño Letra';
resmiViewFontSizeIncrease_Caption = 'Agrandar Tamaño Letra';
resmiViewToggleAddressbar_Caption = 'Mostrar/Ocultar Barra Direccion';
// --> menu bar*s "tools" menu captions:
resmiToolsConfigureTools_Caption = 'Configurar Herramientas ...';
resmiToolsExportPreview_Caption = 'Vista Previa Exportar ...';
// --> menu bar*s "treeview" menu captions:
resmiTreeviewExplore_Caption = 'Explorar VistaArbol';
resmiTreeviewExpand_Caption = 'Expandir VistaArbol';
resmiTreeviewCollapse_Caption = 'Colapsar VistaArbol';
resmiTreeviewEmpty_Caption = 'Vaciar VistaArbol';
resmiTreeviewItemSelectOff_Caption = 'Marcar Seleccion elemento';
resmiTreeviewItemSelectOn_Caption = 'Desmarcar Seleccion elemento';
resmiTreeviewItemInsertLast_Caption = 'Insertar ultimo elemento ...';
resmiTreeviewItemDelete_Caption = 'Eliminar elemento ...';
resmiTreeviewItemProperties_Caption = 'Editar Propiedades de elemento ...';
resmiTreeviewItemInsertBefore_Caption = 'Insertar elemento antes ...';
resmiTreeviewItemInsertAfter_Caption = 'Insertar elemento despues ...';
// --> menu bar*s "tags" menu captions:
resmiTagsNewBlockTag_Caption = 'Nueva Etiqueta Bloque...';
resmiTagsNewSingleTag_Caption = 'Nueva Etiqueta Sencilla...';
resmiTagsNewCommentTag_Caption = 'Nueva Etiqueta Comentario...';
resmiTagsNewTextTag_Caption = 'Nueva Etiqueta Texto...';
// --> menu bar*s "help" menu captions:
resmiHelpAbout_Caption = 'Acerca ...';
resAddressLabel_Caption = 'Ruta:';
resCannotRemoveNode = 'No se puede eliminar este elemento';
resAbout_Contents = 'Acerca de sxmlpad.';
resTagsWithoutDelimiters = 'Marcador sin delimitadores';
resCommentWithoutDelimiters = 'Comentario sin delimitadores';
resNewElementTitle = 'Nuevo Elemento';
resNewElementContents = 'Seleccione Tipo de Elemento:';
resTagBlockInsert = 'Insertar Bloque de Marcadores';
resTagBlockEdit = 'Editar Bloque de Marcadores';
resTagSingleInsert = 'Insertar Marcador Simple';
resTagSingleEdit = 'Editar Marcador Simple';
resTagCommentInsert = 'Insertar Marcador de Comentario';
resTagCommentEdit = 'Editar Marcador de Comentario';
resTagTextInsert = 'Insertar Solo Texto';
resTagTextEdit = 'Editar Texto';
resTagTextCapture = 'Capturar Texto';
// --> Dialogs:
resOpenDialog_Title = 'Abrir un archivo existente';
resNewAsDialog_Title = 'Crear archivo nuevo con plantilla';
resSaveDialog_Title = 'Guardar archivo como';
resRenameAsDialog_Title = 'Renombrar archivo como';
resSaveCopyAsDialog_Title = 'Guardar una copia de un archivo como';
{$ENDIF}
{$IFDEF sxmlpad_language_spanishlatam}
resourcestring
// --> menu bar*s captions:
resmiMainFile_Caption = 'Archivo';
resmiMainEdit_Caption = '&Edicion';
resmiMainSearch_Caption = 'Bu&squeda';
resmiMainView_Caption = '&Ver';
resmiMainTools_Caption = 'Herramien&tas';
resmiMainTreeview_Caption = 'Vistaarbol';
resmiMainTags_Caption = 'Marcadores';
resmiMainHelp_Caption = 'Ayuda';
// --> menu bar*s file captions:
resmiFileNew_Caption = 'Nuevo ...';
resmiFileNewAs_Caption = 'Nuevo con Plantilla ...';
resmiFileOpen_Caption = 'Abrir ...';
resmiFileSave_Caption = 'Guardar ...';
resmiFileSaveAs_Caption = 'Guardar Como ...';
resmiFileSavePreview_Caption = 'Vista Previa de Guardar ...';
resmiFileSaveRename_Caption = 'Guardar Archivo Como ...';
resmiFileSaveCopyAs_Caption = 'Guardar una copia Como ...';
resmiFileProperties_Caption = '&Propiedades de Archivo...';
resmiFileClose_Caption = 'Cerrar';
resmiFileExit_Caption = 'Salir';
// --> menu bar*s file hints:
resmiFileNew_Hint = 'Nuevo ...';
resmiFileNewAs_Hint = 'Nuevo con Plantilla ...';
resmiFileOpen_Hint = 'Abrir ...';
resmiFileSave_Hint = 'Guardar ...';
resmiFileSaveAs_Hint = 'Guardar Como ...';
resmiFileSavePreview_Hint = 'Vista Previa de Guardar ...';
resmiFileSaveRename_Hint = 'Guardar Archivo Como ...';
resmiFileSaveCopyAs_Hint = 'Guardar una copia Como ...';
resmiFileProperties_Hint = '&Propiedades de Archivo...';
resmiFileClose_Hint = 'Cerrar';
resmiFileExit_Hint = 'Salir';
// --> menu bar*s "edit" menu captions:
resmiEditUndo_Caption = 'Deshacer';
resmiEditRedo_Caption = 'Rehacer';
resmiEditSelectAll_Caption = 'Seleccionar Todo';
resmiEditSelectNone_Caption = 'Cancelar Seleccion';
resmiEditCut_Caption = 'Cortar';
resmiEditCopy_Caption = 'Copiar';
resmiEditPaste_Caption = 'Pegar';
resmiEditDuplicate_Caption = 'Pegar Duplicado';
resmiEditClearClipboard_Caption = 'Limpiar Portapapeles';
// --> menu bar*s "search" menu captions:
resmiSearchFind_Caption = 'Buscar ...';
resmiSearchFindAgain_Caption = 'Buscar de nuevo ...';
resmiSearchReplace_Caption = 'Reemplazar ...';
resmiSearchReplaceAgain_Caption = 'Reemplazar de nuevo ...';
// --> menu bar*s "view" menu captions:
resmiViewToolBarsConfigure_Caption = 'Configurar Barras Herramientas...';
resmiViewToolBarQuick_Caption = 'Mostrar/Ocultar Barra Rapida';
resmiViewToolBarFile_Caption = 'Mostrar/Ocultar Barra Archivo';
resmiViewToolBarEditSearch_Caption = 'Mostrar/Ocultar Barra EdicionBusqueda';
resmiViewToolBarTreeview_Caption = 'Mostrar/Ocultar Barra VistaArbol';
resmiViewFontSizeReduce_Caption = 'Reducir Tamaño Letra';
resmiViewFontSizeIncrease_Caption = 'Agrandar Tamaño Letra';
resmiViewToggleAddressbar_Caption = 'Mostrar/Ocultar Barra Direccion';
// --> menu bar*s "tools" menu captions:
resmiToolsConfigureTools_Caption = 'Configurar Herramientas ...';
resmiToolsExportPreview_Caption = 'Vista Previa Exportar ...';
// --> menu bar*s "treeview" menu captions:
resmiTreeviewExplore_Caption = 'Explorar VistaArbol';
resmiTreeviewExpand_Caption = 'Expandir VistaArbol';
resmiTreeviewCollapse_Caption = 'Collapsar VistaArbol';
resmiTreeviewEmpty_Caption = 'Vaciar VistaArbol';
resmiTreeviewItemSelectOff_Caption = 'Marcar Seleccion elemento';
resmiTreeviewItemSelectOn_Caption = 'Desmarcar Seleccion elemento';
resmiTreeviewItemInsertLast_Caption = 'Insertar ultimo elemento ...';
resmiTreeviewItemDelete_Caption = 'Eliminar elemento ...';
resmiTreeviewItemProperties_Caption = 'Editar Propiedades de elemento ...';
resmiTreeviewItemInsertBefore_Caption = 'Insertar elemento antes ...';
resmiTreeviewItemInsertAfter_Caption = 'Insertar elemento despues ...';
// --> menu bar*s "tags" menu captions:
resmiTagsNewBlockTag_Caption = 'Nueva Etiqueta Bloque...';
resmiTagsNewSingleTag_Caption = 'Nueva Etiqueta Sencilla...';
resmiTagsNewCommentTag_Caption = 'Nueva Etiqueta Comentario...';
resmiTagsNewTextTag_Caption = 'Nueva Etiqueta Texto...';
// --> menu bar*s "help" menu captions:
resmiHelpAbout_Caption = 'Acerca ...';
resAddressLabel_Caption = 'Ruta:';
resCannotRemoveNode = 'No se puede eliminar este elemento';
resAbout_Contents = 'Acerca de sxmlpad.';
resTagsWithoutDelimiters = 'Marcador sin delimitadores';
resCommentWithoutDelimiters = 'Comentario sin delimitadores';
resNewElementTitle = 'Nuevo Elemento';
resNewElementContents = 'Seleccione Tipo de Elemento:';
resTagBlockInsert = 'Insertar Bloque de Marcadores';
resTagBlockEdit = 'Editar Bloque de Marcadores';
resTagSingleInsert = 'Insertar Marcador Simple';
resTagSingleEdit = 'Editar Marcador Simple';
resTagCommentInsert = 'Insertar Marcador de Comentario';
resTagCommentEdit = 'Editar Marcador de Comentario';
resTagTextInsert = 'Insertar Solo Texto';
resTagTextEdit = 'Editar Texto';
resTagTextCapture = 'Capturar Texto';
// --> Dialogs:
resOpenDialog_Title = 'Abrir un archivo existente';
resNewAsDialog_Title = 'Crear archivo nuevo con plantilla';
resSaveDialog_Title = 'Guardar archivo como';
resRenameAsDialog_Title = 'Renombrar archivo como';
resSaveCopyAsDialog_Title = 'Guardar una copia de un archivo como';
{$ENDIF}
implementation
end.
|
//******************************************************************************
// VARIAN ASYNC32 COMPONENT
// (c) VARIAN SOFTWARE SERVICES NL 1996-1998
// ALL RIGHTS RESERVED
//******************************************************************************
unit CommObjs;
interface
uses
Sysutils, Windows, Messages, Classes;
type
THandleObject = class(TObject)
private
FHandle: THandle;
FError: Integer;
public
destructor Destroy; override;
property Handle: THandle read FHandle;
property Error: Integer read FError;
end;
TEventWaitResult = (wrSignaled, wrTimeout, wrAbandoned, wrError);
TEvent = class(THandleObject)
public
constructor Create(EventAttributes: PSecurityAttributes; ManualReset,
InitialState: Boolean; const Name: string);
function WaitFor(Timeout: dWord): TEventWaitResult;
procedure SetEvent;
procedure ResetEvent;
end;
TSimpleEvent = class(TEvent)
public
constructor Create;
end;
TCriticalSection = class(TObject)
private
FSection: TRTLCriticalSection;
public
constructor Create;
destructor Destroy; override;
procedure Acquire;
procedure Release;
procedure Enter;
procedure Leave;
end;
implementation
//THandleObject
destructor THandleObject.Destroy;
begin
CloseHandle(FHandle);
inherited Destroy;
end;
//TEvent
constructor TEvent.Create(EventAttributes: PSecurityAttributes; ManualReset,
InitialState: Boolean; const Name: string);
begin
FHandle := CreateEvent(EventAttributes, ManualReset, InitialState, PChar(Name));
end;
function TEvent.WaitFor(Timeout: dWord): TEventWaitResult;
begin
case WaitForSingleObject(Handle, Timeout) of
WAIT_ABANDONED:
Result := wrAbandoned;
WAIT_OBJECT_0:
Result := wrSignaled;
WAIT_TIMEOUT:
Result := wrTimeout;
WAIT_FAILED:
begin
Result := wrError;
FError := GetLastError;
end;
else
Result := wrError;
end;
end;
procedure TEvent.SetEvent;
begin
Windows.SetEvent(Handle);
end;
procedure TEvent.ResetEvent;
begin
Windows.ResetEvent(Handle);
end;
//TSimpleEvent
constructor TSimpleEvent.Create;
begin
FHandle := CreateEvent(nil, True, False, nil);
end;
// TCriticalSection
constructor TCriticalSection.Create;
begin
inherited Create;
InitializeCriticalSection(FSection);
end;
destructor TCriticalSection.Destroy;
begin
DeleteCriticalSection(FSection);
inherited Destroy;
end;
procedure TCriticalSection.Acquire;
begin
EnterCriticalSection(FSection);
end;
procedure TCriticalSection.Release;
begin
LeaveCriticalSection(FSection);
end;
procedure TCriticalSection.Enter;
begin
Acquire;
end;
procedure TCriticalSection.Leave;
begin
Release;
end;
end.
|
unit MessageCollection;
interface
uses Classes, SysUtils, uLkJSON;
type
JSONItem = record
key: String;
value: String;
end;
JSONMessage = class
private
JSONItems: array of JSONItem;
public
ClientID: Integer;
DirectJSONString: String;
OnDeleted: Boolean;
constructor Create();
function AddJSONItem(Item: JSONItem): Boolean;
function GetFirstJSONItem: JSONItem;
function DeleteFirstJSONItem: Boolean;
function GetStrJSON(): Widestring;
end;
TMessageCollectionItem = class(TCollectionItem)
private
FJSONMessage: JSONMessage;
public
MSGJSONObject: TLkJSONObject;
OnDeleted: Boolean;
OnDeletedASKed: Boolean;
ClientID: Integer;
DirectJSONString: String;
Pozyvnoi: Integer;
DriverDBID: Integer;
itsSystemMessage: Boolean;
constructor Create(Collection: TCollection); override;
function GetMessage(): JSONMessage;
function GetStrJSON(): Widestring;
procedure SetDirectJSONString(DirectJSON: String);
end;
TItemChangeEvent = procedure(Item: TCollectionItem) of object;
TMessageCollection = class(TCollection)
private
FOwner: TPersistent;
FOnItemChange: TItemChangeEvent;
protected
function GetOwner: TPersistent; override;
procedure Update(Item: TCollectionItem); override;
procedure DoItemChange(Item: TCollectionItem); dynamic;
function GetItem(Index: Integer): TMessageCollectionItem;
procedure SetItem(Index: Integer; const Value: TMessageCollectionItem);
public
constructor Create();
function Add: TMessageCollectionItem;
property Items[Index: Integer]: TMessageCollectionItem read GetItem write SetItem; default;
published
property OnItemChange: TItemChangeEvent
read FOnItemChange write FOnItemChange;
end;
implementation
uses TCPClientCollection;
constructor JSONMessage.Create();
begin
SetLength(JSONItems,0);
DirectJSONString:='';
end;
function JSONMessage.AddJSONItem(Item: JSONItem): Boolean;
var res: Boolean;
begin
SetLength(JSONItems, Length(JSONItems));
res:=True;
Result:=res;
end;
function JSONMessage.GetFirstJSONItem: JSONItem;
var res: JSONItem;
i: Integer;
begin
res:=JSONItems[0];
Result:=res;
end;
function JSONMessage.DeleteFirstJSONItem: Boolean;
var i: Integer;
begin
for i:=0 to Length(JSONItems)-1 do
JSONItems[i]:=JSONItems[i+1];
end;
function JSONMessage.GetStrJSON(): Widestring;
var i: Integer;
res: Widestring;
begin
res:='';
if (Length(DirectJSONString)<=0) then
begin
if Length(JSONItems)>0 then
begin
res:='{ ';
for i:=0 to Length(JSONItems)-1 do
begin
res:='"'+JSONItems[i].key+'":"'+
JSONItems[i].value+'"';
if i<(Length(JSONItems)-1) then
res:=res+', ';
end;
res:=res+' }';
end;
end
else
res:=DirectJSONString;
Result:=res;
end;
constructor TMessageCollectionItem.Create(Collection: TCollection);
begin
// Создаем сам объект и инициализируем его поля
inherited Create(Collection);
FJSONMessage := JSONMessage.Create();
OnDeleted := False;
OnDeletedASKed := False;
FJSONMessage.OnDeleted := False;
MSGJSONObject:= TLkJSONObject.Create();
itsSystemMessage:=False;
end;
function TMessageCollectionItem.GetMessage(): JSONMessage;
begin
Result:=FJSONMessage;
end;
function TMessageCollectionItem.GetStrJSON(): Widestring;
begin
Result:=FJSONMessage.GetStrJSON();
end;
procedure TMessageCollectionItem.
SetDirectJSONString(DirectJSON: String);
begin
DirectJSONString:=DirectJSON;
FJSONMessage.DirectJSONString:=DirectJSON;
end;
function TMessageCollection.Add: TMessageCollectionItem;
begin
// Получаем общий TCollectionItem и приводим его к нашему TSpot
//try
Result := TMessageCollectionItem(inherited Add);
//except on E:Exception do
//end;
end;
constructor TMessageCollection.Create();
begin
// Создаем коллекцию и запоминаем ссылку на ее владельца
inherited Create(TMessageCollectionItem);
FOwner := nil;
end;
procedure TMessageCollection.DoItemChange(Item: TCollectionItem);
begin
// Стандартный вызов пользовательского обработчика события
if Assigned(FOnItemChange) then
FOnItemChange(Item);
end;
function TMessageCollection.GetItem(Index: Integer): TMessageCollectionItem;
begin
// Получаем общий TCollectionItem и приводим его к нашему TSpot
Result := TMessageCollectionItem(inherited GetItem(Index));
end;
function TMessageCollection.GetOwner: TPersistent;
begin
// Возвращаем ранее запомненную ссылку на владельца коллекции
Result := TPersistent(FOwner);
end;
procedure TMessageCollection.SetItem(Index: Integer; const Value: TMessageCollectionItem);
begin
// Просто используем унаследованный метод записи
inherited SetItem(Index, Value);
end;
procedure TMessageCollection.Update(Item: TCollectionItem);
begin
// Вызов унаследованного метода здесь лишний, но это грамотный стиль. Он
// гарантирует верную работу даже при изменениях в новых версиях Delphi.
inherited Update(Item);
// Даем запрос на перерисовку компонента-владельца
//FSocketCoordinator.Invalidate;
// Возбуждаем событие - сигнал об изменении элемента
DoItemChange(Item);
end;
end.
|
{$i deltics.interfacedobjects.inc}
unit Deltics.InterfacedObjects.ComInterfacedPersistent;
interface
uses
Classes,
Deltics.Multicast;
type
TComInterfacedPersistent = class(Classes.TInterfacedPersistent, IOn_Destroy)
private
fOn_Destroy: IOn_Destroy;
// IOn_Destroy
protected
function get_On_Destroy: IOn_Destroy;
public
property On_Destroy: IOn_Destroy read get_On_Destroy implements IOn_Destroy;
end;
implementation
{ TComInterfacedPersistent ----------------------------------------------------------------------- }
{ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - }
function TComInterfacedPersistent.get_On_Destroy: IOn_Destroy;
begin
if NOT Assigned(fOn_Destroy) then
fOn_Destroy := TOnDestroy.Create(self);
result := fOn_Destroy;
end;
end.
|
unit xElecBusLine;
interface
uses xElecLine, xElecPoint, System.Classes, System.SysUtils;
type
/// <summary>
/// 母线
/// </summary>
TElecBusLine = class
private
FOnValueChnage: TNotifyEvent;
FBusLineN: TElecLine;
FBusLineB: TElecLine;
FBusLineC: TElecLine;
FBusLineA: TElecLine;
procedure ValueChange(Sender : TObject);
public
constructor Create;
destructor Destroy; override;
/// <summary>
/// 母线A相
/// </summary>
property BusLineA : TElecLine read FBusLineA write FBusLineA;
/// <summary>
/// 母线B相
/// </summary>
property BusLineB : TElecLine read FBusLineB write FBusLineB;
/// <summary>
/// 母线C相
/// </summary>
property BusLineC : TElecLine read FBusLineC write FBusLineC;
/// <summary>
/// 母线N相
/// </summary>
property BusLineN : TElecLine read FBusLineN write FBusLineN;
/// <summary>
/// 值改变事件
/// </summary>
property OnValueChnage : TNotifyEvent read FOnValueChnage write FOnValueChnage;
/// <summary>
/// 刷新值
/// </summary>
procedure RefurshValue;
public
/// <summary>
/// 清空电压值
/// </summary>
procedure ClearVolVlaue;
/// <summary>
/// 清除权值
/// </summary>
procedure ClearWValue;
/// <summary>
/// 清空电流列表
/// </summary>
procedure ClearCurrentList;
end;
implementation
{ TElecBusLine }
procedure TElecBusLine.ClearCurrentList;
begin
FBusLineN.ClearCurrentList;
FBusLineB.ClearCurrentList;
FBusLineC.ClearCurrentList;
FBusLineA.ClearCurrentList;
end;
procedure TElecBusLine.ClearVolVlaue;
begin
end;
procedure TElecBusLine.ClearWValue;
begin
FBusLineN.ClearWValue;
FBusLineB.ClearWValue;
FBusLineC.ClearWValue;
FBusLineA.ClearWValue;
end;
constructor TElecBusLine.Create;
begin
FBusLineN:= TElecLine.Create;
FBusLineB:= TElecLine.Create;
FBusLineC:= TElecLine.Create;
FBusLineA:= TElecLine.Create;
FBusLineA.SetValue('BusLineA', 220, 90, 100, 70, False, True, True);
FBusLineB.SetValue('BusLineB', 220, 330, 100, 310, False, True, True);
FBusLineC.SetValue('BusLineC', 220, 210, 100, 190, False, True, True);
FBusLineN.SetValue('BusLineN', 0, 0, 0, 0, True, False, False);
FBusLineN.Current.WeightValue[100].WValue := 0;
FBusLineN.Current.WeightValue[101].WValue := 0;
FBusLineN.Current.WeightValue[102].WValue := 0;
FBusLineA.WID := 100;
FBusLineB.WID := 101;
FBusLineC.WID := 102;
FBusLineN.OnChange := ValueChange;
FBusLineB.OnChange := ValueChange;
FBusLineC.OnChange := ValueChange;
FBusLineA.OnChange := ValueChange;
end;
destructor TElecBusLine.Destroy;
begin
FBusLineN.Free;
FBusLineB.Free;
FBusLineC.Free;
FBusLineA.Free;
inherited;
end;
procedure TElecBusLine.RefurshValue;
begin
FBusLineA.SendVolValue;
FBusLineB.SendVolValue;
FBusLineC.SendVolValue;
FBusLineN.SendVolValue;
end;
procedure TElecBusLine.ValueChange(Sender: TObject);
begin
if Assigned(FOnValueChnage) then
begin
FOnValueChnage(Self);
end;
end;
end.
|
program DVRPC_Impacts_2060_V2_6;
{$APPTYPE CONSOLE}
uses
Classes, sysutils, fpstypes, fpSpreadsheet, laz_fpspreadsheet;
type TDynFloat = array of array of Real;
var
workbook: TsWorkbook;
worksheet: TsWorksheet;
datArray : TDynFloat;
function ReadSpreadsheetRange
(MyWorksheet: TsWorksheet; startCell : string; endCell: string = '')
: TDynFloat;
// Function reads numbers FROM range of cells (startCell : endCell)
// and RETURNS them as a dynamical array of Floats.
// If endCell is not provided, it reads all cells from startCell to the last.
// Example usage:
// ReadSpreadsheetRange(MyWorksheet,'B2', 'F3')
const xdebug=false;
var
LastColumn, LastRow, row, col : integer;
cell : PCell;
myArray : TDynFloat;
begin
if MyWorksheet.FindCell(startCell) = nil then
begin
// ToDo: Maybe I should return an empty array before exit (???)
WriteLn('Cell ' + startCell + ' does not exist in ' + MyWorksheet.Name);
exit;
end;
cell := MyWorksheet.FindCell(startCell);
// Set last column and rows depending on whether endCell provided
if ( endCell = '' ) or ( MyWorksheet.FindCell(endCell) = nil ) then
begin
LastColumn := MyWorksheet.GetLastColIndex();
LastRow := MyWorksheet.GetLastRowIndex();
end
else
begin
LastColumn := MyWorksheet.FindCell(endCell)^.Col;
LastRow := MyWorksheet.FindCell(endCell)^.Row;
end;
SetLength(myArray,LastRow - cell^.Row + 1,LastColumn - cell^.Col + 1);
for row := cell^.Row to LastRow do
for col := cell^.Col to LastColumn do
begin
myArray[row - cell^.Row, col - cell^.Col] :=
MyWorksheet.ReadAsNumber(row,col);
end;
if xdebug then begin
for row:=0 to LastRow-cell^.Row do begin
for col:=0 to LastColumn-cell^.Col do write(myArray[row,col]:8:1);
writeln;
end;
readln;
end;
Result := myArray;
end;
function Dummy(a,b:integer): single;
begin
if a=b then Dummy:=1.0 else Dummy:=0.0;
end;
function DummyRange(a,b,c:single): single;
begin
if (a>=b) and (a<c) then DummyRange:=1.0 else DummyRange:=0.0;
end;
function Max(a,b:single): single;
begin
if a>b then Max:=a else Max:=b;
end;
function Min(a,b:single): single;
begin
if a<b then Min:=a else Min:=b;
end;
{Control Module}
{constants}
const
StartYear:single = 2010;
TimeStepLength = 0.5; {years}
NumberOfTimeSteps = 100;
NumberOfRegions = 1;
testWriteYear = 0;
{global variables}
var
outest:text;
TimeStep:integer = 0;
Year:single;
Region:integer = 1;
Scenario:integer = 1;
{Demographic Module}
{constants}
const
NumberOfDemographicDimensions = 6;
NumberOfAgeGroups = 17;
AgeGroupLabels:array[0..NumberOfAgeGroups] of string[29]=
('Total',
'Age 0- 4',
'Age 5- 9',
'Age 10-15',
'Age 16-19',
'Age 20-24',
'Age 25-29',
'Age 30-34',
'Age 35-39',
'Age 40-44',
'Age 45-49',
'Age 50-54',
'Age 55-59',
'Age 60-64',
'Age 65-69',
'Age 70-74',
'Age 75-79',
'Age 80 up');
BirthAgeGroup = 1; {new births go into youngest age group}
AgeGroupDuration:array[1..NumberOfAgeGroups] of single = (5,5,6, 4,5,5, 5,5,5, 5,5,5, 5,5,5, 5,0);
NumberOfHhldTypes = 4;
HhldTypeLabels:array[1..NumberOfHhldTypes] of string[29]=
('Single/No Kids',
'Couple/No Kids',
'Single/With Kids',
'Couple/With Kids');
BirthHhldType:array[1..NumberOfHhldTypes] of integer=(2,4,2,4); {new births change 0 Ch to 1+ Ch}
NumberOfAdults :array[1..NumberOfHhldTypes] of single=(1, 2.2, 1, 2.2);
NumberOfChildren:array[1..NumberOfHhldTypes] of single=(0, 0, 1.5, 1.5);
NumberOfEthnicGrs = 12;
EthnicGrLabels:array[1..NumberOfEthnicGrs] of string[29]=
('Hispanic US born',
'Hispanic >20 yrs',
'Hispanic <20 yrs',
'Black US born',
'Black >20 yrs',
'Black <20 yrs',
'Asian US born',
'Asian >20 yrs',
'Asian <20 yrs',
'White US born',
'White >20 yrs',
'White <20 yrs');
EthnicGrDuration:array[1..NumberOfEthnicGrs] of integer=( 0, 0,20, 0, 0,20, 0, 0,20, 0, 0,20);
NextEthnicGroup:array[1..NumberOfEthnicGrs] of integer=( 0, 0, 2, 0, 0, 5, 0, 0, 8, 0, 0,11);
BirthEthnicGroup:array[1..NumberOfEthnicGrs] of integer=( 1, 1, 1, 4, 4, 4, 7, 7, 7,10,10,10);
OldNumberOfEthnicGrs = 6;
OldEthnicGroup:array[1..NumberOfEthnicGrs] of integer=( 3, 1, 2, 4, 1, 2, 5, 1, 2, 6, 1, 2);
NumberOfIncomeGrs = 3;
IncomeGrLabels:array[1..NumberOfIncomeGrs] of string[29]=
('Lower Income',
'Middle Income',
'Upper Income');
LowIncomeDummy:array[1..NumberOfIncomeGrs] of integer = (1,0,0);
MiddleIncomeDummy:array[1..NumberOfIncomeGrs] of integer = (0,1,0);
HighIncomeDummy:array[1..NumberOfIncomeGrs] of integer = (0,0,1);
NumberOfWorkerGrs = 2;
WorkerGrLabels:array[1..NumberOfWorkerGrs] of string[29]=
('In Workforce',
'Not in Workforce');
BirthWorkerGr = 2; {new births are non-workers}
NumberOfAreaTypes = 12;
AreaTypeLabels:array[1..NumberOfAreaTypes] of string[29]=
('PHIL-Suburban',
'PHIL-Second City',
'PHIL-Urban',
'PHIL-Urban Core',
'O.PA-Rural',
'O.PA-Suburban',
'O.PA-Second City',
'O.PA-Urban',
'N.J.-Rural',
'N.J.-Suburban',
'N.J.-Second City',
'N.J.-Urban');
NumberOfDensityTypes = 5;
DensityTypeLabels:array[1..NumberOfDensityTypes] of string[29]=
('Rural',
'Suburban',
'Second City',
'Urban',
'Urban Core');
AreaTypeDensity:array[1..NumberOfAreaTypes] of integer=(2,3,4,5, 1,2,3,4, 1,2,3,4);
NumberOfSubregions = 3;
SubregionLabels:array[1..NumberOfSubregions] of string[29]=
('Philadelphia',
'Other Penn.',
'New Jersey');
AreaTypeSubregion:array[1..NumberOfAreaTypes] of integer=(1,1,1,1, 2,2,2,2, 3,3,3,3);
(*
SubregionDensityAreaType:array[1..NumberofSubregions,1..NumberOfDensityTypes] of integer=
((0, 1, 2, 3, 4),
(5, 6, 7, 8, 0),
(9,10,11,12, 0));
*)
NumberOfMigrationTypes = 3;
MigrationTypeLabels:array[1..NumberOfMigrationTypes] of string[29]=
('Foreign Migration',
'Domestic Migration',
'Local Migration ');
NumberOfEmploymentTypes = 3;
EmploymentTypeLabels:array[1..NumberOfEmploymentTypes] of string[29]=
('Retail Jobs','Service Jobs','Other Jobs');
NumberOfLandUseTypes = 4;
LandUseTypeLabels:array[1..NumberOfLandUseTypes] of string[29]=
('Non-resid. Land','Residential Land','Developable Land','Protected Land');
NumberOfRoadTypes = 3;
RoadTypeLabels:array[1..NumberOfRoadTypes] of string[29]=
('Freeways','Arterials','Local Roads');
NumberOfODTypes = 3;
NumberOfTransitTypes = 2;
TransitTypeLabels:array[1..NumberOfTransitTypes] of string[29]=
('Rail Transit','Bus Transit');
NumberOfTravelModelVariables = 56;
NumberOfTravelModelEquations = 17;
CarOwnership_CarCompetition = 1;
CarOwnership_NoCar = 2;
WorkTrip_Generation = 3;
NonWorkTrip_Generation = 4;
ChildTrip_Generation = 5;
NonWorkTrip_CarPassengerMode = 6;
NonWorkTrip_TransitMode = 7;
NonWorkTrip_WalkBikeMode = 8;
WorkTrip_CarPassengerMode = 9;
WorkTrip_TransitMode = 10;
WorkTrip_WalkBikeMode = 11;
ChildTrip_CarPassengerMode = 12;
ChildTrip_TransitMode = 13;
ChildTrip_WalkBikeMode = 14;
CarDriverTrip_Distance = 15;
CarPassengerTrip_Distance = 16;
TransitTrip_Distance = 17;
EffectCurveIntervals=20;
{global variables}
type
TimeStepArray = array[0..NumberOfTimeSteps] of single;
AreaTypeArray = array[1..NumberOfAreaTypes] of TimeStepArray;
EmploymentArray = array
[1..NumberOfAreaTypes,
1..NumberOfEmploymentTypes] of TimeStepArray;
LandUseArray = array
[1..NumberOfAreaTypes,
1..NumberOfLandUseTypes] of TimeStepArray;
RoadSupplyArray = array
[1..NumberOfAreaTypes,
1..NumberOfRoadTypes] of TimeStepArray;
TransitSupplyArray = array
[1..NumberOfAreaTypes,
1..NumberOfTransitTypes] of TimeStepArray;
DemographicArray = array
[1..NumberOfAreaTypes,
1..NumberOfAgeGroups,
1..NumberOfHhldTypes,
1..NumberOfEthnicGrs,
1..NumberOfIncomeGrs,
1..NumberOfWorkerGrs] of TimeStepArray;
EffectCurveArray = array[-2..EffectCurveIntervals] of single;
function EffectCurve(curvePoints:EffectCurveArray; arg:single):single;
var low,high,pointOnCurve:single; lowerPoint,higherPoint:integer;
begin
low:=curvePoints[-2];
high:=curvePoints[-1];
if low>=high then begin
writeln('Invalid endpoint arguments for effect curve ...',low:3:2,' and ',high:3:2,' Press Enter');
EffectCurve:=curvePoints[0];
readln;
end else
if (arg<= low) then EffectCurve:=curvePoints[0] else
if (arg>=high) then EffectCurve:=curvePoints[EffectCurveIntervals] else begin
{interpolate linearly between points}
pointOnCurve:= ((arg-low) / (high-low)) * EffectCurveIntervals;
lowerPoint:= trunc(pointOnCurve);
higherPoint:=lowerPoint+1;
EffectCurve:= curvePoints[lowerPoint]
+ (pointOnCurve-lowerPoint) * (curvePoints[higherPoint]-curvePoints[lowerPoint]);
end;
end;
var
C_EffectOfJobDemandSupplyIndexOnEmployerAttractiveness,
C_EffectOfCommercialSpaceDemandSupplyIndexOnEmployerAttractiveness,
C_EffectOfRoadMileDemandSupplyIndexOnEmployerAttractiveness,
C_EffectOfJobDemandSupplyIndexOnResidentAttractiveness,
C_EffectOfResidentialSpaceDemandSupplyIndexOnResidentAttractiveness,
C_EffectOfRoadMileDemandSupplyIndexOnResidentAttractiveness
:EffectCurveArray;
TravelModelParameter: array
[1..NumberOfTravelModelEquations,
1..NumberOfTravelModelVariables] of single;
Jobs,
JobsCreated,
JobsLost,
JobsMovedOut,
JobsMovedIn : EmploymentArray;
Land,
ChangeInLandUseOut,
ChangeInLandUseIn : LandUseArray;
RoadLaneMiles,
RoadLaneMilesAdded,
RoadLaneMilesLost : RoadSupplyArray;
TransitRouteMiles,
TransitRouteMilesAdded,
TransitRouteMilesLost : TransitSupplyArray;
WorkplaceDistribution : array
[1..NumberOfAreaTypes,
1..NumberOfAreaTypes] of TimeStepArray;
Population,
AgeingOut,
AgeingIn,
DeathsOut,
BirthsFrom,
BirthsIn,
MarriagesOut,
MarriagesIn,
DivorcesOut,
DivorcesIn,
FirstChildOut,
FirstChildIn,
EmptyNestOut,
EmptyNestIn,
LeaveNestOut,
LeaveNestIn,
WorkerStatusOut,
WorkerStatusIn,
IncomeGroupOut,
IncomeGroupIn,
AcculturationOut,
AcculturationIn,
RegionalOutmigration,
RegionalInmigration,
DomesticOutmigration,
DomesticInmigration,
ForeignOutmigration,
ForeignInmigration,
OwnCar,
ShareCar,
NoCar,
WorkTrips,
NonWorkTrips,
CarDriverWorkTrips,
CarPassengerWorkTrips,
TransitWorkTrips,
WalkBikeWorkTrips,
CarDriverWorkMiles,
CarPassengerWorkMiles,
TransitWorkMiles,
WalkBikeWorkMiles,
CarDriverNonWorkTrips,
CarPassengerNonWorkTrips,
TransitNonWorkTrips,
WalkBikeNonWorkTrips,
CarDriverNonWorkMiles,
CarPassengerNonWorkMiles,
TransitNonWorkMiles,
WalkBikeNonWorkMiles
:DemographicArray;
const
NumberOfDemographicVariables = 47;
DemographicVariableLabels:array[1..NumberOfDemographicVariables] of string=
('Population',
'Ageing',
'Deaths',
'Births',
'Marriages',
'Divorces',
'FirstChild',
'EmptyNest',
'LeaveNest',
'ChangeStatus',
'ChangeIncome',
'20YearsInU',
'AgeingIn',
'BirthsIn',
'MarriagesIn',
'DivorcesIn',
'FirstChildIn',
'EmptyNestIn',
'LeaveNestIn',
'WorkforceIn',
'IncomeGroupIn',
'20YearsInUSIn',
'ForeignInmigration',
'ForeignOutmigration',
'DomesticInmigration',
'DomesticOutmigration',
'RegionalInmigration',
'RegionalOutmigration',
'OwnCar',
'ShareCar',
'NoCar',
'WorkTrips',
'NonWorkTrips',
'CarDriverWorkTrips',
'CarPassengerWorkTrips',
'TransitWorkTrips',
'WalkBikeWorkTrips',
'CarDriverWorkMiles',
'CarPassengerWorkMiles',
'TransitWorkMiles' ,
'CarDriverNonWorkTrips',
'CarPassengerNonWorkTrips',
'TransitNonWorkTrips',
'WalkBikeNonWorkTrips',
'CarDriverNonWorkMiles',
'CarPassengerNonWorkMiles',
'TransitNonWorkMiles' );
var
{current demographic marginals}
AgeGroupMarginals:array[1..NumberOfDemographicVariables,0..NumberOfAgeGroups] of TimeStepArray;
HhldTypeMarginals:array[1..NumberOfDemographicVariables,1..NumberOfHhldTypes] of TimeStepArray;
EthnicGrMarginals:array[1..NumberOfDemographicVariables,1..NumberOfEthnicGrs] of TimeStepArray;
IncomeGrMarginals:array[1..NumberOfDemographicVariables,1..NumberOfIncomeGrs] of TimeStepArray;
WorkerGrMarginals:array[1..NumberOfDemographicVariables,1..NumberOfWorkerGrs] of TimeStepArray;
AreaTypeMarginals:array[1..NumberOfDemographicVariables,1..NumberOfAreaTypes] of TimeStepArray;
{target demographic marginals}
AgeGroupTargetMarginals:array[1..NumberOfSubregions,1..NumberOfAgeGroups] of single;
HhldTypeTargetMarginals:array[1..NumberOfSubregions,1..NumberOfHhldTypes] of single;
EthnicGrTargetMarginals:array[1..NumberOfSubregions,1..NumberOfEthnicGrs] of single;
IncomeGrTargetMarginals:array[1..NumberOfSubregions,1..NumberOfIncomeGrs] of single;
WorkerGrTargetMarginals:array[1..NumberOfSubregions,1..NumberOfWorkerGrs] of single;
AreaTypeTargetMarginals:array[1..NumberOfSubregions,1..NumberOfAreaTypes] of single;
BaseAverageHouseholdSize,
MigrationRateMultiplier,
BaseMortalityRate,
BaseFertilityRate,
BaseMarriageRate,
BaseDivorceRate,
BaseEmptyNestRate,
BaseLeaveNestSingleRate,
BaseLeaveNestCoupleRate,
BaseEnterWorkforceRate,
BaseLeaveWorkforceRate,
BaseEnterLowIncomeRate,
BaseLeaveLowIncomeRate,
BaseEnterHighIncomeRate,
BaseLeaveHighIncomeRate:array
[1..NumberOfAgeGroups,
1..NumberOfHhldTypes,
1..NumberOfEthnicGrs] of single;
MarryNoChildren_ChildrenFraction,
MarryHasChildren_ChildrenFraction,
DivorceNoChildren_ChildrenFraction,
DivorceHasChildren_ChildrenFraction,
LeaveNestSingle_ChildrenFraction,
LeaveNestCouple_ChildrenFraction: single;
BaseForeignInmigrationRate,
BaseForeignOutmigrationRate,
BaseDomesticMigrationRate,
BaseRegionalMigrationRate:single;
var
ExogenousEffectOnMortalityRate,
ExogenousEffectOnFertilityRate,
ExogenousEffectOnMarriageRate,
ExogenousEffectOnDivorceRate,
ExogenousEffectOnEmptyNestRate,
ExogenousEffectOnLeaveWorkforceRate,
ExogenousEffectOnEnterWorkforceRate,
ExogenousEffectOnLeaveLowIncomeRate,
ExogenousEffectOnEnterLowIncomeRate,
ExogenousEffectOnLeaveHighIncomeRate,
ExogenousEffectOnEnterHighIncomeRate,
ExogenousEffectOnForeignInmigrationRate,
ExogenousEffectOnForeignOutmigrationRate,
ExogenousEffectOnDomesticMigrationRate,
ExogenousEffectOnRegionalMigrationRate,
ExogenousPopulationChangeRate1,
ExogenousPopulationChangeRate2,
ExogenousPopulationChangeRate3,
ExogenousPopulationChangeRate4,
ExogenousPopulationChangeRate5,
ExogenousPopulationChangeRate6,
ExogenousPopulationChangeRate7,
ExogenousPopulationChangeRate8,
ExogenousPopulationChangeRate9,
ExogenousPopulationChangeRate10,
ExogenousPopulationChangeRate11,
ExogenousPopulationChangeRate12,
SingleNoKidsEffectOnMoveTowardsUrbanAreas,
CoupleNoKidsEffectOnMoveTowardsUrbanAreas,
SingleWiKidsEffectOnMoveTowardsUrbanAreas,
CoupleWiKidsEffectOnMoveTowardsUrbanAreas,
LowIncomeEffectOnMoveTowardsUrbanAreas,
HighIncomeEffectOnMoveTowardsUrbanAreas,
LowIncomeEffectOnMortalityRate,
HighIncomeEffectOnMortalityRate,
LowIncomeEffectOnFertilityRate,
HighIncomeEffectOnFertilityRate,
LowIncomeEffectOnMarriageRate,
HighIncomeEffectOnMarriageRate,
LowIncomeEffectOnDivorceRate,
HighIncomeEffectOnDivorceRate,
LowIncomeEffectOnEmptyNestRate,
HighIncomeEffectOnEmptyNestRate,
LowIncomeEffectOnSpacePerHousehold,
HighIncomeEffectOnSpacePerHousehold,
WorkforceChangeDelay,
IncomeChangeDelay,
ForeignInmigrationDelay,
ForeignOutmigrationDelay,
DomesticMigrationDelay,
RegionalMigrationDelay,
ExogenousEffectOnGasolinePrice,
ExogenousEffectOnSharedCarFraction,
ExogenousEffectOnNoCarFraction,
ExogenousEffectOnWorkTripRate,
ExogenousEffectOnNonworkTripRate,
ExogenousEffectOnCarPassengerModeFraction,
ExogenousEffectOnTransitModeFraction,
ExogenousEffectOnWalkBikeModeFraction,
ExogenousEffectOnCarTripDistance,
ExogenousEffectOnAgeCohortVariables,
ExogenousEffectOnJobCreationRate,
ExogenousEffectOnJobLossRate,
ExogenousEffectOnJobMoveRate,
JobCreationDelay,
JobLossDelay,
JobMoveDelay,
ExogenousEmploymentChangeRate1A,
ExogenousEmploymentChangeRate2A,
ExogenousEmploymentChangeRate3A,
ExogenousEmploymentChangeRate4A,
ExogenousEmploymentChangeRate5A,
ExogenousEmploymentChangeRate6A,
ExogenousEmploymentChangeRate7A,
ExogenousEmploymentChangeRate8A,
ExogenousEmploymentChangeRate9A,
ExogenousEmploymentChangeRate10A,
ExogenousEmploymentChangeRate11A,
ExogenousEmploymentChangeRate12A,
ExogenousEmploymentChangeRate1B,
ExogenousEmploymentChangeRate2B,
ExogenousEmploymentChangeRate3B,
ExogenousEmploymentChangeRate4B,
ExogenousEmploymentChangeRate5B,
ExogenousEmploymentChangeRate6B,
ExogenousEmploymentChangeRate7B,
ExogenousEmploymentChangeRate8B,
ExogenousEmploymentChangeRate9B,
ExogenousEmploymentChangeRate10B,
ExogenousEmploymentChangeRate11B,
ExogenousEmploymentChangeRate12B,
ExogenousEmploymentChangeRate1C,
ExogenousEmploymentChangeRate2C,
ExogenousEmploymentChangeRate3C,
ExogenousEmploymentChangeRate4C,
ExogenousEmploymentChangeRate5C,
ExogenousEmploymentChangeRate6C,
ExogenousEmploymentChangeRate7C,
ExogenousEmploymentChangeRate8C,
ExogenousEmploymentChangeRate9C,
ExogenousEmploymentChangeRate10C,
ExogenousEmploymentChangeRate11C,
ExogenousEmploymentChangeRate12C,
ExogenousEffectOnResidentialSpacePerHousehold,
ExogenousEffectOnCommercialSpacePerJob,
ExogenousEffectOnLandProtection,
ResidentialSpaceDevelopmentDelay,
ResidentialSpaceReleaseDelay,
CommercialSpaceDevelopmentDelay,
CommercialSpaceReleaseDelay,
LandProtectionProcessDelay,
ExogenousEffectOnRoadCapacityAddition,
ExogenousEffectOnTransitCapacityAddition,
ExogenousEffectOnRoadCapacityPerLane,
ExogenousEffectOnTransitCapacityPerRoute,
RoadCapacityAdditionDelay,
RoadCapacityRetirementDelay,
TransitCapacityAdditionDelay,
TransitCapacityRetirementDelay,
ExternalJobDemandSupplyIndex,
ExternalCommercialSpaceDemandSupplyIndex,
ExternalResidentialSpaceDemandSupplyIndex,
ExternalRoadMileDemandSupplyIndex
:TimeStepArray;
JobDemand,
JobSupply,
JobDemandSupplyIndex,
ResidentialSpaceDemand,
ResidentialSpaceSupply,
ResidentialSpaceDemandSupplyIndex,
CommercialSpaceDemand,
CommercialSpaceSupply,
CommercialSpaceDemandSupplyIndex,
DevelopableSpaceDemand,
DevelopableSpaceSupply,
DevelopableSpaceDemandSupplyIndex,
RoadVehicleCapacityDemandSupplyIndex,
TransitPassengerCapacityDemandSupplyIndex
:AreaTypeArray;
WorkTripRoadMileDemand,
NonWorkTripRoadMileDemand,
RoadVehicleCapacityDemand,
RoadVehicleCapacitySupply:RoadSupplyArray;
WorkTripTransitMileDemand,
NonWorkTripTransitMileDemand,
TransitPassengerCapacityDemand,
TransitPassengerCapacitySupply:TransitSupplyArray;
BaseResidentialSpacePerPerson:array[1..NumberOfAreaTypes,1..NumberOfHhldTypes] of single;
BaseCommercialSpacePerJob:array[1..NumberOfAreaTypes,1..NumberOfEmploymentTypes] of single;
BaseRoadLaneCapacityPerHour:array[1..NumberOfAreaTypes,1..NumberOfRoadTypes] of single;
BaseTransitRouteCapacityPerHour:array[1..NumberOfAreaTypes,1..NumberOfTransitTypes] of single;
FractionOfDevelopableLandAllowedForResidential:array[1..NumberOfAreaTypes] of single;
FractionOfDevelopableLandAllowedForCommercial:array[1..NumberOfAreaTypes] of single;
WeightOfJobDemandSupplyIndexInEmployerAttractiveness,
WeightOfCommercialSpaceDemandSupplyIndexInEmployerAttractiveness,
WeightOfRoadMileDemandSupplyIndexInEmployerAttractiveness
:array[1..NumberOfAreaTypes,1..NumberOfEmploymentTypes] of single;
WeightOfJobDemandSupplyIndexInResidentAttractiveness,
WeightOfResidentialSpaceDemandSupplyIndexInResidentAttractiveness,
WeightOfRoadMileDemandSupplyIndexInResidentAttractiveness
:array[1..NumberOfAreaTypes,1..NumberOfHhldTypes] of single;
WorkTripPeakHourFraction,NonWorkTripPeakHourFraction:single;
DistanceFractionByRoadType:array[1..NumberOfAreaTypes,1..NumberOfODTypes,1..NumberOfRoadTypes] of single;
WorkTripAutoVehiclePADistribution,
WorkTripAutoPersonPADistribution,
WorkTripTransitPADistribution,
NonworkTripAutoVehiclePADistribution,
NonworkTripAutoPersonPADistribution,
NonworkTripTransitPADistribution,
CarTripAverageODDistance,
TransitTripAverageODDistance,
TransitRailPAFraction:array[1..NumberOfAreaTypes,1..NumberOfAreaTypes] of single;
ODThroughDistanceFraction:array[1..NumberOfAreaTypes,1..NumberOfAreaTypes,1..NumberOfAreaTypes] of single;
Const
BaseGasolinePrice = 3.00;
var
RunLabel,InputDirectory,OutputDirectory:string;
procedure ReadUserInputData;
{const
ScenarioUserInputsFilename = 'ScenarioUserInputs.dat';
DemographicInitialValuesFilename = 'DemographicInitialValues.dat';
EmploymentInitialValuesFilename = 'EmploymentInitialValues.dat';
LandUseInitialValuesFilename = 'LandUseInitialValues.dat';
TransportationSupplyInitialValuesFilename = 'TransportationSupplyInitialValues.dat';
TravelModelParameterFilename = 'TravelModelParameters.dat';
DemographicSeedMatrixFilename = 'DemographicSeedMatrix.dat';
DemographicTransitionRatesFilename = 'DemographicTransitionRates.dat';
}
var {inf:text;}
prefix:string[6]; x:string[1]; inString:string[80]; ctlFileName:string;
{indices}
Subregion,
ResAreaType,
WorkAreaType,
AreaType,
WorkerGr,
IncomeGr,
EthnicGr,
OldEthnicGr,
HhldType,
AgeGroup,
DensityType,
EmploymentType,
LandUseType,
RoadType,
TransitType,
ODType,
MigrationType,
TravelModelVariable,
TravelModelEquation,
point,
rate
: byte;
xval:single;
tempRate:array[1..15] of single;
function getExcelData(fcell,lcell:string):TDynFloat;
var datArray:TDynFloat; r,c:integer;
begin
datArray := ReadSpreadsheetRange(worksheet,fcell,lcell);
getExcelData:= datArray;
end;
procedure setTimeArray(var scenVar:TimeStepArray; tFirst,tLast:integer; fcell,lcell:string);
var t,ts,s,timeStepsPerValue:integer; value,previousValue:single;
begin
datArray := ReadSpreadsheetRange(worksheet,fcell,lcell);
if tFirst=tLast then begin
value:=datArray[0,0];
for ts:=0 to NumberOfTimeSteps do scenVar[ts]:=value;
end else begin
timeStepsPerValue:= round(NumberOfTimeSteps * 1.0 / (tLast-TFirst));
ts:=0;
for t:=tFirst to tLast do begin
value:=datArray[0,t-tFirst];
if t=0 then scenVar[ts]:=value else
{do straight line interpolation between user input values for each time step}
for s:=1 to timeStepsPerValue do begin
ts:=ts+1;
scenVar[ts]:=previousValue + s*1.0/timeStepsPerValue * (value - previousValue);
end;
previousValue:=value;
end;
end;
end;
var inf:text; ii,rr,cc:integer;
begin
{read control file}
if paramCount>0 then ctlFileName:= paramStr(1) else ctlFileName:='Baseline_Test46b.ctl';
{write(ctlFileName); readln;}
assign(inf,ctlFileName); reset(inf);
repeat
readln(inf,prefix,x,inString);
while inString[1]=' ' do inString:= copy(inString,2,length(inString)-1);
while inString[length(inString)]=' ' do inString:= copy(inString,1,length(inString)-1);
for ii:=1 to length(inString) do if inString[ii]=Chr(34) then inString[ii]:=Chr(32);
if prefix='RUNLAB' then RunLabel:=inString else
if prefix='INPDIR' then InputDirectory:=inString else
if prefix='OUTDIR' then OutputDirectory:=inString else
if prefix='REGION' then Region:=StrToInt(inString) else
if prefix='SCENAR' then Scenario:=StrToInt(inString);
until eof(inf);
{if InputDirectory[length(InputDirectory)]<>'\' then InputDirectory:=InputDirectory+'\';}
if OutputDirectory[length(OutputDirectory)]<>'\' then OutputDirectory:=OutputDirectory+'\';
workbook := TsWorkbook.Create;
workbook.ReadFromFile(InputDirectory);
{read demographic seed matrix}
worksheet := workbook.GetWorksheetByName('Demographic seed matrix');
datArray := getExcelData('G6','W1805');
rr:=0;
for DensityType:=1 to NumberOfDensityTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes + 1 do begin
if HhldType<=NumberOfHhldTypes then begin {totals row from SPSS, left in for convenience}
for AgeGroup:=1 to NumberOfAgeGroups do
for AreaType:=1 to NumberOfAreaTypes do if AreaTypeDensity[AreaType]=DensityType then
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][0]:=
datArray[rr,AgeGroup-1];
end;
rr:=rr+1; {next row}
end;
{read demographic sector initial values}
worksheet := workbook.GetWorksheetByName('Demographic initial values');
datArray := getExcelData('B6','D22');
for Subregion:=1 to NumberOfSubregions do
for AgeGroup:=1 to NumberOfAgeGroups do
AgeGroupTargetMarginals[Subregion,AgeGroup]:=datArray[AgeGroup-1,Subregion-1];
datArray := ReadSpreadsheetRange(worksheet,'B26','D29');
for Subregion:=1 to NumberOfSubregions do
for HhldType:=1 to NumberOfHhldTypes do
HhldTypeTargetMarginals[Subregion,HhldType]:=datArray[HhldType-1,Subregion-1];
datArray := getExcelData('B33','D44');
for Subregion:=1 to NumberOfSubregions do
for EthnicGr:=1 to NumberOfEthnicGrs do
EthnicGrTargetMarginals[Subregion,EthnicGr]:=datArray[EthnicGr-1,Subregion-1];
datArray := getExcelData('B48','D50');
for Subregion:=1 to NumberOfSubregions do
for IncomeGr:=1 to NumberOfIncomeGrs do
IncomeGrTargetMarginals[Subregion,IncomeGr]:=datArray[IncomeGr-1,Subregion-1];
datArray := getExcelData('B54','D55');
for Subregion:=1 to NumberOfSubregions do
for WorkerGr:=1 to NumberOfWorkerGrs do
WorkerGrTargetMarginals[Subregion,WorkerGr]:=datArray[WorkerGr-1,Subregion-1];
datArray := getExcelData('B59','D70');
for Subregion:=1 to NumberOfSubregions do
for AreaType:=1 to NumberOfAreaTypes do
AreaTypeTargetMarginals[Subregion,AreaType]:=datArray[AreaType-1,Subregion-1];
{read employment sector initial values}
worksheet := workbook.GetWorksheetByName('Employment initial values');
datArray := getExcelData('B5','D16');
for AreaType:=1 to NumberOfAreaTypes do
for EmploymentType:=1 to NumberOfEmploymentTypes do begin
Jobs[AreaType][EmploymentType][0]:=datArray[AreaType-1,EmploymentType-1];
end;
setTimeArray(JobCreationDelay,0,0,'B26','B26');
setTimeArray(JobLossDelay,0,0,'B27','B27');
setTimeArray(JobMoveDelay,0,0,'B28','B28');
datArray := getExcelData('B33','D47');
rr:=0;
for DensityType:=1 to NumberOfDensityTypes do
for EmploymentType:=1 to NumberOfEmploymentTypes do begin
for AreaType:=1 to NumberOfAreaTypes do if AreaTypeDensity[AreaType]=DensityType then
WeightOfJobDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]:=datArray[rr,0];
for AreaType:=1 to NumberOfAreaTypes do if AreaTypeDensity[AreaType]=DensityType then
WeightOfCommercialSpaceDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]:=datArray[rr,1];
for AreaType:=1 to NumberOfAreaTypes do if AreaTypeDensity[AreaType]=DensityType then
WeightOfRoadMileDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]:=datArray[rr,2];
rr:=rr+1;
end;
datArray := getExcelData('A51','D71');
for point:=0 to EffectCurveIntervals do begin
xval:=datArray[point,0];
C_EffectOfJobDemandSupplyIndexOnEmployerAttractiveness[point]:=datArray[point,1];
C_EffectOfCommercialSpaceDemandSupplyIndexOnEmployerAttractiveness[point]:=datArray[point,2];
C_EffectOfRoadMileDemandSupplyIndexOnEmployerAttractiveness[point]:=datArray[point,3];
if point=0 then begin
C_EffectOfJobDemandSupplyIndexOnEmployerAttractiveness[-2]:=xval;
C_EffectOfCommercialSpaceDemandSupplyIndexOnEmployerAttractiveness[-2]:=xval;
C_EffectOfRoadMileDemandSupplyIndexOnEmployerAttractiveness[-2]:=xval;
end else
if point=EffectCurveIntervals then begin
C_EffectOfJobDemandSupplyIndexOnEmployerAttractiveness[-1]:=xval;
C_EffectOfCommercialSpaceDemandSupplyIndexOnEmployerAttractiveness[-1]:=xval;
C_EffectOfRoadMileDemandSupplyIndexOnEmployerAttractiveness[-1]:=xval;
end;
end;
{read land use sector initial values}
worksheet := workbook.GetWorksheetByName('Land use initial values');
datArray := getExcelData('B4','E15');
for AreaType:=1 to NumberOfAreaTypes do
for LandUseType:=1 to NumberOfLandUseTypes do begin
Land[AreaType][LandUseType][0]:=datArray[AreaType-1,LandUseType-1];
end;
setTimeArray(ResidentialSpaceDevelopmentDelay,0,0,'B18','B18');
setTimeArray(ResidentialSpaceReleaseDelay,0,0,'B19','B19');
setTimeArray(CommercialSpaceDevelopmentDelay,0,0,'B20','B20');
setTimeArray(CommercialSpaceReleaseDelay,0,0,'B21','B21');
setTimeArray(LandProtectionProcessDelay,0,0,'B22','B22');
datArray := getExcelData('B26','E37');
for AreaType:=1 to NumberOfAreaTypes do begin
for HhldType:=1 to NumberOfHhldTypes do
BaseResidentialSpacePerPerson[AreaType][HhldType]:=datArray[AreaType-1,HhldType-1];
end;
datArray := getExcelData('B41','D52');
for AreaType:=1 to NumberOfAreaTypes do begin
for EmploymentType:=1 to NumberOfEmploymentTypes do
BaseCommercialSpacePerJob[AreaType][EmploymentType]:=datArray[AreaType-1,EmploymentType-1];
end;
datArray := getExcelData('B56','C67');
for AreaType:=1 to NumberOfAreaTypes do begin
FractionOfDevelopableLandAllowedForCommercial[AreaType]:=datArray[AreaType-1,0];
FractionOfDevelopableLandAllowedForResidential[AreaType]:=datArray[AreaType-1,1];
end;
{read transportation supply sector initial values}
worksheet := workbook.GetWorksheetByName('Transportation initial values');
datArray := getExcelData('B4','F15');
for AreaType:=1 to NumberOfAreaTypes do begin
for RoadType:=1 to NumberOfRoadTypes do
RoadLaneMiles[AreaType][RoadType][0]:=datArray[AreaType-1,RoadType-1];
for TransitType:=1 to NumberOfTransitTypes do
TransitRouteMiles[AreaType][TransitType][0]:=datArray[AreaType-1,NumberOfRoadTypes+TransitType-1];
end;
setTimeArray(RoadCapacityAdditionDelay,0,0,'B18','B18');
setTimeArray(RoadCapacityRetirementDelay,0,0,'B19','B19');
setTimeArray(TransitCapacityAdditionDelay,0,0,'B20','B20');
setTimeArray(TransitCapacityRetirementDelay,0,0,'B21','B21');
datArray := getExcelData('B25','D36');
for AreaType:=1 to NumberOfAreaTypes do begin
for RoadType:=1 to NumberOfRoadTypes do
BaseRoadLaneCapacityPerHour[AreaType][RoadType]:=datArray[AreaType-1,RoadType-1];
end;
datArray := getExcelData('B40','C51');
for AreaType:=1 to NumberOfAreaTypes do begin
for TransitType:=1 to NumberOfTransitTypes do
BaseTransitRouteCapacityPerHour[AreaType][TransitType]:=datArray[AreaType-1,TransitType-1];
end;
datArray := getExcelData('B54','B55');
WorkTripPeakHourFraction:=datArray[0,0];
NonWorkTripPeakHourFraction:=datArray[1,0];
datArray := getExcelData('B58','J69');
for AreaType:=1 to NumberOfAreaTypes do begin
cc:=0;
for ODType:=1 to NumberOfODTypes do
for RoadType:=1 to NumberOfRoadTypes do begin
DistanceFractionByRoadType[AreaType][ODType][RoadType]:=datArray[AreaType-1,cc];
cc:=cc+1;
end;
end;
datArray := getExcelData('B72','M83');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
WorkTripAutoVehiclePADistribution[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
end;
datArray := getExcelData('B86','M97');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
WorkTripAutoPersonPADistribution[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
WorkplaceDistribution[ResAreaType][AreaType][0]:=WorkTripAutoPersonPADistribution[ResAreaType][AreaType];
end;
datArray := getExcelData('B100','M111');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
WorkTripTransitPADistribution[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
end;
datArray := getExcelData('B114','M125');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
NonworkTripAutoVehiclePADistribution[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
end;
datArray := getExcelData('B128','M139');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
NonworkTripAutoPersonPADistribution[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
end;
datArray := getExcelData('B142','M153');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
NonworkTripTransitPADistribution[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
end;
datArray := getExcelData('B156','M167');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
CarTripAverageODDistance[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
end;
datArray := getExcelData('B170','M181');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
TransitTripAverageODDistance[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
end;
datArray := getExcelData('B184','M195');
for ResAreaType:=1 to NumberOfAreaTypes do
for AreaType:=1 to NumberOfAreaTypes do begin
TransitRailPAFraction[ResAreaType][AreaType]:=datArray[ResAreaType-1,AreaType-1];
end;
datArray := getExcelData('B198','M275');
rr:=0;
for ResAreaType:=1 to NumberOfAreaTypes do
for WorkAreaType:=ResAreaType to NumberOfAreaTypes do begin
for AreaType:=1 to NumberOfAreaTypes do begin
ODThroughDistanceFraction[ResAreaType][WorkAreaType][AreaType]:=datArray[rr,AreaType-1];
ODThroughDistanceFraction[WorkAreaType][ResAreaType][AreaType]:=datArray[rr,AreaType-1];
end;
rr:=rr+1;
end;
{read demographic base demographic transition rates}
worksheet := workbook.GetWorksheetByName('Demographic transition rates');
datArray := getExcelData('D5','R412');
rr:=0;
for AgeGroup:=1 to NumberOfAgeGroups do
for OldEthnicGr:=1 to OldNumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do begin
for rate:=1 to 15 do tempRate[rate]:=datArray[rr,rate-1];
rr:=rr+1;
for EthnicGr:=1 to NumberOfEthnicGrs do if OldEthnicGroup[EthnicGr]=OldEthnicGr then begin
BaseAverageHouseholdSize[AgeGroup][HHldType][EthnicGr]:=tempRate[1];
BaseMortalityRate[AgeGroup][HHldType][EthnicGr]:=tempRate[2];
BaseFertilityRate[AgeGroup][HHldType][EthnicGr]:=tempRate[3];
BaseMarriageRate[AgeGroup][HHldType][EthnicGr]:=tempRate[4];
BaseDivorceRate[AgeGroup][HHldType][EthnicGr]:=tempRate[5];
BaseLeaveNestSingleRate[AgeGroup][HHldType][EthnicGr]:=tempRate[6];
BaseLeaveNestCoupleRate[AgeGroup][HHldType][EthnicGr]:=tempRate[7];
BaseEmptyNestRate[AgeGroup][HHldType][EthnicGr]:=tempRate[8];
BaseEnterLowIncomeRate[AgeGroup][HHldType][EthnicGr]:=tempRate[9];
BaseLeaveLowIncomeRate[AgeGroup][HHldType][EthnicGr]:=tempRate[10];
BaseEnterHighIncomeRate[AgeGroup][HHldType][EthnicGr]:=tempRate[11];
BaseLeaveHighIncomeRate[AgeGroup][HHldType][EthnicGr]:=tempRate[12];
BaseEnterWorkforceRate[AgeGroup][HHldType][EthnicGr]:=tempRate[13];
BaseLeaveWorkforceRate[AgeGroup][HHldType][EthnicGr]:=tempRate[14];
MigrationRateMultiplier[AgeGroup][HHldType][EthnicGr]:=tempRate[15];
end;
end;
setTimeArray(WorkforceChangeDelay,0,0,'B415','B415');
setTimeArray(IncomeChangeDelay,0,0,'B416','B416');
setTimeArray(ForeignInmigrationDelay,0,0,'B417','B417');
setTimeArray(ForeignOutmigrationDelay,0,0,'B418','B418');
setTimeArray(DomesticMigrationDelay,0,0,'B419','B419');
setTimeArray(RegionalMigrationDelay,0,0,'B420','B420');
datArray := getExcelData('D424','D429');
MarryNoChildren_ChildrenFraction:=datArray[0,0];
MarryHasChildren_ChildrenFraction:=datArray[1,0];
DivorceNoChildren_ChildrenFraction:=datArray[2,0];
DivorceHasChildren_ChildrenFraction:=datArray[3,0];
LeaveNestSingle_ChildrenFraction:=datArray[4,0];
LeaveNestCouple_ChildrenFraction:=datArray[5,0];
datArray := getExcelData('B432','B435');
BaseForeignInmigrationRate:=datArray[0,0];
BaseForeignOutmigrationRate:=datArray[1,0];
BaseDomesticMigrationRate:=datArray[2,0];
BaseRegionalMigrationRate:=datArray[3,0];
datArray := getExcelData('B441','D455');
rr:=0;
for DensityType:=1 to NumberOfDensityTypes do
for MigrationType:=1 to NumberOfMigrationTypes do begin
for AreaType:=1 to NumberOfAreaTypes do if AreaTypeDensity[AreaType]=DensityType then
WeightOfJobDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]:=datArray[rr,MigrationType-1];
for AreaType:=1 to NumberOfAreaTypes do if AreaTypeDensity[AreaType]=DensityType then
WeightOfResidentialSpaceDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]:=datArray[rr,MigrationType-1];
for AreaType:=1 to NumberOfAreaTypes do if AreaTypeDensity[AreaType]=DensityType then
WeightOfRoadMileDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]:=datArray[rr,MigrationType-1];
rr:=rr+1;
end;
datArray := getExcelData('A459','D479');
for point:=0 to EffectCurveIntervals do begin
xval:=datArray[point,0];
C_EffectOfJobDemandSupplyIndexOnResidentAttractiveness[point]:=datArray[point,1];
C_EffectOfResidentialSpaceDemandSupplyIndexOnResidentAttractiveness[point]:=datArray[point,2];
C_EffectOfRoadMileDemandSupplyIndexOnResidentAttractiveness[point]:=datArray[point,3];
if point=0 then begin
C_EffectOfJobDemandSupplyIndexOnResidentAttractiveness[-2]:=xval;
C_EffectOfResidentialSpaceDemandSupplyIndexOnResidentAttractiveness[-2]:=xval;
C_EffectOfRoadMileDemandSupplyIndexOnResidentAttractiveness[-2]:=xval;
end else
if point=EffectCurveIntervals then begin
C_EffectOfJobDemandSupplyIndexOnResidentAttractiveness[-1]:=xval;
C_EffectOfResidentialSpaceDemandSupplyIndexOnResidentAttractiveness[-1]:=xval;
C_EffectOfRoadMileDemandSupplyIndexOnResidentAttractiveness[-1]:=xval;
end;
end;
{ read travel demand model parameters}
worksheet := workbook.GetWorksheetByName('Travel behavior models');
datArray := getExcelData('B6','R61');
for TravelModelVariable:=1 to NumberOfTravelModelVariables do begin
for TravelModelEquation:=1 to NumberOfTravelModelEquations do
TravelModelParameter[TravelModelEquation][TravelModelVariable]:=
datArray[TravelModelVariable-1,TravelModelEquation-1];
end;
{read Exogenous user inputs}
worksheet := workbook.GetWorksheetByIndex(Scenario);
{base year}
datArray := getExcelData('B2','B2');
Year:= datArray[0,0];
{demographic sector}
setTimeArray(ExogenousEffectOnMortalityRate,0,10, 'B4','L4');
setTimeArray(ExogenousEffectOnFertilityRate,0,10, 'B5','L5');
setTimeArray(ExogenousEffectOnMarriageRate,0,10, 'B6','L6');
setTimeArray(ExogenousEffectOnDivorceRate,0,10, 'B7','L7');
setTimeArray(ExogenousEffectOnEmptyNestRate,0,10, 'B8','L8');
setTimeArray(ExogenousEffectOnLeaveWorkforceRate,0,10, 'B9','L9');
setTimeArray(ExogenousEffectOnEnterWorkforceRate,0,10, 'B10','L10');
setTimeArray(ExogenousEffectOnLeaveLowIncomeRate,0,10, 'B11','L11');
setTimeArray(ExogenousEffectOnEnterLowIncomeRate,0,10, 'B12','L12');
setTimeArray(ExogenousEffectOnLeaveHighIncomeRate,0,10, 'B13','L13');
setTimeArray(ExogenousEffectOnEnterHighIncomeRate,0,10, 'B14','L14');
setTimeArray(ExogenousEffectOnForeignInmigrationRate,0,10,'B15','L15');
setTimeArray(ExogenousEffectOnForeignOutmigrationRate,0,10,'B16','L16');
setTimeArray(ExogenousEffectOnDomesticMigrationRate,0,10, 'B17','L17');
setTimeArray(ExogenousEffectOnRegionalMigrationRate,0,10, 'B18','L18');
setTimeArray(ExogenousPopulationChangeRate1,0,10, 'B19','L19');
setTimeArray(ExogenousPopulationChangeRate2,0,10, 'B20','L20');
setTimeArray(ExogenousPopulationChangeRate3,0,10, 'B21','L21');
setTimeArray(ExogenousPopulationChangeRate4,0,10, 'B22','L22');
setTimeArray(ExogenousPopulationChangeRate5,0,10, 'B23','L23');
setTimeArray(ExogenousPopulationChangeRate6,0,10, 'B24','L24');
setTimeArray(ExogenousPopulationChangeRate7,0,10, 'B25','L25');
setTimeArray(ExogenousPopulationChangeRate8,0,10, 'B26','L26');
setTimeArray(ExogenousPopulationChangeRate9,0,10, 'B27','L27');
setTimeArray(ExogenousPopulationChangeRate10,0,10, 'B28','L28');
setTimeArray(ExogenousPopulationChangeRate11,0,10, 'B29','L29');
setTimeArray(ExogenousPopulationChangeRate12,0,10, 'B30','L30');
setTimeArray(SingleNoKidsEffectOnMoveTowardsUrbanAreas,0,10, 'B31','L31');
setTimeArray(CoupleNoKidsEffectOnMoveTowardsUrbanAreas,0,10, 'B32','L32');
setTimeArray(SingleWiKidsEffectOnMoveTowardsUrbanAreas,0,10, 'B33','L33');
setTimeArray(CoupleWiKidsEffectOnMoveTowardsUrbanAreas,0,10, 'B34','L34');
setTimeArray(LowIncomeEffectOnMoveTowardsUrbanAreas,0,10, 'B35','L35');
setTimeArray(HighIncomeEffectOnMoveTowardsUrbanAreas,0,10,'B36','L36');
setTimeArray(LowIncomeEffectOnMortalityRate,0,10, 'B37','L37');
setTimeArray(HighIncomeEffectOnMortalityRate,0,10, 'B38','L38');
setTimeArray(LowIncomeEffectOnFertilityRate,0,10, 'B39','L39');
setTimeArray(HighIncomeEffectOnFertilityRate,0,10, 'B40','L40');
setTimeArray(LowIncomeEffectOnMarriageRate,0,10, 'B41','L41');
setTimeArray(HighIncomeEffectOnMarriageRate,0,10, 'B42','L42');
setTimeArray(LowIncomeEffectOnDivorceRate,0,10, 'B43','L43');
setTimeArray(HighIncomeEffectOnDivorceRate,0,10, 'B44','L44');
setTimeArray(LowIncomeEffectOnEmptyNestRate,0,10, 'B45','L45');
setTimeArray(HighIncomeEffectOnEmptyNestRate,0,10, 'B46','L46');
setTimeArray(LowIncomeEffectOnSpacePerHousehold,0,10, 'B47','L47');
setTimeArray(HighIncomeEffectOnSpacePerHousehold,0,10, 'B48','L48');
{travel behavior subsector}
setTimeArray(ExogenousEffectOnGasolinePrice,0,10, 'B51','L51');
setTimeArray(ExogenousEffectOnSharedCarFraction,0,10, 'B52','L52');
setTimeArray(ExogenousEffectOnNoCarFraction,0,10, 'B53','L53');
setTimeArray(ExogenousEffectOnWorkTripRate,0,10, 'B54','L54');
setTimeArray(ExogenousEffectOnNonworkTripRate,0,10, 'B55','L55');
setTimeArray(ExogenousEffectOnCarPassengerModeFraction,0,10,'B56','L56');
setTimeArray(ExogenousEffectOnTransitModeFraction,0,10, 'B57','L57');
setTimeArray(ExogenousEffectOnWalkBikeModeFraction,0,10, 'B58','L58');
setTimeArray(ExogenousEffectOnCarTripDistance,0,10, 'B59','L59');
setTimeArray(ExogenousEffectOnAgeCohortVariables,0,10, 'B60','L60');
{employment sector}
setTimeArray(ExogenousEffectOnJobCreationRate,0,10, 'B63','L63');
setTimeArray(ExogenousEffectOnJobLossRate,0,10, 'B64','L64');
setTimeArray(ExogenousEffectOnJobMoveRate,0,10, 'B65','L65');
setTimeArray(ExogenousEmploymentChangeRate1A,0,10, 'B66','L66');
setTimeArray(ExogenousEmploymentChangeRate1B,0,10, 'B67','L67');
setTimeArray(ExogenousEmploymentChangeRate1C,0,10, 'B68','L68');
setTimeArray(ExogenousEmploymentChangeRate2A,0,10, 'B69','L69');
setTimeArray(ExogenousEmploymentChangeRate2B,0,10, 'B70','L70');
setTimeArray(ExogenousEmploymentChangeRate2C,0,10, 'B71','L71');
setTimeArray(ExogenousEmploymentChangeRate3A,0,10, 'B72','L72');
setTimeArray(ExogenousEmploymentChangeRate3B,0,10, 'B73','L73');
setTimeArray(ExogenousEmploymentChangeRate3C,0,10, 'B74','L74');
setTimeArray(ExogenousEmploymentChangeRate4A,0,10, 'B75','L75');
setTimeArray(ExogenousEmploymentChangeRate4B,0,10, 'B76','L76');
setTimeArray(ExogenousEmploymentChangeRate4C,0,10, 'B77','L77');
setTimeArray(ExogenousEmploymentChangeRate5A,0,10, 'B78','L78');
setTimeArray(ExogenousEmploymentChangeRate5B,0,10, 'B79','L79');
setTimeArray(ExogenousEmploymentChangeRate5C,0,10, 'B80','L80');
setTimeArray(ExogenousEmploymentChangeRate6A,0,10, 'B81','L81');
setTimeArray(ExogenousEmploymentChangeRate6B,0,10, 'B82','L82');
setTimeArray(ExogenousEmploymentChangeRate6C,0,10, 'B83','L83');
setTimeArray(ExogenousEmploymentChangeRate7A,0,10, 'B84','L84');
setTimeArray(ExogenousEmploymentChangeRate7B,0,10, 'B85','L85');
setTimeArray(ExogenousEmploymentChangeRate7C,0,10, 'B86','L86');
setTimeArray(ExogenousEmploymentChangeRate8A,0,10, 'B87','L87');
setTimeArray(ExogenousEmploymentChangeRate8B,0,10, 'B88','L88');
setTimeArray(ExogenousEmploymentChangeRate8C,0,10, 'B89','L89');
setTimeArray(ExogenousEmploymentChangeRate9A,0,10, 'B90','L90');
setTimeArray(ExogenousEmploymentChangeRate9B,0,10, 'B91','L91');
setTimeArray(ExogenousEmploymentChangeRate9C,0,10, 'B92','L92');
setTimeArray(ExogenousEmploymentChangeRate10A,0,10, 'B93','L93');
setTimeArray(ExogenousEmploymentChangeRate10B,0,10, 'B94','L94');
setTimeArray(ExogenousEmploymentChangeRate10C,0,10, 'B95','L95');
setTimeArray(ExogenousEmploymentChangeRate11A,0,10, 'B96','L96');
setTimeArray(ExogenousEmploymentChangeRate11B,0,10, 'B97','L97');
setTimeArray(ExogenousEmploymentChangeRate11C,0,10, 'B98','L98');
setTimeArray(ExogenousEmploymentChangeRate12A,0,10, 'B99','L99');
setTimeArray(ExogenousEmploymentChangeRate12B,0,10, 'B100','L100');
setTimeArray(ExogenousEmploymentChangeRate12C,0,10, 'B101','L101');
{land use sector}
setTimeArray(ExogenousEffectOnResidentialSpacePerHousehold,0,10,'B104','L104');
setTimeArray(ExogenousEffectOnCommercialSpacePerJob,0,10, 'B105','L105');
setTimeArray(ExogenousEffectOnLandProtection,0,10, 'B106','L106');
{transport supply sector}
setTimeArray(ExogenousEffectOnRoadCapacityAddition,0,10, 'B109','L109');
setTimeArray(ExogenousEffectOnTransitCapacityAddition,0,10,'B110','L110');
setTimeArray(ExogenousEffectOnRoadCapacityPerLane,0,10, 'B111','L111');
setTimeArray(ExogenousEffectOnTransitCapacityPerRoute,0,10,'B112','L112');
{external indices}
setTimeArray(ExternalJobDemandSupplyIndex,0,10, 'B115','L115');
setTimeArray(ExternalCommercialSpaceDemandSupplyIndex,0,10, 'B116','L116');
setTimeArray(ExternalResidentialSpaceDemandSupplyIndex,0,10,'B117','L117');
setTimeArray(ExternalRoadMileDemandSupplyIndex,0,10, 'B118','L118');
end;
procedure CalculateDemographicMarginals (Demvar:integer; timeStep:integer);
var cellValue:single;
{indices}
AreaType,
WorkerGr,
IncomeGr,
EthnicGr,
HhldType,
AgeGroup,
LoIndex,HiIndex,DemIndex: byte;
{subprocedure to recalculate the marginals}
begin
if Demvar=0 then LoIndex:=1 else LoIndex:=Demvar;
if Demvar=0 then HiIndex:=NumberOfSubregions else HiIndex:=Demvar;
{empty the marginals}
for DemIndex:=LoIndex to HiIndex do begin
for AgeGroup:=0 to NumberOfAgeGroups do AgeGroupMarginals[DemIndex][AgeGroup][timeStep]:=0;
for HhldType:=1 to NumberOfHhldTypes do HhldTypeMarginals[DemIndex][HhldType][timeStep]:=0;
for EthnicGr:=1 to NumberOfEthnicGrs do EthnicGrMarginals[DemIndex][EthnicGr][timeStep]:=0;
for IncomeGr:=1 to NumberOfIncomeGrs do IncomeGrMarginals[DemIndex][IncomeGr][timeStep]:=0;
for WorkerGr:=1 to NumberOfWorkerGrs do WorkerGrMarginals[DemIndex][WorkerGr][timeStep]:=0;
for AreaType:=1 to NumberOfAreaTypes do AreaTypeMarginals[DemIndex][AreaType][timeStep]:=0;
end;
{loop on all cells and accumulate marginals}
for AreaType:=1 to NumberOfAreaTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do
for AgeGroup:=1 to NumberOfAgeGroups do begin
if Demvar<=1 then cellValue:=Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=2 then cellValue:=AgeingOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=3 then cellValue:=DeathsOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=4 then cellValue:=BirthsFrom[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=5 then cellValue:=MarriagesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=6 then cellValue:=DivorcesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=7 then cellValue:=FirstChildOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=8 then cellValue:=EmptyNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=9 then cellValue:=LeaveNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=10 then cellValue:=WorkerStatusOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=11 then cellValue:=IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=12 then cellValue:=AcculturationOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=13 then cellValue:=AgeingIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=14 then cellValue:=BirthsIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=15 then cellValue:=MarriagesIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=16 then cellValue:=DivorcesIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=17 then cellValue:=FirstChildIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=18 then cellValue:=EmptyNestIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=19 then cellValue:=LeaveNestIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=20 then cellValue:=WorkerStatusIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=21 then cellValue:=IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=22 then cellValue:=AcculturationIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
if Demvar=23 then cellValue:=ForeignInmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=24 then cellValue:=ForeignOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=25 then cellValue:=DomesticInmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=26 then cellValue:=DomesticOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=27 then cellValue:=RegionalInmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=28 then cellValue:=RegionalOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=29 then cellValue:=OwnCar[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=30 then cellValue:=ShareCar[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=31 then cellValue:=NoCar[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=32 then cellValue:=WorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=33 then cellValue:=NonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=34 then cellValue:=CarDriverWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=35 then cellValue:=CarPassengerWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=36 then cellValue:=TransitWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=37 then cellValue:=WalkBikeWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=38 then cellValue:=CarDriverWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=39 then cellValue:=CarPassengerWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=40 then cellValue:=TransitWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=41 then cellValue:=CarDriverNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=42 then cellValue:=CarPassengerNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=43 then cellValue:=TransitNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=44 then cellValue:=WalkBikeNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=45 then cellValue:=CarDriverNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=46 then cellValue:=CarPassengerNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
if Demvar=47 then cellValue:=TransitNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] else
begin end;
if Demvar=0 then DemIndex:=AreaTypeSubregion[areaType] else DemIndex:=Demvar;
AgeGroupMarginals[DemIndex][ 0 ][timeStep]:=AgeGroupMarginals[DemIndex][ 0 ][timeStep] + cellValue;
AgeGroupMarginals[DemIndex][AgeGroup][timeStep]:=AgeGroupMarginals[DemIndex][AgeGroup][timeStep] + cellValue;
HhldTypeMarginals[DemIndex][HhldType][timeStep]:=HhldTypeMarginals[DemIndex][HhldType][timeStep] + cellValue;
EthnicGrMarginals[DemIndex][EthnicGr][timeStep]:=EthnicGrMarginals[DemIndex][EthnicGr][timeStep] + cellValue;
IncomeGrMarginals[DemIndex][IncomeGr][timeStep]:=IncomeGrMarginals[DemIndex][IncomeGr][timeStep] + cellValue;
WorkerGrMarginals[DemIndex][WorkerGr][timeStep]:=WorkerGrMarginals[DemIndex][WorkerGr][timeStep] + cellValue;
AreaTypeMarginals[DemIndex][AreaType][timeStep]:=AreaTypeMarginals[DemIndex][AreaType][timeStep] + cellValue;
end; {cells}
end; {CalculateDemographicMarginals}
{Procedure to initialize the Population for the region}
procedure InitializePopulation;
const
IPFIterations = 15;
var
demVar,iteration,dimension:integer;
current,target:double;
{indices}
Subregion,
AreaType,
WorkerGr,
IncomeGr,
EthnicGr,
HhldType,
AgeGroup: byte;
begin {InitializePopulation}
demVar := 0; {population by subregion}
{perform IPF to get the marginals to match the trarget marginals for the region}
{perform the specified number of iterations}
for iteration:=1 to IPFIterations do begin
{loop on each marginal dimension}
for dimension:=1 to NumberOfDemographicDimensions do begin
{(re)calculate the current population marginals}
CalculateDemographicMarginals(demVar,0);
{loop on all the cells and adjust the current cell values to match the target marginal on the dimension}
for AreaType:=1 to NumberOfAreaTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do
for AgeGroup:=1 to NumberOfAgeGroups do begin
Subregion:=AreaTypeSubregion[areaType];
if dimension=1 then begin current:=AreaTypeMarginals[Subregion][AreaType][0]; target:=AreaTypeTargetMarginals[Subregion][AreaType]; end else
if dimension=2 then begin current:=AgeGroupMarginals[Subregion][AgeGroup][0]; target:=AgeGroupTargetMarginals[Subregion][AgeGroup]; end else
if dimension=3 then begin current:=HhldTypeMarginals[Subregion][HhldType][0]; target:=HhldTypeTargetMarginals[Subregion][HhldType]; end else
if dimension=4 then begin current:=EthnicGrMarginals[Subregion][EthnicGr][0]; target:=EthnicGrTargetMarginals[Subregion][EthnicGr]; end else
if dimension=5 then begin current:=IncomeGrMarginals[Subregion][IncomeGr][0]; target:=IncomeGrTargetMarginals[Subregion][IncomeGr]; end else
if dimension=6 then begin current:=WorkerGrMarginals[Subregion][WorkerGr][0]; target:=WorkerGrTargetMarginals[Subregion][WorkerGr]; end;
if current>0 then begin
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][0]:=
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][0] * target/current;
{writeln(iteration:2,dimension:2,target:10:0,current:10:0,target/current:8:3);}
end;
end; {cells}
{readln;}
end; {dimensions}
end; {iterations}
demVar:=1;
CalculateDemographicMarginals(demVar,0);
end; {InitializePopulation}
procedure CalculateDemographicFeedbacks(timeStep:integer);
var
{indices}
WorkAreaType,
DestAreaType,
RoadAreaType,
ODType,
RoadType,
TransitType,
AreaType,
WorkerGr,
IncomeGr,
EthnicGr,
HhldType,
AgeGroup: byte;
SpacePerPerson, residents, commuters, autotrips, transittrips, tdistance, rdistance: single;
begin
for AreaType:=1 to NumberOfAreaTypes do begin
JobDemand[AreaType][timeStep]:=0;
ResidentialSpaceDemand[AreaType][timeStep]:=0;
for RoadType:=1 to NumberOfRoadTypes do begin
WorkTripRoadMileDemand[AreaType][RoadType][timeStep]:=0;
NonWorkTripRoadMileDemand[AreaType][RoadType][timeStep]:=0;
end;
for TransitType:=1 to NumberOfTransitTypes do begin
WorkTripTransitMileDemand[AreaType][TransitType][timeStep]:=0;
NonWorkTripTransitMileDemand[AreaType][TransitType][timeStep]:=0;
end;
for WorkAreaType:=1 to NumberOfAreaTypes do
WorkplaceDistribution[AreaType][WorkAreaType][timeStep]:=
WorkplaceDistribution[AreaType][WorkAreaType][timeStep-1];
end;
for AreaType:=1 to NumberOfAreaTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do
for AgeGroup:=1 to NumberOfAgeGroups do begin
residents:=Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1];
if residents>0 then begin
SpacePerPerson:=
BaseResidentialSpacePerPerson[AreaType][HHldType]/(5280.0*5280) {sq feet to sq miles}
* (Dummy(IncomeGr,1)*LowIncomeEffectOnSpacePerHousehold[timeStep]
+Dummy(IncomeGr,2)* 1
+Dummy(IncomeGr,3)*HighIncomeEffectOnSpacePerHousehold[timeStep])
* ExogenousEffectOnResidentialSpacePerHousehold[timeStep];
ResidentialSpaceDemand[AreaType][timeStep]:=ResidentialSpaceDemand[AreaType][timeStep]
+ (residents * SpacePerPerson);
if (WorkerGr=1) {worker} then begin
autoTrips:=CarDriverWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1];
transitTrips:=TransitWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1];
for WorkAreaType:=1 to NumberOfAreaTypes do begin
commuters := residents * WorkplaceDistribution[AreaType][WorkAreaType][timeStep];
JobDemand[WorkAreaType][timeStep]:=JobDemand[WorkAreaType][timeStep]
+ commuters;
{miles by area type - work auto trips}
for RoadAreaType:=1 to NumberOfAreaTypes do begin
tdistance:= CarTripAverageODDistance[AreaType][WorkAreaType]
* ODThroughDistanceFraction[AreaType][WorkAreaType][RoadAreaType];
if tdistance>0 then
for RoadType:=1 to NumberOfRoadTypes do begin
if (RoadType=AreaType) and (RoadType=WorkAreaType) then ODType:=1 else
if (RoadType=AreaType) or (RoadType=WorkAreaType) then ODType:=2 else ODType:=3;
rdistance:=tdistance * DistanceFractionByRoadType[AreaType][ODType][RoadType];
WorkTripRoadMileDemand[RoadAreaType][RoadType][timeStep]:=
WorkTripRoadMileDemand[RoadAreaType][RoadType][timeStep]
+ autoTrips * rdistance;
end;
end;
{miles by transit - work transit trips}
for RoadAreaType:=1 to NumberOfAreaTypes do begin
tdistance:= TransitTripAverageODDistance[AreaType][WorkAreaType]
* ODThroughDistanceFraction[AreaType][WorkAreaType][RoadAreaType];
if tdistance>0 then
for TransitType:=1 to NumberOfTransitTypes do begin
if (TransitType=1) then
rdistance:=tdistance * TransitRailPAFraction[AreaType][WorkAreaType]
else
rdistance:=tdistance * (1.0 - TransitRailPAFraction[AreaType][WorkAreaType]);
WorkTripTransitMileDemand[RoadAreaType][TransitType][timeStep]:=
WorkTripTransitMileDemand[RoadAreaType][TransitType][timeStep]
+ transitTrips * rdistance;
end;
end;
end;
end;
begin {non-work}
autoTrips:=CarDriverNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1];
transitTrips:=TransitNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1];
for DestAreaType:=1 to NumberOfAreaTypes do begin
{miles by area type - work auto trips}
for RoadAreaType:=1 to NumberOfAreaTypes do begin
tdistance:= CarTripAverageODDistance[AreaType][DestAreaType]
* ODThroughDistanceFraction[AreaType][DestAreaType][RoadAreaType];
if tdistance>0 then
for RoadType:=1 to NumberOfRoadTypes do begin
if (RoadType=AreaType) and (RoadType=DestAreaType) then ODType:=1 else
if (RoadType=AreaType) or (RoadType=DestAreaType) then ODType:=2 else ODType:=3;
rdistance:=tdistance * DistanceFractionByRoadType[AreaType][ODType][RoadType];
NonWorkTripRoadMileDemand[RoadAreaType][RoadType][timeStep]:=
NonWorkTripRoadMileDemand[RoadAreaType][RoadType][timeStep]
+ autoTrips * rdistance;
end;
end;
{miles by transit - work transit trips}
for RoadAreaType:=1 to NumberOfAreaTypes do begin
tdistance:= TransitTripAverageODDistance[AreaType][DestAreaType]
* ODThroughDistanceFraction[AreaType][DestAreaType][RoadAreaType];
if tdistance>0 then
for TransitType:=1 to NumberOfTransitTypes do begin
if (TransitType=1) then
rdistance:=tdistance * TransitRailPAFraction[AreaType][DestAreaType]
else
rdistance:=tdistance * (1.0 - TransitRailPAFraction[AreaType][DestAreaType]);
NonWorkTripTransitMileDemand[RoadAreaType][TransitType][timeStep]:=
NonWorkTripTransitMileDemand[RoadAreaType][TransitType][timeStep]
+ transitTrips * rdistance;
end;
end;
end;
end;
end;
end;
end;
procedure CalculateEmploymentFeedbacks(timeStep:integer);
var AreaType, EmploymentType: byte;
begin
{get ratio of jobs to labor force in each area type from the previous time step}
for AreaType:=1 to NumberOfAreaTypes do begin
JobSupply[AreaType][timeStep]:=0;
CommercialSpaceDemand[AreaType][timeStep]:=0;
for EmploymentType:=1 to NumberOfEmploymentTypes do begin
JobSupply[AreaType][timeStep]:=JobSupply[AreaType][timeStep]
+Jobs[AreaType][EmploymentType][timeStep-1];
CommercialSpaceDemand[AreaType][timeStep]:=CommercialSpaceDemand[AreaType][timeStep]
+Jobs[AreaType][EmploymentType][timeStep-1]
*BaseCommercialSpacePerJob[AreaType][EmploymentType]/(5280.0*5280) {sq feet to sq miles}
*ExogenousEffectOnCommercialSpacePerJob[timeStep];
end;
end;
{do job index relative to period 1, since not all persons who live in area work in area}
for AreaType:=1 to NumberOfAreaTypes do begin
JobDemandSupplyIndex[AreaType][timeStep]:=
(JobDemand[AreaType][timeStep] / Max(1,JobSupply[AreaType][timeStep]))
/(JobDemand[AreaType][ 1 ] / Max(1,JobSupply[AreaType][ 1 ]));
end;
end;
procedure CalculateLandUseFeedbacks(timeStep:integer);
var AreaType: byte;
const LUResidential=2; LUCommercial=1; LUDevelopable=3; LUProtected=4;
begin
{get ratio of demand and supply for Residential space, commercial space, and developable space}
for AreaType:=1 to NumberOfAreaTypes do begin
CommercialSpaceSupply[AreaType][timeStep]:=Land[AreaType][LUCommercial][timeStep-1];
ResidentialSpaceSupply[AreaType][timeStep]:=Land[AreaType][LUResidential][timeStep-1];
DevelopableSpaceSupply[AreaType][timeStep]:=Land[AreaType][LUDevelopable][timeStep-1];
ResidentialSpaceDemandSupplyIndex[AreaType][timeStep]:=
ResidentialSpaceDemand[AreaType][timeStep] / Max(1,ResidentialSpaceSupply[AreaType][timeStep]);
CommercialSpaceDemandSupplyIndex[AreaType][timeStep]:=
CommercialSpaceDemand[AreaType][timeStep] / Max(1,CommercialSpaceSupply[AreaType][timeStep]);
DevelopableSpaceDemandSupplyIndex[AreaType][timeStep]:=
(Max(0,ResidentialSpaceDemand[AreaType][timeStep] - ResidentialSpaceSupply[AreaType][timeStep])
+Max(0,CommercialSpaceDemand[AreaType][timeStep] - CommercialSpaceSupply[AreaType][timeStep]))
/ Max(1,DevelopableSpaceSupply[AreaType][timeStep] );
end;
end;
procedure CalculateTransportationSupplyFeedbacks(timeStep:integer);
var AreaType, RoadType, TransitType: byte;
TotalRoadDemand, TotalRoadSupply, TotalTransitDemand, TotalTransitSupply:single;
const RoadTypeWeight:array[1..NumberOfRoadTypes] of single=(0.5,0.4,0.1);
TransitTypeWeight:array[1..NumberOfTransitTypes] of single=(0.6,0.4);
begin
{get ratio of demand and supply for road lane miles in each area type and road type}
for AreaType:=1 to NumberOfAreaTypes do begin
RoadVehicleCapacityDemandSupplyIndex[AreaType][timeStep]:= 0;
for RoadType:=1 to NumberOfRoadTypes do begin
RoadVehicleCapacitySupply[AreaType][RoadType][timeStep]:=
RoadLaneMiles[AreaType][RoadType][timeStep-1]
* BaseRoadLaneCapacityPerHour[AreaType,RoadType]
* ExogenousEffectOnRoadCapacityPerLane[timeStep];
RoadVehicleCapacityDemand[AreaType][RoadType][timeStep]:=
WorkTripRoadMileDemand[AreaType][RoadType][timeStep-1]
* WorkTripPeakHourFraction
+ NonWorkTripRoadMileDemand[AreaType][RoadType][timeStep-1]
* NonWorkTripPeakHourFraction;
RoadVehicleCapacityDemandSupplyIndex[AreaType][timeStep]:=
RoadVehicleCapacityDemandSupplyIndex[AreaType][timeStep]
+ RoadTypeWeight[RoadType]
* RoadVehicleCapacityDemand[AreaType][RoadType][timeStep]
/Max(1,RoadVehicleCapacitySupply[AreaType][RoadType][timeStep]);
end;
end;
{get ratio of demand and supply for transit route miles in each area type and transit type}
for AreaType:=1 to NumberOfAreaTypes do begin
TransitPassengerCapacityDemandSupplyIndex[AreaType][timeStep]:=0;
for TransitType:=1 to NumberOfTransitTypes do begin
TransitPassengerCapacitySupply[AreaType][TransitType][timeStep]:=
+ TransitRouteMiles[AreaType][TransitType][timeStep-1]
* BaseTransitRouteCapacityPerHour[AreaType,TransitType]
* ExogenousEffectOnTransitCapacityPerRoute[timeStep];
TransitPassengerCapacityDemand[AreaType][TransitType][timeStep]:=
WorkTripTransitMileDemand[AreaType][TransitType][timeStep-1]
* WorkTripPeakHourFraction
+ NonWorkTripTransitMileDemand[AreaType][TransitType][timeStep-1]
* NonWorkTripPeakHourFraction;
TransitPassengerCapacityDemandSupplyIndex[AreaType][timeStep]:=
TransitPassengerCapacityDemandSupplyIndex[AreaType][timeStep]+
+ TransitTypeWeight[TransitType]
* TransitPassengerCapacityDemand[AreaType][TransitType][timeStep]
/Max(1,TransitPassengerCapacitySupply[AreaType][TransitType][timeStep]);
end;
end;
end;
procedure CalculateEmploymentTransitionRates(timeStep:integer);
var AreaType, EmploymentType, AreaType2: byte;
EmployerAttractivenessIndex, ExternalEmployerAttractivenessIndex
:array[1..NumberOfAreaTypes,1..NumberOfEmploymentTypes] of single;
CurrentJobs,JobsMoved:single;
begin
{set attractivness index for employment}
for AreaType:=1 to NumberOfAreaTypes do
for EmploymentType:=1 to NumberOfEmploymentTypes do begin
EmployerAttractivenessIndex[AreaType][EmploymentType]:=
( EffectCurve(C_EffectOfJobDemandSupplyIndexOnEmployerAttractiveness,
JobDemandSupplyIndex[AreaType][timeStep])
* WeightOfJobDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
+EffectCurve(C_EffectOfCommercialSpaceDemandSupplyIndexOnEmployerAttractiveness,
CommercialSpaceDemandSupplyIndex[AreaType][timeStep])
* WeightOfCommercialSpaceDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
+EffectCurve(C_EffectOfRoadMileDemandSupplyIndexOnEmployerAttractiveness,
RoadVehicleCapacityDemandSupplyIndex[AreaType][timeStep])
* WeightOfRoadMileDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
)/
( WeightOfJobDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
+ WeightOfCommercialSpaceDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
+ WeightOfRoadMileDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]);
ExternalEmployerAttractivenessIndex[AreaType][EmploymentType]:=
( EffectCurve(C_EffectOfJobDemandSupplyIndexOnEmployerAttractiveness,
ExternalJobDemandSupplyIndex[timeStep])
* WeightOfJobDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
+EffectCurve(C_EffectOfCommercialSpaceDemandSupplyIndexOnEmployerAttractiveness,
ExternalCommercialSpaceDemandSupplyIndex[timeStep])
* WeightOfCommercialSpaceDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
+EffectCurve(C_EffectOfRoadMileDemandSupplyIndexOnEmployerAttractiveness,
ExternalRoadMileDemandSupplyIndex[timeStep])
* WeightOfRoadMileDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
)/
( WeightOfJobDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
+ WeightOfCommercialSpaceDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]
+ WeightOfRoadMileDemandSupplyIndexInEmployerAttractiveness[AreaType][EmploymentType]);
end;
for AreaType:=1 to NumberOfAreaTypes do
for EmploymentType:=1 to NumberOfEmploymentTypes do begin
JobsCreated[AreaType][EmploymentType][timeStep]:=0;
JobsLost[AreaType][EmploymentType][timeStep]:=0;
JobsMovedOut[AreaType][EmploymentType][timeStep]:=0;
JobsMovedIn[AreaType][EmploymentType][timeStep]:=0;
end;
{loop on cells and set rates}
for AreaType:=1 to NumberOfAreaTypes do
for EmploymentType:=1 to NumberOfEmploymentTypes do begin
CurrentJobs:=Jobs[AreaType][EmploymentType][timeStep-1];
JobsMoved:=CurrentJobs
* (EmployerAttractivenessIndex[AreaType][EmploymentType]
-ExternalEmployerAttractivenessIndex[AreaType][EmploymentType]);
if JobsMoved>0 then begin
JobsCreated[AreaType][EmploymentType][timeStep]:=
Min(JobsMoved,CurrentJobs) * TimeStepLength/JobCreationDelay[timeStep]
* ExogenousEffectOnJobCreationRate[timeStep];
end
else begin
JobsLost[AreaType][EmploymentType][timeStep]:=
Min(-JobsMoved,CurrentJobs) * TimeStepLength/JobLossDelay[timeStep]
* ExogenousEffectOnJobLossRate[timeStep];
end;
{check other area types, and move jobs there if more attractive}
for AreaType2:=1 to NumberOfAreaTypes do
if (AreaType2 <> AreaType) then begin
JobsMoved:=CurrentJobs
* (EmployerAttractivenessIndex[AreaType2][EmploymentType]
-EmployerAttractivenessIndex[AreaType][EmploymentType])
* ExogenousEffectOnJobMoveRate[timeStep];
if JobsMoved>0 then begin
JobsMovedOut[AreaType][EmploymentType][timeStep]:=
JobsMovedOut[AreaType][EmploymentType][timeStep]
+ Min(JobsMoved,CurrentJobs) * TimeStepLength/JobMoveDelay[timeStep];
JobsMovedIn[AreaType2][EmploymentType][timeStep]:=
JobsMovedIn[AreaType2][EmploymentType][timeStep]
+ Min(JobsMoved,CurrentJobs) * TimeStepLength/JobMoveDelay[timeStep];
end;
end;
end;
end; {CalculateEmploymentTransitionRates}
procedure CalculateLandUseTransitionRates(timeStep:integer);
var AreaType : byte;
NewResidentialSpaceNeeded,ExcessResidentialSpace,NewResidentialSpaceDeveloped,ResidentialSpaceReleased,
NewCommercialSpaceNeeded,ExcessCommercialSpace,NewCommercialSpaceDeveloped,CommercialSpaceReleased,
ProtectedSpaceReleased,DevelopableResidentialSpace,DevelopableCommercialSpace,
IndicatedResidentialDevelopment,IndicatedCommercialDevelopment,DevelopableLandSufficiencyFraction:single;
const LUResidential=2; LUCommercial=1; LUDevelopable=3; LUProtected=4;
begin
for AreaType:=1 to NumberOfAreaTypes do begin
NewResidentialSpaceNeeded:= Max(0,ResidentialSpaceDemand[AreaType][timeStep] - ResidentialSpaceSupply[AreaType][timeStep]);
ExcessResidentialSpace:=Max(0,ResidentialSpaceSupply[AreaType][timeStep] - ResidentialSpaceDemand[AreaType][timeStep]);
DevelopableResidentialSpace:=DevelopableSpaceSupply[AreaType][TimeStep]
* FractionOfDevelopableLandAllowedForResidential[AreaType];
IndicatedResidentialDevelopment:=Min(NewResidentialSpaceNeeded,DevelopableResidentialSpace);
NewCommercialSpaceNeeded:= Max(0,CommercialSpaceDemand[AreaType][timeStep] - CommercialSpaceSupply[AreaType][timeStep]);
ExcessCommercialSpace:=Max(0,CommercialSpaceSupply[AreaType][timeStep] - CommercialSpaceDemand[AreaType][timeStep]);
DevelopableCommercialSpace:=DevelopableSpaceSupply[AreaType][TimeStep]
* FractionOfDevelopableLandAllowedForCommercial[AreaType];
IndicatedCommercialDevelopment:=Min(NewCommercialSpaceNeeded,DevelopableCommercialSpace);
DevelopableLandSufficiencyFraction:= DevelopableSpaceSupply[AreaType][TimeStep]/
Max(1.0,IndicatedResidentialDevelopment+IndicatedCommercialDevelopment);
if DevelopableLandSufficiencyFraction<1.0 then begin
IndicatedResidentialDevelopment:=IndicatedResidentialDevelopment
* DevelopableLandSufficiencyFraction;
IndicatedCommercialDevelopment:=IndicatedCommercialDevelopment
* DevelopableLandSufficiencyFraction;
end;
if NewResidentialSpaceNeeded>0 then
NewResidentialSpaceDeveloped:=IndicatedResidentialDevelopment
* TimeStepLength/ResidentialSpaceDevelopmentDelay[timeStep]
else NewResidentialSpaceDeveloped:=0;
if ExcessResidentialSpace>0 then
ResidentialSpaceReleased:=ExcessResidentialSpace
* TimeStepLength/ResidentialSpaceReleaseDelay[timeStep]
else ResidentialSpaceReleased:=0;
if NewCommercialSpaceNeeded>0 then
NewCommercialSpaceDeveloped:=IndicatedCommercialDevelopment
* TimeStepLength/CommercialSpaceDevelopmentDelay[timeStep]
else NewCommercialSpaceDeveloped:=0;
if ExcessCommercialSpace>0 then
CommercialSpaceReleased:=ExcessCommercialSpace
* TimeStepLength/CommercialSpaceReleaseDelay[timeStep]
else CommercialSpaceReleased:=0;
ProtectedSpaceReleased:= {this can be negative - added to protection}
Land[AreaType][LUProtected][timeStep-1] *
(1.0 - ExogenousEffectOnLandProtection[timeStep])
* TimeStepLength / LandProtectionProcessDelay[timeStep];
ChangeInLandUseIn[AreaType][LUResidential][timeStep]:=NewResidentialSpaceDeveloped;
ChangeInLandUseOut[AreaType][LUResidential][timeStep]:=ResidentialSpaceReleased;
ChangeInLandUseIn[AreaType][LUCommercial][timeStep]:=NewCommercialSpaceDeveloped;
ChangeInLandUseOut[AreaType][LUCommercial][timeStep]:=CommercialSpaceReleased;
ChangeInLandUseIn[AreaType][LUDevelopable][timeStep]:=ResidentialSpaceReleased + CommercialSpaceReleased + ProtectedSpaceReleased;;
ChangeInLandUseOut[AreaType][LUDevelopable][timeStep]:=NewResidentialSpaceDeveloped + NewCommercialSpaceDeveloped;
ChangeInLandUseOut[AreaType][LUProtected][timeStep]:=ProtectedSpaceReleased;
end;
end; {CalculateLandUseTransitionRates}
procedure CalculateTransportationSupplyTransitionRates(timeStep:integer);
var AreaType, RoadType, TransitType : byte;
FractionNewRoadMilesNeeded, FractionNewRoadMilesAdded, FractionNewTransitMilesNeeded, FractionNewTransitMilesAdded:single;
begin
for AreaType:=1 to NumberOfAreaTypes do begin
for RoadType:=1 to NumberOfRoadTypes do begin
FractionNewRoadMilesNeeded:= Max(0,RoadVehicleCapacityDemand[AreaType][RoadType][timeStep] /
Max(1,RoadVehicleCapacitySupply[AreaType][RoadType][timeStep]) - 1.0);
if FractionNewRoadMilesNeeded>0 then begin
FractionNewRoadMilesAdded:=FractionNewRoadMilesNeeded
* ExogenousEffectOnRoadCapacityAddition[timeStep]
* TimeStepLength/RoadCapacityAdditionDelay[timeStep];
RoadLaneMilesAdded[AreaType][RoadType][timeStep]:=
RoadLaneMiles[AreaType][RoadType][timeStep-1]
* FractionNewRoadMilesAdded;
end else begin
RoadLaneMilesLost[AreaType][RoadType][timeStep]:=
RoadLaneMiles[AreaType][RoadType][timeStep-1]
* TimeStepLength/RoadCapacityRetirementDelay[timeStep];
end;
end;
for TransitType:=1 to NumberOfTransitTypes do begin
FractionNewTransitMilesNeeded:= Max(0,TransitPassengerCapacityDemand[AreaType][TransitType][timeStep] /
Max(1,TransitPassengerCapacitySupply[AreaType][TransitType][timeStep]) -1.0);
if FractionNewTransitMilesNeeded>0 then begin
FractionNewTransitMilesAdded:=FractionNewTransitMilesNeeded
* ExogenousEffectOnTransitCapacityAddition[timeStep]
* TimeStepLength/TransitCapacityAdditionDelay[timeStep];
TransitRouteMilesAdded[AreaType][TransitType][timeStep]:=
TransitRouteMiles[AreaType][TransitType][timeStep-1]
* FractionNewTransitMilesAdded;
end else begin
TransitRouteMilesLost[AreaType][TransitType][timeStep]:=
TransitRouteMiles[AreaType][TransitType][timeStep-1]
* TimeStepLength/TransitCapacityRetirementDelay[timeStep];
end;
end;
end;
end; {CalculateTransportationSuppplyTransitionRates}
procedure CalculateDemographicTransitionRates(timeStep:integer);
var PreviousPopulation, ResidentsMoved,NewHHChildrenFraction,
tempSingle,tempCouple,temp1,temp2, PeopleMoved:single;
{indices}
AreaType,AreaType2,
WorkerGr,
IncomeGr,
EthnicGr,
HhldType,
AgeGroup,
MigrationType,
NewAreaType,
NewWorkerGr,
NewIncomeGr,
NewEthnicGr,
NewHhldType,
NewAgeGroup,
BirthEthnicGr : byte;
ResidentAttractivenessIndex,ExternalResidentAttractivenessIndex
:array[1..NumberOfAreaTypes,1..NumberOfMigrationTypes] of single;
begin
{set attractivness index for residents}
for AreaType:=1 to NumberOfAreaTypes do
for MigrationType:=1 to NumberOfMigrationTypes do begin
ResidentAttractivenessIndex[AreaType][MigrationType]:=
( EffectCurve(C_EffectOfJobDemandSupplyIndexOnResidentAttractiveness,
JobDemandSupplyIndex[AreaType][timeStep])
* WeightOfJobDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
+EffectCurve(C_EffectOfResidentialSpaceDemandSupplyIndexOnResidentAttractiveness,
ResidentialSpaceDemandSupplyIndex[AreaType][timeStep])
* WeightOfResidentialSpaceDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
+EffectCurve(C_EffectOfRoadMileDemandSupplyIndexOnResidentAttractiveness,
RoadVehicleCapacityDemandSupplyIndex[AreaType][timeStep])
* WeightOfRoadMileDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
)/
( WeightOfJobDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
+ WeightOfResidentialSpaceDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
+ WeightOfRoadMileDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]);
ExternalResidentAttractivenessIndex[AreaType][MigrationType]:=
( EffectCurve(C_EffectOfJobDemandSupplyIndexOnResidentAttractiveness,
ExternalJobDemandSupplyIndex[timeStep])
* WeightOfJobDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
+EffectCurve(C_EffectOfResidentialSpaceDemandSupplyIndexOnResidentAttractiveness,
ExternalResidentialSpaceDemandSupplyIndex[timeStep])
* WeightOfResidentialSpaceDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
+EffectCurve(C_EffectOfRoadMileDemandSupplyIndexOnResidentAttractiveness,
ExternalRoadMileDemandSupplyIndex[timeStep])
* WeightOfRoadMileDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
)/
( WeightOfJobDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
+ WeightOfResidentialSpaceDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]
+ WeightOfRoadMileDemandSupplyIndexInResidentAttractiveness[AreaType][MigrationType]);
end;
{initialize all entries for each cell to 0}
for AreaType:=1 to NumberOfAreaTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do
for AgeGroup:=1 to NumberOfAgeGroups do begin
BirthsFrom[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
DeathsOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
MarriagesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
DivorcesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
FirstChildOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
EmptyNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
LeaveNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
AcculturationOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
WorkerStatusOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
BirthsIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
MarriagesIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
DivorcesIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
FirstChildIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
EmptyNestIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
LeaveNestIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
AcculturationIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
WorkerStatusIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
ForeignInmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
DomesticInmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
RegionalInmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
ForeignOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
DomesticOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
RegionalOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
end;
{apply rates for each cell}
for AreaType:=1 to NumberOfAreaTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do
for AgeGroup:=1 to NumberOfAgeGroups do begin
PreviousPopulation:=Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1];
if PreviousPopulation > 0 then begin
{Calculate number ageing to the next age group}
if (AgeGroupDuration[AgeGroup]>0.5) then begin
{ageing rate is based only on duration of age cohort}
AgeingOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* TimeStepLength / AgeGroupDuration[AgeGroup];
{put them into next age group}
NewAgeGroup:=AgeGroup+1;
AgeingIn[AreaType][NewAgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=AgeingIn[AreaType][NewAgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ AgeingOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
end;
{Calculate number of deaths}
DeathsOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseMortalityRate[AgeGroup][HhldType][EthnicGr] * TimeStepLength
* (LowIncomeDummy[IncomeGr] * LowIncomeEffectOnMortalityRate[timeStep]
+ MiddleIncomeDummy[IncomeGr]
+ HighIncomeDummy[IncomeGr] * HighIncomeEffectOnMortalityRate[timeStep])
* ExogenousEffectOnMortalityRate[timeStep];
{deaths aren't put into any other group}
{Calculate number of births}
BirthsFrom[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseFertilityRate[AgeGroup][HhldType][EthnicGr] * TimeStepLength
* (LowIncomeDummy[IncomeGr] * LowIncomeEffectOnFertilityRate[timeStep]
+ MiddleIncomeDummy[IncomeGr]
+ HighIncomeDummy[IncomeGr] * HighIncomeEffectOnFertilityRate[timeStep])
* ExogenousEffectOnFertilityRate[timeStep];
{If first child, all adults in HH become "full nest" household}
if (NumberOfChildren[HhldType]<0.5) then begin
FirstChildOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:= BirthsFrom[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] * NumberOfAdults[HhldType];
NewHhldType:=HhldType + 2; {same number of adults, 1+ kids}
{add full nest to new hhld type}
FirstChildIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=FirstChildIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ BirthsFrom[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] * NumberOfAdults[HhldType];
end else begin
NewHhldType:=HhldType; {not first child, same hhld type}
end;
BirthEthnicGr:=BirthEthnicGroup[EthnicGr];
BirthsIn[AreaType][BirthAgeGroup][NewHhldType][BirthEthnicGr][IncomeGr][BirthWorkerGr][timeStep]
:=BirthsIn[AreaType][BirthAgeGroup][NewHhldType][BirthEthnicGr][IncomeGr][BirthWorkerGr][timeStep]
+ BirthsFrom[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
{Calculate number of "marriages"}
if (NumberOfAdults[HhldType]<1.99) then begin
MarriagesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseMarriageRate[AgeGroup][HhldType][EthnicGr] * TimeStepLength
* (LowIncomeDummy[IncomeGr] * LowIncomeEffectOnMarriageRate[timeStep]
+ MiddleIncomeDummy[IncomeGr]
+ HighIncomeDummy[IncomeGr] * HighIncomeEffectOnMarriageRate[timeStep])
* ExogenousEffectOnMarriageRate[timeStep];
if NumberOfChildren[HhldType]=0
then NewHHChildrenFraction:=MarryNoChildren_ChildrenFraction
else NewHHChildrenFraction:=MarryHasChildren_ChildrenFraction;
{add marriages to new hhld types}
NewHhldType:=3; {couple, no children}
MarriagesIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=MarriagesIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ MarriagesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
*(1.0-NewHHChildrenFraction);
NewHhldType:=4; {couple, children}
MarriagesIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=MarriagesIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ MarriagesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
* NewHHChildrenFraction;
end;
{Calculate number "divorces"}
if (NumberOfAdults[HhldType]>1.99) then begin
DivorcesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseDivorceRate[AgeGroup][HhldType][EthnicGr] * TimeStepLength
* (LowIncomeDummy[IncomeGr] * LowIncomeEffectOnDivorceRate[timeStep]
+ MiddleIncomeDummy[IncomeGr]
+ HighIncomeDummy[IncomeGr] * HighIncomeEffectOnDivorceRate[timeStep])
* ExogenousEffectOnDivorceRate[timeStep];
if NumberOfChildren[HhldType]=0
then NewHHChildrenFraction:=DivorceNoChildren_ChildrenFraction
else NewHHChildrenFraction:=DivorceHasChildren_ChildrenFraction;
{add divorces to new hhld types}
NewHhldType:=1; {single, no children}
DivorcesIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=DivorcesIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ DivorcesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
*(1.0-NewHHChildrenFraction);
{add divorces to new hhld types}
NewHhldType:=2; {single, w/ children}
DivorcesIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=DivorcesIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ DivorcesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
* NewHHChildrenFraction;
end;
{Calculate number of 1+ child HH transitioning to 0 child ("empty nest" }
if (NumberOfChildren[HhldType]>0.5) then begin
EmptyNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseEmptyNestRate[AgeGroup][HhldType][EthnicGr] * TimeStepLength
* (LowIncomeDummy[IncomeGr] * LowIncomeEffectOnEmptyNestRate[timeStep]
+ MiddleIncomeDummy[IncomeGr]
+ HighIncomeDummy[IncomeGr] * HighIncomeEffectOnEmptyNestRate[timeStep])
* ExogenousEffectOnEmptyNestRate[timeStep];
{add to new hhld type}
NewHhldType:=HhldType-2; {same adults, no children}
EmptyNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=EmptyNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ EmptyNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
end;
{calculate number of children "leaving the nest" }
if (NumberOfChildren[HhldType]>0.5) then begin
tempSingle:=PreviousPopulation
* BaseLeaveNestSingleRate[AgeGroup][HhldType][EthnicGr] * TimeStepLength
* (LowIncomeDummy[IncomeGr] * LowIncomeEffectOnEmptyNestRate[timeStep]
+ MiddleIncomeDummy[IncomeGr]
+ HighIncomeDummy[IncomeGr] * HighIncomeEffectOnEmptyNestRate[timeStep])
* ExogenousEffectOnEmptyNestRate[timeStep];
tempCouple:=PreviousPopulation
* BaseLeaveNestCoupleRate[AgeGroup][HhldType][EthnicGr] * TimeStepLength
* (LowIncomeDummy[IncomeGr] * LowIncomeEffectOnEmptyNestRate[timeStep]
+ MiddleIncomeDummy[IncomeGr]
+ HighIncomeDummy[IncomeGr] * HighIncomeEffectOnEmptyNestRate[timeStep])
* ExogenousEffectOnEmptyNestRate[timeStep];
LeaveNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:= tempSingle + tempCouple;
{add to new hhld types}
NewHhldType:=1; {single, no children}
LeaveNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=LeaveNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempSingle * (1.0-LeaveNestSingle_ChildrenFraction);
NewHhldType:=2; {couple, no children}
LeaveNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=LeaveNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCouple * (1.0-LeaveNestCouple_ChildrenFraction);
NewHhldType:=3; {single, w/ children}
LeaveNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=LeaveNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempSingle * LeaveNestSingle_ChildrenFraction;
NewHhldType:=4; {couple, w/ children}
LeaveNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=LeaveNestIn[AreaType][AgeGroup][NewHhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCouple * LeaveNestCouple_ChildrenFraction;
end;
{Calculate workforce shifts}
if WorkerGr=1 then begin {in workforce}
WorkerStatusOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseLeaveWorkforceRate[AgeGroup][HhldType][EthnicGr]
* TimeStepLength / WorkforceChangeDelay[timeStep]
* ExogenousEffectOnLeaveWorkforceRate[timeStep];
NewWorkerGr:=2; {out of workforce}
WorkerStatusIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][NewWorkerGr][timeStep]
:=WorkerStatusIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][NewWorkerGr][timeStep]
+ WorkerStatusOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
end;
if WorkerGr=2 then begin {out workforce}
WorkerStatusOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseEnterWorkforceRate[AgeGroup][HhldType][EthnicGr]
* TimeStepLength / WorkforceChangeDelay[timeStep]
* ExogenousEffectOnEnterWorkforceRate[timeStep];
NewWorkerGr:=1; {in workforce}
WorkerStatusIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][NewWorkerGr][timeStep]
:=WorkerStatusIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][NewWorkerGr][timeStep]
+ WorkerStatusOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
end;
{Calculate income shifts}
if IncomeGr=1 then begin {leave low income}
IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseLeaveLowIncomeRate[AgeGroup][HhldType][EthnicGr]
* TimeStepLength / IncomeChangeDelay[timeStep]
* ExogenousEffectOnLeaveLowIncomeRate[timeStep];
NewIncomeGr:=2; {enter middle income}
IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][NewIncomeGr][WorkerGr][timeStep]
:=IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][NewIncomeGr][WorkerGr][timeStep]
+ IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
end else
if IncomeGr=2 then begin {leave middle income to low}
temp1
:=PreviousPopulation
* BaseEnterLowIncomeRate[AgeGroup][HhldType][EthnicGr]
* TimeStepLength / IncomeChangeDelay[timeStep]
* ExogenousEffectOnEnterLowIncomeRate[timeStep];
NewIncomeGr:=1; {enter low income}
IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][NewIncomeGr][WorkerGr][timeStep]
:=IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][NewIncomeGr][WorkerGr][timeStep]
+ temp1;
{leave middle income to high}
temp2
:=PreviousPopulation
* BaseEnterHighIncomeRate[AgeGroup][HhldType][EthnicGr]
* TimeStepLength / IncomeChangeDelay[timeStep]
* ExogenousEffectOnEnterHighIncomeRate[timeStep];
NewIncomeGr:=3; {enter high income}
IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][NewIncomeGr][WorkerGr][timeStep]
:=IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][NewIncomeGr][WorkerGr][timeStep]
+ temp2;
IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=temp1+temp2;
end else
if IncomeGr=3 then begin {leave high income}
IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* BaseLeaveHighIncomeRate[AgeGroup][HhldType][EthnicGr]
* TimeStepLength / IncomeChangeDelay[timeStep]
* ExogenousEffectOnLeaveHighIncomeRate[timeStep];
NewIncomeGr:=2; {enter middle income}
IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][NewIncomeGr][WorkerGr][timeStep]
:=IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][NewIncomeGr][WorkerGr][timeStep]
+ IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
end;
{Calculate number of non-US Born reaching 20 years in US ("acculturation") }
if (EthnicGrDuration[EthnicGr]<0.1) then begin
AcculturationOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
end else begin
AcculturationOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
:=PreviousPopulation
* TimeStepLength / EthnicGrDuration[EthnicGr];
NewEthnicGr:=NextEthnicGroup[EthnicGr];
{add acculturated to new ethnic gr}
AcculturationIn[AreaType][AgeGroup][HhldType][NewEthnicGr][IncomeGr][WorkerGr][timeStep]
:=AcculturationIn[AreaType][AgeGroup][HhldType][NewEthnicGr][IncomeGr][WorkerGr][timeStep]
+ AcculturationOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
end;
{Foreign migration only in foreign born <20 years ethnic group}
if (EthnicGrDuration[EthnicGr]>0.1) then begin
MigrationType:=1;
PeopleMoved:=PreviousPopulation
* BaseForeignInmigrationRate * MigrationRateMultiplier[AgeGroup][HhldType][EthnicGr]
* ResidentAttractivenessIndex[AreaType][MigrationType]
* ExogenousEffectOnForeignInmigrationRate[timeStep];
ForeignInmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
PeopleMoved * TimeStepLength/ForeignInmigrationDelay[timeStep];
PeopleMoved:=PreviousPopulation
* BaseForeignOutmigrationRate * MigrationRateMultiplier[AgeGroup][HhldType][EthnicGr]
* (1.0/ResidentAttractivenessIndex[AreaType][MigrationType])
* ExogenousEffectOnForeignOutmigrationRate[timeStep];
ForeignOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
PeopleMoved * TimeStepLength/ForeignOutmigrationDelay[timeStep];
end;
{Domestic migration}
begin
MigrationType:=2;
PeopleMoved:=PreviousPopulation
* BaseDomesticMigrationRate * MigrationRateMultiplier[AgeGroup][HhldType][EthnicGr]
*(ResidentAttractivenessIndex[AreaType][MigrationType]
/ ExternalResidentAttractivenessIndex[AreaType][MigrationType])
* ExogenousEffectOnDomesticMigrationRate[timeStep];
DomesticInmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
PeopleMoved * TimeStepLength/DomesticMigrationDelay[timeStep];
PeopleMoved:=PreviousPopulation
* BaseDomesticMigrationRate * MigrationRateMultiplier[AgeGroup][HhldType][EthnicGr]
*(ExternalResidentAttractivenessIndex[AreaType][MigrationType]
/ ResidentAttractivenessIndex[AreaType][MigrationType])
* ExogenousEffectOnDomesticMigrationRate[timeStep];
DomesticOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
PeopleMoved * TimeStepLength/DomesticMigrationDelay[timeStep];
end;
{Internal regonal migration between area types}
MigrationType:=3;
{check other area types, and move jobs there if more attractive}
for AreaType2:=1 to NumberOfAreaTypes do
if (AreaType2 <> AreaType) then begin
PeopleMoved:=PreviousPopulation
* BaseRegionalMigrationRate
*(ResidentAttractivenessIndex[AreaType2][MigrationType]
/ ResidentAttractivenessIndex[AreaType][MigrationType])
* ExogenousEffectOnRegionalMigrationRate[timeStep];
RegionalOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
RegionalOutmigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ PeopleMoved * TimeStepLength/RegionalMigrationDelay[timeStep];
RegionalInmigration[AreaType2][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
RegionalInmigration[AreaType2][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ PeopleMoved * TimeStepLength/RegionalMigrationDelay[timeStep];
end;
end; {population > 0}
end; {loop on cells}
end; {CalculateDemographicTransitionRates}
procedure ApplyDemographicTransitionRates(timeStep:integer);
var
{indices}
FAreaType,
AreaType,
WorkerGr,
IncomeGr,
EthnicGr,
HhldType,
AgeGroup: byte;
PLeave,PEnter,UFactor,HUrbEnter,HUrbLeave,IUrbEnter,IUrbLeave,PGrowth, ExogPopChange:single;
begin
{apply transition rates for each cell}
for AreaType:=1 to NumberOfAreaTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do
for AgeGroup:=1 to NumberOfAgeGroups do begin
{adjust population growth rate first for exogenous change}
if AreaType=1 then PGrowth:=ExogenousPopulationChangeRate1[timeStep]-ExogenousPopulationChangeRate1[timeStep-1] else
if AreaType=2 then PGrowth:=ExogenousPopulationChangeRate2[timeStep]-ExogenousPopulationChangeRate2[timeStep-1] else
if AreaType=3 then PGrowth:=ExogenousPopulationChangeRate3[timeStep]-ExogenousPopulationChangeRate3[timeStep-1] else
if AreaType=4 then PGrowth:=ExogenousPopulationChangeRate4[timeStep]-ExogenousPopulationChangeRate4[timeStep-1] else
if AreaType=5 then PGrowth:=ExogenousPopulationChangeRate5[timeStep]-ExogenousPopulationChangeRate5[timeStep-1] else
if AreaType=6 then PGrowth:=ExogenousPopulationChangeRate6[timeStep]-ExogenousPopulationChangeRate6[timeStep-1] else
if AreaType=7 then PGrowth:=ExogenousPopulationChangeRate7[timeStep]-ExogenousPopulationChangeRate7[timeStep-1] else
if AreaType=8 then PGrowth:=ExogenousPopulationChangeRate8[timeStep]-ExogenousPopulationChangeRate8[timeStep-1] else
if AreaType=9 then PGrowth:=ExogenousPopulationChangeRate9[timeStep]-ExogenousPopulationChangeRate9[timeStep-1] else
if AreaType=10 then PGrowth:=ExogenousPopulationChangeRate10[timeStep]-ExogenousPopulationChangeRate10[timeStep-1] else
if AreaType=11 then PGrowth:=ExogenousPopulationChangeRate11[timeStep]-ExogenousPopulationChangeRate11[timeStep-1] else
if AreaType=12 then PGrowth:=ExogenousPopulationChangeRate12[timeStep]-ExogenousPopulationChangeRate12[timeStep-1];
ExogPopChange:=PGrowth*Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][0];
FAreaType:=4*(AreaTypeSubregion[AreaType]-1)+1;
{apply household type factors toward urban areas}
HUrbLeave:=0;
HUrbEnter:=0;
if HhldType=1 then UFactor:=SingleNoKidsEffectOnMoveTowardsUrbanAreas[timeStep] else
if HhldType=2 then UFactor:=CoupleNoKidsEffectOnMoveTowardsUrbanAreas[timeStep] else
if HhldType=3 then UFactor:=SingleWiKidsEffectOnMoveTowardsUrbanAreas[timeStep] else
if HhldType=4 then UFactor:=CoupleWiKidsEffectOnMoveTowardsUrbanAreas[timeStep];
if UFactor>1.0 then begin
PLeave:=(UFactor-1.0)*
(Population[FAreaType+0][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
+Population[FAreaType+1][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]);
PEnter:=
(Population[FAreaType+2][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
+Population[FAreaType+3][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]);
if (PLeave>0) and (PEnter>0) then begin
if (AreaType=FAreaType+0) or (AreaType=FAreaType+1) then
HUrbLeave:=(UFactor-1.0)*
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1] else
if (AreaType=FAreaType+2) or (AreaType=FAreaType+3) then
HUrbEnter:=PLeave*
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]/PEnter;
end;
end else
if UFactor<1.0 then begin
PLeave:=(1.0-UFactor)*
(Population[FAreaType+2][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
+Population[FAreaType+3][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]);
PEnter:=
(Population[FAreaType+0][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
+Population[FAreaType+1][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]);
if (PLeave>0) and (PEnter>0) then begin
if (AreaType=FAreaType+2) or (AreaType=FAreaType+3) then
HUrbLeave:=(1.0-UFactor)*
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1] else
if (AreaType=FAreaType+0) or (AreaType=FAreaType+1) then
HUrbEnter:=PLeave*
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]/PEnter;
end;
end;
{apply income factors toward urban areas}
IUrbLeave:=0;
IUrbEnter:=0;
if IncomeGr=1 then UFactor:=LowIncomeEffectOnMoveTowardsUrbanAreas[timeStep] else
if IncomeGr=2 then UFactor:=1.0 else
if IncomeGr=3 then UFactor:=HighIncomeEffectOnMoveTowardsUrbanAreas[timeStep];
if UFactor>1.0 then begin
PLeave:=(UFactor-1.0)*
(Population[FAreaType+0][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
+Population[FAreaType+1][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]);
PEnter:=
(Population[FAreaType+2][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
+Population[FAreaType+3][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]);
if (PLeave>0) and (PEnter>0) then begin
if (AreaType=FAreaType+0) or (AreaType=FAreaType+1) then
IUrbLeave:=(UFactor-1.0)*
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1] else
if (AreaType=FAreaType+2) or (AreaType=FAreaType+3) then
IUrbEnter:=PLeave*
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]/PEnter;
end;
end else
if UFactor<1.0 then begin
PLeave:=(1.0-UFactor)*
(Population[FAreaType+2][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
+Population[FAreaType+3][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]);
PEnter:=
(Population[FAreaType+0][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
+Population[FAreaType+1][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]);
if (PLeave>0) and (PEnter>0) then begin
if (AreaType=FAreaType+2) or (AreaType=FAreaType+3) then
IUrbLeave:=(1.0-UFactor)*
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1] else
if (AreaType=FAreaType+0) or (AreaType=FAreaType+1) then
IUrbEnter:=PLeave*
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]/PEnter;
end;
end;
RegionalOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
RegionalOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] + HUrbLeave+IUrbLeave;
if ExogPopChange<0 then
RegionalOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
RegionalOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] - ExogPopChange;
RegionalInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
RegionalInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] + HUrbEnter+IUrbEnter;
if ExogPopChange>0 then
RegionalInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
RegionalInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] + ExogPopChange;
{Set new cell population by applying all the demographic rates}
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]
- AgeingOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract ageing}
- DeathsOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract deaths}
- MarriagesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract marriages}
- DivorcesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract divorces}
- FirstChildOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract full nest}
- EmptyNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract empty nest}
- LeaveNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract leave nest}
- AcculturationOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract acculturation}
- WorkerStatusOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract workforce out}
- IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract income group out}
- ForeignOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
- DomesticOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
- RegionalOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ AgeingIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {add ageing}
+ BirthsIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {add births}
+ MarriagesIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {add marriages}
+ DivorcesIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {add divorces}
+ FirstChildIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {add full nest}
+ EmptyNestIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {add empty nest}
+ LeaveNestIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {add leave nest}
+ AcculturationIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {add acculturation}
+ WorkerStatusIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract workforce out}
+ IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] {subtract income group out}
+ ForeignInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ DomesticInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ RegionalInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep];
if abs(Year-testWriteYear)<0.1 then
writeln(outest,Year:1:0,',',AreaType,',',AgeGroup,',',HhldType,',',EthnicGr,',',IncomeGr,',',WorkerGr,',',
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',',
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep-1]:5:4,',',
AgeingOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract ageing}
DeathsOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract deaths}
MarriagesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract marriages}
DivorcesOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract divorces}
FirstChildOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract full nest}
EmptyNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract empty nest}
LeaveNestOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract leave nest}
AcculturationOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract acculturation}
WorkerStatusOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract workforce out}
IncomeGroupOut[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract income group out}
ForeignOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',',
DomesticOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',',
RegionalOutMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',',
AgeingIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {add ageing}
BirthsIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {add births}
MarriagesIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {add marriages}
DivorcesIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {add divorces}
FirstChildIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {add full nest}
EmptyNestIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {add empty nest}
LeaveNestIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {add leave nest}
AcculturationIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {add acculturation}
WorkerStatusIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract workforce out}
IncomeGroupIn[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',', {subtract income group out}
ForeignInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',',
DomesticInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',',
RegionalInMigration[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:5:4,',',
ExogPopChange:5:4,',',
HUrbEnter:5:4,',',
HUrbLeave:5:4,',',
IUrbEnter:5:4,',',
IUrbLeave:5:4);
end;
end; {ApplyDemographicTransitionRates}
procedure ApplyEmploymentTransitionRates(timeStep:integer);
var
{indices}
AreaType,
EmploymentType: byte;
JGrowth,ExogJobChange:single;
begin
{apply transition in number of workers for each cell}
for AreaType:=1 to NumberOfAreaTypes do
for EmploymentType:=1 to NumberOfEmploymentTypes do begin
{adjust job growth rate first for exogenous change}
if EmploymentType=1 then begin
if AreaType=1 then JGrowth:=ExogenousEmploymentChangeRate1A[timeStep]-ExogenousEmploymentChangeRate1A[timeStep-1] else
if AreaType=2 then JGrowth:=ExogenousEmploymentChangeRate2A[timeStep]-ExogenousEmploymentChangeRate2A[timeStep-1] else
if AreaType=3 then JGrowth:=ExogenousEmploymentChangeRate3A[timeStep]-ExogenousEmploymentChangeRate3A[timeStep-1] else
if AreaType=4 then JGrowth:=ExogenousEmploymentChangeRate4A[timeStep]-ExogenousEmploymentChangeRate4A[timeStep-1] else
if AreaType=5 then JGrowth:=ExogenousEmploymentChangeRate5A[timeStep]-ExogenousEmploymentChangeRate5A[timeStep-1] else
if AreaType=6 then JGrowth:=ExogenousEmploymentChangeRate6A[timeStep]-ExogenousEmploymentChangeRate6A[timeStep-1] else
if AreaType=7 then JGrowth:=ExogenousEmploymentChangeRate7A[timeStep]-ExogenousEmploymentChangeRate7A[timeStep-1] else
if AreaType=8 then JGrowth:=ExogenousEmploymentChangeRate8A[timeStep]-ExogenousEmploymentChangeRate8A[timeStep-1] else
if AreaType=9 then JGrowth:=ExogenousEmploymentChangeRate9A[timeStep]-ExogenousEmploymentChangeRate9A[timeStep-1] else
if AreaType=10 then JGrowth:=ExogenousEmploymentChangeRate10A[timeStep]-ExogenousEmploymentChangeRate10A[timeStep-1] else
if AreaType=11 then JGrowth:=ExogenousEmploymentChangeRate11A[timeStep]-ExogenousEmploymentChangeRate11A[timeStep-1] else
if AreaType=12 then JGrowth:=ExogenousEmploymentChangeRate12A[timeStep]-ExogenousEmploymentChangeRate12A[timeStep-1];
end else
if EmploymentType=2 then begin
if AreaType=1 then JGrowth:=ExogenousEmploymentChangeRate1B[timeStep]-ExogenousEmploymentChangeRate1B[timeStep-1] else
if AreaType=2 then JGrowth:=ExogenousEmploymentChangeRate2B[timeStep]-ExogenousEmploymentChangeRate2B[timeStep-1] else
if AreaType=3 then JGrowth:=ExogenousEmploymentChangeRate3B[timeStep]-ExogenousEmploymentChangeRate3B[timeStep-1] else
if AreaType=4 then JGrowth:=ExogenousEmploymentChangeRate4B[timeStep]-ExogenousEmploymentChangeRate4B[timeStep-1] else
if AreaType=5 then JGrowth:=ExogenousEmploymentChangeRate5B[timeStep]-ExogenousEmploymentChangeRate5B[timeStep-1] else
if AreaType=6 then JGrowth:=ExogenousEmploymentChangeRate6B[timeStep]-ExogenousEmploymentChangeRate6B[timeStep-1] else
if AreaType=7 then JGrowth:=ExogenousEmploymentChangeRate7B[timeStep]-ExogenousEmploymentChangeRate7B[timeStep-1] else
if AreaType=8 then JGrowth:=ExogenousEmploymentChangeRate8B[timeStep]-ExogenousEmploymentChangeRate8B[timeStep-1] else
if AreaType=9 then JGrowth:=ExogenousEmploymentChangeRate9B[timeStep]-ExogenousEmploymentChangeRate9B[timeStep-1] else
if AreaType=10 then JGrowth:=ExogenousEmploymentChangeRate10B[timeStep]-ExogenousEmploymentChangeRate10B[timeStep-1] else
if AreaType=11 then JGrowth:=ExogenousEmploymentChangeRate11B[timeStep]-ExogenousEmploymentChangeRate11B[timeStep-1] else
if AreaType=12 then JGrowth:=ExogenousEmploymentChangeRate12B[timeStep]-ExogenousEmploymentChangeRate12B[timeStep-1];
end else
if EmploymentType=3 then begin
if AreaType=1 then JGrowth:=ExogenousEmploymentChangeRate1C[timeStep]-ExogenousEmploymentChangeRate1C[timeStep-1] else
if AreaType=2 then JGrowth:=ExogenousEmploymentChangeRate2C[timeStep]-ExogenousEmploymentChangeRate2C[timeStep-1] else
if AreaType=3 then JGrowth:=ExogenousEmploymentChangeRate3C[timeStep]-ExogenousEmploymentChangeRate3C[timeStep-1] else
if AreaType=4 then JGrowth:=ExogenousEmploymentChangeRate4C[timeStep]-ExogenousEmploymentChangeRate4C[timeStep-1] else
if AreaType=5 then JGrowth:=ExogenousEmploymentChangeRate5C[timeStep]-ExogenousEmploymentChangeRate5C[timeStep-1] else
if AreaType=6 then JGrowth:=ExogenousEmploymentChangeRate6C[timeStep]-ExogenousEmploymentChangeRate6C[timeStep-1] else
if AreaType=7 then JGrowth:=ExogenousEmploymentChangeRate7C[timeStep]-ExogenousEmploymentChangeRate7C[timeStep-1] else
if AreaType=8 then JGrowth:=ExogenousEmploymentChangeRate8C[timeStep]-ExogenousEmploymentChangeRate8C[timeStep-1] else
if AreaType=9 then JGrowth:=ExogenousEmploymentChangeRate9C[timeStep]-ExogenousEmploymentChangeRate9C[timeStep-1] else
if AreaType=10 then JGrowth:=ExogenousEmploymentChangeRate10C[timeStep]-ExogenousEmploymentChangeRate10C[timeStep-1] else
if AreaType=11 then JGrowth:=ExogenousEmploymentChangeRate11C[timeStep]-ExogenousEmploymentChangeRate11C[timeStep-1] else
if AreaType=12 then JGrowth:=ExogenousEmploymentChangeRate12C[timeStep]-ExogenousEmploymentChangeRate12C[timeStep-1];
end;
ExogJobChange:= JGrowth*Jobs[AreaType][EmploymentType][0];
{Set new cell population by applying all the demographic rates}
Jobs[AreaType][EmploymentType][timeStep]:=
Jobs[AreaType][EmploymentType][timeStep-1]
+JobsCreated[AreaType][EmploymentType][timeStep]
-JobsLost[AreaType][EmploymentType][timeStep]
+JobsMovedIn[AreaType][EmploymentType][timeStep]
-JobsMovedOut[AreaType][EmploymentType][timeStep]
+ExogJobChange;
end;
end; {ApplyEmploymentTransitionRates}
procedure ApplyLandUseTransitionRates(timeStep:integer);
var
{indices}
AreaType, LandUseType: byte;
begin
{apply transition rates for all land use types}
for AreaType:=1 to NumberOfAreaTypes do
for LandUseType:=1 to NumberOfLandUseTypes do begin
Land[AreaType][LandUseType][timeStep]:=
Land[AreaType][LandUseType][timeStep-1]
+ChangeInLandUseIn[AreaType][LandUseType][timeStep]
-ChangeInLandUseOut[AreaType][LandUseType][timeStep]
end;
end; {ApplyLandUseTransitionRates}
procedure ApplyTransportationSupplyTransitionRates(timeStep:integer);
var
{indices}
AreaType,
RoadType,TransitType: byte;
begin
for AreaType:=1 to NumberOfAreaTypes do begin
for RoadType:=1 to NumberOfRoadTypes do
RoadLaneMiles[AreaType][RoadType][timeStep]:=
RoadLaneMiles[AreaType][RoadType][timeStep-1]
+RoadLaneMilesAdded[AreaType][RoadType][timeStep]
-RoadLaneMilesLost[AreaType][RoadType][timeStep];
for TransitType:=1 to NumberOfTransitTypes do
TransitRouteMiles[AreaType][TransitType][timeStep]:=
TransitRouteMiles[AreaType][TransitType][timeStep-1]
+TransitRouteMilesAdded[AreaType][TransitType][timeStep]
-TransitRouteMilesLost[AreaType][TransitType][timeStep];
end;
end; {ApplyTransportationSuppplyTransitionRates}
procedure CalculateTravelDemand(timeStep:integer);
var
{indices}
AreaType,
WorkerGr,
IncomeGr,
EthnicGr,
HhldType,
AgeGroup,
CarOwnershipLevel,
TripPurpose: byte;
FullCarUtility,CarCompUtility,NoCarUtility,
CarDriverUtility,CarPassengerUtility,TransitUtility,WalkBikeUtility,
tempCarDriverTrips,tempCarPassengerTrips,tempTransitTrips,tempWalkBikeTrips,
tempCarDriverMiles,tempCarPassengerMiles,tempTransitMiles,tempWalkBikeMiles,
tempTrips,tempPop,prob,ageBorn:single;
VarValue:array[1..NumberOfTravelModelVariables] of single;
function TravelModelEquationResult(modelNumber,firstVar,lastVar:integer):single;
var value:single; varNumber:integer;
begin
value:=0;
for varNumber:=firstVar to lastVar do begin
value:=value + + TravelModelParameter[modelNumber,varNumber] * VarValue[varNumber];
end;
TravelModelEquationResult := value;
end;
begin
{apply travel demand models for each cell}
for AreaType:=1 to NumberOfAreaTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do
for AgeGroup:=1 to NumberOfAgeGroups do begin
{initialize}
WorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
NonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
CarDriverWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
CarPassengerWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
TransitWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
WalkBikeWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
CarDriverWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
CarPassengerWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
TransitWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
CarDriverNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
CarPassengerNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
TransitNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
WalkBikeNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
CarDriverNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
CarPassengerNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:= 0;
TransitNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=0;
{ set the initial array of input variables }
VarValue[1]:= 1.0; {constant}
VarValue[2]:= 0.0; {1995}
VarValue[3]:= 0.0; {2001}
VarValue[4]:= max(0.9 - (timeStep*TimeStepLength*0.15) , 0) ; {2009 vs 2016}
VarValue[5]:= Dummy(AgeGroup,1);
VarValue[6]:= Dummy(AgeGroup,2);
VarValue[7]:= Dummy(AgeGroup,3);
VarValue[8]:= Dummy(AgeGroup,4);
VarValue[9]:= Dummy(AgeGroup,5);
VarValue[10]:= Dummy(AgeGroup,6);
VarValue[11]:= Dummy(AgeGroup,7);
VarValue[12]:= Dummy(AgeGroup,8);
VarValue[13]:= Dummy(AgeGroup,9);
VarValue[14]:= Dummy(AgeGroup,10);
VarValue[15]:= Dummy(AgeGroup,11);
VarValue[16]:= Dummy(AgeGroup,12);
VarValue[17]:= Dummy(AgeGroup,13);
VarValue[18]:= Dummy(AgeGroup,14);
VarValue[19]:= Dummy(AgeGroup,15);
VarValue[20]:= Dummy(AgeGroup,16);
VarValue[21]:= Dummy(AgeGroup,17);
ageBorn:=StartYear+timeStep*TimeStepLength - 5*AgeGroup + 2.5;
VarValue[22]:= DummyRange(ageBorn,1900,1925)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[23]:= DummyRange(ageBorn,1925,1935)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[24]:= DummyRange(ageBorn,1935,1945)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[25]:= DummyRange(ageBorn,1945,1955)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[26]:= DummyRange(ageBorn,1955,1965)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[27]:= DummyRange(ageBorn,1965,1975)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[28]:= DummyRange(ageBorn,1975,1985)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[29]:= DummyRange(ageBorn,1985,1995)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[30]:= DummyRange(ageBorn,1995,2005)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[31]:= DummyRange(ageBorn,2005,2075)*ExogenousEffectOnAgeCohortVariables[timeStep];
VarValue[32]:= Dummy(HhldType,2) + Dummy(HhldType,4);
VarValue[33]:= Dummy(HhldType,3) + Dummy(HhldType,4);
VarValue[34]:= Dummy(HhldType,3);
VarValue[35]:= Dummy(EthnicGr,1) + Dummy(EthnicGr,2) + Dummy(EthnicGr,3);
VarValue[36]:= Dummy(EthnicGr,4) + Dummy(EthnicGr,5) + Dummy(EthnicGr,6);
VarValue[37]:= Dummy(EthnicGr,7) + Dummy(EthnicGr,8) + Dummy(EthnicGr,9);
VarValue[38]:= 1.0 - (Dummy(EthnicGr,1) + Dummy(EthnicGr,4) + Dummy(EthnicGr,7) + Dummy(EthnicGr,10));
VarValue[39]:= Dummy(EthnicGr,3) + Dummy(EthnicGr,6) + Dummy(EthnicGr,9) + Dummy(EthnicGr,12);
VarValue[40]:= Dummy(WorkerGr,1);
VarValue[41]:= Dummy(IncomeGr,1);
VarValue[42]:= Dummy(IncomeGr,3);
VarValue[43]:= Dummy(AreaTypeDensity[AreaType],1);
VarValue[44]:= Dummy(AreaTypeDensity[AreaType],2);
VarValue[45]:= Dummy(AreaTypeDensity[AreaType],3);
VarValue[46]:= Dummy(AreaTypeDensity[AreaType],4);
VarValue[47]:= Dummy(AreaTypeDensity[AreaType],5);
VarValue[48]:= 1.0; {rail MSA}
VarValue[49]:= 1.0; {large MSA}
VarValue[50]:= 1.0; {DVRPC MSA}
VarValue[51]:= 0.0; {gas price not used in first model}
VarValue[52]:= 0.0; {proxy}
VarValue[53]:= 0.0; {no diary}
{apply the auto ownership model}
FullCarUtility:= 1.0; {base}
CarCompUtility:= exp(TravelModelEquationResult(CarOwnership_CarCompetition,1,53))
* ExogenousEffectOnSharedCarFraction[timeStep];
NoCarUtility:= exp(TravelModelEquationResult(CarOwnership_NoCar,1,53))
* ExogenousEffectOnNoCarFraction[timeStep];
{apply the rest of the models conditional on car ownership}
for CarOwnershipLevel:= 1 to 3 do begin
if CarOwnershipLevel = 1 then begin
prob:=FullCarUtility / (FullCarUtility + CarCompUtility + NoCarUtility);
OwnCar[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] * prob;
end else
if CarOwnershipLevel = 2 then begin
prob:=CarCompUtility / (FullCarUtility + CarCompUtility + NoCarUtility);
ShareCar[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] * prob;
end else
prob:=NoCarUtility / (FullCarUtility + CarCompUtility + NoCarUtility);
NoCar[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] * prob;
tempPop:=Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] * prob;
VarValue[54]:= Dummy(CarOwnershipLevel,3);
VarValue[55]:= Dummy(CarOwnershipLevel,2);
VarValue[51]:= BaseGasolinePrice * ExogenousEffectOnGasolinePrice[timeStep];
{loop on trip purposes 1= work, 2= non-work, 3=child }
for TripPurpose:=1 to 3 do begin
VarValue[56]:= Dummy(TripPurpose,1);
{apply trip generation model, work trips only for workers}
if (TripPurpose=1) and (WorkerGr = 1) and (AgeGroup>3) then begin
tempTrips:= tempPop * (exp(TravelModelEquationResult(WorkTrip_Generation,1,56)) - 1.0)
* ExogenousEffectOnWorkTripRate[timeStep];
WorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
WorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] + tempTrips;
end
else if (TripPurpose=2) and (AgeGroup>3) then begin
tempTrips:= tempPop * (exp(TravelModelEquationResult(NonWorkTrip_Generation,1,56)) - 1.0)
* ExogenousEffectOnNonWorkTripRate[timeStep];
NonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
NonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] + tempTrips;
end
else if (TripPurpose=3) and (AgeGroup<=3) then begin
tempTrips:= tempPop * (exp(TravelModelEquationResult(ChildTrip_Generation,1,56)) - 1.0)
* ExogenousEffectOnNonWorkTripRate[timeStep];
NonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
NonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep] + tempTrips;
end
else tempTrips:=0;
if tempTrips>0 then begin
{set mode utilities}
if (TripPurpose=1) and (WorkerGr = 1) and (AgeGroup>3) then begin
CarDriverUtility:= 1.0; {base}
CarPassengerUtility:= exp(TravelModelEquationResult(WorkTrip_CarPassengerMode,1,56))
* ExogenousEffectOnCarPassengerModeFraction[timeStep];
TransitUtility:= exp(TravelModelEquationResult(WorkTrip_TransitMode,1,56))
* ExogenousEffectOnTransitModeFraction[timeStep];
WalkBikeUtility:= exp(TravelModelEquationResult(WorkTrip_WalkBikeMode,1,56))
* ExogenousEffectOnWalkBikeModeFraction[timeStep];
end
else if (TripPurpose=2) and (AgeGroup>3) then begin
CarDriverUtility:= 1.0; {base}
CarPassengerUtility:= exp(TravelModelEquationResult(NonWorkTrip_CarPassengerMode,1,56))
* ExogenousEffectOnCarPassengerModeFraction[timeStep];
TransitUtility:= exp(TravelModelEquationResult(NonWorkTrip_TransitMode,1,56))
* ExogenousEffectOnTransitModeFraction[timeStep];
WalkBikeUtility:= exp(TravelModelEquationResult(NonWorkTrip_WalkBikeMode,1,56))
* ExogenousEffectOnWalkBikeModeFraction[timeStep];
end
else if (TripPurpose=3) and (AgeGroup<=3) then begin
CarDriverUtility:= 1.0; {school bus for kids}
CarPassengerUtility:=exp(TravelModelEquationResult(ChildTrip_CarPassengerMode,1,56))
* ExogenousEffectOnCarPassengerModeFraction[timeStep];
TransitUtility:= exp(TravelModelEquationResult(ChildTrip_TransitMode,1,56))
* ExogenousEffectOnTransitModeFraction[timeStep];
WalkBikeUtility:= exp(TravelModelEquationResult(ChildTrip_WalkBikeMode,1,56))
* ExogenousEffectOnWalkBikeModeFraction[timeStep];
end;
{split trips by mode and apply distance models}
if (TripPurpose = 3) then tempCarDriverTrips := 0 else
tempCarDriverTrips := tempTrips *
CarDriverUtility / (CarDriverUtility + CarPassengerUtility + TransitUtility + WalkBikeUtility);
tempCarDriverMiles := tempCarDriverTrips *
(exp(TravelModelEquationResult(CarDriverTrip_Distance, 1,56)) - 1.0)
* ExogenousEffectOnCarTripDistance[timeStep];
tempCarPassengerTrips := tempTrips *
CarPassengerUtility / (CarDriverUtility + CarPassengerUtility + TransitUtility + WalkBikeUtility);
tempCarPassengerMiles := tempCarPassengerTrips *
(exp(TravelModelEquationResult(CarPassengerTrip_Distance, 1,56)) - 1.0)
* ExogenousEffectOnCarTripDistance[timeStep];
tempTransitTrips := tempTrips *
TransitUtility / (CarDriverUtility + CarPassengerUtility + TransitUtility + WalkBikeUtility);
tempTransitMiles := tempTransitTrips *
(exp(TravelModelEquationResult(TransitTrip_Distance, 1,56)) - 1.0);
tempWalkBikeTrips := tempTrips *
WalkBikeUtility / (CarDriverUtility + CarPassengerUtility + TransitUtility + WalkBikeUtility);
if (TripPurpose = 1) then begin
CarDriverWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
CarDriverWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCarDriverTrips;
CarPassengerWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
CarPassengerWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCarPassengerTrips;
TransitWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
TransitWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempTransitTrips;
WalkBikeWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
WalkBikeWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempWalkBikeTrips;
CarDriverWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
CarDriverWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCarDriverMiles;
CarPassengerWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
CarPassengerWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCarPassengerMiles;
TransitWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
TransitWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempTransitMiles;
end else begin
CarDriverNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
CarDriverNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCarDriverTrips;
CarPassengerNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
CarPassengerNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCarPassengerTrips;
TransitNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
TransitNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempTransitTrips;
WalkBikeNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
WalkBikeNonWorkTrips[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempWalkBikeTrips;
CarDriverNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
CarDriverNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCarDriverMiles;
CarPassengerNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
CarPassengerNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempCarPassengerMiles;
TransitNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]:=
TransitNonWorkMiles[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][timeStep]
+ tempTransitMiles;
end;
end; {trips for purpose}
end; {purpose loop}
end; {car ownership loop}
end; {cells}
end; {CalculateTravelDemand}
procedure writeSimulationResults;
var ouf:text; ts,demVar:integer;
{indices}
AreaType,
WorkerGr,
IncomeGr,
EthnicGr,
HhldType,
AgeGroup,
EmploymentType,
LandUseType,
RoadType,
TransitType: byte;
procedure writeTimeArray(demArray:TimeStepArray; demLabel:string; varLabel:string);
var ts,tx:integer;
begin
if varLabel = 'Population' then write(ouf,demLabel) else
if demLabel = 'Total' then write(ouf,varLabel) else
if demLabel = '' then write(ouf,varLabel) else
write(ouf,varLabel+'-'+demLabel);
for ts:=0 to NumberOfTimeSteps do begin
if (ts=0) and (demArray[ts]=0) then tx:=1 else tx:=ts; {avoids 0 rate in first period}
write(ouf,',',demArray[tx]:4:2);
end;
writeln(ouf);
end;
begin
assign(ouf,OutputDirectory+RunLabel+'.csv'); rewrite(ouf);
write(ouf,'Year');
for ts:=0 to NumberOfTimeSteps do begin
write(ouf,',',StartYear + ts*TimeStepLength:4:1);
end;
writeln(ouf);
for demVar:=1 to NumberOfDemographicVariables do
for AgeGroup:=0 to 0 do writeTimeArray(AgeGroupMarginals[demVar][AgeGroup],'',DemographicVariableLabels[demVar]);
for AreaType:=1 to NumberOfAreaTypes do
for EmploymentType:=1 to NumberOfEmploymentTypes do
writeTimeArray(Jobs[AreaType][EmploymentType],'',
AreaTypeLabels[AreaType]+'/'+EmploymentTypeLabels[EmploymentType]);
for AreaType:=1 to NumberOfAreaTypes do
for LandUseType:=1 to NumberOfLandUseTypes do
writeTimeArray(Land[AreaType][LandUseType],'',
AreaTypeLabels[AreaType]+'/'+LandUseTypeLabels[LandUseType]);
for AreaType:=1 to NumberOfAreaTypes do
for RoadType:=1 to NumberOfRoadTypes do
writeTimeArray(RoadLaneMiles[AreaType][RoadType],
AreaTypeLabels[AreaType]+'/'+RoadTypeLabels[RoadType],'LaneMiles');
for AreaType:=1 to NumberOfAreaTypes do
for TransitType:=1 to NumberOfTransitTypes do
writeTimeArray(TransitRouteMiles[AreaType][TransitType],
AreaTypeLabels[AreaType]+'/'+TransitTypeLabels[TransitType],'RouteMiles');
for demVar:=1 to NumberOfDemographicVariables do begin
for AgeGroup:=1 to NumberOfAgeGroups do writeTimeArray(AgeGroupMarginals[demVar][AgeGroup],AgeGroupLabels[AgeGroup],DemographicVariableLabels[demVar]);
for HhldType:=1 to NumberOfHhldTypes do writeTimeArray(HhldTypeMarginals[demVar][HhldType],HhldTypeLabels[HhldType],DemographicVariableLabels[demVar]);
for EthnicGr:=1 to NumberOfEthnicGrs do writeTimeArray(EthnicGrMarginals[demVar][EthnicGr],EthnicGrLabels[EthnicGr],DemographicVariableLabels[demVar]);
for IncomeGr:=1 to NumberOfIncomeGrs do writeTimeArray(IncomeGrMarginals[demVar][IncomeGr],IncomeGrLabels[IncomeGr],DemographicVariableLabels[demVar]);
for WorkerGr:=1 to NumberOfWorkerGrs do writeTimeArray(WorkerGrMarginals[demVar][WorkerGr],WorkerGrLabels[WorkerGr],DemographicVariableLabels[demVar]);
for AreaType:=1 to NumberOfAreaTypes do writeTimeArray(AreaTypeMarginals[demVar][AreaType],AreaTypeLabels[AreaType],DemographicVariableLabels[demVar]);
end;
for AreaType:=1 to NumberOfAreaTypes do
writeTimeArray(JobDemandSupplyIndex[AreaType],
AreaTypeLabels[AreaType],'Job Demand/Supply');
for AreaType:=1 to NumberOfAreaTypes do
writeTimeArray(CommercialSpaceDemandSupplyIndex[AreaType],
AreaTypeLabels[AreaType],'NonR.Space Demand/Supply');
for AreaType:=1 to NumberOfAreaTypes do
writeTimeArray(ResidentialSpaceDemandSupplyIndex[AreaType],
AreaTypeLabels[AreaType],'Res.Space Demand/Supply');
for AreaType:=1 to NumberOfAreaTypes do
writeTimeArray(DevelopableSpaceDemandSupplyIndex[AreaType],
AreaTypeLabels[AreaType],'Dev.Space Demand/Supply');
for AreaType:=1 to NumberOfAreaTypes do
writeTimeArray(RoadVehicleCapacityDemandSupplyIndex[AreaType],
AreaTypeLabels[AreaType],'Road Miles Demand/Supply');
close(ouf);
end;
procedure writeHouseholdConversionFile;
{
Income,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low,Low, 0.0000 ,Person characteristics, 0.0000 ,HH characteristics >>>, 0.0000 ,
HH size,1,1,2,2,2,2,2,2,3,3,3,3,3,3,4+,4+,4+,4+,4+,4+, 0.0000 , V, 0.0000 , 0.0000 , 0.0000 ,
HH workers,0,1,0,0,1,1,2+,2+,0,0,1,1,2+,2+,0,0,1,1,2+,2+, 0.0000 , V, 0.0000 , 0.0000 , 0.0000 ,
Children?,No,No,No,Yes,No,Yes,No,Yes,No,Yes,No,Yes,No,Yes,No,Yes,No,Yes,No,Yes, 0.0000 , V, 0.0000 , 0.0000 , 0.0000 ,
Code,1111,1121,1211,1212,1221,1222,1231,1232,1311,1312,1321,1322,1331,1332,1411,1412,1421,1422,1431,1432,Total,HH income,"Marital status, kids",Work status,Age group,
}
const nHInc = 3; nHComp=20; nHSize=4; nHWork=3; nHKids=2;
HIncLabel:array[1..nHInc] of string= ('LowInc','MedInc','Hi Inc');
HSizeLabel:array[1..nHSize] of string= ('1 pers','2 pers','3 pers','4+pers');
HWorkLabel:array[1..nHWork] of string= ('0 wkrs','1 wrkr','2+wkrs');
HKidsLabel:array[1..nHKids] of string= ('0 kids','1+kids');
HCompSize:array[1..nHComp] of byte= (1,1, 2,2,2,2,2,2, 3,3,3,3,3,3, 4,4,4,4,4,4);
HCompWork:array[1..nHComp] of byte= (0,1, 0,0,1,1,2,2, 0,0,1,1,2,2, 0,0,1,1,2,2);
HCompKids:array[1..nHComp] of byte= (0,0, 0,1,0,1,0,1, 0,1,0,1,0,1, 0,1,0,1,0,1);
AvgHSize:array[1..nHInc,1..nHComp] of single=((1.00,1.00,2.00,2.00,2.00,2.00,2.00,2.00,3.00,3.00,3.00,3.00,3.00,3.00,4.48,4.96,4.61,5.03,4.62,5.42),
(1.00,1.00,2.00,2.00,2.00,2.00,2.00,2.00,3.00,3.00,3.00,3.00,3.00,3.00,4.35,4.76,4.29,4.78,4.39,4.87),
(1.00,1.00,2.00,2.00,2.00,2.00,2.00,2.00,3.00,3.00,3.00,3.00,3.00,3.00,4.46,4.72,4.22,4.66,4.32,4.64));
HSizeAdj:array[1..nHSize] of single = (0.91,0.91,1.1,1.15);
nPInc=3; nPHType=4; nPWork=2; nPAgeG=6;
phFrac:array[1..nPInc,1..nPHType,1..nPWork,1..nPAgeG,1..nHComp] of single=
{IHWA 1p0w0k 1p1w0k 2p0w0k 2p0w+k 2p1w0k 2p1w+k 2p2w0k 2p2w+k 3p0w0k 3p0w+k 3p1w0k 3p1w+k 3p2w0k 3p2w+k 4p0w0k 4p0w+k 4p1w0k 4p1w+k 4p2w0k 4p2w+k }
{1111}((((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{1112} ( 0.1946 , 0.0000 , 0.2265 , 0.0000 , 0.1549 , 0.0000 , 0.0000 , 0.0000 , 0.0768 , 0.0000 , 0.0984 , 0.0000 , 0.0503 , 0.0000 , 0.0487 , 0.0000 , 0.0571 , 0.0000 , 0.0926 , 0.0000) ,
{1113} ( 0.3873 , 0.0000 , 0.2825 , 0.0000 , 0.1264 , 0.0000 , 0.0000 , 0.0000 , 0.0571 , 0.0000 , 0.0591 , 0.0000 , 0.0236 , 0.0000 , 0.0269 , 0.0000 , 0.0232 , 0.0000 , 0.0139 , 0.0000) ,
{1114} ( 0.5826 , 0.0000 , 0.1803 , 0.0000 , 0.0881 , 0.0000 , 0.0000 , 0.0000 , 0.0466 , 0.0000 , 0.0424 , 0.0000 , 0.0194 , 0.0000 , 0.0089 , 0.0000 , 0.0118 , 0.0000 , 0.0198 , 0.0000) ,
{1115} ( 0.7164 , 0.0000 , 0.1382 , 0.0000 , 0.0639 , 0.0000 , 0.0000 , 0.0000 , 0.0268 , 0.0000 , 0.0243 , 0.0000 , 0.0090 , 0.0000 , 0.0072 , 0.0000 , 0.0067 , 0.0000 , 0.0076 , 0.0000) ,
{1116} ( 0.7439 , 0.0000 , 0.1131 , 0.0000 , 0.0754 , 0.0000 , 0.0000 , 0.0000 , 0.0235 , 0.0000 , 0.0194 , 0.0000 , 0.0061 , 0.0000 , 0.0041 , 0.0000 , 0.0040 , 0.0000 , 0.0106 , 0.0000)) ,
{1121} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{1122} ( 0.0000 , 0.2347 , 0.0000 , 0.0000 , 0.1729 , 0.0000 , 0.2054 , 0.0000 , 0.0000 , 0.0000 , 0.0369 , 0.0000 , 0.1794 , 0.0000 , 0.0000 , 0.0000 , 0.0122 , 0.0000 , 0.1584 , 0.0000) ,
{1123} ( 0.0000 , 0.4038 , 0.0000 , 0.0000 , 0.2199 , 0.0000 , 0.1625 , 0.0000 , 0.0000 , 0.0000 , 0.0323 , 0.0000 , 0.0994 , 0.0000 , 0.0000 , 0.0000 , 0.0076 , 0.0000 , 0.0744 , 0.0000) ,
{1124} ( 0.0000 , 0.5653 , 0.0000 , 0.0000 , 0.1692 , 0.0000 , 0.1266 , 0.0000 , 0.0000 , 0.0000 , 0.0323 , 0.0000 , 0.0590 , 0.0000 , 0.0000 , 0.0000 , 0.0061 , 0.0000 , 0.0415 , 0.0000) ,
{1125} ( 0.0000 , 0.7243 , 0.0000 , 0.0000 , 0.1046 , 0.0000 , 0.0889 , 0.0000 , 0.0000 , 0.0000 , 0.0047 , 0.0000 , 0.0513 , 0.0000 , 0.0000 , 0.0000 , 0.0058 , 0.0000 , 0.0203 , 0.0000) ,
{1126} ( 0.0000 , 0.7243 , 0.0000 , 0.0000 , 0.1046 , 0.0000 , 0.0889 , 0.0000 , 0.0000 , 0.0000 , 0.0047 , 0.0000 , 0.0513 , 0.0000 , 0.0000 , 0.0000 , 0.0058 , 0.0000 , 0.0203 , 0.0000))) ,
{1211} ((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{1212} ( 0.0000 , 0.0000 , 0.0781 , 0.0000 , 0.2421 , 0.0000 , 0.0000 , 0.0000 , 0.1213 , 0.0000 , 0.1468 , 0.0000 , 0.1061 , 0.0000 , 0.0089 , 0.0000 , 0.1188 , 0.0000 , 0.1779 , 0.0000) ,
{1213} ( 0.0000 , 0.0000 , 0.3107 , 0.0000 , 0.2975 , 0.0000 , 0.0000 , 0.0000 , 0.1025 , 0.0000 , 0.0822 , 0.0000 , 0.0477 , 0.0000 , 0.0223 , 0.0000 , 0.0782 , 0.0000 , 0.0589 , 0.0000) ,
{1214} ( 0.0000 , 0.0000 , 0.3486 , 0.0000 , 0.2790 , 0.0000 , 0.0000 , 0.0000 , 0.0884 , 0.0000 , 0.1003 , 0.0000 , 0.0698 , 0.0000 , 0.0325 , 0.0000 , 0.0374 , 0.0000 , 0.0440 , 0.0000) ,
{1215} ( 0.0000 , 0.0000 , 0.6490 , 0.0000 , 0.1662 , 0.0000 , 0.0000 , 0.0000 , 0.0452 , 0.0000 , 0.0730 , 0.0000 , 0.0176 , 0.0000 , 0.0161 , 0.0000 , 0.0126 , 0.0000 , 0.0203 , 0.0000) ,
{1216} ( 0.0000 , 0.0000 , 0.8346 , 0.0000 , 0.0333 , 0.0000 , 0.0000 , 0.0000 , 0.0513 , 0.0000 , 0.0546 , 0.0000 , 0.0056 , 0.0000 , 0.0027 , 0.0000 , 0.0103 , 0.0000 , 0.0076 , 0.0000)) ,
{1221} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{1222} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0933 , 0.0000 , 0.3741 , 0.0000 , 0.0000 , 0.0000 , 0.0669 , 0.0000 , 0.2510 , 0.0000 , 0.0000 , 0.0000 , 0.0146 , 0.0000 , 0.2000 , 0.0000) ,
{1223} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.1532 , 0.0000 , 0.4193 , 0.0000 , 0.0000 , 0.0000 , 0.1467 , 0.0000 , 0.1418 , 0.0000 , 0.0000 , 0.0000 , 0.0214 , 0.0000 , 0.1177 , 0.0000) ,
{1224} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.2715 , 0.0000 , 0.3783 , 0.0000 , 0.0000 , 0.0000 , 0.0686 , 0.0000 , 0.1736 , 0.0000 , 0.0000 , 0.0000 , 0.0185 , 0.0000 , 0.0895 , 0.0000) ,
{1225} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.4895 , 0.0000 , 0.3094 , 0.0000 , 0.0000 , 0.0000 , 0.0364 , 0.0000 , 0.1194 , 0.0000 , 0.0000 , 0.0000 , 0.0057 , 0.0000 , 0.0395 , 0.0000) ,
{1226} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.4895 , 0.0000 , 0.3094 , 0.0000 , 0.0000 , 0.0000 , 0.0364 , 0.0000 , 0.1194 , 0.0000 , 0.0000 , 0.0000 , 0.0057 , 0.0000 , 0.0395 , 0.0000))) ,
{1311} ((( 0.0000 , 0.0000 , 0.0000 , 0.0362 , 0.0000 , 0.0706 , 0.0000 , 0.0000 , 0.0000 , 0.0663 , 0.0000 , 0.1740 , 0.0000 , 0.0299 , 0.0000 , 0.1343 , 0.0000 , 0.3236 , 0.0000 , 0.1651) ,
{1312} ( 0.0000 , 0.0000 , 0.0098 , 0.0574 , 0.0000 , 0.0541 , 0.0000 , 0.0000 , 0.0372 , 0.0932 , 0.0165 , 0.1446 , 0.0000 , 0.0252 , 0.0253 , 0.1408 , 0.0416 , 0.1948 , 0.0071 , 0.1522) ,
{1313} ( 0.0000 , 0.0000 , 0.0120 , 0.1027 , 0.0000 , 0.0062 , 0.0000 , 0.0000 , 0.0920 , 0.1535 , 0.0037 , 0.0396 , 0.0000 , 0.0004 , 0.1052 , 0.2632 , 0.0318 , 0.1188 , 0.0070 , 0.0639) ,
{1314} ( 0.0000 , 0.0000 , 0.0153 , 0.1607 , 0.0000 , 0.0191 , 0.0000 , 0.0000 , 0.0306 , 0.1320 , 0.0536 , 0.0861 , 0.0000 , 0.0038 , 0.0306 , 0.1518 , 0.0542 , 0.1492 , 0.0019 , 0.1110) ,
{1315} ( 0.0000 , 0.0000 , 0.0117 , 0.1301 , 0.0000 , 0.0108 , 0.0000 , 0.0000 , 0.0528 , 0.0851 , 0.0656 , 0.0900 , 0.0000 , 0.0029 , 0.0763 , 0.1037 , 0.0548 , 0.1673 , 0.0166 , 0.1321) ,
{1316} ( 0.0000 , 0.0000 , 0.0096 , 0.0669 , 0.0000 , 0.0032 , 0.0000 , 0.0000 , 0.0478 , 0.0541 , 0.0223 , 0.0828 , 0.0000 , 0.0064 , 0.0446 , 0.1210 , 0.2070 , 0.2038 , 0.0127 , 0.1178)) ,
{1321} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{1322} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0313 , 0.0439 , 0.0000 , 0.0105 , 0.0000 , 0.0000 , 0.0642 , 0.0859 , 0.0215 , 0.1053 , 0.0000 , 0.0000 , 0.0627 , 0.1487 , 0.0968 , 0.3292) ,
{1323} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0288 , 0.1013 , 0.0000 , 0.0031 , 0.0000 , 0.0000 , 0.0445 , 0.1914 , 0.0085 , 0.0643 , 0.0000 , 0.0000 , 0.0730 , 0.1960 , 0.0545 , 0.2345) ,
{1324} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0142 , 0.1338 , 0.0000 , 0.0097 , 0.0000 , 0.0000 , 0.0564 , 0.1383 , 0.0162 , 0.1050 , 0.0000 , 0.0000 , 0.0430 , 0.1273 , 0.1042 , 0.2518) ,
{1325} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0070 , 0.1174 , 0.0000 , 0.0094 , 0.0000 , 0.0000 , 0.0540 , 0.1573 , 0.0094 , 0.1009 , 0.0000 , 0.0000 , 0.1127 , 0.0376 , 0.0446 , 0.3498) ,
{1326} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0070 , 0.1174 , 0.0000 , 0.0094 , 0.0000 , 0.0000 , 0.0540 , 0.1573 , 0.0094 , 0.1009 , 0.0000 , 0.0000 , 0.1127 , 0.0376 , 0.0446 , 0.3498))) ,
{1411} ((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0103 , 0.0000 , 0.0512 , 0.0000 , 0.0348 , 0.0000 , 0.0619 , 0.0000 , 0.4295 , 0.0000 , 0.4123) ,
{1412} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0030 , 0.0148 , 0.0844 , 0.0679 , 0.0000 , 0.0289 , 0.0116 , 0.0850 , 0.0750 , 0.3150 , 0.0222 , 0.2923) ,
{1413} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0136 , 0.0206 , 0.0713 , 0.0734 , 0.0000 , 0.0016 , 0.0272 , 0.1471 , 0.0510 , 0.4816 , 0.0136 , 0.0990) ,
{1414} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0161 , 0.0739 , 0.0067 , 0.1766 , 0.0000 , 0.0094 , 0.0168 , 0.1269 , 0.0396 , 0.2794 , 0.0302 , 0.2243) ,
{1415} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0340 , 0.1089 , 0.0328 , 0.1113 , 0.0000 , 0.0023 , 0.0351 , 0.1616 , 0.0585 , 0.2482 , 0.0351 , 0.1721) ,
{1416} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0038 , 0.1107 , 0.0115 , 0.0307 , 0.0000 , 0.0000 , 0.0191 , 0.1145 , 0.0420 , 0.1947 , 0.0649 , 0.4084)) ,
{1421} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{1422} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0786 , 0.0277 , 0.0751 , 0.0534 , 0.0000 , 0.0000 , 0.0684 , 0.1138 , 0.1483 , 0.4346) ,
{1423} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0391 , 0.0379 , 0.0334 , 0.0714 , 0.0000 , 0.0000 , 0.0391 , 0.2398 , 0.0652 , 0.4740) ,
{1424} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0377 , 0.1048 , 0.0176 , 0.1429 , 0.0000 , 0.0000 , 0.0239 , 0.1806 , 0.0356 , 0.4567) ,
{1425} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0157 , 0.1289 , 0.0189 , 0.0660 , 0.0000 , 0.0000 , 0.0346 , 0.1038 , 0.1415 , 0.4906) ,
{1426} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0157 , 0.1289 , 0.0189 , 0.0660 , 0.0000 , 0.0000 , 0.0346 , 0.1038 , 0.1415 , 0.4906)))),
{2111} (((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{2112} ( 0.0451 , 0.0000 , 0.0860 , 0.0000 , 0.2547 , 0.0000 , 0.0000 , 0.0000 , 0.0168 , 0.0000 , 0.1630 , 0.0000 , 0.1504 , 0.0000 , 0.0503 , 0.0000 , 0.0645 , 0.0000 , 0.1693 , 0.0000) ,
{2113} ( 0.1564 , 0.0000 , 0.1818 , 0.0000 , 0.1913 , 0.0000 , 0.0000 , 0.0000 , 0.0423 , 0.0000 , 0.1015 , 0.0000 , 0.1268 , 0.0000 , 0.0359 , 0.0000 , 0.1068 , 0.0000 , 0.0571 , 0.0000) ,
{2114} ( 0.3200 , 0.0000 , 0.2297 , 0.0000 , 0.1597 , 0.0000 , 0.0000 , 0.0000 , 0.0365 , 0.0000 , 0.0712 , 0.0000 , 0.0856 , 0.0000 , 0.0081 , 0.0000 , 0.0307 , 0.0000 , 0.0584 , 0.0000) ,
{2115} ( 0.5582 , 0.0000 , 0.1701 , 0.0000 , 0.1170 , 0.0000 , 0.0000 , 0.0000 , 0.0160 , 0.0000 , 0.0560 , 0.0000 , 0.0312 , 0.0000 , 0.0046 , 0.0000 , 0.0206 , 0.0000 , 0.0262 , 0.0000) ,
{2116} ( 0.6034 , 0.0000 , 0.1114 , 0.0000 , 0.1273 , 0.0000 , 0.0000 , 0.0000 , 0.0141 , 0.0000 , 0.0713 , 0.0000 , 0.0317 , 0.0000 , 0.0039 , 0.0000 , 0.0166 , 0.0000 , 0.0204 , 0.0000)) ,
{2121} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{2122} ( 0.0000 , 0.2112 , 0.0000 , 0.0000 , 0.0973 , 0.0000 , 0.2974 , 0.0000 , 0.0000 , 0.0000 , 0.0106 , 0.0000 , 0.2269 , 0.0000 , 0.0000 , 0.0000 , 0.0090 , 0.0000 , 0.1477 , 0.0000) ,
{2123} ( 0.0000 , 0.5261 , 0.0000 , 0.0000 , 0.1290 , 0.0000 , 0.1903 , 0.0000 , 0.0000 , 0.0000 , 0.0169 , 0.0000 , 0.0883 , 0.0000 , 0.0000 , 0.0000 , 0.0067 , 0.0000 , 0.0427 , 0.0000) ,
{2124} ( 0.0000 , 0.5778 , 0.0000 , 0.0000 , 0.1379 , 0.0000 , 0.1365 , 0.0000 , 0.0000 , 0.0000 , 0.0214 , 0.0000 , 0.0811 , 0.0000 , 0.0000 , 0.0000 , 0.0036 , 0.0000 , 0.0418 , 0.0000) ,
{2125} ( 0.0000 , 0.6620 , 0.0000 , 0.0000 , 0.1365 , 0.0000 , 0.1023 , 0.0000 , 0.0000 , 0.0000 , 0.0163 , 0.0000 , 0.0635 , 0.0000 , 0.0000 , 0.0000 , 0.0016 , 0.0000 , 0.0178 , 0.0000) ,
{2126} ( 0.0000 , 0.6620 , 0.0000 , 0.0000 , 0.1365 , 0.0000 , 0.1023 , 0.0000 , 0.0000 , 0.0000 , 0.0163 , 0.0000 , 0.0635 , 0.0000 , 0.0000 , 0.0000 , 0.0016 , 0.0000 , 0.0178 , 0.0000))) ,
{2211} ((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{2212} ( 0.0000 , 0.0000 , 0.0258 , 0.0000 , 0.1921 , 0.0000 , 0.0000 , 0.0000 , 0.0556 , 0.0000 , 0.1536 , 0.0000 , 0.2565 , 0.0000 , 0.0163 , 0.0000 , 0.0474 , 0.0000 , 0.2527 , 0.0000) ,
{2213} ( 0.0000 , 0.0000 , 0.0532 , 0.0000 , 0.4953 , 0.0000 , 0.0000 , 0.0000 , 0.0719 , 0.0000 , 0.1474 , 0.0000 , 0.0884 , 0.0000 , 0.0129 , 0.0000 , 0.0503 , 0.0000 , 0.0805 , 0.0000) ,
{2214} ( 0.0000 , 0.0000 , 0.2198 , 0.0000 , 0.4390 , 0.0000 , 0.0000 , 0.0000 , 0.0534 , 0.0000 , 0.0990 , 0.0000 , 0.0898 , 0.0000 , 0.0122 , 0.0000 , 0.0212 , 0.0000 , 0.0656 , 0.0000) ,
{2215} ( 0.0000 , 0.0000 , 0.5932 , 0.0000 , 0.2368 , 0.0000 , 0.0000 , 0.0000 , 0.0312 , 0.0000 , 0.0656 , 0.0000 , 0.0320 , 0.0000 , 0.0058 , 0.0000 , 0.0099 , 0.0000 , 0.0254 , 0.0000) ,
{2216} ( 0.0000 , 0.0000 , 0.7700 , 0.0000 , 0.0542 , 0.0000 , 0.0000 , 0.0000 , 0.0358 , 0.0000 , 0.0708 , 0.0000 , 0.0259 , 0.0000 , 0.0069 , 0.0000 , 0.0110 , 0.0000 , 0.0254 , 0.0000)) ,
{2221} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{2222} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0409 , 0.0000 , 0.3616 , 0.0000 , 0.0000 , 0.0000 , 0.0269 , 0.0000 , 0.3229 , 0.0000 , 0.0000 , 0.0000 , 0.0062 , 0.0000 , 0.2415 , 0.0000) ,
{2223} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0795 , 0.0000 , 0.5989 , 0.0000 , 0.0000 , 0.0000 , 0.0511 , 0.0000 , 0.1717 , 0.0000 , 0.0000 , 0.0000 , 0.0085 , 0.0000 , 0.0903 , 0.0000) ,
{2224} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.1593 , 0.0000 , 0.5154 , 0.0000 , 0.0000 , 0.0000 , 0.0308 , 0.0000 , 0.2071 , 0.0000 , 0.0000 , 0.0000 , 0.0037 , 0.0000 , 0.0838 , 0.0000) ,
{2225} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.3781 , 0.0000 , 0.4237 , 0.0000 , 0.0000 , 0.0000 , 0.0277 , 0.0000 , 0.1288 , 0.0000 , 0.0000 , 0.0000 , 0.0023 , 0.0000 , 0.0395 , 0.0000) ,
{2226} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.3781 , 0.0000 , 0.4237 , 0.0000 , 0.0000 , 0.0000 , 0.0277 , 0.0000 , 0.1288 , 0.0000 , 0.0000 , 0.0000 , 0.0023 , 0.0000 , 0.0395 , 0.0000))) ,
{2311} ((( 0.0000 , 0.0000 , 0.0000 , 0.0090 , 0.0000 , 0.1102 , 0.0000 , 0.0000 , 0.0000 , 0.0236 , 0.0000 , 0.2297 , 0.0000 , 0.0538 , 0.0000 , 0.0631 , 0.0000 , 0.3008 , 0.0000 , 0.2099) ,
{2312} ( 0.0000 , 0.0000 , 0.0010 , 0.0048 , 0.0000 , 0.1245 , 0.0000 , 0.0000 , 0.0148 , 0.0376 , 0.0043 , 0.1906 , 0.0000 , 0.0510 , 0.0273 , 0.0512 , 0.0256 , 0.1992 , 0.0223 , 0.2459) ,
{2313} ( 0.0000 , 0.0000 , 0.0062 , 0.0273 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0502 , 0.1056 , 0.0062 , 0.0290 , 0.0000 , 0.0000 , 0.1303 , 0.2931 , 0.0704 , 0.1382 , 0.0070 , 0.1364) ,
{2314} ( 0.0000 , 0.0000 , 0.0016 , 0.0791 , 0.0000 , 0.0032 , 0.0000 , 0.0000 , 0.0728 , 0.1297 , 0.0285 , 0.0475 , 0.0000 , 0.0016 , 0.0316 , 0.0665 , 0.0443 , 0.2168 , 0.0364 , 0.2405) ,
{2315} ( 0.0000 , 0.0000 , 0.0017 , 0.0380 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0155 , 0.0484 , 0.0225 , 0.1693 , 0.0000 , 0.0069 , 0.0190 , 0.0518 , 0.0656 , 0.2971 , 0.0225 , 0.2418) ,
{2316} ( 0.0000 , 0.0000 , 0.0000 , 0.0090 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0151 , 0.0904 , 0.0392 , 0.1777 , 0.0000 , 0.0030 , 0.0120 , 0.0572 , 0.0813 , 0.3012 , 0.0301 , 0.1837)) ,
{2321} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{2322} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0194 , 0.0227 , 0.0002 , 0.0257 , 0.0000 , 0.0000 , 0.0319 , 0.0525 , 0.0212 , 0.1707 , 0.0000 , 0.0000 , 0.0484 , 0.0764 , 0.0823 , 0.4486) ,
{2323} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0221 , 0.1127 , 0.0008 , 0.0092 , 0.0000 , 0.0000 , 0.0586 , 0.1778 , 0.0066 , 0.0927 , 0.0000 , 0.0000 , 0.0906 , 0.1819 , 0.0329 , 0.2141) ,
{2324} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0144 , 0.1713 , 0.0000 , 0.0099 , 0.0000 , 0.0000 , 0.0504 , 0.1623 , 0.0108 , 0.1187 , 0.0000 , 0.0000 , 0.0289 , 0.0952 , 0.0470 , 0.2911) ,
{2325} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0067 , 0.0976 , 0.0000 , 0.0202 , 0.0000 , 0.0000 , 0.0337 , 0.0842 , 0.0168 , 0.1481 , 0.0000 , 0.0000 , 0.0471 , 0.0640 , 0.0774 , 0.4040) ,
{2326} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0067 , 0.0976 , 0.0000 , 0.0202 , 0.0000 , 0.0000 , 0.0337 , 0.0842 , 0.0168 , 0.1481 , 0.0000 , 0.0000 , 0.0471 , 0.0640 , 0.0774 , 0.4040))) ,
{2411} ((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0034 , 0.0000 , 0.0328 , 0.0000 , 0.0844 , 0.0000 , 0.0102 , 0.0000 , 0.2925 , 0.0000 , 0.5767) ,
{2412} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0026 , 0.0065 , 0.0309 , 0.0578 , 0.0000 , 0.0938 , 0.0045 , 0.0139 , 0.0345 , 0.2347 , 0.0155 , 0.5053) ,
{2413} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0124 , 0.0095 , 0.0819 , 0.0855 , 0.0000 , 0.0021 , 0.0034 , 0.0250 , 0.0781 , 0.6067 , 0.0096 , 0.0858) ,
{2414} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0026 , 0.0216 , 0.0104 , 0.2197 , 0.0000 , 0.0182 , 0.0143 , 0.0489 , 0.0229 , 0.3348 , 0.0411 , 0.2656) ,
{2415} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0123 , 0.0775 , 0.0034 , 0.0953 , 0.0000 , 0.0041 , 0.0158 , 0.0686 , 0.0556 , 0.2428 , 0.0912 , 0.3333) ,
{2416} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0096 , 0.0795 , 0.0193 , 0.0169 , 0.0000 , 0.0024 , 0.0289 , 0.0217 , 0.0410 , 0.2169 , 0.0747 , 0.4892)) ,
{2421} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{2422} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0198 , 0.0134 , 0.0854 , 0.0996 , 0.0000 , 0.0000 , 0.0267 , 0.0510 , 0.0910 , 0.6130) ,
{2423} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0245 , 0.0235 , 0.0591 , 0.1254 , 0.0000 , 0.0000 , 0.0282 , 0.1355 , 0.0660 , 0.5378) ,
{2424} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0079 , 0.0471 , 0.0116 , 0.2487 , 0.0000 , 0.0000 , 0.0063 , 0.0880 , 0.0379 , 0.5525) ,
{2425} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0080 , 0.1072 , 0.0067 , 0.1984 , 0.0000 , 0.0000 , 0.0214 , 0.0858 , 0.1019 , 0.4705) ,
{2426} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0080 , 0.1072 , 0.0067 , 0.1984 , 0.0000 , 0.0000 , 0.0214 , 0.0858 , 0.1019 , 0.4705)))),
{3111} (((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{3112} ( 0.0195 , 0.0000 , 0.0420 , 0.0000 , 0.1261 , 0.0000 , 0.0000 , 0.0000 , 0.0105 , 0.0000 , 0.2643 , 0.0000 , 0.2222 , 0.0000 , 0.0045 , 0.0000 , 0.0661 , 0.0000 , 0.2447 , 0.0000) ,
{3113} ( 0.2514 , 0.0000 , 0.1886 , 0.0000 , 0.1886 , 0.0000 , 0.0000 , 0.0000 , 0.0229 , 0.0000 , 0.1029 , 0.0000 , 0.0971 , 0.0000 , 0.0114 , 0.0000 , 0.0686 , 0.0000 , 0.0686 , 0.0000) ,
{3114} ( 0.2785 , 0.0000 , 0.2034 , 0.0000 , 0.1186 , 0.0000 , 0.0000 , 0.0000 , 0.0387 , 0.0000 , 0.1186 , 0.0000 , 0.0993 , 0.0000 , 0.0048 , 0.0000 , 0.0242 , 0.0000 , 0.1138 , 0.0000) ,
{3115} ( 0.3738 , 0.0000 , 0.2025 , 0.0000 , 0.1236 , 0.0000 , 0.0000 , 0.0000 , 0.0498 , 0.0000 , 0.1329 , 0.0000 , 0.0571 , 0.0000 , 0.0021 , 0.0000 , 0.0083 , 0.0000 , 0.0498 , 0.0000) ,
{3116} ( 0.4764 , 0.0000 , 0.0849 , 0.0000 , 0.1309 , 0.0000 , 0.0000 , 0.0000 , 0.0106 , 0.0000 , 0.1132 , 0.0000 , 0.0802 , 0.0000 , 0.0035 , 0.0000 , 0.0342 , 0.0000 , 0.0660 , 0.0000)) ,
{3121} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{3122} ( 0.0000 , 0.0942 , 0.0000 , 0.0000 , 0.0639 , 0.0000 , 0.2266 , 0.0000 , 0.0000 , 0.0000 , 0.0140 , 0.0000 , 0.3462 , 0.0000 , 0.0000 , 0.0000 , 0.0023 , 0.0000 , 0.2529 , 0.0000) ,
{3123} ( 0.0000 , 0.3983 , 0.0000 , 0.0000 , 0.1607 , 0.0000 , 0.2531 , 0.0000 , 0.0000 , 0.0000 , 0.0171 , 0.0000 , 0.1173 , 0.0000 , 0.0000 , 0.0000 , 0.0026 , 0.0000 , 0.0510 , 0.0000) ,
{3124} ( 0.0000 , 0.4125 , 0.0000 , 0.0000 , 0.1821 , 0.0000 , 0.1551 , 0.0000 , 0.0000 , 0.0000 , 0.0189 , 0.0000 , 0.1570 , 0.0000 , 0.0000 , 0.0000 , 0.0048 , 0.0000 , 0.0697 , 0.0000) ,
{3125} ( 0.0000 , 0.5523 , 0.0000 , 0.0000 , 0.1526 , 0.0000 , 0.1057 , 0.0000 , 0.0000 , 0.0000 , 0.0238 , 0.0000 , 0.1265 , 0.0000 , 0.0000 , 0.0000 , 0.0018 , 0.0000 , 0.0374 , 0.0000) ,
{3126} ( 0.0000 , 0.5523 , 0.0000 , 0.0000 , 0.1526 , 0.0000 , 0.1057 , 0.0000 , 0.0000 , 0.0000 , 0.0238 , 0.0000 , 0.1265 , 0.0000 , 0.0000 , 0.0000 , 0.0018 , 0.0000 , 0.0374 , 0.0000))) ,
{3211} ((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{3212} ( 0.0000 , 0.0000 , 0.0043 , 0.0000 , 0.0429 , 0.0000 , 0.0000 , 0.0000 , 0.0206 , 0.0000 , 0.1309 , 0.0000 , 0.3329 , 0.0000 , 0.0062 , 0.0000 , 0.0570 , 0.0000 , 0.4052 , 0.0000) ,
{3213} ( 0.0000 , 0.0000 , 0.0683 , 0.0000 , 0.5524 , 0.0000 , 0.0000 , 0.0000 , 0.0254 , 0.0000 , 0.1508 , 0.0000 , 0.0905 , 0.0000 , 0.0063 , 0.0000 , 0.0365 , 0.0000 , 0.0698 , 0.0000) ,
{3214} ( 0.0000 , 0.0000 , 0.1420 , 0.0000 , 0.4881 , 0.0000 , 0.0000 , 0.0000 , 0.0244 , 0.0000 , 0.1046 , 0.0000 , 0.1344 , 0.0000 , 0.0032 , 0.0000 , 0.0187 , 0.0000 , 0.0846 , 0.0000) ,
{3215} ( 0.0000 , 0.0000 , 0.4649 , 0.0000 , 0.3663 , 0.0000 , 0.0000 , 0.0000 , 0.0287 , 0.0000 , 0.0576 , 0.0000 , 0.0413 , 0.0000 , 0.0010 , 0.0000 , 0.0084 , 0.0000 , 0.0318 , 0.0000) ,
{3216} ( 0.0000 , 0.0000 , 0.6418 , 0.0000 , 0.0692 , 0.0000 , 0.0000 , 0.0000 , 0.0341 , 0.0000 , 0.0711 , 0.0000 , 0.0939 , 0.0000 , 0.0011 , 0.0000 , 0.0090 , 0.0000 , 0.0797 , 0.0000)) ,
{3221} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{3222} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0119 , 0.0000 , 0.2330 , 0.0000 , 0.0000 , 0.0000 , 0.0116 , 0.0000 , 0.4006 , 0.0000 , 0.0000 , 0.0000 , 0.0021 , 0.0000 , 0.3408 , 0.0000) ,
{3223} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0497 , 0.0000 , 0.7423 , 0.0000 , 0.0000 , 0.0000 , 0.0122 , 0.0000 , 0.1304 , 0.0000 , 0.0000 , 0.0000 , 0.0015 , 0.0000 , 0.0640 , 0.0000) ,
{3224} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0959 , 0.0000 , 0.5600 , 0.0000 , 0.0000 , 0.0000 , 0.0162 , 0.0000 , 0.2235 , 0.0000 , 0.0000 , 0.0000 , 0.0025 , 0.0000 , 0.1019 , 0.0000) ,
{3225} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.2745 , 0.0000 , 0.5046 , 0.0000 , 0.0000 , 0.0000 , 0.0167 , 0.0000 , 0.1436 , 0.0000 , 0.0000 , 0.0000 , 0.0020 , 0.0000 , 0.0586 , 0.0000) ,
{3226} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.2745 , 0.0000 , 0.5046 , 0.0000 , 0.0000 , 0.0000 , 0.0167 , 0.0000 , 0.1436 , 0.0000 , 0.0000 , 0.0000 , 0.0020 , 0.0000 , 0.0586 , 0.0000))) ,
{3311} ((( 0.0000 , 0.0000 , 0.0000 , 0.0018 , 0.0000 , 0.0792 , 0.0000 , 0.0000 , 0.0000 , 0.0155 , 0.0000 , 0.1573 , 0.0000 , 0.0236 , 0.0000 , 0.0995 , 0.0000 , 0.3801 , 0.0000 , 0.2430) ,
{3312} ( 0.0000 , 0.0000 , 0.0000 , 0.0063 , 0.0000 , 0.0888 , 0.0000 , 0.0000 , 0.0055 , 0.0173 , 0.0165 , 0.1909 , 0.0000 , 0.0353 , 0.0259 , 0.0487 , 0.0369 , 0.2372 , 0.0228 , 0.2679) ,
{3313} ( 0.0000 , 0.0000 , 0.0000 , 0.0064 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.1674 , 0.0622 , 0.0236 , 0.0129 , 0.0000 , 0.0064 , 0.1974 , 0.3648 , 0.0064 , 0.0579 , 0.0129 , 0.0815) ,
{3314} ( 0.0000 , 0.0000 , 0.0216 , 0.0378 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0811 , 0.1622 , 0.0054 , 0.0919 , 0.0000 , 0.0054 , 0.0973 , 0.1946 , 0.0324 , 0.0865 , 0.0162 , 0.1676) ,
{3315} ( 0.0000 , 0.0000 , 0.0000 , 0.0272 , 0.0000 , 0.0068 , 0.0000 , 0.0000 , 0.0204 , 0.0068 , 0.0136 , 0.0680 , 0.0000 , 0.0000 , 0.0272 , 0.0680 , 0.0408 , 0.3810 , 0.0408 , 0.2993) ,
{3316} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0097 , 0.0000 , 0.0777 , 0.0000 , 0.0000 , 0.0000 , 0.0680 , 0.0777 , 0.3010 , 0.0194 , 0.4466)) ,
{3321} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{3322} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0042 , 0.0006 , 0.0000 , 0.0158 , 0.0000 , 0.0000 , 0.0291 , 0.0352 , 0.0170 , 0.0873 , 0.0000 , 0.0000 , 0.0570 , 0.0485 , 0.0904 , 0.6149) ,
{3323} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0121 , 0.0452 , 0.0000 , 0.0016 , 0.0000 , 0.0000 , 0.0987 , 0.1000 , 0.0062 , 0.0524 , 0.0000 , 0.0000 , 0.1849 , 0.2386 , 0.0275 , 0.2327) ,
{3324} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0077 , 0.1386 , 0.0000 , 0.0095 , 0.0000 , 0.0000 , 0.0922 , 0.1261 , 0.0018 , 0.0547 , 0.0000 , 0.0000 , 0.0607 , 0.1190 , 0.0416 , 0.3480) ,
{3325} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0385 , 0.1374 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0275 , 0.0549 , 0.0165 , 0.0604 , 0.0000 , 0.0000 , 0.0055 , 0.0330 , 0.0714 , 0.5549) ,
{3326} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0385 , 0.1374 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0275 , 0.0549 , 0.0165 , 0.0604 , 0.0000 , 0.0000 , 0.0055 , 0.0330 , 0.0714 , 0.5549))) ,
{3411} ((( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0016 , 0.0000 , 0.0237 , 0.0000 , 0.0870 , 0.0000 , 0.0071 , 0.0000 , 0.2613 , 0.0000 , 0.6193) ,
{3412} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0022 , 0.0036 , 0.0139 , 0.0385 , 0.0000 , 0.1184 , 0.0000 , 0.0109 , 0.0130 , 0.1738 , 0.0064 , 0.6193) ,
{3413} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0075 , 0.0045 , 0.0831 , 0.0748 , 0.0000 , 0.0002 , 0.0016 , 0.0214 , 0.1088 , 0.6221 , 0.0037 , 0.0723) ,
{3414} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0052 , 0.0342 , 0.0312 , 0.2077 , 0.0000 , 0.0208 , 0.0004 , 0.0558 , 0.0108 , 0.4392 , 0.0095 , 0.1852) ,
{3415} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0016 , 0.0643 , 0.0033 , 0.0791 , 0.0000 , 0.0165 , 0.0033 , 0.0643 , 0.0231 , 0.2026 , 0.1087 , 0.4333) ,
{3416} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0070 , 0.0000 , 0.0035 , 0.0000 , 0.0000 , 0.0000 , 0.0458 , 0.0176 , 0.2606 , 0.0634 , 0.6021)) ,
{3421} (( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000) ,
{3422} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0060 , 0.0022 , 0.0582 , 0.0921 , 0.0000 , 0.0000 , 0.0068 , 0.0114 , 0.0686 , 0.7548) ,
{3423} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0198 , 0.0126 , 0.1034 , 0.1159 , 0.0000 , 0.0000 , 0.0289 , 0.1114 , 0.0866 , 0.5215) ,
{3424} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0084 , 0.0352 , 0.0155 , 0.2433 , 0.0000 , 0.0000 , 0.0048 , 0.0816 , 0.0220 , 0.5892) ,
{3425} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0083 , 0.0812 , 0.0141 , 0.2565 , 0.0000 , 0.0000 , 0.0035 , 0.0435 , 0.0518 , 0.5412) ,
{3426} ( 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0000 , 0.0083 , 0.0812 , 0.0141 , 0.2565 , 0.0000 , 0.0000 , 0.0035 , 0.0435 , 0.0518 , 0.5412)))));
pAgeCorr:array[1..NumberOfAgeGroups] of integer=(1,1,1, 2,2,2, 3,3,3, 4,4,4, 5,5,5, 6,6);
var hhds:array[1..NumberOfAreaTypes,1..nHInc,1..nHComp,0..NumberOfTimeSteps] of single;
demVar,Subregion,AreaType,HInc,HComp,ts,WorkerGr,IncomeGr,EthnicGr,HhldType,AgeGroup:integer; ouf:text;
begin
for AreaType:=1 to NumberOfAreaTypes do
for HInc:=1 to nHInc do
for HComp:=1 to nHComp do
for ts:=0 to NumberOfTimeSteps do
hhds[AreaType,HInc,HComp,ts]:=0;
for ts:=0 to NumberOfTimeSteps do begin
for AreaType:=1 to NumberOfAreaTypes do
for WorkerGr:=1 to NumberOfWorkerGrs do
for IncomeGr:=1 to NumberOfIncomeGrs do
for EthnicGr:=1 to NumberOfEthnicGrs do
for HhldType:=1 to NumberOfHhldTypes do
for AgeGroup:=1 to NumberOfAgeGroups do begin
{worker code is backwards - switch below}
HInc:=IncomeGr;
for HComp:=1 to nHComp do begin
hhds[AreaType,HInc,HComp,ts]:=
hhds[AreaType,HInc,HComp,ts]+
Population[AreaType][AgeGroup][HhldType][EthnicGr][IncomeGr][WorkerGr][ts]
* phFrac[IncomeGr,HhldType,3-WorkerGr,pAgeCorr[AgeGroup],HComp]
/ (AvgHSize[Hinc,HComp]*HSizeAdj[HCompSize[HComp]]);
end;
end;
end;
assign(ouf,OutputDirectory+RunLabel+'hhlds.csv'); rewrite(ouf);
write(ouf,'Year');
for ts:=0 to NumberOfTimeSteps do if (ts*TimeStepLength=round(ts*TimeStepLength)) then begin
write(ouf,',',StartYear + ts*TimeStepLength:4:0);
end;
writeln(ouf);
for AreaType:=1 to NumberOfAreaTypes do
for HInc:=1 to nHInc do
for HComp:=1 to nHComp do begin
write(ouf,AreaTypeLabels[AreaType],'/',
HIncLabel[HInc],'/',
HSizeLabel[HCompSize[HComp]],'/',
HWorkLabel[HCompWork[HComp]+1],'/',
HKidsLabel[HCompKids[HComp]+1]);
for ts:=0 to NumberOfTimeSteps do if (ts*TimeStepLength=round(ts*TimeStepLength)) then
write(ouf,',',hhds[AreaType,HInc,HComp,ts]:1:0);
writeln(ouf);
end;
writeln(ouf);
{write some outputs for calibration}
demVar := 0; {population by subregion}
ts:=round(5.0/TimeStepLength);
CalculateDemographicMarginals(demVar,ts);
write(ouf,'2015 Output by Age Group');
for subregion:=1 to NumberOfSubregions do write(ouf,',',SubregionLabels[subregion]);
writeln(ouf);
for AgeGroup:=1 to NumberOfAgeGroups do begin
write(ouf,AgeGroupLabels[AgeGroup]);
for subregion:=1 to NumberOfSubregions do write(ouf,',',AgeGroupMarginals[subregion][AgeGroup][ts]:1:0);
writeln(ouf);
end;
writeln(ouf); writeln(ouf);
write(ouf,'2015 Output by HHld Type');
for subregion:=1 to NumberOfSubregions do write(ouf,',',SubregionLabels[subregion]);
writeln(ouf);
for HhldType:=1 to NumberOfHhldTypes do begin
write(ouf,HhldTypeLabels[HhldType]);
for subregion:=1 to NumberOfSubregions do write(ouf,',',HhldTypeMarginals[subregion][HhldType][ts]:1:0);
writeln(ouf);
end;
writeln(ouf); writeln(ouf);
write(ouf,'2015 Output by Ethnic Group');
for subregion:=1 to NumberOfSubregions do write(ouf,',',SubregionLabels[subregion]);
writeln(ouf);
for EthnicGr:=1 to NumberOfEthnicGrs do begin
write(ouf,EthnicGrLabels[EthnicGr]);
for subregion:=1 to NumberOfSubregions do write(ouf,',',EthnicGrMarginals[subregion][EthnicGr][ts]:1:0);
writeln(ouf);
end;
writeln(ouf); writeln(ouf);
write(ouf,'2015 Output by Income Group');
for subregion:=1 to NumberOfSubregions do write(ouf,',',SubregionLabels[subregion]);
writeln(ouf);
for IncomeGr:=1 to NumberOfIncomeGrs do begin
write(ouf,IncomeGrLabels[IncomeGr]);
for subregion:=1 to NumberOfSubregions do write(ouf,',',IncomeGrMarginals[subregion][IncomeGr][ts]:1:0);
writeln(ouf);
end;
writeln(ouf); writeln(ouf);
write(ouf,'2015 Output by Workforce Part');
for subregion:=1 to NumberOfSubregions do write(ouf,',',SubregionLabels[subregion]);
writeln(ouf);
for WorkerGr:=1 to NumberOfWorkerGrs do begin
write(ouf,WorkerGrLabels[WorkerGr]);
for subregion:=1 to NumberOfSubregions do write(ouf,',',WorkerGrMarginals[subregion][WorkerGr][ts]:1:0);
writeln(ouf);
end;
writeln(ouf); writeln(ouf);
write(ouf,'2015 Output by Area Type');
for subregion:=1 to NumberOfSubregions do write(ouf,',',SubregionLabels[subregion]);
writeln(ouf);
for AreaType:=1 to NumberOfAreaTypes do begin
write(ouf,AreaTypeLabels[AreaType]);
for subregion:=1 to NumberOfSubregions do write(ouf,',',AreaTypeMarginals[subregion][AreaType][ts]:1:0);
writeln(ouf);
end;
writeln(ouf); writeln(ouf);
close(ouf);
end;
{Main simulation program}
var demVar:integer;
begin
{Read in all input data}
writeln('Loading input data from spreadsheet');
ReadUserInputData;
if testWriteYear>0 then begin
assign(outest,'test_out.csv'); rewrite(outest);
writeln(outest,'Year,AreaType,AgeGroup,HhldType,EthnicGr,IncomeGr,WorkerGr,PopulationNew,PopulationOld,',
'AgeingOut,DeathsOut,MarriagesOut,DivorcesOut,FirstChildOut,',
'EmptyNestOut,LeaveNestOut,AcculturationOut,WorkerStatusOut,IncomeGroupOut,',
'ForeignOutMigration,DomesticOutMigration,RegionalOutMigration,',
'AgeingIn,BirthsIn,MarriagesIn,DivorcesIn,FirstChildIn,',
'EmptyNestIn,LeaveNestIn,AcculturationIn,WorkerStatusIn,IncomeGroupIn,',
'ForeignInMigration,DomesticInMigration,RegionalInMigration,',
'ExogPopChange,HUrbEnter,HUrbLeave,IUrbEnter,IUrbLeave');
end;
{Initialize all sectors}
writeln('Using IPF for base year population');
InitializePopulation;
{InitializeEmployment; not necessary - in input data }
{InitializeLandUse: not necessary - in input data }
{InitializeTransportationSupply; not necessary - in input data }
{Do travel demand for year 0 without supply feedback effects}
CalculateTravelDemand(0);
{step through time t}
write('Simulating year ... ');
TimeStep:=0;
for demVar:=1 to NumberOfDemographicVariables do CalculateDemographicMarginals(demVar,TimeStep);
repeat
TimeStep := TimeStep + 1;
Year := Year + TimeStepLength;
if Year = trunc(Year) then write(Year:8:0);
{Calculate feedbacks between sectors based on levels from previous time step}
CalculateDemographicFeedbacks(TimeStep);
CalculateEmploymentFeedbacks(TimeStep);
CalculateLandUseFeedbacks(TimeStep);
CalculateTransportationSupplyFeedbacks(TimeStep);
{Calculate rate variables for time t based on levels from time t-1 and feedback effects}
CalculateDemographicTransitionRates(TimeStep);
CalculateEmploymentTransitionRates(TimeStep);
CalculateLandUseTransitionRates(TimeStep);
CalculateTransportationSupplyTransitionRates(TimeStep);
{Apply transition rates to get new levels for time t}
ApplyDemographicTransitionRates(TimeStep);
ApplyEmploymentTransitionRates(TimeStep);
ApplyLandUseTransitionRates(TimeStep);
ApplyTransportationSupplyTransitionRates(TimeStep);
{based on resulting population for time t, calculate the travel demand}
CalculateTravelDemand(TimeStep);
for demVar:=1 to NumberOfDemographicVariables do CalculateDemographicMarginals(demVar,TimeStep);
until TimeStep >= NumberOfTimeSteps; {end of simulation}
{Write out all simulation results}
writeln;
writeln('Writing results files ....');
WriteSimulationResults;
WriteHouseholdConversionFile;
{TimeStep:=0; repeat TimeStep:=TimeStep+1 until TimeStep = 9999999;}
if testWriteYear>0 then close(outest);
{write('Simulation finished. Press Enter to send results to Excel'); readln;}
end.
|
unit MasterMind.TestHelper;
interface
uses
MasterMind.API;
function MakeCode(const Colors: array of TMasterMindCodeColor): TMasterMindCode;
function MakeResult(const Hints: array of TMasterMindHint): TGuessEvaluationResult;
implementation
function MakeCode(const Colors: array of TMasterMindCodeColor): TMasterMindCode;
var
I: Integer;
begin
for I := Low(Result) to High(Result) do
Result[I] := Colors[I];
end;
function MakeResult(const Hints: array of TMasterMindHint): TGuessEvaluationResult;
var
I: Integer;
begin
for I := Low(Result) to High(Result) do
Result[I] := Hints[I];
end;
end. |
(**
THIS IS A STUB FOR TESTING THE OPEN TOOLS API.
@stopdocumentation
**)
unit ToolsAPI;
interface
Uses
IniFiles;
Type
IOTAProjectGroup = Interface
Function GetFileName : String;
Property FileName : String Read GetFileName;
End;
IOTAProject = Interface
Function GetFileName : String;
Property FileName : String Read GetFileName;
End;
TProjectStub = Class(TInterfacedObject, IOTAProject)
Function GetFileName : String;
End;
TProjectGroupStub = Class(TInterfacedObject, IOTAProjectGroup)
Function GetFileName : String;
End;
TINIHelper = Class Helper For TCustomINIFile
Strict Private
Function GetText : String;
Public
Property Text : String Read GetText;
End;
Function ProjectGroup : IOTAProjectGroup;
Function GetProjectINIFileName : String;
Function GetProjectName(Project : IOTAProject) : String;
Procedure WriteINIFile(strText, strFileName : String);
implementation
Uses
SysUtils,
Classes;
Function ProjectGroup : IOTAProjectGroup;
Begin
Result := TProjectGroupStub.Create;;
End;
Function GetProjectINIFileName : String;
Begin
Result := ExtractFilePath(ParamStr(0)) + 'TestProjectOptionsProject.ITHELPER';
End;
Function GetProjectName(Project : IOTAProject) : String;
Begin
Result := ExtractFileName(Project.FileName);
End;
Procedure WriteINIFile(strText, strFileName : String);
Var
sl : TStringList;
Begin
sl := TStringList.Create;
Try
sl.Text := strText;
sl.SaveToFile(strFileName);
Finally
sl.Free;
End;
End;
{ TProjectStub }
function TProjectStub.GetFileName: String;
begin
Result := ExtractFilePath(ParamStr(0)) + 'TestProjectOptionsProject.dpr';
end;
{ TProjectGroupStub }
function TProjectGroupStub.GetFileName: String;
begin
Result := ExtractFilePath(ParamStr(0)) + 'TestGlobalOptionsGroup.groupproj';
end;
{ TINIHelper }
function TINIHelper.GetText: String;
Var
sl : TStringList;
i : Integer;
begin
sl := TStringList.Create;
Try
ReadSections(sl);
For i := 0 To sl.Count -1 Do
Result := Result + Format('[%s]', [sl[i]]);
Finally
sl.Free;
End;
end;
end.
|
unit fPKIPINPrompt;
interface
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Variants,
System.Classes,
System.UITypes,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.StdCtrls,
Vcl.ExtCtrls,
oPKIEncryption;
type
TfrmPKIPINPrompt = class(TForm)
btnOK: TButton;
btnCancel: TButton;
edtPINValue: TEdit;
lblInstructions: TLabel;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
lblPIN: TLabel;
Label2: TLabel;
Label1: TLabel;
procedure FormShow(Sender: TObject);
procedure FormCreate(Sender: TObject);
public
class function GetPINValue: string;
class function VerifyPKIPIN(aPKIEncryptionEngine: IPKIEncryptionEngine): TPKIPINResult;
end;
implementation
{$R *.dfm}
uses
oPKIEncryptionEx, VAUtils;
procedure TfrmPKIPINPrompt.FormCreate(Sender: TObject);
begin
Self.Font := Application.MainForm.Font;
end;
procedure TfrmPKIPINPrompt.FormShow(Sender: TObject);
begin
edtPINValue.SetFocus;
end;
class function TfrmPKIPINPrompt.VerifyPKIPIN(aPKIEncryptionEngine: IPKIEncryptionEngine): TPKIPINResult;
// Prompt the user up to three times for their PIN value
var
aTryCount: integer;
aMessage: string;
aPKIEncryptionEngineEx: IPKIEncryptionEngineEx;
begin
// First we get an interface that CAN validate PINs
if aPKIEncryptionEngine.QueryInterface(IPKIEncryptionEngineEx, aPKIEncryptionEngineEx) <> 0 then
begin
MessageDlg('Internal error with IPKIEncryptionEngineEx', mtError, [mbOk], 0);
Result := prError;
end
else
with TfrmPKIPINPrompt.Create(Application) do
try
aTryCount := 1;
edtPINValue.Text := '';
while aTryCount < 4 do
case ShowModal of
mrOK:
try
if aPKIEncryptionEngineEx.getIsValidPIN(edtPINValue.Text, aMessage) then
begin
Result := prOK;
Exit;
end
else
begin
case aTryCount of
1:
MessageDlg('Invalid PIN Value Entered. You have 2 attempts left.', mtInformation, [mbOk], 0);
2:
MessageDlg('Invalid PIN Value Entered. You have one attempt left before the card is locked.', mtInformation, [mbOk], 0);
end;
Result := prError;
inc(aTryCount);
edtPINValue.Text := '';
end;
except
Result := prError;
Exit;
end;
mrCancel:
begin
if aTryCount > 1 then
MessageDlg('PKI PIN Entry Cancelled. Note: The invalid attempts are still logged on your card.', mtConfirmation, [mbOk], 0);
Result := prCancel;
Exit;
end;
end;
MessageDlg('Card is locked due to repeated invalid attempts.', mtError, [mbOk], 0);
Result := prLocked; // This is only reached if the while loop runs out
finally
Free;
end;
end;
class function TfrmPKIPINPrompt.GetPINValue: string;
begin
with TfrmPKIPINPrompt.Create(Application) do
try
if ShowModal = mrOK then
Result := edtPINValue.Text
else
Result := '';
finally
Free;
end;
end;
end.
|
program MeanNumbers;
Const
NumberOfNumbers: integer = 5;
var
Number1, Number2, Number3, Number4, Number5, Sum: integer;
Mean: real;
begin
Number1 := 45;
Number2 := 7;
Number3 := 68;
Number4 := 2;
Number5 := 34;
Sum := Number1 + Number2 + Number3 + Number4 + Number5;
Mean := Sum / NumberOfNumbers;
(* Output *)
WriteLn('Number of numbers: ', NumberOfNumbers);
WriteLn('Number 1: ', Number1);
WriteLn('Number 2: ', Number2);
WriteLn('Number 3: ', Number3);
WriteLn('Number 4: ', Number4);
WriteLn('Number 5: ', Number5);
WriteLn('Mean: ', Mean);
end.
|
program TP06P1;
uses
crt;
const
MAX=100;
type
TNombre = String[50];
TProducto = record
NroVenta : Integer;
NombreLote : TNombre;
CostoLote : Real;
end;
AProductos = Array[1..MAX] of TProducto;
(*-------------------------------ORDENACIONES---------------------------------*)
procedure Intercambiar(var X:TProducto;var Y:TProducto);
var
Temp:TProducto;
begin
Temp:=X;
X:=Y;
Y:=Temp;
end;
//seleccion
procedure OrdenarPorPrecioDesc(var Productos:AProductos; var N:integer);
var
i, j,Minimo: Integer;
begin
for i := 1 to N - 1 do
begin
Minimo:=i;
for J := (I + 1) to N Do
if (Productos[j].CostoLote > Productos[Minimo].CostoLote) then
Minimo:=j;
Intercambiar(Productos[i],Productos[Minimo]);
end
end;
(*------------------------CARGA Y UNION DE VECTORES-------------------------*)
procedure CargarVentas (var lista:AProductos;var N:integer);
var
i,CodigoError:integer;
opcion:char;
CosteLoteString:TNombre;
begin
I:=N+1;
repeat
with lista[i] do
begin
NroVenta:=i;//nro de venta se genera automaticamente
Writeln('Venta Nro. ',i);
Write('Ingrese el nombre del lote -> ');
ReadLn(NombreLote);
Write('Ingrese el costo del lote -> ');
ReadLn(CosteLoteString);
Val(CosteLoteString,CostoLote,CodigoError);
while (CodigoError<>0) do
begin
write('Coste incorrecto, por favor ingrese un valor real->');
ReadLn(CosteLoteString);
Val(CosteLoteString,CostoLote,CodigoError);
end;
end;
inc(N);
inc(i);
WriteLn();
WriteLn('Desea ingresar otra venta? S/N ->');
ReadLn(Opcion);
Opcion := upCase(Opcion);
until Opcion='N';
end;
(*------------------------MUESTRAS POR PANTALLA-----------------------------*)
procedure MostrarCabecera();
begin
Write('Nro Venta');GotoXY(20,1);
Write('Nombre Lote');GotoXY(40,1);
Writeln('Costo Lote');
end;
procedure MostrarVentaTabla(Producto:TProducto;y:integer);
begin
with Producto do
begin
Write(NroVenta);GotoXY(20,y);
Write(NombreLote);GotoXY(40,y);
WriteLn(CostoLote:5:2);
end;
end;
procedure MostrarVentas (Lista:AProductos;N:integer);
var
i:integer;
begin
MostrarCabecera();
for i:=1 to n do
begin
MostrarVentaTabla(Lista[i],i+1);
end;
end;
procedure MostrarListasFusionadas(var v1,v2:AProductos; N1,N2:integer);
var
v3:AProductos;
i,j,k,z,N3:integer;
begin
i := 1; j:=1 ; k := 1;
if(N1>= 2) and (N2>=2) then
OrdenarPorPrecioDesc(v1,n1);
OrdenarPorPrecioDesc(v2,n2);
while (i<=N1) and (j<=N2) do
begin
if (v1[i].CostoLote> v2[j].CostoLote) then
begin
v3[k] := v1[i];
i:= i+1;
end
else
begin
v3[k] := v2[j];
j:= j+1;
end;
k:=k+1;
end;
if (i>N1) then
for z:=j to N2 do
begin
v3[k]:=v2[z];
k:=k+1;
end
else
for z:=i to N1 do
begin
v3[k]:=v2[z];
k:=k+1;
end;
N3:=N1+N2;
MostrarVentas(V3,N3);
end;
function MostrarMenu ():integer;
begin
WriteLn('MENU');
WriteLN('1- Cargar ventas de lista 1 o lista 2');
WriteLn('2- Mostrar ventas de lista 1 o lista 2');
WriteLn('3- Fusionar listas en una sola');
WriteLn('0- Salir');
Write('->');
Readln(MostrarMenu);
end;
(*-------------------------------PRINCIPAL---------------------------------*)
var
Lista1,Lista2:AProductos;
N1,N2:integer;
Opcion:integer;
begin
N1:=0;
N2:=0;
repeat
ClrScr;
Opcion:=MostrarMenu();
case Opcion of
1:
begin
Writeln('Que lista desea cargar? 1 o 2?');
ReadLn(Opcion);
while (opcion<>1) and (Opcion<>2) do
begin
Writeln('opcion incorrecta, debe ser 1 o 2');
ReadLn(Opcion);
end;
if (opcion=1) then
CargarVentas(Lista1,N1)
else
CargarVentas(Lista2,N2);
end;
2:
begin
Writeln('Que lista desea mostrar? 1 o 2?');
ReadLn(Opcion);
while (opcion<>1) and (Opcion<>2) do
begin
Writeln('opcion incorrecta, debe ser 1 o 2');
ReadLn(Opcion);
end;
if (opcion=1) then
begin
ClrScr;
MostrarVentas(Lista1,N1)
end
else
begin
ClrScr;
MostrarVentas(Lista2,N2);
end;
end;
3:
begin
ClrScr;
MostrarListasFusionadas(lista1,lista2,n1,n2);
end;
0:writeln('Fin del programa');
else
writeln('Opcion incorrecta');
end;
WriteLn;
write('Presione una tecla para continuar...');
ReadKey;
until Opcion=0;
end.
|
unit caPrimes;
{$INCLUDE ca.inc}
interface
uses
// Standard Delphi units
SysUtils,
Classes,
Math,
// ca units
caClasses,
caUtils;
type
//---------------------------------------------------------------------------
// IcaPrimes
//---------------------------------------------------------------------------
IcaPrimes = interface
['{0967DBFF-AE62-43DF-95C0-4195AE106B03}']
// Property methods
function GetCount: Integer;
function GetItem(Index: Integer): Word;
// Public methods
function ClosestPrime(N: Integer): Integer;
// Properties
property Count: Integer read GetCount;
property Items[Index: Integer]: Word read GetItem; default;
end;
//---------------------------------------------------------------------------
// TcaPrimes
//---------------------------------------------------------------------------
TcaPrimes = class(TcaInterfacedPersistent, IcaPrimes)
private
// Property methods
function GetCount: Integer;
function GetItem(Index: Integer): Word;
// Private methods
function FindClosestPrimeByBinarySearch(N: Integer): Integer;
function FindClosestPrimeBySequentialSearch(N: Integer): Integer;
public
// Public methods
function ClosestPrime(N: Integer): Integer;
// Properties
property Count: Integer read GetCount;
property Items[Index: Integer]: Word read GetItem; default;
end;
implementation
const
cPrimeCount = 565;
cPrimes: array [0..Pred(cPrimeCount)] of Word = (
2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069,
1087, 1091, 1093, 1097, 1103, 1109, 1117, 1123, 1129, 1151,
1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223,
1229, 1231, 1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291,
1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367, 1373,
1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451,
1453, 1459, 1471, 1481, 1483, 1487, 1489, 1493, 1499, 1511,
1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583,
1597, 1601, 1607, 1609, 1613, 1619, 1621, 1627, 1637, 1657,
1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811,
1823, 1831, 1847, 1861, 1867, 1871, 1873, 1877, 1879, 1889,
1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987,
1993, 1997, 1999, 2003, 2011, 2017, 2027, 2029, 2039, 2053,
2063, 2069, 2081, 2083, 2087, 2089, 2099, 2111, 2113, 2129,
2131, 2137, 2141, 2143, 2153, 2161, 2179, 2203, 2207, 2213,
2221, 2237, 2239, 2243, 2251, 2267, 2269, 2273, 2281, 2287,
2293, 2297, 2309, 2311, 2333, 2339, 2341, 2347, 2351, 2357,
2371, 2377, 2381, 2383, 2389, 2393, 2399, 2411, 2417, 2423,
2437, 2441, 2447, 2459, 2467, 2473, 2477, 2503, 2521, 2531,
2539, 2543, 2549, 2551, 2557, 2579, 2591, 2593, 2609, 2617,
2621, 2633, 2647, 2657, 2659, 2663, 2671, 2677, 2683, 2687,
2689, 2693, 2699, 2707, 2711, 2713, 2719, 2729, 2731, 2741,
2749, 2753, 2767, 2777, 2789, 2791, 2797, 2801, 2803, 2819,
2833, 2837, 2843, 2851, 2857, 2861, 2879, 2887, 2897, 2903,
2909, 2917, 2927, 2939, 2953, 2957, 2963, 2969, 2971, 2999,
3001, 3011, 3019, 3023, 3037, 3041, 3049, 3061, 3067, 3079,
3083, 3089, 3109, 3119, 3121, 3137, 3163, 3167, 3169, 3181,
3187, 3191, 3203, 3209, 3217, 3221, 3229, 3251, 3253, 3257,
3259, 3271, 3299, 3301, 3307, 3313, 3319, 3323, 3329, 3331,
3343, 3347, 3359, 3361, 3371, 3373, 3389, 3391, 3407, 3413,
3433, 3449, 3457, 3461, 3463, 3467, 3469, 3491, 3499, 3511,
3517, 3527, 3529, 3533, 3539, 3541, 3547, 3557, 3559, 3571,
3581, 3583, 3593, 3607, 3613, 3617, 3623, 3631, 3637, 3643,
3659, 3671, 3673, 3677, 3691, 3697, 3701, 3709, 3719, 3727,
3733, 3739, 3761, 3767, 3769, 3779, 3793, 3797, 3803, 3821,
3823, 3833, 3847, 3851, 3853, 3863, 3877, 3881, 3889, 3907,
3911, 3917, 3919, 3923, 3929, 3931, 3943, 3947, 3967, 3989,
4001, 4003, 4007, 4013, 4019, 4021, 4027, 4049, 4051, 4057,
4073, 4079, 4091, 4093, 4099);
cMaxPrime = 4099;
//---------------------------------------------------------------------------
// TcaPrimes
//---------------------------------------------------------------------------
// Public methods
function TcaPrimes.ClosestPrime(N: Integer): Integer;
begin
if N = 2 then
Result := 2
else
begin
Result := N;
Inc(Result, Ord(not Odd(N)));
if Result <= cMaxPrime then
Result := FindClosestPrimeByBinarySearch(Result)
else
Result := FindClosestPrimeBySequentialSearch(Result);
end;
end;
// Private methods
function TcaPrimes.FindClosestPrimeByBinarySearch(N: Integer): Integer;
var
Left: Integer;
Right: Integer;
Middle: Integer;
begin
Result := N;
Left := 0;
Right := Pred(cPrimeCount);
while (Left <= Right) do
begin
Middle := (Left + Right) div 2;
if (Result = cPrimes[Middle]) then
Exit
else
begin
if (Result < cPrimes[Middle]) then
Right := Pred(Middle)
else
Left := Succ(Middle);
end;
end;
Result := cPrimes[Left];
end;
function TcaPrimes.FindClosestPrimeBySequentialSearch(N: Integer): Integer;
const
Forever = True;
var
DivisorIndex: Integer;
IsPrime: Boolean;
RootN: integer;
begin
Result := N;
if Result <= (cMaxPrime * cMaxPrime) then
begin
while Forever do
begin
RootN := Round(Sqrt(Result));
DivisorIndex := 1;
IsPrime := True;
while (DivisorIndex < cPrimeCount) and (RootN > cPrimes[DivisorIndex]) do
begin
if ((Result div cPrimes[DivisorIndex]) * cPrimes[DivisorIndex] = Result) then
begin
IsPrime := False;
Break;
end;
Inc(DivisorIndex);
end;
if IsPrime then Break;
Inc(Result, 2);
end;
end;
end;
// Property methods
function TcaPrimes.GetCount: Integer;
begin
Result := cPrimeCount;
end;
function TcaPrimes.GetItem(Index: Integer): Word;
begin
Result := cPrimes[Index];
end;
end.
|
{*******************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ WSDL Items }
{ }
{ Copyright (c) 2001 Borland Software Corporation }
{ }
{*******************************************************}
unit WSDLItems;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, TypInfo, XMLIntf, XMLDoc,
xmldom, XmlSchema, MSXMLDOM, WSDLIntf, WSDLBind;
type
{ Helper class to get WSDL Items }
TWSDLItems = class(TWSDLDocument)
private
{ Helper methods to Import WSDL documents }
procedure ImportServices(const WSDLDoc: IWSDLDocument; ServiceNames: TWideStrings);
procedure ImportPortTypes(const WSDLDoc: IWSDLDocument; PortTypeNames: TWideStrings);
procedure ImportPortsForService(const WSDLDoc: IWSDLDocument; const ServiceName: WideString; PortNames: TWideStrings);
function ImportBindingForServicePort(const WSDLDoc: IWSDLDocument; const ServiceName, PortName: WideString): WideString;
function ImportSoapAddressForServicePort(const WSDLDoc: IWSDLDocument; const ServiceName, PortName: WideString): WideString;
function ImportSoapBodyAttribute(const WSDLDoc: IWSDLDocument; const BindingName,Operation, IOType, Attribute: WideString): WideString;
function ImportSoapOperationAttribute(const WSDLDoc: IWSDLDocument; const BindingName,Operation, Attribute: WideString): WideString;
function ImportSoapBodyNamespace(const WSDLDoc: IWSDLDocument; const BindingPortType: WideString): WideString;
procedure ImportPartsForOperation(const WSDLDoc: IWSDLDocument; const PortTypeName, OperationName: WideString; OperationIndex: Integer; PartNames: TWideStrings);
public
{Helper methods to get WSDL Items}
function GetName: WideString;
function GetTargetNamespace: WideString;
procedure GetServices(ServiceNames: TWideStrings);
function GetServiceNode(const ServiceName: WideString): IXMLNode;
procedure GetMessages(MessageNames: TWideStrings);
function GetMessageNode(const MessageName: WideString): IXMLNode;
procedure GetParts(const MessageName: WideString; PartNames: TWideStrings);
function GetPartNode(const MessageName, PartName: WideString): IXMLNode;
procedure GetPortTypes(PortTypeNames: TWideStrings);
function GetPortTypeNode(const PortTypeName: WideString): IXMLNode;
procedure GetOperations(const PortTypeName: WideString; OperationNames: TWideStrings);
function GetOperationNode(const PortTypeName, OperationName: WideString): IXMLNode;
procedure GetInOutMessagesForOperation(const PortTypeName, OperationName: WideString; OperationIndex: Integer; InOutMessages: TWideStrings);
procedure GetPortsForService(const ServiceName: WideString; PortNames: TWideStrings);
function GetBindingForServicePort(const ServiceName, PortName: WideString): WideString;
function GetSoapAddressForServicePort(const ServiceName, PortName: WideString): WideString;
procedure GetImports(ImportNames: TWideStrings);
function GetLocationForImport(const ImportNameSpace: WideString): WideString;
function HasTypesNode: Boolean;
procedure GetSchemas(SchemaNames: TWideStrings);
function GetSchemaNode(const SchemaTns: WideString) : IXMLNode;
procedure GetBindings(BindingNames: TWideStrings);
function GetBindingType(const BindingName: WideString): WideString;
function GetSoapBindingAttribute(const BindingName: WideString; Attribute: WideString): WideString;
procedure GetOperationsForBinding(const BindingName: WideString; OperationNames: TWideStrings);
function GetSoapOperationAttribute(const BindingName, Operation, Attribute: WideString): WideString;
function GetSoapBodyAttribute(const BindingName, Operation, IOType, Attribute: WideString): WideString;
function GetSoapBodyNamespace(const BindingPortType: WideString): WideString;
procedure GetSoapHeaderAttribute(const BindingName, Operation, IOType, Attribute: WideString; SoapHeaderAttrs: TWideStrings);
procedure GetSoapFaultsForOperation(const BindingName, Operation: WideString; FaultNames: TWideStrings);
function GetSoapFaultAttribute(const BindingName, Operation, FaultName, Attribute: WideString): WideString;
procedure GetPartsForOperation(const PortTypeName, OperationName: WideString; OperationIndex: Integer; PartNames: TWideStrings);
end;
//Helper functions
function HasDefinition(const WSDLDoc: IWSDLDocument): Boolean;
implementation
function HasDefinition(const WSDLDoc: IWSDLDocument): Boolean;
var
Index: Integer;
begin
Result := False;
for Index := 0 to WSDLDoc.ChildNodes.Count -1 do
begin
if WSDLDoc.ChildNodes[Index].NodeName = SDefinitions then
Result := True;
end;
end;
{ TWSDLItems implementation }
function TWSDLItems.GetName: WideString;
begin
Result := Definition.Name;
end;
function TWSDLItems.GetTargetNamespace: WideString;
begin
Result := Definition.GetTargetNamespace;
end;
procedure TWSDLItems.GetServices(ServiceNames: TWideStrings);
var
Count, Index: Integer;
Services: IServices;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Services := Definition.Services;
if Services <> nil then
begin
for Count:= 0 to Services.Count-1 do
ServiceNames.Add(Services[Count].Name);
end;
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
ImportServices(ImportedWSDLDoc, ServiceNames)
end;
end;
end;
procedure TWSDLItems.ImportServices(const WSDLDoc: IWSDLDocument; ServiceNames: TWideStrings);
var
Count, Index: Integer;
Services: IServices;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Services := WSDLDoc.Definition.Services;
if Services <> nil then
begin
for Count:= 0 to Services.Count-1 do
ServiceNames.Add(Services[Count].Name);
end;
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
ImportServices(ImportedWSDLDoc, ServiceNames)
end;
end;
end;
function TWSDLItems.GetServiceNode(const ServiceName: WideString): IXMLNode;
var
Count: Integer;
Services: IServices;
ServiceNode: IXMLNode;
begin
Services := Definition.Services;
for Count:= 0 to Services.Count-1 do
if (ServiceName = Services[Count].Name) then
begin
ServiceNode := Services[Count] as IXMLNode;
break;
end;
Result := ServiceNode;
end;
procedure TWSDLItems.GetPortsForService(const ServiceName: WideString; PortNames: TWideStrings);
var
I,Index,Count: Integer;
Services: IServices;
Ports: IPorts;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Services := Definition.Services;
if Services <> nil then
begin
for Count := 0 to Services.Count -1 do
if (ServiceName = Services[Count].Name) then
begin
Ports := Services[Count].Ports;
for I := 0 to Ports.Count-1 do
PortNames.Add(Ports[I].Name);
end;
end;
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
ImportPortsForService(ImportedWSDLDoc, ServiceName, PortNames)
end;
end;
end;
procedure TWSDLItems.ImportPortsForService(const WSDLDoc: IWSDLDocument; const ServiceName: WideString; PortNames: TWideStrings);
var
I, Index, Count: Integer;
Services: IServices;
Ports: IPorts;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Services := WSDLDoc.Definition.Services;
if Services <> nil then
begin
for Count := 0 to Services.Count -1 do
if (ServiceName = Services[Count].Name) then
begin
Ports := Services[Count].Ports;
for I := 0 to Ports.Count-1 do
PortNames.Add(Ports[I].Name);
end;
end;
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
ImportPortsForService(ImportedWSDLDoc, ServiceName, PortNames)
end;
end;
end;
function TWSDLItems.GetBindingForServicePort(const ServiceName, PortName: WideString): WideString;
var
I, Index, Count: Integer;
BindingName: WideString;
Services: IServices;
Ports: IPorts;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
BindingName := '';
Services := Definition.Services;
if Services <> nil then
for Count := 0 to Services.Count -1 do
if (ServiceName = Services[Count].Name) then
begin
Ports := Services[Count].Ports;
for I := 0 to Ports.Count-1 do
if (PortName = Ports[I].Name) then
begin
BindingName := Ports[I].Binding;
break;
end;
break;
end;
if BindingName = '' then
begin
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
BindingName := ImportBindingForServicePort(ImportedWSDLDoc, ServiceName, PortName);
if BindingName <> '' then
break;
end;
end;
end;
Result := BindingName;
end;
function TWSDLItems.ImportBindingForServicePort(const WSDLDoc: IWSDLDocument; const ServiceName, PortName: WideString): WideString;
var
I, Index, Count: Integer;
BindingName: WideString;
Services: IServices;
Ports: IPorts;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
BindingName := '';
Services := WSDLDoc.Definition.Services;
if Services <> nil then
for Count := 0 to Services.Count -1 do
if (ServiceName = Services[Count].Name) then
begin
Ports := Services[Count].Ports;
for I := 0 to Ports.Count-1 do
if (PortName = Ports[I].Name) then
begin
BindingName := Ports[I].Binding;
break;
end;
break;
end;
if BindingName = '' then
begin
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
BindingName := ImportBindingForServicePort(ImportedWSDLDoc, ServiceName, PortName);
if BindingName <> '' then
break;
end;
end;
end;
Result := BindingName;
end;
function TWSDLItems.GetSoapAddressForServicePort(const ServiceName, PortName: WideString): WideString;
var
I, J, Index, Count: Integer;
SoapAddress: WideString;
Services: IServices;
AddressNode: IXMLNode;
Ports: IPorts;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
SoapAddress := '';
Services := Definition.Services;
if Services <> nil then
for Count := 0 to Services.Count -1 do
if (ServiceName = Services[Count].Name) then
begin
Ports := Services[Count].Ports;
for I := 0 to Ports.Count-1 do
if (PortName = Ports[I].Name) then
begin
for J := 0 to Ports[I].ChildNodes.Count -1 do
begin
if Ports[I].ChildNodes.Nodes[J].NodeName = SWSDLSoapAddress then
begin
AddressNode := Ports[I].ChildNodes.Nodes[J];
SoapAddress := AddressNode.Attributes[SLocation];
break;
end;
end;
break;
end;
break;
end;
if SoapAddress = '' then
begin
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
SoapAddress := ImportSoapAddressForServicePort(ImportedWSDLDoc, ServiceName, PortName);
if SoapAddress <> '' then
break;
end;
end;
end;
Result := SoapAddress;
end;
function TWSDLItems.ImportSoapAddressForServicePort(const WSDLDoc: IWSDLDocument; const ServiceName, PortName: WideString): WideString;
var
I, J, Index, Count: Integer;
SoapAddress: WideString;
Services: IServices;
AddressNode: IXMLNode;
Ports: IPorts;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
SoapAddress := '';
Services := WSDLDoc.Definition.Services;
if Services <> nil then
for Count := 0 to Services.Count -1 do
if (ServiceName = Services[Count].Name) then
begin
Ports := Services[Count].Ports;
for I := 0 to Ports.Count-1 do
if (PortName = Ports[I].Name) then
begin
for J := 0 to Ports[I].ChildNodes.Count -1 do
begin
if Ports[I].ChildNodes.Nodes[J].NodeName = SWSDLSoapAddress then
begin
AddressNode := Ports[I].ChildNodes.Nodes[J];
SoapAddress := AddressNode.Attributes[SLocation];
break;
end;
end;
break;
end;
break;
end;
if SoapAddress = '' then
begin
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
SoapAddress := ImportSoapAddressForServicePort(ImportedWSDLDoc, ServiceName, PortName);
if SoapAddress <> '' then
break;
end;
end;
end;
Result := SoapAddress;
end;
procedure TWSDLItems.GetMessages(MessageNames: TWideStrings);
var
Count: Integer;
Messages: IMessages;
begin
Messages := Definition.Messages;
for Count:= 0 to Messages.Count-1 do
MessageNames.Add(Messages[Count].Name);
end;
function TWSDLItems.GetMessageNode(const MessageName: WideString): IXMLNode;
var
Count: Integer;
MessageNode: IXMLNode;
Messages: IMessages;
begin
Messages := Definition.Messages;
for Count := 0 to Messages.Count-1 do
if (MessageName = Messages[Count].Name) then
begin
MessageNode := Messages[Count] as IXMLNode;
break;
end;
Result := MessageNode;
end;
procedure TWSDLItems.GetParts(const MessageName: WideString; PartNames: TWideStrings);
var
I, Count: Integer;
UnQMessageName: WideString;
Messages: IMessages;
Parts: IParts;
begin
Messages := Definition.Messages;
for Count := 0 to Messages.Count-1 do
begin
UnQMessageName := ExtractLocalName(MessageName);
if( (UnQMessageName = Messages[Count].Name) or
(MessageName = Messages[Count].Name) ) then
begin
Parts := Messages[Count].Parts;
break;
end;
end;
if Parts <> nil then
for I := 0 to Parts.Count -1 do
begin
{
if ( Parts[I].Element <> '' ) then
PartName := Parts[I].Name + ',' + Parts[I].Element;
if ( Parts[I].Type_ <> '') then
PartName := Parts[I].Name + ',' + Parts[I].Type_;
PartNames.Add(PartName);
}
PartNames.Add(Parts[I].Name);
end;
end;
function TWSDLItems.GetPartNode(const MessageName, PartName: WideString): IXMLNode;
var
I, Count: Integer;
Messages: IMessages;
Parts: IParts;
PartNode: IXMLNode;
begin
Messages := Definition.Messages;
for Count := 0 to Messages.Count-1 do
if (MessageName = Messages[Count].Name) then
begin
Parts := Messages[Count].Parts;
break;
end;
for I := 0 to Parts.Count -1 do
if (PartName = Parts[I].Name) then
begin
PartNode := Parts[I] as IXMLNode;
break;
end;
Result := PartNode;
end;
procedure TWSDLItems.GetPortTypes (PortTypeNames: TWideStrings);
var
Count, Index: Integer;
PortTypes: IPortTypes;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
PortTypeNames.Add(PortTypes[Count].Name);
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
ImportPortTypes(ImportedWSDLDoc, PortTypeNames)
end;
end;
end;
procedure TWSDLItems.ImportPortTypes (const WSDLDoc: IWSDLDocument; PortTypeNames: TWideStrings);
var
Count, Index: Integer;
PortTypes: IPortTypes;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
PortTypes := WSDLDoc.Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
PortTypeNames.Add(PortTypes[Count].Name);
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
ImportPortTypes(ImportedWSDLDoc, PortTypeNames)
end;
end;
end;
function TWSDLItems.GetPortTypeNode(const PortTypeName: WideString): IXMLNode;
var
Count: Integer;
PortTypeNode: IXMLNode;
PortTypes: IPortTypes;
begin
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if (PortTypeName = PortTypes[Count].Name) then
begin
PortTypeNode := PortTypes[Count] as IXMLNode;
break;
end;
Result := PortTypeNode;
end;
procedure TWSDLItems.GetOperations(const PortTypeName: WideString; OperationNames: TWideStrings);
var
I, Count: Integer;
PortTypes: IPortTypes;
Operations: IOperations;
begin
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if (PortTypeName = PortTypes[Count].Name) then
begin
Operations := PortTypes[Count].Operations;
break;
end;
if Operations <> nil then
for I:=0 to Operations.Count -1 do
OperationNames.Add(Operations[I].Name);
end;
function TWSDLItems.GetOperationNode(const PortTypeName, OperationName: WideString): IXMLNode;
var
I, Count: Integer;
PortTypes: IPortTypes;
Operations: IOperations;
OperationNode : IXMLNode;
begin
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if (PortTypeName = PortTypes[Count].Name) then
begin
Operations := PortTypes[Count].Operations;
break;
end;
for I:=0 to Operations.Count -1 do
if (OperationName = Operations[I].Name) then
begin
OperationNode := Operations[I] as IXMLNode;
break;
end;
Result := OperationNode;
end;
procedure TWSDLItems.GetInOutMessagesForOperation(const PortTypeName, OperationName: WideString; OperationIndex: Integer; InOutMessages: TWideStrings);
var
I, Count: Integer;
InOutMessageName: WideString;
PortTypes: IPortTypes;
Operations: IOperations;
begin
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if (PortTypeName = PortTypes[Count].Name) then
begin
Operations := PortTypes[Count].Operations;
break;
end;
for I:=0 to Operations.Count -1 do
if ((OperationName = Operations[I].Name) and (OperationIndex = I)) then
begin
if (Operations[I].Input.Message <> '') then
begin
InOutMessageName := SInput + ', ' + Operations[I].Input.Message;
InOutMessages.Add(InOutMessageName);
end;
if (Operations[I].Output.Message <> '') then
begin
InOutMessageName := SOutput + ', ' + Operations[I].Output.Message;
InOutMessages.Add(InOutMessageName);
end;
end;
end;
procedure TWSDLItems.GetPartsForOperation(const PortTypeName, OperationName: WideString; OperationIndex: Integer; PartNames: TWideStrings);
var
I,Index,Count: Integer;
PortTypes: IPortTypes;
Operations: IOperations;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
PortTypes := Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if (PortTypeName = PortTypes[Count].Name) then
begin
Operations := PortTypes[Count].Operations;
break;
end;
if ((Operations <> nil) and (Operations.Count > 0)) then
begin
for I:=0 to Operations.Count -1 do
if ((OperationName = Operations[I].Name) and (OperationIndex = I)) then
begin
if (Operations[I].Input.Message <> '') then
GetParts(Operations[I].Input.Message, PartNames);
end;
end
else
begin
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
ImportPartsForOperation(ImportedWSDLDoc, PortTypeName, OperationName, OperationIndex, PartNames)
end;
end;
end;
end;
procedure TWSDLItems.ImportPartsForOperation(const WSDLDoc: IWSDLDocument; const PortTypeName, OperationName: WideString; OperationIndex: Integer; PartNames: TWideStrings);
var
I, Index, Count: Integer;
PortTypes: IPortTypes;
Operations: IOperations;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
PortTypes := WSDLDoc.Definition.PortTypes;
for Count:= 0 to PortTypes.Count-1 do
if (PortTypeName = PortTypes[Count].Name) then
begin
Operations := PortTypes[Count].Operations;
break;
end;
if ((Operations <> nil) and (Operations.Count > 0) ) then
begin
for I:=0 to Operations.Count -1 do
if ((OperationName = Operations[I].Name) and (OperationIndex = I)) then
begin
if (Operations[I].Input.Message <> '') then
GetParts(Operations[I].Input.Message, PartNames);
end;
end
else
begin
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
ImportPartsForOperation(ImportedWSDLDoc, PortTypeName, OperationName, OperationIndex, PartNames);
end;
end;
end;
end;
procedure TWSDLItems.GetImports(ImportNames: TWideStrings);
var
Count: Integer;
Imports: IImports;
begin
Imports := Definition.Imports;
for Count := 0 to Imports.Count -1 do
ImportNames.Add(Imports[Count].Namespace);
end;
function TWSDLItems.GetLocationForImport(const ImportNameSpace: WideString): WideString;
var
Count: Integer;
Location: WideString;
Imports: IImports;
begin
Imports := Definition.Imports;
for Count := 0 to Imports.Count -1 do
if (ImportNameSpace = Imports[Count].Namespace) then
begin
Location := Imports[Count].Location;
break;
end;
Result := Location;
end;
procedure TWSDLItems.GetBindings(BindingNames: TWideStrings);
var
Count: Integer;
Bindings: IBindings;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
BindingNames.Add(Bindings[Count].Name);
end;
function TWSDLItems.GetBindingType(const BindingName: WideString): WideString;
var
Count: Integer;
BindingTypeName: WideString;
Bindings: IBindings;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindingTypeName := Bindings[Count].Type_;
break;
end;
Result := BindingTypeName;
end;
function TWSDLItems.GetSoapBindingAttribute(const BindingName: WideString; Attribute: WideString): WideString;
var
I,Count: Integer;
BindingAttribute: WideString;
Bindings: IBindings;
SoapBinding: IXMLNode;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
for I := 0 to Bindings[Count].ChildNodes.Count -1 do
if Bindings[Count].ChildNodes.Nodes[I].NodeName = SWSDLSoapBinding then
begin
SoapBinding := Bindings[Count].ChildNodes.Nodes[I];
if (SoapBinding.GetAttribute(Attribute) <> Null ) then
BindingAttribute := SoapBinding.GetAttribute(Attribute);
end;
break;
end;
Result := BindingAttribute;
end;
procedure TWSDLItems.GetOperationsForBinding(const BindingName: WideString; OperationNames: TWideStrings);
var
I,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
OperationNames.Add(BindOperations[I].Name);
break;
end;
end;
function TWSDLItems.GetSoapOperationAttribute(const BindingName,Operation, Attribute: WideString): WideString;
var
I,J,Index,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
SoapOperationNode: IXMLNode;
SoapOperationAttr: WideString;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
SoapOperationAttr := '';
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
if (Operation = BindOperations[I].Name) then
begin
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if (BindOperations[I].ChildNodes.Nodes[J].NodeName = SWSDLSoapOperation ) then
begin
SoapOperationNode := BindOperations[I].ChildNodes.Nodes[J];
if (SoapOperationNode.Attributes[Attribute] <> Null) then
SoapOperationAttr := SoapOperationNode.Attributes[Attribute];
break;
end;
break;
end;
end;
break;
end;
if SoapOperationAttr = '' then
begin
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
SoapOperationAttr := ImportSoapOperationAttribute(ImportedWSDLDoc, BindingName, Operation, Attribute);
if SoapOperationAttr <> '' then
break;
end;
end;
end;
Result := SoapOperationAttr;
end;
function TWSDLItems.ImportSoapOperationAttribute(const WSDLDoc: IWSDLDocument; const BindingName,Operation, Attribute: WideString): WideString;
var
I,J,Index,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
SoapOperationNode: IXMLNode;
SoapOperationAttr: WideString;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
SoapOperationAttr := '';
Bindings := WSDLDoc.Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
if (Operation = BindOperations[I].Name) then
begin
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if (BindOperations[I].ChildNodes.Nodes[J].NodeName = SWSDLSoapOperation ) then
begin
SoapOperationNode := BindOperations[I].ChildNodes.Nodes[J];
if (SoapOperationNode.Attributes[Attribute] <> Null) then
SoapOperationAttr := SoapOperationNode.Attributes[Attribute];
break;
end;
break;
end;
end;
break;
end;
if SoapOperationAttr = '' then
begin
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
SoapOperationAttr := ImportSoapOperationAttribute(ImportedWSDLDoc, BindingName, Operation, Attribute);
if SoapOperationAttr <> '' then
break;
end;
end;
end;
Result := SoapOperationAttr;
end;
function TWSDLItems.GetSoapBodyAttribute(const BindingName,Operation, IOType, Attribute: WideString): WideString;
var
I,J,K,Index,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
IONode, SoapBodyNode: IXMLNode;
Attr: WideString;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
Attr := '';
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
if (Operation = BindOperations[I].Name) then
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if (BindOperations[I].ChildNodes.Nodes[J].NodeName = IOType) then
begin
IONode := BindOperations[I].ChildNodes.Nodes[J];
for K := 0 to IONode.ChildNodes.Count -1 do
if (IONode.ChildNodes.Nodes[K].NodeName = SWSDLSoapBody) then
begin
SoapBodyNode := IONode.ChildNodes[K];
if (SoapBodyNode.Attributes[Attribute] <> Null) then
Attr := SoapBodyNode.Attributes[Attribute];
break;
end;
break;
end;
end;
break;
end;
if Attr = '' then
begin
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
Attr := ImportSoapBodyAttribute(ImportedWSDLDoc, BindingName, Operation, IOType, Attribute);
if Attr <> '' then
break;
end;
end;
end;
Result := Attr;
end;
function TWSDLItems.ImportSoapBodyAttribute(const WSDLDoc: IWSDLDocument; const BindingName,Operation, IOType, Attribute: WideString): WideString;
var
I,J,K,Index,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
IONode, SoapBodyNode: IXMLNode;
Attr: WideString;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
Attr := '';
Bindings := WSDLDoc.Definition.Bindings;
if Bindings <> nil then
begin
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
if (Operation = BindOperations[I].Name) then
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if (BindOperations[I].ChildNodes.Nodes[J].NodeName = IOType) then
begin
IONode := BindOperations[I].ChildNodes.Nodes[J];
for K := 0 to IONode.ChildNodes.Count -1 do
if (IONode.ChildNodes.Nodes[K].NodeName = SWSDLSoapBody) then
begin
SoapBodyNode := IONode.ChildNodes[K];
if (SoapBodyNode.Attributes[Attribute] <> Null) then
Attr := SoapBodyNode.Attributes[Attribute];
break;
end;
break;
end;
end;
break;
end;
end;
if Attr = '' then
begin
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
Attr := ImportSoapBodyAttribute(ImportedWSDLDoc, BindingName, Operation, IOType, Attribute);
if Attr <> '' then
break;
end;
end;
end;
Result := Attr;
end;
function TWSDLItems.GetSoapBodyNamespace(const BindingPortType: WideString): WideString;
var
I,J,K,Index,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
IONode, SoapBodyNode: IXMLNode;
Attr: WideString;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
Attr := '';
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingPortType = Bindings[Count].Type_) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if ((BindOperations[I].ChildNodes.Nodes[J].NodeName = SInput) or
(BindOperations[I].ChildNodes.Nodes[J].NodeName = SOutput))then
begin
IONode := BindOperations[I].ChildNodes.Nodes[J];
for K := 0 to IONode.ChildNodes.Count -1 do
if (IONode.ChildNodes.Nodes[K].NodeName = SWSDLSoapBody) then
begin
SoapBodyNode := IONode.ChildNodes[K];
if (SoapBodyNode.Attributes[SNamespace] <> Null) then
Attr := SoapBodyNode.Attributes[SNamespace];
break;
end;
break;
end;
end;
break;
end;
if Attr = '' then
begin
//Get any imported WSDL
Imports := Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
Attr := ImportSoapBodyNamespace(ImportedWSDLDoc, BindingPortType);
if Attr <> '' then
break;
end;
end;
end;
Result := Attr;
end;
function TWSDLItems.ImportSoapBodyNamespace(const WSDLDoc: IWSDLDocument; const BindingPortType: WideString): WideString;
var
I,J,K,Index,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
IONode, SoapBodyNode: IXMLNode;
Attr: WideString;
Imports: IImports;
ImportedWSDLDoc: IWSDLDocument;
begin
Result := '';
Attr := '';
Bindings := WSDLDoc.Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingPortType = Bindings[Count].Type_) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if ((BindOperations[I].ChildNodes.Nodes[J].NodeName = SInput) or
(BindOperations[I].ChildNodes.Nodes[J].NodeName = SOutput))then
begin
IONode := BindOperations[I].ChildNodes.Nodes[J];
for K := 0 to IONode.ChildNodes.Count -1 do
if (IONode.ChildNodes.Nodes[K].NodeName = SWSDLSoapBody) then
begin
SoapBodyNode := IONode.ChildNodes[K];
if (SoapBodyNode.Attributes[SNamespace] <> Null) then
Attr := SoapBodyNode.Attributes[SNamespace];
break;
end;
break;
end;
end;
break;
end;
if Attr = '' then
begin
//Get any imported WSDL
Imports := WSDLDoc.Definition.Imports;
if Imports <> nil then
begin
for Index := 0 to Imports.Count -1 do
begin
ImportedWSDLDoc := TWSDLDocument.Create(nil);
ImportedWSDLDoc.FileName := Imports[Index].Location;
ImportedWSDLDoc.Active := True;
if HasDefinition(ImportedWSDLDoc) then
Attr := ImportSoapBodyNamespace(ImportedWSDLDoc, BindingPortType);
if Attr <> '' then
break;
end;
end;
end;
Result := Attr;
end;
procedure TWSDLItems.GetSoapHeaderAttribute(const BindingName, Operation, IOType, Attribute: WideString; SoapHeaderAttrs: TWideStrings);
var
I,J,K,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
IONode, SoapHeaderNode: IXMLNode;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
begin
if (Operation = BindOperations[I].Name) then
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if (BindOperations[I].ChildNodes.Nodes[J].NodeName = IOType) then
begin
IONode := BindOperations[I].ChildNodes.Nodes[J];
for K := 0 to IONode.ChildNodes.Count -1 do
if (IONode.ChildNodes.Nodes[K].NodeName = SWSDLSoapHeader) then
begin
SoapHeaderNode := IONode.ChildNodes[K];
if (SoapHeaderNode.Attributes[Attribute] <> Null) then
SoapHeaderAttrs.Add(SoapHeaderNode.Attributes[Attribute]);
end;
break;
end;
end;
break;
end;
end;
procedure TWSDLItems.GetSoapFaultsForOperation(const BindingName, Operation: WideString; FaultNames: TWideStrings);
var
I,J,K,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
FaultNode, SoapFaultNode: IXMLNode;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
if (Operation = BindOperations[I].Name) then
begin
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if (BindOperations[I].ChildNodes.Nodes[J].NodeName = SFault) then
begin
FaultNode := BindOperations[I].ChildNodes.Nodes[J];
for K := 0 to FaultNode.ChildNodes.Count -1 do
if (FaultNode.ChildNodes.Nodes[K].NodeName = SWSDLSoapFault) then
begin
SoapFaultNode := FaultNode.ChildNodes[K];
if (SoapFaultNode.Attributes[SName] <> Null) then
FaultNames.Add(SoapFaultNode.Attributes[SName]);
end;
end;
break;
end; //end if operation
break;
end; //end if BindingName
end;
function TWSDLItems.GetSoapFaultAttribute(const BindingName, Operation, FaultName, Attribute: WideString): WideString;
var
I,J,K,Count: Integer;
Bindings: IBindings;
BindOperations: IBindingOperations;
FaultNode, SoapFaultNode: IXMLNode;
Attr: WideString;
begin
Bindings := Definition.Bindings;
for Count := 0 to Bindings.Count -1 do
if (BindingName = Bindings[Count].Name) then
begin
BindOperations := Bindings[Count].BindingOperations;
for I := 0 to BindOperations.Count -1 do
if (Operation = BindOperations[I].Name) then
begin
for J := 0 to BindOperations[I].ChildNodes.Count -1 do
if (BindOperations[I].ChildNodes.Nodes[J].NodeName = SFault) then
begin
FaultNode := BindOperations[I].ChildNodes.Nodes[J];
for K := 0 to FaultNode.ChildNodes.Count -1 do
if (FaultNode.ChildNodes.Nodes[K].NodeName = SWSDLSoapFault) then
begin
SoapFaultNode := FaultNode.ChildNodes[K];
if (SoapFaultNode.Attributes[SName] <> Null) then
if (FaultName = SoapFaultNode.Attributes[SName]) then
if (SoapFaultNode.Attributes[Attribute] <> Null) then
Attr := SoapFaultNode.Attributes[Attribute];
end;
end;
break;
end; //end if operation
break;
end; //end if BindingName
Result := Attr;
end;
function TWSDLItems.HasTypesNode: Boolean;
begin
Result := False;
if (Definition.Types <> nil) then
Result := True;
end;
procedure TWSDLItems.GetSchemas(SchemaNames: TWideStrings);
var
Types: ITypes;
Tns: WideString;
Index: Integer;
begin
Types := Definition.Types;
if (Types <> nil) and (Types.SchemaDefs.Count > 0) then
begin
for Index := 0 to Types.SchemaDefs.Count - 1 do
begin
Tns := Types.SchemaDefs[Index].Attributes[sTns];
SchemaNames.Add(Tns);
end;
end;
end;
function TWSDLItems.GetSchemaNode(const SchemaTns: WideString) : IXMLNode;
var
Index: Integer;
Types: ITypes;
SchemaRootNode: IXMLNode;
begin
Types := Definition.Types;
if (Types <> nil) and (Types.SchemaDefs.Count > 0) then
begin
for Index := 0 to Types.SchemaDefs.Count - 1 do
begin
if ( SchemaTns = Types.SchemaDefs[Index].Attributes[sTns] ) then
begin
SchemaRootNode := Types.SchemaDefs[Index] as IXMLNode;
break;
end;
end;
end;
Result := SchemaRootNode;
end;
end.
|
unit TestUtils;
interface
uses
System.SysUtils,
TestFramework;
type
TInterfaceTestCase<I : IInterface> = class abstract (TGenericTestCase)
strict private
FSUT : I;
strict protected
function SUTAsClass<T : class> : T;
property SUT : I read FSUT;
protected
procedure DoSetUp; virtual;
procedure DoTearDown; virtual;
function MakeSUT : I; virtual; abstract;
public
procedure SetUp; override; final;
procedure TearDown; override; final;
end;
TTestCaseHelper = class helper for TTestCase
private
const
STR_PROJECT_GROUP_DIR_RELATIVE_PATH = '..\..\..\..\';
public
procedure CheckAggregateException(const AProc : TProc; AExceptionClass : ExceptClass;
const Msg : String = String.Empty);
procedure CheckEquals(Expected, Actual : TObject; const Msg : String = String.Empty); overload;
procedure CheckException(const AProc : TProc; AExceptionClass : ExceptClass;
const Msg : String = String.Empty); overload;
procedure CheckFalse(Condition : Boolean; const Msg : String; const Args : array of const); overload;
procedure CheckInnerException(const AProc : TProc; AExceptionClass : ExceptClass;
const Msg : String = String.Empty);
procedure CheckNotEquals(Expected, Actual : TObject; const Msg : String = String.Empty); overload;
procedure CheckTrue(Condition : Boolean; const Msg : String; const Args : array of const); overload;
function CloneFile(const FileName : TFileName) : TFileName;
procedure DebugMsg(const Msg : String; const Args : array of const);
function GetCurrTestMethodAddr : Pointer;
function GetProjectGroupDir : String;
function GetTestIniFileName : TFileName;
end;
{ Utils }
function LinesCount(const S : String) : Integer;
implementation
uses
System.IOUtils, System.Threading,
Winapi.Windows, Vcl.Dialogs,
DUnitConsts;
{ Utils }
function LinesCount(const S : String) : Integer;
begin
if S.IsEmpty then
Result := 0
else
Result := S.CountChar(#10) + 1;
end;
{ TInterfaceTestCase<I> }
procedure TInterfaceTestCase<I>.DoSetUp;
begin
{NOP}
end;
procedure TInterfaceTestCase<I>.DoTearDown;
begin
{NOP}
end;
procedure TInterfaceTestCase<I>.SetUp;
begin
FSUT := MakeSUT;
DoSetUp;
end;
function TInterfaceTestCase<I>.SUTAsClass<T> : T;
begin
Result := nil;
if FSUT <> nil then
if TObject(IInterface(FSUT)).InheritsFrom(T) then
Result := TObject(IInterface(FSUT)) as T;
end;
procedure TInterfaceTestCase<I>.TearDown;
begin
DoTearDown;
FSUT := nil;
end;
{ TTestCaseHelper }
procedure TTestCaseHelper.CheckAggregateException(const AProc : TProc; AExceptionClass : ExceptClass; const Msg : String);
var
bFound : Boolean;
E : Exception;
begin
FCheckCalled := True;
try
AProc;
except
on Raised: Exception do
begin
if not Assigned(AExceptionClass) then
raise
else
begin
bFound := False;
if Raised.InheritsFrom(EAggregateException) then
for E in EAggregateException(Raised) do
if E.InheritsFrom(AExceptionClass) then
begin
bFound := True;
Break;
end;
if bFound then
AExceptionClass := nil
else
FailNotEquals(AExceptionClass.ClassName,
Format('%s:%s%s', [Raised.ClassName, sLineBreak, Raised.ToString]), Msg, ReturnAddress);
end;
end;
end;
if Assigned(AExceptionClass) then
FailNotEquals(AExceptionClass.ClassName, sExceptionNothig, Msg, ReturnAddress);
end;
procedure TTestCaseHelper.CheckEquals(Expected, Actual : TObject; const Msg : String);
begin
FCheckCalled := True;
if Pointer(Expected) <> Pointer(Actual) then
FailNotEquals(Format('%p', [Pointer(Expected)]), Format('%p', [Pointer(Actual)]), Msg, ReturnAddress);
end;
procedure TTestCaseHelper.CheckException(const AProc : TProc; AExceptionClass : ExceptClass; const Msg : String);
begin
FCheckCalled := True;
try
AProc;
except
on E: Exception do
begin
if not Assigned(AExceptionClass) then
raise
else
if not E.InheritsFrom(AExceptionClass) then
FailNotEquals(AExceptionClass.ClassName, E.ClassName, Msg, ReturnAddress)
else
AExceptionClass := nil;
end;
end;
if Assigned(AExceptionClass) then
FailNotEquals(AExceptionClass.ClassName, sExceptionNothig, Msg, ReturnAddress);
end;
procedure TTestCaseHelper.CheckFalse(Condition : Boolean; const Msg : String; const Args : array of const);
begin
FCheckCalled := True;
if Condition then
FailNotEquals(BoolToStr(False), BoolToStr(True), Format(Msg, Args), ReturnAddress);
end;
procedure TTestCaseHelper.CheckInnerException(const AProc : TProc; AExceptionClass : ExceptClass; const Msg : String);
var
bFound : Boolean;
E : Exception;
begin
FCheckCalled := True;
try
AProc;
except
on Raised: Exception do
begin
if not Assigned(AExceptionClass) then
raise
else
begin
bFound := False;
E := Raised;
while Assigned(E.InnerException) do
if not E.InnerException.InheritsFrom(AExceptionClass) then
E := E.InnerException
else
begin
bFound := True;
Break;
end;
if bFound then
AExceptionClass := nil
else
FailNotEquals(AExceptionClass.ClassName,
Format('%s:%s%s', [Raised.ClassName, sLineBreak, Raised.ToString]), Msg, ReturnAddress);
end;
end;
end;
if Assigned(AExceptionClass) then
FailNotEquals(AExceptionClass.ClassName, sExceptionNothig, Msg, ReturnAddress);
end;
procedure TTestCaseHelper.CheckNotEquals(Expected, Actual : TObject; const Msg : String);
begin
FCheckCalled := True;
if Pointer(Expected) = Pointer(Actual) then
FailEquals(Format('%p', [Pointer(Expected)]), Format('%p', [Pointer(Actual)]), Msg, ReturnAddress);
end;
procedure TTestCaseHelper.CheckTrue(Condition : Boolean; const Msg : String; const Args : array of const);
begin
FCheckCalled := True;
if not Condition then
FailNotEquals(BoolToStr(True), BoolToStr(False), Format(Msg, Args), ReturnAddress);
end;
function TTestCaseHelper.CloneFile(const FileName : TFileName) : TFileName;
const
STR_CLONE_EXT = '.clone';
var
sCloneFileName : TFileName;
begin
Result := String.Empty;
if TFile.Exists(FileName) then
begin
sCloneFileName := String(FileName).Substring(0, MAX_PATH - Length(STR_CLONE_EXT) - 1) + STR_CLONE_EXT;
TFile.Copy(FileName, sCloneFileName, True);
if TFile.Exists(sCloneFileName) then
Result := sCloneFileName;
end;
end;
procedure TTestCaseHelper.DebugMsg(const Msg : String; const Args : array of const);
begin
ShowMessageFmt(Msg, Args);
end;
function TTestCaseHelper.GetCurrTestMethodAddr : Pointer;
begin
if Assigned(fMethod) then
Result := TMethod(fMethod).Code
else
Result := nil;
end;
function TTestCaseHelper.GetProjectGroupDir : String;
var
iLevels, i : Integer;
arrTokens : TArray<String>;
begin
iLevels := 0;
arrTokens := String(STR_PROJECT_GROUP_DIR_RELATIVE_PATH)
.Split([TPath.DirectorySeparatorChar], TStringSplitOptions.ExcludeEmpty);
for i := High(arrTokens) downto 0 do
if arrTokens[i] = '..' then
Inc(iLevels)
else
Break;
arrTokens := TestDataDir.Split([TPath.DirectorySeparatorChar], TStringSplitOptions.ExcludeEmpty);
Result := String
.Join(TPath.DirectorySeparatorChar, arrTokens, 0, Length(arrTokens) - iLevels) + TPath.DirectorySeparatorChar;
end;
function TTestCaseHelper.GetTestIniFileName : TFileName;
begin
Result := TestDataDir + TPath.GetFileNameWithoutExtension(ParamStr(0)) + '.ini';
end;
end.
|
unit DB_Handle;
interface
uses Classes, SysUtils, ASGSQLite3, StdCtrls, DB_GetData, DB_Type;
function CheckInventory(StockNO: String): TInventory_Stock;
function CheckTestMode(): boolean;
procedure UpdateRestart(SetValue: String);
implementation
uses DMRecord;
function CheckInventory(StockNO: String): TInventory_Stock;
var sql_str, IsTestMode: String;
begin
if(DB_Handle.CheckTestMode) then
IsTestMode:= '1'
else IsTestMode:= '0';
sql_str:= 'select * from RecordMsg where StockNM="' + StockNO + '" and TestMode="' + IsTestMode + '"';
DB_GetData.GetFree_Sql(sql_str, DataModule1.asqQU_Temp);
if(DataModule1.asqQU_Temp.RecordCount > 0) then begin
DataModule1.asqQU_Temp.Last;
Result.LeftQty:= DataModule1.asqQU_Temp.FindField('LeftQty').AsInteger;
Result.LastBuySell:= DataModule1.asqQU_Temp.FindField('BuySell').AsString;
Result.LastPrice:= DataModule1.asqQU_Temp.FindField('Price').AsFloat;
end else begin
Result.LeftQty:= 0;
end;
end;
function CheckTestMode(): boolean;
begin
DB_GetData.GetSpecific_Sql('TestMode', '', '', 'tbConfigure', DataModule1.asqQU_Temp, true);
if(DataModule1.asqQU_Temp.RecordCount > 0) then begin
Result:= DataModule1.asqQU_Temp.FieldByName('TestMode').AsString= '1';
end else begin
Result:= false;
end;
end;
procedure UpdateRestart(SetValue: String);
begin
DataModule1.asqQU_Temp.SQL.Text:= 'Update tbConfigure set IsRestart="' + SetValue + '"' ;
DataModule1.asqQU_Temp.ExecSQL;
end;
end.
|
program HelloWorld;
{
procedure
}
procedure sayHi;
begin
writeln('hi!');
end;
procedure sayHello(name: string);
const
myname = 'yocchan';
begin
writeln('hello! ' + name + ' ! from ' + myname);
end;
// var : 参照渡し→呼び出し元が変わる
procedure swap(var x,y: integer);
var
tmp: integer;
begin
tmp := x;
x := y;
y := tmp;
end;
{
function
}
function getNumber:integer;
begin
getNumber := 10;
end;
function getNumber2(a,b:integer):integer;
const
factor = 2;
begin
getNumber2 := (a + b) * factor;
end;
procedure p2; forward; // 後で宣言するprocedureを先に使いたい時
procedure p1;
begin
writeln('p1');
p2;
end;
procedure p2;
begin
writeln('p2');
end;
// Mainブロック
var
x,y: integer;
result: integer;
begin
sayHi;
sayHello('Tom');
sayHello('Bob');
writeln('-------------');
x:= 10;
y:= 3;
swap(x,y);
writeln(x:5,y:5); // 3 10
writeln('-------------');
result := getNumber;
writeln(result);
result := getNumber2(3,5);
writeln(result);
end.
|
unit MasterMind.CodeSelector.Random;
interface
uses
MasterMind.API;
type
TMasterMindRandomCodeSelector = class(TInterfacedObject, ICodeSelector)
private
function GetNumberOfAvailableColors: Integer;
public
function SelectNewCode: TMasterMindCode;
end;
implementation
function TMasterMindRandomCodeSelector.SelectNewCode: TMasterMindCode;
var
I: Integer;
begin
Randomize;
for I := Low(TMasterMindCode) to High(TMasterMindCode) do
Result[I] := TMasterMindCodeColor(Random(GetNumberOfAvailableColors));
end;
function TMasterMindRandomCodeSelector.GetNumberOfAvailableColors: Integer;
var
Colors: array[TMasterMindCodeColor] of Byte;
begin
Result := Length(Colors);
end;
end. |
unit LTConsts;
interface
const
AUTH_GUEST = -1;
AUTH_STUDENT_BEGIN = 2; // 학생 ?
AUTH_STUDENT_END = 3; // 학생 ?
AUTH_TEACHER = 4; // 강사
AUTH_ACADEMY = 5; // 학원장
AUTH_BRANCH = 6; // 지사장
const
RIGHT = 0;
WRONG = 1;
MARKING = 2;
UNMARKING = 3;
implementation
end.
|
{-----------------------------------------------------------------------------
Unit Name: Subject
Author: Erwien Saputra
This software and source code are distributed on an as is basis, without
warranty of any kind, either express or implied.
This file can be redistributed, modified if you keep this header.
Copyright © Erwien Saputra 2002.
Purpose: Implements ISubjet, to be used as aggregated object, being exposed
via property (delegated interface).
History:
-----------------------------------------------------------------------------}
unit Subject;
interface
uses
IntfObserver, Classes;
type
//Class reference for TSubject
TSubjectClass = class of TSubject;
//Implements
TSubject = class (TAggregatedObject, ISubject)
private
FUpdateCount : integer;
FObserverList : IInterfaceList;
FEnabled : boolean;
//IObserver
function GetEnabled : boolean;
function GetIsUpdating : boolean;
procedure SetEnabled (const AValue : boolean);
procedure Notify; overload;
procedure Notify (const AIntf : IInterface); overload;
procedure AttachObserver (const AObserver : IObserver);
procedure DetachObserver (const AObserver : IObserver);
procedure BeginUpdate;
procedure EndUpdate;
protected
public
constructor Create (Controller : IInterface); reintroduce; virtual;
end;
implementation
uses
SysUtils;
{ TSubject }
{-----------------------------------------------------------------------------
Procedure: TSubject.AttachObserver
Author: Erwien Saputra
Date: 19-Aug-2002
Purpose: Add the observer to the internal observer list. Raise exception
if AObserver is not assigned. No duplicate is allowed.
Arguments: AObserver: IObserver
Result: None
Notes:
-----------------------------------------------------------------------------}
procedure TSubject.AttachObserver (const AObserver: IObserver);
begin
if (Assigned (AObserver) = false) then
raise Exception.Create ('Observer cannot be nil.');
if (FObserverList.IndexOf (AObserver) < 0) then begin
FObserverList.Add (AObserver);
Notify;
end;
end;
{-----------------------------------------------------------------------------
Procedure: TSubject.BeginUpdate
Author: Erwien Saputra
Date: 19-Aug-2002
Purpose: Increase the FUpdateCount private counter.
Arguments: None
Result: None
Notes:
-----------------------------------------------------------------------------}
procedure TSubject.BeginUpdate;
begin
if (FEnabled = true) then
Inc (FUpdateCount);
end;
{-----------------------------------------------------------------------------
Procedure: TSubject.Create
Author: Erwien Saputra
Date: 19-Aug-2002
Purpose: AggregatedObject constructor. It calls TAggregatedObject's
constructor. Create IInterfaceList and initialize FUpdateCount.
Arguments: Controller: IInterface
Result: None
Notes: TSubject must be implemented as aggregated interfaced object.
-----------------------------------------------------------------------------}
constructor TSubject.Create(Controller: IInterface);
begin
inherited Create (Controller);
FUpdateCount := 0;
FEnabled := true;
FObserverList := TInterfaceList.Create;
end;
{-----------------------------------------------------------------------------
Procedure: TSubject.DetachObserver
Author: Erwien Saputra
Date: 19-Aug-2002
Purpose:
Arguments: AObserver: IObserver
Result: None
Notes:
-----------------------------------------------------------------------------}
procedure TSubject.DetachObserver(const AObserver: IObserver);
begin
FObserverList.Remove (AObserver);
end;
{-----------------------------------------------------------------------------
Procedure: TSubject.EndUpdate
Author: Erwien Saputra
Date: 19-Aug-2002
Purpose: Decrease the UpdateCount counter and if it reaches 0, call Notify.
But if the FUpdateCount is already 0, don't call notify.
Arguments: None
Result: None
Notes: Thanks to Joanna Carter from delphi OOD newsgroup, that informing
me this BeginUpdate/EndUpdate technique.
-----------------------------------------------------------------------------}
procedure TSubject.EndUpdate;
begin
if (FEnabled = false) or (FUpdateCount = 0) then
Exit;
Dec (FUpdateCount);
if (FUpdateCount = 0) then
Notify;
end;
{-----------------------------------------------------------------------------
Procedure: TSubject.GetEnabled
Author: Erwien Saputra
Date: 19-Aug-2002
Purpose: This returns if this Subject is enabled.
Arguments: None
Result: boolean
Notes:
-----------------------------------------------------------------------------}
function TSubject.GetEnabled: boolean;
begin
Result := FEnabled;
end;
{-----------------------------------------------------------------------------
Procedure: TSubject.Notify
Author: Erwien Saputra
Date: 19-Aug-2002
Purpose: Notify all observers that subject has changed and probably they
want to update themselves.
Arguments: None
Result: None
Notes:
-----------------------------------------------------------------------------}
procedure TSubject.Notify;
var
iLoop : integer;
begin
if (FEnabled = true) then
for iLoop := 0 to (FObserverList.Count - 1) do
IObserver (FObserverList.Items [iLoop]).Update (Controller as ISubject);
end;
//Notify all observers about change and notify what interface has been changed.
procedure TSubject.Notify (const AIntf : IInterface);
var
iLoop : integer;
begin
if (FEnabled = true) then
for iLoop := 0 to (FObserverList.Count - 1) do
IObserver (FObserverList.Items [iLoop]).Update (Controller as ISubject,
AIntf);
end;
function TSubject.GetIsUpdating: boolean;
begin
Result := (FUpdateCount > 0);
end;
{-----------------------------------------------------------------------------
Procedure: TSubject.SetEnabled
Author: Erwien Saputra
Date: 19-Aug-2002
Purpose: Set this subject enabled or not. Subject cannot be disabled
in the middle of update (FUpdateCount <> 0);
Arguments: const AValue: boolean
Result: None
Notes:
-----------------------------------------------------------------------------}
procedure TSubject.SetEnabled(const AValue: boolean);
begin
if (GetIsUpdating = true) then
raise Exception.Create ('Subject is updating.');
if (AValue <> FEnabled) then begin
FEnabled := AValue;
Notify;
end;
end;
end.
|
{
Oracle Deploy System ver.1.0 (ORDESY)
by Volodymyr Sedler aka scribe
2016
Desc: wrap/deploy/save objects of oracle database.
No warranty of using this program.
Just Free.
With bugs, suggestions please write to justscribe@yahoo.com
On Github: github.com/justscribe/ORDESY
Dialog to edit the list of bases in ProjectList.
}
unit uBaseList;
interface
uses
// ORDESY Modules
uORDESY, uErrorHandle,
// Delphi Modules
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TfmBaseList = class(TForm)
lbxList: TListBox;
pnlControl: TPanel;
btnAdd: TButton;
btnDelete: TButton;
btnEdit: TButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure UpdateList(aProjectList: TORDESYProjectList);
procedure btnDeleteClick(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnEditClick(Sender: TObject);
private
ProjectList: TORDESYProjectList;
end;
function ShowBaseListDialog(aProjectList: TORDESYProjectList): boolean;
implementation
{$R *.dfm}
uses
uMain;
function ShowBaseListDialog(aProjectList: TORDESYProjectList): boolean;
begin
with TfmBaseList.Create(Application) do
try
try
Result:= false;
ProjectList:= aProjectList;
UpdateList(ProjectList);
ShowModal;
Result:= true;
except
on E: Exception do
HandleError([ClassName, 'ShowBaseListDialog', E.Message]);
end;
finally
Free;
end;
end;
procedure TfmBaseList.btnAddClick(Sender: TObject);
begin
try
fmMain.AddBase(Self);
UpdateList(ProjectList);
except
on E: Exception do
HandleError([ClassName, 'btnAddClick', E.Message]);
end;
end;
procedure TfmBaseList.btnDeleteClick(Sender: TObject);
var
reply: word;
begin
try
if (lbxList.Count > 0) and (lbxList.ItemIndex >= 0) and (lbxList.Items.Objects[lbxList.ItemIndex] is TOraBase) then
begin
reply:= MessageBox(Handle, PChar('Delete base: ' + TOraBase(lbxList.Items.Objects[lbxList.ItemIndex]).Name + '?' + #13#10), PChar('Confirm'), 36);
if reply = IDYES then
if ProjectList.RemoveBaseById(TOraBase(lbxList.Items.Objects[lbxList.ItemIndex]).Id) then
UpdateList(ProjectList);
end;
except
on E: Exception do
HandleError([ClassName, 'btnDeleteClick', E.Message]);
end;
end;
procedure TfmBaseList.btnEditClick(Sender: TObject);
begin
try
if (lbxList.Count > 0) and (lbxList.ItemIndex >= 0) and (lbxList.Items.Objects[lbxList.ItemIndex] is TOraBase) then
if fmMain.EditBase(TOraBase(lbxList.Items.Objects[lbxList.ItemIndex])) then
UpdateList(ProjectList);
except
on E: Exception do
HandleError([ClassName, 'btnEditClick', E.Message]);
end;
end;
procedure TfmBaseList.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Action:= caFree;
end;
procedure TfmBaseList.UpdateList(aProjectList: TORDESYProjectList);
var
i: integer;
iBase: TOraBase;
begin
try
lbxList.Items.BeginUpdate;
lbxList.Clear;
for i := 0 to aProjectList.OraBaseCount - 1 do
begin
iBase:= aProjectList.GetOraBaseByIndex(i);
if Assigned(iBase) then
lbxList.AddItem(inttostr(iBase.Id) + ':|' + iBase.Name, iBase);
end;
lbxList.Items.EndUpdate;
except
on E: Exception do
HandleError([ClassName, 'UpdateList', E.Message]);
end;
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 14/12/2018 17:03:44
//
unit ClientClassesUnit1;
interface
uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.FireDACJSONReflect, Data.DBXJSONReflect;
type
IDSRestCachedTFDJSONDataSets = interface;
TSmServicosClient = class(TDSAdminRestClient)
private
FEchoStringCommand: TDSRestCommand;
FReverseStringCommand: TDSRestCommand;
FDispositivosCommand: TDSRestCommand;
FDispositivosCommand_Cache: TDSRestCommand;
FRegistrarDispositivoCommand: TDSRestCommand;
FEnviarPushUnicoCommand: TDSRestCommand;
FEnviarPushMultiploCommand: TDSRestCommand;
public
constructor Create(ARestConnection: TDSRestConnection); overload;
constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function EchoString(Value: string; const ARequestFilter: string = ''): string;
function ReverseString(Value: string; const ARequestFilter: string = ''): string;
function Dispositivos(const ARequestFilter: string = ''): TFDJSONDataSets;
function Dispositivos_Cache(const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function RegistrarDispositivo(ADeviceToken: string; ADeviceID: string; ATipoDevice: string; ANome: string; const ARequestFilter: string = ''): Boolean;
function EnviarPushUnico(AID_Usuario: Integer; AMensagem: string; const ARequestFilter: string = ''): Boolean;
function EnviarPushMultiplo(AMensagem: string; const ARequestFilter: string = ''): Boolean;
end;
IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>)
end;
TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand)
end;
const
TSmServicos_EchoString: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'string')
);
TSmServicos_ReverseString: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'string')
);
TSmServicos_Dispositivos: array [0..0] of TDSRestParameterMetaData =
(
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TSmServicos_Dispositivos_Cache: array [0..0] of TDSRestParameterMetaData =
(
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TSmServicos_RegistrarDispositivo: array [0..4] of TDSRestParameterMetaData =
(
(Name: 'ADeviceToken'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ADeviceID'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ATipoDevice'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: 'ANome'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TSmServicos_EnviarPushUnico: array [0..2] of TDSRestParameterMetaData =
(
(Name: 'AID_Usuario'; Direction: 1; DBXType: 6; TypeName: 'Integer'),
(Name: 'AMensagem'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TSmServicos_EnviarPushMultiplo: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'AMensagem'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
implementation
function TSmServicosClient.EchoString(Value: string; const ARequestFilter: string): string;
begin
if FEchoStringCommand = nil then
begin
FEchoStringCommand := FConnection.CreateCommand;
FEchoStringCommand.RequestType := 'GET';
FEchoStringCommand.Text := 'TSmServicos.EchoString';
FEchoStringCommand.Prepare(TSmServicos_EchoString);
end;
FEchoStringCommand.Parameters[0].Value.SetWideString(Value);
FEchoStringCommand.Execute(ARequestFilter);
Result := FEchoStringCommand.Parameters[1].Value.GetWideString;
end;
function TSmServicosClient.ReverseString(Value: string; const ARequestFilter: string): string;
begin
if FReverseStringCommand = nil then
begin
FReverseStringCommand := FConnection.CreateCommand;
FReverseStringCommand.RequestType := 'GET';
FReverseStringCommand.Text := 'TSmServicos.ReverseString';
FReverseStringCommand.Prepare(TSmServicos_ReverseString);
end;
FReverseStringCommand.Parameters[0].Value.SetWideString(Value);
FReverseStringCommand.Execute(ARequestFilter);
Result := FReverseStringCommand.Parameters[1].Value.GetWideString;
end;
function TSmServicosClient.Dispositivos(const ARequestFilter: string): TFDJSONDataSets;
begin
if FDispositivosCommand = nil then
begin
FDispositivosCommand := FConnection.CreateCommand;
FDispositivosCommand.RequestType := 'GET';
FDispositivosCommand.Text := 'TSmServicos.Dispositivos';
FDispositivosCommand.Prepare(TSmServicos_Dispositivos);
end;
FDispositivosCommand.Execute(ARequestFilter);
if not FDispositivosCommand.Parameters[0].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FDispositivosCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FDispositivosCommand.Parameters[0].Value.GetJSONValue(True)));
if FInstanceOwner then
FDispositivosCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TSmServicosClient.Dispositivos_Cache(const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FDispositivosCommand_Cache = nil then
begin
FDispositivosCommand_Cache := FConnection.CreateCommand;
FDispositivosCommand_Cache.RequestType := 'GET';
FDispositivosCommand_Cache.Text := 'TSmServicos.Dispositivos';
FDispositivosCommand_Cache.Prepare(TSmServicos_Dispositivos_Cache);
end;
FDispositivosCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FDispositivosCommand_Cache.Parameters[0].Value.GetString);
end;
function TSmServicosClient.RegistrarDispositivo(ADeviceToken: string; ADeviceID: string; ATipoDevice: string; ANome: string; const ARequestFilter: string): Boolean;
begin
if FRegistrarDispositivoCommand = nil then
begin
FRegistrarDispositivoCommand := FConnection.CreateCommand;
FRegistrarDispositivoCommand.RequestType := 'GET';
FRegistrarDispositivoCommand.Text := 'TSmServicos.RegistrarDispositivo';
FRegistrarDispositivoCommand.Prepare(TSmServicos_RegistrarDispositivo);
end;
FRegistrarDispositivoCommand.Parameters[0].Value.SetWideString(ADeviceToken);
FRegistrarDispositivoCommand.Parameters[1].Value.SetWideString(ADeviceID);
FRegistrarDispositivoCommand.Parameters[2].Value.SetWideString(ATipoDevice);
FRegistrarDispositivoCommand.Parameters[3].Value.SetWideString(ANome);
FRegistrarDispositivoCommand.Execute(ARequestFilter);
Result := FRegistrarDispositivoCommand.Parameters[4].Value.GetBoolean;
end;
function TSmServicosClient.EnviarPushUnico(AID_Usuario: Integer; AMensagem: string; const ARequestFilter: string): Boolean;
begin
if FEnviarPushUnicoCommand = nil then
begin
FEnviarPushUnicoCommand := FConnection.CreateCommand;
FEnviarPushUnicoCommand.RequestType := 'GET';
FEnviarPushUnicoCommand.Text := 'TSmServicos.EnviarPushUnico';
FEnviarPushUnicoCommand.Prepare(TSmServicos_EnviarPushUnico);
end;
FEnviarPushUnicoCommand.Parameters[0].Value.SetInt32(AID_Usuario);
FEnviarPushUnicoCommand.Parameters[1].Value.SetWideString(AMensagem);
FEnviarPushUnicoCommand.Execute(ARequestFilter);
Result := FEnviarPushUnicoCommand.Parameters[2].Value.GetBoolean;
end;
function TSmServicosClient.EnviarPushMultiplo(AMensagem: string; const ARequestFilter: string): Boolean;
begin
if FEnviarPushMultiploCommand = nil then
begin
FEnviarPushMultiploCommand := FConnection.CreateCommand;
FEnviarPushMultiploCommand.RequestType := 'GET';
FEnviarPushMultiploCommand.Text := 'TSmServicos.EnviarPushMultiplo';
FEnviarPushMultiploCommand.Prepare(TSmServicos_EnviarPushMultiplo);
end;
FEnviarPushMultiploCommand.Parameters[0].Value.SetWideString(AMensagem);
FEnviarPushMultiploCommand.Execute(ARequestFilter);
Result := FEnviarPushMultiploCommand.Parameters[1].Value.GetBoolean;
end;
constructor TSmServicosClient.Create(ARestConnection: TDSRestConnection);
begin
inherited Create(ARestConnection);
end;
constructor TSmServicosClient.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean);
begin
inherited Create(ARestConnection, AInstanceOwner);
end;
destructor TSmServicosClient.Destroy;
begin
FEchoStringCommand.DisposeOf;
FReverseStringCommand.DisposeOf;
FDispositivosCommand.DisposeOf;
FDispositivosCommand_Cache.DisposeOf;
FRegistrarDispositivoCommand.DisposeOf;
FEnviarPushUnicoCommand.DisposeOf;
FEnviarPushMultiploCommand.DisposeOf;
inherited;
end;
end.
|
unit SC_INTV;
{$ifdef VirtualPascal}
{$stdcall+}
{$else}
Error('Interface unit for VirtualPascal');
{$endif}
(*************************************************************************
DESCRIPTION : Interface unit for SC_DLL
REQUIREMENTS : VirtualPascal
EXTERNAL DATA : ---
MEMORY USAGE : ---
DISPLAY MODE : ---
Version Date Author Modification
------- -------- ------- ------------------------------------------
0.10 02.01.05 W.Ehrhardt Initial version a la BF_INTF
0.11 16.07.09 we SC_DLL_Version returns PAnsiChar
0.12 06.08.10 we Longint ILen, SC_CTR_Seek via sc_seek.inc
**************************************************************************)
(*-------------------------------------------------------------------------
(C) Copyright 2005-2010 Wolfgang Ehrhardt
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.
----------------------------------------------------------------------------*)
interface
const
SC_Err_Invalid_Key_Size = -1; {Key size in bytes <1 or >64}
SC_Err_Invalid_Length = -3; {No full block for cipher stealing}
SC_Err_Data_After_Short_Block = -4; {Short block must be last}
SC_Err_MultipleIncProcs = -5; {More than one IncProc Setting}
SC_Err_NIL_Pointer = -6; {nil pointer to block with nonzero length}
SC_Err_CTR_SeekOffset = -15; {Negative offset in SC_CTR_Seek}
SC_Err_Invalid_16Bit_Length = -20; {Pointer + Offset > $FFFF for 16 bit code}
type
TSCKeyArr = packed array[0..63] of longint;
TSCBlock = packed array[0..31] of byte;
TWA8 = packed array[0..7] of longint;
PSCBlock = ^TSCBlock;
type
TSCIncProc = procedure(var CTR: TSCBlock); {user supplied IncCTR proc}
{$ifdef DLL} stdcall; {$endif}
type
TSCContext = packed record
RK : TSCKeyArr; {round key array }
IV : TSCBlock; {IV or CTR }
buf : TSCBlock; {Work buffer }
bLen : word; {Bytes used in buf }
Flag : word; {Bit 1: Short block }
IncProc : TSCIncProc; {Increment proc CTR-Mode}
end;
const
SCBLKSIZE = sizeof(TSCBlock);
function SC_DLL_Version: PAnsiChar;
{-Return DLL version as PAnsiChar}
function SC_Init(const Key; KeyBytes: word; var ctx: TSCContext): integer;
{-SHACAL-2 context SBox initialization}
procedure SC_Encrypt(var ctx: TSCContext; const BI: TSCBlock; var BO: TSCBlock);
{-encrypt one block (in ECB mode)}
procedure SC_Decrypt(var ctx: TSCContext; const BI: TSCBlock; var BO: TSCBlock);
{-decrypt one block (in ECB mode)}
procedure SC_XorBlock(const B1, B2: TSCBlock; var B3: TSCBlock);
{-xor two blocks, result in third}
procedure SC_SetFastInit(value: boolean);
{-set FastInit variable}
function SC_GetFastInit: boolean;
{-Returns FastInit variable}
function SC_CBC_Init(const Key; KeyBytes: word; const IV: TSCBlock; var ctx: TSCContext): integer;
{-SHACAL-2 key expansion, error if invalid key size, save IV}
procedure SC_CBC_Reset(const IV: TSCBlock; var ctx: TSCContext);
{-Clears ctx fields bLen and Flag, save IV}
function SC_CBC_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CBC mode}
function SC_CBC_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CBC mode}
function SC_CFB_Init(const Key; KeyBytes: word; const IV: TSCBlock; var ctx: TSCContext): integer;
{-SHACAL-2 key expansion, error if invalid key size, encrypt IV}
procedure SC_CFB_Reset(const IV: TSCBlock; var ctx: TSCContext);
{-Clears ctx fields bLen and Flag, encrypt IV}
function SC_CFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CFB mode}
function SC_CFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CFB mode}
function SC_CTR_Init(const Key; KeyBytes: word; const CTR: TSCBlock; var ctx: TSCContext): integer;
{-SHACAL-2 key expansion, error if inv. key size, encrypt CTR}
procedure SC_CTR_Reset(const CTR: TSCBlock; var ctx: TSCContext);
{-Clears ctx fields bLen and Flag, encrypt CTR}
function SC_CTR_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in CTR mode}
function SC_CTR_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in CTR mode}
function SC_CTR_Seek(const iCTR: TSCBlock; SOL, SOH: longint; var ctx: TSCContext): integer;
{-Setup ctx for random access crypto stream starting at 64 bit offset SOH*2^32+SOL,}
{ SOH >= 0. iCTR is the initial CTR for offset 0, i.e. the same as in SC_CTR_Init.}
function SC_SetIncProc(IncP: TSCIncProc; var ctx: TSCContext): integer;
{-Set user supplied IncCTR proc}
procedure SC_IncMSBFull(var CTR: TSCBlock);
{-Increment CTR[31]..CTR[0]}
procedure SC_IncLSBFull(var CTR: TSCBlock);
{-Increment CTR[0]..CTR[31]}
procedure SC_IncMSBPart(var CTR: TSCBlock);
{-Increment CTR[31]..CTR[16]}
procedure SC_IncLSBPart(var CTR: TSCBlock);
{-Increment CTR[0]..CTR[15]}
function SC_ECB_Init(const Key; KeyBytes: word; var ctx: TSCContext): integer;
{-SHACAL-2 key expansion, error if invalid key size}
procedure SC_ECB_Reset(var ctx: TSCContext);
{-Clears ctx fields bLen and Flag}
function SC_ECB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in ECB mode}
function SC_ECB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in ECB mode}
function SC_OFB_Init(const Key; KeyBits: word; const IV: TSCBlock; var ctx: TSCContext): integer;
{-SHACAL-2 key expansion, error if invalid key size, encrypt IV}
procedure SC_OFB_Reset(const IV: TSCBlock; var ctx: TSCContext);
{-Clears ctx fields bLen and Flag, encrypt IV}
function SC_OFB_Encrypt(ptp, ctp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Encrypt ILen bytes from ptp^ to ctp^ in OFB mode}
function SC_OFB_Decrypt(ctp, ptp: Pointer; ILen: longint; var ctx: TSCContext): integer;
{-Decrypt ILen bytes from ctp^ to ptp^ in OFB mode}
implementation
function SC_DLL_Version; external 'SC_DLL' name 'SC_DLL_Version';
function SC_Init; external 'SC_DLL' name 'SC_Init';
procedure SC_Encrypt; external 'SC_DLL' name 'SC_Encrypt';
procedure SC_Decrypt; external 'SC_DLL' name 'SC_Decrypt';
procedure SC_XorBlock; external 'SC_DLL' name 'SC_XorBlock';
procedure SC_SetFastInit; external 'SC_DLL' name 'SC_SetFastInit';
function SC_GetFastInit; external 'SC_DLL' name 'SC_GetFastInit';
function SC_CBC_Init; external 'SC_DLL' name 'SC_CBC_Init';
procedure SC_CBC_Reset; external 'SC_DLL' name 'SC_CBC_Reset';
function SC_CBC_Encrypt; external 'SC_DLL' name 'SC_CBC_Encrypt';
function SC_CBC_Decrypt; external 'SC_DLL' name 'SC_CBC_Decrypt';
function SC_CFB_Init; external 'SC_DLL' name 'SC_CFB_Init';
procedure SC_CFB_Reset; external 'SC_DLL' name 'SC_CFB_Reset';
function SC_CFB_Encrypt; external 'SC_DLL' name 'SC_CFB_Encrypt';
function SC_CFB_Decrypt; external 'SC_DLL' name 'SC_CFB_Decrypt';
function SC_CTR_Init; external 'SC_DLL' name 'SC_CTR_Init';
procedure SC_CTR_Reset; external 'SC_DLL' name 'SC_CTR_Reset';
function SC_CTR_Encrypt; external 'SC_DLL' name 'SC_CTR_Encrypt';
function SC_CTR_Decrypt; external 'SC_DLL' name 'SC_CTR_Decrypt';
function SC_SetIncProc; external 'SC_DLL' name 'SC_SetIncProc';
procedure SC_IncMSBFull; external 'SC_DLL' name 'SC_IncMSBFull';
procedure SC_IncLSBFull; external 'SC_DLL' name 'SC_IncLSBFull';
procedure SC_IncMSBPart; external 'SC_DLL' name 'SC_IncMSBPart';
procedure SC_IncLSBPart; external 'SC_DLL' name 'SC_IncLSBPart';
function SC_ECB_Init; external 'SC_DLL' name 'SC_ECB_Init';
procedure SC_ECB_Reset; external 'SC_DLL' name 'SC_ECB_Reset';
function SC_ECB_Encrypt; external 'SC_DLL' name 'SC_ECB_Encrypt';
function SC_ECB_Decrypt; external 'SC_DLL' name 'SC_ECB_Decrypt';
function SC_OFB_Init; external 'SC_DLL' name 'SC_OFB_Init';
procedure SC_OFB_Reset; external 'SC_DLL' name 'SC_OFB_Reset';
function SC_OFB_Encrypt; external 'SC_DLL' name 'SC_OFB_Encrypt';
function SC_OFB_Decrypt; external 'SC_DLL' name 'SC_OFB_Decrypt';
{$define CONST}
{$i sc_seek.inc}
end.
|
unit VCLBI.Editor.Hops;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
BI.Expressions, BI.Query, BI.DataItem;
type
THopsViewer = class(TForm)
LBHops: TListBox;
LMain: TLabel;
LCount: TLabel;
LBItems: TListBox;
Label1: TLabel;
Label2: TLabel;
LParent: TLabel;
procedure FormShow(Sender: TObject);
procedure LBHopsClick(Sender: TObject);
private
{ Private declarations }
FHops : TDataHops;
procedure AddHopItems(const AHop:THops);
procedure AddHops;
public
{ Public declarations }
class function HopsFrom(const AProvider:TDataProvider):TDataHops; overload; static;
class function HopsFrom(const AQuery:TBIQuery):TDataHops; overload; static;
class procedure View(const AOwner:TComponent; const AHops:TDataHops); overload; static;
class procedure View(const AOwner:TComponent; const AQuery:TBIQuery); overload; static;
end;
implementation
|
Program muenzenRechner (input, output);
{ liest Geldmünzen zwischen 1 und 99 Cent ein und verteilt
diese Geldmünzen über die Münzen, die im Umlauf sind }
Const
MUENZENLAENGE = 6;
Type
tMuenzen = array [1..MUENZENLAENGE] Of integer;
Var
MuenzenImUmlauf : tMuenzen; {die Münzen, die im Umlauf sind}
MuenzenVerteilt : tMuenzen; {das Ergebnis der Verteilung}
Betrag: integer;
{einzulesende Betrag, der zwischen 1 bis 99 liegt}
Zaehler: integer; {zählt wie oft eine Münze vorkommt}
i: integer;
Begin
MuenzenImUmlauf[1] := 50;
MuenzenImUmlauf[2] := 20;
MuenzenImUmlauf[3] := 10;
MuenzenImUmlauf[4] := 5;
MuenzenImUmlauf[5] := 2;
MuenzenImUmlauf[6] := 1;
write ('Eingabe: ');
read(Betrag);
For i := 1 To MUENZENLAENGE Do
Begin
Zaehler := 0;
Repeat
If (Betrag >= MuenzenImUmlauf[i]) Then
Begin
Betrag := Betrag - MuenzenImUmlauf[i];
Zaehler := Zaehler + 1;
End
Until (Betrag < MuenzenImUmlauf[i]);
write ( Zaehler, ' ');
End;
writeln;
End.
|
unit adot.Collections.Lists;
interface
{
TDoublyLinkedListClass<T>
}
uses
adot.Types,
adot.Collections.Types,
System.Generics.Collections,
System.Generics.Defaults,
System.SysUtils;
type
{ Doubly linked list }
TDoublyLinkedListClass<T> = class(TEnumerableExt<T>)
public
type
{ We use allocation of items by AllocMem, no extra initialization is needed }
PDoublyLinkedListItem = ^TDoublyLinkedListItem;
TDoublyLinkedListItem = record
Data: T;
Prev: PDoublyLinkedListItem;
Next: PDoublyLinkedListItem;
end;
TDListEnumerator = class(TEnumerator<T>)
protected
Data,First,Last: PDoublyLinkedListItem;
function DoGetCurrent: T; override;
function DoMoveNext: Boolean; override;
public
constructor Create(AFirst,ALast: PDoublyLinkedListItem);
end;
protected
FFront: PDoublyLinkedListItem;
FBack: PDoublyLinkedListItem;
FCount: integer;
FOwnsValues: boolean;
FComparer: IComparer<T>;
function DoGetEnumerator: TEnumerator<T>; override;
procedure SetOwnsValues(AOwnsValues: boolean);
class function MergeSortedRanges(C: PDoublyLinkedListItem; Comparer: IComparer<T>): PDoublyLinkedListItem;
class procedure MergeSort(List: TDoublyLinkedListClass<T>; AFirst, ALast: PDoublyLinkedListItem; Comparer: IComparer<T>);
function GetIsConsistent: boolean;
function GetEmpty: boolean;
public
constructor Create(Comparer: IComparer<T> = nil); overload;
constructor Create(const AValues: array of T; Comparer: IComparer<T> = nil); overload;
constructor Create(const AValues: TEnumerable<T>; Comparer: IComparer<T> = nil); overload;
destructor Destroy; override;
procedure Assign(Src: TEnumerable<T>); overload;
procedure Assign(Src: TDoublyLinkedListClass<T>); overload;
procedure Assign(const Src: TArray<T>); overload;
function AllocItem: PDoublyLinkedListItem; overload;
function AllocItem(const Value: T): PDoublyLinkedListItem; overload;
procedure FreeItem(Item: PDoublyLinkedListItem);
function ExtractItem(Item: PDoublyLinkedListItem): PDoublyLinkedListItem;
{ [X,Y,Z].AddToFront([A,B,C]) -> A,B,C,X,Y,Z }
procedure AddToFront(Value: T); overload;
procedure AddToFront(const AValues: array of T); overload;
procedure AddToFront(const AValues: TEnumerable<T>); overload;
{ [X,Y,Z].AddToBack([A,B,C]) -> X,Y,Z,A,B,C }
procedure AddToBack(Value: T); overload;
procedure AddToBack(const AValues: array of T); overload;
procedure AddToBack(const AValues: TEnumerable<T>); overload;
procedure InsertBefore(Value: T; Dst: PDoublyLinkedListItem);
procedure InsertAfter(Value: T; Dst: PDoublyLinkedListItem);
procedure Delete(Item: PDoublyLinkedListItem); overload;
procedure DeleteRange(ItemStart,ItemEnd: PDoublyLinkedListItem); overload;
function Remove(Value: T): integer; overload;
function Remove(Value: T; Comparer: IComparer<T>): integer; overload;
procedure Clear;
function Extract(Item: PDoublyLinkedListItem): T;
function ExtractFront: T;
function ExtractBack: T;
{ Remove duplicate values }
procedure Unique;
procedure Sort; overload;
procedure Sort(Comparer: IComparer<T>); overload;
function Find(Value: T): PDoublyLinkedListItem; overload;
function Find(Value: T; Comparer: IComparer<T>): PDoublyLinkedListItem; overload;
function FindNext(Item: PDoublyLinkedListItem): PDoublyLinkedListItem; overload;
function FindNext(Item: PDoublyLinkedListItem; Comparer: IComparer<T>): PDoublyLinkedListItem; overload;
function FindByIndex(Index: integer): PDoublyLinkedListItem;
function FindValueByIndex(Index: integer): T;
procedure Exchange(Item1, Item2: PDoublyLinkedListItem);
procedure Reverse(FirstItem, LastItem: PDoublyLinkedListItem; CheckDirection: boolean = True);
procedure Rotate(FirstItem, LastItem: PDoublyLinkedListItem; Shift: integer);
property Front: PDoublyLinkedListItem read FFront;
property Back: PDoublyLinkedListItem read FBack;
property Count: integer read FCount;
property IsEmpty: boolean read GetEmpty;
property OwnsValues: boolean read FOwnsValues write SetOwnsValues;
property IsConsistent: boolean read GetIsConsistent;
end;
implementation
uses
adot.Collections,
adot.Collections.Sets,
adot.Tools.RTTI;
{ TDoublyLinkedListClass<T>.TDListEnumerator }
constructor TDoublyLinkedListClass<T>.TDListEnumerator.Create(AFirst, ALast: PDoublyLinkedListItem);
begin
inherited Create;
First := AFirst;
Last := ALast;
Data := nil;
end;
function TDoublyLinkedListClass<T>.TDListEnumerator.DoMoveNext: Boolean;
begin
result := (First<>nil);
if result then
begin
Data := First;
if (First=Last) then
First := nil
else
First := First.Next;
end;
end;
function TDoublyLinkedListClass<T>.TDListEnumerator.DoGetCurrent: T;
begin
result := Data.Data;
end;
{ TDoublyLinkedListClass<T> }
constructor TDoublyLinkedListClass<T>.Create(Comparer: IComparer<T>);
begin
inherited Create;
if Comparer = nil then
FComparer := TComparerUtils.DefaultComparer<T>
else
FComparer := Comparer;
end;
constructor TDoublyLinkedListClass<T>.Create(const AValues: TEnumerable<T>; Comparer: IComparer<T> = nil);
begin
Create(Comparer);
AddToBack(AValues);
end;
constructor TDoublyLinkedListClass<T>.Create(const AValues: array of T; Comparer: IComparer<T> = nil);
begin
Create(Comparer);
AddToBack(AValues);
end;
destructor TDoublyLinkedListClass<T>.Destroy;
begin
Clear;
inherited;
end;
procedure TDoublyLinkedListClass<T>.AddToBack(Value: T);
var
Item: PDoublyLinkedListItem;
begin
if FBack <> nil then
InsertAfter(Value, FBack)
else
begin
Item := AllocItem(Value);
FFront := Item;
FBack := Item;
inc(FCount);
end;
end;
procedure TDoublyLinkedListClass<T>.AddToBack(const AValues: array of T);
var
I: integer;
begin
for I := Low(AValues) to High(AValues) do
AddToBack(AValues[I]);
end;
procedure TDoublyLinkedListClass<T>.AddToBack(const AValues: TEnumerable<T>);
var
Value: T;
begin
for Value in AValues do
AddToBack(Value);
end;
procedure TDoublyLinkedListClass<T>.AddToFront(Value: T);
var
Item: PDoublyLinkedListItem;
begin
if FFront <> nil then
InsertBefore(Value, FFront)
else
begin
Item := AllocItem(Value);
FFront := Item;
FBack := Item;
inc(FCount);
end;
end;
procedure TDoublyLinkedListClass<T>.AddToFront(const AValues: array of T);
var
I: integer;
begin
for I := High(AValues) downto Low(AValues) do
AddToFront(AValues[I]);
end;
procedure TDoublyLinkedListClass<T>.AddToFront(const AValues: TEnumerable<T>);
var
Value: T;
Dst: PDoublyLinkedListItem;
begin
Dst := nil;
for Value in AValues do
if Dst = nil then
begin
AddToFront(Value);
Dst := Front;
end
else
begin
InsertAfter(Value, Dst);
Dst := Dst.Next;
end;
end;
{ v
\
p.Prev-> . <-p }
procedure TDoublyLinkedListClass<T>.InsertBefore(Value: T; Dst: PDoublyLinkedListItem);
var
Item: PDoublyLinkedListItem;
begin
Item := AllocItem(Value);
if FFront = Dst then
FFront := Item;
if Dst.Prev <> nil then
Dst.Prev.Next := Item;
Item.Prev := Dst.Prev;
Dst.Prev := Item;
Item.Next := Dst;
inc(FCount);
end;
procedure TDoublyLinkedListClass<T>.Unique;
var
Values: TSet<T>;
Item,D: PDoublyLinkedListItem;
begin
Values.Init;
Item := FFront;
while Item <> nil do
if Item.Data in Values then
begin
D := Item;
Item := Item.Next;
Delete(D);
end
else
begin
Values.Add(Item.Data);
Item := Item.Next;
end;
end;
class function TDoublyLinkedListClass<T>.MergeSortedRanges(C: PDoublyLinkedListItem; Comparer: IComparer<T>): PDoublyLinkedListItem;
var
l,r,n: PDoublyLinkedListItem;
begin
result := c;
if c=nil then
exit;
if c.next=nil then
exit;
{ split C->L+R }
l := nil;
r := nil;
repeat
n := c;
c := c.Next;
n.Next := l;
l := n;
if c=nil then
break;
n := c;
c := c.Next;
n.Next := r;
r := n;
until c=nil;
{ sort L&R }
l := MergeSortedRanges(l, Comparer);
r := MergeSortedRanges(r, Comparer);
{ merge L+R->Result }
if l=nil then
result := r
else
if r=nil then
result := l
else
begin
{ result=Head, c=Tail }
if Comparer.Compare(l.Data, r.Data) <= 0 then // L < R
begin
result := l;
l := l.Next;
end else begin
result := r;
r := r.Next;
end;
c := result;
{ L&R -> Tail (c) }
while (l<>nil) and (r<>nil) do
if Comparer.Compare(l.Data, r.Data) <= 0 then // L < R
begin
c.Next := l;
c := l;
l := l.Next;
end else begin
c.Next := r;
c := r;
r := r.Next;
end;
{ put remain Items to back }
if l=nil then
c.Next := r
else
c.Next := l;
end;
end;
class procedure TDoublyLinkedListClass<T>.MergeSort(List: TDoublyLinkedListClass<T>; AFirst, ALast: PDoublyLinkedListItem; Comparer: IComparer<T>);
var
f,l,n: PDoublyLinkedListItem;
begin
n := ALast.Next;
ALast.Next := nil;
f := MergeSortedRanges(AFirst, Comparer);
l := f;
while l.Next<>nil do
l := l.Next;
if ALast=List.FBack then
List.FBack := l;
l.Next := n;
if AFirst=List.FFront then
List.FFront := f
else
AFirst.Prev.Next := f;
{ restore backward links }
f := nil;
n := List.FFront;
while n<>nil do
begin
n.Prev := f;
f := n;
n := n.Next;
end;
end;
procedure TDoublyLinkedListClass<T>.Sort;
begin
Sort(FComparer);
end;
procedure TDoublyLinkedListClass<T>.Sort(Comparer: IComparer<T>);
begin
if FFront <> nil then
if Comparer = nil then
MergeSort(Self, FFront, FBack, FComparer)
else
MergeSort(Self, FFront, FBack, Comparer);
end;
{ v
\
p-> . <-p.next }
procedure TDoublyLinkedListClass<T>.InsertAfter(Value: T; Dst: PDoublyLinkedListItem);
var
Item: PDoublyLinkedListItem;
begin
Item := AllocItem(Value);
if FBack = Dst then
FBack := Item;
if Dst.Next <> nil then
Dst.Next.Prev := Item;
Item.Next := Dst.Next;
Dst.Next := Item;
Item.Prev := Dst;
inc(FCount);
end;
procedure TDoublyLinkedListClass<T>.Exchange(Item1, Item2: PDoublyLinkedListItem);
var
p: PDoublyLinkedListItem;
begin
if Item1 = Item2 then
Exit;
if Item1.Next = Item2 then
begin
{ * - Item1 - Item2 - * }
if Item1.Prev = nil
then FFront := Item2
else Item1.Prev.Next := Item2;
if Item2.Next = nil
then FBack := Item1
else Item2.Next.Prev := Item1;
p := Item1.Prev;
Item1.Prev := Item2;
Item1.Next := Item2.Next;
Item2.Prev := p;
Item2.Next := Item1;
end
else
if Item2.Next = Item1 then
begin
{ * - Item2 - Item1 - * }
if Item2.Prev = nil
then FFront := Item1
else Item2.Prev.Next := Item1;
if Item1.Next = nil
then FBack := Item2
else Item1.Next.Prev := Item2;
p := Item2.Prev;
Item2.Prev := Item1;
Item2.Next := Item1.Next;
Item1.Prev := p;
Item1.Next := Item2;
end
else
begin
{ * - Item1/2 - [...] - Item1/2 - * }
p := Item1.Prev; Item1.Prev := Item2.Prev; Item2.Prev := p;
p := Item1.Next; Item1.Next := Item2.Next; Item2.Next := p;
if Item1.Prev = nil
then FFront := Item1
else Item1.Prev.Next := Item1;
if Item1.Next = nil
then FBack := Item1
else Item1.Next.Prev := Item1;
if Item2.Prev = nil
then FFront := Item2
else Item2.Prev.Next := Item2;
if Item2.Next = nil
then FBack := Item2
else Item2.Next.Prev := Item2;
end;
end;
function TDoublyLinkedListClass<T>.AllocItem: PDoublyLinkedListItem;
begin
result := AllocMem(SizeOf(TDoublyLinkedListItem));
end;
function TDoublyLinkedListClass<T>.AllocItem(const Value: T): PDoublyLinkedListItem;
begin
result := AllocMem(SizeOf(TDoublyLinkedListItem));
result.Data := Value;
end;
procedure TDoublyLinkedListClass<T>.Assign(Src: TDoublyLinkedListClass<T>);
begin
Assign(TEnumerable<T>(Src));
FOwnsValues := Src.FOwnsValues;
FComparer := Src.FComparer;
end;
procedure TDoublyLinkedListClass<T>.Assign(Src: TEnumerable<T>);
begin
Clear;
AddToBack(Src);
end;
procedure TDoublyLinkedListClass<T>.Assign(const Src: TArray<T>);
begin
Clear;
AddToBack(Src);
end;
function TDoublyLinkedListClass<T>.Find(Value: T; Comparer: IComparer<T>): PDoublyLinkedListItem;
begin
result := FFront;
while (result <> nil) and (Comparer.Compare(result.Data, Value) <> 0) do
result := result.Next;
end;
function TDoublyLinkedListClass<T>.Find(Value: T): PDoublyLinkedListItem;
begin
result := Find(Value, FComparer);
end;
function TDoublyLinkedListClass<T>.FindNext(Item: PDoublyLinkedListItem; Comparer: IComparer<T>): PDoublyLinkedListItem;
begin
result := Item;
if result <> nil then
repeat
result := result.Next;
until (result = nil) or (Comparer.Compare(result.Data, Item.Data) = 0);
end;
function TDoublyLinkedListClass<T>.FindNext(Item: PDoublyLinkedListItem): PDoublyLinkedListItem;
begin
result := FindNext(Item, FComparer);
end;
function TDoublyLinkedListClass<T>.FindByIndex(Index: integer): PDoublyLinkedListItem;
begin
result := FFront;
while (Index > 0) and (result <> nil) do
begin
Dec(Index);
result := result.Next;
end;
end;
function TDoublyLinkedListClass<T>.FindValueByIndex(Index: integer): T;
begin
result := FindByIndex(Index).Data;
end;
procedure TDoublyLinkedListClass<T>.FreeItem(Item: PDoublyLinkedListItem);
begin
if FOwnsValues then
PObject(@Item.Data)^.DisposeOf;
Item.Data := Default(T);
FreeMem(Item);
end;
function TDoublyLinkedListClass<T>.GetEmpty: boolean;
begin
result := Count=0;
end;
function TDoublyLinkedListClass<T>.GetIsConsistent: boolean;
var
L: PDoublyLinkedListItem;
I: integer;
begin
result := False;
if Count < 0 then
Exit;
if (FFront=nil) <> (FBack=nil) then
Exit;
if (FFront<>nil) then
if (FFront.Prev<>nil) or (FBack.Next<>nil) then
Exit;
L := FFront;
for I := 0 to Count-2 do
if L = nil then
Exit
else
L := L.Next;
if L <> FBack then
Exit;
L := FBack;
for I := 0 to Count-2 do
if L = nil then
Exit
else
L := L.Prev;
if L <> FFront then
Exit;
result := True;
end;
procedure TDoublyLinkedListClass<T>.SetOwnsValues(AOwnsValues: boolean);
begin
if AOwnsValues and not TRttiUtils.IsInstance<T> then
raise Exception.Create('Generic type is not a class.');
FOwnsValues := AOwnsValues;
end;
function TDoublyLinkedListClass<T>.Extract(Item: PDoublyLinkedListItem): T;
begin
result := Item.Data;
Item.Data := Default(T);
Delete(Item);
end;
function TDoublyLinkedListClass<T>.ExtractBack: T;
begin
result := Extract(FBack);
end;
function TDoublyLinkedListClass<T>.ExtractFront: T;
begin
result := Extract(FFront);
end;
function TDoublyLinkedListClass<T>.ExtractItem(Item: PDoublyLinkedListItem): PDoublyLinkedListItem;
begin
result := Item;
if Item.Prev <> nil then
Item.Prev.Next := Item.Next;
if Item.Next <> nil then
Item.Next.Prev := Item.Prev;
if Item = FFront then
FFront := Item.Next;
if Item = FBack then
FBack := Item.Prev;
dec(FCount);
result.Prev := nil;
result.Next := nil;
end;
procedure TDoublyLinkedListClass<T>.Delete(Item: PDoublyLinkedListItem);
begin
FreeItem(ExtractItem(Item));
end;
procedure TDoublyLinkedListClass<T>.DeleteRange(ItemStart, ItemEnd: PDoublyLinkedListItem);
var
d: PDoublyLinkedListItem;
begin
if ItemStart = nil then
ItemStart := FFront;
while ItemStart <> ItemEnd do
begin
d := ItemStart;
ItemStart := ItemStart.Next;
FreeItem(ExtractItem(d));
end;
if ItemStart <> nil then
FreeItem(ExtractItem(ItemEnd));
end;
procedure TDoublyLinkedListClass<T>.Clear;
var A,B: PDoublyLinkedListItem;
begin
A := FFront;
while A<>nil do
begin
B := A;
A := A.Next;
FreeItem(B);
end;
FFront := nil;
FBack := nil;
FCount := 0;
end;
function TDoublyLinkedListClass<T>.DoGetEnumerator: TEnumerator<T>;
begin
result := TDListEnumerator.Create(FFront, FBack);
end;
function TDoublyLinkedListClass<T>.Remove(Value: T): integer;
begin
Remove(Value, FComparer);
end;
function TDoublyLinkedListClass<T>.Remove(Value: T; Comparer: IComparer<T>): integer;
var
C,D: PDoublyLinkedListItem;
begin
C := FFront;
while C <> nil do
if Comparer.Compare(C.Data, Value) <> 0 then
C := C.Next
else
begin
D := C;
C := C.Next;
Delete(D);
end;
end;
procedure TDoublyLinkedListClass<T>.Reverse(FirstItem, LastItem: PDoublyLinkedListItem; CheckDirection: boolean = True);
var
q, Temp, NFirst, NPrev, NNext: PDoublyLinkedListItem;
begin
if FirstItem = nil then
FirstItem := FFront;
if LastItem = nil then
LastItem := FBack;
if FirstItem = LastItem then
exit;
{ check direction }
if CheckDirection then
begin
q := FirstItem;
while (q <> nil) and (q <> LastItem) do
q := q.Next;
if q = nil then
begin
{$If Defined(Debug)}
q := LastItem;
while (q <> nil) and (q <> FirstItem) do
q := q.Next;
Assert(q <> nil);
{$EndIf}
Reverse(LastItem, FirstItem, False);
Exit;
end;
end;
{ NPrev -> A->B->...->C -> NNext }
NPrev := FirstItem.Prev;
NFirst:= FirstItem;
NNext := LastItem.Next;
q := nil;
repeat
Temp := FirstItem;
if FirstItem=LastItem then
FirstItem := nil
else
FirstItem := FirstItem.Next;
Temp.Next := q;
q := Temp;
until FirstItem=nil;
{ NPrev -> C->...->B->A -> NNext }
if NPrev=nil then
FFront := q
else
NPrev.Next := q;
{ "NFirst" has moved to the end of reverse range }
NFirst.Next := NNext;
if NNext=nil then
FBack := NFirst;
{ restore backward links }
LastItem.Prev := NPrev;
while LastItem.next<>nil do
begin
LastItem.Next.Prev := LastItem;
if LastItem=NFirst then
Break;
LastItem := LastItem.Next;
end;
end;
procedure TDoublyLinkedListClass<T>.Rotate(FirstItem, LastItem: PDoublyLinkedListItem; Shift: integer);
var
p, NPrev, NFirst, NLast: PDoublyLinkedListItem;
i,w: integer;
begin
if FirstItem=LastItem then
Exit;
{ find W and make Shift positive and less than W }
w := 1;
p := FirstItem;
while (p<>LastItem) and (p<>nil) do
begin
p := p.Next;
inc(w);
end;
if p=nil then
begin
Rotate(LastItem, FirstItem, Shift);
exit;
end;
Shift := Shift mod w;
if Shift=0 then
exit;
if Shift<0 then
inc(Shift, w);
{ number of left shifts = w-Shift }
p := FirstItem;
for i := 0 to w-Shift-1 do
p := p.Next;
{ prev(FirstItem) <-> P-LastItem <-> FirstItem-prev(p) <-> next(LastItem) }
NPrev := p.prev;
NFirst := FirstItem.prev;
NLast := LastItem.next;
if NFirst=nil then
FFront := p
else
NFirst.Next := p;
NPrev.Next := LastItem.Next;
LastItem.Next := FirstItem;
if FBack=LastItem then
FBack := NPrev;
p.Prev := NFirst;
FirstItem.prev := LastItem;
if NLast<>nil then
NLast.Prev := NPrev;
end;
end.
|
{$R-} {Range checking off}
{$B+} {Boolean complete evaluation on}
{$S+} {Stack checking on}
{$I+} {I/O checking on}
{$N-} {No numeric coprocessor}
{$M 65500,16384,655360} {Turbo 3 default stack and heap}
program STRIPESC;
{
Strip printer codes and non printing chars from text file.
Leave: <TAB>
<FF>
<CR>
<LF>
Alters a text file <file>.<ext>. The original remains as
<file>.BAK. Type STRIPESC. You will be prompted for the file
name.
}
uses
CRT,
DirUtil {Dir, NextName} ;
CONST
{ set of chars TEXFILT will pass }
PassableChars = [Chr(9),Chr(10),Chr(12),Chr(13),' '..'~'];
ESC = #27;
type AnyStr = string[80];
delimters = (LF,CR,NONE,GOOD);
var FileToRead, OutFile : text;
NameOfFile : anystr;
currfile : integer;
function Exist(name: anystr):Boolean;
var
Fil: file;
begin
Assign(Fil,name);
{$I-}
Reset(Fil);
Close(Fil);
{$I+}
Exist := (IOresult = 0);
{! 1. IOResult^ now returns different values corresponding to DOS error codes.}
end; {exist}
Procedure ChooseFile(currentfile : integer);
begin
GotoXY(1,1);
if currentfile = 0 then begin
Writeln ('Name of file (include extension)?');ClrEol;
Readln(NameOfFile);ClrEol;
end
else begin
NameOfFile := paramstr(currentfile);
GotoXY(1,3);
end;
if Exist(NameOfFile) then begin
Writeln('Processing ',NameOfFile);
Assign(FileToRead,NameOfFile);
Assign(OutFile,'text.tmp');
Reset(FileToRead);
Rewrite(Outfile);
end
else begin
writeln('File ',NameOfFile,' does not exist here.');ClrEol;
writeln('Choose again or <Ctrl><Break> to exit.');ClrEol;
writeln;
Choosefile(0);
end;
end; {choosefile}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
procedure Swapfile;
{leave unaltered file with a '.BAK' extension
Rename TEMP file as old file name.}
var temp : anystr;
tempfile : text;
begin
if pos('.',nameOfFile)<>0 then
temp := copy(NameofFile,1,pos('.',nameOfFile)-1)+ '.BAK'
else
temp := nameOfFile + '.BAK';
if Exist(temp) then
begin
Assign(tempfile,temp);
Erase(tempfile);
{ Close(tempfile); }
end;
Rename(FileToRead,temp);
Rename(OutFile,NameOfFile);
end; {swapfile}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
function ChangeLines : boolean;
var chrA : char;
Skip : BOOLEAN; {skip printable char after <ESC> }
begin { CHANGELINES }
Skip := FALSE;
while not eof(FileToRead) do
begin
read(FileToRead,ChrA);
IF NOT Skip THEN
Skip := (ChrA = ESC);
IF (chrA IN PassableChars) THEN
IF NOT Skip THEN
write(Outfile,chrA)
ELSE
Skip := FALSE; { reset for next char }
end;
close(fileToRead);
close(OutFile);
ChangeLines := TRUE;
end; {changeLines}
{~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~}
{MAIN PROGRAM}
BEGIN
ClrScr;
if paramcount = 0 then
begin
ChooseFile(0);
if ChangeLines then SwapFile;
end
else
BEGIN
Dir(paramstr(1));
NameOfFile := NextName;
WHILE NameOfFile <> '' DO
begin
Writeln('Processing ',NameOfFile);
Assign(FileToRead,NameOfFile);
Assign(OutFile,'text.tmp');
Reset(FileToRead);
Rewrite(Outfile);
if ChangeLines then SwapFile;
NameOfFile := NextName;
end;
END;
END.
|
unit testchebyshevunit;
interface
uses Math, Sysutils, Ap, chebyshev;
function TestChebyshev(Silent : Boolean):Boolean;
function testchebyshevunit_test_silent():Boolean;
function testchebyshevunit_test():Boolean;
implementation
function TestChebyshev(Silent : Boolean):Boolean;
var
Err : Double;
SumErr : Double;
CErr : Double;
FErr : Double;
Threshold : Double;
X : Double;
V : Double;
T : Double;
Pass : AlglibInteger;
I : AlglibInteger;
J : AlglibInteger;
K : AlglibInteger;
N : AlglibInteger;
MaxN : AlglibInteger;
C : TReal1DArray;
P1 : TReal1DArray;
P2 : TReal1DArray;
A : TReal2DArray;
WasErrors : Boolean;
begin
Err := 0;
SumErr := 0;
CErr := 0;
FErr := 0;
Threshold := 1.0E-9;
WasErrors := False;
//
// Testing Chebyshev polynomials of the first kind
//
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 0, 0.00)-1));
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 0, 0.33)-1));
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 0, -0.42)-1));
X := 0.2;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 1, X)-0.2));
X := 0.4;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 1, X)-0.4));
X := 0.6;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 1, X)-0.6));
X := 0.8;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 1, X)-0.8));
X := 1.0;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 1, X)-1.0));
X := 0.2;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 2, X)+0.92));
X := 0.4;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 2, X)+0.68));
X := 0.6;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 2, X)+0.28));
X := 0.8;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 2, X)-0.28));
X := 1.0;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, 2, X)-1.00));
N := 10;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, N, 0.2)-0.4284556288));
N := 11;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, N, 0.2)+0.7996160205));
N := 12;
Err := Max(Err, AbsReal(ChebyshevCalculate(1, N, 0.2)+0.7483020370));
//
// Testing Chebyshev polynomials of the second kind
//
N := 0;
Err := Max(Err, AbsReal(ChebyshevCalculate(2, N, 0.2)-1.0000000000));
N := 1;
Err := Max(Err, AbsReal(ChebyshevCalculate(2, N, 0.2)-0.4000000000));
N := 2;
Err := Max(Err, AbsReal(ChebyshevCalculate(2, N, 0.2)+0.8400000000));
N := 3;
Err := Max(Err, AbsReal(ChebyshevCalculate(2, N, 0.2)+0.7360000000));
N := 4;
Err := Max(Err, AbsReal(ChebyshevCalculate(2, N, 0.2)-0.5456000000));
N := 10;
Err := Max(Err, AbsReal(ChebyshevCalculate(2, N, 0.2)-0.6128946176));
N := 11;
Err := Max(Err, AbsReal(ChebyshevCalculate(2, N, 0.2)+0.6770370970));
N := 12;
Err := Max(Err, AbsReal(ChebyshevCalculate(2, N, 0.2)+0.8837094564));
//
// Testing Clenshaw summation
//
MaxN := 20;
SetLength(C, MaxN+1);
K:=1;
while K<=2 do
begin
Pass:=1;
while Pass<=10 do
begin
X := 2*RandomReal-1;
V := 0;
N:=0;
while N<=MaxN do
begin
C[N] := 2*RandomReal-1;
V := V+ChebyshevCalculate(K, N, X)*C[N];
SumErr := Max(SumErr, AbsReal(V-ChebyshevSum(C, K, N, X)));
Inc(N);
end;
Inc(Pass);
end;
Inc(K);
end;
//
// Testing coefficients
//
ChebyshevCoefficients(0, C);
CErr := Max(CErr, AbsReal(C[0]-1));
ChebyshevCoefficients(1, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]-1));
ChebyshevCoefficients(2, C);
CErr := Max(CErr, AbsReal(C[0]+1));
CErr := Max(CErr, AbsReal(C[1]-0));
CErr := Max(CErr, AbsReal(C[2]-2));
ChebyshevCoefficients(3, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]+3));
CErr := Max(CErr, AbsReal(C[2]-0));
CErr := Max(CErr, AbsReal(C[3]-4));
ChebyshevCoefficients(4, C);
CErr := Max(CErr, AbsReal(C[0]-1));
CErr := Max(CErr, AbsReal(C[1]-0));
CErr := Max(CErr, AbsReal(C[2]+8));
CErr := Max(CErr, AbsReal(C[3]-0));
CErr := Max(CErr, AbsReal(C[4]-8));
ChebyshevCoefficients(9, C);
CErr := Max(CErr, AbsReal(C[0]-0));
CErr := Max(CErr, AbsReal(C[1]-9));
CErr := Max(CErr, AbsReal(C[2]-0));
CErr := Max(CErr, AbsReal(C[3]+120));
CErr := Max(CErr, AbsReal(C[4]-0));
CErr := Max(CErr, AbsReal(C[5]-432));
CErr := Max(CErr, AbsReal(C[6]-0));
CErr := Max(CErr, AbsReal(C[7]+576));
CErr := Max(CErr, AbsReal(C[8]-0));
CErr := Max(CErr, AbsReal(C[9]-256));
//
// Testing FromChebyshev
//
MaxN := 10;
SetLength(A, MaxN+1, MaxN+1);
I:=0;
while I<=MaxN do
begin
J:=0;
while J<=MaxN do
begin
A[I,J] := 0;
Inc(J);
end;
ChebyshevCoefficients(I, C);
APVMove(@A[I][0], 0, I, @C[0], 0, I);
Inc(I);
end;
SetLength(C, MaxN+1);
SetLength(P1, MaxN+1);
N:=0;
while N<=MaxN do
begin
Pass:=1;
while Pass<=10 do
begin
I:=0;
while I<=N do
begin
P1[I] := 0;
Inc(I);
end;
I:=0;
while I<=N do
begin
C[I] := 2*RandomReal-1;
V := C[I];
APVAdd(@P1[0], 0, I, @A[I][0], 0, I, V);
Inc(I);
end;
FromChebyshev(C, N, P2);
I:=0;
while I<=N do
begin
FErr := Max(FErr, AbsReal(P1[I]-P2[I]));
Inc(I);
end;
Inc(Pass);
end;
Inc(N);
end;
//
// Reporting
//
WasErrors := AP_FP_Greater(Err,Threshold) or AP_FP_Greater(SumErr,Threshold) or AP_FP_Greater(CErr,Threshold) or AP_FP_Greater(FErr,Threshold);
if not Silent then
begin
Write(Format('TESTING CALCULATION OF THE CHEBYSHEV POLYNOMIALS'#13#10'',[]));
Write(Format('Max error against table %5.3e'#13#10'',[
Err]));
Write(Format('Summation error %5.3e'#13#10'',[
SumErr]));
Write(Format('Coefficients error %5.3e'#13#10'',[
CErr]));
Write(Format('FrobChebyshev error %5.3e'#13#10'',[
FErr]));
Write(Format('Threshold %5.3e'#13#10'',[
Threshold]));
if not WasErrors then
begin
Write(Format('TEST PASSED'#13#10'',[]));
end
else
begin
Write(Format('TEST FAILED'#13#10'',[]));
end;
end;
Result := not WasErrors;
end;
(*************************************************************************
Silent unit test
*************************************************************************)
function testchebyshevunit_test_silent():Boolean;
begin
Result := TestChebyshev(True);
end;
(*************************************************************************
Unit test
*************************************************************************)
function testchebyshevunit_test():Boolean;
begin
Result := TestChebyshev(False);
end;
end. |
unit main;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, Menus,
StdCtrls;
type
{ TMainForm }
TMainForm = class(TForm)
MemoryClear: TButton;
Root: TButton;
Digit7: TButton;
Digit8: TButton;
Digit9: TButton;
Division: TButton;
Percent: TButton;
Digit4: TButton;
Digit1: TButton;
Digit0: TButton;
Digit5: TButton;
MemoryRecall: TButton;
Digit6: TButton;
Digit2: TButton;
Digit3: TButton;
Dot: TButton;
Multiplication: TButton;
Subtraction: TButton;
Addition: TButton;
Equal: TButton;
Inverse: TButton;
MemorySave: TButton;
MemorySubtranction: TButton;
MemoryAddition: TButton;
Backspace: TButton;
ClearEntry: TButton;
Clear: TButton;
PlusMinus: TButton;
Display: TEdit;
MemoryIndicator: TEdit;
MemoryDisplay: TEdit;
MainMenu: TMainMenu;
FileItem: TMenuItem;
ExitItem: TMenuItem;
EditItem: TMenuItem;
CopyItem: TMenuItem;
HelpItem: TMenuItem;
AboutItem: TMenuItem;
DeleteItem: TMenuItem;
ShowItem: TMenuItem;
PasteItem: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure AboutItemClick(Sender: TObject);
procedure ExitItemClick(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure MakeOperation(n: Integer);
procedure MakeResult();
procedure ZeroCheck();
procedure MemoryCheck();
procedure DigitsClick(Sender: TObject);
procedure ClearClick(Sender: TObject);
procedure ClearEntryClick(Sender: TObject);
procedure RootClick(Sender: TObject);
procedure PlusMinusClick(Sender: TObject);
procedure InverseClick(Sender: TObject);
procedure BackspaceClick(Sender: TObject);
procedure DotClick(Sender: TObject);
procedure OperationClick(Sender: TObject);
procedure IsClick(Sender: TObject);
procedure PercentClick(Sender: TObject);
procedure CopyItemClick(Sender: TObject);
procedure PasteItemClick(Sender: TObject);
procedure ShowItemClick(Sender: TObject);
procedure DeleteItemClick(Sender: TObject);
procedure MemoryAdditionOrSubtractionClick(Sender: TObject);
procedure MemorySaveClick(Sender: TObject);
procedure MemoryRecallClick(Sender: TObject);
procedure MemoryClearClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
MainForm: TMainForm;
implementation
var
Operation: Char;
First, Second, Result, Memory, CopyBuffer: Double;
BothZero, Zero, Block, State, OperationBlock, OperationOn, IsOn: Boolean;
{$R *.lfm}
{ TMainForm }
procedure TMainForm.FormCreate(Sender: TObject);
begin
MainForm.Caption := 'Калькулятор';
MainForm.Constraints.MinHeight := 576;
MainForm.Constraints.MaxHeight := 576;
MainForm.Constraints.MinWidth := 400;
MainForm.Constraints.MaxWidth := 400;
MainForm.Left := 40;
MainForm.Top := 40;
MainForm.KeyPreview := True;
Display.Font.Size := 20;
Display.ReadOnly := True;
MemoryDisplay.Font.Size := 20;
MemoryDisplay.ReadOnly := True;
MemoryIndicator.Font.Size := 20;
MemoryIndicator.ReadOnly := True;
MemoryIndicator.Visible := False;
Clear.Click;
end;
procedure TMainForm.ExitItemClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TMainForm.AboutItemClick(Sender: TObject);
begin
ShowMessage('Калькулятор для OS X' + #10 + 'Создано Алексеем Сердюковым.' + #10 + 'ver. 1.0.0' + #10 + 'NorthWest Records.' + #10 + '2015.');
end;
procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if (ssShift in Shift) then begin
case Key of
53: Percent.Click;
56: Multiplication.Click;
187: Addition.Click;
end;
end else begin
if (ssCtrl in Shift) then begin
case Key of
67: CopyItem.Click;
86: PasteItem.Click;
90: ShowItem.Click;
68: DeleteItem.Click;
end;
end else begin
case Key of
8: Backspace.Click;
48, 96: Digit0.Click;
49: Digit1.Click;
50: Digit2.Click;
51: Digit3.Click;
52: Digit4.Click;
53: Digit5.Click;
54: Digit6.Click;
55: Digit7.Click;
56: Digit8.Click;
57, 105: Digit9.Click;
67: Clear.Click;
106: Multiplication.Click;
107: Addition.Click;
189, 109: Subtraction.Click;
187, 13: Equal.Click;
188, 110: Dot.Click;
191, 111: Division.Click;
end;
end;
end;
end;
procedure TMainForm.MakeOperation(n: Integer);
begin
case n of
10: Operation := '+';
11: Operation := '-';
12: Operation := '*';
13: Operation := '/';
end;
end;
procedure TMainForm.MakeResult();
begin
case Operation of
'+': Result := First + Second;
'-': Result := First - Second;
'*': Result := First * Second;
'/':
begin
if ((First = 0) and (Second = 0)) then begin
BothZero := True;
end else begin
if (Second = 0) then begin
Zero := True;
end else begin
Result := First / Second;
end;
end;
end;
end;
end;
procedure TMainForm.ZeroCheck();
begin
if (BothZero) then begin
Display.Text := 'Результат не определен';
MemoryDisplay.Text := '';
Block := True;
end;
if (Zero) then begin
Display.Text := 'Деление на ноль невозможно';
MemoryDisplay.Text := '';
Block := True;
end;
end;
procedure TMainForm.MemoryCheck();
begin
if (Memory = 0) then begin
MemoryClear.Click;
end;
end;
procedure TMainForm.DigitsClick(Sender: TObject);
begin
if (not Block) then begin
if (State) then begin
Display.Text := Display.Text + IntToStr((Sender as TButton).Tag);
end else begin
Display.Text := IntToStr((Sender as TButton).Tag);
if (Display.Text <> '0') then begin
State := True;
end;
end;
end;
if (Operation = ' ') then begin
MemoryDisplay.Text := '';
end;
OperationBlock := False;
end;
procedure TMainForm.ClearClick(Sender: TObject);
begin
First := 0;
Second := 0;
Result := 0;
Operation := ' ';
OperationOn := False;
IsOn := False;
ClearEntry.Click;
end;
procedure TMainForm.ClearEntryClick(Sender: TObject);
begin
Display.Text := '0';
MemoryDisplay.Text := '';
State := False;
Block := False;
Zero := False;
BothZero := False;
OperationBlock := False;
end;
procedure TMainForm.RootClick(Sender: TObject);
begin
if (not Block) then begin
if (StrToFloat(Display.Text) >= 0) then begin
MemoryDisplay.Text := '√' + Display.Text;
Display.Text := FloatToStr(sqrt(StrToFloat(Display.Text)));
end else begin
Display.Text := 'Недопустимый ввод';
MemoryDisplay.Text := '';
Block := True;
end;
end;
State := False;
end;
procedure TMainForm.PlusMinusClick(Sender: TObject);
begin
if (not Block) then begin
if (StrToFloat(Display.Text) <> 0) then begin
Display.Text := FloatToStr(StrToFloat(Display.Text) * -1);
State := False;
end;
end;
end;
procedure TMainForm.InverseClick(Sender: TObject);
begin
if (not Block) then begin
if (StrToFloat(Display.Text) <> 0) then begin
MemoryDisplay.Text := '1/(' + Display.Text + ')';
Display.Text := FloatToStr(1 / StrToFloat(Display.Text));
end else begin
Display.Text := 'Деление на ноль невозможно';
MemoryDisplay.Text := '';
Block := True;
end;
end;
State := False;
end;
procedure TMainForm.BackspaceClick(Sender: TObject);
var
Buffer: String;
begin
if (not Block) then begin
if (Length(Display.Text) = 1) then begin
Display.Text := '0';
State := False;
end else begin
Buffer := Display.Text;
Delete(Buffer, Length(Buffer), 1);
Display.Text := Buffer;
State := True;
end;
end;
end;
procedure TMainForm.DotClick(Sender: TObject);
begin
if (not Block) then begin
if (2 = 2) then begin
Display.Text := Display.Text + '.';
State := True;
end;
end;
end;
procedure TMainForm.OperationClick(Sender: TObject);
begin
if (not Block) then begin
if (not OperationBlock) then begin
IsOn := False;
State := False;
if (OperationOn) then begin
Second := StrToFloat(Display.Text);
MakeResult;
MakeOperation((Sender as TButton).Tag);
Display.Text := FloatToStr(Result);
First := Result;
MemoryDisplay.Text := MemoryDisplay.Text + ' ' + FloatToStr(Second) + ' ' + Operation;
end else begin
First := StrToFloat(Display.Text);
OperationOn := True;
OperationBlock := True;
MakeOperation((Sender as TButton).Tag);
MemoryDisplay.Text := FloatToStr(First) + ' ' + Operation;
end;
ZeroCheck();
end else begin
MakeOperation((Sender as TButton).Tag);
MemoryDisplay.Text := Display.Text + ' ' + Operation;
end;
end;
end;
procedure TMainForm.IsClick(Sender: TObject);
begin
if (not Block) then begin
if (Operation <> ' ') then begin
MemoryDisplay.Text := '';
OperationOn := False;
State := False;
if (IsOn) then begin
First := StrToFloat(Display.Text);
end else begin
Second := StrToFloat(Display.Text);
IsOn := True;
end;
MakeResult();
Display.Text := FloatToStr(Result);
ZeroCheck();
end;
end;
end;
procedure TMainForm.PercentClick(Sender: TObject);
begin
if (not Block) then begin
Second := (StrToFloat(Display.Text) * First) / 100;
Display.Text := FloatToStr(Second);
State := False;
if (Second <> 0) then begin
if (MemoryDisplay.Text = '') then begin
MemoryDisplay.Text := FloatToStr(Second);
end else begin
MemoryDisplay.Text := MemoryDisplay.Text + ' ' + FloatToStr(Second);
end;
end;
end;
end;
procedure TMainForm.CopyItemClick(Sender: Tobject);
begin
if (not Block) then begin
CopyBuffer := StrToFloat(Display.Text);
State := False;
end;
end;
procedure TMainForm.PasteItemClick(Sender: TObject);
begin
if (not Block) then begin
Display.Text := FloatToStr(CopyBuffer);
State := False;
end;
end;
procedure TMainForm.ShowItemClick(Sender: TObject);
begin
ShowMessage('Содержимое буфера: ' + FloatToStr(CopyBuffer));
end;
procedure TMainForm.DeleteItemClick(Sender: TObject);
begin
CopyBuffer := 0;
end;
procedure TMainForm.MemoryAdditionOrSubtractionClick(Sender: TObject);
begin
if (not Block) then begin
MemoryIndicator.Visible := True;
State := False;
case (Sender as TButton).Tag of
20: Memory += StrToFloat(Display.Text);
21: Memory -= StrToFloat(Display.Text);
end;
MemoryCheck();
end;
end;
procedure TMainForm.MemorySaveClick(Sender: TObject);
begin
if (not Block) then begin
Memory := StrToFloat(Display.Text);
MemoryIndicator.Visible := True;
State := False;
MemoryCheck();
end;
end;
procedure TMainForm.MemoryRecallClick(Sender: TObject);
begin
if (not Block) then begin
Display.Text := FloatToStr(Memory);
State := False;
end;
end;
procedure TMainForm.MemoryClearClick(Sender: TObject);
begin
if (not Block) then begin
Memory := 0;
MemoryIndicator.Visible := False;
State := False;
end;
end;
end.
|
{
this file is part of Ares
Aresgalaxy ( http://aresgalaxy.sourceforge.net )
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 2 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, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
}
{
Description:
consts related to timeouts
}
unit const_timeouts;
interface
const
MIN_INTERVAL_QUERY_CACHE_ROOT=45;//seconds
MIN_LOG_INTERVAL_CHAT=25000; //25 secondi tra tentativi collegamento a chat server
MIN_LOG_INTERVAL_SUPERNODE=20000; //20 secondi tra tentativi collegamento a supernode hash server
MIN_LOG_INTERVAL_CACHE=30000; //30 secondi tra tentativi collegamento a cache server
UDPTRANSFER_PINGTIMEOUT=60000;
TIMEOUT_UDP_UPLOAD =60000;
INTERVAL_REQUERY_PARTIALS=120000;//due minuti
TIMEOUT_DATA_PARTIAL=60000;
TIMEOUT_RECEIVE_HANDSHAKE=15000; // after accept between handshake...
TIMEOUT_RECEIVE_REPLY=25000;
TIMEOUT_RECEIVING_FILE=60000;
SOURCE_RETRY_INTERVAL=45000;
TIMEOUT_FLUSH_TCP=15000;
TIMEOUT_INVIO_HEADER_REPLY_UPLOAD=40000;
MIN_DELAY_BETWEEN_PUSH=30000; // 30 secondi tra push req inviate...
DELAY_BETWEEN_RECHAT_REQUEST=2500; // 5 sec
GRAPH_TICK_TIME=55; // millisecs
implementation
end.
|
unit FC.Trade.Trader.TrendFollower.TestBenchDialog;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufmDialogClose_B, StdCtrls, ExtendControls, ExtCtrls, ComCtrls,
FC.Trade.Trader.TrendFollower,FC.DataUtils, FC.Dialogs.DockedDialogCloseAndAppWindow_B, ImgList, JvComponentBase,
JvCaptionButton, CheckLst,
FC.Definitions, StockChart.Definitions.Units, StockChart.Definitions, JvDockControlForm,
FC.Trade.Trader.TestBenchDialog_B,
FC.Trade.Trader.Base, Grids, DBGrids, MultiSelectDBGrid, ColumnSortDBGrid, EditDBGrid, DB, MemoryDS, JvExExtCtrls,
JvNetscapeSplitter, Mask;
type
TfmTrendFollowerTestBenchDialog = class(TfmTestBenchDialog_B)
paWorkspace: TPanel;
taTrendFollow: TMemoryDataSet;
taTrendFollowTime: TDateTimeField;
taTrendFollowTrendDir: TFloatField;
dsTrendFollow: TDataSource;
taTrendFollowClose: TFloatField;
taTrendFollowNo: TIntegerField;
PageControlEx1: TPageControlEx;
TabSheet1: TTabSheet;
paLeft: TPanel;
Label1: TLabel;
buStart: TButton;
lbTimeIntervals: TCheckListBox;
ckStopAfterEachRecord: TExtendCheckBox;
buResume: TButton;
buStop: TButton;
JvNetscapeSplitter2: TJvNetscapeSplitter;
grOrders: TEditDBGrid;
TabSheet2: TTabSheet;
taTrendFollow2: TMemoryDataSet;
dsTrendFollow2: TDataSource;
Panel1: TPanel;
buStart2: TButton;
JvNetscapeSplitter1: TJvNetscapeSplitter;
taTrendFollow2Time: TDateTimeField;
taTrendFollow2No: TIntegerField;
Label2: TLabel;
taTrendFollow2Guess: TFloatField;
taTrendFollow2ZigZag4H: TFloatField;
laStatisticsMatches: TLabel;
Panel2: TPanel;
edFilter: TExtendComboBox;
EditDBGrid1: TEditDBGrid;
taTrendFollow2EURUSD_H1_PbSAR: TFloatField;
taTrendFollow2EURUSD_H1_Acc: TFloatField;
taTrendFollow2EURUSD_H1_Fr: TFloatField;
taTrendFollow2GBPUSD_H1_PbSAR: TFloatField;
taTrendFollow2GBPUSD_H1_Acc: TFloatField;
taTrendFollow2GBPUSD_H1_Fr: TFloatField;
taTrendFollow2USDCHF_H1_PbSAR: TFloatField;
taTrendFollow2USDCHF_H1_Acc: TFloatField;
taTrendFollow2USDCHF_H1_Fr: TFloatField;
taTrendFollow2EURUSD_H4_PbSAR: TFloatField;
taTrendFollow2EURUSD_H4_Acc: TFloatField;
taTrendFollow2EURUSD_H4_Fr: TFloatField;
taTrendFollow2GBPUSD_H4_PbSAR: TFloatField;
taTrendFollow2GBPUSD_H4_Acc: TFloatField;
taTrendFollow2GBPUSD_H4_Fr: TFloatField;
taTrendFollow2USDCHF_H4_PbSAR: TFloatField;
taTrendFollow2USDCHF_H4_Acc: TFloatField;
taTrendFollow2USDCHF_H4_Fr: TFloatField;
laRecordCount: TLabel;
taTrendFollow2Price: TFloatField;
taTrendFollow2AtPbSARReverse: TFloatField;
taTrendFollow2ZigZag1H: TFloatField;
taTrendFollow2ZigZag1HTime: TDateTimeField;
taTrendFollow2ZigZag4HTime: TDateTimeField;
lbHours: TCheckListBox;
procedure edFilterKeyPress(Sender: TObject; var Key: Char);
procedure EditDBGrid1BeforeDrawColumnCell(Sender: TObject; DataCol: Integer; Column: TColumn;
State: TGridDrawState);
procedure buStart2Click(Sender: TObject);
procedure EditDBGrid1DblClick(Sender: TObject);
procedure grOrdersDblClick(Sender: TObject);
procedure grOrdersBeforeDrawColumnCell(Sender: TObject; DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure buStopClick(Sender: TObject);
procedure buResumeClick(Sender: TObject);
procedure buStartClick(Sender: TObject);
function GetIndicatorFromChart(aChart: IStockChart; const aIID: TGUID): ISCIndicator;
procedure CalcRecordCount;
private
FInputDatas : TStockTimeIntervalInputDataCollectionArray;
FCharts : TStockTimeIntervalChartArray;
FLastTrendIndexes : array [TStockTimeInterval] of integer;
FTrader: TStockTraderTrendFollower;
FContinue : boolean;
FStop : boolean;
procedure OnTick(const aDateTime: TDateTime; const aIndexes: TStockTimeIntervalIntArray);
public
constructor Create(aTrader: TStockTraderBase); override;
destructor Destroy; override;
end;
implementation
uses Math, BaseUtils, DateUtils, SystemService,StockChart.Obj;
{$R *.dfm}
procedure TfmTrendFollowerTestBenchDialog.CalcRecordCount;
var
aBk: TBookmark;
i: integer;
begin
aBk:=taTrendFollow2.Bookmark;
taTrendFollow2.DisableControls;
try
taTrendFollow2.First; i:=0;
while not taTrendFollow2.Eof do
begin
inc(i);
taTrendFollow2.Next;
end;
finally
try
taTrendFollow2.Bookmark:=aBk;
except
end;
taTrendFollow2.EnableControls;
end;
laRecordCount.Caption:=Format('Count=%d',[i]);
end;
constructor TfmTrendFollowerTestBenchDialog.Create(aTrader: TStockTraderBase);
var
i:TStockTimeInterval;
j: integer;
begin
inherited;
FTrader:=aTrader as TStockTraderTrendFollower;
for i:=Low(TStockTimeInterval) to High(TStockTimeInterval) do
begin
lbTimeIntervals.Items.Add(StockTimeIntervalNames[i]);
if not (i in [sti1,sti30]) then
lbTimeIntervals.Checked[integer(i)]:=true;
FInputDatas[i]:=FTrader.GetProject.GetStockChart(i).GetInputData;
FCharts[i]:=FTrader.GetProject.GetStockChart(i);
end;
for j:=0 to 23 do
lbHours.Items.AddObject(IntToStrEx(j,2),TObject(j));
lbHours.Checked[15]:=true;
end;
destructor TfmTrendFollowerTestBenchDialog.Destroy;
begin
lbTimeIntervals.Items.Clear;
inherited;
end;
procedure TfmTrendFollowerTestBenchDialog.edFilterKeyPress(Sender: TObject; var Key: Char);
begin
inherited;
if Key=#13 then
begin
taTrendFollow2.Filter:=edFilter.Text;
taTrendFollow2.Filtered:=true;
CalcRecordCount;
end;
end;
procedure TfmTrendFollowerTestBenchDialog.EditDBGrid1BeforeDrawColumnCell(Sender: TObject; DataCol: Integer;
Column: TColumn; State: TGridDrawState);
begin
if (Column.Field.Tag<>0) then
begin
if Column.Field.IsNull then
TEditDBGrid(Sender).Canvas.Brush.Color:=clWindow
else if Column.Field.AsFloat<0 then
TEditDBGrid(Sender).Canvas.Brush.Color:=clWebLightBlue
else
TEditDBGrid(Sender).Canvas.Brush.Color:=clWebBisque;
end
end;
procedure TfmTrendFollowerTestBenchDialog.EditDBGrid1DblClick(Sender: TObject);
var
aOpenTime,aCloseTime: TDateTime;
aShiftState: TShiftState;
begin
aOpenTime:=taTrendFollow2Time.Value;
aCloseTime:=aOpenTime+60/MinsPerDay;
aShiftState:=KeyboardStateToShiftState;
FTrader.GetProject.HilightOnCharts(aOpenTime,aCloseTime,not (ssShift in aShiftState));
end;
function TfmTrendFollowerTestBenchDialog.GetIndicatorFromChart(aChart: IStockChart; const aIID: TGUID): ISCIndicator;
var
aCollection: ISCIndicatorCollectionReadOnly;
s: string;
begin
aCollection:=aChart.FindIndicators(aIID);
if aCollection.Count=0 then
begin
s:=Format('Indicator "%s" was not found on the chart "%s". Add the indicator before start.',
[IndicatorFactory.GetIndicatorInfo(aIID).Name,aChart.StockSymbol.GetDisplayText]);
raise EStockError.Create(s);
end;
result:=aCollection[0];
end;
procedure TfmTrendFollowerTestBenchDialog.grOrdersBeforeDrawColumnCell(Sender: TObject; DataCol: Integer;
Column: TColumn; State: TGridDrawState);
begin
if Column.Field=taTrendFollowTrendDir then
begin
if taTrendFollowTrendDir.IsNull then
TEditDBGrid(Sender).Canvas.Brush.Color:=clWindow
else if taTrendFollowTrendDir.Value<0 then
TEditDBGrid(Sender).Canvas.Brush.Color:=clWebLightBlue
else
TEditDBGrid(Sender).Canvas.Brush.Color:=clWebBisque;
end
end;
procedure TfmTrendFollowerTestBenchDialog.grOrdersDblClick(Sender: TObject);
var
aOpenTime,aCloseTime: TDateTime;
aShiftState: TShiftState;
begin
aOpenTime:=taTrendFollowTime.Value;
aCloseTime:=aOpenTime+60/MinsPerDay;
aShiftState:=KeyboardStateToShiftState;
FTrader.GetProject.HilightOnCharts(aOpenTime,aCloseTime,not (ssShift in aShiftState));
end;
procedure TfmTrendFollowerTestBenchDialog.buResumeClick(Sender: TObject);
begin
inherited;
FContinue:=true;
end;
procedure TfmTrendFollowerTestBenchDialog.buStart2Click(Sender: TObject);
const
ChartCount = 6;
var
aCharts: array [0..ChartCount-1] of IStockChart;
aPbSARs: array [0..ChartCount-1] of ISCIndicatorParabolicSAR;
// aAccs: array [0..ChartCount-1] of ISCIndicatorAccelerator;
//aFrs: array [0..ChartCount-1] of ISCIndicatorFractals;
aPbSARFields: array [0..ChartCount-1] of TField;
// aAccFields: array [0..ChartCount-1] of TField;
//aFrFields: array [0..ChartCount-1] of TField;
aStartTime: TDateTime;
aStopTime: TDateTime;
i,j: Integer;
aZigZag1H,aZigZag4H: ISCIndicatorZigZag;
aGuess: TStockRealNumber;
aMatched,aMismatched:integer;
begin
inherited;
aCharts[0]:=FTrader.GetProject.FindStockChart('EURUSD',sti60);
aCharts[1]:=FTrader.GetProject.FindStockChart('GBPUSD',sti60);
aCharts[2]:=FTrader.GetProject.FindStockChart('USDCHF',sti60);
aCharts[3]:=FTrader.GetProject.FindStockChart('EURUSD',sti240); //EURUSD 4 h
aCharts[4]:=FTrader.GetProject.FindStockChart('GBPUSD',sti240);
aCharts[5]:=FTrader.GetProject.FindStockChart('USDCHF',sti240);
for i := 0 to ChartCount - 1 do
aPbSARs[i]:=GetIndicatorFromChart(aCharts[i],ISCIndicatorParabolicSAR) as ISCIndicatorParabolicSAR;
// for i := 0 to ChartCount - 1 do
// aAccs[i]:=GetIndicatorFromChart(aCharts[i],ISCIndicatorAccelerator) as ISCIndicatorAccelerator;
// for i := 0 to ChartCount - 1 do
// aFrs[i]:=GetIndicatorFromChart(aCharts[i],ISCIndicatorFractals) as ISCIndicatorFractals;
aZigZag1H:=GetIndicatorFromChart(aCharts[0], ISCIndicatorZigZag) as ISCIndicatorZigZag;
aZigZag4H:=GetIndicatorFromChart(aCharts[3], ISCIndicatorZigZag) as ISCIndicatorZigZag;
aPbSARFields[0]:= taTrendFollow2EURUSD_H1_PbSAR;
aPbSARFields[1]:= taTrendFollow2GBPUSD_H1_PbSAR;
aPbSARFields[2]:= taTrendFollow2USDCHF_H1_PbSAR;
aPbSARFields[3]:= taTrendFollow2EURUSD_H4_PbSAR;
aPbSARFields[4]:= taTrendFollow2GBPUSD_H4_PbSAR;
aPbSARFields[5]:= taTrendFollow2USDCHF_H4_PbSAR;
// aAccFields[0]:= taTrendFollow2EURUSD_H1_Acc;
// aAccFields[1]:= taTrendFollow2GBPUSD_H1_Acc;
// aAccFields[2]:= taTrendFollow2USDCHF_H1_Acc;
// aAccFields[3]:= taTrendFollow2EURUSD_H4_Acc;
// aAccFields[4]:= taTrendFollow2GBPUSD_H4_Acc;
// aAccFields[5]:= taTrendFollow2USDCHF_H4_Acc;
// aFrFields[0]:= taTrendFollow2EURUSD_H1_Fr;
// aFrFields[1]:= taTrendFollow2GBPUSD_H1_Fr;
// aFrFields[2]:= taTrendFollow2USDCHF_H1_Fr;
// aFrFields[3]:= taTrendFollow2EURUSD_H4_Fr;
// aFrFields[4]:= taTrendFollow2GBPUSD_H4_Fr;
// aFrFields[5]:= taTrendFollow2USDCHF_H4_Fr;
aStartTime:=-1;
aStopTime:=high(integer);
for i := 0 to ChartCount - 1 do
aStartTime:=max(aStartTime,aCharts[i].GetInputData.DirectGetItem_DataDateTime(0));
for i := 0 to ChartCount - 1 do
aStopTime:=min(aStopTime,aCharts[i].GetInputData.DirectGetItem_DataDateTime(aCharts[i].GetInputData.Count-1));
TWaitCursor.SetUntilIdle;
taTrendFollow2.DisableControls;
aMatched:=0;
aMismatched:=0;
try
taTrendFollow2.Open;
taTrendFollow2.EmptyTable;
while aStartTime<=aStopTime do
begin
aStartTime:=TStockDataUtils.RefineTime(aStartTime);
if not (DayOfTheWeek(aStartTime) in [6,7]) then
if lbHours.Checked[HourOfTheDay(aStartTime)] then
begin
taTrendFollow2.Append;
taTrendFollow2No.Value:=taTrendFollow2.RecordCount+1;
taTrendFollow2Time.Value:=aStartTime;
//Цена закрытия бара, EURUSD 1h
j:=aCharts[0].GetInputData.FindExactMatched(aStartTime);
if j<>-1 then
taTrendFollow2Price.Value:=aCharts[0].GetInputData.DirectGetItem_DataClose(j);
for i := 0 to ChartCount - 1 do
begin
j:=aCharts[i].GetInputData.FindExactMatched(aStartTime);
if j<>-1 then
begin
//Parabolic SAR
if j>=aPbSARs[i].GetFirstValidValueIndex then
aPbSARFields[i].AsInteger:=
aCharts[i].GetInputData.PriceToPoint(sqrt(Abs(aPbSARs[i].GetDivergence(j)*aPbSARs[i].GetTrendForce(j))))*
aPbSARFields[i].Tag*
Sign(aPbSARs[i].GetDivergence(j));
//Fractals
{ if (j-2>=2) and (aFrs[i].GetPrecedentExtremumIndex(j-2,k)) then
begin
if (aFrs[i].GetValue(k))=1 then
aFrFields[i].AsInteger:=1*aFrFields[i].Tag
else if (aFrs[i].GetValue(k))=2 then
aFrFields[i].AsInteger:=-1*aFrFields[i].Tag
end;
}
//Accelerator/Deccelerator
{ if j>aAccs[i].GetFirstValidValueIndex then
aAccFields[i].AsInteger:=PriceToPoint(
(aAccs[i].GetValue(j)-aAccs[i].GetValue(j-1))*aAccFields[i].Tag);
}
end;
end;
//Guess
try
{ j:=0; aGuess:=0;
for i := 0 to ChartCount - 1 do
begin
if aPbSARFields[i].IsNull then
abort;
aGuess:=aGuess+aPbSARFields[i].AsInteger;
inc(j);
end;
}
//Пока упрощаем, считаем только по EURUSD
//j:=2;
//aGuess:=Sign(aPbSARFields[0].AsInteger)+Sign(aPbSARFields[3].AsInteger);
aGuess:=aPbSARFields[0].AsInteger+aPbSARFields[3].AsInteger;
{ for i := 0 to ChartCount - 1 do
begin
if aAccFields[i].IsNull then
abort;
aGuess:=aGuess+aAccFields[i].AsInteger;
inc(j);
end;
}
if aGuess<>0 then
taTrendFollow2Guess.AsFloat:=aGuess;
except
on E:EAbort do ;
end;
//ZigZag 4H
j:=aZigZag4H.GetInputData.FindExactMatched(aStartTime);
if (j<>-1) and (aZigZag4H.GetSuccedentExtremumIndex(j+1,i)) then
begin
taTrendFollow2ZigZag4HTime.Value:=aZigZag4H.GetInputData.DirectGetItem_DataDateTime(i);
//Min
if aZigZag4H.GetValue(i)=-1 then
taTrendFollow2ZigZag4H.AsInteger:=aZigZag4H.GetInputData.PriceToPoint(aZigZag4H.GetInputData.DirectGetItem_DataLow(i)-taTrendFollow2Price.AsFloat)
//Max
else if aZigZag4H.GetValue(i)=1 then
taTrendFollow2ZigZag4H.AsInteger:=aZigZag4H.GetInputData.PriceToPoint(aZigZag4H.GetInputData.DirectGetItem_DataHigh(i)-taTrendFollow2Price.AsFloat);
end;
//ZigZag 1H
j:=aZigZag1H.GetInputData.FindExactMatched(aStartTime);
if (j<>-1) and (aZigZag1H.GetSuccedentExtremumIndex(j+1,i)) then
begin
//Цена закрытия бара
taTrendFollow2Price.Value:=aZigZag1H.GetInputData.DirectGetItem_DataClose(j);
taTrendFollow2ZigZag1HTime.Value:=aZigZag1H.GetInputData.DirectGetItem_DataDateTime(i);
//Min
if aZigZag1H.GetValue(i)=-1 then
taTrendFollow2ZigZag1H.AsInteger:=aZigZag1H.GetInputData.PriceToPoint(aZigZag1H.GetInputData.DirectGetItem_DataLow(i)-taTrendFollow2Price.AsFloat)
//Max
else if aZigZag1H.GetValue(i)=1 then
taTrendFollow2ZigZag1H.AsInteger:=aZigZag1H.GetInputData.PriceToPoint(aZigZag1H.GetInputData.DirectGetItem_DataHigh(i)-taTrendFollow2Price.AsFloat);
end;
//At PbSARReverse (EURUSD 4h)
try
j:=aCharts[3].GetInputData.FindExactMatched(aStartTime);
if j<>-1 then
begin
i:=j;
while Sign(aPbSARFields[3].AsInteger)=Sign(aPbSARs[3].GetDivergence(i)*aPbSARFields[3].Tag) do
begin
inc(i);
if i>=aCharts[3].GetInputData.Count then
abort;
end;
taTrendFollow2AtPbSARReverse.AsInteger:=aCharts[3].GetInputData.PriceToPoint(aCharts[3].GetInputData.DirectGetItem_DataClose(i)-taTrendFollow2Price.AsFloat);
end;
except
on E:EAbort do;
end;
if (not taTrendFollow2Guess.IsNull) then
begin
if Sign(taTrendFollow2Guess.Value)=Sign(taTrendFollow2ZigZag4H.Value) then
inc(aMatched)
else
inc(aMismatched);
end;
taTrendFollow2.Post;
end;
aStartTime:=IncHour(aStartTime);
end;
finally
taTrendFollow2.First;
taTrendFollow2.EnableControls;
end;
EditDBGrid1.ColumnSizes.FitColumnsByContents();
laStatisticsMatches.Caption:=Format('Match/Mism.=%d/%d',[aMatched,aMismatched]);
CalcRecordCount;
end;
procedure TfmTrendFollowerTestBenchDialog.buStartClick(Sender: TObject);
var
aNewInputDatas: array [TStockTimeInterval] of TSCInputDataCollection;
aInterval: TStockTimeInterval;
aGenerators: array [TStockTimeInterval] of TStockBarBackwardGenerator;
i,k: Integer;
aIData: ISCInputDataCollection;
aGenerator : TStockBarBackwardGenerator;
aPriorDate: TDateTime;
aBarData : TStockBarData;
aIndexes: TStockTimeIntervalIntArray;
begin
inherited;
TWaitCursor.SetUntilIdle;
taTrendFollow.OPen;
taTrendFollow.EmptyTable;
FStop:=false;
buStart.Enabled:=false;
buResume.Enabled:=true;
buStop.Enabled:=true;
try
//Подменяем InputData
for aInterval:=low(TStockTimeInterval) to high(TStockTimeInterval) do
begin
FLastTrendIndexes[aInterval]:=-1;
Assert(FCharts[aInterval].GetInputData=FInputDatas[aInterval]);
aNewInputDatas[aInterval]:=TSCInputDataCollection.Create(nil,StockTimeIntervalValues[aInterval]/MinsPerDay);
FCharts[aInterval].SetInputData(aNewInputDatas[aInterval]);
if aInterval<>sti1 then
aGenerators[aInterval]:=TStockBarBackwardGenerator.Create(FInputDatas[sti1],aInterval)
else
aGenerators[aInterval]:=nil;
end;
for i := 0 to FInputDatas[sti1].Count-1 do
begin
//Минутку добавляем
aNewInputDatas[sti1].AddItem(
FInputDatas[sti1].DirectGetItem_DataDateTime(i),
FInputDatas[sti1].DirectGetItem_DataOpen(i),
FInputDatas[sti1].DirectGetItem_DataHigh(i),
FInputDatas[sti1].DirectGetItem_DataLow(i),
FInputDatas[sti1].DirectGetItem_DataClose(i),
FInputDatas[sti1].DirectGetItem_DataVolume(i));
aIndexes[sti1]:=aNewInputDatas[sti1].Count-1;
//Эмулируем тики на разных таймфреймах
for aInterval:=Succ(sti1) to high(TStockTimeInterval) do
begin
aIData:=FInputDatas[aInterval];
aGenerator:=aGenerators[aInterval];
aGenerator.GenerateBar(i);
aBarData:=aGenerator.BarData;
aPriorDate:=0;
k:=aNewInputDatas[aInterval].Count;
if (k>0) then
aPriorDate:=aNewInputDatas[aInterval].DirectGetItem_DataDateTime(k-1);
//Модифицируем старый бар
if aPriorDate=aGenerator.DestLeftBound then
begin
Assert(k>0);
aNewInputDatas[aInterval].ModifyItem(k-1,
aBarData.Open,aBarData.High,aBarData.Low,aBarData.Close,aBarData.Volume)
end
//Новый бар - добавляем
else begin
Assert(aPriorDate<aGenerator.DestLeftBound);
aNewInputDatas[aInterval].AddItem(
aIData.DirectGetItem_DataDateTime(k),
aBarData.Open,aBarData.High,aBarData.Low,aBarData.Close,aBarData.Volume)
end;
aIndexes[aInterval]:=aNewInputDatas[aInterval].Count-1;
end;
OnTick(FInputDatas[sti1].DirectGetItem_DataDateTime(i),aIndexes);
if FStop then
break;
end;
finally
for aInterval:=low(TStockTimeInterval) to high(TStockTimeInterval) do
begin
//Возвращаем InputData
FCharts[aInterval].SetInputData(FInputDatas[aInterval]);
aGenerators[aInterval].Free;
end;
buStart.Enabled:=true;
buResume.Enabled:=false;
buStop.Enabled:=false;
end;
end;
procedure TfmTrendFollowerTestBenchDialog.buStopClick(Sender: TObject);
begin
inherited;
FStop:=true;
end;
procedure TfmTrendFollowerTestBenchDialog.OnTick(const aDateTime: TDateTime;const aIndexes: TStockTimeIntervalIntArray);
var
aHigherTrend: integer;
aMyTrend: integer;
bFound : boolean;
i:TStockTimeInterval;
index: integer;
aPbSARs: array [TStockTimeInterval] of ISCExpertParabolicSAR;
begin
aHigherTrend:=0;
bFound:=true;
//Вне этого диапазона волатильность низкая
if (Frac(aDateTime)<EncodeTime(8,0,0,0)) or (Frac(aDateTime)>EncodeTime(20,30,0,0)) then
exit;
for i:=Low(TStockTimeInterval) to High(TStockTimeInterval) do
begin
if not lbTimeIntervals.Checked[integer(i)] then
aPbSARs[i]:=nil
else
raise Exception.Create('Не доделано');
//aPbSARs[i]:=FTrader.GetExpertPbSAR(i);
end;
for i:=Low(TStockTimeInterval) to High(TStockTimeInterval) do
begin
if (aPbSARs[i]=nil) then
continue;
index:=aIndexes[i];
if (index<max(1,aPbSARs[i].GetFirstValidValueIndex)) then
begin
bFound:=false;
break;
end;
aMyTrend:=Sign(aPbSARs[i].GetTrend(index));
if aHigherTrend=0 then //Если это первый (самый младший) чарт
begin
if FLastTrendIndexes[i]=index then
aMyTrend:=-2 //Если это все тот-же тренд
else if (Sign(aMyTrend)=Sign(aPbSARs[i].GetTrend(index-1))) and (index=FLastTrendIndexes[i]+1) then
begin
aMyTrend:=-2; //Если это все тот-же тренд
FLastTrendIndexes[i]:=index;
end
else
aHigherTrend:=aMyTrend;
end;
if aHigherTrend<>aMyTrend then
begin
bFound:=false;
break;
end;
end;
if bFound then
begin
for i:=Low(TStockTimeInterval) to High(TStockTimeInterval) do
begin
FLastTrendIndexes[i]:=aIndexes[i];
end;
taTrendFollow.Append;
taTrendFollowNo.Value:=taTrendFollow.RecordCount+1;
taTrendFollowTime.Value:=aDateTime;
taTrendFollowTrendDir.Value:=aHigherTrend;
taTrendFollowClose.Value:=FCharts[sti1].GetInputData.DirectGetItem_DataClose(aIndexes[sti1]);
taTrendFollow.Post;
Application.ProcessMessages;
if ckStopAfterEachRecord.Checked then
begin
FContinue:=false;
FStop:=false;
while not FContinue and not FStop do
Application.ProcessMessages;
end
end;
end;
end.
|
unit RadioGroupImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ExtCtrls;
type
TRadioGroupX = class(TActiveXControl, IRadioGroupX)
private
{ Private declarations }
FDelphiControl: TRadioGroup;
FEvents: IRadioGroupXEvents;
procedure ClickEvent(Sender: TObject);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_Caption: WideString; safecall;
function Get_Color: OLE_COLOR; safecall;
function Get_Columns: Integer; safecall;
function Get_Ctl3D: WordBool; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_ItemIndex: Integer; safecall;
function Get_Items: IStrings; safecall;
function Get_ParentColor: WordBool; safecall;
function Get_ParentCtl3D: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_Visible: WordBool; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_Caption(const Value: WideString); safecall;
procedure Set_Color(Value: OLE_COLOR); safecall;
procedure Set_Columns(Value: Integer); safecall;
procedure Set_Ctl3D(Value: WordBool); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_ItemIndex(Value: Integer); safecall;
procedure Set_Items(const Value: IStrings); safecall;
procedure Set_ParentColor(Value: WordBool); safecall;
procedure Set_ParentCtl3D(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_Visible(Value: WordBool); safecall;
end;
implementation
uses ComObj, About25;
{ TRadioGroupX }
procedure TRadioGroupX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_RadioGroupXPage); }
end;
procedure TRadioGroupX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IRadioGroupXEvents;
end;
procedure TRadioGroupX.InitializeControl;
begin
FDelphiControl := Control as TRadioGroup;
FDelphiControl.OnClick := ClickEvent;
end;
function TRadioGroupX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TRadioGroupX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TRadioGroupX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TRadioGroupX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TRadioGroupX.Get_Caption: WideString;
begin
Result := WideString(FDelphiControl.Caption);
end;
function TRadioGroupX.Get_Color: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.Color);
end;
function TRadioGroupX.Get_Columns: Integer;
begin
Result := FDelphiControl.Columns;
end;
function TRadioGroupX.Get_Ctl3D: WordBool;
begin
Result := FDelphiControl.Ctl3D;
end;
function TRadioGroupX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TRadioGroupX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TRadioGroupX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TRadioGroupX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TRadioGroupX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TRadioGroupX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TRadioGroupX.Get_ItemIndex: Integer;
begin
Result := FDelphiControl.ItemIndex;
end;
function TRadioGroupX.Get_Items: IStrings;
begin
GetOleStrings(FDelphiControl.Items, Result);
end;
function TRadioGroupX.Get_ParentColor: WordBool;
begin
Result := FDelphiControl.ParentColor;
end;
function TRadioGroupX.Get_ParentCtl3D: WordBool;
begin
Result := FDelphiControl.ParentCtl3D;
end;
function TRadioGroupX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TRadioGroupX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TRadioGroupX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TRadioGroupX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TRadioGroupX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TRadioGroupX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TRadioGroupX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TRadioGroupX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TRadioGroupX.AboutBox;
begin
ShowRadioGroupXAbout;
end;
procedure TRadioGroupX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TRadioGroupX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TRadioGroupX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TRadioGroupX.Set_Caption(const Value: WideString);
begin
FDelphiControl.Caption := TCaption(Value);
end;
procedure TRadioGroupX.Set_Color(Value: OLE_COLOR);
begin
FDelphiControl.Color := TColor(Value);
end;
procedure TRadioGroupX.Set_Columns(Value: Integer);
begin
FDelphiControl.Columns := Value;
end;
procedure TRadioGroupX.Set_Ctl3D(Value: WordBool);
begin
FDelphiControl.Ctl3D := Value;
end;
procedure TRadioGroupX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TRadioGroupX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TRadioGroupX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TRadioGroupX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TRadioGroupX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TRadioGroupX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TRadioGroupX.Set_ItemIndex(Value: Integer);
begin
FDelphiControl.ItemIndex := Value;
end;
procedure TRadioGroupX.Set_Items(const Value: IStrings);
begin
SetOleStrings(FDelphiControl.Items, Value);
end;
procedure TRadioGroupX.Set_ParentColor(Value: WordBool);
begin
FDelphiControl.ParentColor := Value;
end;
procedure TRadioGroupX.Set_ParentCtl3D(Value: WordBool);
begin
FDelphiControl.ParentCtl3D := Value;
end;
procedure TRadioGroupX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TRadioGroupX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TRadioGroupX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TRadioGroupX,
TRadioGroup,
Class_RadioGroupX,
25,
'{695CDB98-02E5-11D2-B20D-00C04FA368D4}',
0,
tmApartment);
end.
|
unit fft;
interface
{$mode objfpc}
uses base;
type
TFFT = class
private
fPoints: PtrInt;
fIndex: array of PtrInt;
fTwiddleR, fTwiddleI: array of single;
procedure CalcFFT(var OutR, OutI: TVector);
public
procedure CalcFFTRealAbs(const InpR: TVector; var OutR: TVector);
procedure CalcFFTReal(const InpR: TVector; var OutR, OutI: TVector);
procedure CalcFFTComplex(const InpR, InpI: TVector; var OutR, OutI: TVector);
constructor Create(Points: PtrInt; Inverse: boolean = false);
destructor Destroy; override;
property Points: PtrInt read fPoints;
end;
function FFTRealReal(const T: TVector): TVector; // Transform a vector of only real components, and return the real components of the FFT
function FFTRealRealSqr(const T: TVector): TVector; // Transform a vector of only real components, and return the square of the FFT result
function FFTRealRealAbs(const T: TVector): TVector; // Transform a vector of only real components, and return the magnitude of the FFT result
function IFFTRealReal(const T: TVector): TVector;
function IFFTRealRealSqr(const T: TVector): TVector;
function IFFTRealRealAbs(const T: TVector): TVector;
implementation
function BitReverse(X, N: PtrInt): PtrInt;
begin
result := 0;
while n > 1 do
begin
result := result shl 1;
if (x and 1) = 1 then
result := result or 1;
x := x shr 1;
n := n shr 1;
end;
end;
function FFTRealReal(const T: TVector): TVector;
var f: TFFT;
tmp: TVector;
begin
setlength(result, length(t));
setlength(tmp, length(t));
f := TFFT.Create(length(t));
f.CalcFFTReal(t, result, tmp);
f.Free;
end;
function FFTRealRealSqr(const T: TVector): TVector;
var f: TFFT;
begin
setlength(result, length(t));
f := TFFT.Create(length(t));
f.CalcFFTRealAbs(t, result);
f.Free;
result := sqr(result);
end;
function FFTRealRealAbs(const T: TVector): TVector;
var f: TFFT;
begin
setlength(result, length(t));
f := TFFT.Create(length(t));
f.CalcFFTRealAbs(t, result);
f.Free;
end;
function IFFTRealReal(const T: TVector): TVector;
var f: TFFT;
tmp: TVector;
begin
setlength(result, length(t));
setlength(tmp, length(t));
f := TFFT.Create(length(t), true);
f.CalcFFTReal(t, result, tmp);
f.Free;
end;
function IFFTRealRealSqr(const T: TVector): TVector;
var f: TFFT;
begin
setlength(result, length(t));
f := TFFT.Create(length(t), true);
f.CalcFFTRealAbs(t, result);
f.Free;
result := sqr(result);
end;
function IFFTRealRealAbs(const T: TVector): TVector;
var f: TFFT;
begin
setlength(result, length(t));
f := TFFT.Create(length(t), true);
f.CalcFFTRealAbs(t, result);
f.Free;
end;
procedure TFFT.CalcFFT(var OutR, OutI: TVector);
var n,nb, pti,i: PtrInt;
xr,xi,sr,si,yr,yi,tr,ti: single;
begin
n := 2;
pti := 0;
nb := 1;
repeat
pti := 0;
repeat
for i := 0 to nb-1 do
begin
xr := outr[pti+i];
xi := outi[pti+i];
yr := outr[pti+i+nb];
yi := outi[pti+i+nb];
tr := fTwiddleR[fPoints*i div n];
ti := fTwiddleI[fPoints*i div n];
sr := yr*tr-yi*ti;
si := yr*ti+yi*tr;
outr[pti+i] := (xr+sr)/2;
outi[pti+i] := (xi+si)/2;
outr[pti+i+nb] := (xr-sr)/2;
outi[pti+i+nb] := (xi-si)/2;
end;
inc(pti, n);
until pti >= fPoints;
nb := n;
n := n shl 1;
until n > fPoints;
end;
procedure TFFT.CalcFFTRealAbs(const InpR: TVector; var OutR: TVector);
var i: ptrint;
tmpi: TVector;
begin
//Bit reverse input
setlength(tmpi, length(inpr));
for i := 0 to fPoints-1 do
begin
OutR[i] := Inpr[fIndex[i]];
tmpi[i] := 0;
end;
CalcFFT(OutR, tmpi);
for i := 0 to fPoints-1 do
OutR[i] := system.sqrt(outR[i]*outR[i]+tmpi[i]*tmpi[i]);
end;
procedure TFFT.CalcFFTReal(const InpR: TVector; var OutR, OutI: TVector);
var i: ptrint;
begin
//Bit reverse input
for i := 0 to fPoints-1 do
begin
OutR[i] := InpR[fIndex[i]];
OutI[i] := 0;
end;
CalcFFT(OutR, OutI);
end;
procedure TFFT.CalcFFTComplex(const InpR, InpI: TVector; var OutR, OutI: TVector);
var i: ptrint;
begin
//Bit reverse input
for i := 0 to fPoints-1 do
begin
OutR[i] := InpR[fIndex[i]];
OutI[i] := InpI[fIndex[i]];
end;
CalcFFT(OutR, OutI);
end;
constructor TFFT.Create(Points: PtrInt; Inverse: boolean);
var i, sign: ptrint;
begin
inherited Create;
assert(system.sqrt(points*points)=points, 'FFT must be of a power of 2');
fPoints := Points;
setlength(fIndex, points);
for i := 0 to Points-1 do fIndex[i] := BitReverse(i, Points);
setlength(fTwiddleR, points div 2);
setlength(fTwiddleI, points div 2);
if inverse then
sign := 1
else
sign := -1;
for i := 0 to (points div 2)-1 do
begin
fTwiddleR[i] := cos(sign*i/points*2*pi);
fTwiddleI[i] := sin(sign*i/points*2*pi);
end;
end;
destructor TFFT.Destroy;
begin
setlength(fIndex, 0);
setlength(fTwiddleR, 0);
setlength(fTwiddleI, 0);
inherited Destroy;
end;
end.
|
unit ufrmCaptionToolbar;
interface
uses
Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Types, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls;
type
TTest = class
strict private const
WM_NCUAHDRAWCAPTION = $00AE;
WM_NCUAHDRAWFRAME = $00AF;
private
FCallDefaultProc: Boolean;
FChangeSizeCalled: Boolean;
FControl: TWinControl;
FHandled: Boolean;
FNeedsUpdate: Boolean; //
FRegion: HRGN;
FLeft: integer;
FTop: integer;
FWidth: integer;
FHeight: integer;
function GetHandle: HWND; inline;
function GetForm: TCustomForm; inline;
procedure ChangeSize;
procedure WMNCPaint(var message: TWMNCPaint); message WM_NCPAINT;
procedure WMNCActivate(var Message: TMessage); message WM_NCACTIVATE;
procedure WMNCLButtonDown(var Message: TWMNCHitMessage); message WM_NCLBUTTONDOWN;
procedure WMNCUAHDrawCaption(var Message: TMessage); message WM_NCUAHDRAWCAPTION;
procedure WMNCUAHDrawFrame(var Message: TMessage); message WM_NCUAHDRAWFRAME;
procedure WMNCCalcSize(var message: TWMNCCalcSize); message WM_NCCALCSIZE;
procedure WMWindowPosChanging(var Message: TWMWindowPosChanging); message WM_WINDOWPOSCHANGING;
procedure WndProc(var message: TMessage);
procedure CallDefaultProc(var message: TMessage);
protected
property Handle: HWND read GetHandle;
procedure InvalidateNC;
procedure PaintNC(ARGN: HRGN = 0);
public
constructor Create(AOwner: TWinControl);
destructor Destroy; override;
property Handled: Boolean read FHandled write FHandled;
property Control: TWinControl read FControl;
property Form: TCustomForm read GetForm;
end;
TForm11 = class(TForm)
Button1: TButton;
private
FTest: TTest;
protected
function DoHandleMessage(var message: TMessage): Boolean;
procedure WndProc(var Message: TMessage); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
Form11: TForm11;
implementation
{$R *.dfm}
{ TForm11 }
constructor TForm11.Create(AOwner: TComponent);
begin
FTest := TTest.Create(Self);
inherited;
end;
destructor TForm11.Destroy;
begin
inherited;
FreeAndNil(FTest);
end;
function TForm11.DoHandleMessage(var message: TMessage): Boolean;
begin
Result := False;
if not FTest.FCallDefaultProc then
begin
FTest.WndProc(message);
Result := FTest.Handled;
end;
end;
procedure TForm11.WndProc(var Message: TMessage);
begin
if not DoHandleMessage(Message) then
inherited;
end;
procedure TTest.CallDefaultProc(var message: TMessage);
begin
///
/// 调用控件默认消息处理过错
/// 为防止出现循环调用,需要使用状态控制(FCallDefaultProc)
///
if FCallDefaultProc then
FControl.WindowProc(message)
else
begin
FCallDefaultProc := True;
FControl.WindowProc(message);
FCallDefaultProc := False;
end;
end;
procedure TTest.ChangeSize;
var
hTmp: HRGN;
begin
/// 调整窗体样式
FChangeSizeCalled := True;
try
hTmp := FRegion;
try
/// 创建 倒角为3的矩形区域。
/// 在这里可以实现不规则界面的创建,可以通过bmp创建绘制区域
///
/// 注:
/// HRGN 句柄是是图形对象,由window管理的资源,不释放会出现内存泄露,
/// 后果,你懂得。
FRegion := CreateRoundRectRgn(0, 0, FWidth, FHeight, 3, 3);
SetWindowRgn(Handle, FRegion, True);
finally
if hTmp <> 0 then
DeleteObject(hTmp); // 释放资源
end;
finally
FChangeSizeCalled := False;
end;
end;
constructor TTest.Create(AOwner: TWinControl);
begin
FControl := AOwner;
FNeedsUpdate := True;
FRegion := 0;
FChangeSizeCalled := False;
FCallDefaultProc := False;
FWidth := FControl.Width;
FHeight := FControl.Height;
end;
destructor TTest.Destroy;
begin
if FRegion <> 0 then
DeleteObject(FRegion);
inherited;
end;
function TTest.GetForm: TCustomForm;
begin
Result := TCustomForm(Control);
end;
function TTest.GetHandle: HWND;
begin
if FControl.HandleAllocated then
Result := FControl.Handle
else
Result := 0;
end;
procedure TTest.InvalidateNC;
begin
if FControl.HandleAllocated then
SendMessage(Handle, WM_NCPAINT, 1, 0);
end;
procedure TTest.PaintNC(ARGN: HRGN = 0);
var
DC: HDC;
Flags: cardinal;
hb: HBRUSH;
P: TPoint;
r: TRect;
begin
Flags := DCX_CACHE or DCX_CLIPSIBLINGS or DCX_WINDOW or DCX_VALIDATE;
if (ARgn = 1) then
DC := GetDCEx(Handle, 0, Flags)
else
DC := GetDCEx(Handle, ARgn, Flags or DCX_INTERSECTRGN);
if DC <> 0 then
begin
P := Point(0, 0);
Windows.ClientToScreen(Handle, P);
Windows.GetWindowRect(Handle, R);
P.X := P.X - R.Left;
P.Y := P.Y - R.Top;
Windows.GetClientRect(Handle, R);
ExcludeClipRect(DC, P.X, P.Y, R.Right - R.Left + P.X, R.Bottom - R.Top + P.Y);
GetWindowRect(handle, r);
OffsetRect(R, -R.Left, -R.Top);
hb := CreateSolidBrush($00bf7b18);
FillRect(dc, r, hb);
DeleteObject(hb);
SelectClipRgn(DC, 0);
ReleaseDC(Handle, dc);
end;
end;
procedure TTest.WMNCActivate(var Message: TMessage);
begin
//FFormActive := Message.WParam > 0;
Message.Result := 1;
InvalidateNC;
Handled := True;
end;
procedure TTest.WMNCCalcSize(var message: TWMNCCalcSize);
const
SIZE_BORDER = 5;
SIZE_CAPTION = 28;
begin
// 改变边框尺寸
with TWMNCCALCSIZE(Message).CalcSize_Params^.rgrc[0] do
begin
Inc(Left, SIZE_BORDER);
Inc(Top, SIZE_CAPTION);
Dec(Right, SIZE_BORDER);
Dec(Bottom, SIZE_BORDER);
end;
Message.Result := 0;
Handled := True;
end;
procedure TTest.WMWindowPosChanging(var Message: TWMWindowPosChanging);
var
bChanged: Boolean;
begin
/// 由外部优先处理消息,完成以下默认的控制
CallDefaultProc(TMessage(Message));
Handled := True;
bChanged := False;
/// 防止嵌套
if FChangeSizeCalled then
Exit;
/// 调整窗体外框
/// 如果窗体尺寸有调整时需要重新生成窗体外框区域。
///
if (Message.WindowPos^.flags and SWP_NOSIZE = 0) or
(Message.WindowPos^.flags and SWP_NOMOVE = 0) then
begin
if (Message.WindowPos^.flags and SWP_NOMOVE = 0) then
begin
FLeft := Message.WindowPos^.x;
FTop := Message.WindowPos^.y;
end;
if (Message.WindowPos^.flags and SWP_NOSIZE = 0) then
begin
bChanged := ((Message.WindowPos^.cx <> FWidth) or (Message.WindowPos^.cy <> FHeight)) and
(Message.WindowPos^.flags and SWP_NOSIZE = 0);
FWidth := Message.WindowPos^.cx;
FHeight := Message.WindowPos^.cy;
end;
end;
if (Message.WindowPos^.flags and SWP_FRAMECHANGED <> 0) then
bChanged := True;
// 进行调整和重绘处理
if bChanged then
begin
ChangeSize;
InvalidateNC;
end;
end;
procedure TTest.WMNCLButtonDown(var Message: TWMNCHitMessage);
begin
inherited;
if (Message.HitTest = HTCLOSE) or (Message.HitTest = HTMAXBUTTON) or
(Message.HitTest = HTMINBUTTON) or (Message.HitTest = HTHELP) then
begin
//FPressedButton := Message.HitTest;
InvalidateNC;
Message.Result := 0;
Message.Msg := WM_NULL;
Handled := True;
end;
end;
procedure TTest.WMNCPaint(var message: TWMNCPaint);
begin
PaintNC(message.RGN);
Handled := True;
end;
procedure TTest.WMNCUAHDrawCaption(var Message: TMessage);
begin
/// 这个消息会在winxp下产生,是内部Bug处理,直接丢弃此消息
Handled := True;
end;
procedure TTest.WMNCUAHDrawFrame(var Message: TMessage);
begin
/// 这个消息会在winxp下产生,是内部Bug处理,直接丢弃此消息
Handled := True;
end;
procedure TTest.WndProc(var message: TMessage);
begin
FHandled := False;
Dispatch(message);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC ODBC metadata }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
unit FireDAC.Phys.ODBCMeta;
interface
uses
System.Classes,
FireDAC.Stan.Intf,
FireDAC.Phys.Intf, FireDAC.Phys, FireDAC.Phys.Meta, FireDAC.Phys.ODBCBase,
FireDAC.Phys.ODBCCli;
type
TFDPhysODBCMetadata = class(TFDPhysConnectionMetadata)
private type
__TFDPhysConnectionMetadata = class(TFDPhysConnectionMetadata);
private
FNameMaxLength: Integer;
FNameQuoteChar: Char;
FNameQuoteChar1: Char;
FNameQuoteChar2: Char;
FTxNested: Boolean;
FTxSupported: Boolean;
FQuotedCatSchSupported: Boolean;
FQuotedIdentifierCase: SQLUSmallint;
FIdentifierCase: SQLUSmallint;
FCatalogUsage: SQLUInteger;
FSchemaUsage: SQLUInteger;
FCancelSupported: Boolean;
FCatalogSeparator: Char;
FNullLocations: TFDPhysNullLocations;
FIsFileBased: Boolean;
FParentMeta: __TFDPhysConnectionMetadata;
protected
// IUnknown
function QueryInterface(const IID: TGUID; out Obj): HResult; override; stdcall;
// IFDPhysConnectionMetadata
function GetAsyncAbortSupported: Boolean; override;
function GetAsyncNativeTimeout: Boolean; override;
function GetCommandSeparator: String; override;
function GetDefValuesSupported: TFDPhysDefaultValues; override;
function GetIdentityInsertSupported: Boolean; override;
function GetInlineRefresh: Boolean; override;
function GetKind: TFDRDBMSKind; override;
function GetIsFileBased: Boolean; override;
function GetLockNoWait: Boolean; override;
function GetNameCaseSensParts: TFDPhysNameParts; override;
function GetNameDefLowCaseParts: TFDPhysNameParts; override;
function GetNameParts: TFDPhysNameParts; override;
function GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel; ASide: TFDPhysNameQuoteSide): Char; override;
function GetCatalogSeparator: Char; override;
function GetNameQuotedSupportedParts: TFDPhysNameParts; override;
function GetNameQuotedCaseSensParts: TFDPhysNameParts; override;
function GetParamNameMaxLength: Integer; override;
function GetSelectOptions: TFDPhysSelectOptions; override;
function GetTruncateSupported: Boolean; override;
function GetTxAutoCommit: Boolean; override;
function GetTxNested: Boolean; override;
function GetTxSavepoints: Boolean; override;
function GetTxSupported: Boolean; override;
function GetLimitOptions: TFDPhysLimitOptions; override;
function GetNullLocations: TFDPhysNullLocations; override;
function GetColumnOriginProvided: Boolean; override;
function InternalDecodeObjName(const AName: String;
out AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand;
ARaise: Boolean): Boolean; override;
function InternalEncodeObjName(const AParsedName: TFDPhysParsedName;
const ACommand: IFDPhysCommand): String; override;
function InternalGetSQLCommandKind(const ATokens: TStrings): TFDPhysCommandKind; override;
function InternalEscapeDate(const AStr: String): String; override;
function InternalEscapeDateTime(const AStr: String): String; override;
function InternalEscapeTime(const AStr: String): String; override;
function InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String; override;
function TranslateEscapeSequence(var ASeq: TFDPhysEscapeData): String; override;
public
constructor Create(const AConnection: TFDPhysConnection;
AServerVersion, AClientVersion: TFDVersion; AParentMeta: TFDPhysConnectionMetadata);
destructor Destroy; override;
end;
implementation
uses
System.SysUtils,
FireDAC.Stan.Consts, FireDAC.Stan.Util,
FireDAC.Phys.ODBCWrapper;
{------------------------------------------------------------------------------}
{ TFDPhysODBCMetadata }
{------------------------------------------------------------------------------}
constructor TFDPhysODBCMetadata.Create(const AConnection: TFDPhysConnection;
AServerVersion, AClientVersion: TFDVersion; AParentMeta: TFDPhysConnectionMetadata);
var
C: String;
oConn: TODBCConnection;
begin
inherited Create(AConnection, AServerVersion, AClientVersion, False);
FParentMeta := __TFDPhysConnectionMetadata(AParentMeta);
oConn := TODBCConnection(AConnection.CliObj);
FTxSupported := oConn.TXN_CAPABLE <> SQL_TC_NONE;
FTxNested := oConn.MULTIPLE_ACTIVE_TXN = 'Y';
FNameMaxLength := oConn.MAX_COL_NAME_LEN;
C := oConn.IDENTIFIER_QUOTE_CHAR;
FNameQuoteChar := #0;
FNameQuoteChar1 := #0;
FNameQuoteChar2 := #0;
// Sybase ASE returns error on calling SP with name "catalog"."schema"."name".
// But works well with catalog.schema."name". The same for other metadata.
FQuotedCatSchSupported := oConn.DriverKind <> dkSybaseASE;
if Length(C) = 2 then begin
FNameQuoteChar1 := C[1];
FNameQuoteChar2 := C[2];
end
else if Length(C) = 1 then
FNameQuoteChar := C[1];
C := oConn.CATALOG_NAME_SEPARATOR;
if Length(C) = 1 then
FCatalogSeparator := C[1]
else
FCatalogSeparator := #0;
if oConn.DriverKind = dkElevateDB then begin
FQuotedIdentifierCase := SQL_IC_SENSITIVE;
FIdentifierCase := SQL_IC_SENSITIVE;
FCatalogUsage := oConn.CATALOG_USAGE;
FSchemaUsage := 0;
end
else begin
FQuotedIdentifierCase := oConn.QUOTED_IDENTIFIER_CASE;
FIdentifierCase := oConn.IDENTIFIER_CASE;
FCatalogUsage := oConn.CATALOG_USAGE;
FSchemaUsage := oConn.SCHEMA_USAGE;
end;
FCancelSupported := oConn.GetFunctions(SQL_API_SQLCANCEL) = SQL_TRUE;
FKeywords.CommaText := oConn.KEYWORDS;
case oConn.NULL_COLLATION of
SQL_NC_START: FNullLocations := [nlAscFirst, nlDescFirst];
SQL_NC_END: FNullLocations := [nlAscLast, nlDescLast];
SQL_NC_HIGH: FNullLocations := [nlAscLast, nlDescFirst];
SQL_NC_LOW: FNullLocations := [nlAscFirst, nlDescLast];
else FNullLocations := inherited GetNullLocations;
end;
FIsFileBased := oConn.FILE_USAGE = SQL_FILE_TABLE;
ConfigNameParts;
ConfigQuoteChars;
end;
{------------------------------------------------------------------------------}
destructor TFDPhysODBCMetadata.Destroy;
begin
if FParentMeta <> nil then
FDFreeAndNil(FParentMeta);
inherited Destroy;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
Result := inherited QueryInterface(IID, Obj);
if (Result = E_NOINTERFACE) and (FParentMeta <> nil) then
Result := FParentMeta.QueryInterface(IID, Obj)
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetAsyncAbortSupported: Boolean;
begin
Result := FCancelSupported;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetAsyncNativeTimeout: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetAsyncNativeTimeout
else
Result := inherited GetAsyncNativeTimeout;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetCommandSeparator: String;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetCommandSeparator
else
Result := inherited GetCommandSeparator;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetDefValuesSupported: TFDPhysDefaultValues;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetDefValuesSupported
else
Result := inherited GetDefValuesSupported;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetIdentityInsertSupported: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetIdentityInsertSupported
else
Result := inherited GetIdentityInsertSupported;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetInlineRefresh: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetInlineRefresh
else
Result := inherited GetInlineRefresh;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetKind: TFDRDBMSKind;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetKind
else
Result := inherited GetKind;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetIsFileBased: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetIsFileBased
else
Result := FIsFileBased;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetLockNoWait: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetLockNoWait
else
Result := inherited GetLockNoWait;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetNameCaseSensParts: TFDPhysNameParts;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetNameCaseSensParts
else if FIdentifierCase = SQL_IC_SENSITIVE then
Result := [npCatalog, npSchema, npDBLink, npBaseObject, npObject]
else
Result := [];
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetNameDefLowCaseParts: TFDPhysNameParts;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetNameDefLowCaseParts
else if FIdentifierCase = SQL_IC_LOWER then
Result := [npCatalog, npSchema, npDBLink, npBaseObject, npObject]
else
Result := [];
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetNameParts: TFDPhysNameParts;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetNameParts
else begin
Result := inherited GetNameParts;
if FCatalogUsage and SQL_CU_DML_STATEMENTS = SQL_CU_DML_STATEMENTS then
Include(Result, npCatalog);
if FSchemaUsage and SQL_SU_DML_STATEMENTS = SQL_SU_DML_STATEMENTS then
Include(Result, npSchema);
end;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetNameQuoteChar(AQuote: TFDPhysNameQuoteLevel;
ASide: TFDPhysNameQuoteSide): Char;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetNameQuoteChar(AQuote, ASide)
else begin
Result := #0;
if AQuote = ncDefault then
if FNameQuoteChar <> #0 then
Result := FNameQuoteChar
else if ASide = nsLeft then
Result := FNameQuoteChar1
else
Result := FNameQuoteChar2;
end;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetCatalogSeparator: Char;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetCatalogSeparator
else
Result := FCatalogSeparator;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetNameQuotedSupportedParts: TFDPhysNameParts;
begin
Result := inherited GetNameQuotedSupportedParts;
if not FQuotedCatSchSupported then
Result := Result - [npCatalog, npSchema];
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetNameQuotedCaseSensParts: TFDPhysNameParts;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetNameQuotedCaseSensParts
else if FQuotedIdentifierCase = SQL_IC_SENSITIVE then
Result := [npCatalog, npSchema, npDBLink, npBaseObject, npObject]
else
Result := [];
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetParamNameMaxLength: Integer;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetParamNameMaxLength
else
Result := FNameMaxLength;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetSelectOptions: TFDPhysSelectOptions;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetSelectOptions
else
Result := inherited GetSelectOptions;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetTruncateSupported: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetTruncateSupported
else
Result := inherited GetTruncateSupported;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetTxAutoCommit: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetTxAutoCommit
else
Result := inherited GetTxAutoCommit;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetTxNested: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetTxNested
else
Result := FTxNested;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetTxSavepoints: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetTxSavepoints
else
Result := inherited GetTxSavepoints;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetTxSupported: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetTxSupported
else
Result := FTxSupported;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetLimitOptions: TFDPhysLimitOptions;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetLimitOptions
else
Result := inherited GetLimitOptions;
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetNullLocations: TFDPhysNullLocations;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetNullLocations
else
Result := FNullLocations;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.GetColumnOriginProvided: Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetColumnOriginProvided
else
// This is pessimistic, but Informix does not provide origin table name.
// If here will be True, then all Informix result sets will be ReadOnly.
Result := False;
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.InternalDecodeObjName(const AName: String;
out AParsedName: TFDPhysParsedName; const ACommand: IFDPhysCommand;
ARaise: Boolean): Boolean;
begin
if FParentMeta <> nil then
Result := FParentMeta.InternalDecodeObjName(AName, AParsedName, ACommand, ARaise)
else
Result := inherited InternalDecodeObjName(AName, AParsedName, ACommand, ARaise);
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.InternalEncodeObjName(const AParsedName: TFDPhysParsedName;
const ACommand: IFDPhysCommand): String;
begin
if FParentMeta <> nil then
Result := FParentMeta.InternalEncodeObjName(AParsedName, ACommand)
else
Result := inherited InternalEncodeObjName(AParsedName, ACommand);
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.InternalGetSQLCommandKind(const ATokens: TStrings):
TFDPhysCommandKind;
begin
if FParentMeta <> nil then
Result := FParentMeta.GetSQLCommandKind(ATokens)
else
Result := inherited InternalGetSQLCommandKind(ATokens);
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.InternalEscapeDate(const AStr: String): String;
begin
Result := '{D ' + inherited InternalEscapeDate(AStr) + '}';
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.InternalEscapeDateTime(const AStr: String): String;
begin
Result := '{TS ' + inherited InternalEscapeDateTime(AStr) + '}';
end;
{-------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.InternalEscapeTime(const AStr: String): String;
begin
Result := '{T ' + inherited InternalEscapeTime(AStr) + '}';
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.InternalEscapeFunction(const ASeq: TFDPhysEscapeData): String;
begin
if ASeq.FFunc = efCONVERT then
ASeq.FArgs[1] := 'SQL_' + Trim(ASeq.FArgs[1]);
Result := '{FN ' + inherited InternalEscapeFunction(ASeq) + '}';
end;
{------------------------------------------------------------------------------}
function TFDPhysODBCMetadata.TranslateEscapeSequence(var ASeq: TFDPhysEscapeData): String;
begin
if FParentMeta <> nil then
Result := FParentMeta.TranslateEscapeSequence(ASeq)
else
Result := inherited TranslateEscapeSequence(ASeq);
end;
end.
|
unit uFuncoesWindows;
interface
uses Windows, SysUtils, Classes, Variants, Controls, FileCtrl, Forms, ShellAPI, Dialogs,
DB, DBClient, ComObj, uMensagem, ComCtrls, ExtCtrls, uFuncoesString;
type TAbertura = (taShow, taHide);
////////////////////////////////////////////////////////////////////////////////
/// WINDOWS
////////////////////////////////////////////////////////////////////////////////
procedure mostrarBarraDeProgramas;
procedure esconderDaBarraDeProgramas;
procedure mostraOuEscondeFormPrincipal(AAbertura: TAbertura);
function bloquearTecladoEMouse(ABloquear: boolean): boolean;
function GetDiretorioTemp: string;
function GetNomeComputador: string;
// MAC
Function MacAddress: string;
////////////////////////////////////////////////////////////////////////////////
/// ARQUIVO
////////////////////////////////////////////////////////////////////////////////
{Abre o Arquivo}
procedure abrirArquivo(fileName: String);
{Lista Arquivos do diretório passado}
function listarArquivos(ADiretorio: String; AExtensao: string = ''): TStringList;
{Abre Diálogo para selecionar um diretório}
function selecionarDiretorio(diretorioInicial: string = ''): String;
{Abre Diálogo para selecionar um arquivo}
function selecionarArquivo(AFilterText, AFilter, AExtensaoDefault, ATitulo: String; AInitialDir: string = ''; AFileName: string = ''): string;
function salvarArquivo(AFilterText, AFilter, AExtensaoDefault: string; ATitulo: String = 'Salvar Como...'; AFileName: string = ''): string;
function salvarArquivoCalc(ACds: TClientDataSet; ANomePlanilha: string = ''; AFileName: string = ''; AMostraSaveDialog: Boolean = True): string;
function salvarArquivoExcel(ACds: TClientDataSet; ANomePlanilha: string = ''; AFileName: string = ''; AMostraSaveDialog: Boolean = True; AMostraPlanilha: Boolean = True): string;
function cdsParaStringList(ACds: TClientDataSet; ASeparador: string; bIncluiHeader: Boolean = True): TStringList;
function abrirPlanilhaExcel(AXlsFile: String; AAba: Integer = 1): OleVariant; overload;
function abrirPlanilhaExcel(AXlsFile: String; APlanilha: String = ''): OleVariant; overload;
function GetColumnCountPlanilha(APlanilha: OleVariant): Integer;
function GetRowCountPlanilha(APlanilha: OleVariant): Integer;
function GetCellValue(APlanilha: OleVariant; ALinha, AColuna: Integer): Variant;
//////////////////////////////////////////////////////////////////////////////////////////////////
/// ----------------------------------------------------------------------------------------------
/// Gabriel Baltazar - 26/10/2015
/// Ler planilha Excel, em formato de grid, e exporta os dados para CDS
/// ----------------------------------------------------------------------------------------------
/// *********** Parâmetros ****************
/// AExcelFile -> Caminho Completo do arquivo Excel. (Ex.: C:\Arquivos\planilha.xls
/// ALinhaHeader -> Número da Linha onde está o cabeçalho da planilha
/// ANomePlanilha -> Nome da aba da planilha, não passando nada, irá ler da planilha ativa
/// ALinhasRodapé -> Campo para indicar se existe alguma linha após a relação de registros, como
/// Totalizadores, etc... Para não exportar essas linhas no CDS
//////////////////////////////////////////////////////////////////////////////////////////////////
function ExportaExcelToCds(AExcelFile: string; ALinhaHeader: Integer = 1; ANomePlanilha: string = ''; ALinhasRodape: Integer = 0; AProgress: TProgressBar = nil): TClientDataSet;
implementation
Function MacAddress: string;
var
Lib: Cardinal;
Func: function(GUID: PGUID): Longint; stdcall;
GUID1, GUID2: TGUID;
begin
Result := '';
Lib := LoadLibrary('rpcrt4.dll');
if Lib <> 0 then
begin
@Func := GetProcAddress(Lib, 'UuidCreateSequential');
if Assigned(Func) then
begin
if (Func(@GUID1) = 0) and
(Func(@GUID2) = 0) and
(GUID1.D4[2] = GUID2.D4[2]) and
(GUID1.D4[3] = GUID2.D4[3]) and
(GUID1.D4[4] = GUID2.D4[4]) and
(GUID1.D4[5] = GUID2.D4[5]) and
(GUID1.D4[6] = GUID2.D4[6]) and
(GUID1.D4[7] = GUID2.D4[7]) then
begin
Result :=
IntToHex(GUID1.D4[2], 2) + '-' +
IntToHex(GUID1.D4[3], 2) + '-' +
IntToHex(GUID1.D4[4], 2) + '-' +
IntToHex(GUID1.D4[5], 2) + '-' +
IntToHex(GUID1.D4[6], 2) + '-' +
IntToHex(GUID1.D4[7], 2);
end;
end;
end;
end;
procedure mostrarBarraDeProgramas;
begin
ShowWindow(Application.Handle, SW_HIDE);
SetWindowLong(Application.Handle, GWL_EXSTYLE, WS_EX_WINDOWEDGE);
ShowWindow(Application.Handle, SW_SHOW);
end;
procedure esconderDaBarraDeProgramas;
begin
ShowWindow(Application.Handle, SW_HIDE);
SetWindowLong(Application.Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW);
ShowWindow(Application.Handle, SW_SHOW);
end;
procedure mostraOuEscondeFormPrincipal(AAbertura: TAbertura);
var
frmTela: TForm;
i : Integer;
begin
for i:=0 to Application.ComponentCount -1 do
begin
if Application.Components[i] is TForm then
begin
frmTela := Application.Components[i] as TForm ;
if frmTela.Name = 'frmPrincipal' then
if AAbertura = taShow then
begin
frmTela.Show;
mostrarBarraDeProgramas;
end
else
begin
frmTela.Hide;
esconderDaBarraDeProgramas;
end;
end;
end;
end;
procedure abrirArquivo(fileName: String);
begin
ShellExecute(0, 'open', PChar(fileName), nil, nil, SW_SHOW);
end;
/////////////////////////////////////////////////////////
/// Bloquear ou desbloquear ações do Teclado e Mouse
/////////////////////////////////////////////////////////
Function BlockInput(fbLookIt:Boolean):Integer; stdcall; external 'user32.dll';
function bloquearTecladoEMouse(ABloquear: boolean): boolean;
begin
BlockInput(ABloquear);
end;
function GetDiretorioTemp: string;
var
pNetpath: ARRAY[ 0..MAX_path - 1 ] of Char;
nlength: Cardinal;
begin
nlength := MAX_path;
FillChar( pNetpath, SizeOF( pNetpath ), #0 );
GetTemppath( nlength, pNetpath );
Result := StrPas( pNetpath );
end;
function GetNomeComputador: string;
const
tamanhoBuffer = MAX_COMPUTERNAME_LENGTH + 1;
var
lpBuffer: PChar;
nSize : DWORD;
begin
nSize := tamanhoBuffer;
lpBuffer := StrAlloc(tamanhoBuffer);
GetComputerName(lpBuffer, nSize);
Result := string(lpBuffer);
StrDispose(lpBuffer);
end;
function listarArquivos(ADiretorio: String; AExtensao: string): TStringList;
var
arquivos : TStringList;
search : TSearchRec;
ret : Integer;
begin
if AExtensao = '' then
AExtensao := '*';
ret := FindFirst(ADiretorio + '\*.' + AExtensao, faAnyFile, search);
arquivos := TStringList.Create;
try
while ret = 0 do
begin
if (search.Name <> '.') And (search.Name <> '..') then
arquivos.Add(ADiretorio + '\' + search.Name);
Ret := FindNext(search);
end;
result := arquivos;
finally
FindClose(search);
end;
end;
function selecionarDiretorio(diretorioInicial: string = ''): String;
var
pasta: string;
begin
pasta := diretorioInicial;
SelectDirectory('Selecione um Diretório', '', pasta);
if Trim(pasta) <> '' then
if pasta[Length(pasta)] <> '\' then
pasta := pasta + '\';
Result := pasta;
end;
function selecionarArquivo(AFilterText, AFilter, AExtensaoDefault, ATitulo: String; AInitialDir: string = ''; AFileName: string = ''): string;
var
openDialog: TOpenDialog;
begin
openDialog := TOpenDialog.Create(nil);
with openDialog do
begin
Filter := AFilterText + '|' + AFilter;
Title := ATitulo;
DefaultExt := AExtensaoDefault;
FileName := AFileName;
InitialDir := AInitialDir;
end;
if openDialog.Execute then
AFileName := openDialog.FileName
else
AFileName := '';
Result := AFileName;
openDialog.Free;
end;
function salvarArquivo(AFilterText, AFilter, AExtensaoDefault: string; ATitulo: String; AFileName: string): string;
var
saveDialog : TSaveDialog;
begin
saveDialog := TSaveDialog.Create(nil);
with saveDialog do
begin
Filter := AFilterText + '|' + AFilter;
Title := ATitulo;
DefaultExt := AExtensaoDefault;
FileName := AFileName;
end;
if saveDialog.Execute then
AFileName := saveDialog.FileName
else
AFileName := '';
Result := AFileName;
saveDialog.Free;
end;
function salvarArquivoCalc(ACds: TClientDataSet; ANomePlanilha: string = ''; AFileName: string = ''; AMostraSaveDialog: Boolean = True): string;
var
openOffice, connect, calc, sheets, sheet, borda, openDesktop, valorDoCampo : variant;
i, linha, coluna : Integer;
nomeDoCampo : String;
begin
try
openOffice := CreateOleObject('com.sun.star.ServiceManager');
connect := not (VarIsEmpty(OpenOffice) or VarIsNull(OpenOffice));
//Inicia o Calc
openDesktop := openOffice.createInstance('com.sun.star.frame.Desktop');
calc := openDesktop.LoadComponentFromURL('private:factory/scalc', '_blank', 0, VarArrayCreate([0, - 1], varVariant));
sheets := calc.Sheets;
sheet := sheets.getByIndex(0);
//Borda
borda := openOffice.Bridge_GetStruct('com.sun.star.table.BorderLine');
borda.lineDistance := 0;
borda.innerLineWidth := 0;
borda.outerLineWidth := 1;
Sheet.getCellRangeByPosition(0, 0, ACds.FieldCount - 1, 0).Merge(True);
Sheet.getCellByPosition(i, 0).setString(ANomePlanilha);
Sheet.getCellByPosition(i, 0).setPropertyValue('HoriJustify',2);
Sheet.getCellByPosition(i, 0).setPropertyValue('CharWeight',200);
Sheet.getCellByPosition(i, 0).setPropertyValue('CharHeight', 8);
Sheet.getCellByPosition(i, 0).setPropertyValue('CharUnderline', 1);
Sheet.getCellByPosition(i, 0).setPropertyValue('CharFontName', 'verdana');
Sheet.getCellByPosition(i, 0).TopBorder := borda;
Sheet.getCellByPosition(i, 0).RightBorder := borda;
Sheet.getCellByPosition(i, 0).LeftBorder := borda;
Sheet.getCellByPosition(i, 0).BottomBorder := borda;
//////////////////////////////////////////////////////////////////////////
/// Cabeçalho
//////////////////////////////////////////////////////////////////////////
coluna := 0;
for i := 0 to ACds.FieldCount - 1 do
begin
//if grid.Columns[i].Visible then
//begin
//Valor da Célula
Sheet.getCellByPosition(coluna, 1).setString(ACds.Fields[i].DisplayLabel);
//Centraliza
Sheet.getCellByPosition(coluna, 1).setPropertyValue('HoriJustify',2);
//Negrito
Sheet.getCellByPosition(coluna, 1).setPropertyValue('CharWeight',200);
//Tamanho da Fonte
Sheet.getCellByPosition(coluna, 1).setPropertyValue('CharHeight', 8);
//Sublinhado
Sheet.getCellByPosition(coluna, 1).setPropertyValue('CharUnderline', 1);
//Nome da Fonte
Sheet.getCellByPosition(coluna, 1).setPropertyValue('CharFontName', 'verdana');
Sheet.getCellByPosition(coluna, 1).TopBorder := Borda;
Sheet.getCellByPosition(coluna, 1).RightBorder := Borda;
Sheet.getCellByPosition(coluna, 1).LeftBorder := Borda;
Sheet.getCellByPosition(coluna, 1).BottomBorder := Borda;
Inc(coluna, 1);
end;
//end;
//////////////////////////////////////////////////////////////////////////
/// Corpo
//////////////////////////////////////////////////////////////////////////
ACds.First;
linha := 2;
while not ACds.Eof do
begin
coluna := 0;
for i := 0 to ACds.FieldCount - 1 do
begin
//if grid.Columns[i].Visible then
//begin
nomeDoCampo := ACds.Fields[i].DisplayName;
if VarIsNull(ACds.FieldByName(nomeDoCampo).Value) then
valorDoCampo := ''
else
valorDoCampo := ACds.FieldByName(nomeDoCampo).AsString;
//Valor da Célula
Sheet.getCellByPosition(coluna, linha).setString(valorDoCampo);
//Tamanho da Fonte
Sheet.getCellByPosition(coluna, linha).setPropertyValue('CharHeight', 8);
//Nome da Fonte
Sheet.getCellByPosition(coluna, linha).setPropertyValue('CharFontName', 'verdana');
Sheet.getCellByPosition(coluna, linha).TopBorder := Borda;
Sheet.getCellByPosition(coluna, linha).RightBorder := Borda;
Sheet.getCellByPosition(coluna, linha).LeftBorder := Borda;
Sheet.getCellByPosition(coluna, linha).BottomBorder := Borda;
//Ajusta Tamanho das Célula Automaticamente
Sheet.getCellByPosition(coluna, linha).Columns.Optimalwidth := True;
Inc(coluna, 1);
end;
//end;
Inc(linha, 1);
ACds.Next;
end;
// Desconecta o OpenOffice
OpenOffice := Unassigned;
except
//MensagemDeDialogo('Erro ao exportar para Calc.', MB_OK + MB_ICONERROR);
end;
end;
function salvarArquivoExcel(ACds: TClientDataSet; ANomePlanilha: string = ''; AFileName: string = ''; AMostraSaveDialog: Boolean = True; AMostraPlanilha: Boolean = True): String;
var
planilha : variant;
i, coluna, linha : Integer;
nomeDoCampo : String;
sheet : variant;
auxStr : String;
auxInt : Integer;
auxFloat : Double;
begin
try
Result := '';
if AMostraSaveDialog then
AFileName := salvarArquivo('Pasta de Trabalho do Excel (*.xlsx)|*.xlsx|Pasta de Trabalho do Excel 97-2003 (*.xls)|*.xls',
'',
'*.xlsx',
'Salvar Como...',
AFileName);
if AFileName <> '' then
begin
if ANomePlanilha = '' then
ANomePlanilha := 'Planilha';
AFileName := StringReplace(AFileName, '\\', '\', [rfReplaceAll]);
//ACds.DisableControls;
planilha := CreateOleObject('Excel.Application');
planilha.Caption := ANomePlanilha;
planilha.Visible := AMostraPlanilha;
planilha.Workbooks.Add(1);
planilha.Workbooks[1].Sheets.Add;
planilha.Workbooks[1].WorkSheets[1].Name := ANomePlanilha;
Sheet := planilha.Workbooks[1].WorkSheets[ANomePlanilha];
///////////////////////////////////////////////////////////////////////////
/// Preenchendo o Cabeçalho /
///////////////////////////////////////////////////////////////////////////
coluna := 1;
linha := 1;
for i := 0 to ACds.FieldCount - 1 do
begin
Sheet.Cells[linha, coluna] := ACds.Fields[i].DisplayName;
Sheet.Cells[linha, coluna].Font.Bold := True;
Sheet.Cells[linha, coluna].Borders.LineStyle := 0.9;
Inc(coluna, 1);
end;
///////////////////////////////////////////////////////////////////////////
/// Preenchendo o Corpo
///////////////////////////////////////////////////////////////////////////
linha := 2;
ACds.First;
while not ACds.Eof do
begin
coluna := 1;
for i := 0 to ACds.FieldCount - 1 do
begin
nomeDoCampo := ACds.Fields[i].DisplayName;
Sheet.Cells[linha, coluna].Borders.LineStyle := 0.8;
if ACds.FieldByName(nomeDoCampo).DataType in [ftTimeStamp, ftDateTime, ftDate] then
begin
Sheet.Cells[linha, coluna].NumberFormat := 'dd/MM/aaaa';
if ACds.FieldByName(nomeDoCampo).Value > 0 then
Sheet.Cells[linha, coluna] := ACds.FieldByName(nomeDoCampo).asDateTime;
end
else
if ACds.FieldByName(nomeDoCampo).DataType = ftFloat then
begin
Sheet.Cells[linha, coluna].NumberFormat := TFloatField(ACds.FieldByName(nomeDoCampo)).DisplayFormat; // '#.##0,00';
if TFloatField(ACds.FieldByName(nomeDoCampo)).DisplayFormat = '###,##0.00' then
Sheet.Cells[linha, coluna].NumberFormat := '#.##0,00';
Sheet.Cells[linha, coluna] := ACds.FieldByName(nomeDoCampo).Value;
auxFloat := ACds.FieldByName(nomeDoCampo).AsFloat;
auxStr := FloatToStr(auxFloat);
try
if Length(auxStr) >= 12 then
begin
if (Pos(',', auxStr) = 0) and (Pos('.', auxStr) = 0) then
begin
Sheet.Cells[linha, coluna].NumberFormat := '@';
Sheet.Cells[linha, coluna] := auxStr;
end
else
Sheet.Cells[linha, coluna] := ACds.FieldByName(nomeDoCampo).Value;
end
except
end;
// ACds.FieldByName(nomeDoCampo).dis
end
else
if ACds.FieldByName(nomeDoCampo).DataType = ftString then
begin
Sheet.Cells[linha, coluna].NumberFormat := '@';
Sheet.Cells[linha, coluna] := ACds.FieldByName(nomeDoCampo).AsString;
end
else
Sheet.Cells[linha, coluna] := ACds.FieldByName(nomeDoCampo).Value;
Inc(coluna, 1);
end;
Inc(linha, 1);
ACds.Next;
end;
Sheet.Columns.AutoFit;
Sheet.SaveAs(AFileName);
ACds.First;
planilha.quit;
planilha := Null;
planilha := Unassigned;
Result := AFileName;
end;
except
on e : EOleException do
result := e.Message; //MsgDlg('Não foi possível salvar o arquivo.', 'Erro', mtError, [mbOK], 0);
on e : Exception do
Result := e.Message;
end;
end;
function cdsParaStringList(ACds: TClientDataSet; ASeparador: string; bIncluiHeader: Boolean = True): TStringList;
var
linha : string;
valorCampo: string;
i : Integer;
begin
result := TStringList.Create;
//////////////////////////////////////////////////////////////////////////////
/// Cabeçalho
//////////////////////////////////////////////////////////////////////////////
if bIncluiHeader then
begin
for i := 0 to ACds.FieldCount - 1 do
begin
if i = 0 then
linha := ACds.Fields[i].FieldName
else
linha := linha + ASeparador + ACds.Fields[i].FieldName;
end;
result.Add(linha);
end;
//////////////////////////////////////////////////////////////////////////////
/// Registros
//////////////////////////////////////////////////////////////////////////////
ACds.First;
while not ACds.Eof do
begin
for i := 0 to ACds.FieldCount - 1 do
begin
if ACds.Fields[i].DataType in [ftTimeStamp, ftDateTime, ftDate] then
valorCampo := FormatDateTime('dd/MM/yyyy', ACds.Fields[i].AsDateTime)
else
if ACds.Fields[i].DataType = ftFloat then
valorCampo := FormatFloat(',0.00', ACds.Fields[i].AsFloat)
else
valorCampo := ACds.Fields[i].AsString;
if ACds.Fields[i].FieldName = 'CNPJ' then
valorCampo := MascaraCPFCNPJ(valorCampo);
if i = 0 then
linha := valorCampo
else
linha := linha + ASeparador + valorCampo;
end;
result.Add(linha);
ACds.Next;
end;
end;
function abrirPlanilhaExcel(AXlsFile: String; AAba: Integer): OleVariant;
var
planilha : OleVariant;
aba : OleVariant;
begin
planilha := CreateOleObject('Excel.Application');
planilha.Workbooks.Open(AXlsFile);
aba := planilha.Worksheets[aAba];
Result := aba;
end;
function abrirPlanilhaExcel(AXlsFile: String; APlanilha: String = ''): OleVariant;
var
planilha : OleVariant;
aba : OleVariant;
begin
planilha := CreateOleObject('Excel.Application');
planilha.Workbooks.Open(AXlsFile);
aba := planilha.Worksheets[APlanilha];
Result := aba;
end;
function ExportaExcelToCds(AExcelFile: string; ALinhaHeader: Integer = 1; ANomePlanilha: string = ''; ALinhasRodape: Integer = 0; AProgress: TProgressBar = nil): TClientDataSet;
var
i : Integer;
planilha : OleVariant;
cds : TClientDataSet;
numColunas: Integer;
//////////////////////////////////////////////////////////////////////////////
/// Cria Cds com campos da planilha
//////////////////////////////////////////////////////////////////////////////
procedure criarCds;
var
header: string;
begin
cds := TClientDataSet.Create(nil);
header := '';
numColunas := 0;
repeat
numColunas := numColunas + 1;
header := getCellValue(planilha, ALinhaHeader, numColunas);
if header <> '' then
begin
with cds.FieldDefs.AddFieldDef do
begin
Name := header;
DataType := ftString;
end;
end;
until header = '';
cds.CreateDataSet;
numColunas := numColunas - 1;
end;
procedure lerValoresPlanilha;
var
i : Integer;
j : Integer;
totRegistros: Integer;
begin
totRegistros := GetRowCountPlanilha(planilha);
if AProgress <> nil then
AProgress.Max := totRegistros - ALinhasRodape;
for i := ALinhaHeader + 1 to totRegistros - ALinhasRodape do
begin
cds.Insert;
if AProgress <> nil then
AProgress.Position := i;
for j := 1 to numColunas do
cds.Fields[j - 1].Value := VarToStr ( GetcellValue (planilha, i, j) );
cds.Post;
end;
if AProgress <> nil then
AProgress.Position := 0;
end;
begin
if ANomePlanilha = '' then
planilha := abrirPlanilhaExcel(AExcelFile, 1)
else
planilha := abrirPlanilhaExcel(AExcelFile, ANomePlanilha);
criarCds;
lerValoresPlanilha;
result := cds;
end;
function GetColumnCountPlanilha(APlanilha: OleVariant): Integer;
begin
result := APlanilha.Cells.SpecialCells(11).Column;
end;
function GetRowCountPlanilha(APlanilha: OleVariant): Integer;
begin
result := APlanilha.Cells.SpecialCells(11).Row;
end;
function GetCellValue(APlanilha: OleVariant; ALinha, AColuna: Integer): Variant;
begin
result := APlanilha.Cells[ALinha, AColuna];
end;
end.
|
unit Nathan.MapFile.Core;
interface
uses
System.Classes,
System.SysUtils;
{$M+}
type
TMapReturn = record
// Segment: Word;
Offset: Integer;
LineNumberFromAddr: Integer;
ModuleStartFromAddr: Integer;
ModuleNameFromAddr: string;
ProcNameFromAddr: string;
SourceNameFromAddr: string;
LineNumberErrors: Integer;
function ToString(): string;
end;
INathanMapFile = interface
['{09B391E3-9D2F-486D-A349-F1E34BE9071F}']
function GetMapFilename(): string;
procedure SetMapFilename(const Value: string);
function GetCrashAddress(): Integer;
procedure SetCrashAddress(Value: Integer);
function GetMapReturn(): TMapReturn;
procedure Scan();
property MapFilename: string read GetMapFilename write SetMapFilename;
property CrashAddress: Integer read GetCrashAddress write SetCrashAddress;
property MapReturn: TMapReturn read GetMapReturn;
end;
TNathanMapFile = class(TInterfacedObject, INathanMapFile)
strict private
FMapFilename: string;
FCrashAddress: Integer;
FMapReturn: TMapReturn;
private
function GetMapFilename(): string;
procedure SetMapFilename(const Value: string);
function GetCrashAddress(): Integer;
procedure SetCrashAddress(Value: Integer);
function GetMapReturn(): TMapReturn;
procedure CheckStart();
public
constructor Create(const AMapFilename: string; ACrashAddress: Integer); overload;
class function VAFromAddress(const AAddr: Integer): Integer; inline;
procedure Scan();
end;
{$M-}
implementation
uses
System.IOUtils,
JclDebug;
{ **************************************************************************** }
{ TMapReturn }
function TMapReturn.ToString: string;
const
// Format('%p -> %p -> %d', [@iptrValue, iptrValue, iptrValue^]);
// function GetAddressOf(var X): string;
// begin
// Result := IntToHex(Integer(Pointer(@X)), 8);
// end;
// p := System.ReturnAddress;
// Caption := GetAddressOf(P);
ToStringMsg = 'Offset: %d%s'
+ 'Codeline: %d%s'
+ 'Startaddress from Module: $%p%s'
+ 'Name of procedure from address: %s%s'
+ 'Sourcename from address: %s';
begin
Result := string.Format(ToStringMsg,
[Offset,
sLinebreak,
LineNumberFromAddr,
sLinebreak,
Pointer(ModuleStartFromAddr),
sLinebreak,
ProcNameFromAddr,
sLinebreak,
SourceNameFromAddr]);
end;
{ **************************************************************************** }
{ TNathanMapFile }
constructor TNathanMapFile.Create(const AMapFilename: string; ACrashAddress: Integer);
begin
inherited Create();
SetMapFilename(AMapFilename);
SetCrashAddress(ACrashAddress);
end;
function TNathanMapFile.GetCrashAddress: Integer;
begin
Result := FCrashAddress;
end;
function TNathanMapFile.GetMapFilename: string;
begin
Result := FMapFilename;
end;
function TNathanMapFile.GetMapReturn: TMapReturn;
begin
Result := FMapReturn;
end;
procedure TNathanMapFile.SetCrashAddress(Value: Integer);
begin
FCrashAddress := Value;
end;
procedure TNathanMapFile.SetMapFilename(const Value: string);
begin
FMapFilename := Value;
end;
procedure TNathanMapFile.CheckStart();
const
OutMsgAll = 'MapFilename "%s" or CrashAddress "%d" invalid!';
OutMsgFN = 'MapFilename "%s" not found!';
begin
if (FMapFilename.IsEmpty) or (FCrashAddress = 0) then
raise EArgumentException.CreateFmt(OutMsgAll, [FMapFilename, FCrashAddress]);
if (not TFile.Exists(FMapFilename)) then
raise EFileNotFoundException.CreateFmt(OutMsgFN, [FMapFilename]);
end;
class function TNathanMapFile.VAFromAddress(const AAddr: Integer): Integer;
begin
// Result := Pointer(AAddr) - $400000 - $1000;
// In the moment are fix...
Result := AAddr - $400000 - $1000;
end;
procedure TNathanMapFile.Scan();
var
MapScanner: TJclMapScanner;
DummyOffset: Integer;
begin
CheckStart();
MapScanner := TJclMapScanner.Create(FMapFilename);
try
FMapReturn.LineNumberFromAddr := MapScanner.LineNumberFromAddr(FCrashAddress, DummyOffset);
FMapReturn.Offset := DummyOffset;
FMapReturn.ModuleStartFromAddr := MapScanner.ModuleStartFromAddr(FCrashAddress);
FMapReturn.ModuleNameFromAddr := MapScanner.ModuleNameFromAddr(FCrashAddress);
FMapReturn.ProcNameFromAddr := MapScanner.ProcNameFromAddr(FCrashAddress);
FMapReturn.SourceNameFromAddr := MapScanner.SourceNameFromAddr(FCrashAddress);
FMapReturn.LineNumberErrors := MapScanner.LineNumberErrors;
finally
MapScanner.Free;
end;
end;
end.
|
unit WasmSample_Memory;
interface
uses
System.SysUtils
, Wasm
{$ifndef USE_WASMER}
, Wasmtime
{$else}
, Wasmer
{$ifend}
;
function MemorySample() : Boolean;
implementation
procedure check(success : Boolean);
begin
if not success then
begin
writeln('> Error, expected success');
halt(1);
end;
end;
procedure check_call(const func : PWasmFunc; i : Integer; const args : array of TWasmVal; expected : Integer);
begin
var args_ := TWasmValVec.Create(args);
var results := TWasmValVec.Create([nil]);
if (func.Call(@args_, @results).IsError ) or (results.Items[0].i32 <> expected) then
begin
writeln('> Error on result');
halt(1);
end;
end;
procedure check_call0(const func : PWasmFunc; expected : Integer);
begin
check_call(func, 0, [], expected);
end;
procedure check_call1(const func : PWasmFunc; arg : Integer; expected : Integer);
begin
var args := [ WASM_I32_VAL(arg) ];
check_call(func, 1, args, expected);
end;
procedure check_call2(const func : PWasmFunc; arg1 : Integer; arg2 : Integer; expected : Integer);
begin
var args := [ WASM_I32_VAL(arg1), WASM_I32_VAL(arg2) ];
check_call(func, 2, args, expected);
end;
procedure check_ok(const func : PWasmFunc; i : Integer; const args : array of TWasmVal);
begin
var args_ := TWasmValVec.Create(args);
var results := Default(TWasmValVec);
var trap := func.Call(@args_, @results);
if trap.IsError then
begin
var s := (+trap).GetMessage();
writeln('> Error on result, expected empty '+s);
halt(1);
end;
end;
procedure check_ok2(const func : PWasmFunc; arg1 : Integer; arg2 : Integer);
begin
var args := [ WASM_I32_VAL(arg1), WASM_I32_VAL(arg2) ];
check_ok(func, 2, args);
end;
procedure check_trap(const func : PWasmFunc; i : Integer; const args : array of TWasmVal; const ret : array of TWasmVal);
begin
var args_ := TWasmValVec.Create(args);
var results := TWasmValVec.Create(ret);
var trap := func.Call(@args_, @results);
if trap.IsError then
begin
var s := (+trap).GetMessage();
writeln('> Error on result, expected trap '+s);
halt(1);
end;
end;
procedure check_trap1(const func : PWasmFunc; arg : Integer);
begin
var args := [ WASM_I32_VAL(arg) ];
check_trap(func, 1, args, [nil]);
end;
procedure check_trap2(const func : PWasmFunc; arg1 : Integer; arg2 : Integer);
begin
var args := [ WASM_I32_VAL(arg1), WASM_I32_VAL(arg2) ];
check_trap(func, 2, args, []);
end;
function MemorySample() : Boolean;
begin
// Initialize.
writeln('Initializing...');
var engine := TWasmEngine.New();
var store := TWasmStore.New(+engine);
// Load binary.
writeln('Loading binary...');
var binary := TWasmByteVec.NewEmpty;
{$ifdef USE_WASMFILE}
if not (+binary).LoadFromFile('memory.wasm') then
begin
writeln('> Error loading module!');
exit(false);
end;
{$else}
var wat :=
'(module'+
' (memory (export "memory") 2 3)'+
''+
' (func (export "size") (result i32) (memory.size))'+
' (func (export "load") (param i32) (result i32) (i32.load8_s (local.get 0)))'+
' (func (export "store") (param i32 i32)'+
' (i32.store8 (local.get 0) (local.get 1))'+
' )'+
''+
' (data (i32.const 0x1000) "\01\02\03\04")'+
')';
(+binary).Wat2Wasm(wat);
{$ifend}
// Compile.
writeln('Compiling module...');
var module := TWasmModule.New(+store, +binary);
if module.IsNone then
begin
writeln('> Error compiling module!');
exit(false);
end;
// Instantiate.
Writeln('Instantiating module...');
var instance := TWasmInstance.New(+store, +module, []);
if instance.IsNone then
begin
writeln('> Error instantiating module!');
exit(false);
end;
// Extract export.
writeln('Extracting export...');
var export_s := (+instance).GetExports;
var memory := export_s.Unwrap.Items[0].AsMemory;
var size_func := export_s.Unwrap.Items[1].AsFunc;
var load_func := export_s.Unwrap.Items[2].AsFunc;
var store_func := export_s.Unwrap.Items[3].AsFunc;
// Try cloning.
var copy := memory.Copy();
// assert(TWasm.memory_same(memory, copy)); // wasmtime unimplemented wasm_memory_same
// Check initial memory.
writeln('Checking memory...');
check(memory.Size = 2);
check(memory.DataSize = $20000);
check(memory.Data[0] = 0);
check(memory.Data[$1000] = 1);
check(memory.Data[$1003] = 4);
check_call0(size_func, 2);
check_call1(load_func, 0, 0);
check_call1(load_func, $1000, 1);
check_call1(load_func, $1003, 4);
check_call1(load_func, $1ffff, 0);
// check_trap1(load_func, $20000); // ??? trapが起きずに例外発生
// Mutate memory.
writeln('Mutating memory...');
memory.Data[$1003] := 5;
check_ok2(store_func, $1002, 6);
// check_trap2(store_func, $20000, 0); // ??? trapが起きずに例外発生
check(memory.Data[$1002] = 6);
check(memory.Data[$1003] = 5);
check_call1(load_func, $1002, 6);
check_call1(load_func, $1003, 5);
// Grow memory.
writeln('Growing memory...');
check(memory.Grow(1));
check(memory.Size = 3);
check(memory.DataSize = $30000);
check_call1(load_func, $20000, 0);
check_ok2(store_func, $20000, 0);
// check_trap1(load_func, $30000); // ??? trapが起きずに例外発生
// check_trap2(store_func, $30000, 0); // ??? trapが起きずに例外発生
check(not memory.Grow(1));
check(memory.Grow(0));
// Create stand-alone memory.
// TODO(wasm+): Once Wasm allows multiple memories, turn this into import.
writeln('Creating stand-alone memory...');
var lim := TWasmLimits.Create(5, 5);
var memory2 := TWasmMemory.New(+store, +TWasmMemoryType.New(@lim));
check(memory2.Unwrap.Size = 5);
check(not memory2.Unwrap.Grow(1));
check(memory2.Unwrap.Grow(0));
// Shut down.
writeln('Shutting down...');
// All done.
writeln('Done.');
result := true;
end;
end.
|
UNIT Ghost;
{$MODE Delphi}
INTERFACE
USES LCLIntf, LCLType, LMessages, Graphics, Classes, Map, MapObject, LinkedList, Animation,
Astar;
CONST NUM_COLORS = 4;
CONST DEFAULT_SPEED = 2;
TYPE AIMode = (AI_SLEEP, AI_CHASE, AI_IDLE, AI_FLEE);
VAR gfx : ARRAY [0.. NUM_COLORS * 5 * 4 - 1] OF TBitmap;
TYPE TGhost = CLASS(TMobileObject)
PUBLIC
CONSTRUCTOR create(_x, _y, _direction, _color : INTEGER);
CLASS PROCEDURE loadGfx();
PROCEDURE spawn();
PROCEDURE setAIMode(m : AIMode);
FUNCTION getColor() : INTEGER;
FUNCTION blocksMovement(tile : TTile) : BOOLEAN; OVERRIDE;
FUNCTION getType() : TMapObjectType; OVERRIDE;
PROCEDURE onCollide(other : TMapObject; objects : TLinkedList); OVERRIDE;
PROCEDURE move(map : TMap; objects : TLinkedList); OVERRIDE;
PROCEDURE draw(canvas : TCanvas); OVERRIDE;
PRIVATE
startx, starty : INTEGER;
animations : ARRAY [0..4] OF TAnimation;
currentAnimation : TAnimation;
color : INTEGER;
path : TLinkedList;
mode : AIMode;
END;
IMPLEMENTATION
CONSTRUCTOR TGhost.create(_x, _y, _direction, _color : INTEGER);
VAR i : INTEGER;
BEGIN
INHERITED create(_x, _y, TILE_SIZE, TILE_SIZE, DEFAULT_SPEED, 0);
startx := getLeft();
starty := getTop();
path := TLinkedList.create();
color := _color;
FOR i := 0 TO LENGTH(animations)-1 DO
animations[i] := TAnimation.create(i*4, 4, 3, TRUE);
spawn();
END;
PROCEDURE TGhost.spawn();
BEGIN
x := startx;
y := starty;
setAiMode(AI_SLEEP);
path.destroy();
path := TlinkedList.create();
direction := 0;
currentAnimation := animations[direction].start();
speed := DEFAULT_SPEED;
END;
PROCEDURE TGhost.setAIMode(m : AIMode);
BEGIN
mode := m;
END;
FUNCTION TGhost.getColor() : INTEGER;
BEGIN
getColor := color;
END;
CLASS PROCEDURE TGhost.loadGfx();
VAR sheet : TBitmap;
VAR i : INTEGER;
BEGIN
sheet := TBitmap.create();
sheet.loadFromFile('gfx/ghost_spritesheet.bmp');
loadSpriteSheet(sheet, 0, 0, sheet.width, sheet.height, 4, NUM_COLORS * 5, gfx);
FOR i := 0 TO LENGTH(gfx)-1 DO
gfx[i].transparent := TRUE;
sheet.Destroy();
END;
FUNCTION TGhost.blocksMovement(tile : TTile) : BOOLEAN;
BEGIN
blocksMovement := tile = 1;
END;
FUNCTION TGhost.getType() : TMapObjectType;
BEGIN
getType := OBJECT_GHOST;
END;
PROCEDURE TGhost.onCollide (other : TMapObject; objects : TLinkedList);
BEGIN
END;
PROCEDURE TGhost.move (map : TMap; objects : TLinkedList);
VAR ptr : TLinkedNode;
VAR pac : TMapObject;
VAR forbiddenNodes : TLinkedList;
VAR nextTile, firstTile : TPathNode;
VAR i : INTEGER;
BEGIN
IF currentAnimation <> animations[direction] THEN
currentAnimation := animations[direction].resume(currentAnimation);
currentAnimation.advance();
ptr := NIL;
pac := NIL;
WHILE objects.iterate(ptr) DO
IF TMapObject(ptr.getObject()).getType() = OBJECT_PACMAN THEN
BREAK;
IF ptr <> NIL THEN
pac := TMapObject(ptr.getObject());
forbiddenNodes := TLinkedList.create();
ptr := NIL;
WHILE objects.iterate(ptr) DO
BEGIN
IF TMapObject(ptr.getObject()).getType() = OBJECT_GHOST THEN
BEGIN
IF TGhost(ptr.getObject()).mode = AI_CHASE THEN
forbiddenNodes.insertBack(TPathNode.create(
TMapObject(ptr.getObject()).getLeft() DIV TILE_SIZE,
TMapObject(ptr.getObject()).getTop() DIV TILE_SIZE)
);
END;
END;
FOR i := 1 TO speed DO
BEGIN
nextTile := NIL;
IF mode = AI_CHASE THEN
BEGIN
IF path.isEmpty() OR ((heuristic(TPathNode(path.getLast().getObject()).x, TPathNode(path.getLast().getObject()).y,
pac.getCenterX() DIV TILE_SIZE, pac.getCenterY() DIV TILE_SIZE) > 0)) THEN
BEGIN
path.destroy();
path := TLinkedList.create();
findPath(getLeft() DIV TILE_SIZE, getTop() DIV TILE_SIZE,
pac.getLeft() DIV TILE_SIZE, pac.getTop() DIV TILE_SIZE,
map, self, forbiddenNodes, path);
IF NOT path.isEmpty() THEN
BEGIN
firstTile := TPathNode(path.release(path.getFirst()));
IF NOT path.isEmpty() THEN
BEGIN
IF (TPathNode(path.getFirst().getObject()).x*TILE_SIZE <> getLeft()) AND
(TPathNode(path.getFirst().getObject()).y*TILE_SIZE <> getTop()) THEN
path.insertFront(firstTile)
ELSE
firstTile.Destroy();
END;
END;
END;
WHILE (nextTile = NIL) AND (NOT path.isEmpty()) DO
BEGIN
nextTile := TPathNode(path.getFirst().getObject());
IF (nextTile.x*TILE_SIZE = getLeft()) AND (nextTile.y*TILE_SIZE = getTop()) THEN
BEGIN
path.release(path.getFirst()).destroy();
nextTile := NIL;
END;
END;
END;
IF nextTile <> NIL THEN
BEGIN
IF nextTile.x*TILE_SIZE > getLeft() THEN
setDirection(2);
IF nextTile.x*TILE_SIZE < getLeft() THEN
setDirection(4);
IF nextTile.y*TILE_SIZE > getTop() THEN
setDirection(3);
IF nextTile.y*TILE_SIZE < getTop() THEN
setDirection(1);
END
ELSE
setDirection(0);
IF currentAnimation <> animations[direction] THEN
currentAnimation := animations[direction].resume(currentAnimation);
INHERITED move(map, objects);
END;
forbiddenNodes.destroy();
END;
PROCEDURE TGhost.draw(canvas : TCanvas);
VAR spriteid : INTEGER;
BEGIN
spriteid := color*4*5 + currentAnimation.getSpriteId();
canvas.draw(getCenterX() - gfx[spriteid].width DIV 2,
getCenterY() - gfx[spriteid].Height DIV 2, gfx[spriteid]);
END;
END.
|
{ 25/05/2007 10:49:50 (GMT+1:00) > [Akadamia] checked in }
{ 25/05/2007 10:48:58 (GMT+1:00) > [Akadamia] checked out /}
{ 14/02/2007 08:34:19 (GMT+0:00) > [Akadamia] checked in }
{-----------------------------------------------------------------------------
Unit Name: TDU
Author: ken.adam
Date: 11-Jan-2007
Purpose: Translation of Tagged Data example to Delphi
After a flight has loaded, request the vertical speed and pitot
heat switch setting of the user aircraft, but only when the data
has changed.
* adds Latitude and Longitude to requested data
* supports both polled and message driven data transfers.
History:
-----------------------------------------------------------------------------}
unit TDU;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ImgList, ToolWin, ActnMan, ActnCtrls, XPStyleActnCtrls,
ActnList, ComCtrls, SimConnect, StdActns;
const
// maxReturnedItems is 4 in this case, as the sample only requests
// vertical speed, pitot heat switch data, latitude and longitude
MaxReturnedItems = 4;
// Define a user message for message driven version of the example
WM_USER_SIMCONNECT = WM_USER + 2;
type
// A basic structure for a single item of returned data
TOneDatum = record
Id: integer;
Value: single;
end;
// A structure that can be used to receive Tagged data
TDatum = record
Datum: array[0..MaxReturnedItems - 1] of TOneDatum;
end;
PDatum = ^TDatum;
// Use enumerated types to create unique IDs as required
TEventPdr = (EventSimStart);
TDataDefineId = (DefinitionPdr);
TDataRequestId = (RequestPdr);
TDataNames = (DATA_VERTICAL_SPEED, DATA_PITOT_HEAT, DATA_LATITUDE,
DATA_LONGITUDE);
// The form
TTaggedDataForm = class(TForm)
StatusBar: TStatusBar;
ActionManager: TActionManager;
ActionToolBar: TActionToolBar;
Images: TImageList;
Memo: TMemo;
StartPoll: TAction;
FileExit: TFileExit;
StartEvent: TAction;
procedure StartPollExecute(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure SimConnectMessage(var Message: TMessage); message WM_USER_SIMCONNECT;
procedure StartEventExecute(Sender: TObject);
private
{ Private declarations }
RxCount : integer; // Count of Rx messages
Quit : boolean; // True when signalled to quit
hSimConnect : THandle; // Handle for the SimConection
public
{ Public declarations }
procedure DispatchHandler(pData: PSimConnectRecv; cbData: DWORD; pContext: Pointer);
end;
var
TaggedDataForm : TTaggedDataForm;
implementation
resourcestring
StrRx6d = 'Rx: %6d';
{$R *.dfm}
{-----------------------------------------------------------------------------
Procedure: MyDispatchProc
Wraps the call to the form method in a simple StdCall procedure
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure MyDispatchProc(pData: PSimConnectRecv; cbData: DWORD; pContext:
Pointer); stdcall;
begin
TaggedDataForm.DispatchHandler(pData, cbData, pContext);
end;
{-----------------------------------------------------------------------------
Procedure: DispatchHandler
Handle the Dispatched callbacks in a method of the form. Note that this is
used by both methods of handling the interface.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
pData: PSimConnectRecv
cbData: DWORD
pContext: Pointer
-----------------------------------------------------------------------------}
procedure TTaggedDataForm.DispatchHandler(pData: PSimConnectRecv; cbData: DWORD;
pContext: Pointer);
var
hr : HRESULT;
Evt : PSimconnectRecvEvent;
pObjData : PSimConnectRecvSimObjectData;
Count : DWORD;
pS : PDatum;
OpenData : PSimConnectRecvOpen;
begin
// Maintain a display of the message count
Inc(RxCount);
StatusBar.Panels[1].Text := Format(StrRx6d,[RxCount]);
// Only keep the last 200 lines in the Memo
while Memo.Lines.Count > 200 do
Memo.Lines.Delete(0);
// Handle the various types of message
case TSimConnectRecvId(pData^.dwID) of
SIMCONNECT_RECV_ID_OPEN:
begin
StatusBar.Panels[0].Text := 'Opened';
OpenData := PSimConnectRecvOpen(pData);
with OpenData^ do
begin
Memo.Lines.Add('');
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', [szApplicationName,
dwApplicationVersionMajor, dwApplicationVersionMinor,
dwApplicationBuildMajor,dwApplicationBuildMinor]));
Memo.Lines.Add(Format('%s %1d.%1d.%1d.%1d', ['SimConnect',
dwSimConnectVersionMajor, dwSimConnectVersionMinor,
dwSimConnectBuildMajor, dwSimConnectBuildMinor]));
Memo.Lines.Add('');
end;
end;
SIMCONNECT_RECV_ID_EVENT:
begin
evt := PSimconnectRecvEvent(pData);
case TEventPdr(evt^.uEventID) of
EventSimStart:
begin
// Make the call for data every second, but only when it changes and
// only that data that has changed
hr := SimConnect_RequestDataOnSimObject(hSimConnect,
Ord(RequestPdr), Ord(DefinitionPdr),
SIMCONNECT_OBJECT_ID_USER, SIMCONNECT_PERIOD_SECOND,
SIMCONNECT_DATA_REQUEST_FLAG_CHANGED or
SIMCONNECT_DATA_REQUEST_FLAG_TAGGED);
end;
end;
end;
SIMCONNECT_RECV_ID_SIMOBJECT_DATA:
begin
pObjData := PSimConnectRecvSimObjectData(pData);
case TDataRequestId(pObjData^.dwRequestID) of
RequestPdr:
begin
Count := 0;
// Note that this maps the structure so that it overlays the memory
// starting at the location where pObjData^.dwData is stored
pS := PDatum(@pObjData^.dwData);
// There can be a minimum of 1 and a maximum of maxReturnedItems
// in the StructDatum structure. The actual number returned will
// be held in the dwDefineCount parameter.
while Count < pObjData^.dwDefineCount do
begin
case TDataNames(pS.Datum[Count].Id) of
DATA_VERTICAL_SPEED:
Memo.Lines.Add(Format('Vertical speed = %8.5f',
[pS^.datum[count].value]));
DATA_PITOT_HEAT:
Memo.Lines.Add(Format('Pitot heat = %8.5f',
[pS^.datum[count].value]));
DATA_LATITUDE:
Memo.Lines.Add(Format('Latitude = %8.5f',
[pS^.datum[count].value]));
DATA_LONGITUDE:
Memo.Lines.Add(Format('Longitude = %8.5f',
[pS^.datum[count].value]));
else
Memo.Lines.Add(Format('Unknown datum ID: %d',
[pS^.datum[count].id]));
end;
Inc(Count);
end;
end;
end;
end;
SIMCONNECT_RECV_ID_QUIT:
begin
Quit := True;
StatusBar.Panels[0].Text := 'FS X Quit';
end
else
Memo.Lines.Add(Format('Unknown dwID: %d', [pData.dwID]));
end;
end;
{-----------------------------------------------------------------------------
Procedure: FormCloseQuery
Ensure that we can signal "Quit" to the busy wait loop
Author: ken.adam
Date: 11-Jan-2007
Arguments: Sender: TObject var CanClose: Boolean
Result: None
-----------------------------------------------------------------------------}
procedure TTaggedDataForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
Quit := True;
CanClose := True;
end;
{-----------------------------------------------------------------------------
Procedure: FormCreate
We are using run-time dynamic loading of SimConnect.dll, so that the program
will execute and fail gracefully if the DLL does not exist.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
Result: None
-----------------------------------------------------------------------------}
procedure TTaggedDataForm.FormCreate(Sender: TObject);
begin
if InitSimConnect then
StatusBar.Panels[2].Text := 'SimConnect.dll Loaded'
else
begin
StatusBar.Panels[2].Text := 'SimConnect.dll NOT FOUND';
StartPoll.Enabled := False;
StartEvent.Enabled := False;
end;
Quit := False;
hSimConnect := 0;
StatusBar.Panels[0].Text := 'Not Connected';
RxCount := 0;
StatusBar.Panels[1].Text := Format(StrRx6d,[RxCount]);
end;
{-----------------------------------------------------------------------------
Procedure: SimConnectMessage
This uses CallDispatch, but could probably avoid the callback and use
SimConnect_GetNextDispatch instead.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
var Message: TMessage
-----------------------------------------------------------------------------}
procedure TTaggedDataForm.SimConnectMessage(var Message: TMessage);
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
end;
{-----------------------------------------------------------------------------
Procedure: StartEventExecute
Opens the connection for Event driven handling. If successful sets up the data
requests and hooks the system event "SimStart".
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TTaggedDataForm.StartEventExecute(Sender: TObject);
var
hr : HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Tagged Data', Handle, WM_USER_SIMCONNECT, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Set up the data definition, ensuring that all the elements are in Float32 units, to
// match the TDatum structure
// The number of entries in the DEFINITION_PDR definition should be equal to
// the maxReturnedItems define
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionPdr),
'Vertical Speed', 'Feet per second',
SIMCONNECT_DATATYPE_FLOAT32, 0, Ord(DATA_VERTICAL_SPEED));
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionPdr),
'Pitot Heat', 'Bool',
SIMCONNECT_DATATYPE_FLOAT32, 0, Ord(DATA_PITOT_HEAT));
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionPdr),
'Plane Latitude', 'degrees', SIMCONNECT_DATATYPE_FLOAT32, 0,
Ord(DATA_LATITUDE));
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionPdr),
'Plane Longitude', 'degrees', SIMCONNECT_DATATYPE_FLOAT32, 0,
Ord(DATA_LONGITUDE));
// Request a simulation start event
hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart),
'SimStart');
StartEvent.Enabled := False;
StartPoll.Enabled := False;
end;
end;
{-----------------------------------------------------------------------------
Procedure: StartPollExecute
Opens the connection for Polled access. If successful sets up the data
requests and hooks the system event "SimStart", and then loops indefinitely
on CallDispatch.
Author: ken.adam
Date: 11-Jan-2007
Arguments:
Sender: TObject
-----------------------------------------------------------------------------}
procedure TTaggedDataForm.StartPollExecute(Sender: TObject);
var
hr : HRESULT;
begin
if (SUCCEEDED(SimConnect_Open(hSimConnect, 'Tagged Data', 0, 0, 0, 0))) then
begin
StatusBar.Panels[0].Text := 'Connected';
// Set up the data definition, ensuring that all the elements are in Float32 units, to
// match the TDatum structure
// The number of entries in the DEFINITION_PDR definition should be equal to
// the maxReturnedItems define
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionPdr),
'Vertical Speed', 'Feet per second',
SIMCONNECT_DATATYPE_FLOAT32, 0, Ord(DATA_VERTICAL_SPEED));
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionPdr),
'Pitot Heat', 'Bool',
SIMCONNECT_DATATYPE_FLOAT32, 0, Ord(DATA_PITOT_HEAT));
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionPdr),
'Plane Latitude', 'degrees', SIMCONNECT_DATATYPE_FLOAT32, 0,
Ord(DATA_LATITUDE));
hr := SimConnect_AddToDataDefinition(hSimConnect, Ord(DefinitionPdr),
'Plane Longitude', 'degrees', SIMCONNECT_DATATYPE_FLOAT32, 0,
Ord(DATA_LONGITUDE));
// Request a simulation start event
hr := SimConnect_SubscribeToSystemEvent(hSimConnect, Ord(EventSimStart),
'SimStart');
StartEvent.Enabled := False;
StartPoll.Enabled := False;
while not Quit do
begin
SimConnect_CallDispatch(hSimConnect, MyDispatchProc, nil);
Application.ProcessMessages;
Sleep(1);
end;
hr := SimConnect_Close(hSimConnect);
end;
end;
end.
|
unit UndoRedo;
//
// This unit implements a simple Undo/Redo mechanism for interactive systems.
// It is inspired by the treatment of a similar example in Chapter 21 of
// Bertrand Meyer's "Object-Oriented Software Construction" (2nd edition).
//
// The mechanism can be simply described by means of the following transition
// system of ( U, s, R ) triples, in which s is the state of the system ,
// U is the list of undoable commands and R is the list of redoable commands.
//
// Create
// |- ( <> , s0 , <> )
//
//
// Do(c)
// ( U , s , R ) |- ( U ++ <c> , c(s) , <> ) if reversible(c)
// |- ( <> , c(s) , <> ) if ~reversible(c)
//
// Undo
// ( U ++ <c> , s , R ) |- ( U , cRev(s) , <c> ++ R ) // cRev reverts c
//
// Redo
// ( U , s , <c> ++ R ) |- ( U ++ <c> , c(s) , R )
//
// Destroy
// ( U , s , R ) |-
//
interface
uses
Contnrs, Dialogs, SysUtils;
type
// Abstract command class
TCommand =
class(TObject)
procedure Execute; virtual; abstract;
procedure Reverse; virtual; abstract;
function Reversible: Boolean; virtual; abstract;
end;
// The controller maintains the undo list FU and redo list FR
TController =
class(TObject)
protected
FU: TObjectStack;
FR: TObjectStack;
procedure ClearStack(AStack: TObjectStack);
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure DoCommand(ACommand: TCommand);
procedure Undo;
procedure Redo;
function CanUndo: Boolean;
function CanRedo: Boolean;
end;
implementation //===============================================================
{ TController }
constructor TController.Create;
begin
inherited Create;
FU := TObjectStack.Create;
FR := TObjectStack.Create;
end;
destructor TController.Destroy;
begin
ClearStack(FU);
ClearStack(FR);
FU.Free;
FR.Free;
inherited Destroy;
end;
procedure TController.DoCommand(ACommand: TCommand);
begin
ACommand.Execute;
if ACommand.Reversible
then FU.Push(ACommand) // extend FU
else
begin
ClearStack(FU); // clear FU
ACommand.Free;
end;
ClearStack(FR); // clear FR
end;
procedure TController.Undo;
var
VCommand: TCommand;
begin
// ShowMessage( Format('TController.Undo: Undo Stack Count %u ', [FU.Count]) );
VCommand := FU.Pop as TCommand;
// ShowMessage( Format('TController.Undo: Undo Stack Count (Popped) %u ', [FU.Count]) );
VCommand.Reverse;
// ShowMessage( 'Succesfull reverse' );
FR.Push(VCommand);
// ShowMessage( Format('TController.Undo: Redo Stack Count %u ', [FU.Count]) );
end;
procedure TController.Redo;
var
VCommand: TCommand;
begin
VCommand := FR.Pop as TCommand;
VCommand.Execute;
FU.Push(VCommand);
end;
function TController.CanUndo: Boolean;
begin
Result := FU.Count > 0;
end;
function TController.CanRedo: Boolean;
begin
Result := FR.Count > 0;
end;
procedure TController.Clear;
begin
ClearStack(FU);
ClearStack(FR);
end;
procedure TController.ClearStack(AStack: TObjectStack);
begin
while AStack.Count > 0
do AStack.Pop.Free;
end;
end.
|
{------------------------------------------------------------------------------}
{
Lee Beadle
CS 410W
Pascal Paint Cost Program
MODIFIED Assignment #5
}
{------------------------------------------------------------------------------}
{Program info, libraries, and variables}
PROGRAM Paint_Cost;
USES Math;
CONST
HEIGHT = 8;
ONE_GALLON = 350;
VAR
room_type : STRING;
length : REAL;
width : REAL;
can_cost : REAL;
surface_area : REAL;
num_of_gallons : REAL;
num_of_cans : INTEGER;
room_cost : REAL;
answer : CHAR;
is_one_room : BOOLEAN;
previous_room : REAL;
running_total : REAL;
most_exp_cost : REAL;
most_exp_room : STRING;
total_cost : REAL;
{------------------------------------------------------------------------------}
{Read User Input Procedure}
PROCEDURE read_input(var room: STRING; var length: REAL; var width: REAL;
var cost : REAL);
BEGIN
Write('Enter the room type: ');
Readln(room);
Write('Enter the room length: ');
Readln(length);
Write('Enter the room width: ');
Readln(width);
Write('Enter the cost of one can of paint: $');
Readln(cost);
END;
{------------------------------------------------------------------------------}
{Calculate Surface Area Function}
FUNCTION calc_surface_area(length: REAL; width: REAL; height: REAL) : REAL;
BEGIN
calc_surface_area := (length*width) + 2*(length*height) + 2*(width*height);
END;
{------------------------------------------------------------------------------}
{Calculate Number of Gallons Function}
FUNCTION calc_num_gallons(surface_area: REAL; a_gallon: integer): REAL;
BEGIN
calc_num_gallons := surface_area / a_gallon;
END;
{------------------------------------------------------------------------------}
{Calculate Numeber of Cans Function}
FUNCTION calc_num_cans(num_of_gallons: REAL): INTEGER;
BEGIN
calc_num_cans := Ceil(num_of_gallons);
END;
{------------------------------------------------------------------------------}
{Calculate Total Cost Function}
FUNCTION calc_room_cost(num_of_cans: INTEGER; can_cost: REAL): REAL;
BEGIN
calc_room_cost := num_of_cans * can_cost;
END;
{------------------------------------------------------------------------------}
{Outputs One Room Results Procedure}
PROCEDURE display_one_results;
BEGIN
Writeln('Room type: ', room_type);
Writeln('Surface area (minus floor): ', surface_area:0:1, ' sq ft');
Writeln('Number of gallons: ', num_of_gallons:0:3);
Writeln('Number of cans: ', num_of_cans:0);
Writeln('Room Cost: $', room_cost:0:2);
END;
{------------------------------------------------------------------------------}
{Output Muliple Rooms Results Procedure}
PROCEDURE display_mulitple_results;
BEGIN
Writeln('Most Expensive Room: ', most_exp_room);
Writeln('Expensive Room Cost: $', most_exp_cost:0:2);
Writeln('Total Paint Cost: $', total_cost:0:2);
END;
{------------------------------------------------------------------------------}
PROCEDURE calc_one_room;
BEGIN
surface_area := calc_surface_area(length, width, HEIGHT);
num_of_gallons:= calc_num_gallons(surface_area, ONE_GALLON);
num_of_cans := calc_num_cans(num_of_gallons);
room_cost := calc_room_cost(num_of_cans, can_cost);
END;
{------------------------------------------------------------------------------}
{Main Driver}
BEGIN
previous_room := 0;
running_total := 0;
most_exp_cost := 0;
total_cost := 0;
read_input(room_type, length, width, can_cost);
calc_one_room;
previous_room := room_cost;
Write('Would you like to enter more rooms (y/n): ');
Readln(answer);
IF (answer = 'n') THEN
is_one_room := true
ELSE
REPEAT
is_one_room := false;
calc_one_room;
if (room_cost >= previous_room) THEN
most_exp_room := room_type;
most_exp_cost := room_cost;
read_input(room_type, length, width, can_cost);
calc_one_room;
Write('Would you like to enter more rooms (y/n): ');
Readln(answer);
running_total := room_cost + previous_room;
previous_room := room_cost;
UNTIL (answer = 'n');
total_cost := total_cost + running_total;
If(is_one_room = true) THEN
display_one_results;
IF(is_one_room = false) THEN
display_mulitple_results;
END.
{------------------------------------------------------------------------------} |
unit Unit1;
interface
uses
System.SysUtils, System.Classes, System.Math,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.StdCtrls, Vcl.ExtCtrls,
//GLScene
GLScene, GLObjects, GLWin32Viewer, GLVectorGeometry, GLVectorLists,
GLCadencer, GLTexture, GLColor, GLCrossPlatform, GLCoordinates,
GLBaseClasses;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLCamera1: TGLCamera;
DummyCube1: TGLDummyCube;
GLPoints1: TGLPoints;
GLCadencer1: TGLCadencer;
GLPoints2: TGLPoints;
Panel1: TPanel;
CBPointParams: TCheckBox;
CBAnimate: TCheckBox;
Timer1: TTimer;
LabelFPS: TLabel;
procedure FormCreate(Sender: TObject);
procedure GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure GLSceneViewer1MouseMove(Sender: TObject; Shift: TShiftState;
X, Y: Integer);
procedure GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
procedure CBAnimateClick(Sender: TObject);
procedure CBPointParamsClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
mx, my : Integer
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
const
cNbPoints = 180;
procedure TForm1.FormCreate(Sender: TObject);
begin
// allocate points in the 1st point set
GLPoints1.Positions.Count:=cNbPoints;
// specify white color for the 1st point set
// (if a single color is defined, all points will use it,
// otherwise, it's a per-point coloring)
GLPoints1.Colors.Add(clrWhite);
// specify blue color for the 2nd point set
GLPoints2.Colors.Add(clrBlue);
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const deltaTime,
newTime: Double);
var
i : Integer;
f, a, ab, ca, sa : Single;
p : TAffineVectorList;
v : TAffineVector;
begin
if CBAnimate.Checked then begin
// update the 1st point set with values from a math func
f:=1+Cos(newTime);
p:=GLPoints1.Positions;
ab:=newTime*0.1;
for i:=0 to cNbPoints-1 do
begin
a:=DegToRad(4*i)+ab;
SinCos(a, sa, ca);
v.X:=2*ca;
v.Y:=2*Cos(f*a);
v.Z:=2*sa;
p.Create[i]:=v;
end;
// replicate points in second set
GLPoints2.Positions:=GLPoints1.Positions;
end;
GLSceneViewer1.Invalidate;
end;
procedure TForm1.GLSceneViewer1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
mx:=x;
my:=y;
end;
procedure TForm1.GLSceneViewer1MouseMove(Sender: TObject;
Shift: TShiftState; X, Y: Integer);
begin
if Shift<>[] then begin
GLCamera1.MoveAroundTarget(my-y, mx-x);
mx:=x;
my:=y;
end;
end;
procedure TForm1.CBAnimateClick(Sender: TObject);
begin
GLPoints1.Static:=not CBAnimate.Checked;
GLPoints2.Static:=not CBAnimate.Checked;
end;
procedure TForm1.CBPointParamsClick(Sender: TObject);
begin
GLPoints1.PointParameters.Enabled:=CBPointParams.Checked;
GLPoints2.PointParameters.Enabled:=CBPointParams.Checked;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
LabelFPS.Caption:=Format('%.1f FPS', [GLSceneViewer1.FramesPerSecond]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
end.
|
// testing array declarations with expressions
PROGRAM test13;
TYPE
array1 = ARRAY [0..2] of integer;
VAR
a : array1;
BEGIN
a[0 * 1] := 0;
a[2 - 1] := 1;
a[1 + 1] := 2;
WRITE(a[0]);
WRITE(a[1]);
WRITE(a[2]);
END.
|
unit TestLayoutBare2;
{ AFS 28 March 2000
This unit compiles but is not semantically meaningfull
it is test cases for the code formatting utility
a 'bare' block is one that does not have begin..end around it
This unit tests layout for statments with bare blocks
Use of bare blocks nested within bare blocks is not recommended in real-world code
for purely human aethetic & readabilty reasons
}
interface
implementation
procedure Test;
var
iA, IB: integer;
BA: boolean;
begin
if ia > 3 then
if ia > 4 then
begin
ib := 10;
end;
if ia > 4 then
if ia > 4 then
begin
ib := 10;
end;
if ia > 4 then
if ia > 4 then
begin
ib := 10;
end;
end;
{ same with spaces }
procedure Test2;
var
iA, IB: integer;
BA: boolean;
begin
if ia > 3 then
if ia > 4 then
begin
ib := 10;
end;
if ia > 4 then
if ia > 4 then
begin
ib := 10;
end;
if ia > 4 then
if ia > 4 then
begin
ib := 10;
end;
end;
{ next 2 tests exhibited layout bugs found in testing 0.3beta }
procedure Test3;
var
iA, IB: integer;
BA: boolean;
begin
if ia > 3 then
if ia > 4 then
ib := 10;
if ia > 4 then
ib := 10;
if ia > 4 then
ib := 0;
end;
procedure Test4;
var
iA, IB: integer;
BA: boolean;
begin
if ia > 3 then
if ia > 4 then
begin
ib := 10;
end;
if ia > 4 then
begin
ib := 10;
end;
end;
procedure TestEnd1;
var
sA, sb: string;
begin
sA := 'Fred ';
sB := sA + 'Jim';
sA := sA + #40;
if SA = '' then
begin
sA := sA + 'narf';
end;
end;
procedure TestEnd2;
var
sA, sb: string;
begin
sA := 'Fred ';
sB := sA + 'Jim';
sA := sA + #40;
if SA = '' then
if SA='x' then
begin
sA := sA + 'narf';
end;
end;
procedure TestEnd3;
var
sA, sb: string;
begin
sA := 'Fred ';
sB := sA + 'Jim';
sA := sA + #40;
if SA = '' then
if Sb='x' then
if SA <> 'foo' then
begin
sA := sA + 'narf';
end;
end;
procedure TestEnd4;
var
sA, sb: string;
begin
sA := 'Fred ';
sB := sA + 'Jim';
sA := sA + #40;
if SA = '' then
if Sb='x' then
if SA <> 'foo' then
if SA = 'groo' then
begin
sA := sA + 'narf';
end;
end;
procedure TestEnd5;
var
sA, sb: string;
begin
sA := 'Fred ';
sB := sA + 'Jim';
begin
sA := sA + #40;
if SA = '' then
if Sb='x' then
if SA <> 'foo' then
if SA = 'groo' then
begin
sA := sA + 'narf';
end;
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit InetCertFilesWizardPage;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, WizardAPI, ActnList, StdActns, StdCtrls, AppEvnts, ExpertsUIWizard;
type
TDSCertFilesFocusField = (focCertFile, focKeyFile, focKeyFilePassword, focRootCertFile,
focTestButton);
TDSExpertCertFileInfo = record
CertFile: string;
KeyFile: string;
KeyFilePassword: string;
RootCertFile: string;
end;
TInetCertFilesWizardFrame = class(TFrame, IExpertsWizardPageFrame)
LabelCertFile: TLabel;
CertFileEdit: TEdit;
BrowseCertFileBtn: TButton;
KeyFileEdit: TEdit;
LabelKeyFile: TLabel;
RootCertFileEdit: TEdit;
LabelRootCertFile: TLabel;
BrowseKeyFileBtn: TButton;
BrowseRootCertFileBtn: TButton;
LabelKeyFilePassword: TLabel;
KeyPasswordEdit: TEdit;
OpenDialog1: TOpenDialog;
ApplicationEvents1: TApplicationEvents;
ButtonTest: TButton;
procedure BrowseCertFileBtnClick(Sender: TObject);
procedure BrowseKeyFileBtnClick(Sender: TObject);
procedure BrowseRootCertFileBtnClick(Sender: TObject);
procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
procedure ButtonTestClick(Sender: TObject);
private
FOnFocusChange: TNotifyEvent;
FCertFilesFocusField: TDSCertFilesFocusField;
FOnTest: TNotifyEvent;
FPage: TCustomExpertsFrameWizardPage;
function GetLeftMargin: Integer;
procedure SetLeftMargin(const Value: Integer);
procedure OpenFileDialog(AEdit: TEdit; AKeyFile: Boolean);
function ValidateFileExists(AEdit: TEdit): Boolean;
function GetCertFileInfo: TDSExpertCertFileInfo;
protected
{ IExpertsWizardPageFrame }
function ExpertsFrameValidatePage(ASender: TCustomExpertsWizardPage; var AHandled: Boolean): Boolean;
procedure ExpertsFrameUpdateInfo(ASender: TCustomExpertsWizardPage; var AHandled: Boolean);
procedure ExpertsFrameCreated(APage: TCustomExpertsFrameWizardPage);
procedure ExpertsFrameEnterPage(APage: TCustomExpertsFrameWizardPage);
function GetWizardInfo: string;
property LeftMargin: Integer read GetLeftMargin write SetLeftMargin;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
// class function CreateFrame(AOwner: TComponent): TInetCertFilesWizardFrame; static;
procedure TestCertFiles(APort: Integer);
function ValidateFields: Boolean;
property FocusField: TDSCertFilesFocusField read FCertFilesFocusField;
property OnFocusChange: TNotifyEvent read FOnFocusChange write FOnFocusChange;
property OnTest: TNotifyEvent read FOnTest write FOnTest;
property CertFileInfo: TDSExpertCertFileInfo read GetCertFileInfo;
end;
implementation
{$R *.dfm}
uses InetDesignResStrs, IPPeerAPI;
function SlashSep(const Path, S: string): string;
begin
if Path <> '' then
Result := IncludeTrailingPathDelimiter(Path) + S
else
Result := S;
end;
procedure TestCertificateFiles
(APort: Integer; const ACertFileName, AKeyFileName, ARootCertFile: string;
AKeyFilePassword: AnsiString);
var
LTestServer: IIPTestServer;
begin
LTestServer := PeerFactory.CreatePeer('', IIPTestServer) as IIPTestServer;
LTestServer.TestCertificateFiles(APort, ACertFileName, AKeyFileName, ARootCertFile, AKeyFilePassword);
end;
//class function TInetCertFilesWizardFrame.CreateFrame(AOwner: TComponent): TInetCertFilesWizardFrame;
//var
// LFrame: TInetCertFilesWizardFrame;
//begin
// LFrame := TInetCertFilesWizardFrame.Create(AOwner);
// LFrame.LeftMargin := cExpertsLeftMargin;
// Result := LFrame;
//end;
procedure TInetCertFilesWizardFrame.ExpertsFrameCreated(
APage: TCustomExpertsFrameWizardPage);
begin
LeftMargin := cExpertsLeftMargin;
FPage := APage;
FPage.Title := sCertFilesPageTitle;
FPage.Description := sCertFilesPageDescription;
end;
procedure TInetCertFilesWizardFrame.ExpertsFrameEnterPage(
APage: TCustomExpertsFrameWizardPage);
begin
//APage.UpdateInfo;
end;
procedure TInetCertFilesWizardFrame.ExpertsFrameUpdateInfo(
ASender: TCustomExpertsWizardPage; var AHandled: Boolean);
begin
AHandled := True;
ASender.WizardInfo := GetWizardInfo;
end;
function TInetCertFilesWizardFrame.ExpertsFrameValidatePage(
ASender: TCustomExpertsWizardPage; var AHandled: Boolean): Boolean;
begin
AHandled := True;
Result := ValidateFields;
end;
function TInetCertFilesWizardFrame.GetCertFileInfo: TDSExpertCertFileInfo;
begin
Result.CertFile := CertFileEdit.Text;
Result.KeyFile := KeyFileEdit.Text;
Result.KeyFilePassword := KeyPasswordEdit.Text;
Result.RootCertFile := RootCertFileEdit.Text;
end;
procedure TInetCertFilesWizardFrame.OpenFileDialog(AEdit: TEdit; AKeyFile: Boolean);
begin
if AKeyFile then
OpenDialog1.Filter := sPEMKeyFileFilter
else
OpenDialog1.Filter := sPEMFileFilter;
OpenDialog1.Title := sPEMOpenFileTitle;
OpenDialog1.HelpContext := 0;
OpenDialog1.Options := OpenDialog1.Options + [ofShowHelp, ofPathMustExist, ofHideReadonly, ofFileMustExist];
OpenDialog1.FileName := AEdit.Text;
if OpenDialog1.Execute(Self.Handle) then
begin
AEdit.Text := OpenDialog1.FileName;
end;
end;
procedure TInetCertFilesWizardFrame.ApplicationEvents1Idle(Sender: TObject;
var Done: Boolean);
var
LFocus: TDSCertFilesFocusField;
begin
if not Self.Visible then
Exit;
if CertFileEdit.Focused or BrowseCertFileBtn.Focused then
LFocus := focCertFile
else if RootCertFileEdit.Focused or BrowseRootCertFileBtn.Focused then
LFocus := focRootCertFile
else if KeyFileEdit.Focused or BrowseKeyFileBtn.Focused then
LFocus := focKeyFile
else if KeyPasswordEdit.Focused then
LFocus := focKeyFilePassword
else if ButtonTest.Focused then
LFocus := focTestButton
else
LFocus := FocusField;
if LFocus <> FocusField then
begin
Self.FCertFilesFocusField := LFocus;
if Assigned(FOnFocusChange) then
FOnFocusChange(Self);
if FPage <> nil then
FPage.UpdateInfo;
end;
ButtonTest.Enabled :=
(CertFileEdit.Text <> '') and (KeyFileEdit.Text <> '');
end;
procedure TInetCertFilesWizardFrame.BrowseCertFileBtnClick(Sender: TObject);
begin
OpenFileDialog(CertFileEdit, False);
end;
function TInetCertFilesWizardFrame.GetWizardInfo: string;
begin
case FocusField of
focCertFile:
Result := sCertFileInfo;
focRootCertFile:
Result := sRootCertFileInfo;
focTestButton:
Result := sCertFilesTestInfo;
focKeyFilePassword:
Result := sKeyFilePasswordInfo;
focKeyFile:
Result := sKeyFileInfo;
else
Result := sCertFilesPageInfo;
end
end;
procedure TInetCertFilesWizardFrame.BrowseKeyFileBtnClick(Sender: TObject);
begin
OpenFileDialog(KeyFileEdit, True);
end;
procedure TInetCertFilesWizardFrame.BrowseRootCertFileBtnClick(Sender: TObject);
begin
OpenFileDialog(RootCertFileEdit, False);
end;
procedure TInetCertFilesWizardFrame.ButtonTestClick(Sender: TObject);
begin
Assert(Assigned(FOnTest));
if ValidateFields then
if Assigned(FOnTest) then
FOnTest(Self)
end;
procedure TInetCertFilesWizardFrame.TestCertFiles(APort: Integer);
var
LCertFileInfo: TDSExpertCertFileInfo;
begin
LCertFileInfo := CertFileInfo;
try
Screen.Cursor := crHourGlass;
try
TestCertificateFiles(APort,
LCertFileInfo.CertFile, LCertFileInfo.KeyFile,
LCertFileInfo.RootCertFile, AnsiString(LCertFileInfo.KeyFilePassword));
finally
Screen.Cursor := crDefault;
end;
MessageDlg(sTestCertFilesOK, mtInformation, [mbOK], 0);
except
on E: Exception do
begin
MessageDlg(E.Message, mtError, [mbOK], 0);
end;
end;
end;
constructor TInetCertFilesWizardFrame.Create(AOwner: TComponent);
begin
inherited;
FCertFilesFocusField := focCertFile;
end;
function TInetCertFilesWizardFrame.GetLeftMargin: Integer;
begin
Result := CertFileEdit.Left;
end;
procedure TInetCertFilesWizardFrame.SetLeftMargin(const Value: Integer);
begin
CertFileEdit.Width := CertFileEdit.Width - (Value - CertFileEdit.Left);
CertFileEdit.Left := Value;
LabelCertFile.Left := Value;
KeyFileEdit.Width := KeyFileEdit.Width - (Value - KeyFileEdit.Left);
KeyFileEdit.Left := Value;
LabelKeyFile.Left := Value;
RootCertFileEdit.Width := RootCertFileEdit.Width - (Value - RootCertFileEdit.Left);
RootCertFileEdit.Left := Value;
LabelRootCertFile.Left := Value;
KeyPasswordEdit.Left := Value;
LabelKeyFilePassword.Left := Value;
end;
function TInetCertFilesWizardFrame.ValidateFileExists(AEdit: TEdit): Boolean;
var
LFileName: string;
begin
Result := True;
LFileName := AEdit.Text;
if Trim(LFileName) <> '' then
if not FileExists(LFileName) then
begin
MessageDlg(Format(sPEMFileNotFound, [LFileName]), mtError, [mbOK], 0);
AEdit.SetFocus;
Exit(False);
end;
end;
function TInetCertFilesWizardFrame.ValidateFields: Boolean;
begin
Result := True;
if not ValidateFileExists(CertFileEdit) then
Exit(False);
if not ValidateFileExists(KeyFileEdit) then
Exit(False);
if not ValidateFileExists(RootCertFileEdit) then
Exit(False);
end;
end.
|
unit deref_9;
interface
implementation
function SUM(a, b: Int32): Int32;
begin
Result := a + b;
end;
var G1, G2, G3: Int32;
P1, P2, P3: ^Int32;
procedure Test;
begin
P3^ := SUM(P1^, P2^);
end;
initialization
G1 := 1;
G2 := 2;
P1 := @G1;
P2 := @G2;
P3 := @G3;
Test();
finalization
Assert(G3 = 3);
end. |
{*********************************************************************
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* Autor: Brovin Y.D.
* E-mail: y.brovin@gmail.com
*
********************************************************************}
unit FGX.Asserts;
interface
{$SCOPEDENUMS ON}
uses
System.SysUtils;
type
EAssertError = class(Exception);
resourcestring
SObjectIsNotNilError = 'The not nil object is required, but instead of it the empty is received. ';
SValueIsNotInRange = 'The current value "%f" is not in range [%f, %f]. ';
SValueLess = 'The current value "%f" less than [%f].';
SValueMore = 'The current value "%f" more than [%f].';
SValueIsNotRequriedClass = 'The current object has invalid class. Expected receive "%s", but "%s" is received. ';
SValuesIsNotEqual = 'Specified values "%d" and "%d" is not equal';
SValuesIsTrue = 'Specified values is not True.' ;
SValuesIsFalse = 'Specified values is not False.' ;
procedure AssertIsNotNil(const AValue: IInterface; const AMessage: string = ''); overload;
procedure AssertIsNotNil(const AValue: TObject; const AMessage: string = ''); overload;
procedure AssertIsNotNil(const AValue: TClass; const AMessage: string = ''); overload;
procedure AssertInRange(const AValue, ALow, AHight: Integer; const AMessage: string = ''); overload;
procedure AssertInRange(const AValue, ALow, AHight: Single; const AMessage: string = ''); overload;
procedure AssertLessThan(const AValue, AHigh: Integer; const AMessage: string = ''); overload;
procedure AssertLessThan(const AValue, AHigh: Single; const AMessage: string = ''); overload;
procedure AssertMoreThan(const AValue, ALow: Integer; const AMessage: string = ''); overload;
procedure AssertMoreThan(const AValue, ALow: Single; const AMessage: string = ''); overload;
procedure AssertIsClass(const AValue: TObject; const AClass: TClass; const AMessage: string = '');
procedure AssertEqual(const AValue1: Integer; const AValue2: Integer; const AMessage: string = '');
procedure AssertIsTrue(const AValue: Boolean; const AMessage: string = '');
procedure AssertIsFalse(const AValue: Boolean; const AMessage: string = '');
implementation
uses
System.Math;
procedure AssertIsNotNil(const AValue: TObject; const AMessage: string = '');
begin
{$IFDEF DEBUG}
if AValue = nil then
raise EAssertError.Create(SObjectIsNotNilError + AMessage);
{$ENDIF}
end;
procedure AssertIsNotNil(const AValue: IInterface; const AMessage: string = '');
begin
{$IFDEF DEBUG}
if AValue = nil then
raise EAssertError.Create(SObjectIsNotNilError + AMessage);
{$ENDIF}
end;
procedure AssertIsNotNil(const AValue: TClass; const AMessage: string = ''); overload;
begin
{$IFDEF DEBUG}
if AValue = nil then
raise EAssertError.Create(SObjectIsNotNilError + AMessage);
{$ENDIF}
end;
procedure AssertInRange(const AValue, ALow, AHight: Integer; const AMessage: string = ''); overload;
begin
{$IFDEF DEBUG}
if not InRange(AValue, ALow, AHight) then
raise EAssertError.Create(Format(SValueIsNotInRange, [AValue, ALow, AHight]) + AMessage);
{$ENDIF}
end;
procedure AssertInRange(const AValue, ALow, AHight: Single; const AMessage: string = ''); overload;
begin
{$IFDEF DEBUG}
if not InRange(AValue, ALow, AHight) then
raise EAssertError.Create(Format(SValueIsNotInRange, [AValue, ALow, AHight]) + AMessage);
{$ENDIF}
end;
procedure AssertLessThan(const AValue, AHigh: Integer; const AMessage: string = ''); overload;
begin
{$IFDEF DEBUG}
if AValue > AHigh then
raise EAssertError.Create(Format(SValueLess, [AValue, AHigh]) + AMessage);
{$ENDIF}
end;
procedure AssertLessThan(const AValue, AHigh: Single; const AMessage: string = ''); overload;
begin
{$IFDEF DEBUG}
if AValue > AHigh then
raise EAssertError.Create(Format(SValueLess, [AValue, AHigh]) + AMessage);
{$ENDIF}
end;
procedure AssertMoreThan(const AValue, ALow: Integer; const AMessage: string = ''); overload;
begin
{$IFDEF DEBUG}
if AValue < ALow then
raise EAssertError.Create(Format(SValueLess, [AValue, ALow]) + AMessage);
{$ENDIF}
end;
procedure AssertMoreThan(const AValue, ALow: Single; const AMessage: string = ''); overload;
begin
{$IFDEF DEBUG}
if AValue < ALow then
raise EAssertError.Create(Format(SValueLess, [AValue, ALow]) + AMessage);
{$ENDIF}
end;
procedure AssertIsClass(const AValue: TObject; const AClass: TClass; const AMessage: string = '');
begin
{$IFDEF DEBUG}
if not (AValue is AClass) then
raise EAssertError.Create(Format(SValueIsNotRequriedClass, [AClass.ClassName, AValue.ClassName]) + AMessage);
{$ENDIF}
end;
procedure AssertEqual(const AValue1: Integer; const AValue2: Integer; const AMessage: string = '');
begin
{$IFDEF DEBUG}
if AValue1 <> AValue2 then
raise EAssertError.Create(Format(SValuesIsNotEqual, [AValue1, AValue2]) + AMessage);
{$ENDIF}
end;
procedure AssertIsTrue(const AValue: Boolean; const AMessage: string = '');
begin
{$IFDEF DEBUG}
if not AValue then
raise EAssertError.Create(SValuesIsTrue + AMessage);
{$ENDIF}
end;
procedure AssertIsFalse(const AValue: Boolean; const AMessage: string = '');
begin
{$IFDEF DEBUG}
if AValue then
raise EAssertError.Create(SValuesIsFalse + AMessage);
{$ENDIF}
end;
end. |
{*******************************************************}
{ }
{ Delphi DataSnap Framework }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit DSAzureQueueMetadataDialog;
interface
uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Controls, Vcl.StdCtrls,
Vcl.Buttons, Vcl.ExtCtrls, Vcl.Grids, Vcl.ValEdit;
type
TAzureQueueMetadataDialog = class(TForm)
MetadataList: TValueListEditor;
ButtClose: TButton;
ButtCommit: TButton;
btnDelMetadata: TButton;
btnAddMetadata: TButton;
procedure btnDelMetadataClick(Sender: TObject);
procedure btnAddMetadataClick(Sender: TObject);
procedure MetadataListStringsChange(Sender: TObject);
public
/// <summary>Sets the queue name and Metadata</summary>
/// <param name="QueueName">The name of the queue to display metadata for</param>
/// <param name="Metadata">The queue's current metadata</param>
procedure SetActiveQueue(const QueueName: String; Metadata: TStrings);
/// <summary>Returns the metadata as held by the list.</summary>
/// <returns>the metadata as held by the list.</returns>
function GetMetadata: TStringList;
end;
var
AzureQueueMetadataDialog: TAzureQueueMetadataDialog;
implementation
uses Data.DBXClientResStrs;
{$R *.dfm}
procedure TAzureQueueMetadataDialog.btnAddMetadataClick(Sender: TObject);
begin
MetadataList.Col := 0;
MetadataList.Row := MetadataList.InsertRow('', '', true);
MetadataList.SetFocus;
ButtCommit.Enabled := true;
end;
procedure TAzureQueueMetadataDialog.btnDelMetadataClick(Sender: TObject);
var
row: Integer;
begin
row := MetadataList.Row;
if (row > 0) and (row < MetadataList.RowCount) then
begin
MetadataList.DeleteRow(row);
ButtCommit.Enabled := true;
end;
end;
function TAzureQueueMetadataDialog.GetMetadata: TStringList;
begin
Result := TStringList.Create;
Result.AddStrings(MetadataList.Strings);
end;
procedure TAzureQueueMetadataDialog.MetadataListStringsChange(Sender: TObject);
begin
ButtCommit.Enabled := True;
end;
procedure TAzureQueueMetadataDialog.SetActiveQueue(const QueueName: String; Metadata: TStrings);
begin
if (QueueName <> EmptyStr) then
begin
Caption := Format('%s: %s', [SQueueMetadataTitle, QueueName]);
MetadataList.Strings.BeginUpdate;
try
MetadataList.Strings.Clear;
if (MetaData <> nil) then
MetadataList.Strings.AddStrings(Metadata);
finally
MetadataList.Strings.EndUpdate;
end;
end
else
Caption := SQueueMetadataTitle;
ButtCommit.Enabled := False;
end;
end.
|
{$mode objfpc}
unit CMDLineArgs;
interface
type
PKeyArgList = ^TKeyArgList;
TKeyArgList = record
next : PKeyArgList;
Key, val : String;
end;
PChArgList = ^TChArgList;
TChArgList = record
next : PChArgList;
val : Char;
end;
var
KeyArgList, LastInKeyList : PKeyArgList;
ChArgList, LastInChList : PChArgList;
function isArgSet(key : Char) : Boolean;
function getArgKeyValue(key : String) : String;
implementation
var
i, j, count, eqPos : Integer;
str, strkey : String;
procedure addChValue(c : Char);
begin
if LastInChList = nil then
begin
new(ChArgList);
LastInChList := ChArgList;
end
else
begin
new(LastInChList^.next);
LastInChList := LastInChList^.next;
end;
LastInChList^.val := c;
LastInChList^.next := nil;
end;
procedure addKeyPair(key, val : String);
begin
if LastInKeyList = nil then
begin
new(KeyArgList);
LastInKeyList := KeyArgList;
end
else
begin
new(LastInKeyList^.next);
LastInKeyList := LastInKeyList^.next;
end;
LastInKeyList^.Key := key;
LastInKeyList^.val := val;
LastInKeyList^.next := nil;
end;
function isArgSet(key : Char) : Boolean;
var
current : PChArgList;
begin
current := ChArgList;
Result := false;
if current <> nil then
while true do
begin
Result := current^.val = key;
current := current^.next;
if Result or (current = nil) then break;
end;
end;
function getArgKeyValue(key : String) : String;
var
current : PKeyArgList;
begin
current := KeyArgList;
Result := '';
if current <> nil then
while true do
begin
if current^.Key = key then
begin
Result := current^.val;
break;
end;
current := current^.next;
if current = nil then break;
end;
end;
begin
KeyArgList := nil;
LastInKeyList := nil;
ChArgList := nil;
LastInChList := nil;
count := ParamCount();
for i := 1 to count do
begin
str := ParamStr(i);
eqPos := Pos('=', str);
if eqPos = 0 then // This is not a pair of key=value
begin
if str[1] = '-' then // This is a set of flags
for j := 2 to length(str) do
addChValue(str[j]);
end
else
begin
strkey := Copy(str, 1, eqPos - 1);
delete(str, 1, eqPos);
addKeyPair(strkey, str);
end;
end;
end. |
{*******************************************************}
{ }
{ YxdHash 哈希表,哈希函数 }
{ }
{ 版权所有 (C) 2013 - 2019 YangYxd }
{ }
{*******************************************************}
{
--------------------------------------------------------------------
说明
--------------------------------------------------------------------
YxdHash代码来自 swish 的 Qrbtree,感谢swish和他的qrbtree
YxdHash版本归 swish 和 YangYxd所有,保留一切权利
Qrbtree来自QDAC项目,版权归swish(QQ:109867294)所有
QDAC官方群:250530692
--------------------------------------------------------------------
更新记录
--------------------------------------------------------------------
2018.03.26 ver 1.0.11
--------------------------------------------------------------------
- 加强 StringHash, IntHash 功能
2015.06.29 ver 1.0.10
--------------------------------------------------------------------
- 将 MemPool 移入 YxdMemPool 单元中
2015.04.22 ver 1.0.9
--------------------------------------------------------------------
- 将 TYXDHashMapChainTable 改名为 TYXDHashMapLinkTable
2015.03.30 ver 1.0.8
--------------------------------------------------------------------
- 修改 TYXDHashMapChainTable: Add时允许添加nil数据
2014.11.17 ver 1.0.7
--------------------------------------------------------------------
2014.11.08 ver 1.0.6
--------------------------------------------------------------------
- 增加 TLinkedList 类,方便双向链表操作
2014.10.11 ver 1.0.5
--------------------------------------------------------------------
- 增加 TStringHash 类,将IniFiles单元的移植过来的
2014.10.11 ver 1.0.4
--------------------------------------------------------------------
- 修复TYXDHashMapChainTable增删时双向链表错乱的BUG(重要).
2014.10.10 ver 1.0.3
--------------------------------------------------------------------
- 增加YxdMemPool,使用内存池.
- 增加TYXDHashMapTable
- 增加TYXDHashMapList
- 增加TYXDHashMapChainTable
2014.08.27 ver 1.0.2
--------------------------------------------------------------------
- 优化了一下Insert略微提速.
2014.08.15 ver 1.0.1
--------------------------------------------------------------------
- 此单元做为Hash操作的基础库.
- 将原QRBTree中的RBNote改为record型
--------------------------------------------------------------------
}
unit YxdHash;
interface
{$IF defined(FPC) or defined(VER170) or defined(VER180) or defined(VER190) or defined(VER200) or defined(VER210)}
{$DEFINE USEINLINE}
{$IFEND}
{$DEFINE USE_MEMPOOL} // 是否使用内存池
{$DEFINE USE_ATOMIC} // 是否启用原子操作函数
{.$DEFINE AUTORESIE} // 哈希表是否自动调整桶大小
uses
{$IFDEF MSWINDOWs}Windows, {$ENDIF}
YxdMemPool,
SysUtils, Classes, Types, SyncObjs;
type
{$if CompilerVersion < 23}
NativeUInt = Cardinal;
NativeInt = Integer;
{$ifend}
Number = NativeInt;
NumberU = NativeUInt;
PNumber = ^Number;
PNumberU = ^NumberU;
PDWORD = ^DWORD;
type
/// 桶内元素的哈希值列表
THashType = NumberU;
PPHashList = ^PHashList;
PHashList = ^THashList;
THashList = {$IFNDEF USEINLINE}object{$ELSE}packed record{$ENDIF}
Next: PHashList; // 下一元素
Data: Pointer; // 附加数据成员
Hash: THashType; // 当前元素哈希值,记录以便重新分配桶时不需要再次外部计算
procedure Reset; {$IFDEF USEINLINE}inline;{$ENDIF}
end;
THashArray = array of PHashList;
type
PHashValue = ^THashValue;
THashValue = {$IFNDEF USEINLINE}object{$ELSE}packed record{$ENDIF}
Size: Cardinal; // 数据大小
Data: Pointer; // 数据指针
function AsString: string;
procedure Clear;
end;
type
PHashMapValue = ^THashMapValue;
THashMapValue = {$IFNDEF USEINLINE}object{$ELSE}packed record{$ENDIF}
Value: THashValue; // 数据
IsStrKey: WordBool; // 是否是字符串 Key
Key: string; // 字符串 Key
function GetNumKey: Number; {$IFDEF USEINLINE}inline;{$ENDIF}
procedure SetNumKey(const AValue: Number); {$IFDEF USEINLINE}inline;{$ENDIF}
end;
type
PHashMapList = ^THashMapList;
THashMapList = {$IFNDEF USEINLINE}object{$ELSE}packed record{$ENDIF}
Next: PHashList; // 下一元素
Data: PHashMapValue; // 附加数据成员
Hash: THashType; // 当前元素哈希值,记录以便重新分配桶时不需要再次外部计算
end;
type
PHashMapLinkItem = ^THashMapLinkItem;
THashMapLinkItem = {$IFNDEF USEINLINE}object{$ELSE}packed record{$ENDIF}
Next: PHashMapLinkItem;
Prev: PHashMapLinkItem;
Value: PHashMapValue;
end;
type
/// <summary>比较函数</summary>
/// <param name='P1'>第一个要比较的参数</param>
/// <param name='P2'>第二个要比较的参数</param>
/// <returns> 如果P1<P2,返回小于0的值,如果P1>P2返回大于0的值,如果相等,返回0</returns>
TYXDCompare = function (P1, P2:Pointer): Integer of object;
type
/// <summary>删除哈希表一个元素的通知</summary>
/// <param name="ATable">哈希表对象</param>
/// <param name="AHash">要删除的对象的哈希值</param>
/// <param name="AData">要删除的对象数据指针</param>
TYXDHashDeleteNotify = procedure (ATable: TObject; AHash: THashType; AData: Pointer) of object;
type
PPHashItem = ^PHashItem;
PHashItem = ^THashItem;
THashItem = record
Next: PHashItem;
Key: string;
case Int64 of
0: (Value: Number);
1: (AsNumber: Number);
2: (AsDouble: Double);
3: (AsInt64: Int64);
4: (AsPointer: Pointer);
end;
type
/// <summary>删除哈希表一个元素的通知</summary>
/// <param name="ATable">哈希表对象</param>
/// <param name="AHash">要删除的对象的哈希值</param>
/// <param name="AData">要删除的对象数据指针</param>
TYXDStrHashItemFreeNotify = procedure (Item: PHashItem) of object;
TStringHash = class
private
FCount: Integer;
FOnFreeItem: TYXDStrHashItemFreeNotify;
function GetBucketsCount: Integer;
function GetValueItem(const Key: string): Number;
procedure SetValueItem(const Key: string; const Value: Number);
function GetItem(const Key: string): THashItem;
public
Buckets: array of PHashItem;
FLocker: TCriticalSection;
constructor Create(Size: Cardinal = 331);
destructor Destroy; override;
function Find(const Key: string): PPHashItem;
procedure Clear;
procedure Lock;
procedure UnLock;
procedure Remove(const Key: string);
procedure GetItems(AList: TList);
procedure GetKeyList(AList: TStrings);
procedure DoFreePointerItem(Item: PHashItem);
function ValueOf(const Key: string; const DefaultValue: Number = -1): Number;
function Exists(const Key: string): Boolean;
procedure Add(const Key: string; const Value: Number); overload;
procedure Add(const Key: string; const Value: Double); overload;
procedure Add(const Key: string; const Value: Int64); overload;
procedure Add(const Key: string; const Value: Pointer); overload;
procedure AddOrUpdate(const Key: string; const Value: Number); overload;
procedure AddOrUpdate(const Key: string; const Value: Double); overload;
procedure AddOrUpdate(const Key: string; const Value: Int64); overload;
procedure AddOrUpdate(const Key: string; const Value: Pointer); overload;
function Modify(const Key: string; const Value: Number): Boolean; overload;
function Modify(const Key: string; const Value: Double): Boolean; overload;
function Modify(const Key: string; const Value: Int64): Boolean; overload;
function Modify(const Key: string; const Value: Pointer): Boolean; overload;
function TryGetValue(const Key: string; var OutValue: Number): Boolean; overload;
function TryGetValue(const Key: string; var OutValue: Int64): Boolean; overload;
function TryGetValue(const Key: string; var OutValue: Double): Boolean; overload;
function TryGetValue(const Key: string; var OutValue: Pointer): Boolean; overload;
function GetInt(const Key: string; const DefaultValue: Number = -1): Number;
function GetInt64(const Key: string; const DefaultValue: Int64 = -1): Int64;
function GetFolat(const Key: string; const DefaultValue: Double = -1): Double;
function GetPointer(const Key: string): Pointer;
property Values[const Key: string]: Number read GetValueItem write SetValueItem;
property Items[const Key: string]: THashItem read GetItem;
property Count: Integer read FCount;
property BucketsCount: Integer read GetBucketsCount;
property OnFreeItem: TYXDStrHashItemFreeNotify read FOnFreeItem write FOnFreeItem;
end;
type
PPIntHashItem = ^PIntHashItem;
PIntHashItem = ^TIntHashItem;
TIntHashItem = record
Next: PIntHashItem;
Key: THashType;
case Int64 of
0: (Value: Number);
1: (AsNumber: Number);
2: (AsDouble: Double);
3: (AsInt64: Int64);
4: (AsPointer: Pointer);
end;
/// <summary>删除哈希表一个元素的通知</summary>
/// <param name="ATable">哈希表对象</param>
/// <param name="AHash">要删除的对象的哈希值</param>
/// <param name="AData">要删除的对象数据指针</param>
TYXDIntHashItemFreeNotify = procedure (Item: PIntHashItem) of object;
TIntHash = class
private
FCount: Integer;
FLocker: TCriticalSection;
FOnFreeItem: TYXDIntHashItemFreeNotify;
function GetBucketsCount: Integer;
function GetValueItem(const Key: THashType): Number;
procedure SetValueItem(const Key: THashType; const Value: Number);
function GetItem(const Key: THashType): TIntHashItem;
public
Buckets: array of PIntHashItem;
constructor Create(Size: Cardinal = 331);
destructor Destroy; override;
procedure Clear;
procedure Lock;
procedure UnLock;
function Find(const Key: THashType): PPIntHashItem;
function Remove(const Key: THashType): Boolean;
function ValueOf(const Key: THashType; const DefaultValue: Number = -1): Number;
function Exists(const Key: THashType): Boolean;
procedure GetItems(AList: TList);
procedure GetKeyList(AList: TStrings);
procedure DoFreePointerItem(Item: PHashItem);
procedure Add(const Key: THashType; const Value: Number); overload;
procedure Add(const Key: THashType; const Value: Double); overload;
procedure Add(const Key: THashType; const Value: Int64); overload;
procedure Add(const Key: THashType; const Value: Pointer); overload;
procedure AddOrUpdate(const Key: THashType; const Value: Number); overload;
procedure AddOrUpdate(const Key: THashType; const Value: Double); overload;
procedure AddOrUpdate(const Key: THashType; const Value: Int64); overload;
procedure AddOrUpdate(const Key: THashType; const Value: Pointer); overload;
function Modify(const Key: THashType; const Value: Number): Boolean; overload;
function Modify(const Key: THashType; const Value: Double): Boolean; overload;
function Modify(const Key: THashType; const Value: Int64): Boolean; overload;
function Modify(const Key: THashType; const Value: Pointer): Boolean; overload;
function TryGetValue(const Key: THashType; var OutValue: Number): Boolean; overload;
function TryGetValue(const Key: THashType; var OutValue: Int64): Boolean; overload;
function TryGetValue(const Key: THashType; var OutValue: Double): Boolean; overload;
function TryGetValue(const Key: THashType; var OutValue: Pointer): Boolean; overload;
function GetInt(const Key: THashType; const DefaultValue: Number = -1): Number;
function GetInt64(const Key: THashType; const DefaultValue: Int64 = -1): Int64;
function GetFolat(const Key: THashType; const DefaultValue: Double = -1): Double;
function GetPointer(const Key: THashType): Pointer;
property Values[const Key: THashType]: Number read GetValueItem write SetValueItem;
property Items[const Key: THashType]: TIntHashItem read GetItem;
property Count: Integer read FCount;
property BucketsCount: Integer read GetBucketsCount;
property OnFreeItem: TYXDIntHashItemFreeNotify read FOnFreeItem write FOnFreeItem;
end;
type
/// <summary>
/// 哈希表, 用于存贮一些用于查询的散列数据
/// </summary>
TYXDHashTable = class(TObject)
private
FPool: TMemPool;
procedure SetAutoSize(const Value: Boolean);
procedure FreeBucket(var ABucket: PHashList); virtual;
function GetMemSize: Int64; virtual;
protected
FCount: Integer;
FBuckets: THashArray;
FOnDelete: TYXDHashDeleteNotify;
FOnCompare: TYXDCompare;
FAutoSize : Boolean;
procedure DoDelete(AHash: THashType; AData:Pointer); virtual;
function GetBuckets(AIndex: Integer): PHashList; {$IFDEF USEINLINE}inline;{$ENDIF}
function GetBucketCount: Integer; {$IFDEF USEINLINE}inline;{$ENDIF}
function Compare(Data1, Data2: Pointer; var AResult: Integer): Boolean; {$IFDEF USEINLINE}inline;{$ENDIF}
public
///构造函数,以桶数量为参数,后期可以调用Resize调整
constructor Create(ASize: Integer); overload; virtual;
///构造函数
constructor Create; overload;
destructor Destroy;override;
procedure Clear; virtual;
procedure DeleteBucket(Index: Integer);
procedure ReSize(ASize: Cardinal);
procedure Add(AData: Pointer; AHash: THashType);
// 找出哈希值为AHash的所有HashList,需要自己释放返回的HashList
function Find(AHash: THashType): PHashList; overload;
function Find(AData: Pointer; AHash: THashType): Pointer; overload;
function FindFirstData(AHash: THashType): Pointer;
function FindFirst(AHash: THashType): PHashList; {$IFDEF USEINLINE}inline;{$ENDIF}
function FindNext(AList: PHashList): PHashList; {$IFDEF USEINLINE}inline;{$ENDIF}
procedure FreeHashList(AList: PHashList);
function Exists(AData: Pointer; AHash: THashType):Boolean;
procedure Delete(AData: Pointer; AHash: THashType);
procedure Update(AData: Pointer; AOldHash, ANewHash: THashType);
// 元素个数
property Count: Integer read FCount;
// 桶数量
property BucketCount: Integer read GetBucketCount;
// 桶列表
property Buckets[AIndex:Integer]: PHashList read GetBuckets;default;
// 比较函数
property OnCompare:TYXDCompare read FOnCompare write FOnCompare;
// 删除事件通知
property OnDelete: TYXDHashDeleteNotify read FOnDelete write FOnDelete;
// 是否自动调整桶大小
property AutoSize: Boolean read FAutoSize write SetAutoSize;
// 内存占用大小
property MemSize: Int64 read GetMemSize;
end;
type
/// <summary>
/// 以字符串为 Key 的Hash表
/// 特点:
/// 1. 以字符串作为Key
/// 2. 可快速删除数据
/// 3. 可快速添加数据
/// 4. 无索引,只能通过桶来遍列每一个数据
/// </summary>
TYXDHashMapTable = class(TYXDHashTable)
private
FListPool: TMemPool;
procedure FreeBucket(var ABucket: PHashList); override;
function GetMemSize: Int64; override;
protected
procedure DoAdd(ABucket: PHashMapList); virtual;
public
constructor Create(ASize: Integer); override;
destructor Destroy; override;
procedure Add(const Key: string; AData: PHashValue); overload;
procedure Add(const Key: Number; AData: PHashValue); overload;
procedure Add(const Key: string; AData: Integer); overload;
procedure Add(const Key: Number; AData: Integer); overload;
procedure Clear; override;
function Exists(const Key: string): Boolean; overload; {$IFDEF USEINLINE}inline;{$ENDIF}
function Exists(const Key: Number): Boolean; overload; {$IFDEF USEINLINE}inline;{$ENDIF}
function Find(const Key: string): PHashMapValue; overload;
function Find(const Key: Number): PHashMapValue; overload;
function FindList(const Key: string): PPHashList; overload;
function FindList(const Key: Number): PPHashList; overload;
function Update(const Key: string; Value: PHashValue): Boolean; overload;
function Update(const Key: Number; Value: PHashValue): Boolean; overload;
function Remove(const Key: string): Boolean; overload;
function Remove(const Key: Number): Boolean; overload;
function Remove(const P: PHashMapValue): Boolean; overload;
function ValueOf(const Key: string): PHashValue; overload;
function ValueOf(const Key: Number): PHashValue; overload;
end;
type
TYXDHashMapListBase = class(TYXDHashMapTable)
private
function GetItem(Index: Integer): PHashMapValue; virtual; abstract;
public
property Items[Index: Integer]: PHashMapValue read GetItem;
end;
type
/// <summary>
/// 以字符串为Key,带索引的 Hash 列表
/// 特点:
/// 1. 以字符串作为Key
/// 2. 可快速使用 Index 访问遍列数据
/// 3. 可通过Index删除数据。删除速度较慢
/// 4. 可快速添加数据
/// </summary>
TYXDHashMapList = class(TYXDHashMapListBase)
private
FList: TList;
function GetItem(Index: Integer): PHashMapValue; override;
protected
procedure DoAdd(ABucket: PHashMapList); override;
procedure DoDelete(AHash: THashType; AData:Pointer); override;
public
constructor Create(ASize: Integer); override;
destructor Destroy; override;
procedure Clear; override;
procedure Delete(Index: Integer);
end;
type
/// <summary>
/// 以字符串为Key,带双向链表索引的 Hash 链表
/// 特点:
/// 1. 以字符串作为Key
/// 2. 可使用 Index 访问每一个数据(速度慢,建议使用链表方式遍列)
/// 3. 可快速删除数据
/// 4. 可快速添加数据
/// </summary>
TYXDHashMapLinkTable = class;
TYXDHashMapLinkTableEnumerator = class
private
FItem: PHashMapLinkItem;
public
constructor Create(AList: TYXDHashMapLinkTable);
function GetCurrent: PHashMapLinkItem; {$IFDEF USEINLINE}inline;{$ENDIF}
function MoveNext: Boolean;
property Current: PHashMapLinkItem read GetCurrent;
end;
TYXDHashMapLinkTable = class(TYXDHashMapListBase)
private
FFirst: PHashMapLinkItem;
FLast: PHashMapLinkItem;
ListBuckets: THashArray;
FLinkHashPool: TMemPool;
function GetItem(Index: Integer): PHashMapValue; override;
function GetMemSize: Int64; override;
function FindLinkItem(AData: Pointer; isDelete: Boolean): PHashMapLinkItem;
procedure FreeLinkList;
function GetLast: PHashMapValue;
protected
procedure DoAdd(ABucket: PHashMapList); override;
procedure DoDelete(AHash: THashType; AData:Pointer); override;
public
constructor Create(ASize: Integer); override;
destructor Destroy; override;
procedure Clear; override;
procedure Delete(Index: Integer);
function GetEnumerator: TYXDHashMapLinkTableEnumerator;
property First: PHashMapLinkItem read FFirst;
property Last: PHashMapLinkItem read FLast;
property LastValue: PHashMapValue read GetLast;
end;
// 保留旧的名称,以向下兼容
TYXDHashMapChainTable = TYXDHashMapLinkTable;
// --------------------------------------------------------------------------
// HASH 处理函数
// --------------------------------------------------------------------------
// HASH 函数
function HashOf(const Key: Pointer; KeyLen: Cardinal): THashType; overload;
function HashOf(const Key: string): THashType; {$IFDEF USEINLINE}inline;{$ENDIF} overload;
// 根据一个参考客户值,返回适当的哈希表大小
function CalcBucketSize(dataSize: Cardinal): THashType;
implementation
const
BucketSizes: array[0..47] of Cardinal = (
17,37,79,163,331,673,1361,2729,5471,10949,21911,43853,87719,175447,350899,
701819,1403641,2807303,5614657,8999993,11229331,22458671,30009979,44917381,
50009969, 60009997, 70009987, 80009851, 89834777,100009979,110009987,120009979,
130009903, 140009983,150009983,165009937,179669557,200009959,359339171,
400009999, 450009883,550009997,718678369,850009997,1050009979,1437356741,
1850009969, 2147483647
);
const
HASHITEMSize = SizeOf(THashMapList) + SizeOf(THashMapValue);
function HashOf(const Key: Pointer; KeyLen: Cardinal): THashType; overload;
var
ps: PCardinal;
lr: Cardinal;
begin
Result := 0;
if KeyLen > 0 then begin
ps := Key;
lr := (KeyLen and $03);//检查长度是否为4的整数倍
KeyLen := (KeyLen and $FFFFFFFC);//整数长度
while KeyLen > 0 do begin
Result := ((Result shl 5) or (Result shr 27)) xor ps^;
Inc(ps);
Dec(KeyLen, 4);
end;
if lr <> 0 then begin
case lr of
1: KeyLen := PByte(ps)^;
2: KeyLen := PWORD(ps)^;
3: KeyLen := PWORD(ps)^ or (PByte(Cardinal(ps) + 2)^ shl 16);
end;
Result := ((Result shl 5) or (Result shr 27)) xor KeyLen;
end;
end;
end;
function HashOf(const Key: string): THashType; {$IFDEF USEINLINE}inline;{$ENDIF} overload;
begin
Result := HashOf(PChar(Key), Length(Key){$IFDEF UNICODE} shl 1{$ENDIF});
end;
function CalcBucketSize(dataSize: Cardinal): THashType;
var
i: Integer;
begin
for i := 0 to High(BucketSizes) do
if BucketSizes[i] > dataSize then begin
Result := BucketSizes[i];
Exit;
end;
Result := BucketSizes[High(BucketSizes)];
end;
{ THashValue }
function THashValue.AsString: string;
begin
SetLength(Result, Size);
if Size > 0 then
Move(Data^, Result[1], Size);
end;
procedure THashValue.Clear;
begin
Size := 0;
Data := nil;
end;
{ TStringHash }
procedure TStringHash.Add(const Key: string; const Value: Number);
var
Hash: Integer;
Bucket: PHashItem;
begin
Hash := HashOf(Key) mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.Value := Value;
FLocker.Enter;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
Inc(FCount);
FLocker.Leave;
end;
procedure TStringHash.Add(const Key: string; const Value: Double);
var
Hash: Integer;
Bucket: PHashItem;
begin
Hash := HashOf(Key) mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.AsDouble := Value;
FLocker.Enter;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
Inc(FCount);
FLocker.Leave;
end;
procedure TStringHash.Add(const Key: string; const Value: Int64);
var
Hash: Integer;
Bucket: PHashItem;
begin
Hash := HashOf(Key) mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.AsInt64 := Value;
FLocker.Enter;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
Inc(FCount);
FLocker.Leave;
end;
procedure TStringHash.Add(const Key: string; const Value: Pointer);
var
Hash: Integer;
Bucket: PHashItem;
begin
Hash := HashOf(Key) mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.AsPointer := Value;
FLocker.Enter;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
Inc(FCount);
FLocker.Leave;
end;
procedure TStringHash.AddOrUpdate(const Key: string; const Value: Number);
begin
if not Modify(Key, Value) then
Add(Key, Value);
end;
procedure TStringHash.AddOrUpdate(const Key: string; const Value: Int64);
begin
if not Modify(Key, Value) then
Add(Key, Value);
end;
procedure TStringHash.AddOrUpdate(const Key: string; const Value: Double);
begin
if not Modify(Key, Value) then
Add(Key, Value);
end;
procedure TStringHash.AddOrUpdate(const Key: string; const Value: Pointer);
begin
if not Modify(Key, Value) then
Add(Key, Value);
end;
procedure TStringHash.Clear;
var
I: Integer;
P, N: PHashItem;
begin
FLocker.Enter;
for I := 0 to Length(Buckets) - 1 do begin
P := Buckets[I];
while P <> nil do begin
N := P^.Next;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
Dispose(P);
P := N;
end;
Buckets[I] := nil;
end;
FCount := 0;
FLocker.Leave;
end;
constructor TStringHash.Create(Size: Cardinal);
begin
inherited Create;
FCount := 0;
FLocker := TCriticalSection.Create;
SetLength(Buckets, Size);
end;
destructor TStringHash.Destroy;
begin
FLocker.Enter;
try
Clear;
inherited Destroy;
finally
FLocker.Free;
end;
end;
procedure TStringHash.DoFreePointerItem(Item: PHashItem);
begin
if (Item <> nil) and (Item.AsPointer <> nil) then
Dispose(Item.AsPointer);
end;
function TStringHash.Exists(const Key: string): Boolean;
begin
FLocker.Enter;
Result := Find(Key)^ <> nil;
FLocker.Leave;
end;
function TStringHash.Find(const Key: string): PPHashItem;
var
Hash: Integer;
begin
Hash := HashOf(Key) mod Cardinal(Length(Buckets));
Result := @Buckets[Hash];
while Result^ <> nil do
begin
if Result^.Key = Key then
Exit
else
Result := @Result^.Next;
end;
end;
function TStringHash.GetBucketsCount: Integer;
begin
Result := Length(Buckets);
end;
function TStringHash.GetFolat(const Key: string;
const DefaultValue: Double): Double;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.AsDouble
else
Result := DefaultValue;
FLocker.Leave;
end;
function TStringHash.GetInt(const Key: string;
const DefaultValue: Number): Number;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.AsNumber
else
Result := DefaultValue;
FLocker.Leave;
end;
function TStringHash.GetInt64(const Key: string;
const DefaultValue: Int64): Int64;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.AsInt64
else
Result := DefaultValue;
FLocker.Leave;
end;
function TStringHash.GetItem(const Key: string): THashItem;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^
else begin
Result.Next := nil;
Result.Key := '';
Result.AsInt64 := 0;
end;
FLocker.Leave;
end;
procedure TStringHash.GetItems(AList: TList);
var
P: PHashItem;
I: Integer;
begin
if not Assigned(AList) then
Exit;
FLocker.Enter;
try
for I := 0 to High(Buckets) do begin
P := Buckets[I];
while P <> nil do begin
if P.AsPointer <> nil then
AList.Add(P.AsPointer);
P := P.Next;
end;
end;
finally
FLocker.Leave;
end;
end;
procedure TStringHash.GetKeyList(AList: TStrings);
var
P: PHashItem;
I: Integer;
begin
if not Assigned(AList) then
Exit;
FLocker.Enter;
try
for I := 0 to High(Buckets) do begin
P := Buckets[I];
while P <> nil do begin
if P.Key <> '' then
AList.Add(P.Key);
P := P.Next;
end;
end;
finally
FLocker.Leave;
end;
end;
function TStringHash.GetPointer(const Key: string): Pointer;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.AsPointer
else
Result := nil;
FLocker.Leave;
end;
function TStringHash.GetValueItem(const Key: string): Number;
begin
Result := ValueOf(Key);
end;
procedure TStringHash.Lock;
begin
FLocker.Enter;
end;
function TStringHash.Modify(const Key: string; const Value: Pointer): Boolean;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
begin
Result := True;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
P^.AsPointer := Value;
end else
Result := False;
FLocker.Leave;
end;
function TStringHash.Modify(const Key: string; const Value: Int64): Boolean;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
begin
Result := True;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
P^.AsInt64 := Value;
end else
Result := False;
FLocker.Leave;
end;
function TStringHash.Modify(const Key: string; const Value: Double): Boolean;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
begin
Result := True;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
P^.AsDouble := Value;
end else
Result := False;
FLocker.Leave;
end;
function TStringHash.Modify(const Key: string; const Value: Number): Boolean;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
begin
Result := True;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
P^.Value := Value;
end
else
Result := False;
FLocker.Leave;
end;
procedure TStringHash.Remove(const Key: string);
var
P: PHashItem;
Prev: PPHashItem;
begin
FLocker.Enter;
Prev := Find(Key);
P := Prev^;
if P <> nil then
begin
Dec(FCount);
Prev^ := P^.Next;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
Dispose(P);
end;
FLocker.Leave;
end;
procedure TStringHash.SetValueItem(const Key: string; const Value: Number);
begin
AddOrUpdate(Key, Value);
end;
function TStringHash.TryGetValue(const Key: string;
var OutValue: Int64): Boolean;
var
P: PHashItem;
begin
Result := False;
FLocker.Enter;
P := Find(Key)^;
if P <> nil then begin
OutValue := P^.AsInt64;
Result := True;
end;
FLocker.Leave;
end;
function TStringHash.TryGetValue(const Key: string;
var OutValue: Double): Boolean;
var
P: PHashItem;
begin
Result := False;
FLocker.Enter;
P := Find(Key)^;
if P <> nil then begin
OutValue := P^.AsDouble;
Result := True;
end;
FLocker.Leave;
end;
function TStringHash.TryGetValue(const Key: string;
var OutValue: Pointer): Boolean;
var
P: PHashItem;
begin
Result := False;
FLocker.Enter;
P := Find(Key)^;
if P <> nil then begin
OutValue := P^.AsPointer;
Result := True;
end;
FLocker.Leave;
end;
function TStringHash.TryGetValue(const Key: string;
var OutValue: Number): Boolean;
var
P: PHashItem;
begin
Result := False;
FLocker.Enter;
P := Find(Key)^;
if P <> nil then begin
OutValue := P^.AsNumber;
Result := True;
end;
FLocker.Leave;
end;
procedure TStringHash.UnLock;
begin
FLocker.Leave;
end;
function TStringHash.ValueOf(const Key: string; const DefaultValue: Number): Number;
var
P: PHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.Value
else
Result := DefaultValue;
FLocker.Leave;
end;
{ TIntHash }
procedure TIntHash.Add(const Key: THashType; const Value: Number);
var
Hash: Integer;
Bucket: PIntHashItem;
begin
Hash := Key mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.Value := Value;
FLocker.Enter;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
Inc(FCount);
FLocker.Leave;
end;
procedure TIntHash.Add(const Key: THashType; const Value: Int64);
var
Hash: Integer;
Bucket: PIntHashItem;
begin
Hash := Key mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.AsInt64 := Value;
FLocker.Enter;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
Inc(FCount);
FLocker.Leave;
end;
procedure TIntHash.Add(const Key: THashType; const Value: Double);
var
Hash: Integer;
Bucket: PIntHashItem;
begin
Hash := Key mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.AsDouble := Value;
FLocker.Enter;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
Inc(FCount);
FLocker.Leave;
end;
procedure TIntHash.Add(const Key: THashType; const Value: Pointer);
var
Hash: Integer;
Bucket: PIntHashItem;
begin
Hash := Key mod Cardinal(Length(Buckets));
New(Bucket);
Bucket^.Key := Key;
Bucket^.AsPointer := Value;
FLocker.Enter;
Bucket^.Next := Buckets[Hash];
Buckets[Hash] := Bucket;
Inc(FCount);
FLocker.Leave;
end;
procedure TIntHash.AddOrUpdate(const Key: THashType; const Value: Number);
begin
if not Modify(Key, Value) then
Add(Key, Value);
end;
procedure TIntHash.AddOrUpdate(const Key: THashType; const Value: Double);
begin
if not Modify(Key, Value) then
Add(Key, Value);
end;
procedure TIntHash.AddOrUpdate(const Key: THashType; const Value: Pointer);
begin
if not Modify(Key, Value) then
Add(Key, Value);
end;
procedure TIntHash.AddOrUpdate(const Key: THashType; const Value: Int64);
begin
if not Modify(Key, Value) then
Add(Key, Value);
end;
procedure TIntHash.Clear;
var
I: Integer;
P, N: PIntHashItem;
begin
FLocker.Enter;
for I := 0 to Length(Buckets) - 1 do begin
P := Buckets[I];
while P <> nil do begin
N := P^.Next;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
Dispose(P);
P := N;
end;
Buckets[I] := nil;
end;
FLocker.Leave;
end;
constructor TIntHash.Create(Size: Cardinal);
begin
inherited Create;
FLocker := TCriticalSection.Create;
SetLength(Buckets, Size);
FCount := 0;
end;
destructor TIntHash.Destroy;
begin
FLocker.Enter;
try
Clear;
inherited Destroy;
finally
FLocker.Free;
end;
end;
procedure TIntHash.DoFreePointerItem(Item: PHashItem);
begin
end;
function TIntHash.Exists(const Key: THashType): Boolean;
begin
FLocker.Enter;
Result := Find(Key)^ <> nil;
FLocker.Leave;
end;
function TIntHash.Find(const Key: THashType): PPIntHashItem;
begin
Result := @Buckets[Key mod Cardinal(Length(Buckets))];
while Result^ <> nil do begin
if Result^.Key = Key then
Exit
else
Result := @Result^.Next;
end;
end;
function TIntHash.GetBucketsCount: Integer;
begin
Result := Length(Buckets);
end;
function TIntHash.GetFolat(const Key: THashType;
const DefaultValue: Double): Double;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.AsDouble
else
Result := DefaultValue;
FLocker.Leave;
end;
function TIntHash.GetInt(const Key: THashType;
const DefaultValue: Number): Number;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.AsNumber
else
Result := DefaultValue;
FLocker.Leave;
end;
function TIntHash.GetInt64(const Key: THashType;
const DefaultValue: Int64): Int64;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.AsInt64
else
Result := DefaultValue;
FLocker.Leave;
end;
function TIntHash.GetItem(const Key: THashType): TIntHashItem;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^
else begin
Result.Next := nil;
Result.Key := 0;
Result.AsInt64 := 0;
end;
FLocker.Leave;
end;
procedure TIntHash.GetItems(AList: TList);
var
P: PIntHashItem;
I: Integer;
begin
if not Assigned(AList) then
Exit;
FLocker.Enter;
try
for I := 0 to High(Buckets) do begin
P := Buckets[I];
while P <> nil do begin
if Pointer(P.Value) <> nil then
AList.Add(Pointer(P.Value));
P := P.Next;
end;
end;
finally
FLocker.Leave;
end;
end;
procedure TIntHash.GetKeyList(AList: TStrings);
var
P: PIntHashItem;
I: Integer;
begin
if not Assigned(AList) then
Exit;
FLocker.Enter;
try
for I := 0 to High(Buckets) do begin
P := Buckets[I];
while P <> nil do begin
if P.Key <> 0 then
AList.Add(IntToStr(P.Key));
P := P.Next;
end;
end;
finally
FLocker.Leave;
end;
end;
function TIntHash.GetPointer(const Key: THashType): Pointer;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.AsPointer
else
Result := nil;
FLocker.Leave;
end;
function TIntHash.GetValueItem(const Key: THashType): Number;
begin
Result := ValueOf(Key);
end;
procedure TIntHash.Lock;
begin
FLocker.Enter;
end;
function TIntHash.Modify(const Key: THashType; const Value: Double): Boolean;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
begin
Result := True;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
P^.AsDouble := Value;
end
else
Result := False;
FLocker.Leave;
end;
function TIntHash.Modify(const Key: THashType; const Value: Pointer): Boolean;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
begin
Result := True;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
P^.AsPointer := Value;
end
else
Result := False;
FLocker.Leave;
end;
function TIntHash.Modify(const Key: THashType; const Value: Int64): Boolean;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
begin
Result := True;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
P^.AsInt64 := Value;
end
else
Result := False;
FLocker.Leave;
end;
function TIntHash.Modify(const Key: THashType; const Value: Number): Boolean;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
begin
Result := True;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
P^.Value := Value;
end
else
Result := False;
FLocker.Leave;
end;
function TIntHash.Remove(const Key: THashType): Boolean;
var
P: PIntHashItem;
Prev: PPIntHashItem;
begin
Result := False;
FLocker.Enter;
Prev := Find(Key);
P := Prev^;
if P <> nil then begin
Result := True;
Prev^ := P^.Next;
if Assigned(FOnFreeItem) then
FOnFreeItem(P);
Dispose(P);
end;
FLocker.Leave;
end;
procedure TIntHash.SetValueItem(const Key: THashType; const Value: Number);
begin
AddOrUpdate(Key, Value);
end;
function TIntHash.TryGetValue(const Key: THashType;
var OutValue: Double): Boolean;
var
P: PIntHashItem;
begin
Result := False;
FLocker.Enter;
P := Find(Key)^;
if P <> nil then begin
OutValue := P^.AsDouble;
Result := True;
end;
FLocker.Leave;
end;
function TIntHash.TryGetValue(const Key: THashType;
var OutValue: Pointer): Boolean;
var
P: PIntHashItem;
begin
Result := False;
FLocker.Enter;
P := Find(Key)^;
if P <> nil then begin
OutValue := P^.AsPointer;
Result := True;
end;
FLocker.Leave;
end;
function TIntHash.TryGetValue(const Key: THashType;
var OutValue: Number): Boolean;
var
P: PIntHashItem;
begin
Result := False;
FLocker.Enter;
P := Find(Key)^;
if P <> nil then begin
OutValue := P^.AsNumber;
Result := True;
end;
FLocker.Leave;
end;
function TIntHash.TryGetValue(const Key: THashType;
var OutValue: Int64): Boolean;
var
P: PIntHashItem;
begin
Result := False;
FLocker.Enter;
P := Find(Key)^;
if P <> nil then begin
OutValue := P^.AsInt64;
Result := True;
end;
FLocker.Leave;
end;
procedure TIntHash.UnLock;
begin
FLocker.Leave;
end;
function TIntHash.ValueOf(const Key: THashType; const DefaultValue: Number): Number;
var
P: PIntHashItem;
begin
FLocker.Enter;
P := Find(Key)^;
if P <> nil then
Result := P^.Value
else
Result := DefaultValue;
FLocker.Leave;
end;
{ THashList }
procedure THashList.Reset;
begin
Next := nil;
Data := nil;
end;
{ THashMapValue }
function THashMapValue.GetNumKey: Number;
begin
Result := PNumber(@Key)^;
end;
procedure THashMapValue.SetNumKey(const AValue: Number);
begin
PNumber(@Key)^ := THashType(AValue);
end;
{ TYXDHashTable }
procedure TYXDHashTable.Add(AData: Pointer; AHash: THashType);
var
AIndex: Integer;
ABucket: PHashList;
begin
ABucket := FPool.Pop;
ABucket.Hash := AHash;
ABucket.Data := AData;
AIndex := AHash mod Cardinal(Length(FBuckets));
ABucket.Next := FBuckets[AIndex];
FBuckets[AIndex] := ABucket;
Inc(FCount);
{$IFDEF AUTORESIE}
if (FCount div Length(FBuckets)) > 3 then
Resize(0);
{$ENDIF}
end;
procedure TYXDHashTable.Clear;
var
I,H: Integer;
ABucket: PHashList;
begin
H := High(FBuckets);
for I := 0 to H do begin
ABucket := FBuckets[I];
while ABucket <> nil do begin
FBuckets[I] := ABucket.Next;
DoDelete(ABucket.Hash, ABucket.Data);
FreeBucket(ABucket);
ABucket := FBuckets[I];
end;
end;
FPool.Clear;
FCount := 0;
end;
function TYXDHashTable.Compare(Data1, Data2: Pointer;
var AResult: Integer): Boolean;
begin
if Assigned(FOnCompare) then begin
AResult := FOnCompare(Data1, Data2);
Result := True;
end else
Result := False;
end;
constructor TYXDHashTable.Create(ASize: Integer);
begin
//FPool := THashListPool.Create(8192, SizeOf(THashList));
FPool := TMemPool.Create(SizeOf(THashList), 1024);
if ASize = 0 then ASize := 17;
Resize(ASize);
end;
constructor TYXDHashTable.Create;
begin
Resize(0);
end;
procedure TYXDHashTable.Delete(AData: Pointer; AHash: THashType);
var
AIndex, ACompare: Integer;
AHashList, APrior: PHashList;
begin
AIndex := AHash mod Cardinal(Length(FBuckets));
AHashList := FBuckets[AIndex];
APrior := nil;
while Assigned(AHashList) do begin
// 同一数据,哈希值我们只能认为是相同,如果不同,找上帝去吧
if (AHashList.Data=AData) or ((Compare(AHashList.Data,AData,ACompare) and (ACompare=0))) then
begin
DoDelete(AHashList.Hash,AHashList.Data);
if Assigned(APrior) then
APrior.Next := AHashList.Next
else
FBuckets[AIndex] := AHashList.Next; // yangyxd 2014.10.8
FreeBucket(AHashList);
Dec(FCount);
Break;
end else begin
APrior := AHashList;
AHashList := APrior.Next;
end;
end;
end;
procedure TYXDHashTable.DeleteBucket(Index: Integer);
var
ABucket, P: PHashList;
begin
if (Index < 0) or (Index > High(FBuckets)) then Exit;
ABucket := FBuckets[Index];
FBuckets[Index] := nil;
while ABucket <> nil do begin
P := ABucket.Next;
DoDelete(ABucket.Hash, ABucket.Data);
FreeBucket(ABucket);
Dec(FCount);
ABucket := P;
end;
end;
destructor TYXDHashTable.Destroy;
begin
Clear;
FreeAndNil(FPool);
end;
procedure TYXDHashTable.DoDelete(AHash: THashType; AData: Pointer);
begin
if Assigned(FOnDelete) then
FOnDelete(Self, AHash, AData);
end;
function TYXDHashTable.Exists(AData: Pointer; AHash: THashType): Boolean;
var
AList: PHashList;
AResult: Integer;
begin
AList := FindFirst(AHash);
Result := False;
while AList <> nil do begin
if (AList.Data = AData) or (Compare(AList.Data,AData,AResult) and (AResult=0)) then begin
Result:=True;
Break;
end;
AList := FindNext(AList);
end;
end;
function TYXDHashTable.Find(AHash: THashType): PHashList;
var
AIndex: Integer;
AList, AItem: PHashList;
begin
AIndex := AHash mod Cardinal(Length(FBuckets));
Result := nil;
AList := FBuckets[AIndex];
while AList <> nil do begin
if AList.Hash = AHash then begin
New(AItem);
AItem.Data := AList.Data;
AItem.Next := Result;
AItem.Hash := AHash;
Result := AItem;
end;
AList := AList.Next;
end;
end;
function TYXDHashTable.Find(AData: Pointer; AHash: THashType): Pointer;
var
ACmpResult: Integer;
AList: PHashList;
begin
Result := nil;
AList := FindFirst(AHash);
while AList<>nil do begin
if (AList.Data = AData) or (Compare(AData, AList.Data, ACmpResult) and (ACmpResult=0)) then begin
Result := AList.Data;
Break;
end;
AList := AList.Next;
end;
end;
function TYXDHashTable.FindFirst(AHash: THashType): PHashList;
var
AIndex: Integer;
AList: PHashList;
begin
AIndex := AHash mod Cardinal(Length(FBuckets));
Result := nil;
AList := FBuckets[AIndex];
while AList <> nil do begin
if AList.Hash = AHash then begin
Result := AList;
Break;
end;
AList := AList.Next;
end;
end;
function TYXDHashTable.FindFirstData(AHash: THashType): Pointer;
begin
Result := FindFirst(AHash);
if Result <> nil then
Result := PHashList(Result).Data;
end;
function TYXDHashTable.FindNext(AList: PHashList): PHashList;
begin
Result := nil;
if Assigned(AList) then begin
Result := AList.Next;
while Result<>nil do begin
if Result.Hash=AList.Hash then
Break
else
Result := Result.Next;
end;
end;
end;
procedure TYXDHashTable.FreeBucket(var ABucket: PHashList);
begin
FPool.Push(ABucket);
end;
procedure TYXDHashTable.FreeHashList(AList: PHashList);
var
ANext: PHashList;
begin
while AList<>nil do begin
ANext := AList.Next;
FreeBucket(AList);
AList := ANext;
end;
end;
function TYXDHashTable.GetBucketCount: Integer;
begin
Result := Length(FBuckets);
end;
function TYXDHashTable.GetBuckets(AIndex: Integer): PHashList;
begin
Result := FBuckets[AIndex];
end;
function TYXDHashTable.GetMemSize: Int64;
begin
Result := Length(FBuckets) shl 2;
end;
procedure TYXDHashTable.Resize(ASize: Cardinal);
var
I, AIndex: Integer;
AHash: Cardinal;
ALastBuckets: THashArray;
AList, ANext: PHashList;
begin
if ASize = 0 then begin
ASize := CalcBucketSize(FCount);
if ASize = Cardinal(Length(FBuckets)) then
Exit;
end;
//桶尺寸变更后,重新分配元素所在的哈希桶,如果是自动调用的话,理想的结果就是一个桶有一个元素
if ASize <> Cardinal(Length(FBuckets)) then begin
ALastBuckets := FBuckets;
SetLength(FBuckets, ASize);
for I := 0 to ASize-1 do
FBuckets[I] := nil;
for I := 0 to High(ALastBuckets) do begin
AList := ALastBuckets[I];
while AList<>nil do begin
AHash := AList.Hash;
AIndex := AHash mod ASize;
ANext := AList.Next;
AList.Next := FBuckets[AIndex];
FBuckets[AIndex] := AList;
AList := ANext;
end;
end;
end;
end;
procedure TYXDHashTable.SetAutoSize(const Value: Boolean);
begin
if FAutoSize <> Value then begin
FAutoSize := Value;
if AutoSize then begin
if (FCount div Length(FBuckets)) > 3 then
Resize(0);
end;
end;
end;
procedure TYXDHashTable.Update(AData: Pointer; AOldHash, ANewHash: THashType);
var
AList, APrior: PHashList;
ACmpResult: Integer;
AIndex: Integer;
AChanged: Boolean;
begin
AChanged := False;
AIndex := AOldHash mod Cardinal(Length(FBuckets));
AList := FBuckets[AIndex];
APrior := nil;
while AList <> nil do begin
if (AList.Hash = AOldHash) then begin
if (AList.Data=AData) or (Compare(AData, AList.Data, ACmpResult) and (ACmpResult=0)) then begin
if Assigned(APrior) then
APrior.Next := AList.Next
else
FBuckets[AIndex] := AList.Next;
AList.Hash := ANewHash;
AIndex := ANewHash mod Cardinal(Length(FBuckets));
AList.Next := FBuckets[AIndex];
FBuckets[AIndex] := AList;
AChanged := True;
Break;
end;
end;
APrior := AList;
AList := AList.Next;
end;
if not AChanged then
Add(AData, ANewHash);
end;
{ TYXDHashMapTable }
procedure TYXDHashMapTable.Add(const Key: string; AData: PHashValue);
var
AIndex: THashType;
ABucket: PHashMapList;
begin
AIndex := HashOf(Key);
ABucket := Pointer(FListPool.Pop);
ABucket.Hash := AIndex;
AIndex := AIndex mod Cardinal(Length(FBuckets));
ABucket.Data := Pointer(NativeUInt(ABucket) + SizeOf(THashMapList));
Initialize(ABucket.Data.Key);
if AData <> nil then
ABucket.Data.Value := AData^
else
ABucket.Data.Value.Clear;
ABucket.Data.IsStrKey := True;
ABucket.Data.Key := Key;
ABucket.Next := FBuckets[AIndex];
FBuckets[AIndex] := Pointer(ABucket);
Inc(FCount);
{$IFDEF AUTORESIE}
if (FCount div Length(FBuckets)) > 3 then
Resize(0);
{$ENDIF}
DoAdd(ABucket);
end;
procedure TYXDHashMapTable.Add(const Key: Number; AData: PHashValue);
var
AIndex: THashType;
ABucket: PHashMapList;
begin
ABucket := Pointer(FListPool.Pop);
ABucket.Hash := THashType(Key);
AIndex := THashType(Key) mod Cardinal(Length(FBuckets));
ABucket.Data := Pointer(NativeUInt(ABucket) + SizeOf(THashMapList));
if AData <> nil then
ABucket.Data.Value := AData^
else
ABucket.Data.Value.Clear;
ABucket.Data.IsStrKey := False;
PDWORD(@ABucket.Data.Key)^ := THashType(Key);
ABucket.Next := FBuckets[AIndex];
FBuckets[AIndex] := Pointer(ABucket);
{$IFDEF AUTORESIE}
if (FCount div Length(FBuckets)) > 3 then
Resize(0);
{$ENDIF}
DoAdd(ABucket);
Inc(FCount);
end;
procedure TYXDHashMapTable.Add(const Key: string; AData: Integer);
var
AIndex: THashType;
ABucket: PHashMapList;
begin
AIndex := HashOf(Key);
ABucket := Pointer(FListPool.Pop);
ABucket.Hash := AIndex;
AIndex := AIndex mod Cardinal(Length(FBuckets));
ABucket.Data := Pointer(NativeUInt(ABucket) + SizeOf(THashMapList));
Initialize(ABucket.Data.Key);
ABucket.Data.Value.Data := Pointer(AData);
ABucket.Data.Value.Size := 0;
ABucket.Data.IsStrKey := True;
ABucket.Data.Key := Key;
ABucket.Next := FBuckets[AIndex];
FBuckets[AIndex] := Pointer(ABucket);
Inc(FCount);
{$IFDEF AUTORESIE}
if (FCount div Length(FBuckets)) > 3 then
Resize(0);
{$ENDIF}
DoAdd(ABucket);
end;
procedure TYXDHashMapTable.Add(const Key: Number; AData: Integer);
var
AIndex: THashType;
ABucket: PHashMapList;
begin
ABucket := Pointer(FListPool.Pop);
ABucket.Hash := THashType(Key);
AIndex := THashType(Key) mod Cardinal(Length(FBuckets));
ABucket.Data := Pointer(NativeUInt(ABucket) + SizeOf(THashMapList));
ABucket.Data.Value.Data := Pointer(AData);
ABucket.Data.Value.Size := 0;
ABucket.Data.IsStrKey := False;
PDWORD(@ABucket.Data.Key)^ := THashType(Key);
ABucket.Next := FBuckets[AIndex];
FBuckets[AIndex] := Pointer(ABucket);
Inc(FCount);
{$IFDEF AUTORESIE}
if (FCount div Length(FBuckets)) > 3 then
Resize(0);
{$ENDIF}
DoAdd(ABucket);
end;
procedure TYXDHashMapTable.Clear;
var
I: Integer;
P, N: PHashList;
begin
for I := 0 to High(FBuckets) do begin
P := FBuckets[I];
FBuckets[I] := nil;
while P <> nil do begin
N := P^.Next;
DoDelete(P.Hash, P.Data);
FreeBucket(P);
P := N;
end;
end;
FCount := 0;
FListPool.Clear;
FPool.Clear;
end;
constructor TYXDHashMapTable.Create(ASize: Integer);
begin
inherited;
FListPool := TMemPool.Create(HASHITEMSize, 1024);
end;
destructor TYXDHashMapTable.Destroy;
begin
inherited;
FreeAndNil(FListPool);
end;
procedure TYXDHashMapTable.DoAdd(ABucket: PHashMapList);
begin
end;
function TYXDHashMapTable.Exists(const Key: Number): Boolean;
begin
Result := Find(Key) <> nil;
end;
function TYXDHashMapTable.Exists(const Key: string): Boolean;
begin
Result := Find(Key) <> nil;
end;
function TYXDHashMapTable.Find(const Key: string): PHashMapValue;
var
AList: PHashList;
AHash: Cardinal;
begin
AHash := HashOf(Key);
AList := FBuckets[AHash mod Cardinal(Length(FBuckets))];
while AList <> nil do begin
if (AList.Hash = AHash) and (AList.Data <> nil) and (PHashMapValue(AList.Data).IsStrKey) and
(PHashMapValue(AList.Data).Key = Key) then begin
Result := AList.Data;
Exit;
end;
AList := AList.Next;
end;
Result := nil;
end;
function TYXDHashMapTable.Find(const Key: Number): PHashMapValue;
var
AList: PHashList;
AHash: THashType;
begin
AHash := THashType(Key);
AList := FBuckets[AHash mod Cardinal(Length(FBuckets))];
while AList <> nil do begin
if (AList.Hash = AHash) and (AList.Data <> nil) and (not PHashMapValue(AList.Data).IsStrKey) then begin
Result := AList.Data;
Exit;
end;
AList := AList.Next;
end;
Result := nil;
end;
function TYXDHashMapTable.FindList(const Key: Number): PPHashList;
begin
Result := @FBuckets[THashType(Key) mod Cardinal(Length(FBuckets))];
while Result^ <> nil do begin
if (Result^.Hash = THashType(Key)) and (Result^.Data <> nil) and
(not PHashMapValue(Result^.Data).IsStrKey) then
Break;
Result := @Result^.Next;
end;
end;
function TYXDHashMapTable.FindList(const Key: string): PPHashList;
var
AHash: Cardinal;
begin
AHash := HashOf(Key);
Result := @FBuckets[AHash mod Cardinal(Length(FBuckets))];
while Result^ <> nil do begin
if (Result^.Hash = AHash) and (Result^.Data <> nil) and (PHashMapValue(Result^.Data).IsStrKey) and
(PHashMapValue(Result^.Data).Key = Key) then begin
Break;
end;
Result := @Result^.Next;
end;
end;
procedure TYXDHashMapTable.FreeBucket(var ABucket: PHashList);
begin
if PHashMapList(ABucket).Data.IsStrKey then
Finalize(PHashMapList(ABucket).Data.Key);
FListPool.Push(ABucket);
end;
function TYXDHashMapTable.GetMemSize: Int64;
begin
Result := inherited GetMemSize;
end;
function TYXDHashMapTable.Remove(const Key: Number): Boolean;
var
AIndex: Integer;
AHash: THashType;
AHashList: PPHashList;
APrior: PHashList;
begin
Result := False;
AHash := THashType(Key);
AIndex := AHash mod Cardinal(Length(FBuckets));
AHashList := @FBuckets[AIndex];
while AHashList^ <> nil do begin
if (AHashList^.Hash = AHash) and (not PHashMapValue(AHashList^.Data).IsStrKey) then begin
APrior := AHashList^;
AHashList^ := APrior.Next;
DoDelete(APrior.Hash, APrior.Data);
FreeBucket(APrior);
Dec(FCount);
Result := True;
Break;
end else
AHashList := @AHashList^.Next;
end;
end;
function TYXDHashMapTable.Update(const Key: string;
Value: PHashValue): Boolean;
var
P: PHashMapValue;
begin
P := Find(Key);
if P <> nil then begin
if Value <> nil then
P.Value := Value^
else
P.Value.Clear;
Result := True;
end else
Result := False;
end;
function TYXDHashMapTable.Remove(const Key: string): Boolean;
var
AIndex: Integer;
AHash: Cardinal;
AHashList: PPHashList;
APrior: PHashList;
begin
Result := False;
AHash := HashOf(Key);
AIndex := AHash mod Cardinal(Length(FBuckets));
AHashList := @FBuckets[AIndex];
while AHashList^ <> nil do begin
if (AHashList^.Hash = AHash) and (PHashMapValue(AHashList^.Data).IsStrKey) and
(PHashMapValue(AHashList^.Data).Key = Key) then begin
APrior := AHashList^;
AHashList^ := APrior.Next;
DoDelete(APrior.Hash, APrior.Data);
FreeBucket(APrior);
Dec(FCount);
Result := True;
Break;
end else
AHashList := @AHashList^.Next;
end;
end;
function TYXDHashMapTable.ValueOf(const Key: string): PHashValue;
var
P: PHashMapValue;
begin
P := Find(Key);
if (P <> nil) then // and (P.Value.Size > 0) then
Result := @P.Value
else
Result := nil;
end;
function TYXDHashMapTable.ValueOf(const Key: Number): PHashValue;
var
P: PHashMapValue;
begin
P := Find(Key);
if (P <> nil) then // and (P.Value.Size > 0) then
Result := @P.Value
else
Result := nil;
end;
function TYXDHashMapTable.Update(const Key: Number; Value: PHashValue): Boolean;
var
P: PHashMapValue;
begin
P := Find(Key);
if P <> nil then begin
if Value <> nil then
P.Value := Value^
else
P.Value.Clear;
Result := True;
end else
Result := False;
end;
function TYXDHashMapTable.Remove(const P: PHashMapValue): Boolean;
begin
if P <> nil then begin
if P.IsStrKey then
Result := Remove(P.Key)
else
Result := Remove(P.GetNumKey)
end else
Result := False;
end;
{ TYXDHashMapList }
procedure TYXDHashMapList.Clear;
begin
FList.Clear;
inherited;
end;
constructor TYXDHashMapList.Create(ASize: Integer);
begin
inherited;
FList := TList.Create;
end;
procedure TYXDHashMapList.Delete(Index: Integer);
begin
if (index >= 0) and (Index < FCount) then
Remove(Items[index].Key);
end;
destructor TYXDHashMapList.Destroy;
begin
inherited;
FreeAndNil(FList);
end;
procedure TYXDHashMapList.DoAdd(ABucket: PHashMapList);
begin
FList.Add(ABucket.Data);
end;
procedure TYXDHashMapList.DoDelete(AHash: THashType; AData: Pointer);
begin
if Assigned(FOnDelete) then
FOnDelete(Self, AHash, AData);
if FList.Count > 0 then
FList.Remove(AData);
end;
function TYXDHashMapList.GetItem(Index: Integer): PHashMapValue;
begin
Result := FList.Items[index];
end;
{ TYXDHashMapLinkTable }
procedure TYXDHashMapLinkTable.Clear;
begin
if Assigned(Self) then begin
FreeLinkList;
inherited Clear;
end;
end;
constructor TYXDHashMapLinkTable.Create(ASize: Integer);
begin
inherited Create(ASize);
FFirst := nil;
FLast := nil;
FLinkHashPool := TMemPool.Create(SizeOf(THashList), 1024);
SetLength(ListBuckets, ASize);
end;
procedure TYXDHashMapLinkTable.Delete(Index: Integer);
var
P: PHashMapValue;
begin
P := GetItem(Index);
if P <> nil then
Remove(P.Key);
end;
destructor TYXDHashMapLinkTable.Destroy;
begin
inherited Destroy;
FreeAndNil(FLinkHashPool);
end;
procedure TYXDHashMapLinkTable.DoAdd(ABucket: PHashMapList);
var
AIndex: Integer;
AItem: PHashList;
P: PHashMapLinkItem;
begin
P := Pointer(FPool.Pop);
P.Value := ABucket.Data;
P.Next := nil;
if FFirst = nil then begin
P.Prev := nil;
FFirst := P;
FLast := FFirst;
end else begin
P.Prev := FLast;
FLast.Next := P;
FLast := P;
end;
// 添加到Hash表中
AIndex := NativeUInt(ABucket.Data) mod Cardinal(Length(ListBuckets));
AItem := ListBuckets[AIndex];
while AItem <> nil do begin
if AItem.Hash = THashType(ABucket.Data) then begin
AItem.Data := FLast;
Exit
end else
AItem := AItem.Next;
end;
AItem := FLinkHashPool.Pop;
AItem^.Hash := THashType(ABucket.Data);
AItem^.Data := FLast;
AItem^.Next := ListBuckets[AIndex];
ListBuckets[AIndex] := AItem;
end;
procedure TYXDHashMapLinkTable.DoDelete(AHash: THashType; AData: Pointer);
var
P: PHashMapLinkItem;
begin
P := FindLinkItem(AData, True);
if Assigned(FOnDelete) then begin
try
FOnDelete(Self, AHash, AData);
except
{$IFDEF MSWINDOWS}
OutputDebugString(PChar(Exception(ExceptObject).Message));
{$ENDIF}
end;
end;
if P = nil then Exit;
if P = FFirst then begin
FFirst := FFirst.Next;
if FFirst = nil then
FLast := nil
else
FFirst.Prev := nil;
end else if P = FLast then begin
FLast := P.Prev;
if FLast = nil then
FFirst := nil
else
FLast.Next := nil;
end else begin
P.Prev.Next := P.Next;
P.Next.Prev := P.Prev;
end;
FPool.Push(Pointer(P));
end;
function TYXDHashMapLinkTable.FindLinkItem(AData: Pointer;
isDelete: Boolean): PHashMapLinkItem;
var
Prev: PPHashList;
P: PHashList;
begin
Prev := @ListBuckets[NativeUInt(AData) mod Cardinal(Length(ListBuckets))];
while Prev^ <> nil do begin
if PHashMapLinkItem(Prev^.Data).Value = AData then begin
if isDelete then begin
P := Prev^;
Result := P.Data;
Prev^ := P.Next;
FLinkHashPool.Push(P);
end else
Result := Prev^.Data;
Exit;
end else
Prev := @Prev^.Next;
end;
Result := nil;
end;
procedure TYXDHashMapLinkTable.FreeLinkList;
var
P, N: PHashMapLinkItem;
I: Integer;
P1, P2: PHashList;
begin
P := FFirst;
while P <> nil do begin
N := P.Next;
FPool.Push(Pointer(P));
P := N;
end;
if Length(ListBuckets) > 0 then begin
for I := 0 to Length(ListBuckets) - 1 do begin
P1 := ListBuckets[i];
ListBuckets[i] := nil;
while P1 <> nil do begin
P2 := P1.Next;
FLinkHashPool.Push(P1);
P1 := P2;
end;
end;
end;
FLinkHashPool.Clear;
FFirst := nil;
FLast := nil;
end;
function TYXDHashMapLinkTable.GetEnumerator: TYXDHashMapLinkTableEnumerator;
begin
Result := TYXDHashMapLinkTableEnumerator.Create(Self);
end;
function TYXDHashMapLinkTable.GetItem(Index: Integer): PHashMapValue;
var
P: PHashMapLinkItem;
I: Integer;
begin
if Index > (FCount shr 1) then begin
if Index < FCount then begin
P := FLast;
if P <> nil then begin
for I := FCount - Index - 1 downto 1 do
P := P.Prev;
Result := P.Value;
Exit;
end;
end;
end else if Index > -1 then begin
P := FFirst;
if P <> nil then begin
for I := 0 to Index - 1 do
P := P.Next;
Result := P.Value;
Exit;
end;
end;
Result := nil;
end;
function TYXDHashMapLinkTable.GetLast: PHashMapValue;
begin
if FLast <> nil then
Result := FLast.Value
else
Result := nil;
end;
function TYXDHashMapLinkTable.GetMemSize: Int64;
begin
Result := inherited GetMemSize;
Inc(Result, Length(ListBuckets) shl 2);
end;
{ TYXDHashMapLinkTableEnumerator }
constructor TYXDHashMapLinkTableEnumerator.Create(AList: TYXDHashMapLinkTable);
begin
FItem := AList.FFirst;
end;
function TYXDHashMapLinkTableEnumerator.GetCurrent: PHashMapLinkItem;
begin
Result := FItem;
FItem := FItem.Next;
end;
function TYXDHashMapLinkTableEnumerator.MoveNext: Boolean;
begin
Result := FItem <> nil;
end;
end.
|
{-*- Mode: Pascal -*-}
Function TrackButton (theButton: Buttype):boolean;
{track a mouse-down in a button}
var MPoint :point; {current mouse position}
invert, {state of button inversion}
tbool :boolean; {temporary var for same}
begin
InvertRect (theButton.butrect);
invert := true; {start with button pressed in inverted}
while stilldown do
begin
getmouse (MPoint);
tbool := PtInRect (MPoint, theButton.butrect);
if not (invert = tbool) then {the state has changed, so invert it}
InvertRect (theButton.butrect);
invert := tbool;
end; {until the mouse button is released}
ShowButton (theButton); {draw button without hiliting}
trackbut := invert; {return PtInRect for mouse, button-rect}
end;
Procedure ReadClick (Time :longint; Place :point);
{Set the value of DblClick to true or false based upon whether or not the
previous mouse click is within 1/2 second of this mouse click, and if the
mouse position has not changed within 3 pixels vertically or horizontally
of the last click location.}
var
temp: boolean; {for triple clicks}
begin
temp := DblClick; {remember previous double click state}
DblClick := ((Time - LastMClik < 30 ) and
((abs (LastMPos.v-Place.v) < 3) and
(abs (LastMPos.h-Place.h) < 3)));
TriClick := (DblClick and temp);
if TriClick then DblClick := false;
LastMPos := place;
LastMClik := Time;
end;
|
unit MESA;
interface
uses
Classes,
DB,
SysUtils,
Generics.Collections,
ormbr.mapping.attributes,
ormbr.types.mapping,
ormbr.types.lazy,
ormbr.types.nullable,
ormbr.mapping.register;
type
[Entity]
[Table('MESA','')]
[PrimaryKey('ID', AutoInc, NoSort, True, 'Chave primária')]
TMESA = class
private
FID: Integer;
FNOMECLIENTE: String;
fMESADFECHAMENTO: TDate;
fMESACSTATUS: String;
FVENDICOD: Integer;
fMESAN3VLRTOTAL: Double;
fMESADABERTURA: TDate;
FMESAICAPAC: Integer;
fMESADULTPED: TDate;
FOBS: String;
fPedidoAberto: String;
fMESA: Integer;
{ Private declarations }
public
{ Public declarations }
[Restrictions([NoUpdate, NotNull])]
[Column('MESAICOD', ftInteger)]
[Dictionary('MESAICOD','Mensagem de validação','','','',taCenter)]
property id: Integer read FID write FID;
[Column('MESAICAPAC', ftInteger)]
property MESAICAPAC: Integer read FMESAICAPAC write FMESAICAPAC;
[Column('NOMECLIENTE', ftString, 60)]
property NOMECLIENTE:String read FNOMECLIENTE write FNOMECLIENTE;
[Column('MESACSTATUS', ftString, 1)]
property MESACSTATUS:String read fMESACSTATUS write fMESACSTATUS;
[Column('MESADABERTURA', ftDate)]
property MESADABERTURA: TDate read fMESADABERTURA write fMESADABERTURA;
[Column('MESADULTPED', ftDate)]
property MESADULTPED: TDate read fMESADULTPED write fMESADULTPED;
[Column('MESADFECHAMENTO', ftDate)]
property MESADFECHAMENTO: TDate read fMESADFECHAMENTO write fMESADFECHAMENTO;
[Column('MESAN3VLRTOTAL', ftFloat)]
property MESAN3VLRTOTAL: Double read fMESAN3VLRTOTAL write fMESAN3VLRTOTAL;
[Column('VENDICOD', ftInteger)]
property VENDICOD: Integer read FVENDICOD write FVENDICOD;
property PedidoAberto:String read fPedidoAberto write fPedidoAberto;
property OBS:String read FOBS write FOBS;
property MESA:Integer read fMESA write fMESA;
end;
implementation
{ TMESA }
initialization
TRegisterClass.RegisterEntity(TMESA);
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC SAP SQL Anywhere Call Interface }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$ALIGN OFF}
unit FireDAC.Phys.ASACli;
interface
uses
FireDAC.Stan.Consts;
type
// ---------------------------------------------------------------------------
// constants for return values of DOS executables
// ---------------------------------------------------------------------------
an_exit_code = ShortInt;
const
EXIT_OKAY = 0; // everything is okay
EXIT_FAIL = 1; // general failure
EXIT_BAD_DATA = 2; // invalid file format, etc.
EXIT_FILE_ERROR = 3; // file not found, unable to open, etc.
EXIT_OUT_OF_MEMORY = 4; // out of memory
EXIT_BREAK = 5; // terminated by user
EXIT_COMMUNICATIONS_FAIL = 6; // failed communications
EXIT_MISSING_DATABASE = 7; // missing required db name
EXIT_PROTOCOL_MISMATCH = 8; // client/server protocol mismatch
EXIT_UNABLE_TO_CONNECT = 9; // unable to connect to db
EXIT_ENGINE_NOT_RUNNING = 10; // database not running
EXIT_SERVER_NOT_FOUND = 11; // server not running
EXIT_BAD_ENCRYPT_KEY = 12; // missing or bad encryption key
EXIT_DB_VER_NEWER = 13; // server must be upgraded to run db
EXIT_FILE_INVALID_DB = 14; // file is not a database
EXIT_LOG_FILE_ERROR = 15; // log file was missing or
// other log file error
EXIT_FILE_IN_USE = 16; // file in use
EXIT_FATAL_ERROR = 17; // fatal error or assertion occurred
EXIT_MISSING_LICENSE_FILE = 18; // missing server license file
EXIT_BACKGROUND_SYNC_ABORTED = 19; // background synchronization aborted
// to let higher priority operations proceed
EXIT_FILE_ACCESS_DENIED = 20; // access to database file denied
EXIT_USAGE = 255; // invalid parameters on command line
const
{$IFDEF POSIX}
C_SQLAnywhere16Lib = 'libdbodbc16_r' + C_FD_DLLExt;
C_DBTool = 'libdbtool%d_r' + C_FD_DLLExt;
{$ENDIF}
{$IFDEF MSWINDOWS}
C_DBTool = 'DBTOOL%d.DLL';
{$ENDIF}
DB_TOOLS_VERSION_NUMBER = 12000;
type
{$IFDEF POSIX}
a_bit_field = Cardinal;
a_bit_short = Cardinal;
{$ENDIF}
{$IFDEF MSWINDOWS}
a_bit_field = Byte;
a_bit_short = Word;
{$ENDIF}
a_sql_int32 = Integer;
a_sql_uint32 = Cardinal;
a_char = Byte;
Pa_char = ^a_char;
P_name = ^a_name;
a_name = record
next: P_name;
name: array [0 .. 0] of a_char;
end;
MSG_CALLBACK = function (str: Pa_char): ShortInt; stdcall;
STATUS_CALLBACK = function (code: a_sql_uint32; data: Pointer; length: a_sql_uint32): ShortInt; stdcall;
MSG_QUEUE_CALLBACK = function (code: a_sql_uint32): ShortInt; stdcall;
SET_WINDOW_TITLE_CALLBACK = function (str: Pa_char): ShortInt; stdcall;
SET_TRAY_MESSAGE_CALLBACK = function (str: Pa_char): ShortInt; stdcall;
SET_PROGRESS_CALLBACK = function (index: a_sql_uint32; max: a_sql_uint32): ShortInt; stdcall;
USAGE_CALLBACK = function (str: Pa_char): ShortInt; stdcall;
SPLASH_CALLBACK = function (title, body: Pa_char): ShortInt; stdcall;
// ---------------------------------------------------------------------------
// initialization (DBTools) interface
// ---------------------------------------------------------------------------
P_dbtools_info = ^a_dbtools_info;
a_dbtools_info = record
errorrtn: MSG_CALLBACK;
end;
TDBToolsInit = function (ApInfo: P_dbtools_info): ShortInt; stdcall;
TDBToolsFini = function (ApInfo: P_dbtools_info): ShortInt; stdcall;
// ---------------------------------------------------------------------------
// get shared library version
// ---------------------------------------------------------------------------
TDBToolsVersion = function: ShortInt; stdcall;
// ---------------------------------------------------------------------------
// backup database (DBBACKUP) interface
// ---------------------------------------------------------------------------
{
Example:
a_backup_db Structure settings for equivalent of following command:
dbbackup -c "uid=dba;pwd=sql;dbf=d:\db\demo.db" c:\temp
version DB_TOOLS_VERSION_NUMBER
errorrtn 0x0040.... callback_error(char *)
msgrtn 0x0040.... callback_usage(char *)
confirmrtn 0x0040.... callback_confirm(char *)
statusrtn 0x0040.... callback_status(char *)
output_dir "c:\\temp"
connectparms "uid=dba;pwd=sql;dbf=d:\\db\\demo.db"
backup_database 1
backup_logfile 1
}
a_chkpt_log_type = (
BACKUP_CHKPT_LOG_COPY,
BACKUP_CHKPT_LOG_NOCOPY,
BACKUP_CHKPT_LOG_RECOVER,
BACKUP_CHKPT_LOG_AUTO,
BACKUP_CHKPT_LOG_DEFAULT
);
const
CBDB_F1_backup_database = $01; // dbbackup -d sets TRUE
CBDB_F1_backup_logfile = $02; // dbbackup -t sets TRUE
CBDB_F1__unused1 = $04; // (obsolete)
CBDB_F1_no_confirm = $08; // dbbackup -y sets TRUE
CBDB_F1_quiet = $10; // dbbackup -q sets TRUE
CBDB_F1_rename_log = $20; // dbbackup -r sets TRUE
CBDB_F1_truncate_log = $40; // dbbackup -x sets TRUE
CBDB_F1_rename_local_log = $80; // dbbackup -n sets TRUE
CBDB_F2_server_backup = $01; // dbbackup -s sets TRUE
CBDB_F3_backup_database = $0001; // dbbackup -d sets TRUE
CBDB_F3_backup_logfile = $0002; // dbbackup -t sets TRUE
CBDB_F3_no_confirm = $0004; // dbbackup -y sets TRUE
CBDB_F3_quiet = $0008; // dbbackup -q sets TRUE
CBDB_F3_rename_log = $0010; // dbbackup -r sets TRUE
CBDB_F3_truncate_log = $0020; // dbbackup -x sets TRUE
CBDB_F3_rename_local_log = $0040; // dbbackup -n sets TRUE
CBDB_F3_server_backup = $0080; // dbbackup -s sets TRUE
CBDB_F3_progress_messages= $0100; // dbbackup -p sets TRUE
type
P_backup_db = Pointer;
a_backup_db_v12 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
confirmrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
output_dir: Pa_char; // set this to folder for backup files
connectparms: Pa_char; // connection parameters
hotlog_filename: Pa_char; // dbbackup -l sets name
page_blocksize: a_sql_uint32; // dbbackup -b sets
chkpt_log_type: a_char; // dbbackup -k sets
backup_interrupted: a_char; // backup interrupted if non-zero
flags1: a_bit_short; // -> CBDB_F3
end;
a_backup_db_v11 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
output_dir: Pa_char; // set this to folder for backup files
connectparms: Pa_char; // connection parameters
confirmrtn: MSG_CALLBACK;
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
flags1: a_bit_field; // -> CBDB_F1
hotlog_filename: Pa_char; // dbbackup -l sets name
backup_interrupted: a_char; // backup interrupted if non-zero
flags2: a_bit_field; // -> CBDB_F2
// Following fields are new with 10.0
chkpt_log_type: a_chkpt_log_type; // dbbackup -k sets
page_blocksize: a_sql_uint32; // dbbackup -b sets
end;
a_backup_db_v10 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
output_dir: Pa_char; // set this to folder for backup files
connectparms: Pa_char; // connection parameters
_unused0: Pa_char; // (obsolete)
confirmrtn: MSG_CALLBACK;
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
flags1: a_bit_field; // -> CBDB_F1
hotlog_filename: Pa_char; // dbbackup -l sets name
backup_interrupted: a_char; // backup interrupted if non-zero
flags2: a_bit_field; // -> CBDB_F2
// Following fields are new with 10.0
chkpt_log_type: a_chkpt_log_type; // dbbackup -k sets
page_blocksize: a_sql_uint32; // dbbackup -b sets
end;
a_backup_db_v9 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
output_dir: Pa_char; // set this to folder for backup files
connectparms: Pa_char; // connection parameters
startline: Pa_char; // (NULL for default start line)
confirmrtn: MSG_CALLBACK;
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
flags1: a_bit_field; // -> CBDB_F1
hotlog_filename: Pa_char; // dbbackup -l sets name
backup_interrupted: a_char; // backup interrupted if non-zero
end;
TDBBackup = function (ApInfo: P_backup_db): ShortInt; stdcall;
// ---------------------------------------------------------------------------
// validate the tables of a database (DBVALID)
// ---------------------------------------------------------------------------
a_validate_type = (
VALIDATE_NORMAL,
VALIDATE_DATA,
VALIDATE_INDEX,
VALIDATE_EXPRESS,
VALIDATE_FULL,
VALIDATE_CHECKSUM,
VALIDATE_DATABASE,
VALIDATE_COMPLETE
);
const
CVDB_F1_quiet = $01;
CVDB_F1_index = $02;
type
P_validate_db = Pointer;
a_validate_db_v12 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
connectparms: Pa_char; // connection parameters
tables: p_name;
_type: a_validate_type;
flags1: a_bit_field;
end;
a_validate_db_v11 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
connectparms: Pa_char; // connection parameters
tables: p_name;
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
flags1: a_bit_field;
_type: a_validate_type;
end;
a_validate_db_v10 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
connectparms: Pa_char; // connection parameters
_unused1: Pa_char; // (obsolete)
tables: p_name;
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
flags1: a_bit_field;
_type: a_validate_type;
end;
a_validate_db_v9 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
connectparms: Pa_char; // connection parameters
startline: Pa_char; // (NULL for default start line)
tables: p_name;
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
flags1: a_bit_field;
_type: a_validate_type;
end;
a_validate_db_v5 = record
version: Word; // set this to DB_TOOLS_VERSION_NUMBER
connectparms: Pa_char; // connection parameters
startline: Pa_char; // (NULL for default start line)
tables: p_name;
errorrtn: MSG_CALLBACK;
msgrtn: MSG_CALLBACK;
statusrtn: MSG_CALLBACK;
flags1: a_bit_field;
end;
TDBValidate = function (ApInfo: P_validate_db): ShortInt; stdcall;
implementation
end.
|
unit AdapterMain;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
sgcWebSocket_Classes, sgcWebSocket_Client, sgcWebSocket, sgcWebSocket_Server,
FMX.Controls.Presentation, FMX.StdCtrls, FMX.Objects, FMX.Effects,
FMX.Layouts, FMX.ListBox, FMX.ScrollBox, FMX.Memo,
sgcWebSocket_Client_SocketIO, StrUtils, uJSON;
type
TForm1 = class(TForm)
processingListener: TsgcWebSocketServer;
Image1: TImage;
Button1: TButton;
Panel1: TPanel;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
StyleBook1: TStyleBook;
Memo1: TMemo;
mainListener: TsgcWebSocketClient_SocketIO;
Timer1: TTimer;
procedure log(S: String);
procedure processingListenerConnect(Connection: TsgcWSConnection);
procedure processingListenerMessage(Connection: TsgcWSConnection;
const Text: string);
procedure MessageReceive(Event: String; MData: JSONObject);
procedure Button1Click(Sender: TObject);
procedure processingListenerDisconnect(Connection: TsgcWSConnection;
Code: Integer);
procedure mainListenerMessage(Connection: TsgcWSConnection;
const Text: string);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.fmx}
procedure TForm1.log(S: string);
begin
Memo1.Lines.Append(S);
//Memo1.VScrollBar.Value := Memo1.VScrollBar.Max;
end;
procedure TForm1.MessageReceive(Event: string; MData: JSONObject);
begin
if Event = 'who_are_you' then begin
Log('Succesfully informed to main server that I am an adapter.');
mainListener.WriteData('42["iamadapter"]');
end;
if Event = 'data' then begin
ProcessingListener.Broadcast(MData.toString);
end;
MData.Clean;
end;
procedure TForm1.mainListenerMessage(Connection: TsgcWSConnection;
const Text: string);
var
JSONArr : JSONArray;
B : JSONObject;
A: String;
begin
if AnsiStartsStr('42', Text) then begin
try
JSONArr := JSONArray.create(Copy(Text,3,Length(Text)-2));
A := JSONArr.getString(0);
B := JSONArr.getJSONObject(1);
MessageReceive(A,B);
log('Raw data: ' + Copy(Text,3,Length(Text)-2));
finally
B.Clean;
JSONArr.Clean;
end;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
processingListener.Active := True;
mainListener.Active := True;
Timer1.Enabled := True;
log('Adapting Service is started.');
end;
procedure TForm1.processingListenerConnect(Connection: TsgcWSConnection);
begin
log('Processing PApplet is connected.');
end;
procedure TForm1.processingListenerDisconnect(Connection: TsgcWSConnection;
Code: Integer);
begin
log('Processing PApplet is disconnected.');
end;
procedure TForm1.processingListenerMessage(Connection: TsgcWSConnection;
const Text: string);
begin
log('PApplet said: ' + text);
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
if mainListener.Active = false then mainListener.Active := True;
mainListener.WriteData('42["hb"]');
end;
end.
|
unit ACBrSerialToshiba;
{**************************************************************************}
{ }
{ This C DLL header file first (automatic) conversion generated by: }
{ HeadConv 4.0 (c) 2000 by Bob Swart (aka Dr.Bob - www.drbob42.com) }
{ Final Delphi-Jedi (Darth) command-line units edition }
{ }
{ Generated Date: 06/12/2016 }
{ Generated Time: 13:20:22 }
{ }
{**************************************************************************}
interface
uses
{$IFDEF WIN32}
Windows, System.SysUtils;
{$ELSE}
Wintypes, WinProcs;
{$ENDIF}
{=> TGCSSUREMARK.H <=}
{+// }
{-* File: tgcs1nr.h }
{-* var Author: io Tofanelli }
{-* }
{-* Arquivo header das funcoes exportadas da biblioteca TGCSSureMark }
{-* }
{-* Created on 5 de Marco de 2013, 08:51 }
{= }
{$IFNDEF TGCS1NR_H}
{$DEFINE TGCS1NR_H}
const
VERSAO = '1.3.7.0';
{$IFNDEF TRUE}
const
TRUE = 1;
{$ENDIF}
{$IFNDEF FALSE}
const
FALSE = 0;
{$ENDIF}
{/// Bibliotecas especificas de cada sistema operacional }
{$IFDEF __linux__}
{///linux code goes here }
{$DEFINE EXPORT_DLL}
{$DEFINE CALL_TYPE}
{$ELSE _WIN32_}
{/// windows code goes here }
//const
type
EXPORT_DLL = integer;// 'TGCSSureMark.dll';// //__declspec(dllexport);
//const
// CALL_TYPE = stdcall;
{$DEFINE EXPORT_DLL}
{$DEFINE CALL_TYPE}
{$ELSE}
{$DEFINE EXPORT_DLL}
{$DEFINE CALL_TYPE}
{$ENDIF}
{/// Caracteres de comandos }
const
NUL = $00;
const
SOH = $01;
const
HTAB = $09;
const
LF = $0A;
const
CR = $0D;
const
ESC = $1B;
const
GS = $1D;
{/// Bits em um byte }
const
BIT0 = 1;
const
BIT1 = 2;
const
BIT2 = 4;
const
BIT3 = 8;
const
BIT4 = 16;
const
BIT5 = 32;
const
BIT6 = 64;
const
BIT7 = 128;
const
BITS_POR_BYTE = 8;
{///Arquivos utilizados na biblioteca }
const
NOME_ARQUIVO_LOG = 'TGCSSureMark';
const
ARQUIVO_NVS = 'TGCSSureMarkNVS.bin';
const
ARQUIVO_LOG = 'TGCSSureMark.log';
const
ARQUIVO_CONF_COMM = 'TGCSSureMarkComm.ini';
const
ARQUIVO_CONF_GERAL = 'TGCSSureMarkConf.ini';
const
TAMANHO_STATUS_BYTES = 16; {//Tamanho do buffer de status}
const
TAMANHO_STATUS_BYTES_COM_CONTADOR = 18; {//Tamanho do buffer de status com os dois bytes iniciais de contagem}
const
TAMANHO_VERSAO_LIB_BYTES = 8; {//Tamanho do buffer de versao da biblioteca}
const
TAMANHO_VERSAO_FIRMWARE_BYTES = 2; {//Tamanho do buffer de versao do firmware}
const
TAMANHO_MAXIMO_RESULTADO_CMC7 = 67;
const
TAMANHO_BUFFER_IMPRESSAO = 32768;
const
TAMANHO_MAXIMO_LINHA_CHEQUE = 86;
const
TAMANHO_STATUS_MODELO_IMPRESSORA = 1;
const
TAMANHO_STATUS_CODIFICACAO_CARACTERES = 1;
const
TAMANHO_STATUS_DOCUMENTO = 1;
const
TAMANHO_STATUS_PAPEL = 1;
const
TAMANHO_STATUS_GAVETA = 1;
const
TAMANHO_STATUS_TAMPA = 1;
const
TAMANHO_STATUS_LOGO_ID = 1;
const
TAMANHO_STATUS_MENSAGEM_ID = 1;
const
TAMANHO_MAXIMO_LINHA_AUTENTICACAO = 47;
{///modelos das impressoras suportadas }
const
MODELO_IMPRESSORA_2CR = $9E;
const
MODELO_IMPRESSORA_1NR = $80;
{/// Tipos de codigos de barras }
const
CODIGO_BARRAS_UPCA = 0;
const
CODIGO_BARRAS_UPCE = 1;
const
CODIGO_BARRAS_JAN13 = 2;
const
CODIGO_BARRAS_JAN8 = 3;
const
CODIGO_BARRAS_CODE39 = 4;
const
CODIGO_BARRAS_ITF = 5;
const
CODIGO_BARRAS_CODABAR = 6;
const
CODIGO_BARRAS_CODE128C = 7;
const
CODIGO_BARRAS_CODE93 = 8;
const
CODIGO_BARRAS_CODE128ABC = 9;
{///Identificacao do SET utilizado do CODE 128 }
const
CODE128_SET_A = 103;
const
CODE128_SET_B = 104;
const
CODE128_SET_C = 105;
{/// QR CODE }
const
QRCODE_TAM_MAX = 1000;
const
QRCODE_MODO_CODIFICACAO_BYTE = 0;
const
QRCODE_MODO_CODIFICACAO_ALFANUMERICO = 1;
const
QRCODE_MODO_CODIFICACAO_NUMERICO = 2;
const
QRCODE_MODO_CODIFICACAO_KANJI = 3;
const
QRCODE_MODO_CODIFICACAO_ECI = 4;
const
QRCODE_MODO_CODIFICACAO_MIXING = 5;
const
QRCODE_ERROR_L7 = 0;
const
QRCODE_ERROR_M15 = 1;
const
QRCODE_ERROR_Q25 = 2;
const
QRCODE_ERROR_H30 = 3;
const
QRCODE_ECI_PDF417_DEFAULT_GLI = 0;
const
QRCODE_ECI_PDF417_LATIN1_GLI = 1;
const
QRCODE_ECI_PDF417_DEFAULT_ECI = 2;
const
QRCODE_ECI_ISO8859_1 = 3;
const
QRCODE_ECI_ISO8859_2 = 4;
const
QRCODE_ECI_ISO8859_3 = 5;
const
QRCODE_ECI_ISO8859_4 = 6;
const
QRCODE_ECI_ISO8859_5 = 7;
const
QRCODE_ECI_ISO8859_6 = 8;
const
QRCODE_ECI_ISO8859_7 = 9;
const
QRCODE_ECI_ISO8859_8 = 10;
const
QRCODE_ECI_ISO8859_9 = 11;
const
QRCODE_ECI_ISO8859_10 = 12;
const
QRCODE_ECI_ISO8859_11 = 13;
const
QRCODE_ECI_ISO8859_12 = 14;
const
QRCODE_ECI_ISO8859_13 = 15;
const
QRCODE_ECI_ISO8859_14 = 16;
const
QRCODE_ECI_ISO8859_15 = 17;
const
QRCODE_ECI_ISO8859_16 = 18;
const
QRCODE_ECI_SJIS = 20;
const
QRCODE_ECI_UTF8 = 26;
{///posicoes HRI dos codigos de barras }
const
CODIGO_BARRAS_HRI_NAO_IMPRESSO = 0;
const
CODIGO_BARRAS_HRI_ACIMA = 1;
const
CODIGO_BARRAS_HRI_ABAIXO = 2;
const
CODIGO_BARRAS_HRI_ACIMA_ABAIXO = 3;
{///fontes HRI }
const
CODIGO_BARRAS_FONTE_A = 0;
const
CODIGO_BARRAS_FONTE_B = 1;
{///alinhamentos do texto }
const
ALINHAMENTO_TEXTO_A_ESQUERDA = 0;
const
ALINHAMENTO_TEXTO_CENTRO = 1;
const
ALINHAMENTO_TEXTO_A_DIREITA = 2;
{///status papel }
const
STATUS_SEM_PAPEL = 3;
const
STATUS_PAPEL_NIVEL_CRITICO = 2;
const
STATUS_POUCO_PAPEL = 1;
const
STATUS_PAPEL_OK = 0;
{///status documento }
const
STATUS_DOCUMENTO_SENSOR_FRONTAL_SUPERIOR = 3;
const
STATUS_DOCUMENTO_SENSOR_SUPERIOR = 2;
const
STATUS_DOCUMENTO_SENSOR_FRONTAL = 1;
const
STATUS_SEM_DOCUMENTO = 0;
{/// configuracao de impressao em cores }
const
COR_FRACA_DESABILITADA = 0;
const
COR_FRACA_CARACTERE_COMPLETO = 1;
const
COR_FRACA_MEIO_CARACTERE = 2;
{/// Paginas de codificacao de caracteres suportados pela impressora }
const
QUANTIDADE_CODIFICACOES = 25;
const
CODIFICACAO_437 = 0;
const
CODIFICACAO_858 = 1;
const
CODIFICACAO_863 = 2;
const
CODIFICACAO_860 = 3;
const
CODIFICACAO_865 = 4;
const
CODIFICACAO_GENERICA = 5;
const
CODIFICACAO_DEFINIDA_PELO_USUARIO = 6;
const
CODIFICACAO_869 = 7;
const
CODIFICACAO_857 = 8;
const
CODIFICACAO_864 = 9;
const
CODIFICACAO_867 = 10;
const
CODIFICACAO_852 = 11;
const
CODIFICACAO_848 = 12;
const
CODIFICACAO_866 = 13;
const
CODIFICACAO_872 = 14;
const
CODIFICACAO_775 = 15;
const
CODIFICACAO_861 = 16;
const
CODIFICACAO_1250 = 17;
const
CODIFICACAO_1251 = 18;
const
CODIFICACAO_1252 = 19;
const
CODIFICACAO_1253 = 20;
const
CODIFICACAO_1254 = 21;
const
CODIFICACAO_1255 = 22;
const
CODIFICACAO_1256 = 23;
const
CODIFICACAO_1257 = 24;
const
CODIFICACAO_DEFINIDA_PELO_USUARIO_1 = 101;
const
CODIFICACAO_DEFINIDA_PELO_USUARIO_2 = 102;
const
CODIFICACAO_DEFINIDA_PELO_USUARIO_3 = 103;
const
CODIFICACAO_DEFINIDA_PELO_USUARIO_4 = 104;
{/// Lista de codigo de erros }
const
OK = 0;
const
ERRO_PARAMETRO_INVALIDO = 1;
const
ERRO_EXECUCAO_FUNCAO = 2;
const
ERRO_SO_NAO_SUPORTADO = 3;
const
ERRO_TIMEOUT_ENVIO = 4;
const
ERRO_TIMEOUT_RESPOSTA = 5;
const
ERRO_ENVIO_COMANDO = 6;
const
ERRO_ABRIR_PORTA_SERIAL = 7;
const
ERRO_FECHAR_PORTA_SERIAL = 8;
const
ERRO_CONFIGURAR_PORTA_SERIAL = 9;
const
ERRO_TIMEOUT = 10;
const
ERRO_PORTA_SERIAL_NAO_INICIALIZADA = 11;
const
ERRO_NVS_NAO_ENCONTRADO = 12;
const
ERRO_ALOCAR_MEMORIA = 13;
const
ERRO_LIMPAR_PORTA_SERIAL = 14;
const
ERRO_TAMPA_ABERTA = 15;
const
ERRO_FIM_PAPEL = 16;
const
ERRO_COMUNICACAO = 17;
const
ERRO_BUFFER_SUSPENSO = 18;
const
ERRO_BUFFER_CHEIO = 19;
const
ERRO_COMANDO_REJEITADO = 20;
const
ERRO_ACESSO_PORTA = 21;
const
ERRO_FIM_PAPEL_IMPRESSAO = 22;
const
ERRO_TAMPA_ABERTA_IMPRESSAO = 23;
const
ERRO_BUFFER_VAZIO = 24;
const
ERRO_CONVERSAO_CARACTERES_NAO_SUPORTADA = 25;
const
ERRO_TEXTO_NAO_CADASTRADA = 26;
const
ERRO_TEXTO_JA_CADASTRADA = 27;
const
ERRO_ABRIR_ARQUIVO = 28;
const
ERRO_LEITURA_ARQUIVO = 29;
const
ERRO_LOGO_NAO_CADASTRADA = 30;
const
ERRO_LOGO_JA_CADASTRADA = 31;
const
ERRO_TAMANHO_INVALIDO = 32;
const
ERRO_CONEXAO_NAO_INICIADA = 33;
const
ERRO_CONEXAO_JA_INICIADA = 34;
const
ERRO_COMANDO_NAO_SUPORTADO = 35;
const
ERRO_TIMEOUT_RETIRADA_DOCUMENTO = 36;
const
ERRO_TIMEOUT_INSERCAO_DOCUMENTO = 37;
const
ERRO_DOCUMENTO_NAO_INSERIDO = 38;
const
ERRO_LAYOUT_CHEQUE_NAO_REGISTRADO = 39;
const
ERRO_ARQ_CONF_INI_NAO_ENCONTRADO = 40;
const
ERRO_IMPRESSORA_SUPERAQUECIDA = 41;
{///TAGS para formatacao em texto }
{///CARACTERE DE ESCAPE }
const
TAG_ESCAPE = '\\';
{///NEGRITO }
const
TAG_ATIVAR_NEGRITO = '<n>';
const
TAG_ATIVAR_NEGRITO_SZ = 3;
const
TAG_DESATIVAR_NEGRITO = '</n>';
const
TAG_DESATIVAR_NEGRITO_SZ = 4;
{///ALTURA DUPLA }
const
TAG_ATIVAR_ALTURA_DUPLA = '<ad>';
const
TAG_ATIVAR_ALTURA_DUPLA_SZ = 4;
const
TAG_DESATIVAR_ALTURA_DUPLA = '</ad>';
const
TAG_DESATIVAR_ALTURA_DUPLA_SZ = 5;
{///LARGURA DUPLA }
const
TAG_ATIVAR_LARGURA_DUPLA = '<ld>';
const
TAG_ATIVAR_LARGURA_DUPLA_SZ = 4;
const
TAG_DESATIVAR_LARGURA_DUPLA = '</ld>';
const
TAG_DESATIVAR_LARGURA_DUPLA_SZ = 5;
{///SUBLINHADO }
const
TAG_ATIVAR_SUBLINHADO = '<su>';
const
TAG_ATIVAR_SUBLINHADO_SZ = 4;
const
TAG_DESATIVAR_SUBLINHADO = '</su>';
const
TAG_DESATIVAR_SUBLINHADO_SZ = 5;
{///SOBRESCRITO }
const
TAG_ATIVAR_SOBRESCRITO = '<sb>';
const
TAG_ATIVAR_SOBRESCRITO_SZ = 4;
const
TAG_DESATIVAR_SOBRESCRITO = '</sb>';
const
TAG_DESATIVAR_SOBRESCRITO_SZ = 5;
{///COR INVERTIDA }
const
TAG_ATIVAR_COR_INVERTIDA = '<ci>';
const
TAG_ATIVAR_COR_INVERTIDA_SZ = 4;
const
TAG_DESATIVAR_COR_INVERTIDA = '</ci>';
const
TAG_DESATIVAR_COR_INVERTIDA_SZ = 5;
{///COR FRACA CARACTERE COMPLETO }
const
TAG_ATIVAR_COR_FRACA_CARACTERE_COMPLETO = '<cc>';
const
TAG_ATIVAR_COR_FRACA_CARACTERE_COMPLETO_SZ = 4;
const
TAG_DESATIVAR_COR_FRACA_CARACTERE_COMPLETO = '</cc>';
const
TAG_DESATIVAR_COR_FRACA_CARACTERE_COMPLETO_SZ = 5;
{///COR FRACA MEIO CARACTERE }
const
TAG_ATIVAR_COR_FRACA_MEIO_CARACTERE = '<cm>';
const
TAG_ATIVAR_COR_FRACA_MEIO_CARACTERE_SZ = 4;
const
TAG_DESATIVAR_COR_FRACA_MEIO_CARACTERE = '</cm>';
const
TAG_DESATIVAR_COR_FRACA_MEIO_CARACTERE_SZ = 5;
{///TEXTO INVERTIDO }
const
TAG_ATIVAR_TEXTO_INVERTIDO = '<ti>';
const
TAG_ATIVAR_TEXTO_INVERTIDO_SZ = 4;
const
TAG_DESATIVAR_TEXTO_INVERTIDO = '</ti>';
const
TAG_DESATIVAR_TEXTO_INVERTIDO_SZ = 5;
{///NOVA LINHA }
const
TAG_NOVA_LINHA = '<nl>';
const
TAG_NOVA_LINHA_SZ = 4;
{///TABULACAO }
const
TAG_TABULACAO = '<tb>';
const
TAG_TABULACAO_SZ = 4;
{///CORTAR PAPEL }
const
TAG_CORTAR_PAPEL = '<cp>';
const
TAG_CORTAR_PAPEL_SZ = 4;
{///ALINHAMENTO A ESQUERDA }
const
TAG_ALINHAMENTO_A_ESQUERDA = '<ale>';
const
TAG_ALINHAMENTO_A_ESQUERDA_SZ = 5;
{///ALINHAMENTO CENTRO }
const
TAG_ALINHAMENTO_CENTRO = '<alc>';
const
TAG_ALINHAMENTO_CENTRO_SZ = 5;
{///ALINHAMENTO A DIREITA }
const
TAG_ALINHAMENTO_A_DIREITA = '<ald>';
const
TAG_ALINHAMENTO_A_DIREITA_SZ = 5;
{///Setores de memoria da impressora }
const
SETOR_MEMORIA_LOGOS = 1;
const
SETOR_MEMORIA_MENSAGENS = 2;
const
SETOR_MEMORIA_CARACTERES_TERMICA = 4;
{///Numero de ids para setores de memoria }
const
SETOR_MEMORIA_QTDE_LOGOS = 255;
const
SETOR_MEMORIA_QTDE_MEMSAGENS = 255;
const
SETOR_MEMORIA_QTDE_CARACTERES_TERMICA = 4;
const
SETOR_MEMORIA_MENSAGEM_PAGINA_UM = 1;
const
SETOR_MEMORIA_MENSAGEM_PAGINA_DOIS = 2;
const
SETOR_MEMORIA_MENSAGEM_PAGINA_TRES = 3;
const
SETOR_MEMORIA_MENSAGEM_PAGINA_QUATRO = 4;
{///Constantes do sinal sonoro }
const
SINAL_SONORO_NOTA_DO = 0;
const
SINAL_SONORO_NOTA_DO_SUSTENIDO = 1;
const
SINAL_SONORO_NOTA_RE = 2;
const
SINAL_SONORO_NOTA_RE_SUSTENIDO = 3;
const
SINAL_SONORO_NOTA_MI = 4;
const
SINAL_SONORO_NOTA_FA = 5;
const
SINAL_SONORO_NOTA_FA_SUSTENIDO = 6;
const
SINAL_SONORO_NOTA_SOL = 7;
const
SINAL_SONORO_NOTA_SOL_SUSTENIDO = 8;
const
SINAL_SONORO_NOTA_LA = 9;
const
SINAL_SONORO_NOTA_LA_SUSTENIDO = 10;
const
SINAL_SONORO_NOTA_SI = 11;
const
SINAL_SONORO_SEM_NOTA = 12;
const
SINAL_SONORO_BEEP_NORMAL = 15;
const
SINAL_SONORO_OITAVA_UM = 0;
const
SINAL_SONORO_OITAVA_DOIS = 32;
const
SINAL_SONORO_OITAVA_TRES = 16;
const
SINAL_SONORO_OITAVA_QUATRO = 48;
const
SINAL_SONORO_VOLUME_ALTO = 0;
const
SINAL_SONORO_VOLUME_BAIXO = 128;
{+//* }
{-* Abre comunicacao com a impressora }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
abrirComunicacao: function: integer {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Envia sinal de abertura de gaveta }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
abrirGaveta: function: EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Alinha texto horizontalmente, a esquerda, a direita ou no centro. }
{-* @param alinhamento (alinhamento do texto) }
{-* ALINHAMENTO_TEXTO_A_ESQUERDA (padrao) }
{-* ALINHAMENTO_TEXTO_CENTRO }
{-* ALINHAMENTO_TEXTO_A_DIREITA }
{-* }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
alinharTexto: function(alinhamento: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Apaga um setor de memoria da impressora }
{-* @param setor (numero do setor que sera apagado) }
{-* SETOR_MEMORIA_LOGOS }
{-* SETOR_MEMORIA_MENSAGENS }
{-* SETOR_MEMORIA_CARACTERES_TERMICA }
{-* }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
apagarSetorMemoria: function(setor: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Ativa ou desativa o corte de papel }
{-* @param ativar }
{-* 0 = desativa corte de papel }
{-* 1 = ativa corte de papel }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
ativarCortePapel: function(ativar: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Ativa sinal sonora da impressora }
{-* @param nota (nota que sera usada no sinal sonoro) }
{-* SINAL_SONORO_NOTA_DO }
{-* SINAL_SONORO_NOTA_DO_SUSTENIDO }
{-* SINAL_SONORO_NOTA_RE }
{-* SINAL_SONORO_NOTA_RE_SUSTENIDO }
{-* SINAL_SONORO_NOTA_MI }
{-* SINAL_SONORO_NOTA_FA }
{-* SINAL_SONORO_NOTA_FA_SUSTENIDO }
{-* SINAL_SONORO_NOTA_SOL }
{-* SINAL_SONORO_NOTA_SOL_SUSTENIDO }
{-* SINAL_SONORO_NOTA_LA }
{-* SINAL_SONORO_NOTA_LA_SUSTENIDO }
{-* SINAL_SONORO_NOTA_SI }
{-* SINAL_SONORO_SEM_NOTA }
{-* SINAL_SONORO_BEEP_NORMAL }
{-* @param volume (volume do sinal sonoro) }
{-* SINAL_SONORO_VOLUME_ALTO }
{-* SINAL_SONORO_VOLUME_BAIXO }
{-* @param oitava }
{-* SINAL_SONORO_OITAVA_UM }
{-* SINAL_SONORO_OITAVA_DOIS }
{-* SINAL_SONORO_OITAVA_TRES }
{-* SINAL_SONORO_OITAVA_QUATRO }
{-* @param tempo (tempo em que o som sera reproduzido, sendo calculado o tempo de reproducao total como (tempo* 0.1 segundos)) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
ativarSinalSonoro: function(nota: Byte;
volume: Byte;
oitava: Byte;
tempo: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Autentica documento }
{-* @param linha1 (primeira linha da autenticacao) }
{-* @param tamanhoLinha1 (tamanho da primeira linha) }
{-* @param linha2 (segunda linha da autenticacao) }
{-* @param tamanhoLinha2 (tamanho da segunda linha) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
autenticarDocumento: function(var linha1: Byte;
tamanhoLinha1: Integer;
var linha2: Byte;
tamanhoLinha2: Integer): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Avanca papel a quantidade de linhas passada }
{-* @param quantidade (Numero de linhas que serao avancadas) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
avancarLinha: function(quantidade: SmallInt): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Avanca tabulacao horizontal do papel }
{-* @param tabulacoes (numero de avancos de tabulacao desejado (valor entre 1 e 5)) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
avancarTabulacao: function(tabulacoes: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Redefine uma parte dos caracteres das paginas de codigos definidas pelo usuario na memoria da impressora }
{-* @param pagina (qual a pagina de codigo que sera redefinida (paginas existentes: de 1 a 4)) }
{-* @param mapaCaracteres (os bytes que representam os novos caracteres) }
{-* @param caractereInicial (ASCII do caractere inicial da redefinicao) }
{-* @param caractereFinal (ASCII do caractere fina da redefinicao) }
{-* @param tamanhoMapa (tamanho, em bytes, do mapa de caracteres) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
carregaConjuntoCaracteres: function(pagina: Byte;
var mapaCaracteres: Byte;
caractereInicial: Byte;
caractereFinal: Byte;
tamanhoMapa: Word): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Carrega uma imagem Bitmap na memoria da impressora para acesso rapido }
{-* @param id (numero da iamgem na memoria da impressora) }
{-* @param caminho (caminho para imagem que sera salva) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
carregarLogo: function(id: Byte;
var caminho: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Carrega um texto pre-formatado na memoria da impressora para acesso rapido }
{-* @param id (numero da mensagem na impressora) }
{-* @param texto (texto que sera salvo na impressora) }
{-* @param tamanhoTexto (tamanho do texto recebido) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
carregarTextoPreDefinido: function(id: Byte;
var texto: Byte;
tamanhoTexto: Word): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Executa comando diretamente na impressora }
{-* @param comando (comando que sera enviado diretamente para impressora) }
{-* @param tamanhoComando (tamanho do comando enviado) }
{-* @param resposta (resposta esperada pela execucao do comando) }
{-* @param tamanhoResposta (tamanho da resposta esperada) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
cmdDireto: function(var comando: Byte;
tamanhoComando: Word;
var resposta: Byte;
tamanhoResposta: Word): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configura texto para ser impresso com altura dupla }
{-* @param ativar (1 = ativa altura dupla, 0 = desativa altura dupla) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarAlturaDupla: function(ativar: Char): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configura a conversao de caracteres automatica. }
{-* @param ativar Indica se a biblioteca deve converter o texto recebido na codificacao }
{-* do sistema para um texto codificado em uma paginacao que a impressora entenda. }
{-* Ao ativar a conversao automatica, a codificacao da impressora e configurada para a CODIFICACAO_858, que e multilingue. }
{-* @param codificacaoSistema Informa a codificacao que o sistema esta utilizando para os textos enviados. Caso ativar seja FALSE, esse parametro sera ignorado. }
{-* CODIFICACAO_437 - Estados Unidos }
{-* CODIFICACAO_858 - Multilingue (Padrao da impressora) }
{-* CODIFICACAO_863 - Frances do Canada }
{-* CODIFICACAO_860 - Portugal }
{-* CODIFICACAO_865 - Noruega }
{-* CODIFICACAO_GENERICA - Pagina generica da impressora }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO - Paginacao carregada pelo usuario na impressora. }
{-* CODIFICACAO_869 - Grego }
{-* CODIFICACAO_857 - Turco }
{-* CODIFICACAO_864 - Arabe }
{-* CODIFICACAO_867 - Hebraico (Israel) }
{-* CODIFICACAO_852 - Hungaro, Polones, Tcheco, Romeno, Eslovaco, Esloveno, Croata }
{-* CODIFICACAO_848 - Ucraniano }
{-* CODIFICACAO_866 - Russo (cirilico) }
{-* CODIFICACAO_872 - Bulgaro, Servio }
{-* CODIFICACAO_775 - Lituano, Letao, Estonia }
{-* CODIFICACAO_861 - Islandes }
{-* CODIFICACAO_1250 - Windows Latin 2 }
{-* CODIFICACAO_1251 - Windows Cirilico }
{-* CODIFICACAO_1252 - Windows Latin 1 }
{-* CODIFICACAO_1253 - Windows Grego }
{-* CODIFICACAO_1254 - Windows Turco }
{-* CODIFICACAO_1255 - Windows Hebraico }
{-* CODIFICACAO_1256 - Windows Arabe }
{-* CODIFICACAO_1257 - Windows Baltico (Rim) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarConversaoCaracteres: function(ativar: Byte;
codificacaoSistema: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configurar impressao em duas cores }
{-* @param tipo }
{-* COR_FRACA_DESABILITADA = desativa impressao em duas cores }
{-* COR_FRACA_CARACTERE_COMPLETO = ativa impressao em duas cores Completa }
{-* COR_FRACA_MEIO_CARACTERE = ativa impressao em duas cores metade da linha }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarCor: function(tipo: Char): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configurar impressao com cores invertidas }
{-* @param ativar (1 = ativa impressao invertida, 0 = desativa impressao invertida) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarCorInvertida: function(ativar: Char): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configura texto para ser impresso com largura dupla }
{-* @param ativar (1 = ativa largura dupla, 0 = desativa largura dupla) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarLarguraDupla: function(ativar: Char): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configura texto para ser impresso em negrito }
{-* @param ativar (1 = ativa negrito, 0 = desativa negrito) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarNegrito: function(ativar: Char): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configura texto para ser impresso sobrescrito }
{-* @param ativar (1 = ativa sobrescrito, 0 = desativa sobrescrito) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarSobrescrito: function(ativar: Char): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configura texto para ser impresso sublinhado }
{-* @param ativar (1 = ativa sublinhado, 0 = desativa sublinhado) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarSublinhado: function(ativar: Char): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Configura texto para ser impresso de cabeca para baixo }
{-* @param ativar (1 = ativa texto invertido, 0 = desativa texto invertido) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
configurarTextoInvertido: function(ativar: Char): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Funcao utilitaria para conversao de caracteres. }
{-* @param codificacaoEntrada Indica a codificacao utilizada no texto de entrada. }
{-* CODIFICACAO_437 - Estados Unidos }
{-* CODIFICACAO_858 - Multilingue (Padrao da impressora) }
{-* CODIFICACAO_863 - Frances do Canada }
{-* CODIFICACAO_860 - Portugal }
{-* CODIFICACAO_865 - Noruega }
{-* CODIFICACAO_GENERICA - Pagina generica da impressora }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO - Paginacao carregada pelo usuario na impressora. }
{-* CODIFICACAO_869 - Grego }
{-* CODIFICACAO_857 - Turco }
{-* CODIFICACAO_864 - Arabe }
{-* CODIFICACAO_867 - Hebraico (Israel) }
{-* CODIFICACAO_852 - Hungaro, Polones, Tcheco, Romeno, Eslovaco, Esloveno, Croata }
{-* CODIFICACAO_848 - Ucraniano }
{-* CODIFICACAO_866 - Russo (cirilico) }
{-* ODIFICACAO_872 - Bulgaro, Servio }
{-* CODIFICACAO_775 - Lituano, Letao, Estonia }
{-* CODIFICACAO_861 - Islandes }
{-* CODIFICACAO_1250 - Windows Latin 2 }
{-* CODIFICACAO_1251 - Windows Cirilico }
{-* CODIFICACAO_1252 - Windows Latin 1 }
{-* CODIFICACAO_1253 - Windows Grego }
{-* CODIFICACAO_1254 - Windows Turco }
{-* CODIFICACAO_1255 - Windows Hebraico }
{-* CODIFICACAO_1256 - Windows Arabe }
{-* CODIFICACAO_1257 - Windows Baltico (Rim) }
{-* @param caracteresEntrada Texto de entrada a ser convertido. }
{-* @param quantidadeCaracteres Tamanho do texto de entrada. }
{-* @param codificacaoSaida Indica a codificacao utilizada no conversao do texto de entrada, gerando o texto de saida. }
{-* CODIFICACAO_437 - Estados Unidos }
{-* CODIFICACAO_858 - Multilingue (Padrao da impressora) }
{-* CODIFICACAO_863 - Frances do Canada }
{-* CODIFICACAO_860 - Portugal }
{-* CODIFICACAO_865 - Noruega }
{-* CODIFICACAO_GENERICA - Pagina generica da impressora }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO - Paginacao carregada pelo usuario na impressora. }
{-* CODIFICACAO_869 - Grego }
{-* CODIFICACAO_857 - Turco }
{-* CODIFICACAO_864 - Arabe }
{-* CODIFICACAO_867 - Hebraico (Israel) }
{-* CODIFICACAO_852 - Hungaro, Polones, Tcheco, Romeno, Eslovaco, Esloveno, Croata }
{-* CODIFICACAO_848 - Ucraniano }
{-* CODIFICACAO_866 - Russo (cirilico) }
{-* ODIFICACAO_872 - Bulgaro, Servio }
{-* CODIFICACAO_775 - Lituano, Letao, Estonia }
{-* CODIFICACAO_861 - Islandes }
{-* CODIFICACAO_1250 - Windows Latin 2 }
{-* CODIFICACAO_1251 - Windows Cirilico }
{-* CODIFICACAO_1252 - Windows Latin 1 }
{-* CODIFICACAO_1253 - Windows Grego }
{-* CODIFICACAO_1254 - Windows Turco }
{-* CODIFICACAO_1255 - Windows Hebraico }
{-* CODIFICACAO_1256 - Windows Arabe }
{-* CODIFICACAO_1257 - Windows Baltico (Rim) }
{-* @param caracteresSaida Buffer de resposta com o texto convertido, deve possuir no minimo o tamanho do buffer de texto de entrada (caracteresEntrada). }
{-* @return Codigo de erro. }
{= }
var
converterCaracteres: function(codificacaoEntrada: Byte;
var caracteresEntrada: Byte;
quantidadeCaracteres: Word;
codificacaoSaida: Byte;
var caracteresSaida: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Avanca n linhas e corta papel }
{-* @param numeroAvancoLinhas (Numero de linhas que serao avancadas antes de cortar o papel) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
cortarPapel: function(numeroAvancoLinhas: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Define o diretorio onde estao localizado os arquivos de configuracao da biblioteca TGCS Sure Mark }
{-* @param diretorio Caminho relativo ou absoluto para o diretorio onde estao os arquivos de configuracao. }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
definirDiretorioConfiguracao: function(var diretorio: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Ejeta documento da estacao de documentos da impressora. }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
ejetarDocumento: function: EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Fecha comunicacao com a impressora }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
fecharComunicacao: function: EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime codigo no formado QR Code com o conteudo do arquivo passado. }
{-* @param caminho caminho para o arquivo com o conteudo do QRCode }
{-* @param modoCodificacao Modo de codificacao dos dados inseridos: }
{-* QRCODE_MODO_CODIFICACAO_BYTE }
{-* QRCODE_MODO_CODIFICACAO_ALFANUMERICO }
{-* QRCODE_MODO_CODIFICACAO_NUMERICO }
{-* QRCODE_MODO_CODIFICACAO_KANJI }
{-* QRCODE_MODO_CODIFICACAO_ECI }
{-* QRCODE_MODO_CODIFICACAO_MIXING }
{-* @param nivelCorrecaoErro Nivel de correcao de erros. }
{-* QRCODE_ERROR_L7 - 7% }
{-* QRCODE_ERROR_M15 - 15% }
{-* QRCODE_ERROR_Q25 - 25% }
{-* QRCODE_ERROR_H30 - 30% }
{-* @param eci Extended Channel Interpretation (ECI) Mode. Valido domente se o modoCodificacao ECI for selecionado. }
{-* QRCODE_ECI_PDF417_DEFAULT_GLI }
{-* QRCODE_ECI_PDF417_LATIN1_GLI }
{-* QRCODE_ECI_PDF417_DEFAULT_ECI }
{-* QRCODE_ECI_ISO8859_1 }
{-* QRCODE_ECI_ISO8859_2 }
{-* QRCODE_ECI_ISO8859_3 }
{-* QRCODE_ECI_ISO8859_4 }
{-* QRCODE_ECI_ISO8859_5 }
{-* QRCODE_ECI_ISO8859_6 }
{-* QRCODE_ECI_ISO8859_7 }
{-* QRCODE_ECI_ISO8859_8 }
{-* QRCODE_ECI_ISO8859_9 }
{-* QRCODE_ECI_ISO8859_10 }
{-* QRCODE_ECI_ISO8859_11 }
{-* QRCODE_ECI_ISO8859_12 }
{-* QRCODE_ECI_ISO8859_13 }
{-* QRCODE_ECI_ISO8859_14 }
{-* QRCODE_ECI_ISO8859_15 }
{-* QRCODE_ECI_ISO8859_16 }
{-* QRCODE_ECI_SJIS }
{-* QRCODE_ECI_UTF8 }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
gerarQRcodeArquivo: function(var caminho: Byte;
modoCodificacao: Byte;
nivelCorrecaoErro: Byte;
eci: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime texto direto de arquivo .txt, o texto pode estar formatado com as tags de formatacao. }
{-* @param caminhoArquivo (caminho do arquivo que tera o conteudo impresso) }
{-* @return }
{= }
var
impressaoDiretaArquivoTxt: function(var caminhoArquivo: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime uma imagem Bitmap direto do arquivo }
{-* @param caminhoBitmap (caminho do arquivo Bitmap) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirBitmap: function(var caminhoBitmap: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime informacoes em cheque }
{-* @param codigoCheque (Codigo do banco do cheque que sera impresso) }
{-* @param imprimeVerso (Variavel que diz se havera impressao no verso do cheque neste comando) }
{-* @param valor (Valor do cheque) }
{-* @param tamanhoValor (Tamanho do campo valor) }
{-* @param favorecido (Nome do favorecido do cheque) }
{-* @param tamanhoFavorecido (Tamanho do campo favorecido) }
{-* @param local (Local do cheque) }
{-* @param tamanhoLocal (Tamanho do campo local) }
{-* @param data (Data do cheque no formato DDMMAAAA) }
{-* @param infoAdicionalFrente1 (Primeira linha de informacao adicional da frente do cheque) }
{-* @param tamanhoInfoAdicionalFrente1 (Tamanho da primeira linha de informacao adicional da frente do cheque) }
{-* @param infoAdicionalFrente2 (Segunda linha de informacao adicional da frente do cheque) }
{-* @param tamanhoInfoAdicionalFrente2 (Tamanho da segunda linha de informacao adicional da frente do cheque) }
{-* @param infoAdicionalFrente3 (Terceira linha de informacao adicional da frente do cheque) }
{-* @param tamanhoInfoAdicionalFrente3 (Tamanho da terceira linha de informacao adicional da frente do cheque) }
{-* @param infoAdicionalVerso1 (Primeira linha de informacao adicional do verso do cheque) }
{-* @param tamanhoInfoAdicionalVerso1 (Tamanho da primeira linha de informacao adicional do verso do cheque) }
{-* @param infoAdicionalVerso2 (Segunda linha de informacao adicional do verso do cheque) }
{-* @param tamanhoInfoAdicionalVerso2 (Tamanho da segunda linha de informacao adicional do verso do cheque) }
{-* @param infoAdicionalVerso3 (Terceira linha de informacao adicional do verso do cheque) }
{-* @param tamanhoInfoAdicionalVerso3 (Tamanho da terceira linha de informacao adicional do verso do cheque) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirCheque: function(codigoCheque: Integer;
imprimeVerso: Byte;
var valor: Byte;
tamanhoValor: Byte;
var favorecido: Byte;
tamanhoFavorecido: Byte;
var local: Byte;
tamanhoLocal: Byte;
_9: Word;
)
: EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime codigo de barras }
{-* @param tipo (Seleciona o tipo de codigo de barras que sera impresso) }
{-* CODIGO_BARRAS_UPCA }
{-* CODIGO_BARRAS_UPCE }
{-* CODIGO_BARRAS_JAN13 }
{-* CODIGO_BARRAS_JAN8 }
{-* CODIGO_BARRAS_CODE39 }
{-* CODIGO_BARRAS_ITF }
{-* CODIGO_BARRAS_CODABAR }
{-* CODIGO_BARRAS_CODE128C }
{-* CODIGO_BARRAS_CODE93 }
{-* CODIGO_BARRAS_CODE128ABC }
{-* }
{-* @param codigo (Codigo do codigo de barras) }
{-* @param tamanhoCodigo (Tamanho do codigo. Exemplo: codigo = "0123456789", tamanhoCodigo=10) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirCodigoBarras: function(tipo: Byte;
var codigo: Byte;
tamanhoCodigo: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime codigo de barras do tipo PDF417 }
{-* @param nivelCorrecaoErro1 (O byte de ordem superior do nivel de ECC (valor de 0 a 400, padrao = 00)) }
{-* @param nivelCorrecaoErro2 (O byte de ordem inferior do nivel de ECC (valor de 0 a 400, padrao = 15)) }
{-* @param truncar }
{-* 0 = desativa truncamento }
{-* 1 = ativa truncamento }
{-* @param largura (A dimensao de altura para a proporcao (valor de 1 a 9, padrao = 1)) }
{-* @param altura (A dimensao de largura para a proporcao (valor de 1 a 9, padrao = 2)) }
{-* @param codigo (Codigo do codigo de barras) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirCodigoBarrasPDF417: function(nivelCorrecaoErro1: SmallInt;
nivelCorrecaoErro2: SmallInt;
truncar: Char;
largura: Char;
altura: Char;
var codigo: Byte;
tamanhoCodigo: Word): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime logo salvo na memoria da impressora }
{-* @param id (id do logo na impressora) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirLogo: function(id: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime pequeno logo na linha de impressao }
{-* @param largura (lagura do logo) }
{-* @param altura (altura do logo) }
{-* 0 = altura normal }
{-* 1 = altura dupla }
{-* @param dadosLogo (dados do logo) }
{-* @param tamanhoDados (quantidade de bytes enviados) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirLogoSequencial: function(largura: Word;
altura: Byte;
var dadosLogo: Byte;
tamanhoDados: Word): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime codigo no formado QR Code. }
{-* }
{-* @param modoCodificacao Modo de codificacao dos dados inseridos: }
{-* QRCODE_MODO_CODIFICACAO_BYTE }
{-* QRCODE_MODO_CODIFICACAO_ALFANUMERICO }
{-* QRCODE_MODO_CODIFICACAO_NUMERICO }
{-* QRCODE_MODO_CODIFICACAO_KANJI }
{-* QRCODE_MODO_CODIFICACAO_ECI }
{-* QRCODE_MODO_CODIFICACAO_MIXING }
{-* @param nivelCorrecaoErro Nivel de correcao de erros. }
{-* QRCODE_ERROR_L7 - 7% }
{-* QRCODE_ERROR_M15 - 15% }
{-* QRCODE_ERROR_Q25 - 25% }
{-* QRCODE_ERROR_H30 - 30% }
{-* @param eci Extended Channel Interpretation (ECI) Mode. Valido domente se o modoCodificacao ECI for selecionado. }
{-* QRCODE_ECI_PDF417_DEFAULT_GLI }
{-* QRCODE_ECI_PDF417_LATIN1_GLI }
{-* QRCODE_ECI_PDF417_DEFAULT_ECI }
{-* QRCODE_ECI_ISO8859_1 }
{-* QRCODE_ECI_ISO8859_2 }
{-* QRCODE_ECI_ISO8859_3 }
{-* QRCODE_ECI_ISO8859_4 }
{-* QRCODE_ECI_ISO8859_5 }
{-* QRCODE_ECI_ISO8859_6 }
{-* QRCODE_ECI_ISO8859_7 }
{-* QRCODE_ECI_ISO8859_8 }
{-* QRCODE_ECI_ISO8859_9 }
{-* QRCODE_ECI_ISO8859_10 }
{-* QRCODE_ECI_ISO8859_11 }
{-* QRCODE_ECI_ISO8859_12 }
{-* QRCODE_ECI_ISO8859_13 }
{-* QRCODE_ECI_ISO8859_14 }
{-* QRCODE_ECI_ISO8859_15 }
{-* QRCODE_ECI_ISO8859_16 }
{-* QRCODE_ECI_SJIS }
{-* QRCODE_ECI_UTF8 }
{-* @param dados Informacoes a serem impressas no qr code. }
{-* @param tamanhoDados quantidade de bytes enviados no parametro dados. }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirQRcode: function(modoCodificacao: Byte;
nivelCorrecaoErro: Byte;
eci: Byte;
var dados: Byte;
tamanhoDados: Word): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime texto }
{-* @param texto (Texto que sera impresso) }
{-* @param tamanhoTexto (Tamanho do argumento texto. Exemplo: texto="<n>texto</n>1234", tamanhoTexto=16) }
{-* }
{-* OBS: }
{-* O texto pode conter as TAGs a seguir: }
{-* tag desativar negrito - </n> }
{-* tag ativar negrito - <n> }
{-* tag desativar altura dupla - </ad> }
{-* tag ativar altura dupla - <ad> }
{-* tag desativar largura dupla - </ld> }
{-* tag ativar largura dupla - <ld> }
{-* tag desativar sublinhado - </su> }
{-* tag ativar sublinhado - <su> }
{-* tag desativar sobrescrito - </sb> }
{-* tag ativar sobrescrito - <sb> }
{-* tag desativar cor invertida - </ci> }
{-* tag ativar cor invertida - <ci> }
{-* tag desativar cor fraca caractere completo - </cc> }
{-* tag ativar cor fraca caractere completo - <cc> }
{-* tag desativar cor fraca meio caractere - </cm> }
{-* tag ativar cor fraca meio caractere - <cm> }
{-* tag desativar texto invertido - </ti> }
{-* tag ativar texto invertido - <ti> }
{-* tag nova linha - <nl> }
{-* tag tabulacao - <tb> }
{-* tag cortar papel - <cp> }
{-* tag alinhamento a esquerda - <ale> }
{-* tag alinhamento centro - <alc> }
{-* tag alinhamento a direita - <ald> }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirTexto: function(var texto: Byte;
tamanhoTexto: Word): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime texto pre-definido salvo na impressora }
{-* @param id (id do texto na impressora) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirTextoPreDefinido: function(id: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Imprime linhas adicionais no verso do cheque }
{-* @param codigoCheque (Codigo do banco emissor do cheque) }
{-* @param linha1 (Primeira linha que sera impressa) }
{-* @param tamanhoLinha1 (tamanho da primeira linha que sera impressa) }
{-* @param linha2 (Segunda linha que sera impressa) }
{-* @param tamanhoLinha2 (tamanho da segunda linha que sera impressa) }
{-* @param linha3 (Terceira linha que sera impressa) }
{-* @param tamanhoLinha3 (tamanho da terceira linha que sera impressa) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
imprimirVersoCheque: function(codigoCheque: Integer;
var linha1: Byte;
tamanhoLinha1: Byte;
var linha2: Byte;
tamanhoLinha2: Byte;
var linha3: Byte;
tamanhoLinha3: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Ler informacoes sobre a conta a partir da linha de caracteres de tinta magnetica em cheques. }
{-* @param resposta (Conteudo lido das linhas magneticas) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
lerCMC7: function(var resposta: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Retorna status da impressora }
{-* @param status (Vetor com status da impressora.) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
lerStatus: function(var status: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Forca a impressao do buffer contido na impressora. }
{-* Este comando deve ser usado quando o erro de BUFFER_CHEIO for retornado. }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
obrigarImpressao: function: EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Retorna o modelo da impressora conectada atualmente }
{-* @param modelo Modelo da impressora }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
obterModeloImpressora: function(var modelo: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Retorna a versao da biblioteca de comunicacao atual }
{-* @param versao (parametro que ira receber a versao da biblioteca de comunicacao atual (tamanho do vetor = 8 bytes)) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
obterVersaoBiblioteca: function(var versao: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Retorna a versao do Firmware da impressora }
{-* @param versao (parametro que ira receber a versao do Firmware da impressora (tamanho do vetor = TAMANHO_VERSAO_FIRMWARE_BYTES)) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
obterVersaoFirmware: function(var versao: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Posiciona documento para autenticacao. }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
posicionarDocumento: function: EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Reinicia a impressora, reinicia configuracoes e cancela buffer de impressao }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
reiniciarImpressora: function: EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Seleciona a altura do codigo de barras }
{-* @param altura (Altura do codigo de barras (valor entre 1 e 255, padrao = 162)) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
selecionaAlturaCodigoBarras: function(altura: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Seleciona a pagina de codigos a ser utilizada na impressao }
{-* @param codificacao Pagina de codigo a ser utilizada }
{-* CODIFICACAO_437 - Estados Unidos }
{-* CODIFICACAO_858 - Multilingue (Padrao da impressora) }
{-* CODIFICACAO_863 - Frances do Canada }
{-* CODIFICACAO_860 - Portugal }
{-* CODIFICACAO_865 - Noruega }
{-* CODIFICACAO_GENERICA - Pagina generica da impressora }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO - Opcao de compatibilidade, nao usada }
{-* CODIFICACAO_869 - Grego }
{-* CODIFICACAO_857 - Turco }
{-* CODIFICACAO_864 - Arabe }
{-* CODIFICACAO_867 - Hebraico (Israel) }
{-* CODIFICACAO_852 - Hungaro, Polones, Tcheco, Romeno, Eslovaco, Esloveno, Croata }
{-* CODIFICACAO_848 - Ucraniano }
{-* CODIFICACAO_866 - Russo (cirilico) }
{-* ODIFICACAO_872 - Bulgaro, Servio }
{-* CODIFICACAO_775 - Lituano, Letao, Estonia }
{-* CODIFICACAO_861 - Islandes }
{-* CODIFICACAO_1250 - Windows Latin 2 }
{-* CODIFICACAO_1251 - Windows Cirilico }
{-* CODIFICACAO_1252 - Windows Latin 1 }
{-* CODIFICACAO_1253 - Windows Grego }
{-* CODIFICACAO_1254 - Windows Turco }
{-* CODIFICACAO_1255 - Windows Hebraico }
{-* CODIFICACAO_1256 - Windows Arabe }
{-* CODIFICACAO_1257 - Windows Baltico (Rim) }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO_1 - Pagina de codigo 1 definida pelo usuario }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO_2 - Pagina de codigo 2 definida pelo usuario }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO_3 - Pagina de codigo 3 definida pelo usuario }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO_4 - Pagina de codigo 4 definida pelo usuario }
{-* }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
selecionaCodificacaoCaracteres: function(codificacao: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Seleciona fonte HRI para codigo de barras }
{-* @param fonte (Fonte do HRI do codigo de barras (valor 0 ou 1, padrao = 0)) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
selecionaFonteHRICodigoBarras: function(fonte: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Seleciona largura do codigo de barras }
{-* @param largura (Largura do codigo de barras (valor de 2 a 4, padrao = 3)) }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
selecionaLarguraCodigoBarras: function(largura: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Seleciona posicao HRI do codigo de barras }
{-* @param posicao (Posicao do HRI no codigo de barras) }
{-* CODIGO_BARRAS_HRI_NAO_IMPRESSO (padrao) }
{-* CODIGO_BARRAS_HRI_ACIMA_DO_CODIGO_BARRAS }
{-* CODIGO_BARRAS_HRI_ABAIXO_DO_CODIGO_BARRAS }
{-* CODIGO_BARRAS_HRI_ACIMA_ABAIXO_DO_CODIGO_BARRAS }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
selecionaPosicaoHRICodigoBarras: function(posicao: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Retorna a codificacao de caracteres vigente na impressora. }
{-* @param codificacaoAtual Parametro de saida: codificacao de caracteres atual da impressora. }
{-* CODIFICACAO_437 - Estados Unidos }
{-* CODIFICACAO_858 - Multilingue (Padrao da impressora) }
{-* CODIFICACAO_863 - Frances do Canada }
{-* CODIFICACAO_860 - Portugal }
{-* CODIFICACAO_865 - Noruega }
{-* CODIFICACAO_GENERICA - Pagina generica da impressora }
{-* CODIFICACAO_DEFINIDA_PELO_USUARIO - Paginacao carregada pelo usuario na impressora. }
{-* CODIFICACAO_869 - Grego }
{-* CODIFICACAO_857 - Turco }
{-* CODIFICACAO_864 - Arabe }
{-* CODIFICACAO_867 - Hebraico (Israel) }
{-* CODIFICACAO_852 - Hungaro, Polones, Tcheco, Romeno, Eslovaco, Esloveno, Croata }
{-* CODIFICACAO_848 - Ucraniano }
{-* CODIFICACAO_866 - Russo (cirilico) }
{-* CODIFICACAO_872 - Bulgaro, Servio }
{-* CODIFICACAO_775 - Lituano, Letao, Estonia }
{-* CODIFICACAO_861 - Islandes }
{-* CODIFICACAO_1250 - Windows Latin 2 }
{-* CODIFICACAO_1251 - Windows Cirilico }
{-* CODIFICACAO_1252 - Windows Latin 1 }
{-* CODIFICACAO_1253 - Windows Grego }
{-* CODIFICACAO_1254 - Windows Turco }
{-* CODIFICACAO_1255 - Windows Hebraico }
{-* CODIFICACAO_1256 - Windows Arabe }
{-* CODIFICACAO_1257 - Windows Baltico (Rim) }
{-* @return Codigo de erro. }
{= }
var
verificarCodificacaoCaracteres: function(var codificacaoAtual: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Verifica se existe documento inserido na impressora }
{-* @param statusDocumento }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
verificarDocumento: function(var statusDocumento: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Verifica se a gaveta de dinheiro esta aberta }
{-* @param gavetaAberta }
{-* 0 = gaveta fechada }
{-* 1 = gaveta aberta }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
verificarGaveta: function(var gavetaAbertaFimPapel: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Verifica logos cadastrados na impressora. }
{-* @param resposta (vetor de 255 posicoes com as resposta para cada id da impressora, onde:) }
{-* 0 = id nao cadastrado }
{-* 1 = id cadastrado }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
verificarLogo: function(var resposta: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Verifica se existe logo salvo no id passado. }
{-* @param id (id que sera verificado) }
{-* @param resposta }
{-* 0 = logo nao cadastrada }
{-* 1 = logo cadastrada }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
verificarLogoPorId: function(id: Byte;
var resposta: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Verifica status do papel de impressao termica }
{-* @param statusPapel }
{-* STATUS_SEM_PAPEL 3 }
{-* STATUS_POUQUISSIMO_PAPEL 2 }
{-* STATUS_POUCO_PAPEL 1 }
{-* STATUS_PAPEL_OK 0 }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
verificarPapel: function(var statusPapel: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Verifica se a tampa de papel esta aberta }
{-* @param tampaAberta }
{-* 0 = tampa fechada }
{-* 1 = tampa aberta }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
verificarTampa: function(var tampaAberta: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Verifica textos pre definidos ja cadastradas }
{-* @param resposta (vetor de 255 posicoes com as resposta para cada id da impressora, onde:) }
{-* 0 = id nao cadastrado }
{-* 1 = id cadastrado }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
verificarTextoPreDefinido: function(var resposta: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{+//* }
{-* Verifica se existe texto salvo no id passado. }
{-* @param id (id que sera verificado) }
{-* @param resposta }
{-* 0 = texto nao cadastrada }
{-* 1 = texto cadastrada }
{-* @return 0 = OK }
{-* codigo do erro, caso contrario }
{= }
var
verificarTextoPreDefinidoPorId: function(id: Byte;
var resposta: Byte): EXPORT_DLL SHORT cdecl {$IFDEF WIN32} stdcall {$ENDIF};
{$ENDIF /* TGCS1NR_H*/}
var
DLLLoaded: Boolean { is DLL (dynamically) loaded already? }
{$IFDEF WIN32} = False; {$ENDIF}
implementation
var
SaveExit: pointer;
DLLHandle: THandle;
{$IFNDEF MSDOS}
ErrorMode: Integer;
{$ENDIF}
procedure NewExit; far;
begin
ExitProc := SaveExit;
FreeLibrary(DLLHandle)
end {NewExit};
procedure LoadDLL;
begin
if DLLLoaded then Exit;
{$IFNDEF MSDOS}
ErrorMode := SetErrorMode($8000{SEM_NoOpenFileErrorBox});
{$ENDIF}
DLLHandle := LoadLibrary('TGCSSUREMARK.DLL');
if DLLHandle >= 32 then
begin
DLLLoaded := True;
SaveExit := ExitProc;
ExitProc := @NewExit;
@abrirComunicacao := GetProcAddress(DLLHandle,'abrirComunicacao');
{$IFDEF WIN32}
Assert(@abrirComunicacao <> nil);
{$ENDIF}
@abrirGaveta := GetProcAddress(DLLHandle,'abrirGaveta');
{$IFDEF WIN32}
Assert(@abrirGaveta <> nil);
{$ENDIF}
@alinharTexto := GetProcAddress(DLLHandle,'alinharTexto');
{$IFDEF WIN32}
Assert(@alinharTexto <> nil);
{$ENDIF}
@apagarSetorMemoria := GetProcAddress(DLLHandle,'apagarSetorMemoria');
{$IFDEF WIN32}
Assert(@apagarSetorMemoria <> nil);
{$ENDIF}
@ativarCortePapel := GetProcAddress(DLLHandle,'ativarCortePapel');
{$IFDEF WIN32}
Assert(@ativarCortePapel <> nil);
{$ENDIF}
@ativarSinalSonoro := GetProcAddress(DLLHandle,'ativarSinalSonoro');
{$IFDEF WIN32}
Assert(@ativarSinalSonoro <> nil);
{$ENDIF}
@autenticarDocumento := GetProcAddress(DLLHandle,'autenticarDocumento');
{$IFDEF WIN32}
Assert(@autenticarDocumento <> nil);
{$ENDIF}
@avancarLinha := GetProcAddress(DLLHandle,'avancarLinha');
{$IFDEF WIN32}
Assert(@avancarLinha <> nil);
{$ENDIF}
@avancarTabulacao := GetProcAddress(DLLHandle,'avancarTabulacao');
{$IFDEF WIN32}
Assert(@avancarTabulacao <> nil);
{$ENDIF}
@carregaConjuntoCaracteres := GetProcAddress(DLLHandle,'carregaConjuntoCaracteres');
{$IFDEF WIN32}
Assert(@carregaConjuntoCaracteres <> nil);
{$ENDIF}
@carregarLogo := GetProcAddress(DLLHandle,'carregarLogo');
{$IFDEF WIN32}
Assert(@carregarLogo <> nil);
{$ENDIF}
@carregarTextoPreDefinido := GetProcAddress(DLLHandle,'carregarTextoPreDefinido');
{$IFDEF WIN32}
Assert(@carregarTextoPreDefinido <> nil);
{$ENDIF}
@cmdDireto := GetProcAddress(DLLHandle,'cmdDireto');
{$IFDEF WIN32}
Assert(@cmdDireto <> nil);
{$ENDIF}
@configurarAlturaDupla := GetProcAddress(DLLHandle,'configurarAlturaDupla');
{$IFDEF WIN32}
Assert(@configurarAlturaDupla <> nil);
{$ENDIF}
@configurarConversaoCaracteres := GetProcAddress(DLLHandle,'configurarConversaoCaracteres');
{$IFDEF WIN32}
Assert(@configurarConversaoCaracteres <> nil);
{$ENDIF}
@configurarCor := GetProcAddress(DLLHandle,'configurarCor');
{$IFDEF WIN32}
Assert(@configurarCor <> nil);
{$ENDIF}
@configurarCorInvertida := GetProcAddress(DLLHandle,'configurarCorInvertida');
{$IFDEF WIN32}
Assert(@configurarCorInvertida <> nil);
{$ENDIF}
@configurarLarguraDupla := GetProcAddress(DLLHandle,'configurarLarguraDupla');
{$IFDEF WIN32}
Assert(@configurarLarguraDupla <> nil);
{$ENDIF}
@configurarNegrito := GetProcAddress(DLLHandle,'configurarNegrito');
{$IFDEF WIN32}
Assert(@configurarNegrito <> nil);
{$ENDIF}
@configurarSobrescrito := GetProcAddress(DLLHandle,'configurarSobrescrito');
{$IFDEF WIN32}
Assert(@configurarSobrescrito <> nil);
{$ENDIF}
@configurarSublinhado := GetProcAddress(DLLHandle,'configurarSublinhado');
{$IFDEF WIN32}
Assert(@configurarSublinhado <> nil);
{$ENDIF}
@configurarTextoInvertido := GetProcAddress(DLLHandle,'configurarTextoInvertido');
{$IFDEF WIN32}
Assert(@configurarTextoInvertido <> nil);
{$ENDIF}
@converterCaracteres := GetProcAddress(DLLHandle,'converterCaracteres');
{$IFDEF WIN32}
Assert(@converterCaracteres <> nil);
{$ENDIF}
@cortarPapel := GetProcAddress(DLLHandle,'cortarPapel');
{$IFDEF WIN32}
Assert(@cortarPapel <> nil);
{$ENDIF}
@definirDiretorioConfiguracao := GetProcAddress(DLLHandle,'definirDiretorioConfiguracao');
{$IFDEF WIN32}
Assert(@definirDiretorioConfiguracao <> nil);
{$ENDIF}
@ejetarDocumento := GetProcAddress(DLLHandle,'ejetarDocumento');
{$IFDEF WIN32}
Assert(@ejetarDocumento <> nil);
{$ENDIF}
@fecharComunicacao := GetProcAddress(DLLHandle,'fecharComunicacao');
{$IFDEF WIN32}
Assert(@fecharComunicacao <> nil);
{$ENDIF}
@gerarQRcodeArquivo := GetProcAddress(DLLHandle,'gerarQRcodeArquivo');
{$IFDEF WIN32}
Assert(@gerarQRcodeArquivo <> nil);
{$ENDIF}
@impressaoDiretaArquivoTxt := GetProcAddress(DLLHandle,'impressaoDiretaArquivoTxt');
{$IFDEF WIN32}
Assert(@impressaoDiretaArquivoTxt <> nil);
{$ENDIF}
@imprimirBitmap := GetProcAddress(DLLHandle,'imprimirBitmap');
{$IFDEF WIN32}
Assert(@imprimirBitmap <> nil);
{$ENDIF}
@imprimirCheque := GetProcAddress(DLLHandle,'imprimirCheque');
{$IFDEF WIN32}
Assert(@imprimirCheque <> nil);
{$ENDIF}
@imprimirCodigoBarras := GetProcAddress(DLLHandle,'imprimirCodigoBarras');
{$IFDEF WIN32}
Assert(@imprimirCodigoBarras <> nil);
{$ENDIF}
@imprimirCodigoBarrasPDF417 := GetProcAddress(DLLHandle,'imprimirCodigoBarrasPDF417');
{$IFDEF WIN32}
Assert(@imprimirCodigoBarrasPDF417 <> nil);
{$ENDIF}
@imprimirLogo := GetProcAddress(DLLHandle,'imprimirLogo');
{$IFDEF WIN32}
Assert(@imprimirLogo <> nil);
{$ENDIF}
@imprimirLogoSequencial := GetProcAddress(DLLHandle,'imprimirLogoSequencial');
{$IFDEF WIN32}
Assert(@imprimirLogoSequencial <> nil);
{$ENDIF}
@imprimirQRcode := GetProcAddress(DLLHandle,'imprimirQRcode');
{$IFDEF WIN32}
Assert(@imprimirQRcode <> nil);
{$ENDIF}
@imprimirTexto := GetProcAddress(DLLHandle,'imprimirTexto');
{$IFDEF WIN32}
Assert(@imprimirTexto <> nil);
{$ENDIF}
@imprimirTextoPreDefinido := GetProcAddress(DLLHandle,'imprimirTextoPreDefinido');
{$IFDEF WIN32}
Assert(@imprimirTextoPreDefinido <> nil);
{$ENDIF}
@imprimirVersoCheque := GetProcAddress(DLLHandle,'imprimirVersoCheque');
{$IFDEF WIN32}
Assert(@imprimirVersoCheque <> nil);
{$ENDIF}
@lerCMC7 := GetProcAddress(DLLHandle,'lerCMC7');
{$IFDEF WIN32}
Assert(@lerCMC7 <> nil);
{$ENDIF}
@lerStatus := GetProcAddress(DLLHandle,'lerStatus');
{$IFDEF WIN32}
Assert(@lerStatus <> nil);
{$ENDIF}
@obrigarImpressao := GetProcAddress(DLLHandle,'obrigarImpressao');
{$IFDEF WIN32}
Assert(@obrigarImpressao <> nil);
{$ENDIF}
@obterModeloImpressora := GetProcAddress(DLLHandle,'obterModeloImpressora');
{$IFDEF WIN32}
Assert(@obterModeloImpressora <> nil);
{$ENDIF}
@obterVersaoBiblioteca := GetProcAddress(DLLHandle,'obterVersaoBiblioteca');
{$IFDEF WIN32}
Assert(@obterVersaoBiblioteca <> nil);
{$ENDIF}
@obterVersaoFirmware := GetProcAddress(DLLHandle,'obterVersaoFirmware');
{$IFDEF WIN32}
Assert(@obterVersaoFirmware <> nil);
{$ENDIF}
@posicionarDocumento := GetProcAddress(DLLHandle,'posicionarDocumento');
{$IFDEF WIN32}
Assert(@posicionarDocumento <> nil);
{$ENDIF}
@reiniciarImpressora := GetProcAddress(DLLHandle,'reiniciarImpressora');
{$IFDEF WIN32}
Assert(@reiniciarImpressora <> nil);
{$ENDIF}
@selecionaAlturaCodigoBarras := GetProcAddress(DLLHandle,'selecionaAlturaCodigoBarras');
{$IFDEF WIN32}
Assert(@selecionaAlturaCodigoBarras <> nil);
{$ENDIF}
@selecionaCodificacaoCaracteres := GetProcAddress(DLLHandle,'selecionaCodificacaoCaracteres');
{$IFDEF WIN32}
Assert(@selecionaCodificacaoCaracteres <> nil);
{$ENDIF}
@selecionaFonteHRICodigoBarras := GetProcAddress(DLLHandle,'selecionaFonteHRICodigoBarras');
{$IFDEF WIN32}
Assert(@selecionaFonteHRICodigoBarras <> nil);
{$ENDIF}
@selecionaLarguraCodigoBarras := GetProcAddress(DLLHandle,'selecionaLarguraCodigoBarras');
{$IFDEF WIN32}
Assert(@selecionaLarguraCodigoBarras <> nil);
{$ENDIF}
@selecionaPosicaoHRICodigoBarras := GetProcAddress(DLLHandle,'selecionaPosicaoHRICodigoBarras');
{$IFDEF WIN32}
Assert(@selecionaPosicaoHRICodigoBarras <> nil);
{$ENDIF}
@verificarCodificacaoCaracteres := GetProcAddress(DLLHandle,'verificarCodificacaoCaracteres');
{$IFDEF WIN32}
Assert(@verificarCodificacaoCaracteres <> nil);
{$ENDIF}
@verificarDocumento := GetProcAddress(DLLHandle,'verificarDocumento');
{$IFDEF WIN32}
Assert(@verificarDocumento <> nil);
{$ENDIF}
@verificarGaveta := GetProcAddress(DLLHandle,'verificarGaveta');
{$IFDEF WIN32}
Assert(@verificarGaveta <> nil);
{$ENDIF}
@verificarLogo := GetProcAddress(DLLHandle,'verificarLogo');
{$IFDEF WIN32}
Assert(@verificarLogo <> nil);
{$ENDIF}
@verificarLogoPorId := GetProcAddress(DLLHandle,'verificarLogoPorId');
{$IFDEF WIN32}
Assert(@verificarLogoPorId <> nil);
{$ENDIF}
@verificarPapel := GetProcAddress(DLLHandle,'verificarPapel');
{$IFDEF WIN32}
Assert(@verificarPapel <> nil);
{$ENDIF}
@verificarTampa := GetProcAddress(DLLHandle,'verificarTampa');
{$IFDEF WIN32}
Assert(@verificarTampa <> nil);
{$ENDIF}
@verificarTextoPreDefinido := GetProcAddress(DLLHandle,'verificarTextoPreDefinido');
{$IFDEF WIN32}
Assert(@verificarTextoPreDefinido <> nil);
{$ENDIF}
@verificarTextoPreDefinidoPorId := GetProcAddress(DLLHandle,'verificarTextoPreDefinidoPorId');
{$IFDEF WIN32}
Assert(@verificarTextoPreDefinidoPorId <> nil);
{$ENDIF}
end
else
begin
DLLLoaded := False;
{ Error: TGCSSUREMARK.DLL could not be loaded !! }
end;
{$IFNDEF MSDOS}
SetErrorMode(ErrorMode)
{$ENDIF}
end {LoadDLL};
begin
LoadDLL;
end.
|
unit uCSVUpdater;
interface
uses System.Classes, System.SysUtils, System.Types,
System.Generics.Defaults, System.Generics.Collections,
Functional.Value;
Const
ALWAYS_FOLLOW_LINK_FILES = true;
DONT_FOLLOW_LINK_FILES = false;
type
TValidatedFilename = record
private
Name: string;
InvalidReason: string;
IsValid: boolean;
public
Procedure Clear;
procedure AssignFrom(AValidatedFilename: TValidatedFilename);
function Validate(AFilename: string): string;
class operator Implicit(AFileName: string): TValidatedFilename;
End;
TCSVUpdater = class
constructor Create(AFilename: string);
destructor Destroy; override;
private
fFilename: string;
fHeaders: TStringList;
fBody : TStringList;
fLastError: string;
function FileLoadedOrLoadsSuccessfully(AFilename: TValidatedFilename): boolean;
function HeaderLoadedOrLoadsSuccessfully: boolean;
function getRowByIndex(AIndex: integer): string;
procedure setRowByIndex(AIndex: integer; const Value: string);
function getRowByValue(AHeader: string; AValue: string): string;
function getHeaders: string;
function getFileLoaded: boolean;
public
property FileLoaded : boolean read getFileLoaded;
property Filename: string read FFilename;
property Headers : string read getHeaders;
property Row[AIndex : integer] : string read getRowbyIndex write setRowByIndex;
end;
implementation
{ TCSVUpdater }
constructor TCSVUpdater.Create(AFilename: string);
begin
fHeaders := TStringlist.Create;
fBody := TStringList.Create;
fHeaders.QuoteChar := '"';
fHeaders.Delimiter := ',';
fHeaders.LineBreak := #13#10;
fBody.QuoteChar := '"';
fBody.LineBreak := #13#10;
fBody.Delimiter := '"';
fFilename := ExpandFileName(AFilename);
end;
destructor TCSVUpdater.Destroy;
begin
freeandNil(Self.fBody);
freeandNil(self.fHeaders);
inherited;
end;
function TCSVUpdater.FileLoadedOrLoadsSuccessfully(AFilename: TValidatedFilename): boolean;
begin
Result := (Self.fBody.Count>0);
if Result then exit;
if (AFilename.IsValid) then
try
self.fBody.LoadFromFile(AFilename.Name);
result := true;
except
on e:exception do
begin
// What conditions do we want to handle???
self.fLastError := e.Message;
raise;
end;
end;
end;
function TCSVUpdater.getFileLoaded: boolean;
begin
Result := FileLoadedOrLoadsSuccessfully(Filename);
end;
function TCSVUpdater.getHeaders: string;
begin
if HeaderLoadedOrLoadsSuccessfully then
result := self.fHeaders.Text;
end;
function TCSVUpdater.getRowByIndex(AIndex: integer): string;
begin
result := '';
if (AIndex>1) then raise Exception.Create('Row must be >= 1'); // Truly an exception
if (self.FileLoaded) and (Aindex<=self.fBody.Count) then
result := self.fBody[AIndex-1];
end;
function TCSVUpdater.getRowByValue(AHeader, AValue: string): string;
begin
end;
function TCSVUpdater.HeaderLoadedOrLoadsSuccessfully: boolean;
begin
Result := FileLoaded and (fHeaders.Count>0);
if (not Result) and (Self.fBody.Count>0) then
begin
self.fHeaders.DelimitedText := self.fBody[0];
result := self.fHeaders.Count>0;
end;
end;
procedure TCSVUpdater.setRowByIndex(AIndex: integer; const Value: string);
begin
end;
{ TValidatedFilename }
procedure TValidatedFilename.AssignFrom(AValidatedFilename: TValidatedFilename);
begin
Name := AValidatedFilename.Name;
IsValid := AValidatedFilename.IsValid;
InvalidReason := AValidatedFilename.InvalidReason;
end;
procedure TValidatedFilename.Clear;
begin
self.Name := '';
self.isValid := false;
self.InvalidReason := 'No file name has been set.';
end;
{ TValidatedFilenameHelper }
class operator TValidatedFilename.Implicit(AFileName: string): TValidatedFilename;
begin
Result.Clear;
Result.Validate(AFilename);
end;
function TValidatedFilename.Validate(AFilename: string): string;
begin
Result := '';
Clear;
Name := AFilename;
if (Name<>'') and
not (FileExists(Name, ALWAYS_FOLLOW_LINK_FILES)) then
InvalidReason := format('File %s does not exist', [Name])
else
begin
IsValid := true;
InvalidReason := '';
Result := Name;
end;
end;
end.
|
unit fLibItemProps;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls, FlexLibs, FlexUtils;
type
TfmLibItemProps = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
pbItemView: TPaintBox;
bbOk: TBitBtn;
Label1: TLabel;
edTitle: TEdit;
Label2: TLabel;
edDesc: TEdit;
bbCancel: TBitBtn;
procedure pbItemViewPaint(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
LibItem: TFlexLibItem;
end;
var
fmLibItemProps: TfmLibItemProps;
implementation
{$R *.DFM}
procedure TfmLibItemProps.pbItemViewPaint(Sender: TObject);
var CoeffX, CoeffY: double;
Scale: integer;
Origin: TPoint;
begin
with pbItemView, Canvas do begin
Brush.Color := clWindow;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, Width, Height));
if not Assigned(LibItem) then exit;
CoeffX := ((Width - 20)* PixelScaleFactor) / LibItem.Width;
CoeffY := ((Height -20)* PixelScaleFactor) / LibItem.Height;
if CoeffX < CoeffY
then Scale := Round(100*CoeffX)
else Scale := Round(100*CoeffY);
Origin.X := -(Width - ScaleValue(LibItem.Width, Scale)) div 2;
Origin.Y := -(Height - ScaleValue(LibItem.Height, Scale)) div 2;
LibItem.Owner.PaintTo(Canvas, Rect(0, 0, Width, Height),
Origin, Scale, LibItem, True, True, False, False);
end;
end;
end.
|
{*******************************************************}
{ }
{ Delphi Runtime Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
{ *************************************************************************** }
{ }
{ Licensees holding a valid Borland No-Nonsense License for this Software may }
{ use this file in accordance with such license, which appears in the file }
{ license.txt that came with this Software. }
{ }
{ *************************************************************************** }
unit Web.DBXpressWeb;
interface
uses System.SysUtils, System.Classes, Web.HTTPApp, Web.HTTPProd, Data.DB, Web.DBWeb, Data.SqlExpr;
type
{ TSQLQueryTableProducer }
TSQLQueryTableProducer = class(TDSTableProducer)
private
FQuery: TSQLQuery;
procedure SetQuery(AQuery: TSQLQuery);
protected
function GetDataSet: TDataSet; override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure SetDataSet(ADataSet: TDataSet); override;
public
function Content: string; override;
published
property Caption;
property CaptionAlignment;
property Columns;
property Footer;
property Header;
property MaxRows;
property Query: TSQLQuery read FQuery write SetQuery;
property RowAttributes;
property TableAttributes;
property OnCreateContent;
property OnFormatCell;
property OnGetTableCaption;
end;
implementation
{ TSQLQueryTableProducer }
function TSQLQueryTableProducer.Content: string;
var
Params: TStrings;
I: Integer;
Name: string;
Param: TParam;
begin
Result := '';
if FQuery <> nil then
begin
FQuery.Close;
Params := nil;
if Dispatcher <> nil then
if Dispatcher.Request.MethodType = mtPost then
Params := Dispatcher.Request.ContentFields
else if Dispatcher.Request.MethodType = mtGet then
Params := Dispatcher.Request.QueryFields;
if Params <> nil then
for I := 0 to Params.Count - 1 do
begin
Name := Params.Names[I];
Param := FQuery.Params.ParamByName(Name);
if Param <> nil then
Param.Text := Params.Values[Name];
end;
FQuery.Open;
if DoCreateContent then
Result := Header.Text + HTMLTable(FQuery, Self, MaxRows) + Footer.Text;
end;
end;
function TSQLQueryTableProducer.GetDataSet: TDataSet;
begin
Result := FQuery;
end;
procedure TSQLQueryTableProducer.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if (Operation = opRemove) and (AComponent = FQuery) then
FQuery := nil;
end;
procedure TSQLQueryTableProducer.SetDataSet(ADataSet: TDataSet);
begin
SetQuery(ADataSet as TSQLQuery);
end;
procedure TSQLQueryTableProducer.SetQuery(AQuery: TSQLQuery);
begin
if FQuery <> AQuery then
begin
if AQuery <> nil then AQuery.FreeNotification(Self);
FQuery := AQuery;
InternalDataSource.DataSet := FQuery;
end;
end;
end.
|
program CATFreePascal;
{$mode delphiunicode}{$H+}
uses
{$IFDEF UNIX}{$IFDEF UseCThreads}
cthreads,
{$ENDIF}{$ENDIF}
Classes, SysUtils, CustApp, Types, FileUtil,
CompilerUtils, iDStringParser, Operators, iDPascalParser,
PascalCompiler, CompilerClasses, ILInstructions, CompilerMessages, CompilerErrors,
ILMachineTypes, ILTypeInfo, ILMachineInvoke, ILMachineTranslator, ILMachine, SystemUnit,
VM_INTF, VM_CRI, CATNativeCallsTests, VM_System, VM_SysUtils, VM_DateUtils
{ you can add units after this };
type
{ TMyApplication }
TMyApplication = class(TCustomApplication)
private
FSuccessCnt, FFailCnt, FSkipCnt: Integer;
FRTTICharset: TRTTICharset;
function CompileSource(const Src: string; ILStream: TMemoryStream; out ErrorString: string): TCompilerResult;
function VMRun(ILStream: TMemoryStream; out Messages: string; ShowVMCode: Boolean): Boolean;
procedure RunALLTests(const Path: string);
procedure RunTest(const RootDir, FileName: string; ShowVMCode: Boolean);
protected
procedure DoRun; override;
public
constructor Create(TheOwner: TComponent); override;
destructor Destroy; override;
procedure WriteHelp; virtual;
end;
{ TMyApplication }
function TMyApplication.CompileSource(const Src: string; ILStream: TMemoryStream; out ErrorString: string): TCompilerResult;
var
UN: TUnit;
Package: IPackage;
SearchPath: string;
begin
Package := TPackage.Create('test');
try
SearchPath := ExtractFilePath(Params[0]) + 'units' + PathDelim;
Package.AddUnitSearchPath(SearchPath);
Package.IncludeDebugInfo := True;
Package.RTTICharset := FRTTICharset;
UN := TUnit.Create(Package, Src);
Package.AddUnit(SystemUnit.SYSUnit, nil);
Package.AddUnit(UN, nil);
Result := UN.Compile;
Package.SaveToStream(ILStream);
ErrorString := Package.Messages.GetAsString;
finally
Package.Clear;
FreeAndNil(SYSUnit);
end;
end;
procedure ShowVMOut(VM: TILMachine);
var
i, j: Integer;
pUnit: PExportUnit;
pVar: PExportVariable;
begin
for i := 0 to VM.UnitsCount - 1 do
begin
pUnit := @VM.Units[i];
if pUnit.VarsCount > -0 then
begin
WriteLn('------------------');
WriteLn('UNIT: ' + VM.GetUnitName(pUnit));
WriteLn('------------------');
WriteLn('GLOBAL VARS:');
WriteLn('');
for j := 0 to pUnit.VarsCount - 1 do
begin
pVar := @pUnit.Variables[j];
WriteLn(format('%d: %s = %s', [j, VM.GetVarName(pVar), VM.ReadVarValue(pVar)]));
end;
end;
end;
end;
function TMyApplication.VMRun(ILStream: TMemoryStream; out Messages: string; ShowVMCode: Boolean): Boolean;
var
VMStream: TMemoryStream;
VMT: TILMachineTranslator;
VM: TILMachine;
//Str: TStringStream;
//FStr: TFileStream;
Level: Integer;
begin
Level := 0;
try
Result := False;
VMStream := TMemoryStream.Create;
VMT := TILMachineTranslator.Create;
VMT.RTTICharset := FRTTICharset;
VMT.IncludeRTTI := True;
VM := TILMachine.Create();
try
VMT.LoadFromStream(ILStream);
Level := 1;
{if ShowVMCode then
begin
Str := TStringStream.Create(VMT.DebugOut);
FStr := TFileStream.Create(ExtractFilePath(Params[0]) + 'VMCode.txt', fmCreate);
Str.Position := 0;
FStr.CopyFrom(Str, Str.size);
FStr.Free;
Str.Free;
end;}
VMT.SavePreprared(VMStream);
Level := 2;
//VMStream.SaveToFile(ExtractFilePath(Params[0]) + 'VMCode.bin');
VMStream.Position := 0;
VM.LoadPreprared(VMStream);
Level := 3;
try
VM.Run();
Level := 4;
except
ShowVMOut(VM);
raise;
end;
Result := True;
finally
if ShowVMCode then
ShowVMOut(VM);
FreeAndNil(VM);
FreeAndNil(VMT);
FreeAndNil(VMStream);
end;
except
on e: exception do
Messages := 'Level: ' + IntToStr(Level) + ' ' + e.Message;
end;
end;
procedure TMyApplication.RunTest(const RootDir, FileName: string; ShowVMCode: Boolean);
var
Str: TFileStream;
Source: UnicodeString;
Messages: String;
ILStream: TMemoryStream;
CR: TCompilerResult;
TestName: string;
begin
TestName := PathDelim + ExtractRelativepath(RootDir, FileName);
Str := TFileStream.Create(FileName, fmOpenRead);
try
Str.Position := 0;
Source := Str.AsUTF8String();
ILStream := TMemoryStream.Create;
try
CR := CompileSource(Source, ILStream, Messages);
case CR of
CompileFail: begin
Inc(FFailCnt);
WriteLn(TestName + '...FAIL');
WriteLn('Messages: ' + Messages);
Exit;
end;
CompileSkip: begin
Inc(FSkipCnt);
WriteLn(TestName + '...SKIP');
Exit;
end;
else
WriteLn(TestName + '...COMPILE SUCCESS');
ILStream.Position := 0;
if VMRun(ILStream, Messages, ShowVMCode) then
begin
Inc(FSuccessCnt);
WriteLn(TestName + '...SUCCESS');
end else begin
Inc(FFailCnt);
WriteLn(TestName + '...FAIL');
WriteLn('Messages: ' + Messages);
end;
end;
finally
ILStream.free;
end;
finally
Str.Free;
end;
end;
procedure TMyApplication.RunALLTests(const Path: string);
var
FileName: string;
Files: TStrArray;
i: Integer;
begin
Files := CompilerUtils.GetDirectoryFiles(Path, '*.pas', True);
for i := 0 to Length(Files) - 1 do
begin
FileName := Files[i];
//if Pos('1 - import FORMAT.pas', FileName) > 0 then
// if (Pos('tariff_script.pas', FileName) > 0)
// (Pos('cpp_test1.pas', FileName) > 0) or
// (Pos('cpp_test2.pas', FileName) > 0) or
// if Pos('datetime_test_1.pas', FileName) > 0 then
RunTest(Path, FileName, False);
// if i > 10 then
// Exit;
end;
end;
procedure TMyApplication.DoRun;
var
ErrorMsg: String;
RootPath: string;
begin
// quick check parameters
ErrorMsg:=CheckOptions('h', 'help');
if ErrorMsg<>'' then begin
ShowException(Exception.Create(ErrorMsg));
Terminate;
Exit;
end;
// parse parameters
if HasOption('h', 'help') then begin
WriteHelp;
Terminate;
Exit;
end;
{ add your program here }
WriteLn('COMPILER AUTO TEST (CAT) console version');
RootPath := ExtractFilePath(Params[0]) + 'tests' + PathDelim;
FRTTICharset := RTTICharsetUTF16;
WriteLn('TESTS path: ' + RootPath);
WriteLn('-----------------------------------------------------------------------');
RunALLTests(RootPath);
WriteLn('-----------------------------------------------------------------------');
WriteLn('TOTAL Sucess: ', FSuccessCnt, ' Fail: ', FFailCnt, ' Skip: ', FSkipCnt);
{$IFNDEF CPUARM}
ReadLn;
{$ENDIF}
// stop program loop
Terminate;
end;
constructor TMyApplication.Create(TheOwner: TComponent);
begin
inherited Create(TheOwner);
StopOnException:=True;
end;
destructor TMyApplication.Destroy;
begin
inherited Destroy;
end;
procedure TMyApplication.WriteHelp;
begin
{ add your help code here }
writeln('Usage: ', ExeName, ' -h');
end;
var
Application: TMyApplication;
begin
Application:=TMyApplication.Create(nil);
Application.Title:='My Application';
Application.Run;
Application.Free;
end.
|
{$A+,B-,D+,E-,F-,G+,I+,L+,N+,O-,P-,Q-,R-,S-,T-,V+,X+,Y+}
{$M 1024,0,0}
{
by Behdad Esfahbod
Algorithmic Problems Book
August '1999
Problem 1 O(N) Trivial Method
}
program
FunctionValueCalculation;
const
MaxN = 1000;
var
N, I, J, K : Integer;
F : array [1 .. MaxN] of Integer;
begin
Readln(N);
I := 0;
J := 0;
F[1] := 1;
F[2] := 2;
while I < N do
begin
Inc(J);
for K := 1 to F[J] do
begin
Inc(I);
F[I] := J;
if I = N then Break;
end;
end;
Writeln(F[N]);
end.
|
{*******************************************************}
{ }
{ CodeGear Delphi Runtime Library }
{ Copyright(c) 2014-2019 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
unit RSConsole.FormConnection;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes,
System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
RSConsole.FrameSettings, FMX.Controls.Presentation, FMX.StdCtrls;
type
TConnectionForm = class(TForm)
SettingsFrame: TSettingsFrame;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SettingsFrameCloseButtonClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
procedure SetTitle(const ATitle: String);
end;
var
ConnectionForm: TConnectionForm;
implementation
{$R *.fmx}
uses
RSConsole.Form, RSConsole.Consts;
procedure TConnectionForm.SetTitle(const ATitle: String);
begin
Caption := strRSFormTitle + ATitle;
end;
procedure TConnectionForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
if ConnectionForm.Visible then
Action := TCloseAction.caHide;
end;
procedure TConnectionForm.FormCreate(Sender: TObject);
var
DefaultLoaded: Boolean;
begin
MainForm.ApplyStyle(ConnectionForm);
DefaultLoaded := SettingsFrame.ShowDefaultProfile;
SettingsFrame.Enabled := DefaultLoaded;
MainForm.ViewsLayout.Enabled := DefaultLoaded;
end;
procedure TConnectionForm.SettingsFrameCloseButtonClick(Sender: TObject);
begin
MainForm.RefreshEndpoints;
SettingsFrame.CloseButtonClick(Sender);
end;
end.
|
{Ejercicio 8
Dado un fragmento de texto que debe ser leído de la entrada estándar,
todo en una línea, y terminado por el caracter $ (centinela), determine
y exhiba las consonantes y vocales que aparecen duplicadas en forma contigua.
Por ejemplo, el texto "llama al chico que lee$" tiene una consonante doble (ll)
y una vocal doble (ee) y se debería desplegar: "ll ee". Asuma que todas las letras son minúsculas.}
program ejercicio8;
var entrada, aux : char;
begin
writeln('Ingrese un texto continuo, al finalizar ingrese el simbolo $');
read(entrada);
while entrada <> '$' do
begin
aux := entrada;
read(entrada);
if (entrada = aux) then
write(entrada,aux,' ');
end
end. |
unit uCampaigns;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uHeritageScreen, Data.DB,
FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param,
FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf,
FireDAC.Stan.Async, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client,
Vcl.DBCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.Buttons, Vcl.Mask,
Vcl.ExtCtrls, Vcl.ComCtrls, RRPGControls, RLReport, RRPGRichEdit, cCampaigns,
uDTMConnection, uEnum;
type
TfrmCampaigns = class(TfrmHeritageScreen)
pnCampaignInfo: TPanel;
lblCampaignTitlePreview: TLabel;
lblCampaignDescriptionPreview: TLabel;
ledtCampaignId: TLabeledEdit;
ledtCampaignName: TLabeledEdit;
cbCampaignPlayers: TComboBox;
redtPreview: TRRichEdit;
lblCampaignPlayers: TLabel;
lbCampaignPlayers: TListBox;
SpeedButton1: TSpeedButton;
lblPreview: TLabel;
imgCampaign: TImage;
scrbCampaignInfo: TScrollBox;
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnAlterClick(Sender: TObject);
procedure grdListingCellClick(Column: TColumn);
private
{ Private declarations }
oCampaigns:TCampaigns;
function Delete : Boolean; override;
function Save(Status:TStatus): Boolean; override;
public
{ Public declarations }
end;
var
frmCampaigns: TfrmCampaigns;
implementation
{$R *.dfm}
{$region 'Override'}
function TfrmCampaigns.Save(Status: TStatus): Boolean;
begin
if ledtCampaignId.Text<>EmptyStr then
oCampaigns.campaignId := StrToInt(ledtCampaignId.Text)
else
oCampaigns.campaignId := 0;
oCampaigns.name := ledtCampaignName.Text;
oCampaigns.description := redtPreview.Text;
if (Status = ecInsert) then
Result := oCampaigns.Save
else
if (Status = ecAlter) then
Result := oCampaigns.Update;
end;
procedure TfrmCampaigns.btnAlterClick(Sender: TObject);
begin
if oCampaigns.Select(QryListing.FieldByName('id').AsInteger) then
begin
ledtCampaignId.Text := IntToStr(oCampaigns.campaignId);
ledtCampaignName.Text := oCampaigns.name;
redtPreview.Text := oCampaigns.description;
end
else
begin
btnCancel.Click;
abort;
end;
inherited;
end;
function TfrmCampaigns.Delete: Boolean;
begin
if oCampaigns.Select(QryListing.FieldByName('id').AsInteger) then
begin
Result := oCampaigns.Delete;
end;
end;
{$endregion}
procedure TfrmCampaigns.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
if Assigned(oCampaigns) then
FreeAndNil(oCampaigns);
end;
procedure TfrmCampaigns.FormCreate(Sender: TObject);
begin
inherited;
oCampaigns := TCampaigns.Create(dtmConnection.dbConnection);
CurrentIndex := 'description'
end;
procedure TfrmCampaigns.grdListingCellClick(Column: TColumn);
begin
inherited;
if oCampaigns.Select(QryListing.FieldByName('id').AsInteger) then
lblCampaignTitlePreview.Caption := QryListing.FieldByName('name').Text;
lblCampaignDescriptionPreview.Caption := QryListing.FieldByName('description').Text;
end;
end.
|
unit Optimizer.Hibernation;
interface
uses
SysUtils,
OS.EnvironmentVariable, Optimizer.Template, Global.LanguageString,
OS.ProcessOpener;
type
THibernationOptimizer = class(TOptimizationUnit)
public
function IsOptional: Boolean; override;
function IsCompatible: Boolean; override;
function IsApplied: Boolean; override;
function GetName: String; override;
procedure Apply; override;
procedure Undo; override;
end;
implementation
function THibernationOptimizer.IsOptional: Boolean;
begin
exit(false);
end;
function THibernationOptimizer.IsCompatible: Boolean;
begin
exit(IsBelowWindows8);
end;
function THibernationOptimizer.IsApplied: Boolean;
begin
if not IsBelowWindows8 then
exit(false);
result :=
not FileExists(EnvironmentVariable.WinDrive + '\hiberfil.sys');
end;
function THibernationOptimizer.GetName: String;
begin
exit(CapOptHiber[CurrLang]);
end;
procedure THibernationOptimizer.Apply;
begin
ProcessOpener.OpenProcWithOutput(
EnvironmentVariable.WinDrive,
EnvironmentVariable.WinDir + '\System32\cmd.exe /C powercfg -h off');
end;
procedure THibernationOptimizer.Undo;
begin
ProcessOpener.OpenProcWithOutput(
EnvironmentVariable.WinDrive,
EnvironmentVariable.WinDir + '\System32\cmd.exe /C powercfg -h on');
end;
end.
|
unit setbit_0;
interface
implementation
var
V: Int32;
procedure Test;
begin
setbit(V, 1, True);
end;
initialization
Test();
finalization
Assert(V = 2);
end. |
{-------------------------------------------------------------------------------
// EasyComponents For Delphi 7
// 一轩软研第三方开发包
// @Copyright 2010 hehf
// ------------------------------------
//
// 本开发包是公司内部使用,作为开发工具使用任何,何海锋个人负责开发,任何
// 人不得外泄,否则后果自负.
//
// 使用权限以及相关解释请联系何海锋
//
//
// 网站地址:http://www.YiXuan-SoftWare.com
// 电子邮件:hehaifeng1984@126.com
// YiXuan-SoftWare@hotmail.com
// QQ :383530895
// MSN :YiXuan-SoftWare@hotmail.com
//------------------------------------------------------------------------------
//单元说明:
// 本单元是工程的最基本单元,本框架下的所有窗体都必须从此基窗体继承
//
//主要实现:
// 1、回车->Tab
// 设置KeyPreView为True,则在按下回车键等同于按下Tab键
// 2、FormId
// 所有继承的窗体都必须指定一个FormId做为Bpl包导出时的唯一身份标识
//
// 注:(Ctrl+Shift+G 组合键生成GUID) {} {合计38位长度 }
// '{00000000-0000-0000-0000-000000000000}' {表示基窗体 }
// '{11111111-1111-1111-1111-111111111111}' {表示查询窗体}
// 3、开发商信息发布
// LegalCompanyName : String; //公司名称 W
// FileDescription : String; //文件描述 RW
// FileVersion : String; //文件版本 RW
// LegalCopyright : String; //合法版权描述 RW
// 4、TO-DO
// 多语言功能:
// 从Login界面根据用户选择的语言编号,传递到DMEasyConnection公共属性
// EasyLangID中,由各界面在Create时动态从Lang配置文件INI下读取Caption
// 5、初始化配置ClientDataSet、Provider等属性,两层下将Provider动态创建
//-----------------------------------------------------------------------------}
unit untEasyPlateBaseForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, ShlObj, IniFiles, DB, DBClient, TypInfo,
Provider, ExtCtrls, untEasyGroupBox, untEasyWaterImage;
type
TfrmEasyPlateBaseForm = class(TForm)
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
FEasyApplicationHandle: THandle;
FFormId : String;
FLangID : string; //语言类别
FEasyAppPath : string; //应用程序运行路径
FEasyPlugPath: string; //插件存放路径
FEasyImagePath: string; //系统所使用的图片存放路径
FIsKeyPreView: Boolean;
FEasyRootGUID : string; //根节点和根窗体的GUID
FLegalCompanyName : String; //公司名称
FFileDescription : String; //文件描述
FFileVersion : String; //文件版本
FLegalCopyright : String; //合法版权描述
procedure SetFormId(const Value: string);
procedure SetIsKeyPreView(const Value: Boolean);
procedure SetFileDescription(const Value: string);
function GetFormId: string;
function GetKeyPreView: Boolean;
function GetFileDescription: string;
function GetFileVersion: string;
function GetLegalCopyright: string;
procedure SetFileVersion(const Value: string);
procedure SetLegalCopyright(const Value: string);
function GetLangID: string;
procedure SetLangID(const Value: string);
//设置控件的显示属性
procedure SetControlCaption(ALangINIFile: TStrings);
protected
procedure DoShow; override;
procedure DoClose(var Action: TCloseAction); override;
procedure KeyPress(var Key: Char); override;
procedure CreateParams(var Params:TCreateParams);override;
//改变界面语言
procedure ChangeLang(LanguageId: string); virtual;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
//系统局柄
property EasyApplicationHandle: Cardinal read FEasyApplicationHandle;
property FormId: string read GetFormId write SetFormId;
property IsKeyPreView: Boolean read GetKeyPreView write SetIsKeyPreView;
//系统提示信息
function EasyErrorHint(AHint: string): Integer; virtual;
function EasyConfirmHint(AHint: string): Integer; virtual;
function EasyWarningHint(AHint: string): Integer; virtual;
function EasyHint(AHint: string): Integer; virtual;
function EasySelectHint(AHint: string): Integer; virtual;
//获取用户指定模块指定操作的权限
function GetUserRight: Boolean; virtual;
//语言代码
property LangID: string read GetLangID write SetLangID;
//以下为公司版权信息
property LegalCompanyName: string read FLegalCompanyName write FLegalCompanyName;
property FileDescription: string read GetFileDescription write SetFileDescription;
property FileVersion: string read GetFileVersion write SetFileVersion;
property LegalCopyright: string read GetLegalCopyright write SetLegalCopyright;
//系统路径属性
property EasyApplicationPath: string read FEasyAppPath write FEasyAppPath;
property EasyPlugPath: string read FEasyPlugPath write FEasyPlugPath;
property EasyRootGUID: string read FEasyRootGUID write FEasyRootGUID;
property EasyImagePath: string read FEasyImagePath write FEasyImagePath;
end;
var
frmEasyPlateBaseForm: TfrmEasyPlateBaseForm;
implementation
{$R *.dfm}
uses untEasyDBConnection;
{ TfrmEasyBaseFormExt }
function TfrmEasyPlateBaseForm.GetFormId: string;
begin
Result := FFormId;
end;
function TfrmEasyPlateBaseForm.GetKeyPreView: Boolean;
begin
Result := FIsKeyPreView;
end;
procedure TfrmEasyPlateBaseForm.SetFormId(const Value: string);
begin
FFormId := Value;
end;
procedure TfrmEasyPlateBaseForm.SetIsKeyPreView(const Value: Boolean);
begin
FIsKeyPreView := Value;
if FIsKeyPreView then
KeyPreview := FIsKeyPreView;
end;
procedure TfrmEasyPlateBaseForm.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
// if BorderStyle = bsNone then
// Params.Style := Params.Style Xor WS_CAPTION ;
// if BorderStyle <> bsNone then
// Params.Style := WS_THICKFRAME or WS_POPUP or WS_BORDER;
end;
procedure TfrmEasyPlateBaseForm.DoClose(var Action: TCloseAction);
begin
Action := caFree;
inherited;
end;
procedure TfrmEasyPlateBaseForm.DoShow;
begin
inherited;
end;
procedure TfrmEasyPlateBaseForm.KeyPress(var Key: Char);
begin
if ActiveControl <> nil then
begin
if (Key = #13) and KeyPreview then
begin
//如果控件Tag值被30求余5、不移动焦点到下一个控件
if (ActiveControl.Tag mod 30)=5 then
Exit;
Perform(WM_NEXTDLGCTL, 0, 0);
Key := #0;
end;
end;
inherited KeyPress(Key);
end;
function TfrmEasyPlateBaseForm.GetFileDescription: string;
begin
Result := FFileDescription;
end;
procedure TfrmEasyPlateBaseForm.SetFileDescription(const Value: string);
begin
FFileDescription := Value;
end;
constructor TfrmEasyPlateBaseForm.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FIsKeyPreView := True;
FFormId := '{00000000-0000-0000-0000-000000000000}';
FLegalCompanyName := '一轩软件研发有限公司';
FEasyApplicationHandle := DMEasyDBConnection.EasyApplicationHandle;
end;
function TfrmEasyPlateBaseForm.GetFileVersion: string;
begin
Result := FileVersion;
end;
function TfrmEasyPlateBaseForm.GetLegalCopyright: string;
begin
Result := LegalCopyright;
end;
procedure TfrmEasyPlateBaseForm.SetFileVersion(const Value: string);
begin
FFileVersion := Value;
end;
procedure TfrmEasyPlateBaseForm.SetLegalCopyright(const Value: string);
begin
FLegalCopyright := Value;
end;
procedure TfrmEasyPlateBaseForm.FormCreate(Sender: TObject);
var
I : Integer;
cdsName,
dspName : String;
ATmpDsp : TDataSetProvider;
begin
FEasyAppPath := ExtractFilePath(Application.ExeName);
FEasyPlugPath := FEasyAppPath + 'plugins\';
FEasyImagePath := FEasyAppPath + 'images\';
FEasyRootGUID := '{00000000-0000-0000-0000-000000000000}';
for i := 0 to ComponentCount - 1 do
begin
//创建ClientDataSet的相关设置
//EasyAppType当前程序运行模式:CS两层 CAS三层
if DMEasyDBConnection.EasyAppType = 'CS' then
begin
if (Components[I] is TClientDataSet) then
begin
cdsName := TClientDataSet(Components[I]).Name;
dspName := TClientDataSet(Components[I]).ProviderName;
//如果TWaxDataSetProvider不存在才自动创建
if FindComponent(dspName) = nil then
begin
if Trim(dspName) = '' then
dspName := 'EasyDSP' + cdsName;
ATmpDsp := TDataSetProvider.Create(Self);
ATmpDsp.Name := dspName;
ATmpDsp.DataSet := DMEasyDBConnection.EasyQry;
ATmpDsp.Options := ATmpDsp.Options + [poAllowCommandText];
end;
(Components[I] as TClientDataSet).ProviderName := ATmpDsp.Name;
end
end{ else if DMEasyDBConnection.EasyAppType = 'CAS' then
begin
if Components[I] is TClientDataSet then
begin
with Components[I] as TClientDataSet do
begin
RemoteServer := DMEasyDBConnection.EasyScktConn;
ProviderName := 'EasyRDMDsp';
end;
end;
end};
end;
end;
procedure TfrmEasyPlateBaseForm.ChangeLang(LanguageId: string);
var
TmpCaptionList: TStrings;
LangINIPath : string;
begin
LangINIPath := EasyApplicationPath + 'lang\' + LanguageId + '\' + FormId + '.ini';
TmpCaptionList := TStringList.Create;
if FileExists(LangINIPath) then
begin
TmpCaptionList.LoadFromFile(LangINIPath);
SetControlCaption(TmpCaptionList);
end;
TmpCaptionList.Free;
end;
function TfrmEasyPlateBaseForm.GetLangID: string;
var
ATmpList: TStrings;
begin
ATmpList := TStringList.Create;
if FileExists(EasyApplicationPath + 'lang\lang.ini') then
begin
ATmpList.LoadFromFile(EasyApplicationPath + 'lang\lang.ini');
if ATmpList.IndexOfName('lang') <> -1 then
Result := ATmpList.Values['lang']
else
Result := 'Chinese';
end
else
Result := 'Chinese';
ATmpList.Free;
end;
procedure TfrmEasyPlateBaseForm.SetLangID(const Value: string);
begin
FLangID := Value;
end;
procedure TfrmEasyPlateBaseForm.SetControlCaption(ALangINIFile: TStrings);
var
I: Integer;
begin
if ALangINIFile.IndexOfName(Self.Name) <> -1 then
Self.Caption := ALangINIFile.Values[Self.Name];
for I := 0 to ComponentCount - 1 do
begin
if GetPropInfo(Components[I], 'Caption') <> nil then
begin
if ALangINIFile.IndexOfName(Components[I].Name) <> -1 then
SetPropValue(Components[I], 'Caption', ALangINIFile.Values[Components[I].Name]);
end
else
if GetPropInfo(Components[I], 'Text') <> nil then
begin
if ALangINIFile.IndexOfName(Components[I].Name) <> -1 then
SetPropValue(Components[I], 'Text', ALangINIFile.Values[Components[I].Name]);
end;
end;
end;
function TfrmEasyPlateBaseForm.EasyConfirmHint(AHint: string): Integer;
begin
Result := Application.MessageBox(PChar(AHint), PChar(Application.Title),
MB_OKCANCEL + MB_ICONQUESTION);
end;
function TfrmEasyPlateBaseForm.EasyErrorHint(AHint: string): Integer;
begin
Result := Application.MessageBox(PChar(AHint), PChar(Application.Title), MB_OK +
MB_ICONSTOP);
end;
function TfrmEasyPlateBaseForm.EasyHint(AHint: string): Integer;
begin
Result := Application.MessageBox(PChar(AHint), PChar(Application.Title), MB_OK +
MB_ICONINFORMATION);
end;
function TfrmEasyPlateBaseForm.EasySelectHint(AHint: string): Integer;
begin
Result := Application.MessageBox(PChar(AHint), PChar(Application.Title),
MB_YESNOCANCEL + MB_ICONQUESTION);
end;
function TfrmEasyPlateBaseForm.EasyWarningHint(AHint: string): Integer;
begin
Result := Application.MessageBox(PChar(AHint), PChar(Application.Title), MB_OK +
MB_ICONWARNING);
end;
function TfrmEasyPlateBaseForm.GetUserRight: Boolean;
begin
Result := True;
end;
procedure TfrmEasyPlateBaseForm.FormShow(Sender: TObject);
begin
//改变语言设置
ChangeLang(LangID);
end;
end.
|
Unit TERRA_Localization;
{$I terra.inc}
Interface
Uses TERRA_Utils, TERRA_IO;
Const
language_English = 'EN';
language_German = 'DE';
language_French = 'FR';
language_Portuguese= 'PT';
language_Spanish = 'ES';
language_Italian = 'IT';
language_Japanese = 'JP';
language_Chinese = 'ZH';
language_Russian = 'RU';
language_Korean = 'KO';
invalidString = '???';
MaxPinyinSuggestions = 64;
Type
StringEntry = Record
Key:AnsiString;
Value:AnsiString;
Group:Integer;
End;
StringManager = Class(TERRAObject)
Protected
_Lang:AnsiString;
_Strings:Array Of StringEntry;
_StringCount:Integer;
Function GetLang:AnsiString;
Function FormatString(Const Text:AnsiString):AnsiString;
Public
Constructor Create;
Class Function Instance:StringManager;
Procedure SetLanguage(Lang:AnsiString);
Function GetString(Key:AnsiString; Group:Integer = -1):AnsiString;
Function HasString(Key:AnsiString):Boolean;
Procedure SetString(Key, Value:AnsiString; Group:Integer = -1);
Function EmptyString():AnsiString;
Procedure Reload();
Procedure RemoveGroup(GroupID:Integer);
Procedure MergeGroup(Source:Stream; GroupID:Integer);
Property Language:AnsiString Read GetLang Write SetLanguage;
End;
PinyinSuggestion = Record
ID:Word;
Text:AnsiString;
End;
PinyinConverter = Class
Protected
_Suggestions:Array Of PinyinSuggestion;
_SuggestionCount:Integer;
Procedure Match(S:AnsiString);
Public
Constructor Create();
Procedure GetSuggestions(Text:AnsiString);
Function GetResult(Index:Integer):Word;
Function Replace(Var Text:AnsiString; Index:Integer):Boolean;
Property Results:Integer Read _SuggestionCount;
End;
Function GetKoreanInitialJamo(N:Word):Integer;
Function GetKoreanMedialJamo(N:Word):Integer;
Function GetKoreanFinalJamo(N:Word):Integer;
Function MemoryToString(Const N:Cardinal):AnsiString;
Function IsSupportedLanguage(Const Lang:AnsiString):Boolean;
Function GetCurrencyForCountry(Const Country:AnsiString):AnsiString;
Function GetLanguageDescription(Lang:AnsiString):AnsiString;
Implementation
Uses TERRA_Application, TERRA_FileManager, TERRA_Log, TERRA_Unicode;
Var
_Manager:StringManager = Nil;
Function IsSupportedLanguage(Const Lang:AnsiString):Boolean;
Begin
Result := (Lang = language_English) Or (Lang = language_German)
Or (Lang = language_French) Or (Lang = language_Portuguese)
Or (Lang = language_Spanish) Or (Lang = language_Italian)
Or (Lang = language_Japanese) Or (Lang = language_Chinese)
Or (Lang = language_Russian) Or (Lang = language_Korean);
End;
Function GetCurrencyForCountry(Const Country:AnsiString):AnsiString;
Begin
If (Country = 'GB') Then
Begin
Result := 'GBP';
End Else
If (Country = 'RU') Then
Begin
Result := 'RUB';
End Else
If (Country = 'BR') Then
Begin
Result := 'BRL';
End Else
If (Country = 'US') Then
Begin
Result := 'USD';
End Else
If (Country = 'JP') Then
Begin
Result := 'JPY';
End Else
If (Country = 'KR') Then
Begin
Result := 'KRW';
End Else
If (Country = 'UA') Then
Begin
Result := 'UAH';
End Else
If (Country = 'AU') Then
Begin
Result := 'AUD';
End Else
If (Country = 'CA') Then
Begin
Result := 'CAD';
End Else
If (Country = 'ID') Then
Begin
Result := 'IDR';
End Else
If (Country = 'MY') Then
Begin
Result := 'MYR';
End Else
If (Country = 'MX') Then
Begin
Result := 'MXN';
End Else
If (Country = 'NZ') Then
Begin
Result := 'NZD';
End Else
If (Country = 'NO') Then
Begin
Result := 'NOK';
End Else
If (Country = 'PH') Then
Begin
Result := 'PHP';
End Else
If (Country = 'SG') Then
Begin
Result := 'SGD';
End Else
If (Country = 'TH') Then
Begin
Result := 'THB';
End Else
If (Country = 'TR') Then
Begin
Result := 'TRY';
End Else
Begin
Result := 'USD';
End;
End;
Function GetKoreanInitialJamo(N:Word):Integer;
Begin
Case N Of
12593: Result := 0;
12594: Result := 1;
12596: Result := 2;
12599: Result := 3;
12600: Result := 4;
12601: Result := 5;
12609: Result := 6;
12610: Result := 7;
12611: Result := 8;
12613: Result := 9;
12614: Result := 10;
12615: Result := 11;
12616: Result := 12;
12617: Result := 13;
12618: Result := 14;
12619: Result := 15;
12620: Result := 16;
12621: Result := 17;
12622: Result := 18;
Else
Result := -1;
End;
End;
Function GetKoreanMedialJamo(N:Word):Integer;
Begin
Case N Of
12623: Result := 0;
12624: Result := 1;
12625: Result := 2;
12626: Result := 3;
12627: Result := 4;
12628: Result := 5;
12629: Result := 6;
12630: Result := 7;
12631: Result := 8;
12632: Result := 9;
12633: Result := 10;
12634: Result := 11;
12635: Result := 12;
12636: Result := 13;
12637: Result := 14;
12638: Result := 15;
12639: Result := 16;
12640: Result := 17;
12641: Result := 18;
12642: Result := 19;
12643: Result := 20;
Else
Result := -1;
End;
End;
Function GetKoreanFinalJamo(N:Word):Integer;
Begin
Case N Of
12593: Result := 1;
12594: Result := 2;
12595: Result := 3;
12596: Result := 4;
12597: Result := 5;
12598: Result := 6;
12599: Result := 7;
12601: Result := 8;
12602: Result := 9;
12603: Result := 10;
12604: Result := 11;
12605: Result := 12;
12606: Result := 13;
12607: Result := 14;
12608: Result := 15;
12609: Result := 16;
12610: Result := 17;
12612: Result := 18;
12613: Result := 19;
12614: Result := 20;
12615: Result := 21;
12616: Result := 22;
12618: Result := 23;
12619: Result := 24;
12620: Result := 25;
12621: Result := 26;
12622: Result := 27;
Else
Result := -1;
End;
End;
Function MemoryToString(Const N:Cardinal):AnsiString;
Var
Ext:AnsiChar;
X:Single;
Int,Rem:Integer;
Begin
If (N>=1 Shl 30)Then
Begin
X:=N/(1 Shl 30);
Int:=Trunc(X);
Rem:=Trunc(Frac(X)*10);
Ext:='G';
End Else
If (N>=1 Shl 20)Then
Begin
X:=N/(1 Shl 20);
Int:=Trunc(X);
Rem:=Trunc(Frac(X)*10);
Ext:='M';
End Else
If (N>=1 Shl 10)Then
Begin
X:=N/(1 Shl 10);
Int:=Trunc(X);
Rem:=Trunc(Frac(X)*10);
Ext:='K';
End Else
Begin
Int:=N;
Rem:=0;
Ext:=#0;
End;
Result:=IntToString(Int);
If Rem>0 Then
Result:=Result+'.'+IntToString(Rem);
Result:=Result+' ';
If Ext<>#0 Then
Result:=Result+Ext;
If (Application.Instance<>Nil) And (Application.Instance.Language = language_Russian) Then
Result := Result + UnicodeToUCS2(1073)
Else
Result := Result + 'b';
End;
{ StringManager }
Constructor StringManager.Create;
Begin
_Lang := '';
If Assigned(Application.Instance()) Then
SetLanguage(Application.Instance.Language)
Else
SetLanguage('EN');
End;
Function StringManager.EmptyString:AnsiString;
Begin
Result := InvalidString;
End;
Function StringManager.GetLang:AnsiString;
Begin
If (_Lang ='') And (Assigned(Application.Instance())) Then
SetLanguage(Application.Instance.Language);
Result := _Lang;
End;
Procedure StringManager.SetString(Key, Value:AnsiString; Group:Integer = -1);
Var
I:Integer;
Begin
Key := UpStr(Key);
For I:=0 To Pred(_StringCount) Do
If (_Strings[I].Key = Key) Then
Begin
_Strings[I].Value := Value;
_Strings[I].Group := Group;
Exit;
End;
Inc(_StringCount);
SetLength(_Strings, _StringCount);
_Strings[Pred(_StringCount)].Key := UpStr(Key);
_Strings[Pred(_StringCount)].Value := FormatString(Value);
_Strings[Pred(_StringCount)].Group := Group;
End;
Function StringManager.GetString(Key:AnsiString; Group:Integer):AnsiString;
Var
I:Integer;
Begin
If (_Lang ='') And (Assigned(Application.Instance())) Then
SetLanguage(Application.Instance.Language);
Key := UpStr(Key);
For I:=0 To Pred(_StringCount) Do
If (_Strings[I].Key = Key) And ((_Strings[I].Group = Group) Or (Group<0)) Then
Begin
Result := _Strings[I].Value;
Exit;
End;
Log(logWarning, 'Strings', 'String value for ['+Key+'] not found!');
Result := Self.EmptyString;
End;
Class Function StringManager.Instance:StringManager;
Begin
If Not Assigned(_Manager) Then
_Manager := StringManager.Create;
Result := _Manager;
End;
Procedure StringManager.MergeGroup(Source: Stream; GroupID:Integer);
Var
Ofs, I:Integer;
S, S2:AnsiString;
Begin
If (Source = Nil ) Then
Exit;
Log(logDebug, 'Strings', 'Merging strings from '+Source.Name);
Ofs := _StringCount;
S := '';
While Not Source.EOF Do
Begin
Source.ReadUnicodeLine(S);
S := TrimLeft(S);
If S='' Then
Continue;
I := Pos(',', S);
S2 := Copy(S, 1, Pred(I));
S2 := TrimRight(S2);
S := Copy(S, Succ(I), MaxInt);
S := TrimLeft(S);
Inc(_StringCount);
SetLength(_Strings, _StringCount);
_Strings[Pred(_StringCount)].Key := UpStr(S2);
_Strings[Pred(_StringCount)].Value := S;
_Strings[Pred(_StringCount)].Group := GroupID;
//Log(logDebug, 'Strings', 'Found '+S2 +' = '+S);
End;
For I:=Ofs To Pred(_StringCount) Do
_Strings[I].Value := FormatString(_Strings[I].Value);
End;
Procedure StringManager.SetLanguage(Lang:AnsiString);
Var
S, S2:AnsiString;
Source:Stream;
I:Integer;
Begin
Lang := UpStr(Lang);
If (Lang = 'CH') Or (Lang='CN') Then
Lang := 'ZH';
If (Lang = 'JA') Then
Lang := 'JP';
If (_Lang = Lang) Then
Exit;
S := 'translation_'+Lang+'.txt';
S := LowStr(S);
S := FileManager.Instance.SearchResourceFile(S);
If S='' Then
Begin
Log(logWarning, 'Strings', 'Could not find translation file for lang='+Lang);
If (Lang<>language_English) Then
SetLanguage(language_English);
Exit;
End;
_StringCount := 0;
Source := FileManager.Instance.OpenStream(S);
_Lang := Lang;
Self.MergeGroup(Source, -1);
Source.Destroy;
If Application.Instance<>Nil Then
Application.Instance.Language := Lang;
End;
Procedure StringManager.Reload();
Var
S:AnsiString;
Begin
S := _Lang;
_Lang := '';
SetLanguage(S);
End;
Procedure StringManager.RemoveGroup(GroupID: Integer);
Var
I:Integer;
Begin
I := 0;
While (I<_StringCount) Do
If (_Strings[I].Group = GroupID) Then
Begin
_Strings[I] := _Strings[Pred(_StringCount)];
Dec(_StringCount);
End Else
Inc(I);
End;
Function StringManager.HasString(Key:AnsiString): Boolean;
Begin
Result := GetString(Key)<>Self.EmptyString;
End;
Function StringManager.FormatString(Const Text:AnsiString):AnsiString;
Var
I,J,N:Integer;
Len:Integer;
S2, S3, S:AnsiString;
C:AnsiChar;
Begin
I := ucs2_Pos('@', Text);
If I<=0 Then
Begin
Result := Text;
Exit;
End;
S := Text;
S2 := ucs2_Copy(S, 1, Pred(I));
S := ucs2_Copy(S, Succ(I), MaxInt);
N := 0;
J := 1;
Len := ucs2_Length(S);
While J<=Len Do
Begin
C := ucs2_ascii(S, J);
If ((C>='a') And (C<='z')) Or ((C>='A') And (C<='Z')) Or ((C>='0') And (C<='9')) Or (C='_') Then
Begin
N := J;
Inc(J);
End Else
Break;
End;
If (N>0) Then
Begin
S3 := ucs2_Copy(S, 1, N);
S := ucs2_Copy(S, Succ(N), MaxInt);
S3 := Self.GetString(S3);
End Else
S3 := '';
Result := S2 + S3 + S;
I := ucs2_Pos('@', Result);
If I>0 Then
Begin
Result := FormatString(Result);
StringToInt(result+text);
End;
End;
Type
PinyinEntry = Record
ID:Word;
Text:AnsiString;
End;
Var
_PinyinCount:Integer;
_PinyinData:Array Of PinyinEntry;
{ PinyinConverter }
Constructor PinyinConverter.Create;
Var
Src:Stream;
I:Integer;
Begin
If (_PinyinCount>0) Then
Exit;
Src := FileManager.Instance.OpenStream('pinyin.dat');
If Src = Nil Then
Exit;
Src.Read(@_PinyinCount, 4);
SetLength(_PinyinData ,_PinyinCount);
I := 0;
While (Not Src.EOF) And (I<_PinyinCount) Do
Begin
Src.Read(@_PinyinData[I].ID, 2);
Src.ReadString(_PinyinData[I].Text);
Inc(I);
End;
End;
Procedure PinyinConverter.GetSuggestions(Text:AnsiString);
Const
MaxLength = 7;
Var
N, I:Integer;
Temp:AnsiString;
Begin
_SuggestionCount :=0 ;
N := -1;
I := Length(Text);
While I>=1 Do
If (Text[I]=#255) Then
Begin
N := I + 3;
Break;
End Else
Dec(I);
If (N>0) Then
Text := Copy(Text, N, MaxInt);
If (Text='') Then
Exit;
If Length(Text)>MaxLength Then
Text := Copy(Text, Length(Text)-MaxLength, MaxInt);
Text := LowStr(Text);
Temp := Text;
While Text<>'' Do
Begin
Match(Text);
Text := Copy(Text, 2, MaxInt);
End;
Text := Temp;
While Text<>'' Do
Begin
Match(Text);
Text := Copy(Text, 1, Pred(Length(Text)));
End;
End;
Function PinyinConverter.GetResult(Index: Integer): Word;
Begin
If (Index>=0) And (Index<Self.Results) Then
Result := _Suggestions[Index].ID
Else
Result := 0;
End;
Procedure PinyinConverter.Match(S:AnsiString);
Var
I:Integer;
Begin
If (_SuggestionCount>=MaxPinyinSuggestions) Then
Exit;
For I:=0 To Pred(_PinyinCount) Do
If (_PinyinData[I].Text = S) Then
Begin
Inc(_SuggestionCount);
SetLength(_Suggestions, _SuggestionCount);
_Suggestions[Pred(_SuggestionCount)].ID := _PinyinData[I].ID;
_Suggestions[Pred(_SuggestionCount)].Text := S;
End;
End;
Function PinyinConverter.Replace(var Text:AnsiString; Index: Integer):Boolean;
Var
I:Integer;
S,S2:AnsiString;
Begin
Result := False;
I := PosRev(_Suggestions[Index].Text, Text);
If (I<=0) Then
Exit;
S := Copy(Text, 1, Pred(I));
S2 := Copy(Text, I+Length(_Suggestions[Index].Text), MaxInt);
Text := S + UnicodeToUCS2(_Suggestions[Index].ID) + S2;
Result := True;
End;
Function GetLanguageDescription(Lang:AnsiString):AnsiString;
Begin
Lang := UpStr(Lang);
If Lang = language_English Then
Result := 'English'
Else
If Lang = language_German Then
Result := 'Deutsch'
Else
If Lang = language_Spanish Then
Result := 'Español'
Else
If Lang = language_Portuguese Then
Result := 'Português'
Else
If Lang = language_French Then
Result := 'Français'
Else
If Lang = language_Italian Then
Result := 'Italiano'
Else
If Lang = language_Russian Then
Result := #255#4#32#255#4#67#255#4#65#255#4#65#255#4#58#255#4#56#255#4#57
Else
If Lang = language_Korean Then
Result := #255#213#92#255#174#0
Else
If Lang = language_Japanese Then
Result := #255#101#229#255#103#44#255#48#110
Else
If Lang = language_Chinese Then
Result := #255#78#45#255#86#253
Else
Result := invalidString;
End;
Initialization
Finalization
If Assigned(_Manager) Then
_Manager.Destroy;
End. |
////////////////////////////////////////////
// Базовый класс для построителя запросов к устройствам
////////////////////////////////////////////
unit Devices.ReqCreatorBase;
interface
uses Windows, GMGlobals, GMConst, StdRequest;
type
TGMAddRequestToSendBufProc = procedure (ReqDetails: TRequestDetails) of object;
TDevReqCreator = class
private
FAddRequestToSendBuf: TGMAddRequestToSendBufProc;
FAllowEmpty: bool;
protected
FReqDetails: TRequestDetails;
property AllowEmpty: bool read FAllowEmpty write FAllowEmpty;
procedure AddStringRequestToSendBuf(sRequest: string; rqtp: T485RequestType);
procedure AddBufRequestToSendBuf(buf: array of byte; Len: int; rqtp: T485RequestType);
procedure AddUniversalRequestToSendBuf(req: IXMLGMIORequestType; rqtp: T485RequestType; const login: string);
function PrepareCommand(var prmIds: TChannelIds; var Val: double): bool; virtual;
function SetChannelValue(DevNumber, ID_Src, N_Src: int; Val: double; timeHold: int): bool; overload; virtual;
public
constructor Create(AddRequestToSendBuf: TGMAddRequestToSendBufProc; ReqDetails: TRequestDetails); virtual;
procedure AddRequests(); virtual; abstract;
function SetChannelValue(prmIds: TChannelIds; Val: double; timeHold: int): bool; overload;
end;
TDevReqCreatorClass = class of TDevReqCreator;
implementation
{ TDevReqCreator }
constructor TDevReqCreator.Create(AddRequestToSendBuf: TGMAddRequestToSendBufProc; ReqDetails: TRequestDetails);
begin
inherited Create();
FAllowEmpty := false;
FAddRequestToSendBuf := AddRequestToSendBuf;
FReqDetails := ReqDetails;
end;
function TDevReqCreator.PrepareCommand(var prmIds: TChannelIds; var Val: double): bool;
begin
Result := true;
end;
function TDevReqCreator.SetChannelValue(prmIds: TChannelIds; Val: double; timeHold: int): bool;
begin
Result := PrepareCommand(prmIds, Val) and SetChannelValue(prmIds.NDevNumber, prmIds.RealSrc(), prmIds.N_Src, Val, timeHold);
end;
function TDevReqCreator.SetChannelValue(DevNumber, ID_Src, N_Src: int; Val: double; timeHold: int): bool;
begin
Result := false;
end;
procedure TDevReqCreator.AddStringRequestToSendBuf(sRequest: string; rqtp: T485RequestType);
var buf: array [0..50] of byte;
begin
WriteString(buf, 0, sRequest);
AddBufRequestToSendBuf(buf, Length(sRequest), rqtp);
end;
procedure TDevReqCreator.AddUniversalRequestToSendBuf(req: IXMLGMIORequestType; rqtp: T485RequestType; const login: string);
var buffers: TTwoBuffers;
begin
buffers.RequestUniversal(req.XML, login, true, 255, 0);
FReqDetails.BufCnt := buffers.LengthSend;
FReqDetails.rqtp := rqtp;
WriteBuf(FReqDetails.buf, 0, buffers.BufSend, FReqDetails.BufCnt);
if rqtp = rqtCommand then
FReqDetails.Priority := rqprCommand;
FAddRequestToSendBuf(FReqDetails);
FReqDetails.LogRequest();
end;
procedure TDevReqCreator.AddBufRequestToSendBuf(buf: array of byte; Len: int; rqtp: T485RequestType);
begin
if not FAllowEmpty and (Len <= 0) then Exit;
FReqDetails.rqtp := rqtp;
FReqDetails.BufCnt := Len;
WriteBuf(FReqDetails.buf, 0, buf, FReqDetails.BufCnt);
if rqtp = rqtCommand then
FReqDetails.Priority := rqprCommand;
FAddRequestToSendBuf(FReqDetails);
FReqDetails.LogRequest();
end;
end.
|
{*
* Miscelaneous.pas
*
* Miscelaneous functions which are not placed in a proper unit yet.
*
* Copyright (c) 2006-2007 by the MODELbuilder developers team
* Originally written by Darius Blaszijk, <dhkblaszyk@zeelandnet.nl>
* Creation date: 13-May-2006
* Website: www.modelbuilder.org
*
* This file is part of the MODELbuilder component library (MCL)
* and licensed under the LGPL, see COPYING.LGPL included in
* this distribution, for details about the copyright.
*
*}
unit Miscelaneous;
{$mode objfpc}{$H+}
interface
uses
SysUtils, Process, Dialogs, LCLProc;
resourcestring
rsBrowserExecutableNotProperlySet = 'Browser executable not properly set, '
+'please correct setting.';
rsError = 'Error';
type
TVariableTypeSet = (vtVariable, vtConstant);
function IsNumeric(const Value: string): boolean;
procedure OpenURLinBrowser(BrowserExec, BrowserParameters, URL: string); overload;
implementation
function IsNumeric(const Value: string): boolean;
var
dValue: extended;
Code: integer;
begin
Val(Value, dValue, Code);
Result := (Code = 0);
end;
procedure OpenURLinBrowser(BrowserExec, BrowserParameters, URL: string);
var
TheProcess: TProcess;
BrowserCommand: string;
begin
if not FileExists(BrowserExec) then
begin
MessageDlg(rsError, rsBrowserExecutableNotProperlySet, mtError,[mbCancel],0);
exit;
end;
TheProcess:=TProcess.Create(nil);
try
TheProcess.Options:= [poUsePipes, poNoConsole, poStdErrToOutput];
TheProcess.ShowWindow := swoNone;
BrowserCommand := Format(BrowserExec + ' ' + BrowserParameters,[URL]);
TheProcess.CommandLine:=BrowserCommand;
try
TheProcess.Execute;
finally
TheProcess.Free;
end;
except
on E: Exception do begin
DebugLn('OpenURLinBrowser: OpenURL ERROR: ',E.Message);
end;
end;
end;
end.
|
unit Canvases;
interface
uses Windows, Graphics, GDIPAPI, GDIPOBJ, SysUtils, RootObject;
type
TPointEx = record
X : Extended;
Y : Extended;
end;
IMyCanvas = interface
['{E3D5A3FD-FE49-414F-AF6C-92A5AF2C4630}']
procedure SetDC(DC: HDC);
procedure SetBrushColor(Color: TColor);
procedure FillRect(const Rect: TRect);
procedure SetPen(Color: TColor; Width: integer);
procedure MoveTo(const Point: TPointEx);
procedure LineTo(const Point: TPointEx);
function GetCurPoint: TPointEx;
function TextWidth(const Text: string): integer;
procedure TextOut(const Pos: TPoint; const Text: string);
procedure DrawBitmap(Bmp: TBitmap; x, y: integer);
end;
TCurPointHolder = class(TRootObject)
protected
CurPoint: TPointEx;
public
function GetCurPoint: TPointEx;
end;
TVclCanvas = class(TCurPointHolder, IMyCanvas)
private
Canvas: TCanvas;
public
constructor Create; override;
destructor Destroy; override;
procedure SetDC(DC: HDC);
procedure SetBrushColor(Color: TColor);
procedure FillRect(const Rect: TRect);
procedure SetPen(Color: TColor; Width: integer);
procedure MoveTo(const Point: TPointEx);
procedure LineTo(const Point: TPointEx);
function TextWidth(const Text: string): integer;
procedure TextOut(const Pos: TPoint; const Text: string);
procedure DrawBitmap(Bmp: TBitmap; x, y: integer);
end;
TGdiPlusCanvas = class(TCurPointHolder, IMyCanvas)
private
Context: TGPGraphics;
Brush: TGPSolidBrush;
Font: HFont;
Pen: TGPPen;
DC: HDC;
procedure CreateFont;
public
constructor Create; override;
destructor Destroy; override;
procedure SetDC(ADC: HDC);
procedure SetBrushColor(Color: TColor);
procedure FillRect(const Rect: TRect);
procedure SetPen(Color: TColor; Width: integer);
procedure MoveTo(const Point: TPointEx);
procedure LineTo(const Point: TPointEx);
function TextWidth(const Text: string): integer;
procedure TextOut(const Pos: TPoint; const Text: string);
procedure DrawBitmap(Bmp: TBitmap; x, y: integer);
end;
implementation
{ TCurPointHolding }
function TCurPointHolder.GetCurPoint: TPointEx;
begin
Result := CurPoint;
end;
{ TVclCanvas }
constructor TVclCanvas.Create;
begin
Canvas := TCanvas.Create;
end;
destructor TVclCanvas.Destroy;
begin
Canvas.Free;
inherited;
end;
procedure TVclCanvas.SetDC(DC: HDC);
begin
if DC <> 0 then
Canvas.Handle := DC;
end;
procedure TVclCanvas.DrawBitmap(Bmp: TBitmap; x, y: integer);
begin
Canvas.Draw(x, y, Bmp);
end;
procedure TVclCanvas.SetPen(Color: TColor; Width: integer);
begin
Canvas.Pen.Color := Color;
Canvas.Pen.Width := Width;
end;
function TVclCanvas.TextWidth(const Text: string): integer;
begin
Result := Canvas.TextWidth(Text);
end;
procedure TVclCanvas.TextOut(const Pos: TPoint; const Text: string);
begin
Canvas.TextOut(Pos.X, Pos.Y, Text);
end;
procedure TVclCanvas.MoveTo(const Point: TPointEx);
begin
CurPoint := Point;
Canvas.MoveTo(round(Point.x), round(Point.y));
end;
procedure TVclCanvas.LineTo(const Point: TPointEx);
begin
CurPoint := Point;
Canvas.LineTo(round(Point.x), round(Point.y));
end;
procedure TVclCanvas.FillRect(const Rect: TRect);
begin
Canvas.FillRect(Rect);
end;
procedure TVclCanvas.SetBrushColor(Color: TColor);
begin
Canvas.Brush.Color := Color;
end;
{ TGdiPlusCanvas }
constructor TGdiPlusCanvas.Create;
begin
Brush := TGPSolidBrush.Create(aclBlack);
Pen := TGPPen.Create(aclBlack);
end;
procedure TGdiPlusCanvas.CreateFont;
var
f: TLogFont;
begin
FillChar(f, sizeof(f), 0);
f.lfFaceName := 'Tahoma';
f.lfHeight := -11;
Font := CreateFontIndirect(f);
DeleteObject(SelectObject(DC, Font));
end;
destructor TGdiPlusCanvas.Destroy;
begin
Pen.Free;
Brush.Free;
Context.Free;
inherited;
end;
procedure TGdiPlusCanvas.SetDC(ADC: HDC);
begin
DC := ADC;
FreeAndNil(Context);
if DC = 0 then
Exit;
Context := TGPGraphics.Create(DC);
Context.SetSmoothingMode(SmoothingModeAntiAlias);
if Font = 0 then
CreateFont;
end;
procedure TGdiPlusCanvas.SetPen(Color: TColor; Width: integer);
begin
Pen.SetColor(ColorRefToARGB(Color));
Pen.SetWidth(Width);
end;
function TGdiPlusCanvas.TextWidth(const Text: string): integer;
var
size: TSize;
begin
GetTextExtentPoint32(DC, Text, Length(Text), size);
Result := size.cx;
end;
procedure TGdiPlusCanvas.TextOut(const Pos: TPoint; const Text: string);
begin
Windows.TextOut(DC, Pos.X, Pos.Y, PChar(Text), Length(Text));
end;
procedure TGdiPlusCanvas.DrawBitmap(Bmp: TBitmap; x, y: integer);
begin
BitBlt(DC, x, y, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
end;
procedure TGdiPlusCanvas.MoveTo(const Point: TPointEx);
begin
CurPoint := Point;
end;
procedure TGdiPlusCanvas.LineTo(const Point: TPointEx);
begin
Context.DrawLine(Pen, CurPoint.X, CurPoint.Y, Point.X, Point.Y);
CurPoint := Point;
end;
procedure TGdiPlusCanvas.FillRect(const Rect: TRect);
begin
Context.FillRectangle(Brush, MakeRect(Rect));
end;
procedure TGdiPlusCanvas.SetBrushColor(Color: TColor);
begin
Brush.SetColor(ColorRefToARGB(Color));
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireDAC Framework }
{ FireDAC expression custom functions }
{ }
{ Copyright(c) 2004-2018 Embarcadero Technologies, Inc. }
{ All rights reserved }
{ }
{*******************************************************}
{$I FireDAC.inc}
{$HPPEMIT LINKUNIT}
unit FireDAC.Stan.ExprFuncs;
interface
implementation
uses
{$IFDEF MSWINDOWS}
// Preventing from "Inline has not expanded"
Winapi.Windows,
System.Win.ComObj,
{$ENDIF}
System.Classes, System.SysUtils, System.Math,
System.Variants, System.StrUtils, System.DateUtils,
Data.FMTBcd, Data.SQLTimSt,
FireDAC.Stan.Intf, FireDAC.Stan.Expr, FireDAC.Stan.Util, FireDAC.Stan.Error,
FireDAC.Stan.Consts, FireDAC.Stan.SQLTimeInt;
{-------------------------------------------------------------------------------}
procedure ExprTypMisError;
begin
FDException(nil, [S_FD_LStan, S_FD_LStan_PEval], er_FD_ExprTypeMis, []);
end;
{-------------------------------------------------------------------------------}
function FunAbs(const AArgs: array of Variant): Variant;
var
d: Double;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
d := AArgs[0];
Result := Abs(d);
end;
end;
{-------------------------------------------------------------------------------}
function FunCeil(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := Ceil(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunCos(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := Cos(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunCosh(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := Cosh(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunExp(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := Exp(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunFloor(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := Floor(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunLn(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := Ln(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunLog(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if Length(AArgs) = 1 then
Result := Ln(AArgs[0])
else if FDStrIsNull(AArgs[1]) then
Result := Null
else
Result := LogN(AArgs[0], AArgs[1]);
end;
{-------------------------------------------------------------------------------}
function FunMod(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else if AArgs[1] = 0 then
Result := AArgs[0]
else
Result := AArgs[0] mod AArgs[1];
end;
{-------------------------------------------------------------------------------}
function FunPower(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else
Result := Power(AArgs[0], AArgs[1]);
end;
{-------------------------------------------------------------------------------}
function FunRound(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if Length(AArgs) = 1 then
Result := Round(Double(AArgs[0])) + 0.0
else
Result := SimpleRoundTo(Double(AArgs[0]), -Integer(AArgs[1]));
end;
{-------------------------------------------------------------------------------}
function FunSign(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if AArgs[0] > 0.0 then
Result := 1
else if AArgs[0] < 0.0 then
Result := -1
else
Result := 0;
end;
{-------------------------------------------------------------------------------}
function FunSin(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := sin(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunSinh(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := sinh(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunSqrt(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := sqrt(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunTan(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := tan(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunTanh(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := tanh(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunTrunc(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := Trunc(Double(AArgs[0])) + 0.0;
end;
{-------------------------------------------------------------------------------}
function FunChr(const AArgs: array of Variant): Variant;
var
s: String;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
s := Chr(Integer(AArgs[0]));
Result := s;
end;
end;
{-------------------------------------------------------------------------------}
function FunConcat(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := AArgs[1]
else if FDStrIsNull(AArgs[1]) then
Result := AArgs[0]
else
Result := Concat(VarToStr(AArgs[0]), VarToStr(AArgs[1]));
end;
{-------------------------------------------------------------------------------}
function FunInitCap(const AArgs: array of Variant): Variant;
var
s: String;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
s := VarToStr(AArgs[0]);
Result := AnsiUpperCase(Copy(s, 1, 1)) + AnsiLowerCase(Copy(s, 2, MAXINT));
end;
end;
{-------------------------------------------------------------------------------}
function InternalPad(const AArgs: array of Variant; AFront: Boolean): Variant;
var
n: Integer;
s, ps: String;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) or
(Length(AArgs) = 3) and FDStrIsNull(AArgs[2]) then
Result := Null
else begin
s := AArgs[0];
n := AArgs[1];
Dec(n, Length(s));
if Length(AArgs) = 2 then
ps := ' '
else
ps := AArgs[2];
while Length(ps) < n do
ps := ps + ps;
if Length(ps) > n then
ps := Copy(ps, 1, n);
if AFront then
Result := FDStrToVar(ps + s)
else
Result := FDStrToVar(s + ps);
end;
end;
{-------------------------------------------------------------------------------}
function FunLPad(const AArgs: array of Variant): Variant;
begin
Result := InternalPad(AArgs, True);
end;
{-------------------------------------------------------------------------------}
function FunRPad(const AArgs: array of Variant): Variant;
begin
Result := InternalPad(AArgs, False);
end;
{-------------------------------------------------------------------------------}
function FunReplace(const AArgs: array of Variant): Variant;
var
sWhere, sFrom, sTo: String;
i: Integer;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if FDStrIsNull(AArgs[1]) then
Result := AArgs[0]
else begin
sWhere := AArgs[0];
sFrom := AArgs[1];
if Length(AArgs) = 3 then
sTo := AArgs[2]
else
sTo := '';
while True do begin
i := Pos(sFrom, sWhere);
if i = 0 then
Break;
Delete(sWhere, i, Length(sFrom));
if sTo <> '' then
Insert(sTo, sWhere, i);
end;
Result := FDStrToVar(sWhere);
end;
end;
{-------------------------------------------------------------------------------}
function FunTranslate(const AArgs: array of Variant): Variant;
var
sWhere, sFrom, sTo: String;
i, j: Integer;
pCh: PChar;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) or FDStrIsNull(AArgs[2]) then
Result := Null
else begin
sWhere := AArgs[0];
sFrom := AArgs[1];
sTo := AArgs[2];
for i := 1 to Length(sFrom) do begin
pCh := StrScan(PChar(sWhere), sFrom[i]);
if pCh <> nil then begin
j := pCh - PChar(sWhere) + 1;
if i > Length(sTo) then
Delete(sWhere, j, 1)
else
sWhere[j] := sTo[i];
end;
end;
Result := FDStrToVar(sWhere);
end;
end;
{-------------------------------------------------------------------------------}
function FunAscii(const AArgs: array of Variant): Variant;
var
s: String;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
s := AArgs[0];
Result := Ord(s[1]);
end;
end;
{-------------------------------------------------------------------------------}
function FunInstr(const AArgs: array of Variant): Variant;
var
sWhere, sWhat: String;
iCount, iFrom, hBnd: Integer;
pStart, pCh: PChar;
v: Variant;
bReverse: Boolean;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else begin
sWhere := AArgs[0];
sWhat := AArgs[1];
hBnd := Length(AArgs) - 1;
iCount := 1;
iFrom := 1;
bReverse := False;
if hBnd >= 2 then begin
v := AArgs[2];
if FDStrIsNull(v) then begin
Result := Null;
Exit;
end;
iFrom := v;
bReverse := iFrom < 0;
if bReverse then
iFrom := Length(sWhere) + iFrom + 1;
if hBnd >= 3 then begin
v := AArgs[3];
if FDStrIsNull(v) or (v <= 0) then begin
Result := Null;
Exit;
end;
iCount := v;
end;
end;
pStart := PChar(sWhere) + iFrom - 1;
pCh := nil;
while iCount > 0 do begin
if bReverse then begin
pCh := FDStrRPos(pStart, PChar(sWhat));
if pCh = nil then
Break;
pStart := pCh - Length(sWhat);
end
else begin
pCh := StrPos(pStart, PChar(sWhat));
if pCh = nil then
Break;
pStart := pCh + Length(sWhat);
end;
Dec(iCount);
end;
if pCh = nil then
Result := 0
else
Result := pCh - PChar(sWhere) + 1;
end;
end;
{-------------------------------------------------------------------------------}
function FunLength(const AArgs: array of Variant): Variant;
begin
if VarIsNull(AArgs[0]) or VarIsEmpty(AArgs[0]) then
Result := Null
else
Result := Length(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunAddMonths(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else
Result := IncMonth(AArgs[0], AArgs[1]);
end;
{-------------------------------------------------------------------------------}
function FunLastDay(const AArgs: array of Variant): Variant;
var
AYear, AMonth, ADay: Word;
dt: TDateTime;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
dt := AArgs[0];
AYear := 0;
AMonth := 0;
ADay := 0;
DecodeDate(dt, AYear, AMonth, ADay);
ADay := DaysInAMonth(AYear, AMonth);
Result := EncodeDate(AYear, AMonth, ADay) + (dt - Trunc(dt));
TVarData(Result).VType := varDate;
end;
end;
{-------------------------------------------------------------------------------}
function FunFirstDay(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := StartOfTheMonth(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunMonthsBW(const AArgs: array of Variant): Variant;
var
AYear1, AMonth1, ADay1: Word;
AYear2, AMonth2, ADay2: Word;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else begin
AYear1 := 0;
AMonth1 := 0;
ADay1 := 0;
DecodeDate(AArgs[0], AYear1, AMonth1, ADay1);
AYear2 := 0;
AMonth2 := 0;
ADay2 := 0;
DecodeDate(AArgs[1], AYear2, AMonth2, ADay2);
Result := (Integer(AYear1 * 12 * 31 + AMonth1 * 31 + ADay1) -
Integer(AYear2 * 12 * 31 + AMonth2 * 31 + ADay2)) / 31;
end;
end;
{-------------------------------------------------------------------------------}
function FunNextDay(const AArgs: array of Variant): Variant;
var
dt: TDateTime;
nd, d: String;
i: Integer;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else begin
dt := AArgs[0];
nd := AArgs[1];
for i := 1 to 7 do begin
dt := dt + 1;
d := '';
DateTimeToString(d, 'dddd', dt);
if AnsiCompareText(d, nd) = 0 then begin
Result := dt;
Exit;
end;
end;
Result := Null;
end;
end;
{-------------------------------------------------------------------------------}
function FunToChar(const AArgs: array of Variant): Variant;
var
N, i: Integer;
E: Extended;
V: Variant;
rFS: TFormatSettings;
sFormatDate: String;
begin
N := Length(AArgs) - 1;
if FDStrIsNull(AArgs[0]) or
(N > 0) and FDStrIsNull(AArgs[1]) or
(N > 1) and FDStrIsNull(AArgs[2]) then
Result := Null
else begin
V := AArgs[0];
if N > 0 then
if (VarType(V) and varTypeMask) = varDate then begin
rFS.TwoDigitYearCenturyWindow := 50;
rFS.ShortDateFormat := AArgs[1];
sFormatDate := AArgs[1];
for i := 1 to Length(sFormatDate) do
if FDInSet(sFormatDate[i], [' ', '-', '\', '.', '/']) then begin
rFS.DateSeparator := sFormatDate[i];
Break;
end;
Result := FormatDateTime(sFormatDate, V, rFS);
end
else if VarIsNumeric(V) then begin
E := V;
Result := FormatFloat(AArgs[1], E);
end
else if VarIsFMTBcd(V) then
Result := FormatBcd(AArgs[1], VarToBcd(V))
else if VarIsSQLTimeStamp(V) then
Result := SQLTimeStampToStr(AArgs[1], VarToSQLTimeStamp(V))
else
Result := VarAsType(V, varUString)
else
Result := VarAsType(V, varUString);
end;
end;
{-------------------------------------------------------------------------------}
function FunToDate(const AArgs: array of Variant): Variant;
var
N, i: Integer;
sDate: String;
rFS: TFormatSettings;
begin
N := Length(AArgs) - 1;
if FDStrIsNull(AArgs[0]) or
(N > 0) and FDStrIsNull(AArgs[1]) or
(N > 1) and FDStrIsNull(AArgs[2]) then
Result := Null
else begin
sDate := AArgs[0];
rFS.TwoDigitYearCenturyWindow := 50;
if N > 0 then
rFS.ShortDateFormat := AArgs[1]
else
rFS.ShortDateFormat := FormatSettings.ShortDateFormat;
for i := 1 to Length(sDate) do
if not FDInSet(sDate[i], ['0' .. '9', 'a' .. 'z', 'A' .. 'Z', ' ']) then begin
rFS.DateSeparator := sDate[i];
Break;
end;
Result := StrToDate(sDate, rFS);
end;
end;
{-------------------------------------------------------------------------------}
function FunToTime(const AArgs: array of Variant): Variant;
var
N, i: Integer;
sTime: String;
rFS: TFormatSettings;
begin
N := Length(AArgs) - 1;
if FDStrIsNull(AArgs[0]) or
(N > 0) and FDStrIsNull(AArgs[1]) or
(N > 1) and FDStrIsNull(AArgs[2]) then
Result := Null
else begin
sTime := AArgs[0];
rFS.TwoDigitYearCenturyWindow := 50;
if N > 0 then
rFS.ShortTimeFormat := AArgs[1]
else
rFS.ShortTimeFormat := FormatSettings.ShortTimeFormat;
for i := 1 to Length(sTime) do
if not FDInSet(sTime[i], ['0' .. '9', 'a' .. 'z', 'A' .. 'Z', ' ']) then begin
rFS.TimeSeparator := sTime[i];
Break;
end;
Result := StrToTime(sTime, rFS);
end;
end;
{-------------------------------------------------------------------------------}
function VarRemOleStr(const AValue: Variant): Variant;
begin
if VarType(AValue) = varOleStr then
Result := VarAsType(AValue, varUString)
else
Result := AValue;
end;
{-------------------------------------------------------------------------------}
function FunToNumber(const AArgs: array of Variant): Variant;
var
N: Integer;
begin
N := Length(AArgs) - 1;
if FDStrIsNull(AArgs[0]) or
(N > 0) and FDStrIsNull(AArgs[1]) or
(N > 1) and FDStrIsNull(AArgs[2]) then
Result := Null
else
Result := VarAsType(VarRemOleStr(AArgs[0]), varDouble);
end;
{-------------------------------------------------------------------------------}
function FunDecode(const AArgs: array of Variant): Variant;
var
n, i: Integer;
begin
n := Length(AArgs) - 1;
i := 1;
Result := AArgs[0];
while i <= n - 1 do begin
if Result = AArgs[i] then begin
Result := AArgs[i + 1];
Break;
end;
Inc(i, 2);
end;
if i = n then
Result := AArgs[i];
end;
{-------------------------------------------------------------------------------}
function FunNvl(const AArgs: array of Variant): Variant;
begin
Result := AArgs[0];
if FDStrIsNull(Result) then
Result := AArgs[1];
end;
{-------------------------------------------------------------------------------}
function FunGreatest(const AArgs: array of Variant): Variant;
var
n, i: Integer;
begin
n := Length(AArgs) - 1;
Result := AArgs[0];
for i := 0 to n do begin
if FDStrIsNull(AArgs[i]) then begin
Result := Null;
Break;
end;
if Result < AArgs[i] then
Result := AArgs[i];
end;
end;
{-------------------------------------------------------------------------------}
function FunLeast(const AArgs: array of Variant): Variant;
var
n, i: Integer;
begin
n := Length(AArgs) - 1;
Result := AArgs[0];
for i := 0 to n do begin
if FDStrIsNull(AArgs[i]) then begin
Result := Null;
Break;
end;
if Result > AArgs[i] then
Result := AArgs[i];
end;
end;
{-------------------------------------------------------------------------------}
function FunRowNum(const AArgs: array of Variant; const AExpr: IFDStanExpressionEvaluator): Variant;
begin
Result := AExpr.DataSource.RowNum;
end;
{-------------------------------------------------------------------------------}
function FunDatabase(const AArgs: array of Variant; const AExpr: IFDStanExpressionEvaluator): Variant;
begin
Result := AExpr.DataSource.Database;
end;
{-------------------------------------------------------------------------------}
function FunUser(const AArgs: array of Variant; const AExpr: IFDStanExpressionEvaluator): Variant;
begin
Result := AExpr.DataSource.User;
end;
{-------------------------------------------------------------------------------}
function FunInsert(const AArgs: array of Variant): Variant;
var
i, iIndex, iCount: Integer;
sWhat, sTo: String;
begin
for i := 0 to 2 do
if FDStrIsNull(AArgs[i]) then begin
Result := Null;
Exit;
end;
sTo := AArgs[0];
sWhat := AArgs[3];
iIndex := VarAsType(AArgs[1], varInteger);
iCount := VarAsType(AArgs[2], varInteger);
Delete(sTo, iIndex, iCount);
if not FDStrIsNull(AArgs[3]) then
Insert(sWhat, sTo, iIndex);
Result := sTo;
end;
{-------------------------------------------------------------------------------}
function FunLeft(const AArgs: array of Variant): Variant;
var
iIndex: Integer;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if FDStrIsNull(AArgs[1]) then
Result := AArgs[0]
else begin
iIndex := VarAsType(AArgs[1], varInteger);
Result := Copy(VarToStr(AArgs[0]), 1, iIndex);
end;
end;
{-------------------------------------------------------------------------------}
function FunRight(const AArgs: array of Variant): Variant;
var
iIndex: Integer;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if FDStrIsNull(AArgs[1]) then
Result := AArgs[0]
else begin
iIndex := VarAsType(AArgs[1], varInteger);
Result := Copy(VarToStr(AArgs[0]), Length(AArgs[0]) - iIndex + 1, iIndex);
end;
end;
{-------------------------------------------------------------------------------}
function FunPos(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else
Result := Pos(VarToStr(AArgs[0]), VarToStr(AArgs[1]));
end;
{-------------------------------------------------------------------------------}
function FunLocate(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else if (Length(AArgs) > 2) and not FDStrIsNull(AArgs[2]) then
Result := Pos(VarToStr(AArgs[0]), VarToStr(AArgs[1]), AArgs[2])
else
Result := Pos(VarToStr(AArgs[0]), VarToStr(AArgs[1]));
end;
{-------------------------------------------------------------------------------}
function FunRepeat(const AArgs: array of Variant): Variant;
var
i: Integer;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if FDStrIsNull(AArgs[1]) then
Result := AArgs[0]
else begin
Result := '';
for i := 0 to AArgs[1] - 1 do
Result := Result + AArgs[0];
end;
end;
{-------------------------------------------------------------------------------}
function FunSpace(const AArgs: array of Variant): Variant;
var
i: Integer;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
Result := '';
for i := 0 to AArgs[0] - 1 do
Result := Result + ' ';
end;
end;
{-------------------------------------------------------------------------------}
function FunACos(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if (AArgs[0] < -1) or (AArgs[0] > 1) then
Result := Null
else
Result := ArcCos(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunASin(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if (AArgs[0] < -1) or (AArgs[0] > 1) then
Result := Null
else
Result := ArcSin(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunATan(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := ArcTan(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunATan2(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else if AArgs[0] = 0 then
Result := Null
else
Result := ArcTan(AArgs[1] / AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunCot(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else if Tan(AArgs[0]) = 0 then
Result := Null
else
Result := 1 / Tan(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunDegrees(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := 180 / C_FD_Pi * AArgs[0];
end;
{-------------------------------------------------------------------------------}
function FunLog10(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := Log10(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunPi(const AArgs: array of Variant): Variant;
begin
Result := C_FD_Pi;
end;
{-------------------------------------------------------------------------------}
function FunRadians(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := C_FD_Pi / 180 * AArgs[0];
end;
{-------------------------------------------------------------------------------}
function FunRand(const AArgs: array of Variant): Variant;
var
iRange, iLen, i: Integer;
sRange, sVal: String;
begin
if Length(AArgs) = 0 then
Result := Random
else
if (VarType(AArgs[0]) = varUString) or
(VarType(AArgs[0]) = varString) or
(VarType(AArgs[0]) = varOleStr) then begin
sRange := AArgs[0];
if Length(AArgs) >= 2 then
iLen := AArgs[1]
else
iLen := 1;
SetLength(sVal, iLen);
for i := 1 to iLen do
sVal[i] := sRange[1 + Random(Length(sRange))];
Result := sVal;
end
else begin
iRange := VarAsType(AArgs[0], varInteger);
Result := Random(iRange);
end;
end;
{-------------------------------------------------------------------------------}
function FunGetTime(const AArgs: array of Variant): Variant;
begin
Result := Now - Trunc(Now);
end;
{-------------------------------------------------------------------------------}
function FunGetCurDate(const AArgs: array of Variant): Variant;
begin
Result := Trunc(Now) + 0.0;
end;
{-------------------------------------------------------------------------------}
function FunDayName(const AArgs: array of Variant): Variant;
var
s: String;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
s := '';
DateTimeToString(s, 'dddd', TDateTime(VarAsType(AArgs[0], varDouble)));
Result := s;
end
end;
{-------------------------------------------------------------------------------}
function FunDayOfWeek(const AArgs: array of Variant): Variant;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else
Result := DayOfWeek(AArgs[0]);
end;
{-------------------------------------------------------------------------------}
function FunDayOfYear(const AArgs: array of Variant): Variant;
var
Y, M, D: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
Y := 0;
M := 0;
D := 0;
DecodeDate(AArgs[0], Y, M, D);
Result := Integer(Trunc(Double(AArgs[0] - EncodeDate(Y, 1, 1))) + 1);
end
end;
{-------------------------------------------------------------------------------}
function FunExtract(const AArgs: array of Variant): Variant;
var
Y, M, D: Word;
H, MM, S, MS: Word;
sWhat: String;
V: Variant;
rInt: TFDSQLTimeInterval;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else begin
sWhat := Trim(AnsiUpperCase(AArgs[0]));
V := AArgs[1];
if FDVarIsSQLTimeInterval(V) then begin
rInt := FDVar2SQLTimeInterval(V);
if sWhat = 'YEAR' then
Result := rInt.Years
else if sWhat = 'MONTH' then
Result := rInt.Months
else if sWhat = 'DAY' then
Result := rInt.Days
else if sWhat = 'HOUR' then
Result := rInt.Hours
else if sWhat = 'MINUTE' then
Result := rInt.Minutes
else if sWhat = 'SECOND' then
Result := rInt.Seconds
else if sWhat = 'FRAC_SECOND' then
Result := rInt.Fractions * 1000
else
ExprTypMisError;
end
else
begin
Y := 0;
M := 0;
D := 0;
DecodeDate(V, Y, M, D);
H := 0;
MM := 0;
S := 0;
MS := 0;
DecodeTime(V, H, MM, S, MS);
if sWhat = 'YEAR' then
Result := Y
else if sWhat = 'MONTH' then
Result := M
else if sWhat = 'DAY' then
Result := D
else if sWhat = 'HOUR' then
Result := H
else if sWhat = 'MINUTE' then
Result := MM
else if sWhat = 'SECOND' then
Result := S
else if sWhat = 'FRAC_SECOND' then
Result := MS * 1000
else
ExprTypMisError;
end;
end
end;
{-------------------------------------------------------------------------------}
function FunMonthName(const AArgs: array of Variant): Variant;
var
s: String;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
s := '';
DateTimeToString(s, 'mmmm', TDateTime(VarAsType(AArgs[0], varDouble)));
Result := s;
end
end;
{-------------------------------------------------------------------------------}
function FunQuarter(const AArgs: array of Variant): Variant;
var
Y, M, D: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
Y := 0;
M := 0;
D := 0;
DecodeDate(AArgs[0], Y, M, D);
if M < 4 then
Result := 1
else if (M >= 4) and (M < 7) then
Result := 2
else if (M >= 6) and (M < 10) then
Result := 3
else
Result := 4;
end
end;
{-------------------------------------------------------------------------------}
function FunTimeStampAdd(const AArgs: array of Variant): Variant;
var
sWhat: String;
iInterval: Integer;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) or FDStrIsNull(AArgs[2]) then
Result := Null
else begin
sWhat := Trim(AnsiUpperCase(AArgs[0]));
if sWhat = 'FRAC_SECOND' then
Result := VarAsType(((AArgs[2] * MSecsPerDay) + AArgs[1] div 1000) / MSecsPerDay, varDate)
else begin
iInterval := AArgs[1];
if sWhat = 'SECOND' then
Result := ((AArgs[2] * SecsPerDay) + iInterval) / SecsPerDay
else if sWhat = 'MINUTE' then
Result := ((AArgs[2] * MinsPerDay) + iInterval) / MinsPerDay
else if sWhat = 'HOUR' then
Result := ((AArgs[2] * HoursPerDay) + iInterval) / HoursPerDay
else if sWhat = 'DAY' then
Result := AArgs[2] + iInterval
else if sWhat = 'WEEK' then
Result := AArgs[2] + iInterval * 7
else if sWhat = 'MONTH' then
Result := IncMonth(AArgs[2], iInterval)
else if sWhat = 'QUARTER' then
Result := IncMonth(AArgs[2], iInterval * 3)
else if sWhat = 'YEAR' then
Result := IncMonth(AArgs[2], iInterval * 12)
else
ExprTypMisError;
end;
end;
end;
{-------------------------------------------------------------------------------}
function FunTimeStampDiff(const AArgs: array of Variant): Variant;
var
sWhat: String;
d: TDateTime;
r: Double;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) or FDStrIsNull(AArgs[2]) then
Result := Null
else begin
sWhat := Trim(AnsiUpperCase(AArgs[0]));
d := AArgs[2] - AArgs[1];
if sWhat = 'FRAC_SECOND' then begin
d := MSecsPerDay * d;
Result := Trunc(d) * 1000;
end
else if sWhat = 'SECOND' then begin
d := SecsPerDay * d;
Result := Integer(Trunc(d));
end
else if sWhat = 'MINUTE' then begin
d := MinsPerDay * d;
Result := Integer(Trunc(d));
end
else if sWhat = 'HOUR' then begin
d := HoursPerDay * d;
Result := Integer(Trunc(d));
end
else if sWhat = 'DAY' then
Result := Integer(Trunc(d))
else if sWhat = 'WEEK' then
Result := Integer(Trunc(d / 7))
else if sWhat = 'MONTH' then
Result := Integer(Trunc(d / 30.4375))
else if sWhat = 'QUARTER' then
Result := Integer(Trunc(Trunc(d / 30.4375) / 3))
else if sWhat = 'YEAR' then begin
r := VarAsType(d, varDouble);
if (r / 365 = Trunc(r / 365)) and (r / 365 > 0) then
Result := r / 365
else
Result := Integer(Trunc(d / 365.25));
end
else
ExprTypMisError;
end
end;
{-------------------------------------------------------------------------------}
function FunWeek(const AArgs: array of Variant): Variant;
var
Y, M, D, W: Word;
begin
if FDStrIsNull(AArgs[0]) then
Result := Null
else begin
Y := 0;
M := 0;
D := 0;
DecodeDate(AArgs[0], Y, M, D);
D := Word(Trunc(Double(AArgs[0] - EncodeDate(Y, 1, 1))) + 1);
W := Word(D div 7);
if D mod 7 <> 0 then
Inc(W);
Result := W;
end
end;
{-------------------------------------------------------------------------------}
function FunConvert(const AArgs: array of Variant): Variant;
var
sType: String;
V: Variant;
begin
if FDStrIsNull(AArgs[0]) or FDStrIsNull(AArgs[1]) then
Result := Null
else begin
sType := Trim(AnsiUpperCase(AArgs[0]));
V := AArgs[1];
if sType = 'BIGINT' then
Result := VarAsType(V, varInt64)
else if sType = 'BINARY' then
ExprTypMisError
else if sType = 'BIT' then
Result := VarAsType(V, varBoolean)
else if sType = 'CHAR' then
Result := VarAsType(V, varFDAString)
else if sType = 'DECIMAL' then
Result := VarAsType(V, VarFMTBcd)
else if sType = 'DOUBLE' then
Result := VarAsType(VarRemOleStr(V), varDouble)
else if sType = 'FLOAT' then
Result := VarAsType(VarRemOleStr(V), varDouble)
else if sType = 'GUID' then
Result := GUIDToString(StringToGUID(V))
else if sType = 'INTEGER' then
Result := VarAsType(V, varInteger)
else if (sType = 'INTERVAL_MONTH') or (sType = 'INTERVAL_YEAR') or
(sType = 'INTERVAL_YEAR_TO_MONTH') or (sType = 'INTERVAL_DAY') or
(sType = 'INTERVAL_HOUR') or (sType = 'INTERVAL_MINUTE') or
(sType = 'INTERVAL_SECOND') or (sType = 'INTERVAL_DAY_TO_HOUR') or
(sType = 'INTERVAL_DAY_TO_MINUTE') or (sType = 'INTERVAL_DAY_TO_SECOND') or
(sType = 'INTERVAL_HOUR_TO_MINUTE') or (sType = 'INTERVAL_HOUR_TO_SECOND') or
(sType = 'INTERVAL_MINUTE_TO_SECOND') or (sType = 'INTERVAL') then
Result := VarAsType(V, FDVarSQLTimeInterval)
else if sType = 'LONGVARBINARY' then
Result := VarAsType(V, varFDAString)
else if sType = 'LONGVARCHAR' then
Result := VarAsType(V, varFDAString)
else if sType = 'NUMERIC' then
Result := VarAsType(V, VarFMTBcd)
else if sType = 'REAL' then
Result := VarAsType(VarRemOleStr(V), varSingle)
else if sType = 'SMALLINT' then
Result := VarAsType(V, varSmallint)
else if sType = 'DATE' then
Result := Trunc(Double(VarAsType(V, varDate))) + 0.0
else if sType = 'TIME' then
Result := VarAsType(V, varDate) - (Trunc(Double(VarAsType(V, varDate))) + 0.0)
else if sType = 'TIMESTAMP' then
Result := VarAsType(V, VarSQLTimeStamp)
else if sType = 'TINYINT' then
Result := VarAsType(V, varShortInt)
else if sType = 'VARBINARY' then
Result := VarAsType(V, varFDAString)
else if sType = 'VARCHAR' then
Result := VarAsType(V, varFDAString)
else if sType = 'WCHAR' then
Result := VarAsType(V, varUString)
else if sType = 'WLONGVARCHAR' then
Result := VarAsType(V, varUString)
else if sType = 'WVARCHAR' then
Result := VarAsType(V, varUString)
else
ExprTypMisError;
end
end;
{-------------------------------------------------------------------------------}
function FunNewGuid(const AArgs: array of Variant): Variant;
{$IFDEF POSIX}
var
rGUID: TGUID;
{$ENDIF}
begin
{$IFDEF MSWINDOWS}
Result := CreateClassID;
{$ENDIF}
{$IFDEF POSIX}
if CreateGUID(rGUID) = 0 then
Result := GUIDToString(rGUID)
else
Result := Null;
{$ENDIF}
end;
{-------------------------------------------------------------------------------}
procedure RegisterFuncs;
var
oMan: TFDExpressionManager;
begin
oMan := FDExpressionManager();
// ---------------------------------------------
// Oracle's
// Numeric
oMan.AddFunction('ABS', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunAbs);
oMan.AddFunction('CEIL', ckUnknown, 0, dtInt32, -1, 1, 1, 'f', @FunCeil);
oMan.AddFunction('COS', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunCos);
oMan.AddFunction('COSH', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunCosh);
oMan.AddFunction('EXP', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunExp);
oMan.AddFunction('FLOOR', ckUnknown, 0, dtInt32, -1, 1, 1, 'f', @FunFloor);
oMan.AddFunction('LN', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunLn);
oMan.AddFunction('LOG', ckUnknown, 0, dtDouble, -1, 1, 2, 'ff', @FunLog);
oMan.AddFunction('MOD', ckUnknown, 0, dtInt32, -1, 2, 2, 'ii', @FunMod);
oMan.AddFunction('POWER', ckUnknown, 0, dtDouble, -1, 2, 2, 'ff', @FunPower);
oMan.AddFunction('ROUND', ckUnknown, 0, dtDouble, -1, 1, 2, 'fs', @FunRound);
oMan.AddFunction('SIGN', ckUnknown, 0, dtInt32, -1, 1, 1, 'f', @FunSign);
oMan.AddFunction('SIN', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunSin);
oMan.AddFunction('SINH', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunSinh);
oMan.AddFunction('SQRT', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunSqrt);
oMan.AddFunction('TAN', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunTan);
oMan.AddFunction('TANH', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunTanh);
oMan.AddFunction('TRUNC', ckUnknown, 0, dtDouble, -1, 1, 2, 'fs', @FunTrunc);
oMan.AddFunction('ROWNUM', ckField, -1, dtInt32, -1, 0, 0, '', @FunRowNum);
oMan.AddFunction('DATABASE', ckField, -1, dtAnsiString,-1, 0, 0, '', @FunDatabase);
oMan.AddFunction('USER', ckField, -1, dtAnsiString,-1, 0, 0, '', @FunUser);
// Strings, result string
oMan.AddFunction('CHR', ckUnknown, 0, dtAnsiString,-1, 1, 1, 'i', @FunChr);
oMan.AddFunction('CONCAT', ckUnknown, 0, dtUnknown, 0, 2, 2, 'ss', @FunConcat);
oMan.AddFunction('INITCAP', ckUnknown, 0, dtUnknown, 0, 1, 1, 's', @FunInitCap);
oMan.AddFunction('LPAD', ckUnknown, 0, dtUnknown, 0, 2, 3, 'sis', @FunLPad);
oMan.AddSynonym('TRIMLEFT', 'LTRIM');
oMan.AddFunction('REPLACE', ckUnknown, 0, dtUnknown, 0, 2, 3, 'sss', @FunReplace);
oMan.AddFunction('RPAD', ckUnknown, 0, dtUnknown, 0, 2, 3, 'sis', @FunRPad);
oMan.AddSynonym('TRIMRIGHT', 'RTRIM');
oMan.AddSynonym('SUBSTRING', 'SUBSTR');
oMan.AddFunction('TRANSLATE', ckUnknown, 0, dtUnknown, 0, 3, 3, 'sss', @FunTranslate);
// Strings, result integer
oMan.AddFunction('ASCII', ckUnknown, 0, dtInt32, -1, 1, 1, 'a', @FunAscii);
oMan.AddFunction('INSTR', ckUnknown, 0, dtInt32, -1, 2, 4, 'ssii', @FunInstr);
oMan.AddFunction('LENGTH', ckUnknown, 0, dtInt32, -1, 1, 1, 's', @FunLength);
// Date
oMan.AddFunction('ADD_MONTHS',ckUnknown, 0, dtDateTime, -1, 2, 2, 'di', @FunAddMonths);
oMan.AddFunction('MONTHS_BETWEEN',
ckUnknown, 0, dtInt32, -1, 2, 2, 'dd', @FunMonthsBW);
oMan.AddFunction('LAST_DAY', ckUnknown, 0, dtDateTime, -1, 1, 1, 'd', @FunLastDay);
oMan.AddFunction('FIRST_DAY', ckUnknown, 0, dtDateTime, -1, 1, 1, 'd', @FunFirstDay);
oMan.AddFunction('NEXT_DAY', ckUnknown, 0, dtDateTime, -1, 2, 2, 'ds', @FunNextDay);
oMan.AddSynonym('GETDATE', 'SYSDATE');
// Convert
oMan.AddFunction('TO_CHAR', ckUnknown, 0, dtAnsiString,-1, 1, 2, '*s', @FunToChar);
oMan.AddFunction('TO_DATE', ckUnknown, 0, dtDateTime, -1, 1, 2, 'ss', @FunToDate);
oMan.AddFunction('TO_TIME', ckUnknown, 0, dtDateTime, -1, 1, 2, 'ss', @FunToTime);
oMan.AddFunction('TO_NUMBER', ckUnknown, 0, dtDouble, -1, 1, 2, 'ss', @FunToNumber);
// Others
oMan.AddFunction('DECODE', ckUnknown, 2, dtUnknown, 2, 3, MAXINT, '***', @FunDecode);
oMan.AddFunction('NVL', ckUnknown, 0, dtUnknown, 0, 2, 2, '**', @FunNvl);
oMan.AddFunction('GREATEST', ckUnknown, 0, dtUnknown, 0, 1, MAXINT, '*', @FunGreatest);
oMan.AddFunction('LEAST', ckUnknown, 0, dtUnknown, 0, 1, MAXINT, '*', @FunLeast);
// Used in semi-natural language
oMan.AddSynonym('GETDATE', 'TODAY');
// ---------------------------------------------
// ODBC escape funcs
oMan.AddSynonym('CHR', 'CHAR');
oMan.AddSynonym('LENGTH', 'CHAR_LENGTH');
oMan.AddSynonym('CHAR_LENGTH', 'CHARACTER_LENGTH');
oMan.AddFunction('INSERT', ckUnknown, 0, dtAnsiString,-1, 4, 4, 'siis', @FunInsert);
oMan.AddSynonym('LOWER', 'LCASE');
oMan.AddFunction('LEFT', ckUnknown, 0, dtAnsiString,-1, 2, 2, 'si', @FunLeft);
oMan.AddFunction('LOCATE', ckUnknown, 0, dtInt32, -1, 2, 3, 'ssi', @FunLocate);
oMan.AddSynonym('LENGTH', 'OCTET_LENGTH');
oMan.AddFunction('POSITION', ckUnknown, 0, dtInt32, -1, 2, 2, 'ss', @FunPos);
oMan.AddFunction('REPEAT', ckUnknown, 0, dtAnsiString,-1, 2, 2, 'si', @FunRepeat);
oMan.AddFunction('RIGHT', ckUnknown, 0, dtAnsiString,-1, 2, 2, 'si', @FunRight);
oMan.AddFunction('SPACE', ckUnknown, 0, dtAnsiString,-1, 1, 1, 'i', @FunSpace);
oMan.AddSynonym('UPPER', 'UCASE');
oMan.AddFunction('ACOS', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunACos);
oMan.AddFunction('ASIN', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunASin);
oMan.AddFunction('ATAN', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunATan);
oMan.AddFunction('ATAN2', ckUnknown, 0, dtDouble, -1, 2, 2, 'ff', @FunATan2);
oMan.AddFunction('CEILING', ckUnknown, 0, dtInt32, -1, 1, 1, 'f', @FunCeil);
oMan.AddFunction('COT', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunCot);
oMan.AddFunction('DEGREES', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunDegrees);
oMan.AddFunction('LOG10', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunLog10);
oMan.AddFunction('PI', ckConst, 0, dtDouble, -1, 0, 0, '', @FunPi);
oMan.AddFunction('RADIANS', ckUnknown, 0, dtDouble, -1, 1, 1, 'f', @FunRadians);
Randomize;
oMan.AddFunction('RAND', ckUnknown, 0, dtUnknown, 0, 0, 2, '*i', @FunRand);
oMan.AddSynonym('TRUNC', 'TRUNCATE');
oMan.AddFunction('CURRENT_DATE',
ckConst, -1, dtDateTime, -1, 0, 0, '', @FunGetCurDate);
oMan.AddFunction('CURRENT_TIME',
ckConst, -1, dtDateTime, -1, 0, 0, '', @FunGetTime);
oMan.AddSynonym('GETDATE', 'CURRENT_TIMESTAMP');
oMan.AddSynonym('CURRENT_DATE', 'CURDATE');
oMan.AddSynonym('CURRENT_TIME', 'CURTIME');
oMan.AddFunction('DAYNAME', ckUnknown, 0, dtAnsiString,-1, 1, 1, 'd', @FunDayName);
oMan.AddSynonym('DAY', 'DAYOFMONTH');
oMan.AddFunction('DAYOFWEEK', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunDayOfWeek);
oMan.AddFunction('DAYOFYEAR', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunDayOfYear);
oMan.AddFunction('EXTRACT', ckUnknown, 0, dtInt32, -1, 2, 2, 'sd', @FunExtract);
oMan.AddFunction('MONTHNAME', ckUnknown, 0, dtAnsiString,-1, 1, 1, 'd', @FunMonthName);
oMan.AddSynonym('GETDATE', 'NOW');
oMan.AddFunction('QUARTER', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunQuarter);
oMan.AddFunction('TIMESTAMPADD',
ckUnknown, 0, dtDateTime, -1, 3, 3, 'sid', @FunTimeStampAdd);
oMan.AddFunction('TIMESTAMPDIFF',
ckUnknown, 0, dtInt32, -1, 3, 3, 'sdd', @FunTimeStampDiff);
oMan.AddFunction('WEEK', ckUnknown, 0, dtInt16, -1, 1, 1, 'd', @FunWeek);
oMan.AddSynonym('NVL', 'IFNULL');
oMan.AddFunction('CONVERT', ckUnknown, 0, dtUnknown, -1, 2, 2, 's*', @FunConvert);
// ---------------------------------------------
// Other
oMan.AddFunction('NEWGUID', ckConst, -1, dtGUID, -1, 0, 0, '', @FunNewGuid);
end;
{-------------------------------------------------------------------------------}
initialization
RegisterFuncs;
end.
|
unit fAutoSz;
{ provides the basic mechanism to resize all the controls on a form when the form size is
changed. Differs from frmAResize in that this one descends directly from TForm, rather
than TPage }
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, fBase508Form,
VA508AccessibilityManager;
type
TfrmAutoSz = class(TfrmBase508Form)
procedure FormResize(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FSizes: TList;
FAutoSizeDisabled: Boolean;
protected
procedure Loaded; override;
property AutoSizeDisabled: Boolean read FAutoSizeDisabled write FAutoSizeDisabled;
public
end;
var
frmAutoSz: TfrmAutoSz;
implementation
{$R *.DFM}
uses
ORfn, VA508AccessibilityRouter;
type
TSizeRatio = class // records relative sizes and positions for resizing logic
public
FControl: TControl;
FLeft: Extended;
FTop: Extended;
FWidth: Extended;
FHeight: Extended;
constructor Create(AControl: TControl; W, H: Integer);
end;
{ TSizeRatio methods }
constructor TSizeRatio.Create(AControl: TControl; W, H: Integer);
begin
FControl := AControl;
with AControl do
begin
FLeft := Left / W;
FTop := Top / H;
FWidth := Width / W;
FHeight := Height / H;
end;
end;
{ TfrmAutoSz methods }
procedure TfrmAutoSz.Loaded;
{ record initial size & position info for resizing logic }
var
SizeRatio: TSizeRatio;
i,W,H: Integer;
Control: TControl;
begin
inherited Loaded;
FSizes := TList.Create;
if AutoSizeDisabled then Exit;
W := ClientWidth;
H := ClientHeight;
for i := 0 to ComponentCount - 1 do if Components[i] is TControl then
begin
Control := TControl(Components[i]);
W := HigherOf(W, Control.Left + Control.Width);
H := HigherOf(H, Control.Top + Control.Height);
end;
ClientHeight := H;
ClientWidth := W;
for i := 0 to ComponentCount - 1 do if Components[i] is TControl then
begin
SizeRatio := TSizeRatio.Create(TControl(Components[i]), W, H);
FSizes.Add(SizeRatio);
end;
end;
procedure TfrmAutoSz.FormResize(Sender: TObject);
{ resize child controls using their design time proportions }
var
SizeRatio: TSizeRatio;
i, W, H: Integer;
begin
inherited;
if AutoSizeDisabled then Exit;
W := HigherOf(ClientWidth, HorzScrollBar.Range);
H := HigherOf(ClientHeight, VertScrollBar.Range);
with FSizes do for i := 0 to Count - 1 do
begin
SizeRatio := Items[i];
with SizeRatio do
if ((FControl is TLabel) and TLabel(FControl).AutoSize) or ((FControl is TStaticText) and TStaticText(FControl).AutoSize) then
begin
FControl.Left := Round(FLeft*W);
FControl.Top := Round(FTop*H);
end
else FControl.SetBounds(Round(FLeft*W), Round(FTop*H), Round(FWidth*W), Round(FHeight*H));
end; {with FSizes}
end;
procedure TfrmAutoSz.FormDestroy(Sender: TObject);
{ destroy objects used to record size and position information for controls }
var
SizeRatio: TSizeRatio;
i: Integer;
begin
inherited;
if FSizes <> nil then with FSizes do for i := 0 to Count-1 do
begin
SizeRatio := Items[i];
SizeRatio.Free;
end;
FSizes.Free;
end;
initialization
SpecifyFormIsNotADialog(TfrmAutoSz);
end.
|
unit RlCompilerConsts;
interface
const
cvDelphi1 = 8; //VER80
cvDelphi2 = 9; //VER90
cvDelphi3 = 10; //VER100
cvDelphi4 = 12; //VER120
cvDelphi5 = 13; //VER130
cvDelphi6 = 14; //VER140
cvDelphi7 = 15; //VER150
cvDelphi8NET = 16; //VER160
cvDelphi2005 = 17; //VER170
cvDelphi2006 = 18; //VER180
cvDelphi2007 = 18.5; //VER185
cvDelphi2007NET = 19; //VER190
cvDelphi2009 = 20; //VER200
cvDelphi2010 = 21; //VER210
cvDelphiXE = 22; //VER220
cvDelphiXE2 = 23; //VER230
cvDelphiXE3 = 24; //VER240
implementation
end.
|
unit dcm2nii;
{$mode objfpc}{$H+}
{$IFDEF Darwin}
{$modeswitch objectivec1}
{$ENDIF}
interface
uses
{$IFDEF Darwin} CocoaAll, MacOSAll, {$ENDIF}
{$IFDEF UNIX} lclintf, {$ENDIF}
strutils, Process, Classes, SysUtils, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls,
IniFiles, ComCtrls, Types;
type
{ Tdcm2niiForm }
Tdcm2niiForm = class(TForm)
BidsDrop: TComboBox;
BidsLabel: TLabel;
UpdateBtn: TButton;
CropCheck: TCheckBox;
FormatDrop: TComboBox;
FormatLabel: TLabel;
GeneralGroup: TGroupBox;
AdvancedGroup: TGroupBox;
IgnoreCheck: TCheckBox;
LosslessScaleCheck: TCheckBox;
MergeCheck: TCheckBox;
OutDirDrop: TComboBox;
OutDirLabel: TLabel;
OutNameEdit: TEdit;
OutNameExampleLabel: TLabel;
OutNameLabel: TLabel;
OutputDirDialog: TSelectDirectoryDialog;
InputDirDialog: TSelectDirectoryDialog;
PhilipsPreciseCheck: TCheckBox;
SelectFilesBtn: TButton;
ResetBtn: TButton;
OutputMemo: TMemo;
Panel1: TPanel;
StatusBar1: TStatusBar;
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure ConvertDicomDir(DirName: string);
procedure FormDropFiles(Sender: TObject; const FileNames: array of String);
procedure FormShow(Sender: TObject);
procedure OutDirDropChange(Sender: TObject);
procedure ResetBtnClick(Sender: TObject);
procedure SelectFilesBtnClick(Sender: TObject);
procedure ShowPrefs;
procedure ReadPrefs;
function RunCmd (lCmd: string; isDemo: boolean): string;
procedure UpdateBtnClick(Sender: TObject);
procedure UpdateCommand(Sender: TObject);
function TerminalCommand: string;
function getCustomDcm2niix(): string;
procedure setCustomDcm2niix(fnm: string);
//procedure findCustomDcm2niix();
procedure UpdateDialog(versionMsg: string);
private
public
end;
var
dcm2niiForm: Tdcm2niiForm;
implementation
{$R *.lfm}
const kExeName = 'dcm2niix';
{$IFDEF Unix}
kDemoInputDir = ' "/home/user/DicomDir"';
{$ELSE}
kDemoInputDir = ' "c:\DicomDir"';
{$ENDIF}
Type
TPrefs = record
UseOutDir, Ignore, LosslessScale,Merge,PhilipsPrecise, Crop: boolean;
Bids,Format: integer;
OutDir,OutName: String;
end;
var
gPrefs: TPrefs;
gCustomDcm2niix : string = '';
(*procedure Tdcm2niiForm.findCustomDcm2niix();
const
kStr = 'Find the dcm2niix executable (latest at https://github.com/rordenlab/dcm2niix/releases).';
var
openDialog : TOpenDialog;
begin
if fileexists(gCustomDcm2niix) then
showmessage(kStr + ' Currently using "'+gCustomDcm2niix+'".')
else
showmessage(kStr);
openDialog := TOpenDialog.Create(self);
openDialog.InitialDir := GetCurrentDir;
openDialog.Options := [ofFileMustExist];
if openDialog.Execute then
gCustomDcm2niix := openDialog.FileName;
openDialog.Free;
end;*)
{$IFDEF Darwin}
function ResourceDir (): string;
begin
result := NSBundle.mainBundle.resourcePath.UTF8String;
end;
{$ELSE}
function ResourceDir (): string;
begin
result := extractfilepath(paramstr(0))+'Resources';
end;
{$ENDIF}
function getDefaultDcm2niix(): string;
begin
{$IFDEF UNIX}
result := ResourceDir + pathdelim + kExeName;
{$ELSE}
result := ResourceDir + pathdelim + kExeName+'.exe';
{$ENDIF}
end;
function Tdcm2niiForm.getCustomDcm2niix(): string;
begin
if (gCustomDcm2niix = '') or (not fileexists(gCustomDcm2niix)) then
gCustomDcm2niix := getDefaultDcm2niix();
result := gCustomDcm2niix;
end;
procedure Tdcm2niiForm.setCustomDcm2niix(fnm: string);
begin
gCustomDcm2niix := fnm;
end;
function SetDefaultPrefs(): TPrefs;
begin
with result do begin
Ignore := false;
LosslessScale := false;
Merge := false;
PhilipsPrecise := true;
Crop := false;
UseOutDir := false;
Bids := 1;
Format := 1;
OutDir := GetUserDir;
OutName := '%f_%p_%t_%s';
end;
end;
procedure Tdcm2niiForm.ShowPrefs;
begin
with gPrefs do begin
IgnoreCheck.Checked := Ignore;
LosslessScaleCheck.Checked := LosslessScale;
MergeCheck.Checked := Merge;
PhilipsPreciseCheck.Checked := PhilipsPrecise;
CropCheck.Checked := Crop;
if (UseOutDir) then
OutDirDrop.ItemIndex := 2
else
OutDirDrop.ItemIndex:= 0;
OutDirDrop.Items[2] := OutDir;
FormatDrop.ItemIndex := Format;
OutNameEdit.Text:= OutName;
BidsDrop.ItemIndex := Bids;
end;
end;
procedure Tdcm2niiForm.ReadPrefs;
begin
with gPrefs do begin
Ignore := IgnoreCheck.Checked;
LosslessScale := LosslessScaleCheck.Checked;
Merge := MergeCheck.Checked;
PhilipsPrecise := PhilipsPreciseCheck.Checked;
Crop := CropCheck.Checked;
UseOutDir := (OutDirDrop.ItemIndex = 2);
OutDir := OutDirDrop.Items[2];
Format := FormatDrop.ItemIndex;
OutName := OutNameEdit.Text;
Bids := BidsDrop.ItemIndex;
end;
end;
function IniName: string;
begin
result := GetUserDir;
if result = '' then exit;
result := result + '.'+ChangeFileExt(ExtractFileName(ParamStr(0)),'')+'_dcm.ini';
end;
procedure IniInt(lRead: boolean; lIniFile: TIniFile; lIdent: string; var lValue: integer);
//read or write an integer value to the initialization file
var
lStr: string;
begin
if not lRead then begin
lIniFile.WriteString('INT',lIdent,IntToStr(lValue));
exit;
end;
lStr := lIniFile.ReadString('INT',lIdent, '');
if length(lStr) > 0 then
lValue := StrToInt(lStr);
end; //IniInt
function Bool2Char (lBool: boolean): char;
begin
if lBool then
result := '1'
else
result := '0';
end;
function Char2Bool (lChar: char): boolean;
begin
if lChar = '1' then
result := true
else
result := false;
end;
procedure IniBool(lRead: boolean; lIniFile: TIniFile; lIdent: string; var lValue: boolean);
//read or write a boolean value to the initialization file
var
lStr: string;
begin
if not lRead then begin
lIniFile.WriteString('BOOL',lIdent,Bool2Char(lValue));
exit;
end;
lStr := lIniFile.ReadString('BOOL',lIdent, '');
if length(lStr) > 0 then
lValue := Char2Bool(lStr[1]);
end; //IniBool
procedure IniStr(lRead: boolean; lIniFile: TIniFile; lIdent: string; var lValue: string);
//read or write a string value to the initialization file
begin
if not lRead then begin
lIniFile.WriteString('STR',lIdent,lValue);
exit;
end;
lValue := lIniFile.ReadString('STR',lIdent, '');
end; //IniStr
function IniFile(lRead: boolean; var lPrefs: TPrefs): boolean;
//Read or write initialization variables to disk
var
lFilename: string;
lIniFile: TIniFile;
begin
if (lRead) then
lPrefs := SetDefaultPrefs
else
dcm2niiForm.ReadPrefs;
lFilename := IniName;
if lFilename = '' then exit(true);
if (lRead) and (not Fileexists(lFilename)) then
exit(false);
{$IFDEF UNIX}if (lRead) then writeln('Loading preferences '+lFilename);{$ENDIF}
lIniFile := TIniFile.Create(lFilename);
IniBool(lRead,lIniFile, 'UseOutDir',lPrefs.UseOutDir);
IniBool(lRead,lIniFile, 'Ignore',lPrefs.Ignore);
IniBool(lRead,lIniFile, 'LosslessScale',lPrefs.LosslessScale);
IniBool(lRead,lIniFile, 'Merge',lPrefs.Merge);
IniBool(lRead,lIniFile, 'PhilipsPrecise',lPrefs.PhilipsPrecise);
IniBool(lRead,lIniFile, 'Crop',lPrefs.Crop);
IniInt(lRead,lIniFile, 'Bids', lPrefs.Bids);
IniInt(lRead,lIniFile, 'Format', lPrefs.Format);
IniStr(lRead, lIniFile, 'OutDir', lPrefs.OutDir);
IniStr(lRead, lIniFile, 'OutName', lPrefs.OutName );
lIniFile.Free;
exit(true);
end;
function Tdcm2niiForm.TerminalCommand: string;
begin
result := '';
if OutNameEdit.Text <> '' then
result := result + ' -f "'+OutNameEdit.Text+'"';
if IgnoreCheck.Checked then result := result + ' -i y';
if LosslessScaleCheck.Checked then result := result + ' -l y';
if MergeCheck.Checked then result := result + ' -m y';
if PhilipsPreciseCheck.Checked then
result := result + ' -p y'
else
result := result + ' -p n';
if CropCheck.Checked then result := result + ' -x y';
if odd(FormatDrop.ItemIndex) then
result := result + ' -z y'
else
result := result + ' -z n';
if (FormatDrop.ItemIndex > 1) then
result := result + ' -e y';
if BidsDrop.ItemIndex = 0 then
result := result + ' -b n';
if BidsDrop.ItemIndex = 2 then
result := result + ' -ba n';
if OutDirDrop.ItemIndex > 1 then
result := result + ' -o "'+OutDirDrop.Items[OutDirDrop.ItemIndex]+'"';
end;
procedure Tdcm2niiForm.UpdateCommand(Sender: TObject);
var
cmd: string;
begin
cmd := TerminalCommand();
StatusBar1.SimpleText:= kExeName+cmd+kDemoInputDir;
OutNameExampleLabel.Caption:= RunCmd(TerminalCommand,true);
end;
procedure Tdcm2niiForm.ResetBtnClick(Sender: TObject);
begin
gPrefs := SetDefaultPrefs();
ShowPrefs;
UpdateCommand(Sender);
end;
procedure Tdcm2niiForm.SelectFilesBtnClick(Sender: TObject);
begin
if not InputDirDialog.Execute then exit;
ConvertDicomDir(InputDirDialog.Filename);
end;
procedure Tdcm2niiForm.FormShow(Sender: TObject);
begin
{$IFNDEF UNIX}
UpdateBtn.Caption := 'Set Executable Path';
{$ENDIF}
IniFile(true, gPrefs);
ShowPrefs;
UpdateCommand(Sender);
InputDirDialog.InitialDir := GetUserDir;
end;
procedure Tdcm2niiForm.OutDirDropChange(Sender: TObject);
begin
if OutDirDrop.ItemIndex <> 1 then begin
UpdateCommand(Sender);
exit;
end;
if not DirectoryExists(gPrefs.OutDir) then
gPrefs.OutDir := GetUserDir;
OutputDirDialog.InitialDir := gPrefs.OutDir;
if OutputDirDialog.Execute then
gPrefs.OutDir := OutputDirDialog.FileName;
OutDirDrop.Items[2] := gPrefs.OutDir;
OutDirDrop.ItemIndex := 2;
UpdateCommand(Sender);
end;
procedure Tdcm2niiForm.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
IniFile(false, gPrefs);
end;
procedure Tdcm2niiForm.ConvertDicomDir(DirName: string);
var
cmd: string;
begin
cmd := TerminalCommand()+' "'+DirName+'"';
RunCmd(cmd,false);
end;
procedure Tdcm2niiForm.FormDropFiles(Sender: TObject;
const FileNames: array of String);
begin
ConvertDicomDir( FileNames[0]);
end;
function Tdcm2niiForm.RunCmd (lCmd: string; isDemo: boolean): string;
//http://wiki.freepascal.org/Executing_External_Programs
const
kKeyStr = 'Example output filename: ';
var
OutputLines: TStringList;
MemStream: TMemoryStream;
OurProcess: TProcess;
NumBytes: LongInt;
i: integer;
exe: string;
const
READ_BYTES_BIG = 32768;
begin
result := ''; //EXIT_FAILURE
//if (not isAppDoneInitializing) then exit;
exe := getCustomDcm2niix();
if not fileexists(exe) then begin
OutputMemo.Lines.Clear;
OutputMemo.Lines.Add('Error: unable to find '+exe);
exit;
end;
OutputMemo.Lines.Clear;
if isDemo then
OutputMemo.Lines.Add(exe+lCmd+kDemoInputDir)
else
OutputMemo.Lines.Add(exe+lCmd);
MemStream := TMemoryStream.Create;
//BytesRead := 0;
OurProcess := TProcess.Create(nil);
{$IFDEF UNIX}
OurProcess.Environment.Add(GetEnvironmentVariable('PATH'));
{$ENDIF}
OurProcess.CommandLine := exe+lCmd;
OurProcess.Options := [poUsePipes, poNoConsole];
OurProcess.Execute;
OutputLines := TStringList.Create;
MemStream.SetSize(READ_BYTES_BIG);
dcm2niiForm.Refresh;
while True do begin
NumBytes := OurProcess.Output.Read((MemStream.Memory)^, READ_BYTES_BIG);
if NumBytes > 0 then begin
MemStream.SetSize(NumBytes);
OutputLines.LoadFromStream(MemStream);
if (isDemo) and (result = '') and (OutputLines.Count > 0) then begin
for i := 0 to OutputLines.Count - 1 do begin
if PosEx(kKeyStr,OutputLines[i]) > 0 then begin
result := OutputLines[i];
Delete(result, 1, length(kKeyStr));
end;
end;
end;
OutputMemo.Lines.AddStrings(OutputLines);
MemStream.SetSize(READ_BYTES_BIG);
MemStream.Position:=0;
dcm2niiForm.Refresh;
Application.ProcessMessages;
Sleep(15);
end else
BREAK; // Program has finished execution.
end;
if isDemo then begin
OutputMemo.Lines.Add('');
OutputMemo.Lines.Add('Drop files/folders to convert here');
end;
dcm2niiForm.Refresh;
OutputLines.Free;
OurProcess.Free;
MemStream.Free;
end;
procedure Tdcm2niiForm.UpdateDialog(versionMsg: string);
const
kURL = 'https://github.com/rordenlab/dcm2niix/releases';
var
PrefForm: TForm;
openDialog : TOpenDialog;
UrlBtn,OkBtn,UseDefaultBtn, CustomBtn: TButton;
promptLabel: TLabel;
defaultDcm2niix, currentDcm2niix: string;
isSetCustomPath,isGotoURL, isCurrentAlsoDefault: boolean;
begin
PrefForm:=TForm.Create(nil);
//PrefForm.SetBounds(100, 100, 512, 212);
PrefForm.AutoSize := True;
PrefForm.BorderWidth := 8;
PrefForm.Caption:='dcm2niix Settings';
PrefForm.Position := poScreenCenter;
PrefForm.BorderStyle := bsDialog;
//Possible situations:
// if getDefaultDcm2niix is not set but exists
//label
promptLabel:=TLabel.create(PrefForm);
currentDcm2niix := getCustomDcm2niix();
defaultDcm2niix := getDefaultDcm2niix();
isCurrentAlsoDefault := CompareStr(currentDcm2niix, defaultDcm2niix) = 0;
if (not fileexists(defaultDcm2niix)) and (not isCurrentAlsoDefault) then
isCurrentAlsoDefault := true; //default does not exist: do not show "Select Default")
if versionMsg = '' then begin
if fileexists(currentDcm2niix) then
promptLabel.Caption:= format('dcm2niix path: "%s"', [gCustomDcm2niix])
else
promptLabel.Caption:= 'Unable to find dcm2niix';
end else
promptLabel.Caption:= versionMsg;
promptLabel.AutoSize := true;
promptLabel.AnchorSide[akTop].Side := asrTop;
promptLabel.AnchorSide[akTop].Control := PrefForm;
promptLabel.BorderSpacing.Top := 6;
promptLabel.AnchorSide[akLeft].Side := asrLeft;
promptLabel.AnchorSide[akLeft].Control := PrefForm;
promptLabel.BorderSpacing.Left := 6;
promptLabel.Parent:=PrefForm;
//UrlBtn Btn
UrlBtn:=TButton.create(PrefForm);
UrlBtn.Caption:='Visit '+kURL;
UrlBtn.AutoSize := true;
UrlBtn.AnchorSide[akTop].Side := asrBottom;
UrlBtn.AnchorSide[akTop].Control := promptLabel;
UrlBtn.BorderSpacing.Top := 6;
UrlBtn.AnchorSide[akLeft].Side := asrLeft;
UrlBtn.AnchorSide[akLeft].Control := PrefForm;
UrlBtn.BorderSpacing.Left := 6;
UrlBtn.Parent:=PrefForm;
UrlBtn.ModalResult:= mrCancel;
//CustomBtn
CustomBtn:=TButton.create(PrefForm);
CustomBtn.Caption:='Select custom dcm2niix path';
CustomBtn.AutoSize := true;
CustomBtn.AnchorSide[akTop].Side := asrBottom;
CustomBtn.BorderSpacing.Top := 6;
CustomBtn.AnchorSide[akLeft].Side := asrLeft;
CustomBtn.AnchorSide[akLeft].Control := PrefForm;
CustomBtn.BorderSpacing.Left := 6;
CustomBtn.Parent:=PrefForm;
CustomBtn.ModalResult:= mrIgnore;
//UseDefaultBtn
if not isCurrentAlsoDefault then begin
UseDefaultBtn:=TButton.create(PrefForm);
//UseDefaultBtn.Caption:= format('Reset default "%s"', [defaultDcm2niix]);
UseDefaultBtn.Caption:= 'Reset default dcm2niix path';
UseDefaultBtn.AutoSize := true;
UseDefaultBtn.AnchorSide[akTop].Side := asrBottom;
UseDefaultBtn.AnchorSide[akTop].Control := UrlBtn;
UseDefaultBtn.BorderSpacing.Top := 6;
UseDefaultBtn.AnchorSide[akLeft].Side := asrLeft;
UseDefaultBtn.AnchorSide[akLeft].Control := PrefForm;
UseDefaultBtn.BorderSpacing.Left := 6;
UseDefaultBtn.Parent:=PrefForm;
UseDefaultBtn.ModalResult:= mrAbort;
CustomBtn.AnchorSide[akTop].Control := UseDefaultBtn;
end else
CustomBtn.AnchorSide[akTop].Control := UrlBtn;
//OK button
OkBtn:=TButton.create(PrefForm);
OkBtn.Caption:='OK';
OkBtn.AutoSize := true;
OkBtn.AnchorSide[akTop].Side := asrBottom;
OkBtn.AnchorSide[akTop].Control := CustomBtn;
OkBtn.BorderSpacing.Top := 6;
OkBtn.AnchorSide[akLeft].Side := asrRight;
OkBtn.AnchorSide[akLeft].Control := UrlBtn;
OkBtn.BorderSpacing.Left := 6;
OkBtn.Parent:=PrefForm;
OkBtn.ModalResult:= mrOK;
//Display form
PrefForm.ActiveControl := OkBtn;
PrefForm.ShowModal;
isGotoURL := (PrefForm.ModalResult = mrCancel);
if (PrefForm.ModalResult = mrAbort) then //isResetDefault
gCustomDcm2niix := defaultDcm2niix;
isSetCustomPath := (PrefForm.ModalResult = mrIgnore);
FreeAndNil(PrefForm);
if (isGotoURL) then
OpenURL(kURL); //uses lclintf
if isSetCustomPath then begin
openDialog := TOpenDialog.Create(self);
openDialog.Title := 'Find dcm2niix executable';
openDialog.InitialDir := GetCurrentDir;
openDialog.Options := [ofFileMustExist];
if openDialog.Execute then
gCustomDcm2niix := openDialog.FileName;
openDialog.Free;
end;
end; //GetFloat()
procedure Tdcm2niiForm.UpdateBtnClick(Sender: TObject);
begin
{$IFDEF UNIX}
RunCmd(' -u', false);
if OutputMemo.Lines.Count > 2 then
UpdateDialog(OutputMemo.Lines[2])
else
{$ENDIF}
UpdateDialog('');
end;
end.
|
{*******************************************************}
{ }
{ Delphi Visual Component Library }
{ }
{ Copyright(c) 1995-2011 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit SvrLogFrame;
interface
uses
{$IFDEF MSWINDOWS}
System.Win.Registry,
{$ENDIF}
System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.Dialogs,
Vcl.ActnList, Vcl.Menus, Vcl.ComCtrls, SvrLogDetailFrame, SvrLog, System.IniFiles;
type
TColumnInfo = record
Visible: Boolean;
Width: Integer;
ColumnPosition: Integer;
SubItemPosition: Integer;
Caption: string;
end;
TLogColumnOrder = array[0..Ord(High(TLogColumn))] of TLogColumn;
TLogFrame = class(TFrame)
lvLog: TListView;
PopupMenu2: TPopupMenu;
ActionList1: TActionList;
ClearAction: TAction;
Clear1: TMenuItem;
DetailAction: TAction;
DetailAction1: TMenuItem;
procedure ClearActionExecute(Sender: TObject);
procedure ClearActionUpdate(Sender: TObject);
procedure DetailActionExecute(Sender: TObject);
procedure lvLogDblClick(Sender: TObject);
procedure lvLogColumnClick(Sender: TObject; Column: TListColumn);
procedure lvLogCompare(Sender: TObject; Item1, Item2: TListItem;
Data: Integer; var Compare: Integer);
private
FShowingDetail: Boolean;
FColumnToSort: Integer;
FSortDescending: Boolean;
FSorted: Boolean;
FColumnInfo: array[TLogColumn] of TColumnInfo;
FLogMax: Integer;
FLogDelete: Integer;
function GetCount: Integer;
function GetIndex: Integer;
function GetCurrent: TTransactionLogEntry;
procedure ConstrainLog;
function GetColumnVisible(I: TLogColumn): Boolean;
function GetColumnWidth(I: TLogColumn): Integer;
procedure SetColumnVisible(I: TLogColumn; const Value: Boolean);
procedure SetColumnWidth(I: TLogColumn; const Value: Integer);
function GetColumnCaption(I: TLogColumn): string;
function GetColumnPosition(I: TLogColumn): Integer;
procedure SetColumnPosition(I: TLogColumn; const Value: Integer);
function GetSubItemPosition(I: TLogColumn): Integer;
procedure SetSubItemPosition(I: TLogColumn; const Value: Integer);
function GetColumn(ALogColumn: TLogColumn): TListColumn;
procedure SetCurrent(AItem: TListItem);
function GetItemCount: Integer;
procedure SetLogDelete(const Value: Integer);
procedure SetLogMax(const Value: Integer);
function GetSelectedItem: TListItem;
function GetSelectedItemIndex: Integer;
{ Private declarations }
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SynchColumnInfo;
procedure Add(Transaction: TTransactionLogEntry);
procedure Next;
procedure Previous;
procedure Clear;
property Count: Integer read GetCount;
procedure ShowDetail(Details: TLogDetailFrame);
procedure RefreshColumns;
procedure RefreshSubItems;
procedure Save(Reg: TRegIniFile; const Section: string);
procedure Load(Reg: TRegIniFile; const Section: string);
procedure GetSubItemOrder(var Positions: TLogColumnOrder);
procedure GetColumnOrder(var Positions: TLogColumnOrder);
property Index: Integer read GetIndex;
property Current: TTransactionLogEntry read GetCurrent;
property LogMax: Integer read FLogMax write SetLogMax;
property LogDelete: Integer read FLogDelete write SetLogDelete;
property ColumnCaption[I: TLogColumn]: string read GetColumnCaption;
property ColumnWidth[I: TLogColumn]: Integer read GetColumnWidth write SetColumnWidth;
property ColumnVisible[I: TLogColumn]: Boolean read GetColumnVisible write SetColumnVisible;
property ColumnPosition[I: TLogColumn]: Integer read GetColumnPosition write SetColumnPosition;
property SubItemPosition[I: TLogColumn]: Integer read GetSubItemPosition write SetSubItemPosition;
property Columns[I: TLogColumn]: TListColumn read GetColumn;
property ItemCount: Integer read GetItemCount;
end;
implementation
uses SvrLogDetailDlg, SvrConst;
{$R *.dfm}
const
LogColumnCaptions: array[TLogColumn] of string =
(sEvent, sTime, sDate, sElapsed, sPath, sCode, sContentLength, sContentType, sThread);
DefaultColumnPositions: array[TLogColumn] of Integer =
(1, 2, 3, 4, 5, 6, 7, 8, 0);
DefaultColumnVisible: array[TLogColumn] of Boolean =
(True, True, False, True, True, True, True, True, True);
DefaultColumnWidth: array[TLogColumn] of Integer =
(50, 50, 50, 50, 50, 50, 50, 50, 50);
procedure TLogFrame.Add(Transaction: TTransactionLogEntry);
var
Item: TListItem;
I: Integer;
LogColumn: TLogColumn;
Positions: TLogColumnOrder;
HaveCaption: Boolean;
begin
GetSubItemOrder(Positions);
Item := lvLog.Items.Add;
Item.Data := Transaction;
HaveCaption := False;
for I := Low(Positions) to High(Positions) do
begin
LogColumn := Positions[I];
if ColumnVisible[LogColumn] then
begin
if HaveCaption then
Item.SubItems.Add(string(Transaction.Columns[LogColumn]))
else
begin
Item.Caption := string(Transaction.Columns[LogColumn]);
HaveCaption := True;
end;
end;
end;
ConstrainLog;
if (ItemCount = 1) or not FShowingDetail then
begin
SetCurrent(Item);
if FShowingDetail then
ShowDetail(FLogDetail.LogDetailFrame);
end;
end;
procedure TLogFrame.RefreshSubItems;
var
Item: TListItem;
I, J: Integer;
LogColumn: TLogColumn;
Positions: TLogColumnOrder;
HaveCaption: Boolean;
Transaction: TTransactionLogEntry;
Count: Integer;
begin
GetSubItemOrder(Positions);
lvLog.Items.BeginUpdate;
try
for I := 0 to lvLog.Items.Count - 1 do
begin
Item := lvLog.Items[I];
Transaction := TTransactionLogEntry(Item.Data);
HaveCaption := False;
Count := 0;
for J := Low(Positions) to High(Positions) do
begin
LogColumn := Positions[J];
if ColumnVisible[LogColumn] then
begin
if HaveCaption then
begin
if Count >= Item.SubItems.Count then
Item.SubItems.Add(string(Transaction.Columns[LogColumn]))
else
Item.SubItems[Count] := string(Transaction.Columns[LogColumn]);
Inc(Count);
end
else
begin
Item.Caption := string(Transaction.Columns[LogColumn]);
HaveCaption := True;
end;
end;
end;
end;
finally
lvLog.Items.EndUpdate;
end;
end;
procedure TLogFrame.Clear;
var
I: Integer;
begin
for I := 0 to lvLog.Items.Count - 1 do
if Assigned(lvLog.Items[I].Data) then
TObject(lvLog.Items[I].Data).Free;
lvLog.Items.Clear;
end;
procedure TLogFrame.ClearActionExecute(Sender: TObject);
begin
Clear;
end;
procedure TLogFrame.ClearActionUpdate(Sender: TObject);
begin
(Sender as TAction).Enabled := lvLog.Items.Count > 0;
end;
function TLogFrame.GetCount: Integer;
begin
Result := lvLog.Items.Count;
end;
function TLogFrame.GetIndex: Integer;
var
Item: TListItem;
begin
Item := GetSelectedItem;
if Assigned(Item) then
Result := Item.Index
else
Result := -1;
end;
procedure TLogFrame.Next;
var
I: Integer;
begin
I := GetSelectedItemIndex;
if I >= 0 then
if I + 1 < lvLog.Items.Count then
SetCurrent(lvLog.Items[I + 1]);
end;
procedure TLogFrame.SetCurrent(AItem: TListItem);
begin
if Assigned(AItem) then
begin
lvLog.Selected := AItem;
AItem.MakeVisible(False);
end
else
lvLog.Selected := nil;
end;
procedure TLogFrame.Previous;
var
I: Integer;
begin
I := GetSelectedItemIndex;
if I >= 0 then
if I > 0 then
SetCurrent(lvLog.Items[I - 1]);
end;
procedure TLogFrame.DetailActionExecute(Sender: TObject);
begin
with FLogDetail do
try
FShowingDetail := True;
ShowModal;
finally
FShowingDetail := False;
end;
end;
procedure TLogFrame.ShowDetail(Details: TLogDetailFrame);
var
Entry: TTransactionLogEntry;
begin
Entry := Current;
if Assigned(Current) then
begin
Details.Text := string(Entry.LogString);
end
else
begin
Details.Clear;
end;
end;
destructor TLogFrame.Destroy;
begin
Clear;
FreeAndNil(FLogDetail);
inherited;
end;
function TLogFrame.GetSelectedItem: TListItem;
var
I: Integer;
begin
I := GetSelectedItemIndex;
if I >= 0 then
Result := lvLog.Items[I]
else
Result := nil;
end;
function TLogFrame.GetSelectedItemIndex: Integer;
var
I: Integer;
F: Integer;
begin
F := -1;
// GetNextItem might be more efficient but there are bugs
// in the K2 version.
for I := 0 to lvLog.Items.Count - 1 do
begin
Result := I;
if lvLog.Items[Result].Selected then
Exit;
if lvLog.Items[Result].Focused then
F := Result;
end;
Result := F;
end;
function TLogFrame.GetCurrent: TTransactionLogEntry;
var
Item: TListItem;
begin
Item := GetSelectedItem;
if Assigned(Item) then
Result := TObject(Item.Data) as TTransactionLogEntry
else
Result := nil;
end;
constructor TLogFrame.Create(AOwner: TComponent);
var
I: TLogColumn;
begin
inherited;
FLogDetail := TLogDetail.Create(Self);
FLogDetail.LogFrame := Self;
for I := Low(TLogColumn) to High(TLogColumn) do
begin
FColumnInfo[I].Width := DefaultColumnWidth[I];
FColumnInfo[I].Visible := DefaultColumnVisible[I];
FColumnInfo[I].Caption := LogColumnCaptions[I];
FColumnInfo[I].ColumnPosition := DefaultColumnPositions[I];
FColumnInfo[I].SubItemPosition := DefaultColumnPositions[I];
end;
RefreshColumns;
end;
procedure TLogFrame.RefreshColumns;
var
I: Integer;
LogColumn: TLogColumn;
Column: TListColumn;
Positions: TLogColumnOrder;
Count: Integer;
begin
lvLog.Columns.BeginUpdate;
try
lvLog.Columns.Clear;
GetColumnOrder(Positions);
Count := 0;
for I := Low(Positions) to High(Positions) do
begin
LogColumn := Positions[I];
if FColumnInfo[LogColumn].Visible then
begin
FColumnInfo[LogColumn].SubItemPosition := Count;
Column := lvLog.Columns.Add;
Column.Caption := FColumnInfo[LogColumn].Caption;
Column.Width := FColumnInfo[LogColumn].Width;
Inc(Count);
end
else
FColumnInfo[LogColumn].SubItemPosition := High(Positions);
end;
finally
lvLog.Columns.EndUpdate;
end;
end;
procedure TLogFrame.ConstrainLog;
var
DeleteCount: Integer;
begin
if LogMax > 0 then
if lvLog.Items.Count > LogMax then
begin
if LogDelete > 0 then
DeleteCount := LogDelete
else
DeleteCount := 1;
while (lvLog.Items.Count > 0) and (DeleteCount > 0) do
begin
lvLog.Items.Delete(0);
Dec(DeleteCount);
end;
end;
end;
procedure TLogFrame.SetLogMax(const Value: Integer);
begin
FLogMax := Value;
ConstrainLog;
end;
procedure TLogFrame.lvLogDblClick(Sender: TObject);
begin
DetailActionExecute(Self);
end;
procedure TLogFrame.lvLogColumnClick(Sender: TObject; Column: TListColumn);
begin
if FSorted and (FColumnToSort = Column.Index) then
FSortDescending := not FSortDescending
else
FSortDescending := False;
FColumnToSort := Column.Index;
(Sender as TCustomListView).AlphaSort;
FSorted := True;
end;
procedure TLogFrame.lvLogCompare(Sender: TObject; Item1, Item2: TListItem; Data: Integer; var Compare: Integer);
function SortOnKey(AKey: TLogColumn): Integer;
var
Transaction1, Transaction2: TTransactionLogEntry;
begin
Result := 0;
if FColumnToSort <> FColumnInfo[AKey].SubItemPosition then
begin
Transaction1 := TTransactionLogEntry(Item1.Data);
Transaction2 := TTransactionLogEntry(Item2.Data);
Result := AnsiStrComp(PAnsiChar(Transaction1.Columns[AKey]),
PAnsiChar(Transaction2.Columns[AKey]));
end;
end;
var
I: Integer;
begin
if FColumnToSort = 0 then
Compare := CompareText(Item1.Caption,Item2.Caption)
else
begin
I := FColumnToSort - 1;
Compare := AnsiCompareText(Item1.SubItems[I],Item2.SubItems[I]);
end;
if Compare = 0 then
begin
Compare := SortOnKey(lcThreadID);
if Compare = 0 then
Compare := SortOnKey(lcTime);
end;
if FSortDescending then
Compare := -Compare;
end;
function TLogFrame.GetColumnVisible(I: TLogColumn): Boolean;
begin
Result := FColumnInfo[I].Visible;
end;
function TLogFrame.GetColumnWidth(I: TLogColumn): Integer;
begin
Result := FColumnInfo[I].Width;
end;
procedure TLogFrame.SetColumnVisible(I: TLogColumn; const Value: Boolean);
begin
FColumnInfo[I].Visible := Value;
end;
procedure TLogFrame.SetColumnWidth(I: TLogColumn; const Value: Integer);
begin
FColumnInfo[I].Width := Value;
end;
function TLogFrame.GetColumnCaption(I: TLogColumn): string;
begin
Result := FColumnInfo[I].Caption;
end;
const
LogColumnID: array[TLogColumn] of string =
('Event', 'Time', 'Date', 'Elapsed', 'Path', 'Code', 'Content_Length', // Do not localize
'Content_Type', 'Thread'); // Do not localize
sWidth = 'Width'; // Do not localize
sVisible = 'Visible'; // Do not localize
sPosition = 'Position'; // Do not localize
sDetails = 'Details'; // Do not localize
procedure TLogFrame.Load(Reg: TRegIniFile; const Section: string);
var
I: TLogColumn;
SubSection: string;
begin
FLogDetail.Load(Reg, sDetails);
for I := Low(TLogColumn) to High(TLogColumn) do
begin
SubSection := Section + '_' + LogColumnID[I];
ColumnVisible[I] := Reg.ReadBool(SubSection, sVisible, ColumnVisible[I]);
ColumnWidth[I] := Reg.ReadInteger(SubSection, sWidth, ColumnWidth[I]);
ColumnPosition[I] := Reg.ReadInteger(SubSection, sPosition, ColumnPosition[I]);
end;
RefreshColumns;
end;
procedure TLogFrame.Save(Reg: TRegIniFile; const Section: string);
var
I: TLogColumn;
SubSection: string;
begin
FLogDetail.Save(Reg, sDetails);
SynchColumnInfo;
for I := Low(TLogColumn) to High(TLogColumn) do
begin
SubSection := Section + '_' + LogColumnID[I];
Reg.WriteBool(SubSection, sVisible, ColumnVisible[I]);
Reg.WriteInteger(SubSection, sWidth, ColumnWidth[I]);
Reg.WriteInteger(SubSection, sPosition, ColumnPosition[I]);
end;
end;
procedure TLogFrame.SynchColumnInfo;
var
I, J: Integer;
LogColumn, L: TLogColumn;
Positions: TLogColumnOrder;
begin
for I := 0 to High(Positions) do
Positions[I] := TLogColumn(-1);
for LogColumn := Low(TLogColumn) to High(TLogColumn) do
if not FColumnInfo[LogColumn].Visible then
Positions[FColumnInfo[LogColumn].ColumnPosition] := LogColumn;
for I := 0 to lvLog.Columns.Count - 1 do
begin
LogColumn := Low(TLogColumn);
for L := Low(TLogColumn) to High(TLogColumn) do
if AnsiCompareText(FColumnInfo[L].Caption, lvLog.Columns[I].Caption) = 0 then
begin
LogColumn := L;
break;
end;
FColumnInfo[LogColumn].Width := lvLog.Columns[I].Width;
for J := I to High(Positions) do
if Positions[J] = TLogColumn(-1) then
begin
FColumnInfo[LogColumn].ColumnPosition := J;
Positions[J] := LogColumn;
break;
end;
end;
end;
function TLogFrame.GetColumnPosition(I: TLogColumn): Integer;
begin
Result := FColumnInfo[I].ColumnPosition;
end;
procedure TLogFrame.SetColumnPosition(I: TLogColumn; const Value: Integer);
begin
FColumnInfo[I].ColumnPosition := Value;
end;
procedure TLogFrame.GetColumnOrder(var Positions: TLogColumnOrder);
var
LogColumn: TLogColumn;
begin
for LogColumn := Low(TLogColumn) to High(TLogColumn) do
Positions[FColumnInfo[LogColumn].ColumnPosition] := LogColumn;
end;
procedure TLogFrame.GetSubItemOrder(var Positions: TLogColumnOrder);
var
LogColumn: TLogColumn;
begin
for LogColumn := Low(TLogColumn) to High(TLogColumn) do
Positions[FColumnInfo[LogColumn].SubItemPosition] := LogColumn;
end;
function TLogFrame.GetSubItemPosition(I: TLogColumn): Integer;
begin
Result := FColumnInfo[I].SubItemPosition;
end;
procedure TLogFrame.SetSubItemPosition(I: TLogColumn;
const Value: Integer);
begin
FColumnInfo[I].SubItemPosition := Value;
end;
function TLogFrame.GetColumn(ALogColumn: TLogColumn): TListColumn;
var
I: Integer;
begin
for I := 0 to lvLog.Columns.Count - 1 do
begin
Result := lvLog.Columns[I];
if AnsiCompareText(Result.Caption, FColumnInfo[ALogColumn].Caption) = 0 then Exit;
end;
Result := nil;
end;
function TLogFrame.GetItemCount: Integer;
begin
Result := lvLog.Items.Count;
end;
procedure TLogFrame.SetLogDelete(const Value: Integer);
begin
FLogDelete := Value;
end;
end.
|
unit PageScrollerImpl1;
interface
uses
Windows, ActiveX, Classes, Controls, Graphics, Menus, Forms, StdCtrls,
ComServ, StdVCL, AXCtrls, DelCtrls_TLB, ComCtrls;
type
TPageScrollerX = class(TActiveXControl, IPageScrollerX)
private
{ Private declarations }
FDelphiControl: TPageScroller;
FEvents: IPageScrollerXEvents;
procedure ClickEvent(Sender: TObject);
procedure DblClickEvent(Sender: TObject);
procedure KeyPressEvent(Sender: TObject; var Key: Char);
procedure ResizeEvent(Sender: TObject);
protected
{ Protected declarations }
procedure DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage); override;
procedure EventSinkChanged(const EventSink: IUnknown); override;
procedure InitializeControl; override;
function ClassNameIs(const Name: WideString): WordBool; safecall;
function DrawTextBiDiModeFlags(Flags: Integer): Integer; safecall;
function DrawTextBiDiModeFlagsReadingOnly: Integer; safecall;
function Get_AutoScroll: WordBool; safecall;
function Get_BiDiMode: TxBiDiMode; safecall;
function Get_ButtonSize: Integer; safecall;
function Get_Color: OLE_COLOR; safecall;
function Get_Cursor: Smallint; safecall;
function Get_DockSite: WordBool; safecall;
function Get_DoubleBuffered: WordBool; safecall;
function Get_DragCursor: Smallint; safecall;
function Get_DragMode: TxDragMode; safecall;
function Get_DragScroll: WordBool; safecall;
function Get_Enabled: WordBool; safecall;
function Get_Font: IFontDisp; safecall;
function Get_Margin: Integer; safecall;
function Get_Orientation: TxPageScrollerOrientation; safecall;
function Get_ParentColor: WordBool; safecall;
function Get_ParentFont: WordBool; safecall;
function Get_Position: Integer; safecall;
function Get_Visible: WordBool; safecall;
function GetButtonState(
Button: TxPageScrollerButton): TxPageScrollerButtonState; safecall;
function GetControlsAlignment: TxAlignment; safecall;
function IsRightToLeft: WordBool; safecall;
function UseRightToLeftAlignment: WordBool; safecall;
function UseRightToLeftReading: WordBool; safecall;
function UseRightToLeftScrollBar: WordBool; safecall;
procedure _Set_Font(const Value: IFontDisp); safecall;
procedure AboutBox; safecall;
procedure FlipChildren(AllLevels: WordBool); safecall;
procedure InitiateAction; safecall;
procedure Set_AutoScroll(Value: WordBool); safecall;
procedure Set_BiDiMode(Value: TxBiDiMode); safecall;
procedure Set_ButtonSize(Value: Integer); safecall;
procedure Set_Color(Value: OLE_COLOR); safecall;
procedure Set_Cursor(Value: Smallint); safecall;
procedure Set_DockSite(Value: WordBool); safecall;
procedure Set_DoubleBuffered(Value: WordBool); safecall;
procedure Set_DragCursor(Value: Smallint); safecall;
procedure Set_DragMode(Value: TxDragMode); safecall;
procedure Set_DragScroll(Value: WordBool); safecall;
procedure Set_Enabled(Value: WordBool); safecall;
procedure Set_Font(const Value: IFontDisp); safecall;
procedure Set_Margin(Value: Integer); safecall;
procedure Set_Orientation(Value: TxPageScrollerOrientation); safecall;
procedure Set_ParentColor(Value: WordBool); safecall;
procedure Set_ParentFont(Value: WordBool); safecall;
procedure Set_Position(Value: Integer); safecall;
procedure Set_Visible(Value: WordBool); safecall;
end;
implementation
uses ComObj, About21;
{ TPageScrollerX }
procedure TPageScrollerX.DefinePropertyPages(DefinePropertyPage: TDefinePropertyPage);
begin
{ Define property pages here. Property pages are defined by calling
DefinePropertyPage with the class id of the page. For example,
DefinePropertyPage(Class_PageScrollerXPage); }
end;
procedure TPageScrollerX.EventSinkChanged(const EventSink: IUnknown);
begin
FEvents := EventSink as IPageScrollerXEvents;
end;
procedure TPageScrollerX.InitializeControl;
begin
FDelphiControl := Control as TPageScroller;
FDelphiControl.OnClick := ClickEvent;
FDelphiControl.OnDblClick := DblClickEvent;
FDelphiControl.OnKeyPress := KeyPressEvent;
FDelphiControl.OnResize := ResizeEvent;
end;
function TPageScrollerX.ClassNameIs(const Name: WideString): WordBool;
begin
Result := FDelphiControl.ClassNameIs(Name);
end;
function TPageScrollerX.DrawTextBiDiModeFlags(Flags: Integer): Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlags(Flags);
end;
function TPageScrollerX.DrawTextBiDiModeFlagsReadingOnly: Integer;
begin
Result := FDelphiControl.DrawTextBiDiModeFlagsReadingOnly;
end;
function TPageScrollerX.Get_AutoScroll: WordBool;
begin
Result := FDelphiControl.AutoScroll;
end;
function TPageScrollerX.Get_BiDiMode: TxBiDiMode;
begin
Result := Ord(FDelphiControl.BiDiMode);
end;
function TPageScrollerX.Get_ButtonSize: Integer;
begin
Result := FDelphiControl.ButtonSize;
end;
function TPageScrollerX.Get_Color: OLE_COLOR;
begin
Result := OLE_COLOR(FDelphiControl.Color);
end;
function TPageScrollerX.Get_Cursor: Smallint;
begin
Result := Smallint(FDelphiControl.Cursor);
end;
function TPageScrollerX.Get_DockSite: WordBool;
begin
Result := FDelphiControl.DockSite;
end;
function TPageScrollerX.Get_DoubleBuffered: WordBool;
begin
Result := FDelphiControl.DoubleBuffered;
end;
function TPageScrollerX.Get_DragCursor: Smallint;
begin
Result := Smallint(FDelphiControl.DragCursor);
end;
function TPageScrollerX.Get_DragMode: TxDragMode;
begin
Result := Ord(FDelphiControl.DragMode);
end;
function TPageScrollerX.Get_DragScroll: WordBool;
begin
Result := FDelphiControl.DragScroll;
end;
function TPageScrollerX.Get_Enabled: WordBool;
begin
Result := FDelphiControl.Enabled;
end;
function TPageScrollerX.Get_Font: IFontDisp;
begin
GetOleFont(FDelphiControl.Font, Result);
end;
function TPageScrollerX.Get_Margin: Integer;
begin
Result := FDelphiControl.Margin;
end;
function TPageScrollerX.Get_Orientation: TxPageScrollerOrientation;
begin
Result := Ord(FDelphiControl.Orientation);
end;
function TPageScrollerX.Get_ParentColor: WordBool;
begin
Result := FDelphiControl.ParentColor;
end;
function TPageScrollerX.Get_ParentFont: WordBool;
begin
Result := FDelphiControl.ParentFont;
end;
function TPageScrollerX.Get_Position: Integer;
begin
Result := FDelphiControl.Position;
end;
function TPageScrollerX.Get_Visible: WordBool;
begin
Result := FDelphiControl.Visible;
end;
function TPageScrollerX.GetButtonState(
Button: TxPageScrollerButton): TxPageScrollerButtonState;
begin
Result := TxPageScrollerButtonState(FDelphiControl.GetButtonState(TPageScrollerButton(Button)));
end;
function TPageScrollerX.GetControlsAlignment: TxAlignment;
begin
Result := TxAlignment(FDelphiControl.GetControlsAlignment);
end;
function TPageScrollerX.IsRightToLeft: WordBool;
begin
Result := FDelphiControl.IsRightToLeft;
end;
function TPageScrollerX.UseRightToLeftAlignment: WordBool;
begin
Result := FDelphiControl.UseRightToLeftAlignment;
end;
function TPageScrollerX.UseRightToLeftReading: WordBool;
begin
Result := FDelphiControl.UseRightToLeftReading;
end;
function TPageScrollerX.UseRightToLeftScrollBar: WordBool;
begin
Result := FDelphiControl.UseRightToLeftScrollBar;
end;
procedure TPageScrollerX._Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TPageScrollerX.AboutBox;
begin
ShowPageScrollerXAbout;
end;
procedure TPageScrollerX.FlipChildren(AllLevels: WordBool);
begin
FDelphiControl.FlipChildren(AllLevels);
end;
procedure TPageScrollerX.InitiateAction;
begin
FDelphiControl.InitiateAction;
end;
procedure TPageScrollerX.Set_AutoScroll(Value: WordBool);
begin
FDelphiControl.AutoScroll := Value;
end;
procedure TPageScrollerX.Set_BiDiMode(Value: TxBiDiMode);
begin
FDelphiControl.BiDiMode := TBiDiMode(Value);
end;
procedure TPageScrollerX.Set_ButtonSize(Value: Integer);
begin
FDelphiControl.ButtonSize := Value;
end;
procedure TPageScrollerX.Set_Color(Value: OLE_COLOR);
begin
FDelphiControl.Color := TColor(Value);
end;
procedure TPageScrollerX.Set_Cursor(Value: Smallint);
begin
FDelphiControl.Cursor := TCursor(Value);
end;
procedure TPageScrollerX.Set_DockSite(Value: WordBool);
begin
FDelphiControl.DockSite := Value;
end;
procedure TPageScrollerX.Set_DoubleBuffered(Value: WordBool);
begin
FDelphiControl.DoubleBuffered := Value;
end;
procedure TPageScrollerX.Set_DragCursor(Value: Smallint);
begin
FDelphiControl.DragCursor := TCursor(Value);
end;
procedure TPageScrollerX.Set_DragMode(Value: TxDragMode);
begin
FDelphiControl.DragMode := TDragMode(Value);
end;
procedure TPageScrollerX.Set_DragScroll(Value: WordBool);
begin
FDelphiControl.DragScroll := Value;
end;
procedure TPageScrollerX.Set_Enabled(Value: WordBool);
begin
FDelphiControl.Enabled := Value;
end;
procedure TPageScrollerX.Set_Font(const Value: IFontDisp);
begin
SetOleFont(FDelphiControl.Font, Value);
end;
procedure TPageScrollerX.Set_Margin(Value: Integer);
begin
FDelphiControl.Margin := Value;
end;
procedure TPageScrollerX.Set_Orientation(Value: TxPageScrollerOrientation);
begin
FDelphiControl.Orientation := TPageScrollerOrientation(Value);
end;
procedure TPageScrollerX.Set_ParentColor(Value: WordBool);
begin
FDelphiControl.ParentColor := Value;
end;
procedure TPageScrollerX.Set_ParentFont(Value: WordBool);
begin
FDelphiControl.ParentFont := Value;
end;
procedure TPageScrollerX.Set_Position(Value: Integer);
begin
FDelphiControl.Position := Value;
end;
procedure TPageScrollerX.Set_Visible(Value: WordBool);
begin
FDelphiControl.Visible := Value;
end;
procedure TPageScrollerX.ClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnClick;
end;
procedure TPageScrollerX.DblClickEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnDblClick;
end;
procedure TPageScrollerX.KeyPressEvent(Sender: TObject; var Key: Char);
var
TempKey: Smallint;
begin
TempKey := Smallint(Key);
if FEvents <> nil then FEvents.OnKeyPress(TempKey);
Key := Char(TempKey);
end;
procedure TPageScrollerX.ResizeEvent(Sender: TObject);
begin
if FEvents <> nil then FEvents.OnResize;
end;
initialization
TActiveXControlFactory.Create(
ComServer,
TPageScrollerX,
TPageScroller,
Class_PageScrollerX,
21,
'{695CDB7B-02E5-11D2-B20D-00C04FA368D4}',
OLEMISC_SIMPLEFRAME or OLEMISC_ACTSLIKELABEL,
tmApartment);
end.
|
{***************************************************************}
{ }
{ Borland Delphi Visual Component Library }
{ }
{ Copyright (c) 2000-2001 Borland Software Corporation }
{ }
{***************************************************************}
unit WebNode;
interface
uses Classes, IntfInfo, WSDLIntf, SOAPAttachIntf;
type
{ IWebNode defines the basic interface to be implemented by any
SOAP Transport. IOW, if you want to implement SOAP on SMTP,
plain Socket, etc - you'll have to create a RIO that implements
IWebNode.
See THTTPRIO and TLinkedRIO for examples }
IWebNode = interface
['{77DB2644-0C12-4C0A-920E-89579DB9CC16}']
{ Obsolete - use version that takes a Stream as first parameter }
procedure Execute(const DataMsg: String; Response: TStream); overload; deprecated;
procedure BeforeExecute(const IntfMD: TIntfMetaData;
const MethMD: TIntfMethEntry;
MethodIndex: Integer;
AttachHandler: IMimeAttachmentHandler);
procedure Execute(const Request: TStream; Response: TStream); overload;
function Execute(const Request: TStream): TStream; overload;
{ Transport Attributes exposed in a generic fashion so that Converter
can break apart a multipart/related packet }
function GetMimeBoundary: string;
procedure SetMimeBoundary(Value: string);
property MimeBoundary: string read GetMimeBoundary write SetMimeBoundary;
end;
implementation
end.
|
{ *********************************************************** }
{ * TForge Library * }
{ * Copyright (c) Sergey Kasandrov 1997, 2016 * }
{ *********************************************************** }
unit tfCipherServ;
interface
{$I TFL.inc}
uses tfRecords, tfTypes, tfByteVectors, tfAlgServ,
tfAES, tfDES, tfRC5, tfRC4, tfSalsa20, tfKeyStreams;
function GetCipherServer(var A: ICipherServer): TF_RESULT;
implementation
type
PCipherServer = ^TCipherServer;
TCipherServer = record
public const
TABLE_SIZE = 64;
public
// !! inherited from TAlgServer
FVTable: PPointer;
FCapacity: Integer;
FCount: Integer;
FAlgTable: array[0..TABLE_SIZE - 1] of TAlgItem;
class function GetByAlgID(Inst: PCipherServer; AlgID: UInt32;
var Alg: ICipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetRC5(Inst: PCipherServer; BlockSize, Rounds: Integer;
var Alg: ICipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetSalsa20(Inst: PCipherServer; Rounds: Integer;
var Alg: ICipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetChaCha20(Inst: PCipherServer; Rounds: Integer;
var Alg: ICipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetKSByAlgID(Inst: PCipherServer; AlgID: UInt32;
var KS: IStreamCipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetKSByName(Inst: PAlgServer;
Name: Pointer; CharSize: Integer; var KS: IStreamCipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetKSRC5(Inst: PCipherServer; BlockSize, Rounds: Integer;
var KS: IStreamCipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetKSSalsa20(Inst: PCipherServer; Rounds: Integer;
var KS: IStreamCipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
class function GetKSChaCha20(Inst: PCipherServer; Rounds: Integer;
var KS: IStreamCipher): TF_RESULT;
{$IFDEF TFL_STDCALL}stdcall;{$ENDIF} static;
end;
class function TCipherServer.GetByAlgID(Inst: PCipherServer; AlgID: UInt32;
var Alg: ICipher): TF_RESULT;
begin
case AlgID of
// block ciphers
TF_ALG_AES: Result:= GetAESAlgorithm(PAESAlgorithm(Alg));
TF_ALG_DES: Result:= GetDESAlgorithm(PDESAlgorithm(Alg));
TF_ALG_RC5: Result:= GetRC5Algorithm(PRC5Algorithm(Alg));
TF_ALG_3DES: Result:= Get3DESAlgorithm(P3DESAlgorithm(Alg));
else
case AlgID of
// stream ciphers
TF_ALG_RC4: Result:= GetRC4Algorithm(PRC4Algorithm(Alg));
TF_ALG_SALSA20: Result:= GetSalsa20Algorithm(PSalsa20(Alg));
TF_ALG_CHACHA20: Result:= GetChaCha20Algorithm(PSalsa20(Alg));
else
Result:= TF_E_INVALIDARG;
end;
end;
end;
class function TCipherServer.GetRC5(Inst: PCipherServer; BlockSize,
Rounds: Integer; var Alg: ICipher): TF_RESULT;
begin
Result:= GetRC5AlgorithmEx(PRC5Algorithm(Alg), BlockSize, Rounds);
end;
class function TCipherServer.GetSalsa20(Inst: PCipherServer; Rounds: Integer;
var Alg: ICipher): TF_RESULT;
begin
Result:= GetSalsa20AlgorithmEx(PSalsa20(Alg), Rounds);
end;
class function TCipherServer.GetChaCha20(Inst: PCipherServer; Rounds: Integer;
var Alg: ICipher): TF_RESULT;
begin
Result:= GetChaCha20AlgorithmEx(PSalsa20(Alg), Rounds);
end;
class function TCipherServer.GetKSByAlgID(Inst: PCipherServer; AlgID: UInt32;
var KS: IStreamCipher): TF_RESULT;
var
Alg: ICipher;
begin
Result:= GetByAlgID(Inst, AlgID, Alg);
if Result = TF_S_OK then
Result:= TStreamCipherInstance.GetInstance(PStreamCipherInstance(KS), Alg);
end;
class function TCipherServer.GetKSByName(Inst: PAlgServer; Name: Pointer;
CharSize: Integer; var KS: IStreamCipher): TF_RESULT;
var
Alg: ICipher;
begin
Result:= TAlgServer.GetByName(Inst, Name, CharSize, IInterface(Alg));
if Result = TF_S_OK then
Result:= TStreamCipherInstance.GetInstance(PStreamCipherInstance(KS), Alg);
end;
class function TCipherServer.GetKSRC5(Inst: PCipherServer; BlockSize,
Rounds: Integer; var KS: IStreamCipher): TF_RESULT;
var
Alg: ICipher;
begin
Result:= GetRC5AlgorithmEx(PRC5Algorithm(Alg), BlockSize, Rounds);
if Result = TF_S_OK then
Result:= TStreamCipherInstance.GetInstance(PStreamCipherInstance(KS), Alg);
end;
class function TCipherServer.GetKSSalsa20(Inst: PCipherServer; Rounds: Integer;
var KS: IStreamCipher): TF_RESULT;
var
Alg: ICipher;
begin
Result:= GetSalsa20AlgorithmEx(PSalsa20(Alg), Rounds);
if Result = TF_S_OK then
Result:= TStreamCipherInstance.GetInstance(PStreamCipherInstance(KS), Alg);
end;
class function TCipherServer.GetKSChaCha20(Inst: PCipherServer; Rounds: Integer;
var KS: IStreamCipher): TF_RESULT;
var
Alg: ICipher;
begin
Result:= GetChaCha20AlgorithmEx(PSalsa20(Alg), Rounds);
if Result = TF_S_OK then
Result:= TStreamCipherInstance.GetInstance(PStreamCipherInstance(KS), Alg);
end;
const
VTable: array[0..15] of Pointer = (
@TForgeInstance.QueryIntf,
@TForgeSingleton.Addref,
@TForgeSingleton.Release,
@TCipherServer.GetByAlgID,
@TAlgServer.GetByName,
@TAlgServer.GetByIndex,
@TAlgServer.GetName,
@TAlgServer.GetCount,
@TCipherServer.GetRC5,
@TCipherServer.GetSalsa20,
@TCipherServer.GetChaCha20,
@TCipherServer.GetKSByAlgID,
@TCipherServer.GetKSByName,
@TCipherServer.GetKSRC5,
@TCipherServer.GetKSSalsa20,
@TCipherServer.GetKSChaCha20
);
var
Instance: TCipherServer;
const
AES_LITERAL: UTF8String = 'AES';
DES_LITERAL: UTF8String = 'DES';
TRIPLE_DES_LITERAL: UTF8String = '3DES';
RC5_LITERAL: UTF8String = 'RC5';
RC4_LITERAL: UTF8String = 'RC4';
SALSA20_LITERAL: UTF8String = 'SALSA20';
CHACHA20_LITERAL: UTF8String = 'CHACHA20';
procedure InitInstance;
begin
Instance.FVTable:= @VTable;
Instance.FCapacity:= TCipherServer.TABLE_SIZE;
// Instance.FCount:= 0;
TAlgServer.AddTableItem(@Instance, AES_LITERAL, @GetAESAlgorithm);
TAlgServer.AddTableItem(@Instance, DES_LITERAL, @GetDESAlgorithm);
TAlgServer.AddTableItem(@Instance, TRIPLE_DES_LITERAL, @Get3DESAlgorithm);
TAlgServer.AddTableItem(@Instance, RC5_LITERAL, @GetRC5Algorithm);
TAlgServer.AddTableItem(@Instance, RC4_LITERAL, @GetRC4Algorithm);
TAlgServer.AddTableItem(@Instance, SALSA20_LITERAL, @GetSalsa20Algorithm);
TAlgServer.AddTableItem(@Instance, CHACHA20_LITERAL, @GetChaCha20Algorithm);
end;
function GetCipherServer(var A: ICipherServer): TF_RESULT;
begin
if Instance.FVTable = nil then InitInstance;
// Server is implemented by a singleton, no need for releasing old instance
Pointer(A):= @Instance;
Result:= TF_S_OK;
end;
end.
|
{koder: A^2P}
{PSN 2005 #84 "Las compa¤ias de juegos y la guerra"}
uses umissile;
var
A,B,C,j,k : longint;
begin
{solve}
C := high(0);
j := high(1) - C; {j = A + B}
k := high(-1) - C; {k = A - B}
A := (j + k) div 2;
B := j - A;
{check}
solution(high(-B div (A * 2)));
end.{main}
{
84þ þ Las compa¤ias de juegos y la guerra. Polonia 2005
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
La compa¤¡a Nintendo ha inventado una nueva consola de juegos, para
que la disfruten los ni¤os de los presidentes de pa¡ses poderosos.
La consola de juegos tiene un funcionamiento muy sencillo, cada vez
que pap (el presidente) lanza un misil sobre un pa¡s rabe, ‚sta
filma todo el lanzamiento, despu‚s el ni¤o (con un dulce de chocolate
en la mano) introduce un n£mero entero "x" en la consola, para el cual
es devuelto otro entero "y" calculado a partir de y=axý+bx+c. El ni¤o
introduce varios n£meros hasta que ya sabe cual es el x que retorna
mayor y, entonces da este x como soluci¢n si es correcto gana sino
pierde.
Los enteros a, b, y c determinan la trayectoria del misil; para un
valor de x se tiene que axý+bx+c es la altura alcanzada por el misil
para la coordenada x. (a siempre es negativo x,y,b,c pueden ser
negativos o positivos)
Note que "y" puede ser negativo aunque represente la altura.
Tarea
Usted ser ni¤o de presidente poderoso por unas horas y debe
determinar el valor de x para el cual axý+bx+c tiene un valor m ximo.
Unit
Existir una unit llamada UMISSILE, que funciona id‚ntico a la consola
de juegos; posee una funci¢n y un procedimiento:
function high(x:longint) : longint;
procedure solution(x:longint);
La funci¢n high puede ser llamada cada vez que se quiera, a esta se le
pasa un entero "x" y devuelve la altura "y" del misile para esa "x".
El procedimiento solution debe ser llamada con el valor de x para el
cual high(x) retorna el mayor valor. Este procedimiento terminar la
corrida de su programa.
La unit UMISSILE leer los valores de a,b,c desde el archivo
MISSILE.IN, adem s escribir en el archivo MISSILE.OUT si su programa
lleg¢ a la soluci¢n correcta, adem s crear el archivo MISSILE.LOG con
toda la interacci¢n de su programa con la unit.
Su programa no tiene permitido leer del archivo MISSILE.IN
Restricciones
-4000 <= valor x de la soluci¢n <= 4000
-100 <= a,b,c <= 100 a es negativa Los valores de a,b,c en los juegos
de datos son tales que la "x" que alcanza altura m xima ser siempre
un entero.
Calificaci¢n
Si el valor de x en Solution(x) es incorrecto usted obtendr 0 ptos;
de lo contrario se le dar n 3*V/S ptos donde S es la cantidad de
preguntas a high y V es el valor del ese juego de datos.
Informaci¢n adicional
. la funcion y=axý+bx+c describe en el plano una par bola.
. si a < 0 la par bola tiene una "y" m xima pero no tiene m¡nima
. si a > 0 la par bola tiene una "y" m¡nima pero no m xima
. la "y" m xima o m¡nima se obtiene cuando x=-b/(2a)
Ejemplo
Para a=-1, b=2, c=3, la m xima y se alcanza cuando x=1
} |
unit FieldAttr;
interface
uses Classes, HTTPApp, Db, DbClient, Midas,
XMLBrokr, WebComp, PagItems, MidItems;
type
TFieldTextAttr = class(TFieldText)
private
FRequired: Boolean;
FDecimals: Integer;
FMaxValue: string;
FMinValue: string;
FFixedDecimals: Integer;
FCurrencySymbol: string;
protected
function ImplGetRowSetFieldAttributes(const FieldVarName: string): string; override;
public
constructor Create(AOwner: TComponent); override;
published
property Required: Boolean read FRequired write FRequired;
property Decimals: Integer read FDecimals write FDecimals default -1;
property FixedDecimals: Integer read FFixedDecimals write FFixedDecimals default -1;
property MinValue: string read FMinValue write FMinValue;
property MaxValue: string read FMaxValue write FMaxValue;
property CurrencySymbol: string read FCurrencySymbol write FCurrencySymbol;
end;
TTextColumnAttr = class(TTextColumn)
private
FRequired: Boolean;
FDecimals: Integer;
FMaxValue: string;
FMinValue: string;
FFixedDecimals: Integer;
FCurrencySymbol: string;
protected
function ImplGetRowSetFieldAttributes(const FieldVarName: string): string; override;
public
constructor Create(AOwner: TComponent); override;
published
property Required: Boolean read FRequired write FRequired;
property Decimals: Integer read FDecimals write FDecimals default -1;
property FixedDecimals: Integer read FFixedDecimals write FFixedDecimals default -1;
property MinValue: string read FMinValue write FMinValue;
property MaxValue: string read FMaxValue write FMaxValue;
property CurrencySymbol: string read FCurrencySymbol write FCurrencySymbol;
end;
procedure Register;
implementation
uses sysutils;
function FormatRowSetFieldAttributes(
const FieldVarName: string;
Required: Boolean; Decimals, FixedDecimals: Integer;
const MinValue, MaxValue, CurrencySymbol: string): string;
const
FalseTrue: array[Boolean] of string = ('false','true');
begin
Result := '';
Result := Format('%s%s.required = %s;'#13#10,
[Result, FieldVarName, FalseTrue[Required]]);
if Decimals >= 0 then
Result := Format('%s%s.decimals = %d;'#13#10,
[Result, FieldVarName, Decimals]);
if FixedDecimals >= 0 then
Result := Format('%s%s.fixeddec = %d;'#13#10,
[Result, FieldVarName, FixedDecimals]);
if MinValue <> '' then
Result := Format('%0:s%1:s.minval = %1:s.frdisp("%2:s");'#13#10,
[Result, FieldVarName, MinValue]);
if MaxValue <> '' then
Result := Format('%0:s%1:s.maxval = %1:s.frdisp("%2:s");'#13#10,
[Result, FieldVarName, MaxValue]);
if CurrencySymbol <> '' then
Result := Format('%s%s.currencySymbol = "%s";'#13#10,
[Result, FieldVarName, CurrencySymbol]);
end;
{ TFieldTextAttr }
constructor TFieldTextAttr.Create(AOwner: TComponent);
begin
inherited;
FDecimals := -1;
FFixedDecimals := -1;
end;
function TFieldTextAttr.ImplGetRowSetFieldAttributes(
const FieldVarName: string): string;
begin
Result := inherited ImplGetRowSetFieldAttributes(FieldVarName) +
FormatRowSetFieldAttributes(
FieldVarName,
Required, Decimals, FixedDecimals,
MinValue, MaxValue, CurrencySymbol);
end;
procedure Register;
begin
RegisterWebComponents([TFieldTextAttr, TTextColumnAttr]);
end;
{ TTextColumnAttr }
constructor TTextColumnAttr.Create(AOwner: TComponent);
begin
inherited;
FDecimals := -1;
FFixedDecimals := -1;
end;
function TTextColumnAttr.ImplGetRowSetFieldAttributes(
const FieldVarName: string): string;
begin
Result := inherited ImplGetRowSetFieldAttributes(FieldVarName) +
FormatRowSetFieldAttributes(
FieldVarName,
Required, Decimals, FixedDecimals,
MinValue, MaxValue, CurrencySymbol);
end;
end.
|
unit UnitTIniTracer;
interface
uses
Windows, Classes, Forms, SysUtils, Dialogs, IniFiles, Registry, Controls,
StrUtils, Messages, UnitTCifrador, frm_CifraIni,Graphics;
type
TIniTracer=class
private
sIndicador:string;
sRegName:string;
sSysName:string;
sKeyWord:string;
padre:TComponent;
function obtenerRuta:string;
function escribirRuta(sFileName:string):boolean;
function borrarRuta:boolean;
function crearDialog:TOpenDialog;
procedure mensajeNoIni(sFileName:string);
function descifrar(sEntrada:string):boolean;//devuelve true si al descifrar sEntrada da la KeyWord
public
property indicador:string read sIndicador;
property regName:string read sRegName;
property sysName:string read sSysName;
constructor Create(origen:TComponent;indicador,regName,sysName,keyWord:string);
function definirIni:string;
function borrarIni:string;
function cambiarIni:string;
end;
implementation
constructor TIniTracer.Create(origen:TComponent;indicador,regName,sysName,keyWord:string);
begin
padre:=origen;
sIndicador:=indicador;
sRegName:=regName;
sSysName:=sysName;
sKeyWord:=keyWord;
end;
function TIniTracer.definirIni: string;
var
Abrir:TOpenDialog;
sFileName:string;
xmed, ymed: integer;
begin
xmed:=trunc((Screen.width)/2)-80;
ymed:=trunc((screen.Height)/2)-30;
//Verificar si la ruta existe en el registro
sFileName:=obtenerRuta;
if sFileName = '' then begin
//Ya que no se localizó en el registro del sistema, verificar si el archivo ini existe localmente
sFileName := ChangeFileExt(Application.ExeName,'.ini');
if Not FileExists(sFileName) then begin//sino existe el archivo
mensajeNoIni(sFileName);//mandar mensaje para avisar que no existe el INI local
sFileName:='';
Abrir:=crearDialog;//crear el dialog
if Abrir.Execute then begin
sFileName := Abrir.FileName;//obtener el nombre de archivo indicado por el usurio
// Grabar la dirección especificada del archivo ini
if not escribirRuta(sFileName) then begin
//sino fue posible grabar, avisar al usuario y devolver vacio ''
sFileName:='';
MessageDlgPos('No fue posible definir el archivo seleccionado como archivo INI del sistema',
mtInformation, [mbOk],20,xmed,ymed);
end;
end
//else//no se eligio ningun archivo, enviar mensaje
//PostMessage(Handle, WM_CLOSE,0,0);
end;
end;
if not FileExists(sFileName) then
sFileName:='';
result:=sFileName;
end;
function TIniTracer.descifrar(sEntrada: string): boolean;
var
Cifrador:TCifrador;
sDescifrado:string;
xmed, ymed: integer;
begin
xmed:=trunc((Screen.width)/2)-80;
ymed:=trunc((screen.Height)/2)-30;
sDescifrado:='';
Cifrador:=TCifrador.crear('');
Cifrador.cifra:=sEntrada;
Cifrador.generarClaveBR1;
try
sDescifrado:=Cifrador.descifrar;
except
MessageDlgPos('No fue posible descifrar la clave porque no tiene el formato adecuado',
mtInformation, [mbOk], 0, xmed, ymed);
end;
Cifrador.Free;
result:=(sDescifrado=sKeyWord);
end;
function TIniTracer.cambiarIni: string;
var
Abrir:TOpenDialog;
sFileName:string;
xmed, ymed: integer;
begin
xmed:=trunc((Screen.width)/2)-80;
ymed:=trunc((screen.Height)/2)-30;
sFileName:='';
//Mostrar la ventana donde el usuario escribira la clave cifrada
Application.CreateForm(TFrmCifraIni, frmCifraIni);
if frmCifraIni.ShowModal = mrOk then begin
if descifrar(frmCifraIni.edtCifrado.Text) then begin
//Intentar cambiar el ini a uno determinado por el usuario
Abrir:=crearDialog;//crear el dialog
if Abrir.Execute then begin
sFileName := Abrir.FileName;//obtener el nombre de archivo indicado por el usurio
// Grabar la dirección especificada del archivo ini
if not escribirRuta(sFileName) then begin
//sino fue posible grabar, avisar al usuario y devolver vacio ''
sFileName:='';
MessageDlgPos('No fue posible definir el archivo seleccionado como archivo INI del sistema',
mtInformation, [mbOk], 200, xmed,ymed);
end;
end;
end
else begin
//la clave no es correcta, no esta permitido cambiar el INI
MessageDlgPos('La clave no es correcta', mtInformation, [mbOk], 0,xmed,ymed);
end;
end;
frmCifraIni.Free;
result:=sFileName;
end;
function TIniTracer.crearDialog: TOpenDialog;
var
Abrir:TOpenDialog;
begin
Abrir := TOpenDialog.Create(padre);
Abrir.Title := 'Seleccione el archivo INI';
Abrir.DefaultExt := 'INI';
Abrir.Filter := 'Archivos INI|*.ini';
Abrir.FilterIndex := 1;
Abrir.Options := [ofHideReadOnly,ofPathMustExist,ofFileMustExist,ofEnableSizing,ofForceShowHidden];
result:=Abrir;
end;
function TIniTracer.borrarIni: string;
begin
result:='No se pudo borrar el archivo INI';
if self.borrarRuta then begin
result:='Archivo INI borrado'
end;
end;
function TIniTracer.borrarRuta: boolean;
var
myReg: TRegistry;
begin
result:=false;
// Borrar la ruta del registro para que la vuelva a pedir en caso de ser necesario
try
myReg := TRegistry.Create;
myReg.RootKey := HKEY_LOCAL_MACHINE;
if myReg.OpenKey(sIndicador, TRUE) then
begin
myReg.WriteString(sRegName, '');
end;
result:=true;
finally
myReg.Free;
end;
end;
function TIniTracer.escribirRuta(sFileName:string): boolean;
Var
myReg: TRegistry;
begin
result:=false;
// Grabar la dirección especificada del archivo ini
try
myReg := TRegistry.Create;
myReg.RootKey := HKEY_LOCAL_MACHINE;
if myReg.OpenKey(sIndicador, TRUE) then begin
myReg.WriteString(sRegName, sFileName);
end;
result:=true;
finally
myReg.Free;
end;
end;
procedure TIniTracer.mensajeNoIni(sFileName: string);
var
sMensaje:string;
begin
sMensaje:=
'El sistema no ha podido localizar el archivo ' + sFileName + ' correspondiente.' + #10 + #10 +
'Este archivo es primordial para poder ejecutar el sistema '+sSysName+', en la siguiente ventana Usted prodrá indicar en donde se encuentra el archivo INI necesario.' + #10 + #10 +
'Si no conoce la ruta en la cual se encuentra su archivo INI pregunte al administrador del sistema.';
MessageDlg(sMensaje, mtInformation, [mbOk], 0);
end;
function TIniTracer.obtenerRuta:string;
Var
myReg: TRegistry;
sFile:string;
begin
sFile:='';
// Verificar si la ruta existe en el registro
try
myReg:= TRegistry.Create;
myReg.RootKey:=HKEY_LOCAL_MACHINE;
if myReg.OpenKey(sIndicador, FALSE) then
sFile:= myReg.ReadString(sRegName)
else
sFile := '';
finally
myReg.Free;
end;
result:=sFile;
end;
end.
|
unit Ex12FullUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, MTUtils, ComCtrls, ExtCtrls, StrUtils, Contnrs,
Generics.Collections;
type
TMyThread = class(TThread)
private
procedure LogEvent(EventText: string);
procedure CallMyFuncInMainThread(param1: Integer; param2: string);
protected
procedure Execute; override;
end;
TForm1 = class(TForm)
btnRunInParallelThread: TButton;
Button1: TButton;
ListBox1: TListBox;
labLabLastThreadTime: TLabel;
Label1: TLabel;
cbLinkThreadToQueue: TComboBox;
btnClearListBox: TButton;
procedure btnRunInParallelThreadClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure cbLinkThreadToQueueSelect(Sender: TObject);
procedure btnClearListBoxClick(Sender: TObject);
private
{ Private declarations }
FList: TObjectList<TMyThread>;
public
{ Public declarations }
end;
var
Form1: TForm1;
LinkThreadToQueue: Boolean = True;
implementation
{$R *.dfm}
procedure TForm1.btnClearListBoxClick(Sender: TObject);
begin
ListBox1.Clear;
end;
procedure TForm1.btnRunInParallelThreadClick(Sender: TObject);
begin
// Создаём и запускаем новый поток
FList.Add(TMyThread.Create(False));
end;
procedure TForm1.Button1Click(Sender: TObject);
var
t: TMyThread;
begin
for t in FList do
t.Terminate; // Сообщаем потокам о необходимости завершаться
FList.Clear; // Уничтожаем потоки
end;
procedure TForm1.cbLinkThreadToQueueSelect(Sender: TObject);
begin
LinkThreadToQueue := cbLinkThreadToQueue.ItemIndex = 0;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
FList := TObjectList<TMyThread>.Create;
ThreadWaitTimeoutSleepTime := 1;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FList.Free;
end;
{ TMyThread }
procedure TMyThread.CallMyFuncInMainThread(param1: Integer; param2: string);
begin
TThread.Queue(nil,
procedure
var
s: string;
begin
s := Format('param1=%d; param2=%s', [param1, param2]);
Form1.ListBox1.Items.Add(s);
end);
end;
procedure TMyThread.Execute;
var
I: Integer;
CurTime: TDateTime;
sVal: string;
begin
// Делаем низкий приоритет потоку, чтобы выделялим минимальные
// кванты времени. Так быстрее проявляется проблема очистки
// очереди при уничтожении потока
Priority := tpLowest;
CurTime := Now; // Запоминаем время ДО вызова Queue
Queue(
procedure
begin
Form1.labLabLastThreadTime.Caption :=
'Последний поток был запущен: ' + DateTimeToStr(CurTime);
end);
{I := 111;
sVal := 'Text 1';
CallMyFuncInMainThread(I, sVal);
I := 222;
sVal := 'Text 2';
CallMyFuncInMainThread(I, sVal); }
I := 111;
sVal := 'Text 1';
TThread.Queue(nil,
procedure
var
s: string;
begin
s := Format('param1=%d; param2=%s', [I, sVal]);
Form1.ListBox1.Items.Add(s);
end);
I := 222;
sVal := 'Text 2';
TThread.Queue(nil,
procedure
var
s: string;
begin
s := Format('param1=%d; param2=%s', [I, sVal]);
Form1.ListBox1.Items.Add(s);
end);
LogEvent('Thread start');
while not Terminated do
begin
Inc(I);
LogEvent('Event #' + IntToStr(I));
ThreadWaitTimeout(Self, 500);
end;
LogEvent('Thread stop');
for I := 1 to 100 do
begin
LogEvent('Thread stop' + I.ToString);
Sleep(0); // Делаем активным другой поток
end;
end;
procedure TMyThread.LogEvent(EventText: string);
var
ThreadId: Cardinal;
EventTime: TDateTime;
ThreadRef: TMyThread;
begin
// Запоминаем ID потока и текущее время ДО вызова Queue
ThreadId := GetCurrentThreadId;
EventTime := Now;
if LinkThreadToQueue then
ThreadRef := Self
else
ThreadRef := nil;
TThread.Queue(ThreadRef,
procedure
begin
Form1.ListBox1.Items.Add(Format('%s [T:%d] - %s',
[FormatDateTime('hh:nn:ss.zzz', EventTime), ThreadId, EventText]));
Form1.ListBox1.ItemIndex := Form1.ListBox1.Count - 1;
// Подвешиваем основной поток
Sleep(5);
end);
end;
end.
|
{******************************************}
{ TDragPointTool and Editor Dialog }
{ Copyright (c) 2000-2004 by David Berneda }
{******************************************}
unit TeeDragPoint;
{$I TeeDefs.inc}
interface
uses {$IFDEF CLR}
Windows,
Classes,
Borland.VCL.Controls,
Borland.VCL.StdCtrls,
Borland.VCL.ExtCtrls,
{$ELSE}
{$IFDEF LINUX}
Libc,
{$ELSE}
{$IFNDEF CLX}
Windows, Messages,
{$ENDIF}
{$ENDIF}
SysUtils, Classes,
{$IFDEF CLX}
QGraphics, QControls, QForms, QDialogs, QStdCtrls, QExtCtrls,
{$ELSE}
Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls,
{$ENDIF}
{$ENDIF}
TeeToolSeriesEdit, TeEngine, TeeTools, TeCanvas;
{ DragPoint: A TeeChart Tool example.
This tool component can be used to allow the end-user to
drag points of any Chart Series by using the mouse.
This unit also includes a Form that is used as the editor dialog
for the tool. This form automatically shows at the Tools tab of the
TeeChart editor.
Installation / use:
1) Add this unit to a project or to a design-time package.
2) Then, edit a Chart1 and go to "Tools" tab and Add a DragPoint tool.
3) Set the tool Series property to a existing series (eg: Series1 ).
4) Fill the series with points as usually.
5) At run-time, use the left mouse button to click and drag a
Series point.
}
type
{ The Tool editor dialog }
TDragPointToolEdit = class(TSeriesToolEditor)
RGStyle: TRadioGroup;
Label2: TLabel;
CBCursor: TComboFlat;
procedure FormShow(Sender: TObject);
procedure RGStyleClick(Sender: TObject);
procedure CBSeriesChange(Sender: TObject);
procedure CBCursorChange(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TDragPointTool=class;
TDragPointToolEvent=procedure(Sender:TDragPointTool; Index:Integer) of object;
TDragPointStyle=(dsX,dsY,dsBoth);
{ Drag Point Tool }
TDragPointTool=class(TTeeCustomToolSeries)
private
FDragStyle: TDragPointStyle;
FOnDrag : TDragPointToolEvent;
IDragging : Integer;
protected
Procedure ChartMouseEvent( AEvent: TChartMouseEvent;
Button:TMouseButton;
Shift: TShiftState; X, Y: Integer); override;
class Function GetEditorClass:String; override;
public
Constructor Create(AOwner:TComponent); override;
class Function Description:String; override;
published
property Active;
property DragStyle:TDragPointStyle read FDragStyle write FDragStyle
default dsBoth;
property Series;
{ events }
property OnDragPoint:TDragPointToolEvent read FOnDrag write FOnDrag;
end;
implementation
{$IFNDEF CLX}
{$R *.DFM}
{$ELSE}
{$R *.xfm}
{$ENDIF}
Uses Chart, TeeProCo, TeePenDlg;
{ TDragPointTool }
Constructor TDragPointTool.Create(AOwner: TComponent);
begin
inherited;
IDragging:=-1;
FDragStyle:=dsBoth;
end;
{ When the user clicks or moves the mouse... }
procedure TDragPointTool.ChartMouseEvent(AEvent: TChartMouseEvent;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
Function CheckAxisLimits(Axis:TChartAxis; Position:Integer):Double;
begin
with Axis do
if Maximum=Minimum then
begin
AutomaticMaximum:=False;
Maximum:=Maximum+0.1*MinAxisIncrement; // 6.02, fix when values are equal
end;
result:=Axis.CalcPosPoint(Position);
end;
begin
if Assigned(Series) then
Case AEvent of
cmeUp: IDragging:=-1; { stop dragging on mouse up }
cmeMove: if IDragging<>-1 then { if dragging... }
With Series do
begin
BeginUpdate;
{ Change the Series point X and / or Y values... }
if (Self.DragStyle=dsX) or (Self.DragStyle=dsBoth) then
XValue[IDragging]:=CheckAxisLimits(GetHorizAxis,x);
if (Self.DragStyle=dsY) or (Self.DragStyle=dsBoth) then
YValue[IDragging]:=CheckAxisLimits(GetVertAxis,y);
EndUpdate;
{ Notify the point values change... }
if Assigned(FOnDrag) then FOnDrag(Self,IDragging);
end;
cmeDown: begin { when the mouse button is pressed... }
IDragging:=Series.Clicked(x,y);
{ if clicked a Series point... }
if IDragging<>-1 then ParentChart.CancelMouse:=True;
end;
end;
end;
class function TDragPointTool.Description: String;
begin
result:=TeeMsg_DragPoint;
end;
class function TDragPointTool.GetEditorClass: String;
begin
result:='TDragPointToolEdit'; { the editor dialog class name }
end;
procedure TDragPointToolEdit.FormShow(Sender: TObject);
var tmpCursor : TCursor;
begin
inherited;
tmpCursor:=crDefault;
CBCursor.Enabled:=False;
if Assigned(Tool) then
begin
Case TDragPointTool(Tool).DragStyle of
dsX : RGStyle.ItemIndex:=0;
dsY : RGStyle.ItemIndex:=1;
else
RGStyle.ItemIndex:=2;
end;
if Assigned(Tool.Series) then
begin
tmpCursor:=Tool.Series.Cursor;
CBCursor.Enabled:=True;
end;
end;
TeeFillCursors(CBCursor,tmpCursor);
end;
procedure TDragPointToolEdit.RGStyleClick(Sender: TObject);
begin
With TDragPointTool(Tool) do
Case RGStyle.ItemIndex of
0: DragStyle:=dsX;
1: DragStyle:=dsY;
else
DragStyle:=dsBoth;
end;
end;
{ register both the tool and the tool editor dialog form }
procedure TDragPointToolEdit.CBSeriesChange(Sender: TObject);
begin
inherited;
CBCursor.Enabled:=Assigned(Tool.Series);
end;
procedure TDragPointToolEdit.CBCursorChange(Sender: TObject);
begin
with Tool.Series do
Cursor:=TeeSetCursor(Cursor,CBCursor.Items[CBCursor.ItemIndex]);
end;
initialization
RegisterClass(TDragPointToolEdit);
RegisterTeeTools([TDragPointTool]);
finalization
{ un-register the tool }
UnRegisterTeeTools([TDragPointTool]);
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.