text
stringlengths
14
6.51M
program actividad3; const dimF = 20; type str40 = String[40]; rangoCategoria = 1..20; producto = record nombre : str40; precioCosto : Real; precioVenta : Real; categoria : Integer; end; lista = ^nodo; nodo = record datos : producto; sig : lista; end; vContador = array[rangoCategoria] of Integer; procedure LeerDatos(var p:producto); begin with p do begin write('Ingrese la CATEGORIA: '); readln(categoria); if (categoria <> 999) then begin write('Ingrese el NOMBRE: '); readln(nombre); write('Ingrese PRECIO DE COSTO: '); readln(precioCosto); write('Ingrese PRECIO DE VENTA: '); readln(precioVenta); writeln('------------------------'); end; end; end; procedure inicializarVectorContador(var vc:vContador); var i: rangoCategoria; begin for i := 1 to dimF do begin vc[i]:=0; end; end; procedure agregarAdelante(var l:lista; p:producto); var nue: lista; begin new(nue); nue^.datos:= p; nue^.sig:= l; l:= nue; end; procedure cargarLista(var l:lista); var p: producto; begin LeerDatos(p); while (p.categoria <> 999) do begin agregarAdelante(l,p); LeerDatos(p); end; end; //#### FINALIZO CARGA DE LISTA #### procedure imprimirVector(vc:vContador); var i: rangoCategoria; begin for i := 1 to dimF do begin writeln('La CATEGORIA: ', i, ' tiene ', vc[i], ' productos '); end; end; function cumple(precioCosto,precioVenta: Real): Boolean; begin cumple:= (precioVenta > ((precioCosto)*1.1)); end; procedure nomMaxProducto(precio:Real; var max:Real; nombre: String; var nomMax:String); begin if (precio > max) then begin max:= precio; nomMax:= nombre; end; end; procedure procesarInfo(l:lista; var vc:vContador); var cat, cont: Integer; max: Real; nomMax: String; begin cont:= 0; max:= -1; nomMax:= ''; while (l <> nil) do begin cat:= l^.datos.categoria; //inciso 1 vc[cat]:= vc[cat] + 1; if (cumple(l^.datos.precioCosto,l^.datos.precioVenta)) then //inciso 2 cont:= cont + 1; nomMaxProducto(l^.datos.precioVenta, max, l^.datos.nombre,nomMax); //inciso 3 l:= l^.sig; end; //inciso 1 imprimirVector(vc); writeln('--------------------------------------------------------'); //inciso 2 writeln('La cantidad de productos que dejan gananacia son: ', cont); //inciso 3 writeln('El nombre del producto con mayor precio es: ', nomMax); end; var l: lista; vc: vContador; begin l:=nil; inicializarVectorContador(vc); cargarLista(l); procesarInfo(l,vc); readln(); end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { { Rev 1.3 10/26/2004 9:55:58 PM JPMugaas { Updated refs. } { { Rev 1.2 4/19/2004 5:06:10 PM JPMugaas { Class rework Kudzu wanted. } { Rev 1.1 10/19/2003 3:36:18 PM DSiders Added localization comments. } { { Rev 1.0 10/1/2003 12:55:20 AM JPMugaas { New FTP list parsers. } unit IdFTPListParseStercomOS390Exp; interface uses IdFTPList, IdFTPListParseBase, IdObjs; type TIdSterCommExpOS390FTPListItem = class(TIdFTPListItem) protected FRecFormat : String; FRecLength : Integer; FBlockSize : Integer; public property RecFormat : String read FRecFormat write FRecFormat; property RecLength : Integer read FRecLength write FRecLength; property BlockSize : Integer read FBlockSize write FBlockSize; end; TIdFTPLPSterCommExpOS390 = class(TIdFTPListBase) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String=''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TIdStrings; const ASysDescript : String =''; const ADetails : Boolean = True): boolean; override; end; const STIRCOMEXPOS390 = 'Connect:Express for OS/390'; {do not localize} implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, IdSys; { "Connect:Express OS/390 FTP Guide Version 4.1" Copyright © 2002, 2003 Sterling Commerce, Inc. 125 LIST Command accepted. -D 2 T VB 00244 18000 FTPGDG!PSR$TST.GDG.TSTGDG0(+01) -D 2 * VB 00244 27800 FTPV!PSR$TST.A.VVV.&REQNUMB -F 1 R - - - FTPVAL1!PSR$TST.A.VVV 250 list completed successfully. The LIST of symbolic files from Connect:Express Files directory available for User FTP1 is sent. A number of File attributes are showed. Default profile FTPV is part of the list. The Following attributes are sent: - Dynamic or Fixed Allocation - Allocation rule: 2 = to be created, 1 = pre-allocated, 0=to be created or replaced - Direction Transmission, Reception, * = both - File record format (Variable, Fixed, Blocked..) - Record length - Block size } { TIdFTPLPSterCommExpOS390 } class function TIdFTPLPSterCommExpOS390.CheckListing(AListing: TIdStrings; const ASysDescript: String; const ADetails: Boolean): boolean; var LBuf : String; begin Result := False; if AListing.Count >0 then begin LBuf := AListing[0]; if (Copy(LBuf,2,2)<>'D ') and (Copy(LBuf,2,2)<>'F ') then {do not localize} begin Exit; end; if (Copy(LBuf,4,2) <> '0 ') and (Copy(LBuf,4,2) <> '1 ') and (Copy(LBuf,4,2) <> '2 ') then {do not localize} begin Exit; end; Result := True; end; end; class function TIdFTPLPSterCommExpOS390.GetIdent: String; begin Result := STIRCOMEXPOS390; end; class function TIdFTPLPSterCommExpOS390.MakeNewItem( AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdSterCommExpOS390FTPListItem.Create(AOwner); end; class function TIdFTPLPSterCommExpOS390.ParseLine( const AItem: TIdFTPListItem; const APath: String): Boolean; var s : TIdStrings; LI : TIdSterCommExpOS390FTPListItem; begin LI := AItem as TIdSterCommExpOS390FTPListItem; s := TIdStringList.Create; try SplitColumns(AItem.Data,s); if s.Count > 3 then begin if s[3]<>'-' then begin LI.RecFormat := s[3]; end; end; if s.Count > 4 then begin LI.RecLength := Sys.StrToInt64(s[4],0); end; if s.Count > 5 then begin LI.BlockSize := Sys.StrToInt64(s[5],0); end; if s.Count > 6 then begin LI.FileName := s[6]; end; finally Sys.FreeAndNil(s); end; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPSterCommExpOS390); finalization UnRegisterFTPListParser(TIdFTPLPSterCommExpOS390); end.
unit DDrawManager; interface uses Windows, Forms, Classes, DDraw, GDI, Dibs, DirectStuff; // function AreOverlaysSupported : boolean; type PVideoMode = ^TVideoMode; TVideoMode = record vmWidth : dword; vmHeight : dword; vmBitCount : dword; vmDepth : dword; vmEnabled : boolean; end; type PVideoModes = ^TVideoModes; TVideoModes = record Count : dword; Modes : array[0..50] of TVideoMode; end; type TDirectDrawManager = class private fDirectDraw : IDirectDrawX; public constructor Create; destructor Destroy; override; function CreatePrimarySurface(BackBufferCount : dword ; Support3D : boolean) : IDirectSurface; function CreateOverlaySurface(Width, Height : dword; BitCount : dword; BackBufferCount : dword; Support3D : boolean) : IDirectSurface; function CreateOffscreenSurface( Width, Height : dword; BitCount : dword; Support3D : boolean ) : IDirectSurface; function CreateTextureSurface(Width, Height : dword; BitCount : dword; managed : boolean) : IDirectSurface; function CreateSurfaceEx( SurfaceDesc : TDirectSurfaceDesc ) : IDirectSurface; function CreatePalette(Count : dword; LogEntries : pointer; dwCaps : dword) : IDirectPalette; function CreateClipper : IDirectClipper; function GetDriverCaps(out Caps : TDirectDrawCaps) : HRESULT; procedure InitDirectDraw; procedure FreeDirectDraw; procedure InitSurfaces; procedure FreeSurfaces; procedure SetCooperativeLevel(Flags : dword); protected fUseHardware : boolean; //fDeviceDesc : TD3DDeviceDesc; //fDeviceGUID : TGUID; fCooperativeFlags : dword; fVideoMemory : dword; fVideoMode : dword; fVideoModes : PVideoModes; fOverlayMinStretch : dword; fOverlaySrcSizeAlign : dword; fOverlayDestSizeAlign : dword; fOverlayXPosAlign : dword; procedure SetCurrentMode(Value : dword); procedure GetVideoModes; function GetCurrentModeCaps : TVideoMode; function GetVideoModeCaps(Value : dword) : TVideoMode; public property DirectDraw : IDirectDraw read fDirectDraw; property CurrentModeIndx : dword read fVideoMode write SetCurrentMode; property CurrentModeCaps : TVideoMode read GetCurrentModeCaps; property OverlayMinStretch : dword read fOverlayMinStretch; property OverlaySrcSizeAlign : dword read fOverlaySrcSizeAlign; property OverlayDestSizeAlign : dword read fOverlayDestSizeAlign; property OverlayXPosAlign : dword read fOverlayXPosAlign; property AvailableVideoModes : PVideoModes read fVideoModes; procedure SetVideoMode( Width, Height, BitCount : dword; RequiresExactMatch : boolean ); procedure SetupVideoMode( Width, Height, BitCount : dword ); function SearchVideoMode( Width, Height, BitCount : dword; RequiresExactMatch : boolean ) : dword; function BestFitVideoMode( Width, Height, BitCount : dword ) : dword; end; // Cooperative level flags const clFullScreen = DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN or DDSCL_ALLOWMODEX or DDSCL_ALLOWREBOOT; clFullScreenNoReboot = DDSCL_EXCLUSIVE or DDSCL_FULLSCREEN or DDSCL_ALLOWMODEX; clNormal = DDSCL_NORMAL; // var DirectDrawMgr : TDirectDrawManager; procedure InitDirectDrawMgr; // type TSurfaceType = (stPlain, stPrimary, stOverlay, stTexture); implementation uses Dialogs, SysUtils, NumUtils, BitBlt, LogFile; // DirectDrawMgr procedure InitDirectDrawMgr; begin if DirectDrawMgr = nil then DirectDrawMgr := TDirectDrawManager.Create; end; const idxNotFound = $FFFFFFFF; function AreOverlaysSupported : boolean; var capsDrv : TDirectDrawCaps; ddrval : HRESULT ; begin Result := false; InitDirectDrawMgr; ddrval := DirectDrawMgr.GetDriverCaps( capsDrv ); // Does the driver support overlays in the current mode? // ( Currently the DirectDraw emulation layer does not support overlays. // Overlay related APIs will fail without hardware support ). if ( ddrval = DD_OK ) and ( capsDrv.dwCaps and DDCAPS_OVERLAY <> 0 ) then Result := true; end; // DirectDraw devices enumeration callback function DDEnumCallback( lpGUID : PGUID; lpDriverDesc: pchar; lpDriverName : pchar; lpContext : pointer ): BOOL; var DD : IDirectDraw; DriverCaps : TDirectDrawCaps; HELCaps : TDirectDrawCaps; DDrawMgr : TDirectDrawManager absolute lpContext; begin Result := BOOL( DDENUMRET_OK ); if DDR( DirectDrawCreate( lpGUID, DD, nil ) ) = DD_OK then begin DDrawMgr.fDirectDraw := DD as IDirectDrawX; InitRecord( DriverCaps, sizeof( DriverCaps ) ); InitRecord( HELCaps, sizeof( HELCaps ) ); if DDR( DDrawMgr.fDirectDraw.GetCaps( @DriverCaps, @HELCaps ) ) = DD_OK then begin if ( DriverCaps.dwCaps and DDCAPS_3D ) <> 0 then Result := BOOL( DDENUMRET_CANCEL ); end; end; end; (* // Direct3D devices enumeration callback function D3DEnumDeviceCallBack( var lpGuid: TGUID; lpDeviceDescription: PAnsiChar; lpDeviceName: PAnsiChar; var lpD3DHWDeviceDesc: TD3DDeviceDesc; var lpD3DHELDeviceDesc: TD3DDeviceDesc; lpContext : pointer ) : HRESULT; stdcall; var DDrawMgr : TDirectDrawManager absolute lpContext; begin Result := DDENUMRET_OK; if ( integer( lpD3DHWDeviceDesc.dcmColorModel ) and integer( D3DCOLOR_RGB ) ) <> 0 then begin // Make sure the driver has ZBuffering capabilities if ( ( ( lpD3DHWDeviceDesc.dwDeviceZBufferBitDepth and DDBD_16 ) <> 0 ) or ( ( lpD3DHWDeviceDesc.dwDeviceZBufferBitDepth and DDBD_24 ) <> 0 ) or ( ( lpD3DHWDeviceDesc.dwDeviceZBufferBitDepth and DDBD_32 ) <> 0 ) ) then begin // Record the HAL description DDrawMgr.fDeviceDesc := lpD3DHWDeviceDesc;; DDrawMgr.fDeviceGUID := lpGuid; DDrawMgr.fUseHardware := true; Result := DDENUMRET_CANCEL; end; end else if ( integer( lpD3DHELDeviceDesc.dcmColorModel ) and integer( D3DCOLOR_MONO ) ) <> 0 then begin DDrawMgr.fDeviceDesc := lpD3DHWDeviceDesc;; DDrawMgr.fDeviceGUID := lpGuid; end; end; *) // TDirectDrawManager constructor TDirectDrawManager.Create; begin inherited; InitDirectDraw; end; destructor TDirectDrawManager.Destroy; begin FreeSurfaces; FreeDirectDraw; end; function TDirectDrawManager.GetDriverCaps( out Caps : TDirectDrawCaps ) : HRESULT; begin // Get driver capabilities InitRecord( Caps, sizeof( Caps ) ); Result := fDirectDraw.GetCaps( @Caps, nil ); end; function TDirectDrawManager.CreateClipper : IDirectClipper; begin if DDR( fDirectDraw.CreateClipper( 0, Result, nil ) ) <> DD_OK then // TODO 1 -oJRG : DD CreateClipper Error end; function TDirectDrawManager.CreatePalette( Count : dword; LogEntries : pointer; dwCaps : dword ) : IDirectPalette; begin assert( Count <> 0, 'Invalid Count specified!!' ); case Count of 1..2 : dwCaps := dwCaps or DDPCAPS_1BIT; 3..4 : dwCaps := dwCaps or DDPCAPS_2BIT; 5..16 : dwCaps := dwCaps or DDPCAPS_4BIT; else // 17..256 : dwCaps := dwCaps or DDPCAPS_8BIT; end; if DDR( fDirectDraw.CreatePalette( dwCaps, LogEntries, Result, nil ) ) <> DD_OK then // TODO 1 -oJRG : DD CreatePalette Error end; procedure SetPixFormat(BitCount : dword; var Dest : TDDPixelFormat ); begin with Dest do begin // TODO 1 -oJRG -cGraphics : Tengo que aņadir soporte para el formato BGR!! dwSize := sizeof( TDDPixelFormat ); dwFourCC := 0; dwRGBBitCount := BitCount; case BitCount of 1 : dwFlags := DDPF_RGB or DDPF_PALETTEINDEXED1; 2 : dwFlags := DDPF_RGB or DDPF_PALETTEINDEXED2; 4 : dwFlags := DDPF_RGB or DDPF_PALETTEINDEXED4; 8 : dwFlags := DDPF_RGB or DDPF_PALETTEINDEXED8; 15 : begin dwFlags := DDPF_RGB; dwRGBBitCount := 16; dwRBitMask := $7C00; dwGBitMask := $03E0; dwBBitMask := $001F; dwRGBAlphaBitMask := 0; end; 16 : begin dwFlags := DDPF_RGB; dwRBitMask := $F800; dwGBitMask := $07E0; dwBBitMask := $001F; dwRGBAlphaBitMask := 0; end; 24 : begin dwFlags := DDPF_RGB; dwRBitMask := $FF0000; dwGBitMask := $00FF00; dwBBitMask := $0000FF; dwRGBAlphaBitMask := 0; end; // 24 : // begin // dwFlags := DDPF_RGB; // dwRBitMask := $0000FF; // dwGBitMask := $00FF00; // dwBBitMask := $FF0000; // dwRGBAlphaBitMask := 0; // end; 32 : begin dwFlags := DDPF_RGB; dwRBitMask := $FF0000; dwGBitMask := $00FF00; dwBBitMask := $0000FF; dwRGBAlphaBitMask := 0; end; // 32 : // begin // dwFlags := DDPF_RGB; // dwRBitMask := $0000FF; // dwGBitMask := $00FF00; // dwBBitMask := $FF0000; // dwRGBAlphaBitMask := 0; // end; end; end; end; function TDirectDrawManager.CreateSurfaceEx(SurfaceDesc : TDirectSurfaceDesc) : IDirectSurface; begin if DDR(fDirectDraw.CreateSurface(SurfaceDesc, Result, nil)) <> DD_OK then Result := nil; end; function TDirectDrawManager.CreateOffscreenSurface(Width, Height, BitCount : dword; Support3D : boolean) : IDirectSurface; var ddsd : TDirectSurfaceDesc; begin InitRecord( ddsd, sizeof( ddsd ) ); with ddsd do begin dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT; ddsCaps.dwCaps := DDSCAPS_OFFSCREENPLAIN;// or DDSCAPS_SYSTEMMEMORY; dwWidth := Width; dwHeight := Height; if Support3D then ddsCaps.dwCaps := ddsCaps.dwCaps or DDSCAPS_3DDEVICE; SetPixFormat( BitCount, ddpfPixelFormat ); end; if DDR( fDirectDraw.CreateSurface( ddsd, Result, nil ) ) <> DD_OK then raise Exception.Create( 'Could not create plain surface!!' ); //EDirectDrawSurface.Create;; end; function TDirectDrawManager.CreateTextureSurface(Width, Height, BitCount : dword) : IDirectSurface; var ddsd : TDirectSurfaceDesc; begin // TODO 1 -oJRG -cGraphics : Unfinished!! with ddsd do begin dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT or DDSD_TEXTURESTAGE; ddsCaps.dwCaps := DDSCAPS_TEXTURE or DDSCAPS_SYSTEMMEMORY; ddsCaps.dwCaps2 := 0; dwWidth := Width; dwHeight := Height; SetPixFormat( BitCount, ddpfPixelFormat ); end; end; function TDirectDrawManager.CreatePrimarySurface(BackBufferCount : dword; Support3D : boolean) : IDirectSurface; var ddsd : TDirectSurfaceDesc; begin InitRecord( ddsd, sizeof( ddsd ) ); with ddsd do begin if BackBufferCount > 0 then begin dwFlags := DDSD_CAPS or DDSD_BACKBUFFERCOUNT; dwBackBufferCount := BackBufferCount; ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE or DDSCAPS_FLIP or DDSCAPS_COMPLEX; end else begin dwFlags := DDSD_CAPS; ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE; end; if Support3D then ddsCaps.dwCaps := ddsCaps.dwCaps or DDSCAPS_3DDEVICE; end; if DDR( fDirectDraw.CreateSurface( ddsd, Result, nil ) ) <> DD_OK then raise Exception.Create( 'Could not create primary surface!!' ); //EDirectDrawSurface.Create;; end; function TDirectDrawManager.CreateOverlaySurface(Width, Height, BitCount, BackBufferCount : dword; Support3D : boolean) : IDirectSurface; var ddsd : TDirectSurfaceDesc; retcode : integer; begin InitRecord( ddsd, sizeof( ddsd ) ); with ddsd do begin if BackBufferCount > 0 then begin dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT or DDSD_BACKBUFFERCOUNT; dwBackBufferCount := BackBufferCount; ddsCaps.dwCaps := DDSCAPS_OVERLAY or DDSCAPS_FLIP or DDSCAPS_COMPLEX or DDSCAPS_VIDEOMEMORY; end else begin dwFlags := DDSD_CAPS or DDSD_HEIGHT or DDSD_WIDTH or DDSD_PIXELFORMAT; ddsCaps.dwCaps := DDSCAPS_OVERLAY or DDSCAPS_VIDEOMEMORY; end; if Support3D then ddsCaps.dwCaps := ddsCaps.dwCaps or DDSCAPS_3DDEVICE; SetPixFormat( BitCount, ddpfPixelFormat ); dwWidth := Width; dwHeight := Height; end; retcode := {DDR( }fDirectDraw.CreateSurface( ddsd, Result, nil ){)}; LogThis(ErrorString(retcode)); if retcode <> DD_OK then raise Exception.Create( 'Could not create overlay surface!! ' + ' Error : ' + ErrorString(retcode)); //EDirectDrawSurface.Create;; end; (* procedure TDirectDrawManager.CreateSurfaces; var CurMode : TVideoMode; ddsd : TDDSURFACEDESC; ddscaps : TDDSCAPS; Palette : IDIRECTPALETTE; i : integer; begin Result := false; CurMode := fModes[fVideoMode]; InitRecord( ddsd, sizeof( ddsd ) ); ddsd.dwFlags := DDSD_CAPS or DDSD_BACKBUFFERCOUNT; ddsd.ddsCaps.dwCaps := DDSCAPS_PRIMARYSURFACE or DDSCAPS_FLIP or DDSCAPS_COMPLEX or DDSCAPS_3DDEVICE; ddsd.dwBackBufferCount := 1; if DDR( fDirectDraw.CreateSurface( ddsd, fPrimaryBuffer, nil ) ) = DD_OK then begin InitRecord( ddscaps, sizeof( ddscaps ) ); ddscaps.dwCaps := DDSCAPS_BACKBUFFER; if DDR( fPrimaryBuffer.GetAttachedSurface( ddscaps, fBackBuffer ) ) = DD_OK then begin if fZBufferBitDepth > 0 then begin InitRecord( ddsd, sizeof( ddsd ) ); ddsd.dwFlags := DDSD_WIDTH or DDSD_HEIGHT or DDSD_CAPS or DDSD_ZBUFFERBITDEPTH;; ddsd.dwWidth := CurMode.Width; ddsd.dwHeight := CurMode.Height; ddsd.ddsCaps.dwCaps := DDSCAPS_ZBUFFER or fZBufferMemType; ddsd.dwZBufferBitDepth := fZBufferBitDepth; if DDR( fDirectDraw.CreateSurface( ddsd, fZBuffer, nil ) ) = DD_OK then fBackBuffer.AddAttachedSurface( fZBuffer ); end; if DDR( fPrimaryBuffer.GetCaps( ddscaps ) ) = DD_OK then begin if ( CurMode.BPP = 8 ) and ( ( ddscaps.dwCaps and DDCAPS_PALETTE ) <> 0 ) then begin for i := 0 to 255 do begin fPaletteEntries[i].peRed := i;//random( 256 ); fPaletteEntries[i].peGreen := i;//random( 256 ); fPaletteEntries[i].peBlue := i;//random( 256 ); fPaletteEntries[i].peFlags := D3DPAL_FREE; //D3DPAL_READONLY; end; if DDR( fDirectDraw.CreatePalette( DDPCAPS_8BIT or DDPCAPS_INITIALIZE, @fPaletteEntries, Palette, nil ) ) = DD_OK then begin fBackBuffer.SetPalette( Palette ); fPrimaryBuffer.SetPalette( Palette ); end; end; end; // Create device Result := DDR( fDirect3D.CreateDevice( fDeviceGUID, fBackBuffer, fDevice ) ) = DD_OK; end; end; if not Result then DoneSurfaces; end; *) procedure TDirectDrawManager.InitDirectDraw; var DirectDraw : IDirectDraw; ddsd : TDirectSurfaceDesc; begin DirectDrawCreate( nil, DirectDraw, nil ); fDirectDraw := DirectDraw as IDirectDrawX; GetVideoModes; ddsd.dwSize := sizeof(ddsd); if DDR( fDirectDraw.GetDisplayMode( ddsd ) ) = DD_OK then with ddsd do fVideoMode := BestFitVideoMode( dwWidth, dwHeight, ddpfPixelFormat.dwRGBBitCount ); end; procedure TDirectDrawManager.FreeDirectDraw; begin fDirectDraw := nil; end; procedure TDirectDrawManager.InitSurfaces; begin // TODO 1 -oJRG : Finish InitSurfaces end; procedure TDirectDrawManager.FreeSurfaces; begin // TODO 1 -oJRG : Finish FreeSurfaces end; procedure ReallocVideoModes( var List : PVideoModes ); begin reallocmem( List, sizeof( TVideoModes ) + ( List.Count - 1 ) * sizeof( TVideoMode ) ); end; procedure DeleteVideoMode( const List : PVideoModes; Indx : integer ); var i : integer; begin with List^ do if Count > 0 then begin dec( Count ); if Indx > 0 then for i := Indx to Count - 1 do Modes[i] := Modes[i + 1]; end; end; procedure InsertVideoMode( const List : PVideoModes; Indx : integer; const Value : TVideoMode ); var i : integer; begin with List^ do begin inc( Count ); if Indx = -1 then Indx := Count - 1 else for i := Count - 1 downto Indx + 1 do Modes[i] := Modes[i - 1]; Modes[Indx] := Value; end; end; procedure AddVideoMode( const List : PVideoModes; const Value : TVideoMode ); begin InsertVideoMode( List, -1, Value ); end; procedure AddVideoModeEx( const List : PVideoModes; Width, Height, BitCount, Depth : dword ); var VideoMode : TVideoMode; begin with VideoMode do begin vmWidth := Width; vmHeight := Height; vmBitCount := BitCount; vmDepth := Depth; end; InsertVideoMode( List, -1, VideoMode ); end; function CopyVideoModes( const List : PVideoModes ) : PVideoModes; var ListSize : dword; begin with List^ do ListSize := sizeof( TVideoModes ) + ( List.Count - 1 ) * sizeof( TVideoMode ); getmem( Result, ListSize ); move( List^, Result^, ListSize ); end; procedure PackVideoModes( const List : PVideoModes ); var i, j : integer; begin with List^ do if Count > 0 then for i := Count - 1 downto 0 do if not Modes[i].vmEnabled then begin dec( Count ); if Count > 0 then for j := i to Count - 1 do Modes[j] := Modes[j + 1]; end; end; // Screen modes enumeration callback function DDEnumDisplayModesCallback( const ddsd : TDirectSurfaceDesc; lpContext : pointer ) : HRESULT; stdcall; const Bits : array[0..3] of dword = ( DDBD_8, DDBD_16, DDBD_24, DDBD_32 ); var DDrawMgr : TDirectDrawManager absolute lpContext; Depth : dword; BitDepthMultiplier : dword; VidRamNeeded : dword; begin BitDepthMultiplier := ddsd.ddpfPixelFormat.dwRGBBitCount div 8; Depth := Bits[BitDepthMultiplier - 1]; with DDrawMgr do begin if fUseHardware then begin VidRamNeeded := ( ( ddsd.dwWidth * ddsd.dwHeight ) * BitDepthMultiplier ) * 3; // TODO 1 -oJRG: Por que * 3?? if ( VidRamNeeded <= DDrawMgr.fVideoMemory ) //and ( ( fDeviceDesc.dwDeviceRenderBitDepth and Depth ) <> 0 ) then AddVideoModeEx( fVideoModes, ddsd.dwWidth, ddsd.dwHeight, BitDepthMultiplier * 8, Depth ); end else AddVideoModeEx( fVideoModes, ddsd.dwWidth, ddsd.dwHeight, BitDepthMultiplier * 8, Depth ); end; Result := DDENUMRET_OK; end; procedure TDirectDrawManager.GetVideoModes; begin getmem( fVideoModes, sizeof( TVideoModes ) + 255 * sizeof( TVideoMode ) ); // TODO 5 -oJRG: Use MAX_VIDEOMODES fVideoModes.Count := 0; fDirectDraw.EnumDisplayModes( 0, nil, Self, DDEnumDisplayModesCallback ); ReallocVideoModes( fVideoModes ); end; function TDirectDrawManager.GetVideoModeCaps( Value : dword ) : TVideoMode; begin assert( Value < fVideoModes.Count, 'Invalid video mode specified!!' ); Result := fVideoModes.Modes[Value]; end; function TDirectDrawManager.GetCurrentModeCaps : TVideoMode; begin Result := fVideoModes.Modes[fVideoMode]; end; procedure TDirectDrawManager.SetCurrentMode( Value : dword ); var Caps : TDirectDrawCaps; begin assert( fCooperativeFlags <> 0, 'You must first set cooperative level!!' ); fVideoMode := Value; FreeSurfaces; with fVideoModes.Modes[Value] do if DDR( fDirectDraw.SetDisplayMode( vmWidth, vmHeight, vmBitCount, 0, 0 ) ) = DD_OK then begin GetDriverCaps( Caps ); fVideoMemory := Caps.dwVidMemFree; InitSurfaces; // Check the minimum stretch and set the variable accordingly if Caps.dwCaps and DDCAPS_OVERLAYSTRETCH <> 0 then if Caps.dwMinOverlayStretch>1000 then fOverlayMinStretch := Caps.dwMinOverlayStretch else fOverlayMinStretch := 1000 else fOverlayMinStretch := 1000; // Grab any alignment restrictions and set the variables acordingly if Caps.dwCaps and DDCAPS_ALIGNSIZESRC <> 0 then begin fOverlaySrcSizeAlign := Caps.dwAlignSizeSrc; fOverlayDestSizeAlign := Caps.dwAlignSizeDest; end else begin fOverlaySrcSizeAlign := 0; fOverlayDestSizeAlign := 0; end; // Set the "destination position alignment" global so we won't have to // keep calling GetCaps() every time we move the overlay surface. if Caps.dwCaps and DDCAPS_ALIGNBOUNDARYDEST <> 0 then fOverlayXPosAlign := Caps.dwAlignBoundaryDest else fOverlayXPosAlign := 0; end else raise Exception.Create( 'Could not set video mode!!' ); //EDirectDrawVidMode.Create; end; function TDirectDrawManager.BestFitVideoMode( Width, Height, BitCount : dword ) : dword; var TmpList : PVideoModes; i : dword; begin Result := SearchVideoMode( Width, Height, BitCount, true ); if Result = idxNotFound // The exact match for this mode wasn't found then begin TmpList := CopyVideoModes( fVideoModes ); with TmpList^ do begin for i := 0 to Count - 1 do with Modes[i] do if (vmWidth < Width) or (vmHeight < Height) or (vmBitCount < BitCount) then vmEnabled := false; PackVideoModes( TmpList ); if Count > 0 then with Modes[0] do Result := SearchVideoMode( vmWidth, vmHeight, vmBitCount, true ) else Result := idxNotFound end; end; end; function TDirectDrawManager.SearchVideoMode( Width, Height, BitCount : dword; RequiresExactMatch : boolean ) : dword; var i : dword; Found : boolean; begin if RequiresExactMatch then with fVideoModes^ do begin i := 0; repeat with Modes[i] do Found := ( vmWidth = Width ) and ( vmHeight = Height ) and ( vmBitCount = BitCount ); if not Found then inc( i ); until Found or ( i >= Count ); if not Found then i := idxNotFound; end else i := BestFitVideoMode(Width, Height, BitCount); Result := i; end; procedure TDirectDrawManager.SetVideoMode( Width, Height, BitCount : dword; RequiresExactMatch : boolean ); begin SetCurrentMode(SearchVideoMode(Width, Height, BitCount, RequiresExactMatch)); end; procedure TDirectDrawManager.SetupVideoMode( Width, Height, BitCount : dword ); begin SetCooperativeLevel(clFullScreen); SetVideoMode(Width, Height, BitCount, true); end; procedure TDirectDrawManager.SetCooperativeLevel( Flags : dword ); begin if fCooperativeFlags <> Flags then if DDR( fDirectDraw.SetCooperativeLevel( Application.Handle, Flags ) ) = DD_OK then fCooperativeFlags := Flags else raise Exception.Create( 'Could not set cooperative level' ); //EDirectDrawCoopLevel.Create; end; end.
Const ginp='game.inp'; gout='game.out'; maxn=100010; Var n:longint; res:qword; a,b:array[0..maxn] of int64; Procedure Sort(l,r:longint; var d:array of int64); Var i,j:longint; t,tmp:int64; begin if l>=r then exit; i:=l; j:=r; t:=d[random(r-l+1)+l]; repeat while d[i]<t do inc(i); while d[j]>t do dec(j); if i<=j then begin tmp:=d[i]; d[i]:=d[j]; d[j]:=tmp; inc(i); dec(j); end; until i>j; sort(l,j,d); sort(i,r,d); end; Function Abs(x:int64):int64; Begin if x<0 then abs:=-x else abs:=x; End; Function Min(x,y:qword):qword; Begin if x<y then min:=x else min:=y; End; Procedure Answer(x,y:int64); Begin if ((x<0) and (y>0)) or ((x>0) and (y<0)) then res:=min(res,qword(abs(x+y))) else res:=min(res,qword(abs(x))+qword(abs(y))); End; Procedure Enter; Var i:longint; Begin readln(n); for i:=1 to n do read(a[i]); sort(1,n,a); readln; for i:=1 to n do read(b[i]); sort(1,n,b); End; Procedure Process; Var i,j:longint; Begin res:=high(qword); j:=n; for i:=1 to n do begin while (j>0) and (b[j]>=-a[i]) do dec(j); if j>0 then answer(a[i],b[j]); if j<n then answer(a[i],b[j+1]); end; write(res); End; Begin Assign(input,ginp); Assign(output,gout); Reset(input); Rewrite(output); Enter; Process; Close(input); Close(output); End.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpCollectionUtilities; {$I ..\..\Include\CryptoLib.inc} interface uses Generics.Collections, Classes, ClpAsn1Encodable, ClpIProxiedInterface; type TCollectionUtilities = class sealed(TObject) public class function ToStructuredString(c: TList<IAsn1Encodable>): String; static; end; implementation { TCollectionUtilities } class function TCollectionUtilities.ToStructuredString (c: TList<IAsn1Encodable>): String; var sl: TStringList; idx: Int32; begin sl := TStringList.Create(); sl.LineBreak := ''; try sl.Add('['); if (c.Count <> 0) then begin sl.Add((c[0] as TAsn1Encodable).ClassName); if c.Count > 1 then begin for idx := 1 to c.Count - 2 do begin sl.Add(', '); sl.Add((c[idx] as TAsn1Encodable).ClassName); end; end; end; sl.Add(']'); result := sl.Text; finally sl.Free; end; end; end.
unit Settings; interface uses SysUtils, Classes, Generics.Collections; type TProperties = TDictionary<string,string>; function Properties: TProperties; implementation var P: TProperties; function Properties: TProperties; begin if P = nil then P := TProperties.Create; Result := P; end; initialization P := nil; finalization FreeAndNil(P); end.
// 设计器gfm文件格式,这里是加密格式,至于为啥使用加密的,一 // 开始是做了外部gfm文件加载,防止项目发布使用了外部文件随意被修改,所以没有公开相关的 unit uFormDesignerFile; interface uses System.SysUtils, System.Classes, System.Zlib; type TFormResFile = class public const VERSION = 1; // GOVCLFORMZ HEADER: array[0..9] of byte = ($47, $4F, $56, $43, $4C, $46, $4F, $52, $4D, $5A); // TPF0 HEADERTPF0: array[0..3] of byte = ($54, $50, $46, $30); public class function Decrypt(AInStream: TStream; AOutStream: TStream): Boolean; class procedure XorStream(AStream: TMemoryStream); end; implementation uses Winapi.Windows, uComponents; { TFormResFile } class function TFormResFile.Decrypt(AInStream: TStream; AOutStream: TStream): Boolean; var LVer: Word; LMem, LZipMem: TMemoryStream; LHeader:array[0..High(HEADER)] of Byte; LBytes: TBytes; begin Result := False; AInStream.Position := 0; if AInStream.Size > Length(HEADER) + SizeOf(Word) then begin AInStream.Read(LHeader[0], Length(LHeader)); if CompareMem(@LHeader[0], @HEADER[0], Length(HEADER)) then begin AInStream.Read(LVer, SizeOf(Word)); if LVer >= VERSION then begin LMem := TMemoryStream.Create; try SetLength(LBytes, AInStream.Size - Length(HEADER) - SizeOf(Word)); AInStream.Read(LBytes, 0, Length(LBytes)); LMem.Write(LBytes, 0, Length(LBytes)); LMem.Position := 0; XorStream(LMem); LMem.Position := 0; LZipMem := TMemoryStream.Create; try ZDecompressStream(LMem, LZipMem); AOutStream.Position := 0; AOutStream.Write(LZipMem.Memory^, LZipMem.Size); AOutStream.Position := 0; Result := True; finally LZipMem.Free; end; finally LMem.Free; end; end; end else // 原生格式 if CompareMem(@LHeader[0], @HEADERTPF0[0], Length(HEADERTPF0)) then begin AInStream.Position := 0; AOutStream.Position := 0; AOutStream.CopyFrom(AInStream, AInStream.Size); AOutStream.Position := 0; Result := True; end; end; end; class procedure TFormResFile.XorStream(AStream: TMemoryStream); var EncodedBytes, ZipBytes:array of Byte; //编码字节 BytesLength: Integer; I, L:integer; const EncKey: array[0..15] of Byte = ( $EB, $D4, $93, $48, $97, $0E, $38, $5B, $89, $B8, $2F, $D2, $31, $11, $AD, $BC); begin AStream.Position := 0; BytesLength := AStream.Size; SetLength(EncodedBytes, BytesLength); SetLength(ZipBytes, BytesLength); AStream.Read(EncodedBytes[0], BytesLength); for I := 0 to BytesLength - 1 do begin L := I mod 16; ZipBytes[i] := EncodedBytes[i] xor EncKey[L]; end; AStream.Clear; //清除以前的流 AStream.Write(ZipBytes[0], BytesLength); //将异或后的字节集写入原流中 AStream.Position := 0; end; type TResForm = class public procedure OnFindComponentClass(Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); procedure OnAncestorNotFound(Reader: TReader; const ComponentName: string; ComponentClass: TPersistentClass; var Component: TComponent); procedure OnReaderError(Reader: TReader; const Message: string; var Handled: Boolean); procedure OnFindMethod(Reader: TReader; const MethodName: string; var Address: Pointer; var Error: Boolean); procedure OnFindMethodInstance(Reader: TReader; const MethodName: string; var AMethod: TMethod; var Error: Boolean); procedure LoadFromFile(const AFileName: string; ARoot: TComponent); procedure LoadFromStream(AStream: TStream; ARoot: TComponent); procedure LoadFromResourceName(AInstance: NativeUInt; AName: string; ARoot: TComponent); end; procedure TResForm.OnFindComponentClass(Reader: TReader; const AClassName: string; var ComponentClass: TComponentClass); var LB: TClass; begin if uClassLists.TryGetValue(AClassName, LB) then ComponentClass := TComponentClass(LB); end; procedure TResForm.OnAncestorNotFound(Reader: TReader; const ComponentName: string; ComponentClass: TPersistentClass; var Component: TComponent); begin end; procedure TResForm.OnReaderError(Reader: TReader; const Message: string; var Handled: Boolean); begin OutputDebugString(PChar('ReaderError: ' + Message)); Handled := True; // 跳过不显示错误。 end; procedure TResForm.OnFindMethod(Reader: TReader; const MethodName: string; var Address: Pointer; var Error: Boolean); begin OutputDebugString(PChar('FindMethod: ' + MethodName)); Error := False; end; procedure TResForm.OnFindMethodInstance(Reader: TReader; const MethodName: string; var AMethod: TMethod; var Error: Boolean); begin OutputDebugString(PChar('FindMethodInstance: ' + MethodName)); Error := False; end; procedure TResForm.LoadFromStream(AStream: TStream; ARoot: TComponent); var LR: TReader; LMem: TMemoryStream; begin if (AStream = nil) or (ARoot = nil) then Exit; AStream.Position := 0; LMem := TMemoryStream.Create; try TFormResFile.Decrypt(AStream, LMem); LR := TReader.Create(LMem, LMem.Size); try LR.OnFindComponentClass := OnFindComponentClass; LR.OnError := OnReaderError; LR.OnFindMethod := OnFindMethod; LR.OnAncestorNotFound := OnAncestorNotFound; LR.OnFindMethodInstance := OnFindMethodInstance; LR.ReadRootComponent(ARoot); ScaledForm(ARoot); finally LR.Free; end; finally LMem.Free; end; end; procedure TResForm.LoadFromFile(const AFileName: string; ARoot: TComponent); var LFileStream: TFileStream; begin LFileStream := TFileStream.Create(AFileName, fmOpenRead); try LoadFromStream(LFileStream, ARoot); finally LFileStream.Free; end; end; procedure TResForm.LoadFromResourceName(AInstance: NativeUInt; AName: string; ARoot: TComponent); var LRes: TResourceStream; begin LRes := TResourceStream.Create(AInstance, PChar(AName), RT_RCDATA); try LoadFromStream(LRes, ARoot); finally LRes.Free; end; end; //----------------------------------------------------------------------------- procedure ResFormLoadFromStream(AStream: TStream; ARoot: TComponent); stdcall; var LObj: TResForm; begin LObj := TResForm.Create; try try LObj.LoadFromStream(AStream, ARoot); except on E: Exception do OutputDebugString(PChar(E.Message)); end; finally LObj.Free; end; end; procedure ResFormLoadFromFile(AFileName: PChar; ARoot: TComponent); stdcall; var LObj: TResForm; begin LObj := TResForm.Create; try try LObj.LoadFromFile(AFileName, ARoot); except on E: Exception do OutputDebugString(PChar(E.Message)); end; finally LObj.Free; end; end; procedure ResFormLoadFromResourceName(AInstance: NativeUInt; AResName: PChar; ARoot: TComponent); stdcall; var LObj: TResForm; begin LObj := TResForm.Create; try try LObj.LoadFromResourceName(AInstance, AResName, ARoot); except on E: Exception do OutputDebugString(PChar(E.Message)); end; finally LObj.Free; end; end; exports ResFormLoadFromStream, ResFormLoadFromFile, ResFormLoadFromResourceName; end.
{* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Author: François PIETTE Creation: Mar 13, 2003 Description: Version: 1.00 EMail: francois.piette@overbyte.be http://www.overbyte.be Support: Unsupported code. Legal issues: Copyright (C) 2003 by François PIETTE Rue de Grady 24, 4053 Embourg, Belgium. Fax: +32-4-365.74.56 <francois.piette@overbyte.be> This software is provided 'as-is', without any express or implied warranty. In no event will the author 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. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. History: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} unit OverByteIcsWndControlTest1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, IniFiles, StdCtrls, ExtCtrls, OverbyteIcsWndControl, OverbyteIcsWSocket, OverbyteIcsWSocketS, OverbyteIcsHttpProt, OverbyteIcsFtpCli; type TDisplayEvent = procedure (Sender : TObject; const Msg : String) of object; TIcsThread = class(TThread) private FWSocket1 : TWSocket; procedure WSocket1SessionConnected(Sender: TObject; ErrCode: WORD); procedure Display(const Msg: String); public OnDisplay : TDisplayEvent; procedure Execute; override; procedure Terminate; end; TAppBaseForm = class(TForm) ToolsPanel: TPanel; DisplayMemo: TMemo; Button1: TButton; Button2: TButton; Connect1Button: TButton; Button4: TButton; Label1: TLabel; Free1Button: TButton; Connect2Button: TButton; Free2Button: TButton; Release1Button: TButton; HttpCliButton: TButton; WSocketServerButton: TButton; FtpCliButton: TButton; Thread1Button: TButton; StopThread1Button: TButton; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Connect1ButtonClick(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Free1ButtonClick(Sender: TObject); procedure Connect2ButtonClick(Sender: TObject); procedure Free2ButtonClick(Sender: TObject); procedure Release1ButtonClick(Sender: TObject); procedure HttpCliButtonClick(Sender: TObject); procedure WSocketServerButtonClick(Sender: TObject); procedure FtpCliButtonClick(Sender: TObject); procedure Thread1ButtonClick(Sender: TObject); procedure StopThread1ButtonClick(Sender: TObject); private FIniFileName : String; FInitialized : Boolean; FWndHandler : TIcsWndHandler; FCtrl1 : TIcsWndControl; FCtrl2 : TIcsWndControl; FCtrl3 : TIcsWndControl; FCtrl4 : TIcsWndControl; FWSocket1 : TWSocket; FWSocket2 : TWSocket; FThread1 : TIcsThread; procedure WSocket1SessionConnected(Sender: TObject; ErrCode: WORD); procedure ThreadDisplay(Sender: TObject; const Msg: String); public procedure Display(Msg : String); property IniFileName : String read FIniFileName write FIniFileName; end; var AppBaseForm: TAppBaseForm; GCritSect : TRTLCriticalSection; implementation {$R *.DFM} const SectionWindow = 'Window'; // Must be unique for each window KeyTop = 'Top'; KeyLeft = 'Left'; KeyWidth = 'Width'; KeyHeight = 'Height'; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppBaseForm.FormCreate(Sender: TObject); begin FIniFileName := LowerCase(ExtractFileName(Application.ExeName)); FIniFileName := Copy(FIniFileName, 1, Length(FIniFileName) - 3) + 'ini'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppBaseForm.FormShow(Sender: TObject); var IniFile : TIniFile; begin if not FInitialized then begin FInitialized := TRUE; IniFile := TIniFile.Create(FIniFileName); Width := IniFile.ReadInteger(SectionWindow, KeyWidth, Width); Height := IniFile.ReadInteger(SectionWindow, KeyHeight, Height); Top := IniFile.ReadInteger(SectionWindow, KeyTop, (Screen.Height - Height) div 2); Left := IniFile.ReadInteger(SectionWindow, KeyLeft, (Screen.Width - Width) div 2); IniFile.Destroy; DisplayMemo.Clear; end; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppBaseForm.FormClose(Sender: TObject; var Action: TCloseAction); var IniFile : TIniFile; begin IniFile := TIniFile.Create(FIniFileName); IniFile.WriteInteger(SectionWindow, KeyTop, Top); IniFile.WriteInteger(SectionWindow, KeyLeft, Left); IniFile.WriteInteger(SectionWindow, KeyWidth, Width); IniFile.WriteInteger(SectionWindow, KeyHeight, Height); IniFile.Destroy; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppBaseForm.Display(Msg : String); begin EnterCriticalSection(GCritSect); try DisplayMemo.Lines.BeginUpdate; try if DisplayMemo.Lines.Count > 200 then begin while DisplayMemo.Lines.Count > 200 do DisplayMemo.Lines.Delete(0); end; DisplayMemo.Lines.Add(Msg); finally DisplayMemo.Lines.EndUpdate; end; finally LeaveCriticalSection(GCritSect); end; SendMessage(DisplayMemo.Handle, EM_SCROLLCARET, 0, 0); end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppBaseForm.Button1Click(Sender: TObject); begin FWndHandler := TIcsWndHandler.Create; FWndHandler.MsgLow := WM_USER + 1; FCtrl1 := TIcsWndControl.Create(Self); FCtrl1.WndHandler := FWndHandler; FCtrl1.Name := 'FCtrl1'; FCtrl2 := TIcsWndControl.Create(Self); FCtrl2.WndHandler := FWndHandler; FCtrl2.Name := 'FCtrl2'; FCtrl3 := TIcsWndControl.Create(Self); FCtrl3.WndHandler := FWndHandler; FCtrl3.Name := 'FCtrl3'; FCtrl4 := TIcsWndControl.Create(Self); FCtrl4.WndHandler := FWndHandler; FCtrl4.Name := 'FCtrl4'; end; {* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *} procedure TAppBaseForm.Button2Click(Sender: TObject); begin FCtrl1.Release; end; procedure TAppBaseForm.Connect1ButtonClick(Sender: TObject); begin FreeAndNil(FWSocket1); FWSocket1 := TWSocket.Create(Self); FWSocket1.Name := 'WSocket1'; FWSocket1.Proto := 'tcp'; FWSocket1.Port := 'telnet'; FWSocket1.Addr := 'localhost'; FWSocket1.OnSessionConnected := WSocket1SessionConnected; FWSocket1.Connect; end; procedure TAppBaseForm.Free1ButtonClick(Sender: TObject); begin FreeAndNil(FWSocket1); end; procedure TAppBaseForm.Release1ButtonClick(Sender: TObject); begin if Assigned(FWSocket1) then begin FWSocket1.Release; FWSocket1 := nil; end; end; procedure TAppBaseForm.Connect2ButtonClick(Sender: TObject); begin FreeAndNil(FWSocket2); FWSocket2 := TWSocket.Create(Self); FWSocket2.Name := 'WSocket2'; FWSocket2.Proto := 'tcp'; FWSocket2.Port := 'telnet'; FWSocket2.Addr := 'localhost'; FWSocket2.OnSessionConnected := WSocket1SessionConnected; FWSocket2.Connect; end; procedure TAppBaseForm.Free2ButtonClick(Sender: TObject); begin FreeAndNil(FWSocket2); end; procedure TAppBaseForm.WSocket1SessionConnected( Sender : TObject; ErrCode : WORD); begin if ErrCode <> 0 then Display(TWSocket(Sender).Name + ': Unable to connect. Error #' + IntToStr(ErrCode)) else Display(TWSocket(Sender).Name + ': Connected'); end; procedure TAppBaseForm.Button4Click(Sender: TObject); var WSocketArray : array of TWSocket; I : Integer; Temp : TWSocket; begin Display('Allocating...'); Temp := nil; I := 0; while I < 65536 do begin if I >= Length(WSocketArray) then SetLength(WSocketArray, Length(WSocketArray) + 20000); try Temp := TWSocket.Create(Self); except break; end; WSocketArray[I] := Temp; Inc(I); Label1.caption := IntToStr(I); Label1.Update; end; Display('Destroying'); while I > 0 do begin Dec(I); FreeAndNil(WSocketArray[I]); end; Display('Done'); end; procedure TAppBaseForm.HttpCliButtonClick(Sender: TObject); var HttpCli1 : THttpCli; begin HttpCli1 := THttpCli.Create(Self); try HttpCli1.Url := 'http://www.overbyte.be'; HttpCli1.RcvdStream := TStringStream.Create(''); try HttpCli1.Get; if HttpCli1.StatusCode <> 200 then Label1.Caption := IntToStr(HttpCli1.StatusCode) + ' ' + HttpCli1.ReasonPhrase else begin Label1.Caption := 'Transfer réussi'; Display(TStringStream(HttpCli1.RcvdStream).DataString); end; finally HttpCli1.RcvdStream.Free; // Ferme le fichier HttpCli1.RcvdStream := nil; end; finally HttpCli1.Free; end; end; procedure TAppBaseForm.WSocketServerButtonClick(Sender: TObject); var WSocketServer1 : TWSocketServer; begin WSocketServer1 := TWSocketServer.Create(Self); try finally WSocketServer1.Free; end; end; procedure TAppBaseForm.FtpCliButtonClick(Sender: TObject); var FtpCli1 : TFtpClient; begin FtpCli1 := TFtpClient.Create(Self); try finally FtpCli1.Free; end; end; { TIcsThread } procedure TIcsThread.Execute; begin Display('Thread start'); FWSocket1 := TWSocket.Create(nil); try FWSocket1.Name := 'WSocket1'; FWSocket1.Proto := 'tcp'; FWSocket1.Port := 'telnet'; FWSocket1.Addr := 'localhost'; FWSocket1.OnSessionConnected := WSocket1SessionConnected; FWSocket1.Connect; FWSocket1.MessageLoop; finally FWSocket1.Free; end; Display('Thread stopped'); end; procedure TIcsThread.Display(const Msg : String); begin if Assigned(OnDisplay) then OnDisplay(Self, Msg); end; procedure TIcsThread.WSocket1SessionConnected( Sender : TObject; ErrCode : WORD); begin if ErrCode <> 0 then Display(TWSocket(Sender).Name + ': Unable to connect. Error #' + IntToStr(ErrCode)) else Display(TWSocket(Sender).Name + ': Connected'); end; procedure TAppBaseForm.ThreadDisplay( Sender: TObject; const Msg : String); begin Display(Msg); end; procedure TAppBaseForm.Thread1ButtonClick(Sender: TObject); begin FThread1 := TIcsThread.Create(TRUE); FThread1.OnDisplay := ThreadDisplay; FThread1.FreeOnTerminate := TRUE; FThread1.Resume; end; procedure TAppBaseForm.StopThread1ButtonClick(Sender: TObject); begin if Assigned(FThread1) then FThread1.Terminate; end; procedure TIcsThread.Terminate; begin PostMessage(FWSocket1.Handle, WM_QUIT, 0, 0); inherited Terminate; end; initialization InitializeCriticalSection(GCritSect); finalization DeleteCriticalSection(GCritSect); end.
unit uMsgDialog; interface type TuMessage = class private public class function MensagemConfirmacao(pMessage: String): Boolean; end; implementation uses FMX.DialogService, System.UITypes, FMX.Dialogs; { TuMessageDialog } class function TuMessage.MensagemConfirmacao(pMessage: String): Boolean; var lResultStr: Boolean; begin lResultStr := False; TDialogService.PreferredMode:=TDialogService.TPreferredMode.Platform; TDialogService.MessageDialog(pMessage, TMsgDlgType.mtConfirmation, FMX.Dialogs.mbYesNo, TMsgDlgBtn.mbNo, 0, procedure(const AResult: TModalResult) begin case AResult of mrYes: lResultStr:= True; mrNo: lResultStr:= False; end; end); Result:=lResultStr; end; end.
unit NtUtils.Processes.Memory; interface uses NtUtils.Exceptions, Ntapi.ntmmapi; // Allocate memory in a process function NtxAllocateMemoryProcess(hProcess: THandle; Size: NativeUInt; out Address: Pointer; Protection: Cardinal = PAGE_READWRITE): TNtxStatus; // Free memory in a process function NtxFreeMemoryProcess(hProcess: THandle; Address: Pointer; Size: NativeUInt): TNtxStatus; // Change memory protection function NtxProtectMemoryProcess(hProcess: THandle; Address: Pointer; Size: NativeUInt; Protection: Cardinal): TNtxStatus; // Read memory function NtxReadMemoryProcess(hProcess: THandle; Address: Pointer; Buffer: Pointer; BufferSize: NativeUInt): TNtxStatus; // Write memory function NtxWriteMemoryProcess(hProcess: THandle; Address: Pointer; Buffer: Pointer; BufferSize: NativeUInt): TNtxStatus; // Flush instruction cache function NtxFlushInstructionCache(hProcess: THandle; Address: Pointer; Size: NativeUInt): TNtxStatus; type NtxMemory = class // Query fixed-size information class function Query<T>(hProcess: THandle; Address: Pointer; InfoClass: TMemoryInformationClass; out Buffer: T): TNtxStatus; static; end; implementation uses Ntapi.ntpsapi; function NtxAllocateMemoryProcess(hProcess: THandle; Size: NativeUInt; out Address: Pointer; Protection: Cardinal): TNtxStatus; var RegionSize: NativeUInt; begin Address := nil; RegionSize := Size; Result.Location := 'NtAllocateVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType); Result.Status := NtAllocateVirtualMemory(hProcess, Address, 0, RegionSize, MEM_COMMIT, Protection); end; function NtxFreeMemoryProcess(hProcess: THandle; Address: Pointer; Size: NativeUInt): TNtxStatus; var BaseAddress: Pointer; RegionSize: NativeUInt; begin BaseAddress := Address; RegionSize := Size; Result.Location := 'NtFreeVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType); Result.Status := NtFreeVirtualMemory(hProcess, BaseAddress, RegionSize, MEM_RELEASE); end; function NtxProtectMemoryProcess(hProcess: THandle; Address: Pointer; Size: NativeUInt; Protection: Cardinal): TNtxStatus; var BaseAddress: Pointer; RegionSize: NativeUInt; OldProtection: Cardinal; begin BaseAddress := Address; RegionSize := Size; Result.Location := 'NtProtectVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_OPERATION, @ProcessAccessType); Result.Status := NtProtectVirtualMemory(hProcess, BaseAddress, RegionSize, Protection, OldProtection) end; function NtxReadMemoryProcess(hProcess: THandle; Address: Pointer; Buffer: Pointer; BufferSize: NativeUInt): TNtxStatus; begin Result.Location := 'NtReadVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_READ, @ProcessAccessType); Result.Status := NtReadVirtualMemory(hProcess, Address, Buffer, BufferSize, nil); end; function NtxWriteMemoryProcess(hProcess: THandle; Address: Pointer; Buffer: Pointer; BufferSize: NativeUInt): TNtxStatus; begin Result.Location := 'NtWriteVirtualMemory'; Result.LastCall.Expects(PROCESS_VM_WRITE, @ProcessAccessType); Result.Status := NtWriteVirtualMemory(hProcess, Address, Buffer, BufferSize, nil); end; function NtxFlushInstructionCache(hProcess: THandle; Address: Pointer; Size: NativeUInt): TNtxStatus; begin Result.Location := 'NtxFlushInstructionCacheProcess'; Result.LastCall.Expects(PROCESS_VM_WRITE, @ProcessAccessType); Result.Status := NtFlushInstructionCache(hProcess, Address, Size); end; class function NtxMemory.Query<T>(hProcess: THandle; Address: Pointer; InfoClass: TMemoryInformationClass; out Buffer: T): TNtxStatus; begin Result.Location := 'NtQueryVirtualMemory'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TMemoryInformationClass); Result.LastCall.Expects(PROCESS_QUERY_INFORMATION, @ProcessAccessType); Result.Status := NtQueryVirtualMemory(hProcess, Address, InfoClass, @Buffer, SizeOf(Buffer), nil); end; end.
{ Exercicio 81: Dada uma relação de 1000 números em graus Celsius, faça um algoritmo que imprima o seguinte relatório: Graus Fahrenheit Graus Celsius xxxxxx xxxxxx } { Solução em Portugol Algoritmo Exercicio 81; Tipo vet = vetor[1..1000] de real; Var celsius,farenheit: vet; i: inteiro; Inicio exiba("Programa conversor de temperaturas."); para i <- 1 até 1000 faça exiba("Digite a ",i,"ª temperatura em Celsius:"); leia(celsius[i]); farenheit[i] <- (9/5) * celsius[i] + 32; fimpara; exiba("Graus Farenheit "Graus Celsius"); para i <- 1 até 1000 faça exiba(farenheit[i]," ",celsius[i]); fimpara; Fim. } // Solução em Pascal Program Exercicio81; uses crt; Type vet = Array[1..1000] of real; Var celsius,farenheit: vet; i: integer; Begin writeln('Programa conversor de temperaturas.'); for i := 1 to 10 do Begin writeln('Digite a ',i,'ª temperatura em Celsius:'); readln(celsius[i]); farenheit[i] := (9/5) * celsius[i] + 32; End; writeln('Graus Farenheit Graus Celsius'); for i := 1 to 10 do // Não sei alinhar. writeln(farenheit[i]:0:2,' ',celsius[i]:0:2); repeat until keypressed; end.
{ Original file taken from "Windows 7 Controls for Delphi" by Daniel Wischnewski http://www.gumpi.com/Blog/2009/01/20/Alpha1OfWindows7ControlsForDelphi.aspx MPL licensed } { D2/D3 support and correct IID consts added by Martijn Laan for Inno Setup } { Inno Setup Copyright (C) 1997-2010 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. This unit provides the ITaskbarList3 interface for Windows 7 taskbar progress indicators. $jrsoftware: issrc/Components/dwTaskbarList.pas,v 1.5 2010/10/21 02:14:14 jr Exp $ } {$IFDEF VER90} {$DEFINE DELPHI2} {$ENDIF} unit dwTaskbarList; interface uses Windows {$IFDEF DELPHI2}, OLE2 {$ENDIF}; const CLSID_TaskbarList: TGUID = ( D1:$56FDF344; D2:$FD6D; D3:$11D0; D4:($95,$8A,$00,$60,$97,$C9,$A0,$90)); IID_TaskbarList: TGUID = ( D1:$56FDF342; D2:$FD6D; D3:$11D0; D4:($95,$8A,$00,$60,$97,$C9,$A0,$90)); IID_TaskbarList2: TGUID = ( D1:$602D4995; D2:$B13A; D3:$429B; D4:($A6,$6E,$19,$35,$E4,$4F,$43,$17)); IID_TaskbarList3: TGUID = ( D1:$EA1AFB91; D2:$9E28; D3:$4B86; D4:($90,$E9,$9E,$9F,$8A,$5E,$EF,$AF)); const THBF_ENABLED = $0000; THBF_DISABLED = $0001; THBF_DISMISSONCLICK = $0002; THBF_NOBACKGROUND = $0004; THBF_HIDDEN = $0008; const THB_BITMAP = $0001; THB_ICON = $0002; THB_TOOLTIP = $0004; THB_FLAGS = $0008; const THBN_CLICKED = $1800; const TBPF_NOPROGRESS = $00; TBPF_INDETERMINATE = $01; TBPF_NORMAL = $02; TBPF_ERROR = $04; TBPF_PAUSED = $08; const TBATF_USEMDITHUMBNAIL: DWORD = $00000001; TBATF_USEMDILIVEPREVIEW: DWORD = $00000002; const WM_DWMSENDICONICTHUMBNAIL = $0323; WM_DWMSENDICONICLIVEPREVIEWBITMAP = $0326; type TTipString = array[0..259] of WideChar; PTipString = ^TTipString; tagTHUMBBUTTON = packed record dwMask: DWORD; iId: UINT; iBitmap: UINT; hIcon: HICON; szTip: TTipString; dwFlags: DWORD; end; THUMBBUTTON = tagTHUMBBUTTON; THUMBBUTTONLIST = ^THUMBBUTTON; dwInteger64 = record Lo, Hi: Cardinal; end; type {$IFDEF DELPHI2} ITaskbarList = class(IUnknown) function HrInit: HRESULT; virtual; stdcall; abstract; function AddTab(hwnd: Cardinal): HRESULT; virtual; stdcall; abstract; function DeleteTab(hwnd: Cardinal): HRESULT; virtual; stdcall; abstract; function ActivateTab(hwnd: Cardinal): HRESULT; virtual; stdcall; abstract; function SetActiveAlt(hwnd: Cardinal): HRESULT; virtual; stdcall; abstract; end; ITaskbarList2 = class(ITaskbarList) function MarkFullscreenWindow(hwnd: Cardinal; fFullscreen: Bool): HRESULT; virtual; stdcall; abstract; end; ITaskbarList3 = class(ITaskbarList2) function SetProgressValue(hwnd: Cardinal; ullCompleted, ullTotal: dwInteger64): HRESULT; virtual; stdcall; abstract; function SetProgressState(hwnd: Cardinal; tbpFlags: DWORD): HRESULT; virtual; stdcall; abstract; function RegisterTab(hwndTab: Cardinal; hwndMDI: Cardinal): HRESULT; virtual; stdcall; abstract; function UnregisterTab(hwndTab: Cardinal): HRESULT; virtual; stdcall; abstract; function SetTabOrder(hwndTab: Cardinal; hwndInsertBefore: Cardinal): HRESULT; virtual; stdcall; abstract; function SetTabActive(hwndTab: Cardinal; hwndMDI: Cardinal; tbatFlags: DWORD): HRESULT; virtual; stdcall; abstract; function ThumbBarAddButtons(hwnd: Cardinal; cButtons: UINT; Button: THUMBBUTTONLIST): HRESULT; virtual; stdcall; abstract; function ThumbBarUpdateButtons(hwnd: Cardinal; cButtons: UINT; pButton: THUMBBUTTONLIST): HRESULT; virtual; stdcall; abstract; function ThumbBarSetImageList(hwnd: Cardinal; himl: Cardinal): HRESULT; virtual; stdcall; abstract; function SetOverlayIcon(hwnd: Cardinal; hIcon: HICON; pszDescription: LPCWSTR): HRESULT; virtual; stdcall; abstract; function SetThumbnailTooltip(hwnd: Cardinal; pszTip: LPCWSTR): HRESULT; virtual; stdcall; abstract; function SetThumbnailClip(hwnd: Cardinal; prcClip: PRect): HRESULT; virtual; stdcall; abstract; end; {$ELSE} ITaskbarList = interface ['{56FDF342-FD6D-11D0-958A-006097C9A090}'] function HrInit: HRESULT; stdcall; function AddTab(hwnd: Cardinal): HRESULT; stdcall; function DeleteTab(hwnd: Cardinal): HRESULT; stdcall; function ActivateTab(hwnd: Cardinal): HRESULT; stdcall; function SetActiveAlt(hwnd: Cardinal): HRESULT; stdcall; end; ITaskbarList2 = interface(ITaskbarList) ['{602D4995-B13A-429B-A66E-1935E44F4317}'] function MarkFullscreenWindow(hwnd: Cardinal; fFullscreen: Bool): HRESULT; stdcall; end; ITaskbarList3 = interface(ITaskbarList2) ['{EA1AFB91-9E28-4B86-90E9-9E9F8A5EEFAF}'] function SetProgressValue(hwnd: Cardinal; ullCompleted, ullTotal: dwInteger64): HRESULT; stdcall; function SetProgressState(hwnd: Cardinal; tbpFlags: DWORD): HRESULT; stdcall; function RegisterTab(hwndTab: Cardinal; hwndMDI: Cardinal): HRESULT; stdcall; function UnregisterTab(hwndTab: Cardinal): HRESULT; stdcall; function SetTabOrder(hwndTab: Cardinal; hwndInsertBefore: Cardinal): HRESULT; stdcall; function SetTabActive(hwndTab: Cardinal; hwndMDI: Cardinal; tbatFlags: DWORD): HRESULT; stdcall; function ThumbBarAddButtons(hwnd: Cardinal; cButtons: UINT; Button: THUMBBUTTONLIST): HRESULT; stdcall; function ThumbBarUpdateButtons(hwnd: Cardinal; cButtons: UINT; pButton: THUMBBUTTONLIST): HRESULT; stdcall; function ThumbBarSetImageList(hwnd: Cardinal; himl: Cardinal): HRESULT; stdcall; function SetOverlayIcon(hwnd: Cardinal; hIcon: HICON; pszDescription: LPCWSTR): HRESULT; stdcall; function SetThumbnailTooltip(hwnd: Cardinal; pszTip: LPCWSTR): HRESULT; stdcall; function SetThumbnailClip(hwnd: Cardinal; prcClip: PRect): HRESULT; stdcall; end; {$ENDIF} implementation end.
program enteros; type vector = array[1..100] of integer; function posicion(v:vector; x:integer):integer; begin if ((x >= 1) and (x <= 100)) then obtenerX := v[x] else obtenerX := -1; end; procedure intercambio(v:vector; x,y:integer); var aux :integer; begin aux := v[x]; v[x] := v[y]; v[y] := aux; end; function sumarVector(v:vector):integer; var suma :integer; begin for i:= 1 to 100 do suma := suma + v[i]; sumarVector := suma; end; function promedio(v:vector):real; begin promedio := sumarVector(v) / 100; end; function elementoMaximo(v:vector):integer; var maximo, pos :integer; begin maximo := 0; for i:=1 to 100 do if (v[i] >= maximo) then begin maximo := v[i]; pos := i; end; elementoMaximo := pos; end; function elementoMinimo(v:vector):integer; var minimo, pos :integer; begin minimo := 999; for i := 1 to 100 do if (v[i] <= minimo) then begin minimo := v[i]; pos := i; end; elementoMinimo := pos; end; var v:vector; i, numero, maxPos, minPos :integer; begin i := 1; repeat write('Ingrese un número: '); readln(numero); v[i] := numero; i := i + 1; until (numero = 0); maxPos := elementoMaximo(v); minPos := elementoMinimo(v); intercambio(v, maxPos, minPos); writeln( 'El elemento máximo ', v[minPos], ' que se encontraba en la posición ', minPos, ' fue intercambiado con el elemento ', v[maxPos], ' que se encontraba en la posición ', minPos, '.' ); end.
{$IfNDef m3RootStream_imp} // Модуль: "w:\common\components\rtl\Garant\m3\m3RootStream.imp.pas" // Стереотип: "Impurity" // Элемент модели: "m3RootStream" MUID: (54073B760302) // Имя типа: "_m3RootStream_" {$Define m3RootStream_imp} {$Include w:\common\components\rtl\Garant\m3\m3CustomHeaderStream.imp.pas} _m3RootStream_ = class(_m3CustomHeaderStream_) private f_Logger: Tl3Logger; protected procedure pm_SetLogger(aValue: Tl3Logger); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure DefaultInitAction; override; procedure DefaultDoneAction; override; function DoLockHeader: Boolean; override; function DoUnlockHeader: Boolean; override; public constructor Create(const aStream: IStream; aAccess: Integer); reintroduce; public property Logger: Tl3Logger read f_Logger write pm_SetLogger; end;//_m3RootStream_ {$Else m3RootStream_imp} {$IfNDef m3RootStream_imp_impl} {$Define m3RootStream_imp_impl} {$Include w:\common\components\rtl\Garant\m3\m3CustomHeaderStream.imp.pas} procedure _m3RootStream_.pm_SetLogger(aValue: Tl3Logger); //#UC START# *540F06CE030B_54073B760302set_var* //#UC END# *540F06CE030B_54073B760302set_var* begin //#UC START# *540F06CE030B_54073B760302set_impl* aValue.SetRefTo(f_Logger); //#UC END# *540F06CE030B_54073B760302set_impl* end;//_m3RootStream_.pm_SetLogger constructor _m3RootStream_.Create(const aStream: IStream; aAccess: Integer); //#UC START# *540F06F60288_54073B760302_var* //#UC END# *540F06F60288_54073B760302_var* begin //#UC START# *540F06F60288_54073B760302_impl* inherited; //#UC END# *540F06F60288_54073B760302_impl* end;//_m3RootStream_.Create procedure _m3RootStream_.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_54073B760302_var* //#UC END# *479731C50290_54073B760302_var* begin //#UC START# *479731C50290_54073B760302_impl* Logger := nil; inherited; //#UC END# *479731C50290_54073B760302_impl* end;//_m3RootStream_.Cleanup procedure _m3RootStream_.DefaultInitAction; //#UC START# *53FDFD1D0164_54073B760302_var* //#UC END# *53FDFD1D0164_54073B760302_var* begin //#UC START# *53FDFD1D0164_54073B760302_impl* // - ничего не делаем //#UC END# *53FDFD1D0164_54073B760302_impl* end;//_m3RootStream_.DefaultInitAction procedure _m3RootStream_.DefaultDoneAction; //#UC START# *53FDFD34034B_54073B760302_var* //#UC END# *53FDFD34034B_54073B760302_var* begin //#UC START# *53FDFD34034B_54073B760302_impl* // - ничего не делаем //#UC END# *53FDFD34034B_54073B760302_impl* end;//_m3RootStream_.DefaultDoneAction function _m3RootStream_.DoLockHeader: Boolean; //#UC START# *540F07260255_54073B760302_var* //#UC END# *540F07260255_54073B760302_var* begin //#UC START# *540F07260255_54073B760302_impl* Result := inherited DoLockHeader; {$IfDef m3LogRootStreamHeaderLocks} if Result then if (Logger <> nil) then Logger.ToLog('Header locked'); {$EndIf m3LogRootStreamHeaderLocks} //#UC END# *540F07260255_54073B760302_impl* end;//_m3RootStream_.DoLockHeader function _m3RootStream_.DoUnlockHeader: Boolean; //#UC START# *540F072F02B4_54073B760302_var* //#UC END# *540F072F02B4_54073B760302_var* begin //#UC START# *540F072F02B4_54073B760302_impl* Result := inherited DoUnlockHeader; {$IfDef m3LogRootStreamHeaderLocks} if Result then if (Logger <> nil) then Logger.ToLog('Header unlocked'); {$EndIf m3LogRootStreamHeaderLocks} //#UC END# *540F072F02B4_54073B760302_impl* end;//_m3RootStream_.DoUnlockHeader {$EndIf m3RootStream_imp_impl} {$EndIf m3RootStream_imp}
unit UTwitterDemo; interface uses FMX.Forms, FMX.TMSCloudURLShortener, FMX.TMSCloudBase, FMX.TMSCloudTwitter, FMX.Controls, FMX.Dialogs, FMX.Objects, FMX.StdCtrls, FMX.Edit, FMX.Grid, FMX.TMSCloudListView, FMX.Memo, FMX.TMSCloudImage, FMX.Layouts, FMX.ListBox, FMX.TabControl, System.Classes, FMX.Types, SysUtils, FMX.TMSCloudBaseFMX, FMX.TMSCloudCustomTwitter; type TForm1 = class(TForm) StyleBook1: TStyleBook; GroupBox1: TGroupBox; PageControl1: TTabControl; TabSheet1: TTabItem; TabSheet2: TTabItem; GroupBox2: TGroupBox; ListBox1: TListBox; ListBox2: TListBox; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; TMSFMXCloudCloudImage1: TTMSFMXCloudImage; GroupBox3: TGroupBox; Label2: TLabel; Memo1: TMemo; Button3: TButton; Button4: TButton; Button2: TButton; Button5: TButton; Panel1: TPanel; Button1: TButton; SpeedButton3: TSpeedButton; Label1: TLabel; Label3: TLabel; Label5: TLabel; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; OpenDialog1: TOpenDialog; TMSFMXCloudTwitter1: TTMSFMXCloudTwitter; CloudListView1: TTMSFMXCloudListView; Label4: TLabel; edURL: TEdit; btURL: TButton; Label10: TLabel; TweetSizeLbl: TLabel; Button7: TButton; TMSFMXCloudURLShortener1: TTMSFMXCloudURLShortener; btRemove: TButton; Image1: TImage; TMSFMXCloudCloudImage2: TTMSFMXCloudImage; Label11: TLabel; procedure Button1Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure TMSFMXCloudTwitter1ReceivedAccessToken(Sender: TObject); procedure FillFollowers; procedure FillFriends; procedure LoadTweets; procedure Button2Click(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure SpeedButton3Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure ToggleControls; procedure ProfileDetails(Profile: TTWitterProfile); procedure ListBox1Click(Sender: TObject); procedure ListBox2Click(Sender: TObject); procedure Button5Click(Sender: TObject); procedure Memo1Change(Sender: TObject); procedure btURLClick(Sender: TObject); procedure Button7Click(Sender: TObject); procedure btRemoveClick(Sender: TObject); procedure CloudListView1Change(Sender: TObject); private { Private declarations } public { Public declarations } Connected: boolean; procedure UpdateTweetSize; end; var Form1: TForm1; implementation {$R *.FMX} // PLEASE USE A VALID INCLUDE FILE THAT CONTAINS THE APPLICATION KEY & SECRET // FOR THE CLOUD STORAGE SERVICES YOU WANT TO USE // STRUCTURE OF THIS .INC FILE SHOULD BE // // const // TwitterAppkey = 'xxxxxxxxx'; // TwitterAppSecret = 'yyyyyyyy'; {$I APPIDS.INC} procedure TForm1.TMSFMXCloudTwitter1ReceivedAccessToken(Sender: TObject); begin TMSFMXCloudTwitter1.SaveTokens; TMSFMXCloudTwitter1.GetAccountInfo; Connected := true; ToggleControls; end; procedure TForm1.FillFollowers; var i: integer; begin TMSFMXCloudTwitter1.GetFollowers; TMSFMXCloudTwitter1.GetProfileListInfo(TMSFMXCloudTwitter1.Followers); ListBox1.Items.Clear; for i := 0 to TMSFMXCloudTwitter1.Followers.Count - 1 do begin listbox1.Items.AddObject(TMSFMXCloudTwitter1.Followers.Items[i].Name, TMSFMXCloudTwitter1.Followers.Items[i]); end; end; procedure TForm1.FillFriends; var i: integer; begin TMSFMXCloudTwitter1.GetFriends; TMSFMXCloudTwitter1.GetProfileListInfo(TMSFMXCloudTwitter1.Friends); ListBox2.Items.Clear; for i := 0 to TMSFMXCloudTwitter1.Friends.Count - 1 do begin listbox2.Items.AddObject(TMSFMXCloudTwitter1.Friends.Items[i].Name, TMSFMXCloudTwitter1.Friends.Items[i]); end; end; procedure TForm1.FormCreate(Sender: TObject); begin Connected := false; ToggleControls; Button5.Enabled := false; Button2.Enabled := false; UpdateTweetSize; CloudListView1.ColumnByIndex(1).Width := 500; end; procedure TForm1.ListBox1Click(Sender: TObject); begin ListBox2.ItemIndex := -1; ProfileDetails(ListBox1.Items.Objects[ListBox1.ItemIndex] as TTWitterProfile); end; procedure TForm1.ListBox2Click(Sender: TObject); begin ListBox1.ItemIndex := -1; ProfileDetails(ListBox2.Items.Objects[ListBox2.ItemIndex] as TTWitterProfile); end; procedure TForm1.LoadTweets; var i: integer; li: TListItem; TwitterStatus: TTWitterStatus; begin if CloudListView1.Items.Count = 0 then TMSFMXCloudTwitter1.GetStatuses(10) else begin TWitterStatus := CloudListView1.Items[CloudListView1.Items.Count - 1].Data; TMSFMXCloudTwitter1.GetStatuses(10, -1, TwitterStatus.ID); end; for i := CloudListView1.Items.Count to TMSFMXCloudTwitter1.Statuses.Count - 1 do begin li := CloudListView1.Items.Add; li.Text := TMSFMXCloudTwitter1.Statuses.Items[i].User.Name; li.SubItems.Add(TMSFMXCloudTwitter1.Statuses.Items[i].Text); li.SubItems.Add(FormatDateTime('dd/mm/yyyy hh:nn',TMSFMXCloudTwitter1.Statuses.Items[i].CreatedAt)); li.Data := TMSFMXCloudTwitter1.Statuses.Items[i]; end; Button5.Enabled := false; end; procedure TForm1.Memo1Change(Sender: TObject); begin UpdateTweetSize; end; procedure TForm1.ProfileDetails(Profile: TTWitterProfile); begin TMSFMXCloudCloudImage1.URL := Profile.ImageURL; Label1.Text := IntToStr(Profile.FriendsCount); Label3.Text := IntToStr(Profile.FollowersCount); Label4.Text := Profile.Description; Label5.Text := Profile.Location; Button2.Text := 'Message to "' + Profile.Name + '"'; Button2.Enabled := true; end; procedure TForm1.SpeedButton1Click(Sender: TObject); begin FillFollowers; end; procedure TForm1.SpeedButton2Click(Sender: TObject); begin FillFriends; end; procedure TForm1.SpeedButton3Click(Sender: TObject); begin CloudListView1.Items.Clear; LoadTweets; Button7.Enabled := true; end; procedure TForm1.Button1Click(Sender: TObject); var acc: boolean; begin TMSFMXCloudTwitter1.App.Key := TwitterAppkey; TMSFMXCloudTwitter1.App.Secret := TwitterAppSecret; if TMSFMXCloudTwitter1.App.Key <> '' then begin TMSFMXCloudTwitter1.PersistTokens.Key := ExtractFilePath(ParamStr(0)) + 'twitter.ini'; TMSFMXCloudTwitter1.PersistTokens.Section := 'tokens'; TMSFMXCloudTwitter1.LoadTokens; acc := TMSFMXCloudTwitter1.TestTokens; if not acc then begin TMSFMXCloudTwitter1.RefreshAccess; TMSFMXCloudTwitter1.DoAuth; TMSFMXCloudTwitter1.GetAccountInfo; end else begin connected := true; ToggleControls; end; end else ShowMessage('Please provide a valid application ID for the client component'); end; procedure TForm1.Button2Click(Sender: TObject); begin if ListBox1.ItemIndex > 0 then TMSFMXCloudTwitter1.DirectMessage(Memo1.Text, IntToStr((ListBox1.Items.Objects[ListBox1.ItemIndex] as TTWitterProfile).ID)) else if ListBox2.ItemIndex > 0 then TMSFMXCloudTwitter1.DirectMessage(Memo1.Text, IntToStr((ListBox2.Items.Objects[ListBox2.ItemIndex] as TTWitterProfile).ID)); end; procedure TForm1.Button3Click(Sender: TObject); var s:string; begin s := Memo1.Lines.Text; if length(s) > 140 then begin ShowMessage('Length of message exceeds Twitter limit of 140 chars'); end else TMSFMXCloudTwitter1.Tweet(s); end; procedure TForm1.Button4Click(Sender: TObject); begin if OpenDialog1.Execute then TMSFMXCloudTwitter1.TweetWithMedia(Memo1.Lines.Text, opendialog1.FileName); end; procedure TForm1.Button5Click(Sender: TObject); var Status: TTWitterStatus; begin if CloudListView1.ItemIndex > 0 then begin Status := CloudListView1.Items[CloudListView1.ItemIndex].Data; TMSFMXCloudTwitter1.ReTweet(Status.ID); end; end; procedure TForm1.Button7Click(Sender: TObject); begin LoadTweets; end; procedure TForm1.CloudListView1Change(Sender: TObject); var TwitterStatus: TTWitterStatus; begin if CloudListView1.ItemIndex >= 0 then begin Button5.Enabled := true; TwitterStatus := CloudListView1.Items[CloudListView1.ItemIndex].Data; TMSFMXCloudCloudImage2.URL := TwitterStatus.MediaURL; end; end; procedure TForm1.btRemoveClick(Sender: TObject); begin TMSFMXCloudTwitter1.ClearTokens; Connected := false; ToggleControls; end; procedure TForm1.btURLClick(Sender: TObject); begin Memo1.Lines.Add(TMSFMXCloudURLShortener1.ShortenURL(edURL.Text)); end; procedure TForm1.ToggleControls; begin GroupBox1.Enabled := Connected; GroupBox3.Enabled := Connected; SpeedButton1.Enabled := Connected; SpeedButton2.Enabled := Connected; SpeedButton3.Enabled := Connected; Button3.Enabled := Connected; Button4.Enabled := Connected; Button7.Enabled := Connected; Memo1.Enabled := Connected; edURL.Enabled := Connected; btURL.Enabled := Connected; btRemove.Enabled := Connected; Button1.Enabled := not Connected; end; procedure TForm1.UpdateTweetSize; begin TweetSizeLbl.Text := inttostr(length(memo1.Lines.Text))+' of 140 chars'; end; end.
Program Aufgabe5; {$codepage utf8} Uses sysutils; Var StrInput, StrKlein, StrGross: String; Begin Write('Bitte gib eine Zeichenkette ein: '); Read(StrInput); StrKlein := LowerCase(StrInput); StrGross := UpperCase(StrInput); WriteLn('Deine Zeichenkette: ', StrInput); WriteLn('Deine Zeichenkette in klein: ', StrKlein); WriteLn('Deine Zeichenkette in GROSS: ', StrGross); End.
unit SceneCustom; interface uses Scene, Engine, DGLE, DGLE_Types; type TSceneCustom = class(TScene) private pBackground: ITexture; public constructor Create(const FileName: AnsiString); destructor Destroy; override; procedure Render(); override; procedure Update(); override; end; implementation { TSceneCustom } constructor TSceneCustom.Create(const FileName: AnsiString); begin pBackground := nil; pResMan.Load(PAnsiChar('Resources\Sprites\Interface\' + FileName), IEngineBaseObject(pBackground), TEXTURE_LOAD_DEFAULT_2D); end; destructor TSceneCustom.Destroy; begin pBackground := nil; inherited; end; procedure TSceneCustom.Render; begin pRender2D.DrawTexture(pBackground, Point2(), Point2(SCREEN_WIDTH, SCREEN_HEIGHT)); end; procedure TSceneCustom.Update; begin end; end.
unit hypersports_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6809,nz80,main_engine,controls_engine,sn_76496,vlm_5030,gfx_engine, dac,rom_engine,pal_engine,konami_decrypt,sound_engine,qsnapshot,file_engine; function iniciar_hypersports:boolean; implementation const hypersports_rom:array[0..5] of tipo_roms=( (n:'c01';l:$2000;p:$4000;crc:$0c720eeb),(n:'c02';l:$2000;p:$6000;crc:$560258e0), (n:'c03';l:$2000;p:$8000;crc:$9b01c7e6),(n:'c04';l:$2000;p:$a000;crc:$10d7e9a2), (n:'c05';l:$2000;p:$c000;crc:$b105a8cd),(n:'c06';l:$2000;p:$e000;crc:$1a34a849)); hypersports_char:array[0..3] of tipo_roms=( (n:'c26';l:$2000;p:0;crc:$a6897eac),(n:'c24';l:$2000;p:$2000;crc:$5fb230c0), (n:'c22';l:$2000;p:$4000;crc:$ed9271a0),(n:'c20';l:$2000;p:$6000;crc:$183f4324)); hypersports_sprites:array[0..7] of tipo_roms=( (n:'c14';l:$2000;p:0;crc:$c72d63be),(n:'c13';l:$2000;p:$2000;crc:$76565608), (n:'c12';l:$2000;p:$4000;crc:$74d2cc69),(n:'c11';l:$2000;p:$6000;crc:$66cbcb4d), (n:'c18';l:$2000;p:$8000;crc:$ed25e669),(n:'c17';l:$2000;p:$a000;crc:$b145b39f), (n:'c16';l:$2000;p:$c000;crc:$d7ff9f2b),(n:'c15';l:$2000;p:$e000;crc:$f3d454e6)); hypersports_pal:array[0..2] of tipo_roms=( (n:'c03_c27.bin';l:$20;p:$0;crc:$bc8a5956),(n:'j12_c28.bin';l:$100;p:$20;crc:$2c891d59), (n:'a09_c29.bin';l:$100;p:$120;crc:$811a3f3f)); hypersports_vlm:tipo_roms=(n:'c08';l:$2000;p:$0;crc:$e8f8ea78); hypersports_snd:array[0..1] of tipo_roms=( (n:'c10';l:$2000;p:$0;crc:$3dc1a6ff),(n:'c09';l:$2000;p:$2000;crc:$9b525c3e)); hypersports_dip_a:array [0..1] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))),()); hypersports_dip_b:array [0..5] of def_dip=( (mask:$1;name:'After Last Event';number:2;dip:((dip_val:$1;dip_name:'Game Over'),(dip_val:$0;dip_name:'Game Continues'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$2;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$2;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Demo Sounds';number:2;dip:((dip_val:$4;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'World Records';number:2;dip:((dip_val:$8;dip_name:'Don''t Erase'),(dip_val:$0;dip_name:'Erase on Reset'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$f0;name:'Difficulty';number:16;dip:((dip_val:$f0;dip_name:'Easy 1'),(dip_val:$e0;dip_name:'Easy 2'),(dip_val:$d0;dip_name:'Easy 3'),(dip_val:$c0;dip_name:'Easy 4'),(dip_val:$b0;dip_name:'Normal 1'),(dip_val:$a0;dip_name:'Normal 2'),(dip_val:$90;dip_name:'Normal 3'),(dip_val:$80;dip_name:'Normal 4'),(dip_val:$70;dip_name:'Normal 5'),(dip_val:$60;dip_name:'Normal 6'),(dip_val:$50;dip_name:'Normal 7'),(dip_val:$40;dip_name:'Normal 8'),(dip_val:$30;dip_name:'Difficult 1'),(dip_val:$20;dip_name:'Difficult 2'),(dip_val:$10;dip_name:'Difficult 3'),(dip_val:$0;dip_name:'Difficult 4'))),()); var irq_ena:boolean; sound_latch,chip_latch:byte; mem_opcodes:array[0..$bfff] of byte; last_addr:word; procedure update_video_hypersports; var x,y,atrib:byte; f,nchar,color:word; scroll_x:array[0..$1f] of word; begin for f:=0 to $7ff do begin if gfx[0].buffer[f] then begin x:=f mod 64; y:=f div 64; atrib:=memoria[$2800+f]; nchar:=memoria[$2000+f]+((atrib and $80) shl 1)+((atrib and $40) shl 3); color:=(atrib and $f) shl 4; put_gfx_flip(x*8,y*8,nchar,color,1,0,(atrib and $10)<>0,(atrib and $20)<>0); gfx[0].buffer[f]:=false; end; end; for f:=0 to $1f do scroll_x[f]:=memoria[$10c0+(f*2)]+((memoria[$10c1+(f*2)] and 1) shl 8); scroll__x_part2(1,2,8,@scroll_x); for f:=$1f downto 0 do begin atrib:=memoria[$1000+(f*4)]; nchar:=memoria[$1002+(f*4)]+((atrib and $20) shl 3); y:=241-memoria[$1001+(f*4)]; x:=memoria[$1003+(f*4)]; color:=(atrib and $f) shl 4; put_gfx_sprite(nchar,color,(atrib and $40)=0,(atrib and $80)<>0,1); actualiza_gfx_sprite(x,y,2,1); end; actualiza_trozo_final(0,16,256,224,2); end; procedure eventos_hypersports; begin if event.arcade then begin if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.but2[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.but0[1] then marcade.in0:=(marcade.in0 and $bf) else marcade.in0:=(marcade.in0 or $40); if arcade_input.but1[1] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.but2[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); //System if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.coin[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.coin[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); end; end; procedure hypersports_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //sound z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; if f=239 then begin if irq_ena then m6809_0.change_irq(HOLD_LINE); update_video_hypersports; end; end; //General eventos_hypersports; video_sync; end; end; function hypersports_getbyte(direccion:word):byte; begin case direccion of $1000..$10ff,$2000..$3fff:hypersports_getbyte:=memoria[direccion]; $1600:hypersports_getbyte:=marcade.dswb; //DSW2 $1680:hypersports_getbyte:=marcade.in2; //SYSTEM $1681:hypersports_getbyte:=marcade.in0; $1682:hypersports_getbyte:=marcade.in1; //P3 y P4 $1683:hypersports_getbyte:=marcade.dswa; //DSW1 $4000..$ffff:if m6809_0.opcode then hypersports_getbyte:=mem_opcodes[direccion-$4000] else hypersports_getbyte:=memoria[direccion]; end; end; procedure hypersports_putbyte(direccion:word;valor:byte); begin case direccion of $1000..$10ff,$3000..$3fff:memoria[direccion]:=valor; $1480:main_screen.flip_main_screen:=(valor and $1)<>0; $1481:z80_0.change_irq(HOLD_LINE); $1487:irq_ena:=(valor<>0); $1500:sound_latch:=valor; $2000..$2fff:if memoria[direccion]<>valor then begin gfx[0].buffer[direccion and $7ff]:=true; memoria[direccion]:=valor; end; $4000..$ffff:; //ROM end; end; function hypersports_snd_getbyte(direccion:word):byte; begin case direccion of 0..$4fff:hypersports_snd_getbyte:=mem_snd[direccion]; $6000:hypersports_snd_getbyte:=sound_latch; $8000:hypersports_snd_getbyte:=(z80_0.totalt shr 10) and $f; end; end; procedure hypersports_snd_putbyte(direccion:word;valor:byte); var changes,offset:integer; begin case direccion of 0..$3fff:; //ROM $4000..$4fff:mem_snd[direccion]:=valor; $a000:vlm5030_0.data_w(valor); $c000..$dfff:begin offset:=direccion and $1fff; changes:=offset xor last_addr; // A4 VLM5030 ST pin */ if (changes and $10)<>0 then vlm5030_0.set_st((offset and $10) shr 4); // A5 VLM5030 RST pin */ if (changes and $20)<>0 then vlm5030_0.set_rst((offset and $20) shr 5); last_addr:=offset; end; $e000:dac_0.data8_w(valor); $e001:chip_latch:=valor; $e002:sn_76496_0.Write(chip_latch); end; end; procedure hypersports_sound_update; begin sn_76496_0.Update; dac_0.update; vlm5030_0.update; end; procedure hypersports_qsave(nombre:string); var data:pbyte; buffer:array[0..4] of byte; size:word; begin open_qsnapshot_save('hypersports'+nombre); getmem(data,250); //CPU size:=m6809_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=z80_0.save_snapshot(data); savedata_qsnapshot(data,size); //SND size:=sn_76496_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=vlm5030_0.save_snapshot(data); savedata_qsnapshot(data,size); size:=dac_0.save_snapshot(data); savedata_qsnapshot(data,size); //MEM savedata_com_qsnapshot(@memoria,$4000); savedata_com_qsnapshot(@mem_snd[$4000],$c000); //MISC buffer[0]:=byte(irq_ena); buffer[1]:=sound_latch; buffer[2]:=chip_latch; buffer[3]:=last_addr and $ff; buffer[4]:=last_addr shr 8; savedata_qsnapshot(@buffer,5); freemem(data); close_qsnapshot; end; procedure hypersports_qload(nombre:string); var data:pbyte; buffer:array[0..4] of byte; begin if not(open_qsnapshot_load('hypersports'+nombre)) then exit; getmem(data,250); //CPU loaddata_qsnapshot(data); m6809_0.load_snapshot(data); loaddata_qsnapshot(data); z80_0.load_snapshot(data); //SND loaddata_qsnapshot(data); sn_76496_0.load_snapshot(data); loaddata_qsnapshot(data); vlm5030_0.load_snapshot(data); loaddata_qsnapshot(data); dac_0.load_snapshot(data); //MEM loaddata_qsnapshot(@memoria); loaddata_qsnapshot(@mem_snd[$4000]); //MISC loaddata_qsnapshot(@buffer); irq_ena:=buffer[0]<>0; sound_latch:=buffer[1]; chip_latch:=buffer[2]; last_addr:=buffer[3] or (buffer[4] shl 8); freemem(data); close_qsnapshot; //end fillchar(gfx[0].buffer,$800,1); end; //Main procedure close_hypersports; begin write_file(Directory.Arcade_nvram+'hypersports.nv',@memoria[$3800],$800); end; procedure reset_hypersports; begin m6809_0.reset; z80_0.reset; vlm5030_0.reset; dac_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; irq_ena:=false; sound_latch:=0; chip_latch:=0; last_addr:=0; end; function iniciar_hypersports:boolean; var colores:tpaleta; f:word; longitud:integer; bit0,bit1,bit2:byte; memoria_temp:array[0..$ffff] of byte; rweights,gweights:array[0..3] of single; bweights:array[0..2] of single; const ps_x:array[0..15] of dword=(0, 1, 2, 3, 8*8+0, 8*8+1, 8*8+2, 8*8+3, 16*8+0, 16*8+1, 16*8+2, 16*8+3, 24*8+0, 24*8+1, 24*8+2, 24*8+3); ps_y:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 , 32*8, 33*8, 34*8, 35*8, 36*8, 37*8, 38*8, 39*8); resistances_rg:array[0..2] of integer=(1000,470,220); resistances_b:array[0..1] of integer=(470,220); begin llamadas_maquina.bucle_general:=hypersports_principal; llamadas_maquina.reset:=reset_hypersports; llamadas_maquina.close:=close_hypersports; llamadas_maquina.save_qsnap:=hypersports_qsave; llamadas_maquina.load_qsnap:=hypersports_qload; iniciar_hypersports:=false; iniciar_audio(false); screen_init(1,512,256); screen_mod_scroll(1,512,256,511,256,256,255); screen_init(2,256,256,false,true); iniciar_video(256,224); //Main CPU m6809_0:=cpu_m6809.Create(18432000 div 12,$100,TCPU_M6809); m6809_0.change_ram_calls(hypersports_getbyte,hypersports_putbyte); //Sound CPU z80_0:=cpu_z80.create(14318180 div 4,$100); z80_0.change_ram_calls(hypersports_snd_getbyte,hypersports_snd_putbyte); z80_0.init_sound(hypersports_sound_update); //Sound Chip sn_76496_0:=sn76496_chip.Create(14318180 div 8); vlm5030_0:=vlm5030_chip.Create(3579545,$2000,4); if not(roms_load(vlm5030_0.get_rom_addr,hypersports_vlm)) then exit; dac_0:=dac_chip.Create(0.80); if not(roms_load(@memoria,hypersports_rom)) then exit; konami1_decode(@memoria[$4000],@mem_opcodes[0],$c000); //NV ram if read_file_size(Directory.Arcade_nvram+'hypersports.nv',longitud) then read_file(Directory.Arcade_nvram+'hypersports.nv',@memoria[$3800],longitud); if not(roms_load(@mem_snd,hypersports_snd)) then exit; //convertir chars if not(roms_load(@memoria_temp,hypersports_char)) then exit; init_gfx(0,8,8,$400); gfx_set_desc_data(4,0,16*8,$4000*8+4,$4000*8+0,4,0); convert_gfx(0,0,@memoria_temp,@ps_x,@ps_y,false,false); //sprites if not(roms_load(@memoria_temp,hypersports_sprites)) then exit; init_gfx(1,16,16,$200); gfx[1].trans[0]:=true; gfx_set_desc_data(4,0,64*8,$8000*8+4,$8000*8+0,4,0); convert_gfx(1,0,@memoria_temp,@ps_x,@ps_y,false,false); //paleta if not(roms_load(@memoria_temp,hypersports_pal)) then exit; compute_resistor_weights(0, 255, -1.0, 3,@resistances_rg,@rweights,1000,0, 3,@resistances_rg,@gweights,1000,0, 2,@resistances_b,@bweights,1000,0); for f:=0 to $1f do begin // red component */ bit0:=(memoria_temp[f] shr 0) and $01; bit1:=(memoria_temp[f] shr 1) and $01; bit2:=(memoria_temp[f] shr 2) and $01; colores[f].r:=combine_3_weights(@rweights[0], bit0, bit1, bit2); // green component */ bit0:=(memoria_temp[f] shr 3) and $01; bit1:=(memoria_temp[f] shr 4) and $01; bit2:=(memoria_temp[f] shr 5) and $01; colores[f].g:=combine_3_weights(@gweights[0], bit0, bit1, bit2); // blue component */ bit0:=(memoria_temp[f] shr 6) and $01; bit1:=(memoria_temp[f] shr 7) and $01; colores[f].b:=combine_2_weights(@bweights[0], bit0, bit1); end; set_pal(colores,$20); for f:=0 to $ff do begin gfx[0].colores[f]:=(memoria_temp[$120+f] and $f) or $10; gfx[1].colores[f]:=memoria_temp[$20+f] and $f; end; //DIP marcade.dswa:=$ff; marcade.dswb:=$49; marcade.dswa_val:=@hypersports_dip_a; marcade.dswb_val:=@hypersports_dip_b; //final reset_hypersports; iniciar_hypersports:=true; end; end.
unit FindUnit.IncluderHandlerInc; interface uses Classes, Generics.Collections, SimpleParser.Lexer.Types; type TIncItem = record Loaded: Boolean; Content: string; FilePath: string; end; TIncludeHandlerInc = class(TInterfacedObject, IIncludeHandler) private FIncList: TObjectDictionary<string, TIncItem>; FPossiblePaths: TStringList; procedure GenerateIncList; public constructor Create(const PossiblePaths: string); destructor Destroy; override; procedure Process; function GetIncludeFileContent(const FileName: string): string; end; implementation uses FindUnit.Utils, SysUtils, Log4Pascal; { TIncludeHandlerInc } constructor TIncludeHandlerInc.Create(const PossiblePaths: string); begin FIncList := TObjectDictionary<string, TIncItem>.Create{([doOwnsValues])}; FPossiblePaths := TStringList.Create; FPossiblePaths.Text := PossiblePaths; end; destructor TIncludeHandlerInc.Destroy; begin FPossiblePaths.Free; FIncList.Free; inherited; end; procedure TIncludeHandlerInc.GenerateIncList; var I: Integer; ItemPath: string; Return: TStringList; iRet: Integer; FileName: string; FilePath: string; IncItem: TIncItem; begin for I := 0 to FPossiblePaths.Count -1 do begin ItemPath := IncludeTrailingPathDelimiter(FPossiblePaths[i]); try if not DirectoryExists(ItemPath) then Continue; Return := GetAllFilesFromPath(ItemPath, '*.inc'); for iRet := 0 to Return.Count -1 do begin FilePath := Return[iRet]; FileName := UpperCase(ExtractFileName(FilePath)); IncItem.Loaded := False; IncItem.Content := ''; IncItem.FilePath := FilePath; FIncList.AddOrSetValue(FileName, IncItem); end; Return.Free except on e: exception do Logger.Error('TIncludeHandlerInc.GenerateIncList[%s]: %s', [ItemPath, e.Message]); end; end; end; function TIncludeHandlerInc.GetIncludeFileContent(const FileName: string): string; var ItemInc: TIncItem; FileInc: TStringList; begin Result := ''; if not FIncList.TryGetValue(UpperCase(FileName), ItemInc) then Exit; if ItemInc.Loaded then begin Result := ItemInc.Content; Exit; end; FileInc := TStringList.Create; try try FileInc.LoadFromFile(ItemInc.FilePath); ItemInc.Content := FileInc.Text; ItemInc.Loaded := True; except Result := ''; end; Result := ItemInc.Content; finally FileInc.Free; end; end; procedure TIncludeHandlerInc.Process; begin GenerateIncList; end; end.
unit UniqueRandom; interface Uses SysUtils; type ENoMoreNumbers = Exception; // alzaimar TUniqueRandomSequenceGenerator = class private FCounter: Integer; FNumberList: array of Integer; public constructor Create(aStart, aEnde: Integer); procedure BuildSequence(aStart, aEnde: Integer); function GetNextNumber: Integer; function TotalCount: Integer; function RemainingCount: Integer; end; // sx2008 TUniqueRandomSequenceGenerator2 = class private FStart, FEnde : integer; FNumberList: array of Integer; procedure AddToList(Value:integer); function CountNumbersBetween(a,b:integer):integer; public constructor Create(aStart, aEnde: Integer); procedure BuildSequence(aStart, aEnde: Integer); function GetNextNumber: Integer; function TotalCount: Integer; function RemainingCount: Integer; end; implementation { TUniqueRandomGenerator } constructor TUniqueRandomSequenceGenerator.Create(aStart, aEnde: Integer); begin BuildSequence(aStart, aEnde); end; procedure TUniqueRandomSequenceGenerator.BuildSequence(aStart, aEnde: Integer); var i, j, tmp: Integer; begin SetLength(FNumberList, aEnde - aStart + 1); // Zahlenliste erzeugen for i := 0 to TotalCount - 1 do FNumberList[i] := aStart + i; // Mischen nach Fisher-Yates for i := Low(FNumberList) to High(FNumberList) do begin j := i + Random(Length(FNumberList) - i); tmp := FNumberList[j]; FNumberList[j] := FNumberList[i]; FNumberList[i] := tmp; end; FCounter := 0; end; function TUniqueRandomSequenceGenerator.GetNextNumber: Integer; begin // if FCounter < High(FNumberList) then begin if FCounter <= High(FNumberList) then begin Result := FNumberList[FCounter]; Inc(FCounter); end else raise ENoMoreNumbers.Create('No more numbers'); end; function TUniqueRandomSequenceGenerator.RemainingCount: Integer; begin Result := TotalCount - FCounter; end; function TUniqueRandomSequenceGenerator.TotalCount: Integer; begin Result := Length(FNumberList); end; { TUniqueRandomSequenceGenerator2 } procedure TUniqueRandomSequenceGenerator2.AddToList(Value: integer); var len : integer; begin len := Length(FNumberList); SetLength(FNumberList, len+1); FNumberlist[len] := Value; end; procedure TUniqueRandomSequenceGenerator2.BuildSequence(aStart, aEnde: Integer); begin FStart := aStart; FEnde := aEnde; FNumberlist := nil; end; function TUniqueRandomSequenceGenerator2.CountNumbersBetween(a, b: integer): integer; var i : Integer; begin Result := 0; for i := 0 to Length(FNumberList) - 1 do begin if (FNumberlist[i] > a) and (FNumberlist[i] <= b) then begin Inc(Result); end; end; end; constructor TUniqueRandomSequenceGenerator2.Create(aStart, aEnde: Integer); begin BuildSequence(aStart, aEnde); end; function TUniqueRandomSequenceGenerator2.GetNextNumber: Integer; var i, t, s : integer; endflag : boolean; begin if RemainingCount = 0 then raise ENoMoreNumbers.Create('no more numbers'); // hole neue Zufallszahl Result := FStart + random(RemainingCount); // Ablauf: // alle Zahlen zwischen Startwert und Zufallszahl zählen // um diese Anzahl erhöhen // solange wiederholen, bis keine Zahlen mehr übersprungen wurden s := FStart - 1; repeat t := CountNumbersBetween(s, Result); s := Result; Inc(Result, t); until t = 0; AddToList(Result); end; function TUniqueRandomSequenceGenerator2.RemainingCount: Integer; begin Result := TotalCount - Length(FNumberList); end; function TUniqueRandomSequenceGenerator2.TotalCount: Integer; begin result := FEnde - FStart + 1; end; end.
unit untDriver; interface uses // VCL Classes, SysUtils, Forms, ActiveX, ComObj, // This DrvFRLib_TLB, Fields; type { TDriver } TDriver = class(TDrvFR) public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ReadTableDef(ATableNumber, ARowNumber, AFieldNumber, ADefValue: Integer): Integer; end; procedure FreeDriver; function Driver: TDriver; implementation uses Windows, fmuMain; function GetParamsFileName: string; begin Result := ChangeFileExt(Application.ExeName, '.dat'); end; var FDriver: TDriver = nil; procedure FreeDriver; begin FDriver.Free; FDriver := nil; end; function Driver: TDriver; begin if FDriver = nil then try FDriver := TDriver.Create(nil); except on E: Exception do begin E.Message := 'Ошибка создания объекта драйвера: ' + E.Message; raise; end; end; Result := FDriver; end; function DriverIsNil: Boolean; begin Result := FDriver = nil; end; { TDriver } constructor TDriver.Create(AOwner: TComponent); begin inherited Create(AOwner); end; destructor TDriver.Destroy; begin inherited Destroy; end; function TDriver.ReadTableDef(ATableNumber, ARowNumber, AFieldNumber, ADefValue: Integer): Integer; begin RowNumber := ARowNumber; TableNumber := ATableNumber; FieldNumber := AFieldNumber; if ReadTable = 0 then Result := ValueOfFieldInteger else Result := ADefValue; end; end.
unit iterator_lib; interface uses classes,contnrs; type TCleanableStack=class(TStack) public procedure Clear; end; TIterator=class(TComponent) private fclassname: TClass; function get_component(i: Integer): TComponent; public constructor Create(owner: TComponent;classname: TClass); reintroduce; overload; function count: Integer; property Component[i: Integer]: TComponent read get_component; default; end; TAbstractDocumentRawIterator=class(TComponent) private fStack: TCleanableStack; //номер посещ. компонента fObjStack: TCleanableStack; //текущий узел, по которому "итерируем" fRecursive: boolean; procedure SetRecursive(value: boolean); public constructor Create(owner: TComponent); override; destructor Destroy; override; // constructor Create(owner: TComponent; intfname: TGUID); overload; procedure rawFirst(var iterator); virtual; procedure rawNext(var iterator); virtual; property recursive: Boolean read frecursive write SetRecursive default true; end; TAbstractDocumentClassIterator=class(TAbstractDocumentRawIterator) private fclassname: TClass; public constructor Create(owner: Tcomponent; aClassName: TClass); reintroduce; procedure First(var iterator); procedure Next(var iterator); end; TAbstractDocumentInterfaceIterator=class(TAbstractDocumentRawIterator) private finterface: TGUID; public constructor Create(owner: TComponent; aInterface: TGUID); reintroduce; procedure First(var Iterator); procedure Next(var iterator); end; implementation uses command_class_lib; (* TCleanableStack *) procedure TCleanableStack.clear; begin List.Clear; end; (* TIterator *) //эту хреновину я давно писал, но где-то применяется, лучше пока не удалять constructor TIterator.Create(owner: TComponent;classname: TClass); begin inherited Create(owner); fclassname:=classname; SetSubComponent(true); end; function TIterator.count: Integer; var i,j: Integer; begin j:=0; for i:=0 to owner.ComponentCount-1 do begin if owner.Components[i] is fclassname then inc(j); end; result:=j; end; function TIterator.get_component(i: Integer): TComponent; var j,k: Integer; // comp: TComponent; begin j:=-1; k:=-1; while k<i do begin inc(j); if owner.Components[j] is fclassname then inc(k); end; Result:=owner.Components[j]; end; (* TAbstractDocumentRawIterator *) constructor TAbstractDocumentRawIterator.Create(owner: TComponent); begin inherited Create(owner); SetSubComponent(true); fstack:=TCleanableStack.Create; fObjStack:=TCleanableStack.Create; fRecursive:=true; end; destructor TAbstractDocumentRawIterator.Destroy; begin fstack.Free; fObjStack.Free; inherited Destroy; end; procedure TAbstractDocumentRawIterator.SetRecursive(value: boolean); var iterator: Pointer; begin fRecursive:=value; rawFirst(iterator); //чтобы очистить стеки с прошлого раза //иначе могут быть очень странные глюки end; procedure TAbstractDocumentRawIterator.rawFirst(var iterator); begin fstack.Clear; fObjStack.Clear; if Assigned(Owner) then begin fObjStack.Push(Owner); fStack.Push(Pointer(0)); end; rawNext(iterator); end; procedure TAbstractDocumentRawIterator.rawNext(var iterator); var i: Integer; c: TComponent; begin while fObjStack.Count>0 do begin c:=TComponent(fObjStack.Pop); //извлекаем текущий компонент и номер его "ребенка" //на котором остановились for i:=Integer(fStack.Pop) to c.ComponentCount-1 do //цикл понадобился if (not (c.Components[i] is TCommandTree)) and //лишь из-за "неугодных" (not (c.Components[i] is TAbstractToolAction)) then begin //ветвей Pointer(iterator):=c.Components[i]; //есть еще непосещенный компонент fObjStack.Push(c); //вернули на место fStack.Push(Pointer(i+1)); //ведь i мы уже посетили if Recursive then begin fObjStack.Push(c.Components[i]); //а у него возможно дети fStack.Push(Pointer(0)); end; Exit; end; //если мы дошли до этого места, значит, не нашлось у нашего компонента больше "детей" //tail recursion тут можно, или тупо цикл // rawNext(iterator); end; Pointer(iterator):=nil //конец итераций end; (* TAbstractDocumentClassIterator *) constructor TAbstractDocumentClassIterator.Create(owner: TComponent; aClassName: TClass); begin inherited Create(owner); fClassName:=aClassName; end; procedure TAbstractDocumentClassIterator.First(var iterator); begin rawFirst(iterator); while Assigned(Pointer(iterator)) and (not (TObject(iterator) is fClassName)) do rawNext(iterator); end; procedure TAbstractDocumentClassIterator.Next(var Iterator); begin rawNext(iterator); while Assigned(Pointer(iterator)) and (not (TObject(iterator) is fClassName)) do rawNext(iterator); end; (* TAbstractDocumentInterfaceIterator *) constructor TAbstractDocumentInterfaceIterator.Create(owner: TComponent; aInterface: TGUID); begin inherited Create(owner); fInterface:=aInterface; end; procedure TAbstractDocumentInterfaceIterator.First(var iterator); var intf: IInterface; begin intf:=nil; rawFirst(iterator); while Assigned(Pointer(iterator)) and (not TObject(iterator).GetInterface(fInterface,intf)) do rawNext(iterator); Pointer(iterator):=Pointer(intf); end; procedure TAbstractDocumentInterfaceIterator.Next(var iterator); var intf: IInterface; begin intf:=nil; rawNext(iterator); while Assigned(Pointer(iterator)) and (not TObject(iterator).GetInterface(fInterface,intf)) do rawNext(iterator); Pointer(iterator):=Pointer(intf); end; end.
unit InsFilterNodeWordsPack; // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Filters\InsFilterNodeWordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "InsFilterNodeWordsPack" MUID: (53B533CE01B6) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3IntfUses //#UC START# *53B533CE01B6intf_uses* //#UC END# *53B533CE01B6intf_uses* ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts)} uses l3ImplUses , nsFiltersInterfaces , tfwPropertyLike , tfwScriptingInterfaces , TypInfo , tfwTypeInfo , tfwAxiomaticsResNameGetter , FiltersUnit , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *53B533CE01B6impl_uses* //#UC END# *53B533CE01B6impl_uses* ; type TkwFilterNodeAutoApplied = {final} class(TtfwPropertyLike) {* Слово скрипта FilterNode:AutoApplied } private function AutoApplied(const aCtx: TtfwContext; const aFilterNode: InsFilterNode): Boolean; {* Реализация слова скрипта FilterNode:AutoApplied } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFilterNodeAutoApplied TkwFilterNodeIsUsed = {final} class(TtfwPropertyLike) {* Слово скрипта FilterNode:IsUsed } private function IsUsed(const aCtx: TtfwContext; const aFilterNode: InsFilterNode): Boolean; {* Реализация слова скрипта FilterNode:IsUsed } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFilterNodeIsUsed TkwFilterNodeIsDeleted = {final} class(TtfwPropertyLike) {* Слово скрипта FilterNode:IsDeleted } private function IsDeleted(const aCtx: TtfwContext; const aFilterNode: InsFilterNode): Boolean; {* Реализация слова скрипта FilterNode:IsDeleted } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFilterNodeIsDeleted TkwFilterNodeIsChangeable = {final} class(TtfwPropertyLike) {* Слово скрипта FilterNode:IsChangeable } private function IsChangeable(const aCtx: TtfwContext; const aFilterNode: InsFilterNode): Boolean; {* Реализация слова скрипта FilterNode:IsChangeable } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwFilterNodeIsChangeable TInsFilterNodeWordsPackResNameGetter = {final} class(TtfwAxiomaticsResNameGetter) {* Регистрация скриптованой аксиоматики } public class function ResName: AnsiString; override; end;//TInsFilterNodeWordsPackResNameGetter function TkwFilterNodeAutoApplied.AutoApplied(const aCtx: TtfwContext; const aFilterNode: InsFilterNode): Boolean; {* Реализация слова скрипта FilterNode:AutoApplied } begin Result := aFilterNode.AutoApplied; end;//TkwFilterNodeAutoApplied.AutoApplied class function TkwFilterNodeAutoApplied.GetWordNameForRegister: AnsiString; begin Result := 'FilterNode:AutoApplied'; end;//TkwFilterNodeAutoApplied.GetWordNameForRegister function TkwFilterNodeAutoApplied.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwFilterNodeAutoApplied.GetResultTypeInfo function TkwFilterNodeAutoApplied.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFilterNodeAutoApplied.GetAllParamsCount function TkwFilterNodeAutoApplied.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(InsFilterNode)]); end;//TkwFilterNodeAutoApplied.ParamsTypes procedure TkwFilterNodeAutoApplied.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); var l_FilterNode: InsFilterNode; begin try l_FilterNode := InsFilterNode(aCtx.rEngine.PopIntf(InsFilterNode)); except on E: Exception do begin RunnerError('Ошибка при получении параметра FilterNode: InsFilterNode : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except l_FilterNode.AutoApplied := aValue.AsBoolean; end;//TkwFilterNodeAutoApplied.SetValuePrim procedure TkwFilterNodeAutoApplied.DoDoIt(const aCtx: TtfwContext); var l_aFilterNode: InsFilterNode; begin try l_aFilterNode := InsFilterNode(aCtx.rEngine.PopIntf(InsFilterNode)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFilterNode: InsFilterNode : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(AutoApplied(aCtx, l_aFilterNode)); end;//TkwFilterNodeAutoApplied.DoDoIt function TkwFilterNodeIsUsed.IsUsed(const aCtx: TtfwContext; const aFilterNode: InsFilterNode): Boolean; {* Реализация слова скрипта FilterNode:IsUsed } //#UC START# *54F9DEB20204_54F9DEB20204_4991887A031F_Word_var* //#UC END# *54F9DEB20204_54F9DEB20204_4991887A031F_Word_var* begin //#UC START# *54F9DEB20204_54F9DEB20204_4991887A031F_Word_impl* Result := aFilterNode.UsedStatus; //#UC END# *54F9DEB20204_54F9DEB20204_4991887A031F_Word_impl* end;//TkwFilterNodeIsUsed.IsUsed class function TkwFilterNodeIsUsed.GetWordNameForRegister: AnsiString; begin Result := 'FilterNode:IsUsed'; end;//TkwFilterNodeIsUsed.GetWordNameForRegister function TkwFilterNodeIsUsed.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwFilterNodeIsUsed.GetResultTypeInfo function TkwFilterNodeIsUsed.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFilterNodeIsUsed.GetAllParamsCount function TkwFilterNodeIsUsed.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(InsFilterNode)]); end;//TkwFilterNodeIsUsed.ParamsTypes procedure TkwFilterNodeIsUsed.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsUsed', aCtx); end;//TkwFilterNodeIsUsed.SetValuePrim procedure TkwFilterNodeIsUsed.DoDoIt(const aCtx: TtfwContext); var l_aFilterNode: InsFilterNode; begin try l_aFilterNode := InsFilterNode(aCtx.rEngine.PopIntf(InsFilterNode)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFilterNode: InsFilterNode : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsUsed(aCtx, l_aFilterNode)); end;//TkwFilterNodeIsUsed.DoDoIt function TkwFilterNodeIsDeleted.IsDeleted(const aCtx: TtfwContext; const aFilterNode: InsFilterNode): Boolean; {* Реализация слова скрипта FilterNode:IsDeleted } //#UC START# *54F9DEC402CD_54F9DEC402CD_4991887A031F_Word_var* //#UC END# *54F9DEC402CD_54F9DEC402CD_4991887A031F_Word_var* begin //#UC START# *54F9DEC402CD_54F9DEC402CD_4991887A031F_Word_impl* Result := aFilterNode.DeletedStatus; //#UC END# *54F9DEC402CD_54F9DEC402CD_4991887A031F_Word_impl* end;//TkwFilterNodeIsDeleted.IsDeleted class function TkwFilterNodeIsDeleted.GetWordNameForRegister: AnsiString; begin Result := 'FilterNode:IsDeleted'; end;//TkwFilterNodeIsDeleted.GetWordNameForRegister function TkwFilterNodeIsDeleted.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwFilterNodeIsDeleted.GetResultTypeInfo function TkwFilterNodeIsDeleted.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFilterNodeIsDeleted.GetAllParamsCount function TkwFilterNodeIsDeleted.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(InsFilterNode)]); end;//TkwFilterNodeIsDeleted.ParamsTypes procedure TkwFilterNodeIsDeleted.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsDeleted', aCtx); end;//TkwFilterNodeIsDeleted.SetValuePrim procedure TkwFilterNodeIsDeleted.DoDoIt(const aCtx: TtfwContext); var l_aFilterNode: InsFilterNode; begin try l_aFilterNode := InsFilterNode(aCtx.rEngine.PopIntf(InsFilterNode)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFilterNode: InsFilterNode : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsDeleted(aCtx, l_aFilterNode)); end;//TkwFilterNodeIsDeleted.DoDoIt function TkwFilterNodeIsChangeable.IsChangeable(const aCtx: TtfwContext; const aFilterNode: InsFilterNode): Boolean; {* Реализация слова скрипта FilterNode:IsChangeable } //#UC START# *54F9DEE200D2_54F9DEE200D2_4991887A031F_Word_var* var l_F: IFilterFromQuery; //#UC END# *54F9DEE200D2_54F9DEE200D2_4991887A031F_Word_var* begin //#UC START# *54F9DEE200D2_54F9DEE200D2_4991887A031F_Word_impl* Supports(aFilterNode, IFilterFromQuery, l_F); RunnerAssert(Assigned(l_F), 'Что-то не так с фильтром.', aCtx); try Result := l_F.GetChangeable; finally l_F := nil; end;//try..finally //#UC END# *54F9DEE200D2_54F9DEE200D2_4991887A031F_Word_impl* end;//TkwFilterNodeIsChangeable.IsChangeable class function TkwFilterNodeIsChangeable.GetWordNameForRegister: AnsiString; begin Result := 'FilterNode:IsChangeable'; end;//TkwFilterNodeIsChangeable.GetWordNameForRegister function TkwFilterNodeIsChangeable.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(Boolean); end;//TkwFilterNodeIsChangeable.GetResultTypeInfo function TkwFilterNodeIsChangeable.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwFilterNodeIsChangeable.GetAllParamsCount function TkwFilterNodeIsChangeable.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(InsFilterNode)]); end;//TkwFilterNodeIsChangeable.ParamsTypes procedure TkwFilterNodeIsChangeable.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству IsChangeable', aCtx); end;//TkwFilterNodeIsChangeable.SetValuePrim procedure TkwFilterNodeIsChangeable.DoDoIt(const aCtx: TtfwContext); var l_aFilterNode: InsFilterNode; begin try l_aFilterNode := InsFilterNode(aCtx.rEngine.PopIntf(InsFilterNode)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aFilterNode: InsFilterNode : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushBool(IsChangeable(aCtx, l_aFilterNode)); end;//TkwFilterNodeIsChangeable.DoDoIt class function TInsFilterNodeWordsPackResNameGetter.ResName: AnsiString; begin Result := 'InsFilterNodeWordsPack'; end;//TInsFilterNodeWordsPackResNameGetter.ResName {$R InsFilterNodeWordsPack.res} initialization TkwFilterNodeAutoApplied.RegisterInEngine; {* Регистрация FilterNode_AutoApplied } TkwFilterNodeIsUsed.RegisterInEngine; {* Регистрация FilterNode_IsUsed } TkwFilterNodeIsDeleted.RegisterInEngine; {* Регистрация FilterNode_IsDeleted } TkwFilterNodeIsChangeable.RegisterInEngine; {* Регистрация FilterNode_IsChangeable } TInsFilterNodeWordsPackResNameGetter.Register; {* Регистрация скриптованой аксиоматики } TtfwTypeRegistrator.RegisterType(TypeInfo(InsFilterNode)); {* Регистрация типа InsFilterNode } TtfwTypeRegistrator.RegisterType(TypeInfo(Boolean)); {* Регистрация типа Boolean } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) end.
unit fmuWorkTotalizer; interface uses // VCL Windows, ComCtrls, StdCtrls, Controls, Classes, SysUtils, Forms, ExtCtrls, Buttons, // This untPages, untUtil, untDriver, untTypes; type { TfmWorkTotalizer } TfmWorkTotalizer = class(TPage) Memo: TMemo; btnRead: TBitBtn; btnStop: TButton; btnReadAll: TButton; procedure btnReadClick(Sender: TObject); procedure btnStopClick(Sender: TObject); procedure btnReadAllClick(Sender: TObject); private FStopFlag: Boolean; procedure AddRegisters; procedure AddAllRegisters; procedure AddCaption(S: string); procedure Terminate(const Message: string); procedure AddOperationRegisters(S: string; L: Integer; H: Integer); end; implementation {$R *.DFM} { TfmWorkTotalizer } procedure TfmWorkTotalizer.AddCaption(S: string); begin Memo.Lines.Add(''); Memo.Lines.Add(S); Memo.Lines.Add(' ' + StringOfChar('-', 54)); end; procedure TfmWorkTotalizer.AddOperationRegisters(S: string; L: Integer; H: Integer); var i: Integer; RegisterName: string; begin AddCaption(S); for i := L to H do begin if FStopFlag then Terminate('<Прервано пользователем>'); Driver.RegisterNumber := i; if Driver.GetOperationReg <> 0 then begin Terminate(Format('<Прервано в результате ошибки: %d %s>', [Driver.ResultCode, Driver.ResultCodeDescription])); end; if i in [0..High(OperationRegisterName)] then RegisterName := OperationRegisterName[i] else RegisterName := '<Описание недоступно>'; Memo.Lines.Add(Format(' %3d.%-45s : %s', [i+1, RegisterName, CurrToStr(Driver.ContentsOfOperationRegister)])); Application.ProcessMessages; end; end; procedure TfmWorkTotalizer.AddRegisters; begin AddOperationRegisters(' Количество:', $00, $93); AddOperationRegisters(' Номер:', $94, $97); AddOperationRegisters(' Сквозной номер', $98, $98); AddOperationRegisters(' Количество:', $99, $9A); AddOperationRegisters(' Номер:', $9B, $9C); AddOperationRegisters(' Количество:', $9D, $9D); AddOperationRegisters(' Номер:', $9E, $A5); AddOperationRegisters(' Количество:', $A6, $A8); AddOperationRegisters(' Количество отчетов по:', $A9, $B0); AddOperationRegisters(' Количество :', $B1, $B1); AddOperationRegisters(' Номер отчета по :', $B2, $B2); AddOperationRegisters(' Количество аннулированных чеков по :', $B3, $B6); AddOperationRegisters(' Количество нефискальных документов :', $B7, $B8); AddOperationRegisters(' Сквозной номер :', $B9, $B9); end; procedure TfmWorkTotalizer.AddAllRegisters; var i: Integer; begin for i := 0 to 255 do begin if FStopFlag then Terminate('<Прервано пользователем>'); Driver.RegisterNumber := i; if Driver.GetOperationReg <> 0 then begin Terminate(Format('<Прервано в результате ошибки: %d %s>', [Driver.ResultCode, Driver.ResultCodeDescription])); end; Memo.Lines.Add(Format(' %3d.%-48s : %s', [i+1, Driver.NameOperationReg, CurrToStr(Driver.ContentsOfOperationRegister)])); Application.ProcessMessages; end; end; procedure TfmWorkTotalizer.btnReadClick(Sender: TObject); begin EnableButtons(False); btnStop.Enabled := True; try try FStopFlag := False; Memo.Clear; AddCaption(' ОПЕРАЦИОННЫЕ РЕГИСТРЫ:'); AddRegisters; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; except on E:EAbort do Memo.Lines.Add(E.Message); end; finally EnableButtons(True); btnStop.Enabled := False; end; end; procedure TfmWorkTotalizer.btnStopClick(Sender: TObject); begin FStopFlag := True; end; procedure TfmWorkTotalizer.btnReadAllClick(Sender: TObject); begin EnableButtons(False); btnStop.Enabled := True; try try FStopFlag := False; Memo.Clear; AddCaption(' ОПЕРАЦИОННЫЕ РЕГИСТРЫ:'); AddAllRegisters; // Прокручиваем Memo на начало Memo.SelStart := 0; Memo.SelLength := 0; except on EAbort do Memo.Lines.Add('<Прервано пользователем>'); end; finally EnableButtons(True); btnStop.Enabled := False; end; end; procedure TfmWorkTotalizer.Terminate(const Message: string); begin raise EAbort.Create(Message); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerOctetString; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, Math, Generics.Collections, ClpCryptoLibTypes, ClpIProxiedInterface, ClpIAsn1Sequence, ClpAsn1Tags, ClpAsn1OutputStream, ClpBerOutputStream, ClpDerOutputStream, ClpIBerOctetString, ClpIDerOctetString, ClpDerOctetString; type TBerOctetString = class(TDerOctetString, IBerOctetString) strict private const MaxLength = Int32(1000); var Focts: TList<IDerOctetString>; function GenerateOcts(): TList<IDerOctetString>; class function ToBytes(octs: TList<IDerOctetString>) : TCryptoLibByteArray; static; public /// <inheritdoc /> /// <param name="str">The octets making up the octet string.</param> constructor Create(const str: TCryptoLibByteArray); overload; constructor Create(const octets: TList<IDerOctetString>); overload; constructor Create(const obj: IAsn1Object); overload; constructor Create(const obj: IAsn1Encodable); overload; destructor Destroy(); override; function GetOctets(): TCryptoLibByteArray; override; /// <summary> /// return the DER octets that make up this string. /// </summary> function GetEnumerable: TCryptoLibGenericArray<IDerOctetString>; virtual; procedure Encode(const derOut: TStream); override; class function FromSequence(const seq: IAsn1Sequence) : IBerOctetString; static; end; implementation { TBerOctetString } constructor TBerOctetString.Create(const octets: TList<IDerOctetString>); begin Inherited Create(ToBytes(octets)); Focts := octets; end; constructor TBerOctetString.Create(const str: TCryptoLibByteArray); begin Inherited Create(str); end; constructor TBerOctetString.Create(const obj: IAsn1Encodable); begin Inherited Create(obj.ToAsn1Object()); end; destructor TBerOctetString.Destroy; begin Focts.Free; inherited Destroy; end; constructor TBerOctetString.Create(const obj: IAsn1Object); begin Inherited Create(obj); end; procedure TBerOctetString.Encode(const derOut: TStream); var oct: IDerOctetString; LListIDerOctetString: TCryptoLibGenericArray<IDerOctetString>; begin if ((derOut is TAsn1OutputStream) or (derOut is TBerOutputStream)) then begin (derOut as TDerOutputStream).WriteByte(TAsn1Tags.Constructed or TAsn1Tags.OctetString); (derOut as TDerOutputStream).WriteByte($80); // // write out the octet array // LListIDerOctetString := Self.GetEnumerable; for oct in LListIDerOctetString do begin (derOut as TDerOutputStream).WriteObject(oct); end; (derOut as TDerOutputStream).WriteByte($00); (derOut as TDerOutputStream).WriteByte($00); end else begin (Inherited Encode(derOut)); end; end; class function TBerOctetString.FromSequence(const seq: IAsn1Sequence) : IBerOctetString; var v: TList<IDerOctetString>; obj: IAsn1Encodable; LListAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>; begin v := TList<IDerOctetString>.Create(); LListAsn1Encodable := seq.GetEnumerable; for obj in LListAsn1Encodable do begin v.Add(obj as IDerOctetString); end; result := TBerOctetString.Create(v); end; function TBerOctetString.GenerateOcts: TList<IDerOctetString>; var i, endPoint: Int32; nStr: TCryptoLibByteArray; begin result := TList<IDerOctetString>.Create(); i := 0; while i < System.Length(str) do begin endPoint := Min(System.Length(str), i + MaxLength); System.SetLength(nStr, endPoint - i); System.Move(str[i], nStr[0], System.Length(nStr) * System.SizeOf(Byte)); result.Add(TDerOctetString.Create(nStr) as IDerOctetString); System.Inc(i, MaxLength); end; end; function TBerOctetString.GetEnumerable: TCryptoLibGenericArray<IDerOctetString>; var LList: TList<IDerOctetString>; begin if (Focts = Nil) then begin LList := GenerateOcts(); try result := LList.ToArray; Exit; finally LList.Free; end; end; result := Focts.ToArray; end; function TBerOctetString.GetOctets: TCryptoLibByteArray; begin result := str; end; class function TBerOctetString.ToBytes(octs: TList<IDerOctetString>) : TCryptoLibByteArray; var bOut: TMemoryStream; o: IDerOctetString; octets: TCryptoLibByteArray; begin bOut := TMemoryStream.Create(); try for o in octs do begin octets := o.GetOctets(); bOut.Write(octets[0], System.Length(octets)); end; System.SetLength(result, bOut.Size); bOut.Position := 0; bOut.Read(result[0], bOut.Size); finally bOut.Free; end; end; end.
unit mainform; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TMain = class(TForm) BPMList: TListBox; BPMCounterBox: TGroupBox; TimeLabel: TLabel; BPMLabel: TLabel; BeatCountLabel: TLabel; BPM: TEdit; BeatCount: TEdit; Beat: TButton; Reset: TButton; Time: TEdit; Time_: TEdit; TimeTimer: TTimer; AutoStop: TTimer; InformationBox: TGroupBox; InfoTitle: TEdit; InfoTitleLabel: TLabel; InfoArtist: TEdit; InfoArtistLabel: TLabel; Timer: TTimer; InfoBPM: TEdit; InfoBPMLabel: TLabel; Save: TButton; procedure TimeTimerTimer(Sender: TObject); procedure BeatClick(Sender: TObject); procedure CarryOn; procedure AutoStopTimer(Sender: TObject); procedure ResetClick(Sender: TObject); procedure TimerTimer(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure SaveClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Main: TMain; implementation {$R *.DFM} procedure TMain.TimeTimerTimer(Sender: TObject); var x, y, ans: double; errcode : integer; begin Val(Time_.Text, x, errcode ); Val('1000', y, errcode ); if errcode <> 0 then else begin ans := x + y; Time_.Text := FloatToStr(ans); Time.Text := FloatToStr(ans / 1000); end; end; procedure TMain.BeatClick(Sender: TObject); begin if Beat.Tag = 0 then Beat.Tag := 1 else begin TimeTimer.Enabled := True; CarryOn; end; end; procedure TMain.CarryOn; var a, x, y, z, answer: double; errcode : integer; begin AutoStop.Enabled := False; Val(BeatCount.Text, x, errcode ); Val(BPM.Text, y, errcode ); Val(Time.Text, z, errcode ); if errcode <> 0 then else begin BeatCount.Text := FloatToStr(x + 1); answer := x * 60 / z; a := y + answer; BPM.Text := FloatToStr(a / 2); end; AutoStop.Enabled := True; end; procedure TMain.AutoStopTimer(Sender: TObject); begin Beat.Enabled := False; TimeTimer.Enabled := False; end; procedure TMain.ResetClick(Sender: TObject); begin Time.Text := ''; Time_.Text := ''; BPM.Text := ''; BeatCount.Text := ''; InfoTitle.Text := ''; InfoArtist.Text := ''; TimeTimer.Enabled := False; AutoStop.Enabled := False; Beat.Enabled := True; Beat.SetFocus; end; procedure TMain.TimerTimer(Sender: TObject); begin InfoBPM.Text := BPM.Text; end; procedure TMain.FormCreate(Sender: TObject); begin BPMList.Items.LoadFromFile('bpm.list'); end; procedure TMain.FormClose(Sender: TObject; var Action: TCloseAction); begin BPMList.Items.SaveToFile('bpm.list'); end; procedure TMain.SaveClick(Sender: TObject); begin BPMList.Items.Add(InfoBPM.Text + ' ' + InfoTitle.Text + ' - ' + InfoArtist.Text); end; end.
(* _______________________________________________________________________ | | | CONFIDENTIAL MATERIALS | | | | These materials include confidential and valuable trade secrets owned | | by JP Software Inc. or its suppliers, and are provided to you under | | the terms of a non-disclosure agreement. These materials may not be | | transmitted or divulged to others or received, viewed, or used by | | others in any way. All source code, source code and technical | | documentation, and related notes, are unpublished materials, except | | to the extent that they are in part legally available as published | | works from other suppliers, and use of a copyright notice below does | | not imply publication of these materials. | | | | This notice must remain as part of these materials and must not be | | removed. | | | | Unpublished work, Copyright 1990 - 1999, JP Software Inc., All Rights | | Reserved. | |_______________________________________________________________________| *) { HELPCFG Version 7.01 Copyright 1990 - 1999, JP Software Inc., P.O. Box 1470, E. Arlington, MA 02174. All Rights Reserved. Originally written by Ross Neilson Wentworth, all rights sold to JP Software Inc. } Program HelpConfig; Uses TpCrt, TpString, Sinst, EdiTools; Const {$IFDEF GERMAN} Title1 = '4DOS 7.01 (D) HILFESYSTEM'; {$ELSE} Title1 = '4DOS 7.01 Help System'; {$ENDIF} {$IFDEF GERMAN} Title2 = 'Farbauswahl'; {$ELSE} {$IFDEF UK} Title2 = 'Colour Configuration'; {$ELSE} Title2 = 'Color Configuration'; {$ENDIF} {$ENDIF} Copyright = 'Copyright 1988 - 1999, JP Software Inc.'; ProgName = '4HELP.EXE'; Type ColorType = (FrAttr, TeAttr, HeAttr, XsAttr, XrAttr, SpAtt1, SpAtt2, SpAtt3, PWAttr, PIAttr, BBAttr); AttributeArray = Array[ColorType] of Byte; SInstallRec = Record ColorAttr : AttributeArray; MonoAttr : AttributeArray; GoodColorCard : Boolean; End; Const SidString : String[18] = '4DH701 PATCH HERE:'; Var SaveBreak : Boolean; {Saved state of CheckBreak} WP : WindowPtr; ScreenDefaults : SInstallRec; Param : string; ForceMono : boolean; ScreenOfs : longint; {$I ediscrn.inc} Begin SaveBreak := CheckBreak; CheckBreak := False; Param := StUpCase(ParamStr(1)); {check for /M or /BW} ForceMono := ((Pos('/M', Param) <> 0) or (Pos('/BW', Param) <> 0)); SinstGetScreenMode(ForceMono); Initialize(ProgName, ''); {Search for screen installation ID string} ScreenOfs := FindString(SIDstring, ScreenDefaults, SizeOf(ScreenDefaults)); if ScreenOfs = 0 then {$IFDEF GERMAN} HaltError('Incorrect version of '+ProgName); { HaltError('Bildschirmkennung nicht gefunden in '+ProgName);} {$ELSE} HaltError('Incorrect version of '+ProgName); {$ENDIF} ClrScr; Window(38, 1, 76, 7); FastCenter(Title1, 2, $0F); FastCenter(Title2, 3, $0F); FastCenter(Copyright, 5, $07); ScreenInstall(ForceMono, ScreenOfs); CleanUp; CheckBreak := SaveBreak; End. 
unit fmuCustomerBonus; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, AtrPages, ToolCtrlsEh, GridsEh, DBGridEh, ComCtrls, ToolWin, DB, FIBDataSet, pFIBDataSet, ActnList, DBGridEhToolCtrls, Buttons, ExtCtrls, DBAxisGridsEh, System.Actions, PrjConst, EhLibVCL, System.UITypes, DBGridEhGrouping, DynVarsEh, FIBDatabase, pFIBDatabase; type TapgCustomerBonus = class(TA4onPage) dsBonus: TpFIBDataSet; srcBonus: TDataSource; dbgGrid: TDBGridEh; ActListCustomers: TActionList; actAdd: TAction; actDel: TAction; pnlButtons: TPanel; btnDel1: TSpeedButton; btnAdd1: TSpeedButton; trRead: TpFIBTransaction; trWrite: TpFIBTransaction; procedure actEditExecute(Sender: TObject); procedure actDelExecute(Sender: TObject); procedure dsBonusAfterOpen(DataSet: TDataSet); public procedure InitForm; override; procedure OpenData; override; procedure CloseData; override; class function GetPageName: string; override; end; implementation uses DM, MAIN; {$R *.dfm} class function TapgCustomerBonus.GetPageName: string; begin Result := rsBonuses; end; procedure TapgCustomerBonus.InitForm; var FullAccess: Boolean; canEdit: Boolean; begin FullAccess := (dmMain.AllowedAction(rght_Customer_full)); // ПОЛНЫЙ ДОСТУП canEdit := (dmMain.AllowedAction(rght_Customer_Bonus)); // ИЗМЕНЕНИЕ actAdd.Visible := canEdit or FullAccess; // actEdit.Visible := canEdit or FullAccess; actDel.Visible := canEdit or FullAccess; pnlButtons.Visible := canEdit or FullAccess; dsBonus.DataSource := FDataSource; end; procedure TapgCustomerBonus.OpenData; begin if dsBonus.Active then dsBonus.Close; dsBonus.OrderClause := GetOrderClause(dbgGrid); dsBonus.Open; end; procedure TapgCustomerBonus.actDelExecute(Sender: TObject); begin if dsBonus.RecordCount = 0 then Exit; if not dsBonus.FieldByName('BONUS').IsNull then begin if (MessageDlg(Format(rsDeleteBonus, [dsBonus.FieldByName('BONUS').AsFloat]), mtConfirmation, [mbYes, mbNo], 0) = mrYes) then dsBonus.Delete; end; actDel.Enabled := (dsBonus.RecordCount > 0) and actDel.Visible; end; procedure TapgCustomerBonus.actEditExecute(Sender: TObject); begin // AddEditDiscount(dsDiscount['DISCOUNT_ID'], FDataSource.Dataset['CUSTOMER_ID']); // dsDiscount.CloseOpen(true); // RecalcCustomer; end; procedure TapgCustomerBonus.CloseData; begin dsBonus.Close; end; procedure TapgCustomerBonus.dsBonusAfterOpen(DataSet: TDataSet); begin actDel.Enabled := (dsBonus.RecordCount > 0) and actDel.Visible; end; end.
program maxSubarray(input, output); { Sample input: 9 -2 1 -3 4 -1 2 1 -5 4 [1|2|3|4] Expected output: The max sum is: 6 } uses math; type sequence = array[1 .. 20] of integer; new_sequence = array[0 .. 20] of integer; var n, i, flag : integer; a : sequence; function select() : integer; var ans : integer; begin (* writeln('Please select the algorithm of choice, the options are:'); writeln(); writeln('1. O(n^3)'); writeln('2. O(n^2)'); writeln('3. O(nlog(n))'); writeln('4. O(n)'); *) read(ans); if not (ans in [1, 2, 3, 4]) then ans := -1; select := ans end; function maxSubarraySlow(s : sequence) : integer; var m, sum, i, j, k: integer; begin m := 0; for j := 1 to n do for k := j to n do begin sum := 0; for i := j to k do sum := sum + s[i]; if sum > m then m := sum end; maxSubarraySlow := m end; function maxSubarrayFaster(s : sequence; var len : integer) : integer; var summations : new_sequence; i, j, m, k, sum : integer; begin summations[0] := 0; for i := 1 to len do summations[i] := summations[i - 1] + s[i]; m := 0; for j := 1 to len do for k := j to len do begin sum := summations[k] - summations[j - 1]; if sum > m then m := sum; end; maxSubarrayFaster := m end; function maxSubarrayDivideAndConquer(s : sequence; low, high : integer) : integer; var mid : integer; left_sum, right_sum, cross_sum : integer; function maxSubarrayCrossing(a : sequence; l, m, h : integer) : integer; var ls, rs, sum, i, j : integer; begin ls := -21474; sum := 0; for i := m downto l do begin sum := sum + a[i]; if sum > ls then ls := sum end; rs := -21474; sum := 0; for j := m + 1 to h do begin sum := sum + a[j]; if sum > rs then rs := sum end; maxSubarrayCrossing := ls + rs; end; function max3(a, b, c : integer) : integer; function max(a, b : integer) : integer; begin if a > b then max := a else max := b end; begin max3 := max(a, max(b, c)) end; begin if high = low then maxSubarrayDivideAndConquer := s[low] else begin mid := floor((low + high) / 2); left_sum := maxSubarrayDivideAndConquer(s, low, mid); right_sum := maxSubarrayDivideAndConquer(s, mid + 1, high); cross_sum := maxSubarrayCrossing(s, low, mid, high); maxSubarrayDivideAndConquer := max3(left_sum, right_sum, cross_sum) end; end; function maxSubarrayDynamicProgramming(s : sequence; len : integer) : integer; var M : new_sequence; t, sum : integer; function max(a, b : integer) : integer; begin if a > b then max := a else max := b end; begin M[0] := 0; sum := 0; for t := 1 to n do begin M[t] := max(0, M[t - 1] + s[t]); sum := max(sum, M[t]); end; maxSubarrayDynamicProgramming := sum; end; begin read(n); if n > 20 then n := 20; for i := 1 to n do read(a[i]); flag := 7; while flag <> -1 do begin flag := select(); case flag of 1 : writeln('The max sum is: ', maxSubarraySlow(a)); 2 : writeln('The max sum is: ', maxSubarrayFaster(a, n)); 3 : writeln('The max sum is: ', maxSubarrayDivideAndConquer(a, 1, n)); 4 : writeln('The max sum is: ', maxSubarrayDynamicProgramming(a, n)); end; end; end.
unit Collection; interface type TMyClass = class private FF2: String; FF1: Integer; procedure SetF1(const Value: Integer); procedure SetF2(const Value: String); public property F1 : Integer read FF1 write SetF1; property F2 : String read FF2 write SetF2; end; TCollection = class private class var refInstance: TCollection; { TODO: Add class members to hold the objects in the collection } class constructor Create; class destructor Destroy; constructor Create; public class function getInstance: TCollection; class property Instance: TCollection read refInstance; end; implementation uses System.SysUtils, System.Types, System.StrUtils; class constructor TCollection.Create; begin if refInstance = nil then refInstance := TCollection.Create; end; class destructor TCollection.Destroy; begin refInstance.Free; refInstance := nil; end; constructor TCollection.Create; begin inherited; if refInstance <> nil then raise Exception.Create( 'No more object can be created from this class'); end; class function TCollection.getInstance: TCollection; begin result := refInstance; end; {type TFuncComparator = reference to function(l1,l2: String): Boolean; procedure Sort(items: TStringDynArray; compareFunc: TFuncComparator); var index, position: Integer; temp: String; begin for index := Low(items)+1 to High(items) do begin temp := items[index]; position := index - 1; while ((position >= Low(items)) and compareFunc(temp, items[position])) do begin items[position+1] := items[position]; dec(position); end; items[position+1] := temp; end; end; } var MyCollection: TCollection; //months: TStringDynArray; type TSort<DataType> = class type ArrayType = array of DataType; TFuncComparator = reference to function(l1,l2: DataType): Boolean; class procedure Sort(items: ArrayType; compareFunc: TFuncComparator); end; TSortString = TSort<String>; TSortInteger = TSort<Integer>; class procedure TSort<DataType>.Sort(items: ArrayType; compareFunc: TFuncComparator); var index, position: Integer; temp: DataType; begin for index := Low(items)+1 to High(items) do begin temp := items[index]; position := index - 1; while ((position >= Low(items)) and compareFunc(temp, items[position])) do begin items[position+1] := items[position]; dec(position); end; items[position+1] := temp; end; end; var months: TSortString.ArrayType; days: TSortInteger.ArrayType; { TMyClass } procedure TMyClass.SetF1(const Value: Integer); begin FF1 := Value; end; procedure TMyClass.SetF2(const Value: String); begin FF2 := Value; end; initialization begin SetLength(days, 10); SetLength(months, 12); // Introduce data into the arrays // months := SplitString('Jan,Feb,Mar,Apr,May,Jun,' + // 'Jul,Aug,Sep,Oct,Nov,Dec', ','); TSortInteger.Sort(days, function(l1, l2: Integer): Boolean begin result := l1 < l2; end); TSortString.Sort(months, function(l1, l2: String): Boolean begin result := l1 < l2; end); // Sort(months, function(l1, l2: String): Boolean // begin // if l1 < l2 then // result := true // else // result := false; // end); MyCollection := TCollection.refInstance; end; end.
// // Created by the DataSnap proxy generator. // 11/05/2017 16:44:54 // unit proxy; 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, UTipos, Data.DBXJSONReflect; type IDSRestCachedTResult = interface; IDSRestCachedTFDJSONDataSets = interface; TMetodosClienteClient = class(TDSAdminRestClient) private FEchoStringCommand: TDSRestCommand; FReverseStringCommand: TDSRestCommand; FClienteCommand: TDSRestCommand; FClienteCommand_Cache: TDSRestCommand; FClienteJSONCommand: TDSRestCommand; FClienteJSONCommand_Cache: TDSRestCommand; FClienteTipoCommand: TDSRestCommand; FClienteTipoCommand_Cache: TDSRestCommand; FClienteStatusCommand: TDSRestCommand; FClienteStatusCommand_Cache: TDSRestCommand; FtesteCommand: TDSRestCommand; FUpdateClienteApplyUpdatesCommand: TDSRestCommand; FUpdateClienteApplyUpdatesCommand_Cache: TDSRestCommand; FUpdateClienteJSONApplyUpdatesCommand: TDSRestCommand; FUpdateClienteJSONApplyUpdatesCommand_Cache: TDSRestCommand; FcancelClienteCommand: TDSRestCommand; FcancelClienteCommand_Cache: 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 Cliente(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): TFDJSONDataSets; function Cliente_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function ClienteJSON(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): TJSONArray; function ClienteJSON_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): IDSRestCachedJSONArray; function ClienteTipo(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): TFDJSONDataSets; function ClienteTipo_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function ClienteStatus(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): TFDJSONDataSets; function ClienteStatus_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function teste(const ARequestFilter: string = ''): string; function UpdateClienteApplyUpdates(ADeltaList: TFDJSONDeltas; const ARequestFilter: string = ''): TResult; function UpdateClienteApplyUpdates_Cache(ADeltaList: TFDJSONDeltas; const ARequestFilter: string = ''): IDSRestCachedTResult; function UpdateClienteJSONApplyUpdates(key: string; jObject: TJSONObject; const ARequestFilter: string = ''): TResult; function UpdateClienteJSONApplyUpdates_Cache(key: string; jObject: TJSONObject; const ARequestFilter: string = ''): IDSRestCachedTResult; function cancelCliente(key: string; const ARequestFilter: string = ''): TResult; function cancelCliente_Cache(key: string; const ARequestFilter: string = ''): IDSRestCachedTResult; end; TMetodosGeraisClient = class(TDSAdminRestClient) private FGetIDFromTableCommand: TDSRestCommand; FCidadeUFCommand: TDSRestCommand; FCidadeUFCommand_Cache: TDSRestCommand; FCidadeUFJSONCommand: TDSRestCommand; FCidadeUFJSONCommand_Cache: TDSRestCommand; FCidadeCommand: TDSRestCommand; FCidadeCommand_Cache: TDSRestCommand; FCidadeJSONCommand: TDSRestCommand; FCidadeJSONCommand_Cache: TDSRestCommand; FUpdateCidadeApplyUpdatesCommand: TDSRestCommand; FUpdateCidadeApplyUpdatesCommand_Cache: TDSRestCommand; FUpdateCidadeJSONApplyUpdatesCommand: TDSRestCommand; FUpdateCidadeJSONApplyUpdatesCommand_Cache: TDSRestCommand; FcancelCidadeCommand: TDSRestCommand; FcancelCidadeCommand_Cache: TDSRestCommand; public constructor Create(ARestConnection: TDSRestConnection); overload; constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function GetIDFromTable(TableName: string; const ARequestFilter: string = ''): Integer; function CidadeUF(ID: Integer; Fields: string; Filtro: string; const ARequestFilter: string = ''): TFDJSONDataSets; function CidadeUF_Cache(ID: Integer; Fields: string; Filtro: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function CidadeUFJSON(ID: Integer; Fields: string; Filtro: string; const ARequestFilter: string = ''): TJSONArray; function CidadeUFJSON_Cache(ID: Integer; Fields: string; Filtro: string; const ARequestFilter: string = ''): IDSRestCachedJSONArray; function Cidade(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): TFDJSONDataSets; function Cidade_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; function CidadeJSON(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): TJSONArray; function CidadeJSON_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string = ''): IDSRestCachedJSONArray; function UpdateCidadeApplyUpdates(ADeltaList: TFDJSONDeltas; const ARequestFilter: string = ''): TResult; function UpdateCidadeApplyUpdates_Cache(ADeltaList: TFDJSONDeltas; const ARequestFilter: string = ''): IDSRestCachedTResult; function UpdateCidadeJSONApplyUpdates(key: string; jObject: TJSONObject; const ARequestFilter: string = ''): TResult; function UpdateCidadeJSONApplyUpdates_Cache(key: string; jObject: TJSONObject; const ARequestFilter: string = ''): IDSRestCachedTResult; function cancelCidade(key: string; const ARequestFilter: string = ''): TResult; function cancelCidade_Cache(key: string; const ARequestFilter: string = ''): IDSRestCachedTResult; end; IDSRestCachedTResult = interface(IDSRestCachedObject<TResult>) end; TDSRestCachedTResult = class(TDSRestCachedObject<TResult>, IDSRestCachedTResult, IDSRestCachedCommand) end; IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>) end; TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand) end; const TMetodosCliente_EchoString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TMetodosCliente_ReverseString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TMetodosCliente_Cliente: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TMetodosCliente_Cliente_Cache: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosCliente_ClienteJSON: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONArray') ); TMetodosCliente_ClienteJSON_Cache: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosCliente_ClienteTipo: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TMetodosCliente_ClienteTipo_Cache: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosCliente_ClienteStatus: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TMetodosCliente_ClienteStatus_Cache: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosCliente_teste: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TMetodosCliente_UpdateClienteApplyUpdates: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADeltaList'; Direction: 1; DBXType: 37; TypeName: 'TFDJSONDeltas'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TResult') ); TMetodosCliente_UpdateClienteApplyUpdates_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADeltaList'; Direction: 1; DBXType: 37; TypeName: 'TFDJSONDeltas'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosCliente_UpdateClienteJSONApplyUpdates: array [0..2] of TDSRestParameterMetaData = ( (Name: 'key'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'jObject'; Direction: 1; DBXType: 37; TypeName: 'TJSONObject'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TResult') ); TMetodosCliente_UpdateClienteJSONApplyUpdates_Cache: array [0..2] of TDSRestParameterMetaData = ( (Name: 'key'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'jObject'; Direction: 1; DBXType: 37; TypeName: 'TJSONObject'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosCliente_cancelCliente: array [0..1] of TDSRestParameterMetaData = ( (Name: 'key'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TResult') ); TMetodosCliente_cancelCliente_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'key'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosGerais_GetIDFromTable: array [0..1] of TDSRestParameterMetaData = ( (Name: 'TableName'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 6; TypeName: 'Integer') ); TMetodosGerais_CidadeUF: array [0..3] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TMetodosGerais_CidadeUF_Cache: array [0..3] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosGerais_CidadeUFJSON: array [0..3] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONArray') ); TMetodosGerais_CidadeUFJSON_Cache: array [0..3] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosGerais_Cidade: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TMetodosGerais_Cidade_Cache: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosGerais_CidadeJSON: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TJSONArray') ); TMetodosGerais_CidadeJSON_Cache: array [0..4] of TDSRestParameterMetaData = ( (Name: 'ID'; Direction: 1; DBXType: 6; TypeName: 'Integer'), (Name: 'Recurso'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Fields'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'Filtro'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosGerais_UpdateCidadeApplyUpdates: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADeltaList'; Direction: 1; DBXType: 37; TypeName: 'TFDJSONDeltas'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TResult') ); TMetodosGerais_UpdateCidadeApplyUpdates_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'ADeltaList'; Direction: 1; DBXType: 37; TypeName: 'TFDJSONDeltas'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosGerais_UpdateCidadeJSONApplyUpdates: array [0..2] of TDSRestParameterMetaData = ( (Name: 'key'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'jObject'; Direction: 1; DBXType: 37; TypeName: 'TJSONObject'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TResult') ); TMetodosGerais_UpdateCidadeJSONApplyUpdates_Cache: array [0..2] of TDSRestParameterMetaData = ( (Name: 'key'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: 'jObject'; Direction: 1; DBXType: 37; TypeName: 'TJSONObject'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); TMetodosGerais_cancelCidade: array [0..1] of TDSRestParameterMetaData = ( (Name: 'key'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TResult') ); TMetodosGerais_cancelCidade_Cache: array [0..1] of TDSRestParameterMetaData = ( (Name: 'key'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); implementation function TMetodosClienteClient.EchoString(Value: string; const ARequestFilter: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FConnection.CreateCommand; FEchoStringCommand.RequestType := 'GET'; FEchoStringCommand.Text := 'TMetodosCliente.EchoString'; FEchoStringCommand.Prepare(TMetodosCliente_EchoString); end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.Execute(ARequestFilter); Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TMetodosClienteClient.ReverseString(Value: string; const ARequestFilter: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FConnection.CreateCommand; FReverseStringCommand.RequestType := 'GET'; FReverseStringCommand.Text := 'TMetodosCliente.ReverseString'; FReverseStringCommand.Prepare(TMetodosCliente_ReverseString); end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.Execute(ARequestFilter); Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; function TMetodosClienteClient.Cliente(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): TFDJSONDataSets; begin if FClienteCommand = nil then begin FClienteCommand := FConnection.CreateCommand; FClienteCommand.RequestType := 'GET'; FClienteCommand.Text := 'TMetodosCliente.Cliente'; FClienteCommand.Prepare(TMetodosCliente_Cliente); end; FClienteCommand.Parameters[0].Value.SetInt32(ID); FClienteCommand.Parameters[1].Value.SetWideString(Recurso); FClienteCommand.Parameters[2].Value.SetWideString(Fields); FClienteCommand.Parameters[3].Value.SetWideString(Filtro); FClienteCommand.Execute(ARequestFilter); if not FClienteCommand.Parameters[4].Value.IsNull then begin FUnMarshal := TDSRestCommand(FClienteCommand.Parameters[4].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FClienteCommand.Parameters[4].Value.GetJSONValue(True))); if FInstanceOwner then FClienteCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosClienteClient.Cliente_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FClienteCommand_Cache = nil then begin FClienteCommand_Cache := FConnection.CreateCommand; FClienteCommand_Cache.RequestType := 'GET'; FClienteCommand_Cache.Text := 'TMetodosCliente.Cliente'; FClienteCommand_Cache.Prepare(TMetodosCliente_Cliente_Cache); end; FClienteCommand_Cache.Parameters[0].Value.SetInt32(ID); FClienteCommand_Cache.Parameters[1].Value.SetWideString(Recurso); FClienteCommand_Cache.Parameters[2].Value.SetWideString(Fields); FClienteCommand_Cache.Parameters[3].Value.SetWideString(Filtro); FClienteCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FClienteCommand_Cache.Parameters[4].Value.GetString); end; function TMetodosClienteClient.ClienteJSON(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): TJSONArray; begin if FClienteJSONCommand = nil then begin FClienteJSONCommand := FConnection.CreateCommand; FClienteJSONCommand.RequestType := 'GET'; FClienteJSONCommand.Text := 'TMetodosCliente.ClienteJSON'; FClienteJSONCommand.Prepare(TMetodosCliente_ClienteJSON); end; FClienteJSONCommand.Parameters[0].Value.SetInt32(ID); FClienteJSONCommand.Parameters[1].Value.SetWideString(Recurso); FClienteJSONCommand.Parameters[2].Value.SetWideString(Fields); FClienteJSONCommand.Parameters[3].Value.SetWideString(Filtro); FClienteJSONCommand.Execute(ARequestFilter); Result := TJSONArray(FClienteJSONCommand.Parameters[4].Value.GetJSONValue(FInstanceOwner)); end; function TMetodosClienteClient.ClienteJSON_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): IDSRestCachedJSONArray; begin if FClienteJSONCommand_Cache = nil then begin FClienteJSONCommand_Cache := FConnection.CreateCommand; FClienteJSONCommand_Cache.RequestType := 'GET'; FClienteJSONCommand_Cache.Text := 'TMetodosCliente.ClienteJSON'; FClienteJSONCommand_Cache.Prepare(TMetodosCliente_ClienteJSON_Cache); end; FClienteJSONCommand_Cache.Parameters[0].Value.SetInt32(ID); FClienteJSONCommand_Cache.Parameters[1].Value.SetWideString(Recurso); FClienteJSONCommand_Cache.Parameters[2].Value.SetWideString(Fields); FClienteJSONCommand_Cache.Parameters[3].Value.SetWideString(Filtro); FClienteJSONCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedJSONArray.Create(FClienteJSONCommand_Cache.Parameters[4].Value.GetString); end; function TMetodosClienteClient.ClienteTipo(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): TFDJSONDataSets; begin if FClienteTipoCommand = nil then begin FClienteTipoCommand := FConnection.CreateCommand; FClienteTipoCommand.RequestType := 'GET'; FClienteTipoCommand.Text := 'TMetodosCliente.ClienteTipo'; FClienteTipoCommand.Prepare(TMetodosCliente_ClienteTipo); end; FClienteTipoCommand.Parameters[0].Value.SetInt32(ID); FClienteTipoCommand.Parameters[1].Value.SetWideString(Recurso); FClienteTipoCommand.Parameters[2].Value.SetWideString(Fields); FClienteTipoCommand.Parameters[3].Value.SetWideString(Filtro); FClienteTipoCommand.Execute(ARequestFilter); if not FClienteTipoCommand.Parameters[4].Value.IsNull then begin FUnMarshal := TDSRestCommand(FClienteTipoCommand.Parameters[4].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FClienteTipoCommand.Parameters[4].Value.GetJSONValue(True))); if FInstanceOwner then FClienteTipoCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosClienteClient.ClienteTipo_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FClienteTipoCommand_Cache = nil then begin FClienteTipoCommand_Cache := FConnection.CreateCommand; FClienteTipoCommand_Cache.RequestType := 'GET'; FClienteTipoCommand_Cache.Text := 'TMetodosCliente.ClienteTipo'; FClienteTipoCommand_Cache.Prepare(TMetodosCliente_ClienteTipo_Cache); end; FClienteTipoCommand_Cache.Parameters[0].Value.SetInt32(ID); FClienteTipoCommand_Cache.Parameters[1].Value.SetWideString(Recurso); FClienteTipoCommand_Cache.Parameters[2].Value.SetWideString(Fields); FClienteTipoCommand_Cache.Parameters[3].Value.SetWideString(Filtro); FClienteTipoCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FClienteTipoCommand_Cache.Parameters[4].Value.GetString); end; function TMetodosClienteClient.ClienteStatus(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): TFDJSONDataSets; begin if FClienteStatusCommand = nil then begin FClienteStatusCommand := FConnection.CreateCommand; FClienteStatusCommand.RequestType := 'GET'; FClienteStatusCommand.Text := 'TMetodosCliente.ClienteStatus'; FClienteStatusCommand.Prepare(TMetodosCliente_ClienteStatus); end; FClienteStatusCommand.Parameters[0].Value.SetInt32(ID); FClienteStatusCommand.Parameters[1].Value.SetWideString(Recurso); FClienteStatusCommand.Parameters[2].Value.SetWideString(Fields); FClienteStatusCommand.Parameters[3].Value.SetWideString(Filtro); FClienteStatusCommand.Execute(ARequestFilter); if not FClienteStatusCommand.Parameters[4].Value.IsNull then begin FUnMarshal := TDSRestCommand(FClienteStatusCommand.Parameters[4].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FClienteStatusCommand.Parameters[4].Value.GetJSONValue(True))); if FInstanceOwner then FClienteStatusCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosClienteClient.ClienteStatus_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FClienteStatusCommand_Cache = nil then begin FClienteStatusCommand_Cache := FConnection.CreateCommand; FClienteStatusCommand_Cache.RequestType := 'GET'; FClienteStatusCommand_Cache.Text := 'TMetodosCliente.ClienteStatus'; FClienteStatusCommand_Cache.Prepare(TMetodosCliente_ClienteStatus_Cache); end; FClienteStatusCommand_Cache.Parameters[0].Value.SetInt32(ID); FClienteStatusCommand_Cache.Parameters[1].Value.SetWideString(Recurso); FClienteStatusCommand_Cache.Parameters[2].Value.SetWideString(Fields); FClienteStatusCommand_Cache.Parameters[3].Value.SetWideString(Filtro); FClienteStatusCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FClienteStatusCommand_Cache.Parameters[4].Value.GetString); end; function TMetodosClienteClient.teste(const ARequestFilter: string): string; begin if FtesteCommand = nil then begin FtesteCommand := FConnection.CreateCommand; FtesteCommand.RequestType := 'GET'; FtesteCommand.Text := 'TMetodosCliente.teste'; FtesteCommand.Prepare(TMetodosCliente_teste); end; FtesteCommand.Execute(ARequestFilter); Result := FtesteCommand.Parameters[0].Value.GetWideString; end; function TMetodosClienteClient.UpdateClienteApplyUpdates(ADeltaList: TFDJSONDeltas; const ARequestFilter: string): TResult; begin if FUpdateClienteApplyUpdatesCommand = nil then begin FUpdateClienteApplyUpdatesCommand := FConnection.CreateCommand; FUpdateClienteApplyUpdatesCommand.RequestType := 'POST'; FUpdateClienteApplyUpdatesCommand.Text := 'TMetodosCliente."UpdateClienteApplyUpdates"'; FUpdateClienteApplyUpdatesCommand.Prepare(TMetodosCliente_UpdateClienteApplyUpdates); end; if not Assigned(ADeltaList) then FUpdateClienteApplyUpdatesCommand.Parameters[0].Value.SetNull else begin FMarshal := TDSRestCommand(FUpdateClienteApplyUpdatesCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FUpdateClienteApplyUpdatesCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ADeltaList), True); if FInstanceOwner then ADeltaList.Free finally FreeAndNil(FMarshal) end end; FUpdateClienteApplyUpdatesCommand.Execute(ARequestFilter); if not FUpdateClienteApplyUpdatesCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FUpdateClienteApplyUpdatesCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TResult(FUnMarshal.UnMarshal(FUpdateClienteApplyUpdatesCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FUpdateClienteApplyUpdatesCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosClienteClient.UpdateClienteApplyUpdates_Cache(ADeltaList: TFDJSONDeltas; const ARequestFilter: string): IDSRestCachedTResult; begin if FUpdateClienteApplyUpdatesCommand_Cache = nil then begin FUpdateClienteApplyUpdatesCommand_Cache := FConnection.CreateCommand; FUpdateClienteApplyUpdatesCommand_Cache.RequestType := 'POST'; FUpdateClienteApplyUpdatesCommand_Cache.Text := 'TMetodosCliente."UpdateClienteApplyUpdates"'; FUpdateClienteApplyUpdatesCommand_Cache.Prepare(TMetodosCliente_UpdateClienteApplyUpdates_Cache); end; if not Assigned(ADeltaList) then FUpdateClienteApplyUpdatesCommand_Cache.Parameters[0].Value.SetNull else begin FMarshal := TDSRestCommand(FUpdateClienteApplyUpdatesCommand_Cache.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FUpdateClienteApplyUpdatesCommand_Cache.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ADeltaList), True); if FInstanceOwner then ADeltaList.Free finally FreeAndNil(FMarshal) end end; FUpdateClienteApplyUpdatesCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTResult.Create(FUpdateClienteApplyUpdatesCommand_Cache.Parameters[1].Value.GetString); end; function TMetodosClienteClient.UpdateClienteJSONApplyUpdates(key: string; jObject: TJSONObject; const ARequestFilter: string): TResult; begin if FUpdateClienteJSONApplyUpdatesCommand = nil then begin FUpdateClienteJSONApplyUpdatesCommand := FConnection.CreateCommand; FUpdateClienteJSONApplyUpdatesCommand.RequestType := 'POST'; FUpdateClienteJSONApplyUpdatesCommand.Text := 'TMetodosCliente."UpdateClienteJSONApplyUpdates"'; FUpdateClienteJSONApplyUpdatesCommand.Prepare(TMetodosCliente_UpdateClienteJSONApplyUpdates); end; FUpdateClienteJSONApplyUpdatesCommand.Parameters[0].Value.SetWideString(key); FUpdateClienteJSONApplyUpdatesCommand.Parameters[1].Value.SetJSONValue(jObject, FInstanceOwner); FUpdateClienteJSONApplyUpdatesCommand.Execute(ARequestFilter); if not FUpdateClienteJSONApplyUpdatesCommand.Parameters[2].Value.IsNull then begin FUnMarshal := TDSRestCommand(FUpdateClienteJSONApplyUpdatesCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler; try Result := TResult(FUnMarshal.UnMarshal(FUpdateClienteJSONApplyUpdatesCommand.Parameters[2].Value.GetJSONValue(True))); if FInstanceOwner then FUpdateClienteJSONApplyUpdatesCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosClienteClient.UpdateClienteJSONApplyUpdates_Cache(key: string; jObject: TJSONObject; const ARequestFilter: string): IDSRestCachedTResult; begin if FUpdateClienteJSONApplyUpdatesCommand_Cache = nil then begin FUpdateClienteJSONApplyUpdatesCommand_Cache := FConnection.CreateCommand; FUpdateClienteJSONApplyUpdatesCommand_Cache.RequestType := 'POST'; FUpdateClienteJSONApplyUpdatesCommand_Cache.Text := 'TMetodosCliente."UpdateClienteJSONApplyUpdates"'; FUpdateClienteJSONApplyUpdatesCommand_Cache.Prepare(TMetodosCliente_UpdateClienteJSONApplyUpdates_Cache); end; FUpdateClienteJSONApplyUpdatesCommand_Cache.Parameters[0].Value.SetWideString(key); FUpdateClienteJSONApplyUpdatesCommand_Cache.Parameters[1].Value.SetJSONValue(jObject, FInstanceOwner); FUpdateClienteJSONApplyUpdatesCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTResult.Create(FUpdateClienteJSONApplyUpdatesCommand_Cache.Parameters[2].Value.GetString); end; function TMetodosClienteClient.cancelCliente(key: string; const ARequestFilter: string): TResult; begin if FcancelClienteCommand = nil then begin FcancelClienteCommand := FConnection.CreateCommand; FcancelClienteCommand.RequestType := 'GET'; FcancelClienteCommand.Text := 'TMetodosCliente.cancelCliente'; FcancelClienteCommand.Prepare(TMetodosCliente_cancelCliente); end; FcancelClienteCommand.Parameters[0].Value.SetWideString(key); FcancelClienteCommand.Execute(ARequestFilter); if not FcancelClienteCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FcancelClienteCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TResult(FUnMarshal.UnMarshal(FcancelClienteCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FcancelClienteCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosClienteClient.cancelCliente_Cache(key: string; const ARequestFilter: string): IDSRestCachedTResult; begin if FcancelClienteCommand_Cache = nil then begin FcancelClienteCommand_Cache := FConnection.CreateCommand; FcancelClienteCommand_Cache.RequestType := 'GET'; FcancelClienteCommand_Cache.Text := 'TMetodosCliente.cancelCliente'; FcancelClienteCommand_Cache.Prepare(TMetodosCliente_cancelCliente_Cache); end; FcancelClienteCommand_Cache.Parameters[0].Value.SetWideString(key); FcancelClienteCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTResult.Create(FcancelClienteCommand_Cache.Parameters[1].Value.GetString); end; constructor TMetodosClienteClient.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TMetodosClienteClient.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TMetodosClienteClient.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FClienteCommand.DisposeOf; FClienteCommand_Cache.DisposeOf; FClienteJSONCommand.DisposeOf; FClienteJSONCommand_Cache.DisposeOf; FClienteTipoCommand.DisposeOf; FClienteTipoCommand_Cache.DisposeOf; FClienteStatusCommand.DisposeOf; FClienteStatusCommand_Cache.DisposeOf; FtesteCommand.DisposeOf; FUpdateClienteApplyUpdatesCommand.DisposeOf; FUpdateClienteApplyUpdatesCommand_Cache.DisposeOf; FUpdateClienteJSONApplyUpdatesCommand.DisposeOf; FUpdateClienteJSONApplyUpdatesCommand_Cache.DisposeOf; FcancelClienteCommand.DisposeOf; FcancelClienteCommand_Cache.DisposeOf; inherited; end; function TMetodosGeraisClient.GetIDFromTable(TableName: string; const ARequestFilter: string): Integer; begin if FGetIDFromTableCommand = nil then begin FGetIDFromTableCommand := FConnection.CreateCommand; FGetIDFromTableCommand.RequestType := 'GET'; FGetIDFromTableCommand.Text := 'TMetodosGerais.GetIDFromTable'; FGetIDFromTableCommand.Prepare(TMetodosGerais_GetIDFromTable); end; FGetIDFromTableCommand.Parameters[0].Value.SetWideString(TableName); FGetIDFromTableCommand.Execute(ARequestFilter); Result := FGetIDFromTableCommand.Parameters[1].Value.GetInt32; end; function TMetodosGeraisClient.CidadeUF(ID: Integer; Fields: string; Filtro: string; const ARequestFilter: string): TFDJSONDataSets; begin if FCidadeUFCommand = nil then begin FCidadeUFCommand := FConnection.CreateCommand; FCidadeUFCommand.RequestType := 'GET'; FCidadeUFCommand.Text := 'TMetodosGerais.CidadeUF'; FCidadeUFCommand.Prepare(TMetodosGerais_CidadeUF); end; FCidadeUFCommand.Parameters[0].Value.SetInt32(ID); FCidadeUFCommand.Parameters[1].Value.SetWideString(Fields); FCidadeUFCommand.Parameters[2].Value.SetWideString(Filtro); FCidadeUFCommand.Execute(ARequestFilter); if not FCidadeUFCommand.Parameters[3].Value.IsNull then begin FUnMarshal := TDSRestCommand(FCidadeUFCommand.Parameters[3].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FCidadeUFCommand.Parameters[3].Value.GetJSONValue(True))); if FInstanceOwner then FCidadeUFCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosGeraisClient.CidadeUF_Cache(ID: Integer; Fields: string; Filtro: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FCidadeUFCommand_Cache = nil then begin FCidadeUFCommand_Cache := FConnection.CreateCommand; FCidadeUFCommand_Cache.RequestType := 'GET'; FCidadeUFCommand_Cache.Text := 'TMetodosGerais.CidadeUF'; FCidadeUFCommand_Cache.Prepare(TMetodosGerais_CidadeUF_Cache); end; FCidadeUFCommand_Cache.Parameters[0].Value.SetInt32(ID); FCidadeUFCommand_Cache.Parameters[1].Value.SetWideString(Fields); FCidadeUFCommand_Cache.Parameters[2].Value.SetWideString(Filtro); FCidadeUFCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FCidadeUFCommand_Cache.Parameters[3].Value.GetString); end; function TMetodosGeraisClient.CidadeUFJSON(ID: Integer; Fields: string; Filtro: string; const ARequestFilter: string): TJSONArray; begin if FCidadeUFJSONCommand = nil then begin FCidadeUFJSONCommand := FConnection.CreateCommand; FCidadeUFJSONCommand.RequestType := 'GET'; FCidadeUFJSONCommand.Text := 'TMetodosGerais.CidadeUFJSON'; FCidadeUFJSONCommand.Prepare(TMetodosGerais_CidadeUFJSON); end; FCidadeUFJSONCommand.Parameters[0].Value.SetInt32(ID); FCidadeUFJSONCommand.Parameters[1].Value.SetWideString(Fields); FCidadeUFJSONCommand.Parameters[2].Value.SetWideString(Filtro); FCidadeUFJSONCommand.Execute(ARequestFilter); Result := TJSONArray(FCidadeUFJSONCommand.Parameters[3].Value.GetJSONValue(FInstanceOwner)); end; function TMetodosGeraisClient.CidadeUFJSON_Cache(ID: Integer; Fields: string; Filtro: string; const ARequestFilter: string): IDSRestCachedJSONArray; begin if FCidadeUFJSONCommand_Cache = nil then begin FCidadeUFJSONCommand_Cache := FConnection.CreateCommand; FCidadeUFJSONCommand_Cache.RequestType := 'GET'; FCidadeUFJSONCommand_Cache.Text := 'TMetodosGerais.CidadeUFJSON'; FCidadeUFJSONCommand_Cache.Prepare(TMetodosGerais_CidadeUFJSON_Cache); end; FCidadeUFJSONCommand_Cache.Parameters[0].Value.SetInt32(ID); FCidadeUFJSONCommand_Cache.Parameters[1].Value.SetWideString(Fields); FCidadeUFJSONCommand_Cache.Parameters[2].Value.SetWideString(Filtro); FCidadeUFJSONCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedJSONArray.Create(FCidadeUFJSONCommand_Cache.Parameters[3].Value.GetString); end; function TMetodosGeraisClient.Cidade(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): TFDJSONDataSets; begin if FCidadeCommand = nil then begin FCidadeCommand := FConnection.CreateCommand; FCidadeCommand.RequestType := 'GET'; FCidadeCommand.Text := 'TMetodosGerais.Cidade'; FCidadeCommand.Prepare(TMetodosGerais_Cidade); end; FCidadeCommand.Parameters[0].Value.SetInt32(ID); FCidadeCommand.Parameters[1].Value.SetWideString(Recurso); FCidadeCommand.Parameters[2].Value.SetWideString(Fields); FCidadeCommand.Parameters[3].Value.SetWideString(Filtro); FCidadeCommand.Execute(ARequestFilter); if not FCidadeCommand.Parameters[4].Value.IsNull then begin FUnMarshal := TDSRestCommand(FCidadeCommand.Parameters[4].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FCidadeCommand.Parameters[4].Value.GetJSONValue(True))); if FInstanceOwner then FCidadeCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosGeraisClient.Cidade_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FCidadeCommand_Cache = nil then begin FCidadeCommand_Cache := FConnection.CreateCommand; FCidadeCommand_Cache.RequestType := 'GET'; FCidadeCommand_Cache.Text := 'TMetodosGerais.Cidade'; FCidadeCommand_Cache.Prepare(TMetodosGerais_Cidade_Cache); end; FCidadeCommand_Cache.Parameters[0].Value.SetInt32(ID); FCidadeCommand_Cache.Parameters[1].Value.SetWideString(Recurso); FCidadeCommand_Cache.Parameters[2].Value.SetWideString(Fields); FCidadeCommand_Cache.Parameters[3].Value.SetWideString(Filtro); FCidadeCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FCidadeCommand_Cache.Parameters[4].Value.GetString); end; function TMetodosGeraisClient.CidadeJSON(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): TJSONArray; begin if FCidadeJSONCommand = nil then begin FCidadeJSONCommand := FConnection.CreateCommand; FCidadeJSONCommand.RequestType := 'GET'; FCidadeJSONCommand.Text := 'TMetodosGerais.CidadeJSON'; FCidadeJSONCommand.Prepare(TMetodosGerais_CidadeJSON); end; FCidadeJSONCommand.Parameters[0].Value.SetInt32(ID); FCidadeJSONCommand.Parameters[1].Value.SetWideString(Recurso); FCidadeJSONCommand.Parameters[2].Value.SetWideString(Fields); FCidadeJSONCommand.Parameters[3].Value.SetWideString(Filtro); FCidadeJSONCommand.Execute(ARequestFilter); Result := TJSONArray(FCidadeJSONCommand.Parameters[4].Value.GetJSONValue(FInstanceOwner)); end; function TMetodosGeraisClient.CidadeJSON_Cache(ID: Integer; Recurso: string; Fields: string; Filtro: string; const ARequestFilter: string): IDSRestCachedJSONArray; begin if FCidadeJSONCommand_Cache = nil then begin FCidadeJSONCommand_Cache := FConnection.CreateCommand; FCidadeJSONCommand_Cache.RequestType := 'GET'; FCidadeJSONCommand_Cache.Text := 'TMetodosGerais.CidadeJSON'; FCidadeJSONCommand_Cache.Prepare(TMetodosGerais_CidadeJSON_Cache); end; FCidadeJSONCommand_Cache.Parameters[0].Value.SetInt32(ID); FCidadeJSONCommand_Cache.Parameters[1].Value.SetWideString(Recurso); FCidadeJSONCommand_Cache.Parameters[2].Value.SetWideString(Fields); FCidadeJSONCommand_Cache.Parameters[3].Value.SetWideString(Filtro); FCidadeJSONCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedJSONArray.Create(FCidadeJSONCommand_Cache.Parameters[4].Value.GetString); end; function TMetodosGeraisClient.UpdateCidadeApplyUpdates(ADeltaList: TFDJSONDeltas; const ARequestFilter: string): TResult; begin if FUpdateCidadeApplyUpdatesCommand = nil then begin FUpdateCidadeApplyUpdatesCommand := FConnection.CreateCommand; FUpdateCidadeApplyUpdatesCommand.RequestType := 'POST'; FUpdateCidadeApplyUpdatesCommand.Text := 'TMetodosGerais."UpdateCidadeApplyUpdates"'; FUpdateCidadeApplyUpdatesCommand.Prepare(TMetodosGerais_UpdateCidadeApplyUpdates); end; if not Assigned(ADeltaList) then FUpdateCidadeApplyUpdatesCommand.Parameters[0].Value.SetNull else begin FMarshal := TDSRestCommand(FUpdateCidadeApplyUpdatesCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FUpdateCidadeApplyUpdatesCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ADeltaList), True); if FInstanceOwner then ADeltaList.Free finally FreeAndNil(FMarshal) end end; FUpdateCidadeApplyUpdatesCommand.Execute(ARequestFilter); if not FUpdateCidadeApplyUpdatesCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FUpdateCidadeApplyUpdatesCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TResult(FUnMarshal.UnMarshal(FUpdateCidadeApplyUpdatesCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FUpdateCidadeApplyUpdatesCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosGeraisClient.UpdateCidadeApplyUpdates_Cache(ADeltaList: TFDJSONDeltas; const ARequestFilter: string): IDSRestCachedTResult; begin if FUpdateCidadeApplyUpdatesCommand_Cache = nil then begin FUpdateCidadeApplyUpdatesCommand_Cache := FConnection.CreateCommand; FUpdateCidadeApplyUpdatesCommand_Cache.RequestType := 'POST'; FUpdateCidadeApplyUpdatesCommand_Cache.Text := 'TMetodosGerais."UpdateCidadeApplyUpdates"'; FUpdateCidadeApplyUpdatesCommand_Cache.Prepare(TMetodosGerais_UpdateCidadeApplyUpdates_Cache); end; if not Assigned(ADeltaList) then FUpdateCidadeApplyUpdatesCommand_Cache.Parameters[0].Value.SetNull else begin FMarshal := TDSRestCommand(FUpdateCidadeApplyUpdatesCommand_Cache.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FUpdateCidadeApplyUpdatesCommand_Cache.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ADeltaList), True); if FInstanceOwner then ADeltaList.Free finally FreeAndNil(FMarshal) end end; FUpdateCidadeApplyUpdatesCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTResult.Create(FUpdateCidadeApplyUpdatesCommand_Cache.Parameters[1].Value.GetString); end; function TMetodosGeraisClient.UpdateCidadeJSONApplyUpdates(key: string; jObject: TJSONObject; const ARequestFilter: string): TResult; begin if FUpdateCidadeJSONApplyUpdatesCommand = nil then begin FUpdateCidadeJSONApplyUpdatesCommand := FConnection.CreateCommand; FUpdateCidadeJSONApplyUpdatesCommand.RequestType := 'POST'; FUpdateCidadeJSONApplyUpdatesCommand.Text := 'TMetodosGerais."UpdateCidadeJSONApplyUpdates"'; FUpdateCidadeJSONApplyUpdatesCommand.Prepare(TMetodosGerais_UpdateCidadeJSONApplyUpdates); end; FUpdateCidadeJSONApplyUpdatesCommand.Parameters[0].Value.SetWideString(key); FUpdateCidadeJSONApplyUpdatesCommand.Parameters[1].Value.SetJSONValue(jObject, FInstanceOwner); FUpdateCidadeJSONApplyUpdatesCommand.Execute(ARequestFilter); if not FUpdateCidadeJSONApplyUpdatesCommand.Parameters[2].Value.IsNull then begin FUnMarshal := TDSRestCommand(FUpdateCidadeJSONApplyUpdatesCommand.Parameters[2].ConnectionHandler).GetJSONUnMarshaler; try Result := TResult(FUnMarshal.UnMarshal(FUpdateCidadeJSONApplyUpdatesCommand.Parameters[2].Value.GetJSONValue(True))); if FInstanceOwner then FUpdateCidadeJSONApplyUpdatesCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosGeraisClient.UpdateCidadeJSONApplyUpdates_Cache(key: string; jObject: TJSONObject; const ARequestFilter: string): IDSRestCachedTResult; begin if FUpdateCidadeJSONApplyUpdatesCommand_Cache = nil then begin FUpdateCidadeJSONApplyUpdatesCommand_Cache := FConnection.CreateCommand; FUpdateCidadeJSONApplyUpdatesCommand_Cache.RequestType := 'POST'; FUpdateCidadeJSONApplyUpdatesCommand_Cache.Text := 'TMetodosGerais."UpdateCidadeJSONApplyUpdates"'; FUpdateCidadeJSONApplyUpdatesCommand_Cache.Prepare(TMetodosGerais_UpdateCidadeJSONApplyUpdates_Cache); end; FUpdateCidadeJSONApplyUpdatesCommand_Cache.Parameters[0].Value.SetWideString(key); FUpdateCidadeJSONApplyUpdatesCommand_Cache.Parameters[1].Value.SetJSONValue(jObject, FInstanceOwner); FUpdateCidadeJSONApplyUpdatesCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTResult.Create(FUpdateCidadeJSONApplyUpdatesCommand_Cache.Parameters[2].Value.GetString); end; function TMetodosGeraisClient.cancelCidade(key: string; const ARequestFilter: string): TResult; begin if FcancelCidadeCommand = nil then begin FcancelCidadeCommand := FConnection.CreateCommand; FcancelCidadeCommand.RequestType := 'GET'; FcancelCidadeCommand.Text := 'TMetodosGerais.cancelCidade'; FcancelCidadeCommand.Prepare(TMetodosGerais_cancelCidade); end; FcancelCidadeCommand.Parameters[0].Value.SetWideString(key); FcancelCidadeCommand.Execute(ARequestFilter); if not FcancelCidadeCommand.Parameters[1].Value.IsNull then begin FUnMarshal := TDSRestCommand(FcancelCidadeCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler; try Result := TResult(FUnMarshal.UnMarshal(FcancelCidadeCommand.Parameters[1].Value.GetJSONValue(True))); if FInstanceOwner then FcancelCidadeCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TMetodosGeraisClient.cancelCidade_Cache(key: string; const ARequestFilter: string): IDSRestCachedTResult; begin if FcancelCidadeCommand_Cache = nil then begin FcancelCidadeCommand_Cache := FConnection.CreateCommand; FcancelCidadeCommand_Cache.RequestType := 'GET'; FcancelCidadeCommand_Cache.Text := 'TMetodosGerais.cancelCidade'; FcancelCidadeCommand_Cache.Prepare(TMetodosGerais_cancelCidade_Cache); end; FcancelCidadeCommand_Cache.Parameters[0].Value.SetWideString(key); FcancelCidadeCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTResult.Create(FcancelCidadeCommand_Cache.Parameters[1].Value.GetString); end; constructor TMetodosGeraisClient.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TMetodosGeraisClient.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TMetodosGeraisClient.Destroy; begin FGetIDFromTableCommand.DisposeOf; FCidadeUFCommand.DisposeOf; FCidadeUFCommand_Cache.DisposeOf; FCidadeUFJSONCommand.DisposeOf; FCidadeUFJSONCommand_Cache.DisposeOf; FCidadeCommand.DisposeOf; FCidadeCommand_Cache.DisposeOf; FCidadeJSONCommand.DisposeOf; FCidadeJSONCommand_Cache.DisposeOf; FUpdateCidadeApplyUpdatesCommand.DisposeOf; FUpdateCidadeApplyUpdatesCommand_Cache.DisposeOf; FUpdateCidadeJSONApplyUpdatesCommand.DisposeOf; FUpdateCidadeJSONApplyUpdatesCommand_Cache.DisposeOf; FcancelCidadeCommand.DisposeOf; FcancelCidadeCommand_Cache.DisposeOf; inherited; end; end.
{ Date Created: 5/22/00 3:22:29 PM } unit InfoPOLTEMPLTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoPOLTEMPLRecord = record PCode: String[6]; PDescription: String[30]; PAutoCreate: Boolean; End; TInfoPOLTEMPLBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoPOLTEMPLRecord end; TEIInfoPOLTEMPL = (InfoPOLTEMPLPrimaryKey); TInfoPOLTEMPLTable = class( TDBISAMTableAU ) private FDFCode: TStringField; FDFDescription: TStringField; FDFAutoCreate: TBooleanField; FDFTemplate: TBlobField; procedure SetPCode(const Value: String); function GetPCode:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPAutoCreate(const Value: Boolean); function GetPAutoCreate:Boolean; procedure SetEnumIndex(Value: TEIInfoPOLTEMPL); function GetEnumIndex: TEIInfoPOLTEMPL; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoPOLTEMPLRecord; procedure StoreDataBuffer(ABuffer:TInfoPOLTEMPLRecord); property DFCode: TStringField read FDFCode; property DFDescription: TStringField read FDFDescription; property DFAutoCreate: TBooleanField read FDFAutoCreate; property DFTemplate: TBlobField read FDFTemplate; property PCode: String read GetPCode write SetPCode; property PDescription: String read GetPDescription write SetPDescription; property PAutoCreate: Boolean read GetPAutoCreate write SetPAutoCreate; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoPOLTEMPL read GetEnumIndex write SetEnumIndex; end; { TInfoPOLTEMPLTable } procedure Register; implementation procedure TInfoPOLTEMPLTable.CreateFields; begin FDFCode := CreateField( 'Code' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFAutoCreate := CreateField( 'AutoCreate' ) as TBooleanField; FDFTemplate := CreateField( 'Template' ) as TBlobField; end; { TInfoPOLTEMPLTable.CreateFields } procedure TInfoPOLTEMPLTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoPOLTEMPLTable.SetActive } procedure TInfoPOLTEMPLTable.Validate; begin { Enter Validation Code Here } end; { TInfoPOLTEMPLTable.Validate } procedure TInfoPOLTEMPLTable.SetPCode(const Value: String); begin DFCode.Value := Value; end; function TInfoPOLTEMPLTable.GetPCode:String; begin result := DFCode.Value; end; procedure TInfoPOLTEMPLTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoPOLTEMPLTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoPOLTEMPLTable.SetPAutoCreate(const Value: Boolean); begin DFAutoCreate.Value := Value; end; function TInfoPOLTEMPLTable.GetPAutoCreate:Boolean; begin result := DFAutoCreate.Value; end; procedure TInfoPOLTEMPLTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Code, String, 6, N'); Add('Description, String, 30, N'); Add('AutoCreate, Boolean, 0, N'); Add('Template, Memo, 0, N'); end; end; procedure TInfoPOLTEMPLTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Code, Y, Y, N, N'); end; end; procedure TInfoPOLTEMPLTable.SetEnumIndex(Value: TEIInfoPOLTEMPL); begin case Value of InfoPOLTEMPLPrimaryKey : IndexName := ''; end; end; function TInfoPOLTEMPLTable.GetDataBuffer:TInfoPOLTEMPLRecord; var buf: TInfoPOLTEMPLRecord; begin fillchar(buf, sizeof(buf), 0); buf.PCode := DFCode.Value; buf.PDescription := DFDescription.Value; buf.PAutoCreate := DFAutoCreate.Value; result := buf; end; procedure TInfoPOLTEMPLTable.StoreDataBuffer(ABuffer:TInfoPOLTEMPLRecord); begin DFCode.Value := ABuffer.PCode; DFDescription.Value := ABuffer.PDescription; DFAutoCreate.Value := ABuffer.PAutoCreate; end; function TInfoPOLTEMPLTable.GetEnumIndex: TEIInfoPOLTEMPL; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoPOLTEMPLPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoPOLTEMPLTable, TInfoPOLTEMPLBuffer ] ); end; { Register } function TInfoPOLTEMPLBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PCode; 2 : result := @Data.PDescription; 3 : result := @Data.PAutoCreate; end; end; end. { InfoPOLTEMPLTable }
unit SelectLenderForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Buttons, Grids, AdvGrid, FFSAdvStringGrid, TCWODT,sPanel,sBitBtn, AdvUtil, AdvObj, BaseGrid; type TfrmSelectLender = class(TForm) grdLender: TFFSAdvStringGrid; Panel1: TsPanel; btnOk: TsBitBtn; btnCancel: TsBitBtn; procedure btnOkClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure grdLenderKeyPress(Sender: TObject; var Key: Char); procedure grdLenderDblClick(Sender: TObject); private FLenderGroup: string; FColName: integer; FColNumber: integer; FLastLender:string; FPrivDaapi: IDaapiGlobal; procedure FillGrid; procedure GotoLastLender; procedure SetPrivDaapi(const Value: IDaapiGlobal); property PrivDaapi:IDaapiGlobal read FPrivDaapi write SetPrivDaapi; procedure FindFirst(c: char); procedure FindNext(c: char); public { Public declarations } constructor create(AOwner:Tcomponent; ADaapi:IDaapiGlobal;ALenderGroup:string;ALastLender:string); property CollNumber:integer read FColNumber; end; var frmSelectLender: TfrmSelectLender; implementation uses ffsutils; {$R *.DFM} procedure TfrmSelectLender.FillGrid; var x : integer; FLendList : TStringList; begin FLendList := TStringList.create; try FLendList.commatext := privdaapi.LendGrpGetListByName(FLenderGroup); if FLendList.count > 0 then grdLender.RowCount := FLendList.count + 1 else grdLender.RowCount := 2; for x := 1 to FLendList.count do grdLender.Rows[x].CommaText := PrivDaapi.LendGetShortRecord(FLendList[x-1]); finally FLendList.Free; end; grdLender.SortByColumn(FColName); end; procedure TfrmSelectLender.btnOkClick(Sender: TObject); begin ModalResult := mrOk; end; constructor TfrmSelectLender.create(AOwner:Tcomponent; ADaapi:IDaapiGlobal; ALenderGroup:string; ALastLender:string); var sl : TStringList; x,y : integer; totalWidth : integer; begin inherited create(AOwner); FLenderGroup := ALenderGroup; FLastLender := ALastLender; PrivDaapi := ADaapi; if not assigned(FPrivDaapi) then raise EDAAPINotAssigned.create; sl := TStringlist.create; try sl.commatext := PrivDaapi.LendGetLendHeaders; y := sl.count - 2; grdLender.ColCount := y div 2; grdLender.columnheaders.clear; totalwidth := 0; x := 0; while x < y do begin grdLender.Columnheaders.add(sl[x]); grdLender.Colwidths[x div 2] := StrToIntDef(sl[x+1],15); inc(totalwidth, grdLender.Colwidths[x div 2]); inc(x,2); end; self.ClientWidth := totalwidth + grdLender.ScrollWidth + 6; if self.ClientWidth < 200 then self.ClientWidth := 200; btnOk.left := (self.clientwidth - 165) div 2; btnCancel.Left := btnOk.Left + 90; FColNumber := StrToIntDef(sl[y],0); FColName := StrToIntDef(sl[y+1],1); grdLender.SortByColumn(FColName); finally sl.free; end; end; procedure TfrmSelectLender.SetPrivDaapi(const Value: IDaapiGlobal); begin FPrivDaapi := Value; end; procedure TfrmSelectLender.FormShow(Sender: TObject); begin FillGrid; GotoLastLender; end; procedure TfrmSelectLender.GotoLastLender; var x : integer; begin grdLender.Row := 1; for x := 1 to grdLender.rowcount - 1 do begin if grdLender.cells[FColNumber,x] = FLastLender then begin grdLender.Row := x; break; end; end; end; procedure TfrmSelectLender.FindFirst(c:char); var x : integer; begin x := 1; while (x < grdLender.rowcount) do begin if uppercase(copy(grdLender.cells[grdLender.SortSettings.Column, x], 1, 1)) = c then begin grdLender.Row := x; break; end else inc(x); end; end; procedure TfrmSelectLender.FindNext(c:char); var x : integer; f : boolean; begin f := false; x := grdLender.Row+1; while (x < grdLender.rowcount) do begin if uppercase(copy(grdLender.cells[grdLender.SortSettings.Column, x], 1, 1)) = c then begin grdLender.Row := x; f := true; break; end else inc(x); end; if not f then FindFirst(c); end; procedure TfrmSelectLender.grdLenderKeyPress(Sender: TObject; var Key: Char); var x : integer; c : char; begin c := upcase(key); if c in ['0'..'9','A'..'Z'] then begin if c = uppercase(copy(grdLender.cells[grdLender.SortSettings.Column, grdLender.Row], 1, 1)) then FindNext(c) else FindFirst(c); key := #0; end; end; procedure TfrmSelectLender.grdLenderDblClick(Sender: TObject); begin btnOk.Click; end; end.
PROGRAM d10b; USES sysutils, integerlist; TYPE crt = array[0..5, 0..39] of char; FUNCTION answer(filename : string) : crt; VAR f: text; l: string; x: integer = 1; cycle: 1..240; instructions: TIntegerList; row: 0..5; col: 0..39; BEGIN IF NOT FileExists(filename) THEN BEGIN writeln('file not found: ', filename); halt; END; instructions := TIntegerList.Create; assign(f, filename); reset(f); WHILE not eof(f) DO BEGIN readln(f, l); instructions.Add(0); IF copy(l, 1, 4) = 'addx' THEN instructions.Add(strToInt(copy(l, 6, length(l)-5))); END; close(f); FOR row:=low(row) TO high(row) DO FOR col:=low(col) to high(col) DO answer[row,col] := '.'; FOR cycle:=1 TO instructions.Count DO BEGIN row := (cycle-1) div 40; col := (cycle-1) mod 40; IF (x-1=col) OR (x=col) OR (x+1=col) THEN answer[row,col] := '#'; inc(x, instructions[cycle-1]); END; instructions.Free; writeln(answer[0]); writeln(answer[1]); writeln(answer[2]); writeln(answer[3]); writeln(answer[4]); writeln(answer[5]); END; VAR a: crt; BEGIN{d10b} writeln('test'); a := answer('d10.test.2'); assert(a[0] = '##..##..##..##..##..##..##..##..##..##..'); assert(a[1] = '###...###...###...###...###...###...###.'); assert(a[2] = '####....####....####....####....####....'); assert(a[3] = '#####.....#####.....#####.....#####.....'); assert(a[4] = '######......######......######......####'); assert(a[5] = '#######.......#######.......#######.....'); writeln(); writeln('answer'); a := answer('d10.input'); END.
unit K610951982; {* [Requestlink:610951982] } // Модуль: "w:\common\components\rtl\Garant\Daily\K610951982.pas" // Стереотип: "TestCase" // Элемент модели: "K610951982" MUID: (565D366A0111) // Имя типа: "TK610951982" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK610951982 = class(TRTFtoEVDWriterTest) {* [Requestlink:610951982] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK610951982 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *565D366A0111impl_uses* //#UC END# *565D366A0111impl_uses* ; function TK610951982.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.12'; end;//TK610951982.GetFolder function TK610951982.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '565D366A0111'; end;//TK610951982.GetModelElementGUID initialization TestFramework.RegisterTest(TK610951982.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
namespace Sugar.Threading; interface type {$IF COOPER} ManualResetEvent = public class private fEvent: java.util.concurrent.CountDownLatch; public constructor(InitialState: Boolean); method &Set; method Reset; locked; method WaitOne; method WaitOne(Timeout: Integer): Boolean; end; {$ELSEIF ECHOES} ManualResetEvent = public class mapped to System.Threading.ManualResetEvent public method &Set; mapped to &Set; method Reset; mapped to Reset; method WaitOne; mapped to WaitOne; method WaitOne(Timeout: Integer): Boolean; mapped to WaitOne(Timeout); end; {$ELSEIF TOFFEE} ManualResetEvent = public class end; {$ENDIF} implementation {$IF COOPER} method ManualResetEvent.&Set; begin fEvent.countDown; end; constructor ManualResetEvent(InitialState: Boolean); begin fEvent := new java.util.concurrent.CountDownLatch(iif(InitialState, 0, 1)); end; method ManualResetEvent.Reset; begin if fEvent.Count = 0 then fEvent := new java.util.concurrent.CountDownLatch(1); end; method ManualResetEvent.WaitOne; begin fEvent.await; end; method ManualResetEvent.WaitOne(Timeout: Integer): Boolean; begin exit fEvent.await(Timeout, java.util.concurrent.TimeUnit.MILLISECONDS); end; {$ENDIF} end.
unit RSStringGrid; { *********************************************************************** } { } { RSPak Copyright (c) Rozhenko Sergey } { http://sites.google.com/site/sergroj/ } { sergroj@mail.ru } { } { This file is a subject to any one of these licenses at your choice: } { BSD License, MIT License, Apache License, Mozilla Public License. } { } { *********************************************************************** } {$I RSPak.inc} interface uses Windows, Messages, SysUtils, Classes, Controls, Grids, RSCommon, RSSysUtils; {$I RSWinControlImport.inc} type TRSStringGrid = class; TRSStringGridCreateEditEvent = procedure(Sender:TStringGrid; var Editor:TInplaceEdit) of object; TRSStringGrid = class(TStringGrid) private FOnCreateParams: TRSCreateParamsEvent; FProps: TRSWinControlProps; FOnBeforeSetEditText: TGetEditEvent; FOnCreateEditor: TRSStringGridCreateEditEvent; protected procedure CreateParams(var Params:TCreateParams); override; procedure TranslateWndProc(var Msg:TMessage); procedure WndProc(var Msg:TMessage); override; function CreateEditor: TInplaceEdit; override; procedure SetEditText(ACol, ARow: Longint; const Value: string); override; procedure WMCommand(var Msg: TWMCommand); message WM_COMMAND; public constructor Create(AOwner:TComponent); override; published property OnBeforeSetEditText: TGetEditEvent read FOnBeforeSetEditText write FOnBeforeSetEditText; property OnCreateEditor: TRSStringGridCreateEditEvent read FOnCreateEditor write FOnCreateEditor; property BevelEdges; property BevelInner; property BevelKind default bkNone; property BevelOuter; property BevelWidth; property InplaceEditor; property OnCanResize; property OnResize; {$I RSWinControlProps.inc} end; procedure register; implementation procedure register; begin RegisterComponents('RSPak', [TRSStringGrid]); end; { ********************************** TRSStringGrid *********************************** } constructor TRSStringGrid.Create(AOwner:TComponent); begin inherited Create(AOwner); WindowProc:=TranslateWndProc; end; procedure TRSStringGrid.CreateParams(var Params:TCreateParams); begin inherited CreateParams(Params); if Assigned(FOnCreateParams) then FOnCreateParams(Params); end; procedure TRSStringGrid.TranslateWndProc(var Msg:TMessage); var b:boolean; begin if assigned(FProps.OnWndProc) then begin b:=false; FProps.OnWndProc(Self, Msg, b, WndProc); if b then exit; end; WndProc(Msg); end; procedure TRSStringGrid.WndProc(var Msg:TMessage); begin RSProcessProps(self, Msg, FProps); inherited; end; function TRSStringGrid.CreateEditor: TInplaceEdit; begin result:=inherited CreateEditor; if Assigned(OnCreateEditor) then OnCreateEditor(self, result); end; procedure TRSStringGrid.SetEditText(ACol, ARow: Longint; const Value: string); var v:string; begin v:=Value; if Assigned(OnBeforeSetEditText) then OnBeforeSetEditText(self, ACol, ARow, v); inherited SetEditText(ACol, ARow, v); end; // A bug that prevented ComboBox dropped on grid from showing drop-down list procedure TRSStringGrid.WMCommand(var Msg: TWMCommand); begin RSDispatchEx(self, TWinControl, Msg); inherited; end; end.
{$INCLUDE ../../flcInclude.inc} {$INCLUDE flcTestInclude.inc} unit flcTestHugeInt; interface procedure Test; implementation uses SysUtils, flcStdTypes, flcHugeInt; { } { Tests } { } {$ASSERTIONS ON} procedure Test_HugeWord; var A, B, C, D : HugeWord; X, Y : HugeInt; I : Integer; S : UTF8String; F : Word32; begin HugeWordInit(A); HugeWordInit(B); HugeWordInit(C); HugeWordInit(D); HugeIntInit(X); HugeIntInit(Y); // Zero HugeWordAssignZero(A); Assert(HugeWordGetSize(A) = 0); Assert(HugeWordIsZero(A)); Assert(HugeWordToWord32(A) = 0); Assert(HugeWordToInt32(A) = 0); Assert(HugeWordToInt64(A) = 0); Assert(HugeWordCompareWord32(A, 0) = 0); Assert(HugeWordCompareWord32(A, 1) = -1); Assert(HugeWordCompare(A, A) = 0); Assert(HugeWordIsWord32Range(A)); Assert(HugeWordIsWord64Range(A)); Assert(HugeWordIsInt32Range(A)); Assert(HugeWordIsInt64Range(A)); Assert(HugeWordIsEven(A)); Assert(not HugeWordIsOdd(A)); Assert(HugeWordToStrB(A) = '0'); Assert(HugeWordToHexB(A) = '00000000'); Assert(HugeWordSetBitScanForward(A) = -1); Assert(HugeWordSetBitScanReverse(A) = -1); Assert(HugeWordClearBitScanForward(A) = 0); Assert(HugeWordClearBitScanReverse(A) = 0); Assert(HugeWordToDouble(A) = 0.0); // One HugeWordAssignOne(A); Assert(not HugeWordIsEven(A)); Assert(HugeWordIsOdd(A)); Assert(not HugeWordIsZero(A)); Assert(HugeWordIsOne(A)); Assert(HugeWordToInt32(A) = 1); Assert(HugeWordCompareWord32(A, 0) = 1); Assert(HugeWordToHexB(A) = '00000001'); Assert(HugeWordSetBitScanForward(A) = 0); Assert(HugeWordSetBitScanReverse(A) = 0); Assert(HugeWordClearBitScanForward(A) = 1); Assert(HugeWordClearBitScanReverse(A) = 1); Assert(HugeWordToDouble(A) = 1.0); // $FFFFFFFF HugeWordAssignZero(A); HugeWordAddWord32(A, $FFFFFFFF); Assert(HugeWordGetSize(A) = 1); Assert(HugeWordGetElement(A, 0) = $FFFFFFFF); Assert(HugeWordIsWord32Range(A)); Assert(not HugeWordIsInt32Range(A)); Assert(HugeWordIsInt64Range(A)); Assert(HugeWordToWord32(A) = $FFFFFFFF); Assert(HugeWordToInt64(A) = $FFFFFFFF); Assert(not HugeWordIsZero(A)); Assert(HugeWordCompareWord32(A, 0) = 1); HugeWordAddWord32(A, $FFFFFFFF); Assert(HugeWordGetSize(A) = 2); Assert((HugeWordGetElement(A, 0) = $FFFFFFFE) and (HugeWordGetElement(A, 1) = 1)); Assert(not HugeWordIsWord32Range(A)); Assert(HugeWordToInt64(A) = $1FFFFFFFE); HugeWordAddWord32(A, $FFFFFFFF); Assert(HugeWordGetSize(A) = 2); Assert((HugeWordGetElement(A, 0) = $FFFFFFFD) and (HugeWordGetElement(A, 1) = 2)); Assert(HugeWordToInt64(A) = $2FFFFFFFD); Assert(HugeWordSubtractWord32(A, $FFFFFFFF) = 1); Assert(HugeWordGetSize(A) = 2); Assert((HugeWordGetElement(A, 0) = $FFFFFFFE) and (HugeWordGetElement(A, 1) = 1)); Assert(HugeWordSubtractWord32(A, $FFFFFFFF) = 1); Assert(HugeWordToWord32(A) = $FFFFFFFF); Assert(HugeWordSubtractWord32(A, $FFFFFFFF) = 0); Assert(HugeWordToWord32(A) = 0); Assert(HugeWordSubtractWord32(A, $FFFFFFFF) = -1); Assert(HugeWordToWord32(A) = $FFFFFFFF); Assert(HugeWordToHexB(A) = 'FFFFFFFF'); Assert(HugeWordSetBitScanForward(A) = 0); Assert(HugeWordSetBitScanReverse(A) = 31); Assert(HugeWordClearBitScanForward(A) = 32); Assert(HugeWordClearBitScanReverse(A) = 32); Assert(HugeWordToDouble(A) = 4294967295.0); // $80000000 HugeWordAssignWord32(A, $80000000); Assert(HugeWordIsWord32Range(A)); Assert(not HugeWordIsInt32Range(A)); Assert(HugeWordIsInt64Range(A)); Assert(HugeWordToWord32(A) = $80000000); Assert(HugeWordEqualsWord32(A, $80000000)); Assert(HugeWordSetBitScanForward(A) = 31); Assert(HugeWordSetBitScanReverse(A) = 31); Assert(HugeWordClearBitScanForward(A) = 0); Assert(HugeWordClearBitScanReverse(A) = 32); // $100000000 HugeWordAssignWord32(A, $80000000); HugeWordAdd(A, A); Assert(HugeWordToInt64(A) = $100000000); Assert(not HugeWordIsWord32Range(A)); Assert(HugeWordEqualsInt64(A, $100000000)); Assert(HugeWordToHexB(A) = '0000000100000000'); Assert(HugeWordSetBitScanForward(A) = 32); Assert(HugeWordSetBitScanReverse(A) = 32); Assert(HugeWordClearBitScanForward(A) = 0); Assert(HugeWordClearBitScanReverse(A) = 33); Assert(HugeWordToDouble(A) = 4294967296.0); // $1234567890ABCDEF HugeWordAssignInt64(A, $1234567890ABCDEF); Assert(HugeWordToInt64(A) = $1234567890ABCDEF); Assert(not HugeWordIsWord32Range(A)); Assert(not HugeWordIsZero(A)); Assert(HugeWordIsInt64Range(A)); Assert(HugeWordToHexB(A) = '1234567890ABCDEF'); Assert(Abs(HugeWordToDouble(A) - 1311768467294899695.0) <= 1E12); // $7654321800000000 HugeWordAssignInt64(A, $7654321800000000); Assert(HugeWordToInt64(A) = $7654321800000000); Assert(not HugeWordIsZero(A)); Assert(not HugeWordIsWord32Range(A)); Assert(not HugeWordIsInt32Range(A)); Assert(HugeWordIsInt64Range(A)); Assert(HugeWordToStrB(A) = '8526495073179795456'); Assert(HugeWordToDouble(A) = 8526495073179795456.0); Assert(HugeWordToHexB(A) = '7654321800000000'); // Swap HugeWordAssignInt32(A, 0); HugeWordAssignInt32(B, 1); HugeWordSwap(A, B); Assert(HugeWordToInt32(A) = 1); Assert(HugeWordToInt32(B) = 0); // Compare/Subtract HugeWordAssignZero(A); HugeWordAssignInt64(B, $FFFFFFFF); Assert(HugeWordToWord32(B) = $FFFFFFFF); Assert(HugeWordCompare(A, B) = -1); Assert(HugeWordCompare(B, A) = 1); Assert(HugeWordCompareWord32(B, $FFFFFFFF) = 0); Assert(HugeWordCompareWord32(B, 0) = 1); Assert(not HugeWordEquals(A, B)); Assert(HugeWordEquals(B, B)); HugeWordAdd(A, B); Assert(HugeWordGetSize(A) = 1); Assert(HugeWordGetElement(A, 0) = $FFFFFFFF); HugeWordAdd(A, B); Assert(HugeWordGetSize(A) = 2); Assert((HugeWordGetElement(A, 0) = $FFFFFFFE) and (HugeWordGetElement(A, 1) = 1)); Assert(HugeWordCompare(A, B) = 1); Assert(HugeWordCompare(B, A) = -1); HugeWordAdd(A, B); Assert(HugeWordGetSize(A) = 2); Assert((HugeWordGetElement(A, 0) = $FFFFFFFD) and (HugeWordGetElement(A, 1) = 2)); Assert(HugeWordSubtract(A, B) = 1); Assert(HugeWordGetSize(A) = 2); Assert((HugeWordGetElement(A, 0) = $FFFFFFFE) and (HugeWordGetElement(A, 1) = 1)); Assert(HugeWordSubtract(A, B) = 1); Assert(HugeWordToWord32(A) = $FFFFFFFF); Assert(HugeWordSubtract(A, B) = 0); Assert(HugeWordToWord32(A) = 0); Assert(HugeWordSubtract(A, B) = -1); Assert(HugeWordToWord32(A) = $FFFFFFFF); // And/Or/Xor/Not HugeWordAssignInt64(A, $1234678FFFFFFFF); HugeWordAssignWord32(B, 0); HugeWordAndHugeWord(B, A); Assert(HugeWordToInt64(B) = 0); HugeWordOrHugeWord(B, A); Assert(HugeWordToInt64(B) = $1234678FFFFFFFF); HugeWordXorHugeWord(B, A); Assert(HugeWordToInt64(B) = 0); HugeWordAssignInt64(A, $FFFFFFFF); HugeWordNot(A); Assert(HugeWordToWord32(A) = 0); // Shl/Shr HugeWordAssignWord32(A, $101); HugeWordShr(A, 1); Assert(HugeWordToWord32(A) = $80); HugeWordShl(A, 1); Assert(HugeWordToWord32(A) = $100); HugeWordShl1(A); Assert(HugeWordToWord32(A) = $200); HugeWordShr1(A); Assert(HugeWordToWord32(A) = $100); // Shl1/Shl/Shr1/Shr HugeWordAssignWord32(A, 1); HugeWordAssignWord32(B, 1); for I := 0 to 50 do begin Assert(HugeWordToInt64(A) = Int64(1) shl I); Assert(HugeWordToInt64(B) = Int64(1) shl I); HugeWordShl1(A); HugeWordShl(B, 1); end; for I := 1 to 32 do HugeWordShl1(A); HugeWordShl(B, 32); Assert(HugeWordEquals(A, B)); for I := 1 to 1000 do HugeWordShl1(A); HugeWordShl(B, 1000); Assert(HugeWordEquals(A, B)); for I := 1 to 1032 do HugeWordShr1(A); HugeWordShr(B, 1000); HugeWordShr(B, 32); HugeWordNormalise(A); HugeWordNormalise(B); Assert(HugeWordEquals(A, B)); for I := 51 downto 1 do begin Assert(HugeWordToInt64(A) = Int64(1) shl I); Assert(HugeWordToInt64(B) = Int64(1) shl I); HugeWordShr1(A); HugeWordShr(B, 1); HugeWordNormalise(A); HugeWordNormalise(B); end; // Shl/Shr HugeWordAssignInt64(A, $1234678FFFFFFFF); HugeWordShl1(A); Assert(HugeWordToInt64(A) = $2468CF1FFFFFFFE); HugeWordShr1(A); Assert(HugeWordToInt64(A) = $1234678FFFFFFFF); // Add/Subtract HugeWordAssignZero(A); HugeWordAddWord32(A, 1); Assert(HugeWordToWord32(A) = 1); Assert(HugeWordSubtractWord32(A, 1) = 0); Assert(HugeWordToWord32(A) = 0); Assert(HugeWordSubtractWord32(A, 1) = -1); Assert(HugeWordToWord32(A) = 1); // Add/Subtract HugeWordAssignZero(A); HugeWordAssignWord32(B, 1); HugeWordAdd(A, B); Assert(HugeWordToWord32(A) = 1); Assert(HugeWordSubtract(A, B) = 0); Assert(HugeWordToWord32(A) = 0); Assert(HugeWordSubtract(A, B) = -1); Assert(HugeWordToWord32(A) = 1); // Add/Subtract HugeWordAssignInt64(A, $FFFFFFFF); HugeWordAddWord32(A, 1); Assert(HugeWordGetSize(A) = 2); Assert((HugeWordGetElement(A, 0) = 0) and (HugeWordGetElement(A, 1) = 1)); Assert(HugeWordSubtractWord32(A, 1) = 1); Assert(HugeWordToWord32(A) = $FFFFFFFF); Assert(HugeWordSubtractWord32(A, 1) = 1); Assert(HugeWordToWord32(A) = $FFFFFFFE); // Add/Subtract HugeWordAssignInt64(A, $FFFFFFFF); HugeWordAssignWord32(B, 1); HugeWordAdd(A, B); Assert(HugeWordGetSize(A) = 2); Assert((HugeWordGetElement(A, 0) = 0) and (HugeWordGetElement(A, 1) = 1)); Assert(HugeWordSubtract(A, B) = 1); Assert(HugeWordToWord32(A) = $FFFFFFFF); Assert(HugeWordSubtract(A, B) = 1); Assert(HugeWordToWord32(A) = $FFFFFFFE); // Add/Subtract StrToHugeWordB('111111111111111111111111111111111111111111111111111111111', A); StrToHugeWordB('222222222222222222222222222222222222222222222222222222222', B); HugeWordAdd(A, B); Assert(HugeWordToStrB(A) = '333333333333333333333333333333333333333333333333333333333'); HugeWordSubtract(A, B); Assert(HugeWordToStrB(A) = '111111111111111111111111111111111111111111111111111111111'); HugeWordSubtract(A, A); Assert(HugeWordIsZero(A)); // Multiply/Divide HugeWordAssignWord32(A, $10000000); HugeWordAssignWord32(B, $20000000); HugeWordMultiply(C, A, B); Assert(HugeWordToInt64(C) = $200000000000000); HugeWordDivide(C, B, D, C); Assert(HugeWordToInt64(D) = $10000000); Assert(HugeWordIsZero(C)); // Multiply/Divide StrToHugeWordB('111111111111111111111111111111111111', A); StrToHugeWordB('100000000000000000000000000000000000', B); HugeWordMultiply(C, A, B); Assert(HugeWordToStrB(A) = '111111111111111111111111111111111111'); Assert(HugeWordToStrB(C) = '11111111111111111111111111111111111100000000000000000000000000000000000'); HugeWordDivide(C, B, D, C); Assert(HugeWordToStrB(D) = '111111111111111111111111111111111111'); Assert(HugeWordToStrB(C) = '0'); HugeWordMultiplyWord8(D, 10); Assert(HugeWordToStrB(D) = '1111111111111111111111111111111111110'); HugeWordMultiplyWord16(D, 100); Assert(HugeWordToStrB(D) = '111111111111111111111111111111111111000'); HugeWordMultiplyWord32(D, 1000); Assert(HugeWordToStrB(D) = '111111111111111111111111111111111111000000'); HugeWordDivideWord32(D, 1000000, D, F); Assert(HugeWordToStrB(D) = '111111111111111111111111111111111111'); Assert(F = 0); StrToHugeWordB('1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', A); StrToHugeWordB('1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', B); HugeWordMultiply(C, A, B); Assert(HugeWordToStrB(C) = '1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'); // Multiply_ShiftAdd StrToHugeWordB('111111111111111111111111111111111111', A); StrToHugeWordB('100000000000000000000000000000000000', B); HugeWordMultiply_ShiftAdd(C, A, B); Assert(HugeWordToStrB(C) = '11111111111111111111111111111111111100000000000000000000000000000000000'); StrToHugeWordB('1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', A); StrToHugeWordB('1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', B); HugeWordMultiply_ShiftAdd(C, A, B); Assert(HugeWordToStrB(C) = '1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'); // Multiply_Karatsuba StrToHugeWordB('111111111111111111111111111111111111', A); StrToHugeWordB('100000000000000000000000000000000000', B); HugeWordMultiply_Karatsuba(C, A, B); Assert(HugeWordToStrB(C) = '11111111111111111111111111111111111100000000000000000000000000000000000'); StrToHugeWordB('1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111', A); StrToHugeWordB('1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000', B); HugeWordMultiply_Karatsuba(C, A, B); Assert(HugeWordToStrB(C) = '1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'); // ISqrt/Sqr HugeWordAssignWord32(A, $FFFF); HugeWordISqrt(A); Assert(HugeWordToInt64(A) = $FF); HugeWordAssignWord32(A, $10000); HugeWordISqrt(A); Assert(HugeWordToInt64(A) = $100); HugeWordAssignInt64(A, $FFFFFFFF); HugeWordISqrt(A); Assert(HugeWordToInt64(A) = $FFFF); HugeWordAssignInt64(A, $100000000); HugeWordISqrt(A); Assert(HugeWordToInt64(A) = $10000); HugeWordAssignInt64(A, $10000FFFF); HugeWordISqrt(A); Assert(HugeWordToInt64(A) = $10000); StrToHugeWordB('10000000000000000000000000000000000000000', A); HugeWordISqrt(A); Assert(HugeWordToStrB(A) = '100000000000000000000'); HugeWordSqr(A, A); Assert(HugeWordToStrB(A) = '10000000000000000000000000000000000000000'); HugeWordAssignWord32(A, $10000000); HugeWordSqr(A, A); Assert(HugeWordToInt64(A) = $100000000000000); HugeWordISqrt(A); Assert(HugeWordToInt64(A) = $10000000); // GCD HugeWordAssignWord32(A, 111); HugeWordAssignWord32(B, 159); HugeWordGCD(A, B, C); Assert(HugeWordToStrB(C) = '3'); // GCD StrToHugeWordB('359334085968622831041960188598043661065388726959079837', A); // Bell number prime StrToHugeWordB('1298074214633706835075030044377087', B); // Carol prime HugeWordGCD(A, B, C); Assert(HugeWordToStrB(C) = '1'); // PowerAndMod HugeWordAssignWord32(A, 3); HugeWordAssignWord32(B, 500); HugeWordAssignWord32(C, 5); HugeWordPowerAndMod(D, A, B, C); Assert(HugeWordToStrB(D) = '1'); // PowerAndMod HugeWordAssignWord32(A, 3); HugeWordAssignWord32(B, 123456); HugeWordAssignWord32(C, 7); HugeWordPowerAndMod(D, A, B, C); Assert(HugeWordToStrB(D) = '1'); // PowerAndMod HugeWordAssignWord32(A, 2905); HugeWordAssignWord32(B, 323); HugeWordAssignWord32(C, 245363); HugeWordPowerAndMod(D, A, B, C); Assert(HugeWordToStrB(D) = '13388'); // PowerAndMod StrToHugeWordB('9999999999', A); HugeWordAssignWord32(B, 10); HugeWordPower(B, 100); HugeWordAssignWord32(C, 700); HugeWordPowerAndMod(D, A, B, C); Assert(HugeWordToStrB(D) = '501'); // Power/Mod HugeWordAssignWord32(A, 3); HugeWordAssignWord32(C, 5); HugeWordPower(A, 500); Assert(HugeWordToStrB(A) = '36360291795869936842385267079543319118023385026001623040346035832580600191583895' + '48419850826297938878330817970253440385575285593151701306614299243091656202578002' + '1771247847643450125342836565813209972590371590152578728008385990139795377610001'); HugeWordMod(A, C, D); Assert(HugeWordToStrB(D) = '1'); // Power/Mod HugeWordAssignWord32(A, 3); HugeWordAssignWord32(C, 7); HugeWordPower(A, 123456); HugeWordMod(A, C, D); Assert(HugeWordToStrB(D) = '1'); // Power HugeWordAssignZero(A); HugeWordPower(A, 0); Assert(HugeWordToInt32(A) = 1); HugeWordAssignZero(A); HugeWordPower(A, 1); Assert(HugeWordToInt32(A) = 0); HugeWordAssignOne(A); HugeWordPower(A, 0); Assert(HugeWordToInt32(A) = 1); HugeWordAssignOne(A); HugeWordPower(A, 1); Assert(HugeWordToInt32(A) = 1); // AssignDouble HugeWordAssignDouble(A, 0.0); Assert(HugeWordToInt64(A) = 0); HugeWordAssignDouble(A, 1.0); Assert(HugeWordToInt64(A) = 1); HugeWordAssignDouble(A, 4294967295.0); Assert(HugeWordToInt64(A) = $FFFFFFFF); HugeWordAssignDouble(A, 4294967296.0); Assert(HugeWordToInt64(A) = $100000000); // HexTo/ToHex HexToHugeWordB('0', A); Assert(HugeWordToHexB(A) = '00000000'); StrToHugeWordB('123456789', A); Assert(HugeWordToHexB(A) = '075BCD15'); HexToHugeWordB('123456789ABCDEF', A); Assert(HugeWordToHexB(A) = '0123456789ABCDEF'); Assert(HugeWordToStrB(A) = '81985529216486895'); HexToHugeWordB('0123456789ABCDEF00112233F', A); Assert(HugeWordToHexB(A) = '00000000123456789ABCDEF00112233F'); // StrTo/ToStr StrToHugeWordB('12345', A); Assert(HugeWordToWord32(A) = 12345); Assert(HugeWordToStrB(A) = '12345'); // StrTo/ToStr S := '123456789012345678901234567890123456789012345678901234567890'; StrToHugeWordB(S, A); for I := 1 to 100 do begin HugeWordMultiplyWord8(A, 10); S := S + '0'; Assert(HugeWordToStrB(A) = S); StrToHugeWordB(S, B); Assert(HugeWordEquals(A, B)); end; // Prime HugeWordAssignWord32(A, 1); Assert(HugeWordIsPrime(A) = pNotPrime); HugeWordAssignWord32(A, 31); Assert(HugeWordIsPrime(A) = pPrime); HugeWordAssignWord32(A, 982451653); Assert(HugeWordIsPrime(A) <> pNotPrime); HugeWordAssignWord32(A, 3464946713); Assert(HugeWordIsPrime(A) <> pNotPrime); HugeWordAssignWord32(A, 3464946767); Assert(HugeWordIsPrime(A) = pNotPrime); HugeWordAssignWord32(A, 3464946769); Assert(HugeWordIsPrime(A) <> pNotPrime); StrToHugeWordB('359334085968622831041960188598043661065388726959079837', A); // Bell number prime Assert(HugeWordIsPrime(A) <> pNotPrime); StrToHugeWordB('1298074214633706835075030044377087', A); // Carol prime Assert(HugeWordIsPrime(A) <> pNotPrime); StrToHugeWordB('393050634124102232869567034555427371542904833', A); // Cullen prime Assert(HugeWordIsPrime(A) <> pNotPrime); StrToHugeWordB('8683317618811886495518194401279999999', A); // Factorial prime Assert(HugeWordIsPrime(A) <> pNotPrime); StrToHugeWordB('19134702400093278081449423917', A); // Fibonacci prime Assert(HugeWordIsPrime(A) <> pNotPrime); StrToHugeWordB('1363005552434666078217421284621279933627102780881053358473', A); // Padovan prime Assert(HugeWordIsPrime(A) <> pNotPrime); StrToHugeWordB('1363005552434666078217421284621279933627102780881053358473', A); // Padovan prime HugeWordNextPotentialPrime(A); Assert(HugeWordToStrB(A) = '1363005552434666078217421284621279933627102780881053358551'); HugeWordAssignWord32(A, 340561); // Carmichael number 340561 = 13 * 17 * 23 * 67 Assert(HugeWordIsPrime(A) = pNotPrime); HugeWordAssignWord32(A, 82929001); // Carmichael number 82929001 = 281 * 421 * 701 Assert(HugeWordIsPrime(A) = pNotPrime); StrToHugeWordB('975177403201', A); // Carmichael number 975177403201 = 2341 * 2861 * 145601 Assert(HugeWordIsPrime(A) = pNotPrime); StrToHugeWordB('989051977369', A); // Carmichael number 989051977369 = 173 * 36809 * 155317 Assert(HugeWordIsPrime(A) = pNotPrime); StrToHugeWordB('999629786233', A); // Carmichael number 999629786233 = 13 * 43 * 127 * 1693 * 8317 Assert(HugeWordIsPrime(A) = pNotPrime); // ExtendedEuclid HugeWordAssignWord32(A, 120); HugeWordAssignWord32(B, 23); HugeWordExtendedEuclid(A, B, C, X, Y); Assert(HugeWordToWord32(C) = 1); Assert(HugeIntToInt32(X) = -9); Assert(HugeIntToInt32(Y) = 47); // ExtendedEuclid HugeWordAssignWord32(A, 11391); HugeWordAssignWord32(B, 5673); HugeWordExtendedEuclid(A, B, C, X, Y); Assert(HugeWordToWord32(C) = 3); Assert(HugeIntToInt32(X) = -126); Assert(HugeIntToInt32(Y) = 253); // ModInv HugeWordAssignWord32(A, 3); HugeWordAssignWord32(B, 26); Assert(HugeWordModInv(A, B, C)); Assert(HugeWordToWord32(C) = 9); // ModInv HugeWordAssignWord32(A, 6); HugeWordAssignWord32(B, 3); Assert(not HugeWordModInv(A, B, C)); // ModInv HugeWordAssignWord32(A, 31); HugeWordAssignWord32(B, 8887231); Assert(HugeWordModInv(A, B, C)); Assert(HugeWordToWord32(C) = 2293479); // ModInv HugeWordAssignWord32(A, 999961543); StrToHugeWordB('3464946713311', B); Assert(HugeWordModInv(A, B, C)); Assert(HugeWordToStrB(C) = '2733464305244'); HugeIntFinalise(Y); HugeIntFinalise(X); HugeWordFinalise(D); HugeWordFinalise(C); HugeWordFinalise(B); HugeWordFinalise(A); end; procedure Test_HugeInt; var A, B, C, D : HugeInt; F : HugeWord; K : Word32; L : Int32; begin HugeIntInit(A); HugeIntInit(B); HugeIntInit(C); HugeIntInit(D); HugeWordInit(F); // Zero HugeIntAssignZero(A); Assert(HugeIntIsZero(A)); Assert(HugeIntIsPositiveOrZero(A)); Assert(HugeIntIsNegativeOrZero(A)); Assert(not HugeIntIsPositive(A)); Assert(not HugeIntIsNegative(A)); Assert(HugeIntIsInt32Range(A)); Assert(HugeIntIsWord32Range(A)); Assert(HugeIntToStrB(A) = '0'); Assert(HugeIntToHexB(A) = '00000000'); Assert(HugeIntToWord32(A) = 0); Assert(HugeIntToInt32(A) = 0); Assert(HugeIntToDouble(A) = 0.0); StrToHugeIntB('0', A); Assert(HugeIntIsZero(A)); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = 1); Assert(HugeIntCompareInt64(A, $7FFFFFFFFFFFFFFF) = -1); Assert(not HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); HugeIntAddInt32(A, 0); Assert(HugeIntIsZero(A)); HugeIntSubtractInt32(A, 0); Assert(HugeIntIsZero(A)); HugeIntMultiplyInt8(A, 0); Assert(HugeIntIsZero(A)); HugeIntMultiplyInt8(A, 1); Assert(HugeIntIsZero(A)); HugeIntMultiplyInt8(A, -1); Assert(HugeIntIsZero(A)); HugeIntMultiplyWord8(A, 0); Assert(HugeIntIsZero(A)); HugeIntMultiplyWord8(A, 1); Assert(HugeIntIsZero(A)); HugeIntMultiplyHugeWord(A, F); Assert(HugeIntIsZero(A)); HugeIntMultiplyHugeInt(A, A); Assert(HugeIntIsZero(A)); HugeIntSqr(A); Assert(HugeIntIsZero(A)); HugeIntISqrt(A); Assert(HugeIntIsZero(A)); // One HugeIntAssignOne(A); Assert(not HugeIntIsZero(A)); Assert(HugeIntIsPositiveOrZero(A)); Assert(not HugeIntIsNegativeOrZero(A)); Assert(HugeIntIsOne(A)); Assert(not HugeIntIsMinusOne(A)); Assert(HugeIntToStrB(A) = '1'); Assert(HugeIntToHexB(A) = '00000001'); Assert(HugeIntIsPositive(A)); Assert(not HugeIntIsNegative(A)); Assert(HugeIntIsInt32Range(A)); Assert(HugeIntIsWord32Range(A)); Assert(HugeIntToDouble(A) = 1.0); StrToHugeIntB('1', A); Assert(HugeIntIsOne(A)); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = 1); Assert(HugeIntCompareInt64(A, $7FFFFFFFFFFFFFFF) = -1); Assert(not HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); HugeIntAddInt32(A, 0); Assert(HugeIntIsOne(A)); HugeIntSubtractInt32(A, 0); Assert(HugeIntIsOne(A)); HugeIntMultiplyInt8(A, 1); Assert(HugeIntIsOne(A)); HugeIntMultiplyInt8(A, -1); Assert(HugeIntIsMinusOne(A)); HugeIntMultiplyInt8(A, -1); Assert(HugeIntIsOne(A)); HugeIntMultiplyWord8(A, 1); Assert(HugeIntIsOne(A)); HugeIntSqr(A); Assert(HugeIntIsOne(A)); HugeIntISqrt(A); Assert(HugeIntIsOne(A)); // MinusOne HugeIntAssignMinusOne(A); Assert(not HugeIntIsZero(A)); Assert(not HugeIntIsPositiveOrZero(A)); Assert(HugeIntIsNegativeOrZero(A)); Assert(not HugeIntIsOne(A)); Assert(HugeIntIsMinusOne(A)); Assert(HugeIntToStrB(A) = '-1'); Assert(HugeIntToHexB(A) = '-00000001'); Assert(not HugeIntIsPositive(A)); Assert(HugeIntIsNegative(A)); Assert(HugeIntIsInt32Range(A)); Assert(HugeIntIsInt64Range(A)); Assert(not HugeIntIsWord32Range(A)); Assert(HugeIntToDouble(A) = -1.0); StrToHugeIntB('-1', A); Assert(HugeIntIsMinusOne(A)); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = 1); Assert(HugeIntCompareInt64(A, $7FFFFFFFFFFFFFFF) = -1); Assert(not HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); HugeIntMultiplyInt8(A, 1); Assert(HugeIntIsMinusOne(A)); HugeIntAddWord32(A, 1); Assert(HugeIntIsZero(A)); HugeIntAddInt32(A, -1); Assert(HugeIntIsMinusOne(A)); HugeIntAddInt32(A, 0); Assert(HugeIntIsMinusOne(A)); HugeIntSubtractInt32(A, 0); Assert(HugeIntIsMinusOne(A)); HugeWordAssignHugeIntAbs(F, A); Assert(HugeWordIsOne(F)); // MinInt64 (-$8000000000000000) HugeIntAssignInt64(A, MinInt64 { -$8000000000000000 }); Assert(HugeIntToInt64(A) = MinInt64 { -$8000000000000000 }); Assert(HugeIntToStrB(A) = '-9223372036854775808'); Assert(HugeIntToHexB(A) = '-8000000000000000'); Assert(HugeIntToDouble(A) = -9223372036854775808.0); Assert(HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); Assert(not HugeIntEqualsInt64(A, MinInt32 { -$80000000 })); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = 0); Assert(HugeIntCompareInt64(A, -$7FFFFFFFFFFFFFFF) = -1); Assert(not HugeIntIsInt32Range(A)); Assert(HugeIntIsInt64Range(A)); StrToHugeIntB('-9223372036854775808', A); Assert(HugeIntToStrB(A) = '-9223372036854775808'); HugeIntAbsInPlace(A); Assert(HugeIntToStrB(A) = '9223372036854775808'); Assert(HugeIntToHexB(A) = '8000000000000000'); Assert(not HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = 1); Assert(not HugeIntIsInt64Range(A)); HugeIntNegate(A); Assert(HugeIntToInt64(A) = MinInt64 { -$8000000000000000 }); // MinInt64 + 1 (-$7FFFFFFFFFFFFFFF) HugeIntAssignInt64(A, -$7FFFFFFFFFFFFFFF); Assert(HugeIntToInt64(A) = -$7FFFFFFFFFFFFFFF); Assert(HugeIntToStrB(A) = '-9223372036854775807'); Assert(HugeIntToHexB(A) = '-7FFFFFFFFFFFFFFF'); {$IFNDEF DELPHIXE2_UP} {$IFNDEF FREEPASCAL} {$IFNDEF CPU_32} Assert(HugeIntToDouble(A) = Double(-9223372036854775807.0)); {$ENDIF} {$ENDIF} {$ENDIF} Assert(HugeIntEqualsInt64(A, -$7FFFFFFFFFFFFFFF)); Assert(not HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); Assert(HugeIntCompareInt64(A, -$7FFFFFFFFFFFFFFE) = -1); Assert(HugeIntCompareInt64(A, -$7FFFFFFFFFFFFFFF) = 0); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = 1); Assert(HugeIntIsInt64Range(A)); HugeIntAbsInPlace(A); Assert(HugeIntToStrB(A) = '9223372036854775807'); Assert(HugeIntToHexB(A) = '7FFFFFFFFFFFFFFF'); Assert(HugeIntToInt64(A) = $7FFFFFFFFFFFFFFF); Assert(HugeIntEqualsInt64(A, $7FFFFFFFFFFFFFFF)); Assert(not HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = 1); Assert(HugeIntIsInt64Range(A)); HugeIntNegate(A); Assert(HugeIntToInt64(A) = -$7FFFFFFFFFFFFFFF); // MinInt64 - 1 (-$8000000000000001) HugeIntAssignInt64(A, MinInt64 { -$8000000000000000 }); HugeIntSubtractInt32(A, 1); Assert(HugeIntToStrB(A) = '-9223372036854775809'); Assert(HugeIntToHexB(A) = '-8000000000000001'); {$IFNDEF DELPHIXE2_UP} {$IFNDEF FREEPASCAL} {$IFNDEF CPU_32} Assert(HugeIntToDouble(A) = Double(-9223372036854775809.0)); {$ENDIF} {$ENDIF} {$ENDIF} Assert(not HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = -1); Assert(not HugeIntIsInt64Range(A)); HugeIntAbsInPlace(A); Assert(HugeIntToStrB(A) = '9223372036854775809'); Assert(not HugeIntEqualsInt64(A, MinInt64 { -$8000000000000000 })); Assert(HugeIntCompareInt64(A, MinInt64 { -$8000000000000000 }) = 1); HugeIntNegate(A); Assert(HugeIntToStrB(A) = '-9223372036854775809'); // Equals/Compare HugeIntAssignInt32(A, -1); HugeIntAssignWord32(B, 2); HugeIntAssignZero(C); Assert(HugeIntEqualsInt32(A, -1)); Assert(not HugeIntEqualsInt32(A, 1)); Assert(HugeIntEqualsWord32(B, 2)); Assert(HugeIntEqualsInt32(B, 2)); Assert(not HugeIntEqualsInt32(B, -2)); Assert(HugeIntEqualsInt32(C, 0)); Assert(HugeIntEqualsWord32(C, 0)); Assert(not HugeIntEqualsWord32(C, 1)); Assert(HugeIntEqualsInt64(C, 0)); Assert(not HugeIntEqualsInt64(A, 1)); Assert(HugeIntCompareWord32(A, 0) = -1); Assert(HugeIntCompareWord32(A, 1) = -1); Assert(HugeIntCompareWord32(B, 1) = 1); Assert(HugeIntCompareWord32(B, 2) = 0); Assert(HugeIntCompareWord32(C, 0) = 0); Assert(HugeIntCompareWord32(C, 1) = -1); Assert(HugeIntCompareInt32(A, 0) = -1); Assert(HugeIntCompareInt32(A, -1) = 0); Assert(HugeIntCompareInt32(A, -2) = 1); Assert(HugeIntCompareInt32(C, -1) = 1); Assert(HugeIntCompareInt32(C, 0) = 0); Assert(HugeIntCompareInt32(C, 1) = -1); Assert(HugeIntCompareInt64(A, 0) = -1); Assert(HugeIntCompareInt64(A, -1) = 0); Assert(HugeIntCompareInt64(A, -2) = 1); Assert(HugeIntCompareInt64(C, 0) = 0); Assert(HugeIntCompareInt64(C, 1) = -1); Assert(not HugeIntEqualsHugeInt(A, B)); Assert(not HugeIntEqualsHugeInt(B, C)); Assert(HugeIntEqualsHugeInt(A, A)); Assert(HugeIntEqualsHugeInt(B, B)); Assert(HugeIntEqualsHugeInt(C, C)); Assert(HugeIntCompareHugeInt(A, B) = -1); Assert(HugeIntCompareHugeInt(B, A) = 1); Assert(HugeIntCompareHugeInt(A, A) = 0); Assert(HugeIntCompareHugeInt(B, B) = 0); Assert(HugeIntCompareHugeInt(C, A) = 1); Assert(HugeIntCompareHugeInt(C, B) = -1); Assert(HugeIntCompareHugeInt(C, C) = 0); Assert(HugeIntCompareHugeInt(A, C) = -1); Assert(HugeIntCompareHugeInt(B, C) = 1); Assert(HugeIntCompareHugeIntAbs(A, B) = -1); Assert(HugeIntCompareHugeIntAbs(B, A) = 1); Assert(HugeIntCompareHugeIntAbs(A, C) = 1); Assert(HugeIntCompareHugeIntAbs(B, C) = 1); Assert(HugeIntCompareHugeIntAbs(C, A) = -1); Assert(HugeIntCompareHugeIntAbs(C, B) = -1); Assert(HugeIntCompareHugeIntAbs(A, A) = 0); Assert(HugeIntCompareHugeIntAbs(B, B) = 0); Assert(HugeIntCompareHugeIntAbs(C, C) = 0); // Min/Max HugeIntAssignInt32(A, -1); HugeIntAssignInt32(B, 0); HugeIntAssignInt32(C, 1); HugeIntMin(A, B); Assert(HugeIntToInt32(A) = -1); HugeIntMin(B, A); Assert(HugeIntToInt32(B) = -1); HugeIntMax(C, A); Assert(HugeIntToInt32(C) = 1); HugeIntMax(A, C); Assert(HugeIntToInt32(A) = 1); // Swap HugeIntAssignInt32(A, 0); HugeIntAssignInt32(B, 1); HugeIntSwap(A, B); Assert(HugeIntToInt32(A) = 1); Assert(HugeIntToInt32(B) = 0); // Add/Subtract HugeIntAssignInt32(A, 0); HugeIntAssignInt32(B, 1); HugeIntAssignInt32(C, -1); HugeIntAddHugeInt(A, B); Assert(HugeIntToInt32(A) = 1); HugeIntAddHugeInt(A, B); Assert(HugeIntToInt32(A) = 2); HugeIntAddHugeInt(A, C); Assert(HugeIntToInt32(A) = 1); HugeIntAddHugeInt(A, C); Assert(HugeIntToInt32(A) = 0); HugeIntAddHugeInt(A, C); Assert(HugeIntToInt32(A) = -1); HugeIntAddHugeInt(A, C); Assert(HugeIntToInt32(A) = -2); HugeIntAddHugeInt(A, B); Assert(HugeIntToInt32(A) = -1); HugeIntAddHugeInt(A, B); Assert(HugeIntToInt32(A) = 0); HugeIntAddHugeInt(A, B); Assert(HugeIntToInt32(A) = 1); HugeIntSubtractHugeInt(A, B); Assert(HugeIntToInt32(A) = 0); HugeIntSubtractHugeInt(A, B); Assert(HugeIntToInt32(A) = -1); HugeIntSubtractHugeInt(A, B); Assert(HugeIntToInt32(A) = -2); HugeIntSubtractHugeInt(A, C); Assert(HugeIntToInt32(A) = -1); HugeIntSubtractHugeInt(A, C); Assert(HugeIntToInt32(A) = 0); HugeIntSubtractHugeInt(A, C); Assert(HugeIntToInt32(A) = 1); HugeIntSubtractHugeInt(A, C); Assert(HugeIntToInt32(A) = 2); // Add/Subtract HugeIntAssignInt32(A, 0); HugeIntAddInt32(A, 1); Assert(HugeIntToInt32(A) = 1); HugeIntAddInt32(A, -1); Assert(HugeIntToInt32(A) = 0); HugeIntAddInt32(A, -1); Assert(HugeIntToInt32(A) = -1); HugeIntAddInt32(A, -1); Assert(HugeIntToInt32(A) = -2); HugeIntAddInt32(A, 1); Assert(HugeIntToInt32(A) = -1); HugeIntAddInt32(A, 1); Assert(HugeIntToInt32(A) = 0); HugeIntAddInt32(A, 1); Assert(HugeIntToInt32(A) = 1); HugeIntAddInt32(A, 1); Assert(HugeIntToInt32(A) = 2); HugeIntSubtractInt32(A, 1); Assert(HugeIntToInt32(A) = 1); HugeIntSubtractInt32(A, 1); Assert(HugeIntToInt32(A) = 0); HugeIntSubtractInt32(A, 1); Assert(HugeIntToInt32(A) = -1); HugeIntSubtractInt32(A, 1); Assert(HugeIntToInt32(A) = -2); HugeIntSubtractInt32(A, -1); Assert(HugeIntToInt32(A) = -1); HugeIntSubtractInt32(A, -1); Assert(HugeIntToInt32(A) = 0); HugeIntSubtractInt32(A, -1); Assert(HugeIntToInt32(A) = 1); HugeIntSubtractInt32(A, -1); Assert(HugeIntToInt32(A) = 2); // Add/Subtract HugeIntAssignInt32(A, -1); HugeIntAddWord32(A, 1); Assert(HugeIntToInt32(A) = 0); HugeIntAddWord32(A, 1); Assert(HugeIntToInt32(A) = 1); HugeIntAddWord32(A, 1); Assert(HugeIntToInt32(A) = 2); HugeIntSubtractWord32(A, 1); Assert(HugeIntToInt32(A) = 1); HugeIntSubtractWord32(A, 1); Assert(HugeIntToInt32(A) = 0); HugeIntSubtractWord32(A, 1); Assert(HugeIntToInt32(A) = -1); HugeIntSubtractWord32(A, 1); Assert(HugeIntToInt32(A) = -2); // Multiply HugeIntAssignInt32(A, 10); HugeIntMultiplyWord8(A, 10); Assert(HugeIntToInt32(A) = 100); HugeIntMultiplyWord16(A, 10); Assert(HugeIntToInt32(A) = 1000); HugeIntMultiplyWord32(A, 10); Assert(HugeIntToInt32(A) = 10000); HugeIntAssignInt32(A, -10); HugeIntMultiplyWord8(A, 10); Assert(HugeIntToInt32(A) = -100); HugeIntMultiplyWord16(A, 10); Assert(HugeIntToInt32(A) = -1000); HugeIntMultiplyWord32(A, 10); Assert(HugeIntToInt32(A) = -10000); // Multiply HugeIntAssignInt32(A, -10); HugeIntMultiplyInt8(A, -10); Assert(HugeIntToInt32(A) = 100); HugeIntMultiplyInt8(A, 10); Assert(HugeIntToInt32(A) = 1000); HugeIntMultiplyInt8(A, -10); Assert(HugeIntToInt32(A) = -10000); HugeIntMultiplyInt8(A, 10); Assert(HugeIntToInt32(A) = -100000); HugeIntMultiplyInt8(A, 0); Assert(HugeIntToInt32(A) = 0); // Multiply HugeIntAssignInt32(A, -10); HugeIntMultiplyInt16(A, -10); Assert(HugeIntToInt32(A) = 100); HugeIntMultiplyInt16(A, 10); Assert(HugeIntToInt32(A) = 1000); HugeIntMultiplyInt16(A, -10); Assert(HugeIntToInt32(A) = -10000); HugeIntMultiplyInt16(A, 10); Assert(HugeIntToInt32(A) = -100000); HugeIntMultiplyInt16(A, 0); Assert(HugeIntToInt32(A) = 0); // Multiply HugeIntAssignInt32(A, -10); HugeIntMultiplyInt32(A, -10); Assert(HugeIntToInt32(A) = 100); HugeIntMultiplyInt32(A, 10); Assert(HugeIntToInt32(A) = 1000); HugeIntMultiplyInt32(A, -10); Assert(HugeIntToInt32(A) = -10000); HugeIntMultiplyInt32(A, 10); Assert(HugeIntToInt32(A) = -100000); HugeIntMultiplyInt32(A, 0); Assert(HugeIntToInt32(A) = 0); // Multiply HugeIntAssignInt32(A, 10); HugeIntAssignInt32(B, 10); HugeIntAssignInt32(C, -10); HugeIntMultiplyHugeInt(A, B); Assert(HugeIntToInt32(A) = 100); HugeIntMultiplyHugeInt(A, C); Assert(HugeIntToInt32(A) = -1000); HugeIntMultiplyHugeInt(A, B); Assert(HugeIntToInt32(A) = -10000); HugeIntMultiplyHugeInt(A, C); Assert(HugeIntToInt32(A) = 100000); HugeIntAssignInt32(B, 1); HugeIntMultiplyHugeInt(A, B); Assert(HugeIntToInt32(A) = 100000); HugeIntAssignInt32(B, -1); HugeIntMultiplyHugeInt(A, B); Assert(HugeIntToInt32(A) = -100000); HugeIntAssignInt32(B, 0); HugeIntMultiplyHugeInt(A, B); Assert(HugeIntToInt32(A) = 0); // Multiply HugeIntAssignInt32(A, 10); HugeWordAssignWord32(F, 10); HugeIntMultiplyHugeWord(A, F); Assert(HugeIntToInt32(A) = 100); HugeIntAssignInt32(A, -10); HugeIntMultiplyHugeWord(A, F); Assert(HugeIntToInt32(A) = -100); // Sqr HugeIntAssignInt32(A, -17); HugeIntSqr(A); Assert(HugeIntToInt32(A) = 289); // ISqrt HugeIntAssignInt32(A, 289); HugeIntISqrt(A); Assert(HugeIntToInt32(A) = 17); // Divide HugeIntAssignInt32(A, -1000); HugeIntDivideWord32(A, 3, B, K); Assert(HugeIntToInt32(B) = -333); Assert(K = 1); // Divide HugeIntAssignInt32(A, -1000); HugeIntDivideInt32(A, 3, B, L); Assert(HugeIntToInt32(B) = -333); Assert(L = 1); HugeIntDivideInt32(A, -3, B, L); Assert(HugeIntToInt32(B) = 333); Assert(L = 1); HugeIntAssignInt32(A, 1000); HugeIntDivideInt32(A, 3, B, L); Assert(HugeIntToInt32(B) = 333); Assert(L = 1); HugeIntDivideInt32(A, -3, B, L); Assert(HugeIntToInt32(B) = -333); Assert(L = 1); // Divide HugeIntAssignInt32(A, -1000); HugeIntAssignInt32(B, 3); HugeIntDivideHugeInt(A, B, C, D); Assert(HugeIntToInt32(C) = -333); Assert(HugeIntToInt32(D) = 1); HugeIntAssignInt32(B, -3); HugeIntDivideHugeInt(A, B, C, D); Assert(HugeIntToInt32(C) = 333); Assert(HugeIntToInt32(D) = 1); HugeIntAssignInt32(A, 1000); HugeIntAssignInt32(B, 3); HugeIntDivideHugeInt(A, B, C, D); Assert(HugeIntToInt32(C) = 333); Assert(HugeIntToInt32(D) = 1); HugeIntAssignInt32(B, -3); HugeIntDivideHugeInt(A, B, C, D); Assert(HugeIntToInt32(C) = -333); Assert(HugeIntToInt32(D) = 1); // Mod HugeIntAssignInt32(A, -1000); HugeIntAssignInt32(B, 3); HugeIntMod(A, B, C); Assert(HugeIntToInt32(C) = 1); // Power HugeIntAssignInt32(A, -2); HugeIntPower(A, 0); Assert(HugeIntToInt32(A) = 1); HugeIntAssignInt32(A, -2); HugeIntPower(A, 1); Assert(HugeIntToInt32(A) = -2); HugeIntAssignInt32(A, -2); HugeIntPower(A, 2); Assert(HugeIntToInt32(A) = 4); HugeIntAssignInt32(A, -2); HugeIntPower(A, 3); Assert(HugeIntToInt32(A) = -8); HugeIntAssignInt32(A, -2); HugeIntPower(A, 4); Assert(HugeIntToInt32(A) = 16); // Power HugeIntAssignZero(A); HugeIntPower(A, 0); Assert(HugeIntToInt32(A) = 1); HugeIntAssignZero(A); HugeIntPower(A, 1); Assert(HugeIntToInt32(A) = 0); HugeIntAssignOne(A); HugeIntPower(A, 0); Assert(HugeIntToInt32(A) = 1); HugeIntAssignOne(A); HugeIntPower(A, 1); Assert(HugeIntToInt32(A) = 1); HugeIntAssignMinusOne(A); HugeIntPower(A, 0); Assert(HugeIntToInt32(A) = 1); HugeIntAssignMinusOne(A); HugeIntPower(A, 1); Assert(HugeIntToInt32(A) = -1); HugeIntAssignMinusOne(A); HugeIntPower(A, 2); Assert(HugeIntToInt32(A) = 1); // AssignDouble HugeIntAssignDouble(A, 0.0); Assert(HugeIntToDouble(A) = 0.0); HugeIntAssignDouble(A, 1.0); Assert(HugeIntToDouble(A) = 1.0); HugeIntAssignDouble(A, -1.0); Assert(HugeIntToDouble(A) = -1.0); // ToStr/StrTo StrToHugeIntB('-1234567890', A); Assert(HugeIntToInt32(A) = -1234567890); Assert(HugeIntToStrB(A) = '-1234567890'); Assert(HugeIntToHexB(A) = '-499602D2'); StrToHugeIntB('123456789012345678901234567890123456789012345678901234567890', A); Assert(HugeIntToStrB(A) = '123456789012345678901234567890123456789012345678901234567890'); // ToHex/HexTo HexToHugeIntB('-0123456789ABCDEF', A); Assert(HugeIntToHexB(A) = '-0123456789ABCDEF'); HexToHugeIntB('-F1230', A); Assert(HugeIntToHexB(A) = '-000F1230'); HugeWordFinalise(F); HugeIntFinalise(D); HugeIntFinalise(C); HugeIntFinalise(B); HugeIntFinalise(A); end; procedure Test; begin Assert(HugeWordElementBits = 32); Test_HugeWord; Test_HugeInt; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.15 2/13/05 7:21:30 PM RLebeau Updated TIdTelnetReadThread.Run() to use a timeout when calling the IOHandler's CheckForDataOnSource() method. Rev 1.14 10/07/2004 10:00:28 ANeillans Fixed compile bug Rev 1.13 7/8/04 4:12:06 PM RLebeau Updated calls to Write() to use the IOHandler Rev 1.12 7/4/04 1:38:36 PM RLebeau Updated Negotiate() to trigger the OnDataAvailable event only when data is actually available. Rev 1.11 5/16/04 3:14:06 PM RLebeau Added destructor to terminate the reading thread Rev 1.10 3/29/04 11:47:00 AM RLebeau Updated to support new ThreadedEvent property Rev 1.9 2004.03.06 1:31:56 PM czhower To match Disconnect changes to core. Rev 1.8 2004.02.03 5:44:32 PM czhower Name changes Rev 1.7 1/21/2004 4:20:48 PM JPMugaas InitComponent Rev 1.6 2003.11.29 10:20:16 AM czhower Updated for core change to InputBuffer. Rev 1.5 3/6/2003 5:08:50 PM SGrobety Updated the read buffer methodes to fit the new core (InputBuffer -> InputBufferAsString + call to CheckForDataOnSource) Rev 1.4 2/24/2003 10:32:46 PM JPMugaas Rev 1.3 12/8/2002 07:26:10 PM JPMugaas Added published host and port properties. Rev 1.2 12/7/2002 06:43:30 PM JPMugaas These should now compile except for Socks server. IPVersion has to be a property someplace for that. Rev 1.1 12/6/2002 05:30:40 PM JPMugaas Now decend from TIdTCPClientCustom instead of TIdTCPClient. Rev 1.0 11/13/2002 08:02:50 AM JPMugaas 03-01-2002 Andrew P.Rybin Renamings and standardization 26-05-2000 SG: Converted to Indy, no other change 07-Mar-2000 Mark Added a bunch of stuff... it's very much a work in progress 05-Mar-2000 Mark Added constants for telnet implememtation. 13-JAN-2000 MTL: Moved to new Palette Scheme (Winshoes Servers) } unit IdTelnet; { Author: Mark Holmes This is the telnet client component. I'm still testing There is no real terminal emulation other than dumb terminal } interface {$i IdCompilerDefines.inc} uses Classes, IdAssignedNumbers, IdGlobal, IdException, IdStack, IdTCPClient, IdThread; const { These are the telnet command constansts from RFC 854 } TNC_EOR = $EF; // End of Record RFC 885 TNC_SE = $F0; // End of subnegotiation parameters. TNC_NOP = $F1; // No operation. TNC_DATA_MARK = $F2; // The data stream portion of a Synch. // This should always be accompanied // by a TCP Urgent notification. TNC_BREAK = $F3; // NVT character BRK. TNC_IP = $F4; // The function IP. TNC_AO = $F5; // The function ABORT OUTPUT. TNC_AYT = $F6; // The function ARE YOU THERE. TNC_EC = $F7; // The function ERASE CHARACTER. TNC_EL = $F8; // The function ERASE LINE. TNC_GA = $F9; // The GO AHEAD signal. TNC_SB = $FA; // Indicates that what follows is // subnegotiation of the indicated // option. TNC_WILL = $FB; // Indicates the desire to begin // performing, or confirmation that // you are now performing, the // indicated option. TNC_WONT = $FC; // Indicates the refusal to perform, // or continue performing, the // indicated option. TNC_DO = $FD; // Indicates the request that the // other party perform, or // confirmation that you are expecting // the other party to perform, the // indicated option. TNC_DONT = $FE; // Indicates the demand that the // other party stop performing, // or confirmation that you are no // longer expecting the other party // to perform, the indicated option. TNC_IAC = $FF; // Data Byte 255. { Telnet options registered with IANA } TNO_BINARY = $00; // Binary Transmission TNO_ECHO = $01; // Echo TNO_RECONNECT = $02; // Reconnection TNO_SGA = $03; // Suppress Go Ahead TNO_AMSN = $04; // Approx Message Size Negotiation TNO_STATUS = $05; // Status TNO_TIMING_MARK = $06; // Timing Mark TNO_RCTE = $07; // Remote Controlled Trans and Echo -BELL TNO_OLW = $08; // Output Line Width TNO_OPS = $09; // Output Page Size TNO_OCRD = $0A; // Output Carriage-Return Disposition TNO_OHTS = $0B; // Output Horizontal Tab Stops TNO_OHTD = $0C; // Output Horizontal Tab Disposition TNO_OFD = $0D; // Output Formfeed Disposition TNO_OVT = $0E; // Output Vertical Tabstops TNO_OVTD = $0F; // Output Vertical Tab Disposition TNO_OLD = $10; // Output Linefeed Disposition TNO_EA = $11; // Extended ASCII TNO_LOGOUT = $12; // Logout TNO_BYTE_MACRO = $13; // Byte Macro TNO_DET = $14; // Data Entry Terminal TNO_SUPDUP = $15; // SUPDUP TNO_SUPDUP_OUTPUT = $16; // SUPDUP Output TNO_SL = $17; // Send Location TNO_TERMTYPE = $18; // Terminal Type TNO_EOR = $19; // End of Record TNO_TACACS_ID = $1A; // TACACS User Identification TNO_OM = $1B; // Output Marking TNO_TLN = $1C; // Terminal Location Number TNO_3270REGIME = $1D; // 3270 regime TNO_X3PAD = $1E; // X.3 PAD TNO_NAWS = $1F; // Window size TNO_TERM_SPEED = $20; // Terminal speed TNO_RFLOW = $21; // Remote flow control TNO_LINEMODE = $22; // Linemode option TNO_XDISPLOC = $23; // X Display Location TNO_ENV = $24; // Environment TNO_AUTH = $25; // Authenticate TNO_ENCRYPT = $26; // Encryption option TNO_NEWENV = $27; TNO_TN3270E = $28; TNO_XAUTH = $29; TNO_CHARSET = $2A; TNO_RSP = $2B; TNO_COMPORT = $2C; TNO_SUPLOCALECHO = $2D; TNO_STARTTLS = $2E; TNO_KERMIT = $2F; TNO_SEND_URL = $30; TNO_FORWARD_X = $31; // 50-137 = Unassigned TNO_PRAGMA_LOGON = $8A; TNO_SSPI_LOGON = $8B; TNO_PRAGMA_HEARTBEAT = $8C; TNO_EOL = $FF; // Extended-Options-List // Sub options TNOS_TERM_IS = $00; TNOS_TERMTYPE_SEND = $01; // Sub option TNOS_REPLY = $02; TNOS_NAME = $03; //Auth commands TNOAUTH_IS = $00; TNOAUTH_SEND = $01; TNOAUTH_REPLY = $02; TNOAUTH_NAME = $03; // Auth options $25 TNOAUTH_NULL = $00; TNOAUTH_KERBEROS_V4 = $01; TNOAUTH_KERBEROS_V5 = $02; TNOAUTH_SPX = $03; TNOAUTH_MINK = $04; TNOAUTH_SRP = $05; TNOAUTH_RSA = $06; TNOAUTH_SSL = $07; TNOAUTH_LOKI = $0A; TNOAUTH_SSA = $0B; TNOAUTH_KEA_SJ = $0C; TNOAUTH_KEA_SJ_INTEG = $0D; TNOAUTH_DSS = $0E; TNOAUTH_NTLM = $0F; //Kerberos4 Telnet Authentication suboption commands TNOAUTH_KRB4_AUTH = $00; TNOAUTH_KRB4_REJECT = $01; TNOAUTH_KRB4_ACCEPT = $02; TNOAUTH_KRB4_CHALLENGE = $03; TNOAUTH_KRB4_RESPONSE = $04; TNOAUTH_KRB4_FORWARD = $05; TNOAUTH_KRB4_FORWARD_ACCEPT = $06; TNOAUTH_KRB4_FORWARD_REJECT = $07; TNOAUTH_KRB4_EXP = $08; TNOAUTH_KRB4_PARAMS = $09; //Kerberos5 Telnet Authentication suboption commands TNOAUTH_KRB5_AUTH = $00; TNOAUTH_KRB5_REJECT = $01; TNOAUTH_KRB5_ACCEPT = $02; TNOAUTH_KRB5_RESPONSE = $03; TNOAUTH_KRB5_FORWARD = $04; TNOAUTH_KRB5_FORWARD_ACCEPT = $05; TNOAUTH_KRB5_FORWARD_REJECT = $06; //DSS Telnet Authentication suboption commands TNOAUTH_DSS_INITIALIZE = $01; TNOAUTH_DSS_TOKENBA = $02; TNOAUTH_DSS_CERTA_TOKENAB = $03; TNOAUTH_DSS_CERTB_TOKENBA2 = $04; //SRP Telnet Authentication suboption commands TNOAUTH_SRP_AUTH = $00; TNOAUTH_SRP_REJECT = $01; TNOAUTH_SRP_ACCEPT = $02; TNOAUTH_SRP_CHALLENGE = $03; TNOAUTH_SRP_RESPONSE = $04; TNOAUTH_SRP_EXP = $08; TNOAUTH_SRP_PARAMS = $09; // KEA_SJ and KEA_SJ_INTEG Telnet Authenticatio suboption commands TNOAUTH_KEA_CERTA_RA = $01; TNOAUTH_KEA_CERTB_RB_IVB_NONCEB = $02; TNOAUTH_KEA_IVA_RESPONSEB_NONCEA = $03; TNOAUTH_KEA_RESPONSEA = $04; //Telnet Encryption Types (Option 38) // commands TNOENC_IS = $00; TNOENC_SUPPORT = $01; TNOENC_REPLY = $02; TNOENC_START = $03; TNOENC_END = $04; TNOENC_REQUEST_START = $05; TNOENC_REQUEST_END = $06; TNOENC_ENC_KEYID = $07; TNOENC_DEC_KEYID = $08; // types TNOENC_NULL = $00; TNOENC_DES_CFB64 = $01; TNOENC_DES_OFB64 = $02; TNOENC_DES3_CFB64 = $03; TNOENC_DES3_OFB64 = $04; TNOENC_CAST5_40_CFB64 = $08; TNOENC_CAST5_40_OFB64 = $09; TNOENC_CAST128_CFB64 = $0A; TNOENC_CAST128_OFB64 = $0B; TNOENC_AES_CCM = $0C; //DES3_CFB64 Telnet Encryption type suboption commands TNOENC_CFB64_IV = $01; TNOENC_CFB64_IV_OK = $02; TNOENC_CFB64_IV_BAD = $03; //CAST5_40_OFB64 and CAST128_OFB64 Telnet Encryption types suboption commands TNOENC_OFB64_IV = $01; TNOENC_OFB64_IV_OK = $02; TNOENC_OFB64_IV_BAD = $03; //CAST5_40_CFB64 and CAST128_CFB64 Telnet Encryption types suboption commands //same as DES3_CFB64 Telnet Encryption type suboption commands //DES_CFB64 Telnet Encryption type //same as DES3_CFB64 Telnet Encryption type suboption commands //DES_OFB64 Telnet Encryption type //same as CAST5_40_OFB64 and CAST128_OFB64 Telnet Encryption types suboption commands type TIdTelnet = class; {Commands to telnet client from server} TIdTelnetCommand = (tncNoLocalEcho, tncLocalEcho, tncEcho); // RLebeau 9/5/2012: in D2009+, TIdBytes is an alias for SysUtils.TBytes, which // is an alias for System.TArray<Byte>, which has some different semantics than // plain dynamic arrays. In Delphi, those differences are more subtle than in // C++, where they are major, in particular for event handlers that were previously // using TIdBytes parameters. The C++ IDE simply can't cope with TArray<Byte> // in RTTI correctly yet, so it produces bad HPP and Event Handler code that // causes errors. In this situation, we will use TIdDynByteArray instead, which // still accomplishes what we need and is compatible with both Delphi and C++... // TIdTelnetDataAvailEvent = procedure (Sender: TIdTelnet; const Buffer: {$IFDEF HAS_TBytes}TIdDynByteArray{$ELSE}TIdBytes{$ENDIF}) of object; TIdTelnetCommandEvent = procedure(Sender: TIdTelnet; Status: TIdTelnetCommand) of object; {This object is for the thread that listens for the telnet server responses to key input and initial protocol negotiations } TIdTelnetReadThread = class(TIdThread) protected FClient: TIdTelnet; // procedure Run; override; public constructor Create(AClient: TIdTelnet); reintroduce; property Client: TIdTelnet read FClient; end; //TIdTelnetReadThread TIdTelnet = class(TIdTCPClientCustom) protected fTerminal : String; fThreadedEvent: Boolean; FOnDataAvailable: TIdTelnetDataAvailEvent; fIamTelnet: Boolean; FOnTelnetCommand: TIdTelnetCommandEvent; FTelnetThread: TIdTelnetReadThread; // procedure DoOnDataAvailable(const Buf: TIdBytes); // Are we connected to a telnet server or some other server? property IamTelnet: Boolean read fIamTelnet write fIamTelnet; // Protocol negotiation begins here procedure Negotiate; // Handle the termtype request procedure Handle_SB(const SbType: Byte; const SbData: TIdBytes); // Send the protocol resp to the server based on what's in Reply {Do not Localize} procedure SendNegotiationResp(const Response: Byte; const ResponseData: Byte); procedure SendSubNegotiationResp(const SbType: Byte; const ResponseData: TIdBytes); // Update the telnet status procedure DoTelnetCommand(Status: TIdTelnetCommand); procedure InitComponent; override; public // {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor Create(AOwner: TComponent); reintroduce; overload; {$ENDIF} destructor Destroy; override; procedure Connect; override; procedure Disconnect(ANotifyPeer: Boolean); override; procedure SendCh(Ch: Char); procedure SendString(const S: String); property TelnetThread: TIdTelnetReadThread read FTelnetThread; published property Host; property Port default IdPORT_TELNET; property OnTelnetCommand: TIdTelnetCommandEvent read FOnTelnetCommand write FOnTelnetCommand; property OnDataAvailable: TIdTelnetDataAvailEvent read FOnDataAvailable write FOnDataAvailable; property Terminal: string read fTerminal write fTerminal; property ThreadedEvent: Boolean read fThreadedEvent write fThreadedEvent default False; end; EIdTelnetError = class(EIdException); EIdTelnetClientConnectError = class(EIdTelnetError); EIdTelnetServerOnDataAvailableIsNil = class(EIdTelnetError); implementation uses IdResourceStringsCore, IdResourceStringsProtocols, SysUtils; constructor TIdTelnetReadThread.Create(AClient: TIdTelnet); begin FClient := AClient; inherited Create(False); end; procedure TIdTelnetReadThread.Run; begin // if we have data run it through the negotiation routine. If we aren't // connected to a telnet server then the data just passes through the // negotiate routine unchanged. // RLebeau 3/29/04 - made Negotiate() get called by Synchronize() to // ensure that the OnTelnetCommand event handler is synchronized when // ThreadedEvent is false if FClient.IOHandler.InputBufferIsEmpty then begin FClient.IOHandler.CheckForDataOnSource(IdTimeoutInfinite); end; if not FClient.IOHandler.InputBufferIsEmpty then begin if FClient.ThreadedEvent then begin FClient.Negotiate; end else begin Synchronize(FClient.Negotiate); end; end; FClient.IOHandler.CheckForDisconnect; end; { TIdTelnet } procedure TIdTelnet.SendCh(Ch : Char); begin // this code is necessary to allow the client to receive data properly // from a non-telnet server if Connected then begin if (Ch <> CR) or IamTelnet then begin IOHandler.Write(Ch); end else begin IOHandler.Write(EOL); end; end; end; procedure TIdTelnet.SendString(const S : String); var I: Integer; Ch: Char; begin // this code is necessary to allow the client to receive data properly // from a non-telnet server for I := 1 to Length(S) do begin if not Connected then begin Break; end; Ch := S[I]; if (Ch <> CR) or IamTelnet then begin IOHandler.Write(Ch); end else begin IOHandler.Write(EOL); end; end; end; {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor TIdTelnet.Create(AOwner: TComponent); begin inherited Create(AOwner); end; {$ENDIF} procedure TIdTelnet.InitComponent; begin inherited InitComponent; Terminal := 'dumb'; {Do not Localize} ThreadedEvent := False; IamTelnet := False; Port := IdPORT_TELNET; end; destructor TIdTelnet.Destroy; begin Disconnect; inherited Destroy; end; procedure TIdTelnet.Disconnect(ANotifyPeer: Boolean); begin if Assigned(FTelnetThread) then begin FTelnetThread.Terminate; end; try inherited Disconnect(ANotifyPeer); finally if Assigned(FTelnetThread) then begin FTelnetThread.WaitFor; end; FreeAndNil(FTelnetThread); end; end; procedure TIdTelnet.DoOnDataAvailable(const Buf: TIdBytes); begin if Assigned(FOnDataAvailable) then begin OnDataAvailable(Self, {$IFDEF HAS_TBytes} PIdDynByteArray(@Buf)^ {$ELSE} Buf {$ENDIF} ); end else begin raise EIdTelnetServerOnDataAvailableIsNil.Create(RSTELNETSRVOnDataAvailableIsNil); end; end; procedure TIdTelnet.Connect; begin inherited Connect; try // create the reading thread and assign the current Telnet object to it IAmTelnet := False; FTelnetThread := TIdTelnetReadThread.Create(Self); except Disconnect(True); raise EIdTelnetClientConnectError.Create(RSNoCreateListeningThread); // translate end; end; procedure TIdTelnet.SendNegotiationResp(const Response: Byte; const ResponseData: Byte); var Resp: TIdBytes; begin SetLength(Resp, 3); Resp[0] := TNC_IAC; Resp[1] := Response; Resp[2] := ResponseData; IOHandler.Write(Resp); end; procedure TIdTelnet.SendSubNegotiationResp(const SbType: Byte; const ResponseData: TIdBytes); var Resp: TIdBytes; begin SetLength(Resp, 3 + Length(ResponseData) + 2); Resp[0] := TNC_IAC; Resp[1] := TNC_SB; Resp[2] := SbType; CopyTIdBytes(ResponseData, 0, Resp, 3, Length(ResponseData)); Resp[Length(Resp)-2] := TNC_IAC; Resp[Length(Resp)-1] := TNC_SE; IOHandler.Write(Resp); end; procedure TIdTelnet.Handle_SB(const SbType: Byte; const SbData: TIdBytes); var Resp: TIdBytes; LTerminal: String; begin Resp := nil; case SbType of TNO_TERMTYPE: if (Length(SbData) > 0) and (SbData[0] = TNOS_TERMTYPE_SEND) then begin // if someone inadvertantly sets Terminal to null // You can set terminal to anything you want I suppose but be // prepared to handle the data emulation yourself LTerminal := Terminal; if LTerminal = '' then begin Terminal := 'UNKNOWN'; {Do not Localize} end; SetLength(Resp, 1); Resp[0] := TNOS_TERM_IS; AppendString(Resp, LTerminal); SendSubNegotiationResp(TNO_TERMTYPE, Resp); end; end; // add authentication code here end; procedure TIdTelnet.Negotiate; var b : Byte; nBuf : TIdBytes; sbBuf : TIdBytes; CurrentSb : Byte; Reply : Byte; begin nBuf := nil; sbBuf := nil; repeat b := IOHandler.ReadByte; if b <> TNC_IAC then begin AppendByte(nBuf, b); Continue; end; { start of command sequence } IamTelnet := True; b := IOHandler.ReadByte; if b = TNC_IAC then begin AppendByte(nBuf, TNC_IAC); Continue; end; case b of TNC_WILL: begin b := IOHandler.ReadByte; case b of TNO_ECHO: begin Reply := TNC_DO; DoTelnetCommand(tncNoLocalEcho); //doStatus('NOLOCALECHO'); {Do not Localize} end; TNO_EOR: Reply := TNC_DO; else Reply := TNC_DONT; end; SendNegotiationResp(Reply, b); end; TNC_WONT: begin b := IOHandler.ReadByte; case b of TNO_ECHO: begin Reply := TNC_DONT; DoTelnetCommand(tncLocalEcho); //Dostatus('LOCALECHO'); {Do not Localize} end; else Reply := TNC_DONT; end; SendNegotiationResp(Reply, b); end; TNC_DONT: begin b := IOHandler.ReadByte; case b of TNO_ECHO: begin DoTelnetCommand(tncEcho); //DoStatus('ECHO'); {Do not Localize} Reply := TNC_WONT; end; else Reply := TNC_WONT; end; SendNegotiationResp(Reply, b); end; TNC_DO: begin b := IOHandler.ReadByte; case b of TNO_ECHO: begin Reply := TNC_WILL; DoTelnetCommand(tncLocalEcho); end; TNO_TERMTYPE: Reply := TNC_WILL; //TNO_NAWS: TNO_AUTH: begin { if (Authentication) then begin Reply := TNC_WILL; end else } begin Reply := TNC_WONT; end; end; else Reply := TNC_WONT; end; SendNegotiationResp(Reply, b); end; TNC_EOR: begin // send any current data to the app if Length(nBuf) > 0 then begin DoOnDataAvailable(nBuf); SetLength(nBuf, 0); end; end; TNC_SB: begin SetLength(sbBuf, 0); // send any current data to the app, as the sub-negotiation // may affect how subsequent data needs to be processed... if Length(nBuf) > 0 then begin DoOnDataAvailable(nBuf); SetLength(nBuf, 0); end; CurrentSB := IOHandler.ReadByte; repeat b := IOHandler.ReadByte; if b = TNC_IAC then begin b := IOHandler.ReadByte; case b of TNC_IAC: begin AppendByte(sbBuf, TNC_IAC); end; TNC_SE: begin Handle_Sb(CurrentSB, sbBuf); SetLength(sbBuf, 0); Break; end; TNC_SB: begin Handle_Sb(CurrentSB, sbBuf); SetLength(sbBuf, 0); CurrentSB := IOHandler.ReadByte; end; end; end else begin AppendByte(sbBuf, b); end; until False; end; end; until IOHandler.InputBufferIsEmpty; // if any data remains then send this data to the app if Length(nBuf) > 0 then begin DoOnDataAvailable(nBuf); end; end; procedure TIdTelnet.DoTelnetCommand(Status: TIdTelnetCommand); begin if Assigned(FOnTelnetCommand) then FOnTelnetCommand(Self, Status); end; END.
unit Monitors; interface uses Classes, SysUtils; type PMonitorArray = ^TMonitorArray; TMonitorArray = array[0..1024] of integer; type TMonitorObject = class; TServerMonitor = class; TAreaMonitor = class; TWorldMonitor = class; TMonitorObject = class public constructor Create(samplCount : integer); destructor Destroy; override; private fSampleCount : integer; fSample : PMonitorArray; fCursor : integer; private procedure ShlSample; protected procedure SetCurrentValue(value : integer); function GetCurrentValue : integer; public function Update : integer; virtual; abstract; procedure Clean; virtual; procedure SetSampleCount(count : integer); virtual; function GetSampleCount : integer; virtual; function GetSample(index : integer) : integer; virtual; function GetMax : integer; function GetMin : integer; public property SampleCount : integer read GetSampleCount write SetSampleCount; property Samples[index : integer] : integer read GetSample; property Cursor : integer read fCursor; property CurrentValue : integer read GetCurrentValue; property Max : integer read GetMax; property Min : integer read GetMin; end; TServerMonitor = class(TMonitorObject) public constructor Create(theProxy : OleVariant; samplCount : integer); //constructor Create(DSAddr : string; Port, samplCount : integer); destructor Destroy; override; public function Update : integer; override; private fProxy : OleVariant; fAreas : TStringList; public property Proxy : OleVariant read fProxy; property Areas : TStringList read fAreas; end; TAreaMonitor = class(TMonitorObject) public constructor Create(Owner : TServerMonitor; aName : string); destructor Destroy; override; private fName : string; fOwner : TServerMonitor; fWorlds : TStringList; public function Update : integer; override; public property Name : string read fName; property Owner : TServerMonitor read fOwner; property Worlds : TStringList read fWorlds; end; TWorldMonitor = class(TMonitorObject) public constructor Create(Owner : TAreaMonitor; aName : string); destructor Destroy; override; private fOwner : TAreaMonitor; fName : string; public function Update : integer; override; public property Name : string read fName; end; implementation uses ComObj; // TMonitorObject constructor TMonitorObject.Create(samplCount : integer); begin inherited Create; fSampleCount := samplCount; SetSampleCount(samplCount); end; destructor TMonitorObject.Destroy; begin SetSampleCount(0); inherited; end; procedure TMonitorObject.Clean; begin fCursor := -1; if fSample <> nil then FillChar(fSample^, fSampleCount*sizeof(fSample[0]), 0); end; function TMonitorObject.GetSample(index : integer) : integer; begin result := fSample[index]; end; function TMonitorObject.GetSampleCount : integer; begin result := fSampleCount; end; function TMonitorObject.GetMax : integer; var i : integer; begin result := 0; for i := 0 to fCursor do if fSample[i] > result then result := fSample[i]; end; function TMonitorObject.GetMin : integer; var i : integer; begin result := 0; for i := 0 to fCursor do if fSample[i] < result then result := fSample[i]; end; procedure TMonitorObject.SetCurrentValue(value : integer); begin if fSampleCount > 0 then begin if fCursor = pred(fSampleCount) then ShlSample else inc(fCursor); fSample[fCursor] := value; end; end; function TMonitorObject.GetCurrentValue : integer; begin if (fCursor >= 0) and (fSampleCount > 0) then result := fSample[fCursor] else result := 0; end; procedure TMonitorObject.SetSampleCount(count: integer); var i : integer; begin ReallocMem(fSample, count*sizeof(fSample[0])); fCursor := pred(fSampleCount); fSampleCount := count; for i := 0 to pred(count) do fSample[i] := 0; end; procedure TMonitorObject.ShlSample; begin move(fSample[1], fSample[0], fCursor*sizeof(fSample[0])); end; // TServerMonitor constructor TServerMonitor.Create(theProxy : OleVariant; samplCount : integer); var key : string; List : TStringList; i : integer; Area : TAreaMonitor; begin inherited Create(samplCount); fProxy := theProxy; fAreas := TStringList.Create; key := 'root/areas'; if fProxy.RDOSetCurrentKey(key) then begin List := TStringList.Create; try List.Text := fProxy.RDOGetKeyNames; for i := 0 to pred(List.count) do begin Area := TAreaMonitor.Create(Self, List[i]); fAreas.AddObject(List[i], Area); end; finally List.Free; end; end; end; destructor TServerMonitor.Destroy; var i : integer; begin for i := 0 to pred(fAreas.Count) do TAreaMonitor(fAreas.Objects[i]).Free; inherited; end; function TServerMonitor.Update : integer; var i : integer; Area : TAreaMonitor; begin result := 0; for i := 0 to pred(fAreas.Count) do begin Area := TAreaMonitor(fAreas.Objects[i]); result := result + Area.Update; end; SetCurrentValue(result); end; // TAreaMonitor constructor TAreaMonitor.Create(Owner : TServerMonitor; aName : string); var key : string; List : TStringList; i : integer; World : TWorldMonitor; begin inherited Create(Owner.SampleCount); fName := aName; fOwner := Owner; fWorlds := TStringList.Create; key := Format('root/areas/%s/worlds', [fName]); if Owner.Proxy.RDOSetCurrentKey(key) then begin List := TStringList.Create; List.Text := Owner.Proxy.RDOGetKeyNames; for i := 0 to pred(List.Count) do begin World := TWorldMonitor.Create(Self, List[i]); fWorlds.AddObject(List[i], World); end; end; end; destructor TAreaMonitor.Destroy; var i : integer; begin for i := 0 to pred(fWorlds.Count) do TWorldMonitor(fWorlds.Objects[i]).Free; inherited; end; function TAreaMonitor.Update : integer; var i : integer; World : TWorldMonitor; begin result := 0; for i := 0 to pred(fWorlds.Count) do begin World := TWorldMonitor(fWorlds.Objects[i]); result := result + World.Update; end; SetCurrentValue(result); end; // TWorldMonitor constructor TWorldMonitor.Create(Owner: TAreaMonitor; aName: string); begin inherited Create(Owner.SampleCount); fOwner := Owner; fName := aName; end; destructor TWorldMonitor.Destroy; begin inherited; end; function TWorldMonitor.Update : integer; var Proxy : OleVariant; key : string; begin try Proxy := fOwner.Owner.Proxy; key := Format('root/areas/%s/worlds/%s/general', [fOwner.Name, fName]); if Proxy.RDOSetCurrentKey(key) then result := Proxy.RDOReadInteger('online') else result := GetCurrentValue; except result := GetCurrentValue; end; SetCurrentValue(result); end; end.
PROGRAM Stat(INPUT, OUTPUT); FUNCTION ReadNumber(VAR F: TEXT): INTEGER; { Хорошая версия + работает! } VAR Number, Digit: INTEGER; BlankEater: CHAR; Overflow: BOOLEAN; FUNCTION ReadDigit(VAR F: TEXT): INTEGER; { Функция возвращает число, соответствующее символу-цифре } VAR Ch: CHAR; Digit: INTEGER; BEGIN {ReadDigit} IF NOT EOLN(F) THEN READ(F, Ch); IF Ch = '0' THEN Digit := 0 ELSE IF Ch = '1' THEN Digit := 1 ELSE IF Ch = '2' THEN Digit := 2 ELSE IF Ch = '3' THEN Digit := 3 ELSE IF Ch = '4' THEN Digit := 4 ELSE IF Ch = '5' THEN Digit := 5 ELSE IF Ch = '6' THEN Digit := 6 ELSE IF Ch = '7' THEN Digit := 7 ELSE IF Ch = '8' THEN Digit := 8 ELSE IF Ch = '9' THEN Digit := 9 ELSE Digit := -1; ReadDigit := Digit END; {ReadDigit} BEGIN {ReadNumber} Number := 0; Digit := 0; Overflow := FALSE; WHILE NOT EOF(F) AND (Digit <> -1) AND NOT Overflow DO BEGIN IF Number > 3276 THEN Overflow := TRUE ELSE IF Number = 3276 THEN IF Digit > 7 THEN Overflow := TRUE; IF Overflow {>INTMAX? (32767)} THEN Number := -1 ELSE Number := Number * 10 + Digit; Digit := ReadDigit(F); END; ReadNumber := Number END; {ReadNumber} VAR Number, Sum, CountOfNumbers, MaxInt, MinInt, MathAverage: INTEGER; BEGIN {TestFunction} MaxInt := 0; MinInt := 32767; MathAverage := 0; CountOfNumbers := 0; Sum := 0; WHILE NOT EOLN DO BEGIN Number := ReadNumber(INPUT); WRITELN(Number); IF Number < MinInt THEN MinInt := Number; IF Number > MaxInt THEN MaxInt := Number; Sum := Sum + Number; CountOfNumbers := CountOfNumbers + 1; END; IF CountOfNumbers <> 0 THEN MathAverage := Sum DIV CountOfNumbers; WRITELN('MinInt:', MinInt, ', MaxInt:', MaxInt, ', MathAverage:', MathAverage) END. {TestFunction}
{ * CVPixelBuffer.h * CoreVideo * * Copyright (c) 2004 Apple Computer, Inc. All rights reserved. * } { Pascal Translation: Gale R Paeper, <gpaeper@empirenet.com>, 2008 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CVPixelBuffer; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes, CFArray, CFBase, CFDictionary, CVBase, CVImageBuffer, CVReturns; {$ALIGN POWER} {! @header CVPixelBuffer.h @copyright 2004 Apple Computer, Inc. All rights reserved. @availability Mac OS X 10.4 or later @discussion CVPixelBuffers are CVImageBuffers that hold the pixels in main memory } //#pragma mark BufferAttributeKeys var kCVPixelBufferPixelFormatTypeKey: CFStringRef; external name '_kCVPixelBufferPixelFormatTypeKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // A single CFNumber or a CFArray of CFNumbers (OSTypes) var kCVPixelBufferMemoryAllocatorKey: CFStringRef; external name '_kCVPixelBufferMemoryAllocatorKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFAllocatorRef var kCVPixelBufferWidthKey: CFStringRef; external name '_kCVPixelBufferWidthKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFNumber var kCVPixelBufferHeightKey: CFStringRef; external name '_kCVPixelBufferHeightKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFNumber var kCVPixelBufferExtendedPixelsLeftKey: CFStringRef; external name '_kCVPixelBufferExtendedPixelsLeftKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFNumber var kCVPixelBufferExtendedPixelsTopKey: CFStringRef; external name '_kCVPixelBufferExtendedPixelsTopKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFNumber var kCVPixelBufferExtendedPixelsRightKey: CFStringRef; external name '_kCVPixelBufferExtendedPixelsRightKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFNumber var kCVPixelBufferExtendedPixelsBottomKey: CFStringRef; external name '_kCVPixelBufferExtendedPixelsBottomKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFNumber var kCVPixelBufferBytesPerRowAlignmentKey: CFStringRef; external name '_kCVPixelBufferBytesPerRowAlignmentKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFNumber var kCVPixelBufferCGBitmapContextCompatibilityKey: CFStringRef; external name '_kCVPixelBufferCGBitmapContextCompatibilityKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFBoolean var kCVPixelBufferCGImageCompatibilityKey: CFStringRef; external name '_kCVPixelBufferCGImageCompatibilityKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFBoolean var kCVPixelBufferOpenGLCompatibilityKey: CFStringRef; external name '_kCVPixelBufferOpenGLCompatibilityKey'; (* attribute const *) (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) // CFBoolean {! @typedef CVPixelBufferRef @abstract Based on the image buffer type. The pixel buffer implements the memory storage for an image buffer. } type CVPixelBufferRef = CVImageBufferRef; function CVPixelBufferGetTypeID: CFTypeID; external name '_CVPixelBufferGetTypeID'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferRetain @abstract Retains a CVPixelBuffer object @discussion Equivalent to CFRetain, but NULL safe @param buffer A CVPixelBuffer object that you want to retain. @result A CVPixelBuffer object that is the same as the passed in buffer. } function CVPixelBufferRetain( texture: CVPixelBufferRef ): CVPixelBufferRef; external name '_CVPixelBufferRetain'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferRelease @abstract Releases a CVPixelBuffer object @discussion Equivalent to CFRelease, but NULL safe @param buffer A CVPixelBuffer object that you want to release. } procedure CVPixelBufferRelease( texture: CVPixelBufferRef ); external name '_CVPixelBufferRelease'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferCreateResolvedAttributesDictionary @abstract Takes a CFArray of CFDictionary objects describing various pixel buffer attributes and tries to resolve them into a single dictionary. @discussion This is useful when you need to resolve multiple requirements between different potential clients of a buffer. @param attributes CFArray of CFDictionaries containing kCVPixelBuffer key/value pairs. @param resolvedDictionaryOut The resulting dictionary will be placed here. @result Return value that may be useful in discovering why resolution failed. } function CVPixelBufferCreateResolvedAttributesDictionary( allocator: CFAllocatorRef; attributes: CFArrayRef; var resolvedDictionaryOut: CFDictionaryRef ): CVReturn; external name '_CVPixelBufferCreateResolvedAttributesDictionary'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferCreate @abstract Call to create a single PixelBuffer for a given size and pixelFormatType. @discussion Creates a single PixelBuffer for a given size and pixelFormatType. It allocates the necessary memory based on the pixel dimensions, pixelFormatType and extended pixels described in the pixelBufferAttributes. Not all parameters of the pixelBufferAttributes will be used here. @param width Width of the PixelBuffer in pixels. @param height Height of the PixelBuffer in pixels. @param pixelFormatType Pixel format indentified by its respective OSType. @param pixelBufferAttributes A dictionary with additonal attributes for a a pixel buffer. This parameter is optional. See PixelBufferAttributes for more details. @param pixelBufferOut The new pixel buffer will be returned here @result returns kCVReturnSuccess on success. } function CVPixelBufferCreate( allocator: CFAllocatorRef; width: size_t; height: size_t; pixelFormatType: OSType; pixelBufferAttributes: CFDictionaryRef; var pixelBufferOut: CVPixelBufferRef ): CVReturn; external name '_CVPixelBufferCreate'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) type CVPixelBufferReleaseBytesCallback = procedure( releaseRefCon: UnivPtr; baseAddress: {const} UnivPtr ); {! @function CVPixelBufferCreateWithBytes @abstract Call to create a single PixelBuffer for a given size and pixelFormatType based on a passed in piece of memory. @discussion Creates a single PixelBuffer for a given size and pixelFormatType. Not all parameters of the pixelBufferAttributes will be used here. It requires a release callback function that will be called, when the PixelBuffer gets destroyed so that the owner of the pixels can free the memory. @param width Width of the PixelBuffer in pixels @param height Height of the PixelBuffer in pixels @param pixelFormatType Pixel format indentified by its respective OSType. @param baseAddress Address of the memory storing the pixels. @param bytesPerRow Row bytes of the pixel storage memory. @param releaseCallback CVPixelBufferReleaseBytePointerCallback function that gets called when the PixelBuffer gets destroyed. @param releaseRefCon User data identifying the PixelBuffer for the release callback. @param pixelBufferAttributes A dictionary with additonal attributes for a a pixel buffer. This parameter is optional. See PixelBufferAttributes for more details. @param pixelBufferOut The new pixel buffer will be returned here @result returns kCVReturnSuccess on success. } function CVPixelBufferCreateWithBytes( allocator: CFAllocatorRef; width: size_t; height: size_t; pixelFormatType: OSType; baseAddress: UnivPtr; bytesPerRow: size_t; releaseCallback: CVPixelBufferReleaseBytesCallback; releaseRefCon: UnivPtr; pixelBufferAttributes: CFDictionaryRef; var pixelBufferOut: CVPixelBufferRef ): CVReturn; external name '_CVPixelBufferCreateWithBytes'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) type CVPixelBufferReleasePlanarBytesCallback = procedure( releaseRefCon: UnivPtr; dataPtr: {const} UnivPtr; dataSize: size_t; numberOfPlanes: size_t; {const} planeAddresses: {variable-size-array} UnivPtr ); {! @function CVPixelBufferCreateWithPlanarBytes @abstract Call to create a single PixelBuffer in planar format for a given size and pixelFormatType based on a passed in piece of memory. @discussion Creates a single PixelBuffer for a given size and pixelFormatType. Not all parameters of the pixelBufferAttributes will be used here. It requires a release callback function that will be called, when the PixelBuffer gets destroyed so that the owner of the pixels can free the memory. @param width Width of the PixelBuffer in pixels @param height Height of the PixelBuffer in pixels @param pixelFormatType Pixel format indentified by its respective OSType. @param dataPtr Pass a pointer to a plane descriptor block, or NULL. @param dataSize pass size if planes are contiguous, NULL if not. @param numberOfPlanes Number of planes. @param planeBaseAddress Array of base addresses for the planes. @param planeWidth Array of plane widths. @param planeHeight Array of plane heights. @param planeBytesPerRow Array of plane bytesPerRow values. @param releaseCallback CVPixelBufferReleaseBytePointerCallback function that gets called when the PixelBuffer gets destroyed. @param releaseRefCon User data identifying the PixelBuffer for the release callback. @param pixelBufferAttributes A dictionary with additonal attributes for a a pixel buffer. This parameter is optional. See PixelBufferAttributes for more details. @param pixelBufferOut The new pixel buffer will be returned here @result returns kCVReturnSuccess on success. } function CVPixelBufferCreateWithPlanarBytes( allocator: CFAllocatorRef; width: size_t; height: size_t; pixelFormatType: OSType; dataPtr: {pass a pointer to a plane descriptor block, or NULL} UnivPtr; dataSize: {pass size if planes are contiguous, NULL if not} size_t; numberOfPlanes: size_t; planeAddresses: {variable-size-array} UnivPtr; planeWidth: {variable-size-array} size_t_Ptr; planeHeight: {variable-size-array} size_t_Ptr; planeBytesPerRow: {variable-size-array} size_t_Ptr; releaseCallback: CVPixelBufferReleasePlanarBytesCallback; releaseRefCon: UnivPtr; pixelBufferAttributes: CFDictionaryRef; var pixelBufferOut: CVPixelBufferRef ): CVReturn; external name '_CVPixelBufferCreateWithPlanarBytes'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferLockBaseAddress @abstract Description Locks the BaseAddress of the PixelBuffer to ensure that the is available. @param pixelBuffer Target PixelBuffer. @param lockFlags No options currently defined, pass 0. @result kCVReturnSuccess if the lock succeeded, or error code on failure } function CVPixelBufferLockBaseAddress( pixelBuffer: CVPixelBufferRef; lockFlags: CVOptionFlags ): CVReturn; external name '_CVPixelBufferLockBaseAddress'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferUnlockBaseAddress @abstract Description Unlocks the BaseAddress of the PixelBuffer. @param pixelBuffer Target PixelBuffer. @param unlockFlags No options currently defined, pass 0. @result kCVReturnSuccess if the unlock succeeded, or error code on failure } function CVPixelBufferUnlockBaseAddress( pixelBuffer: CVPixelBufferRef; unlockFlags: CVOptionFlags ): CVReturn; external name '_CVPixelBufferUnlockBaseAddress'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetWidth @abstract Returns the width of the PixelBuffer. @param pixelBuffer Target PixelBuffer. @result Width in pixels. } function CVPixelBufferGetWidth( pixelBuffer: CVPixelBufferRef ): size_t; external name '_CVPixelBufferGetWidth'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetHeight @abstract Returns the height of the PixelBuffer. @param pixelBuffer Target PixelBuffer. @result Height in pixels. } function CVPixelBufferGetHeight( pixelBuffer: CVPixelBufferRef ): size_t; external name '_CVPixelBufferGetHeight'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetPixelFormatType @abstract Returns the PixelFormatType of the PixelBuffer. @param pixelBuffer Target PixelBuffer. @result OSType identifying the pixel format by its type. } function CVPixelBufferGetPixelFormatType( pixelBuffer: CVPixelBufferRef ): OSType; external name '_CVPixelBufferGetPixelFormatType'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetBaseAddress @abstract Returns the base address of the PixelBuffer. @discussion Retrieving the base address for a PixelBuffer requires that the buffer base address be locked via a successful call to CVPixelBufferLockBaseAddress. @param pixelBuffer Target PixelBuffer. @result Base address of the pixels. For chunky buffers, this will return a pointer to the pixel at 0,0 in the buffer For planar buffers this will return a pointer to a PlanarComponentInfo struct (defined in QuickTime). } function CVPixelBufferGetBaseAddress( pixelBuffer: CVPixelBufferRef ): UnivPtr; external name '_CVPixelBufferGetBaseAddress'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetBytesPerRow @abstract Returns the rowBytes of the PixelBuffer. @param pixelBuffer Target PixelBuffer. @result Bytes per row of the image data. For planar buffers this will return a rowBytes value such that bytesPerRow * height will cover the entire image including all planes. } function CVPixelBufferGetBytesPerRow( pixelBuffer: CVPixelBufferRef ): size_t; external name '_CVPixelBufferGetBytesPerRow'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetDataSize @abstract Returns the data size for contigous planes of the PixelBuffer. @param pixelBuffer Target PixelBuffer. @result Data size used in CVPixelBufferCreateWithPlanarBytes. } function CVPixelBufferGetDataSize( pixelBuffer: CVPixelBufferRef ): size_t; external name '_CVPixelBufferGetDataSize'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferIsPlanar @abstract Returns if the PixelBuffer is planar. @param pixelBuffer Target PixelBuffer. @result True if the PixelBuffer was created using CVPixelBufferCreateWithPlanarBytes. } function CVPixelBufferIsPlanar( pixelBuffer: CVPixelBufferRef ): Boolean; external name '_CVPixelBufferIsPlanar'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetPlaneCount @abstract Returns number of planes of the PixelBuffer. @param pixelBuffer Target PixelBuffer. @result Number of planes. Returns 0 for non-planar CVPixelBufferRefs. } function CVPixelBufferGetPlaneCount( pixelBuffer: CVPixelBufferRef ): size_t; external name '_CVPixelBufferGetPlaneCount'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetWidthOfPlane @abstract Returns the width of the plane at planeIndex in the PixelBuffer. @param pixelBuffer Target PixelBuffer. @param planeIndex Identifying the plane. @result Width in pixels, or 0 for non-planar CVPixelBufferRefs. } function CVPixelBufferGetWidthOfPlane( pixelBuffer: CVPixelBufferRef; planeIndex: size_t ): size_t; external name '_CVPixelBufferGetWidthOfPlane'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetHeightOfPlane @abstract Returns the height of the plane at planeIndex in the PixelBuffer. @param pixelBuffer Target PixelBuffer. @param planeIndex Identifying the plane. @result Height in pixels, or 0 for non-planar CVPixelBufferRefs. } function CVPixelBufferGetHeightOfPlane( pixelBuffer: CVPixelBufferRef; planeIndex: size_t ): size_t; external name '_CVPixelBufferGetHeightOfPlane'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetBaseAddressOfPlane @abstract Returns the base address of the plane at planeIndex in the PixelBuffer. @discussion Retrieving the base address for a PixelBuffer requires that the buffer base address be locked via a successful call to CVPixelBufferLockBaseAddress. @param pixelBuffer Target PixelBuffer. @param planeIndex Identifying the plane. @result Base address of the plane, or NULL for non-planar CVPixelBufferRefs. } function CVPixelBufferGetBaseAddressOfPlane( pixelBuffer: CVPixelBufferRef; planeIndex: size_t ): UnivPtr; external name '_CVPixelBufferGetBaseAddressOfPlane'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetBytesPerRowOfPlane @abstract Returns the row bytes of the plane at planeIndex in the PixelBuffer. @param pixelBuffer Target PixelBuffer. @param planeIndex Identifying the plane. @result Row bytes of the plane, or NULL for non-planar CVPixelBufferRefs. } function CVPixelBufferGetBytesPerRowOfPlane( pixelBuffer: CVPixelBufferRef; planeIndex: size_t ): size_t; external name '_CVPixelBufferGetBytesPerRowOfPlane'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferGetExtendedPixels @abstract Returns the size of extended pixels of the PixelBuffer. @param pixelBuffer Target PixelBuffer. @param extraColumnsOnLeft Returns the pixel row padding to the left. May be NULL. @param extraRowsOnTop Returns the pixel row padding to the top. May be NULL. @param extraColumnsOnRight Returns the pixel row padding to the right. May be NULL. @param extraRowsOnBottom Returns the pixel row padding to the bottom. May be NULL. } procedure CVPixelBufferGetExtendedPixels( pixelBuffer: CVPixelBufferRef; var extraColumnsOnLeft: size_t; var extraColumnsOnRight: size_t; var extraRowsOnTop: size_t; var extraRowsOnBottom: size_t ); external name '_CVPixelBufferGetExtendedPixels'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) {! @function CVPixelBufferFillExtendedPixels @abstract Fills the extended pixels of the PixelBuffer with Zero. This function replicates edge pixels to fill the entire extended region of the image. @param pixelBuffer Target PixelBuffer. } function CVPixelBufferFillExtendedPixels( pixelBuffer: CVPixelBufferRef ): CVReturn; external name '_CVPixelBufferFillExtendedPixels'; (* AVAILABLE_MAC_OS_X_VERSION_10_4_AND_LATER *) end.
unit TestuRedisHandle; { 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, Classes, SysUtils, IdTCPClient, uRedisHandle; type // Test methods for class TRedisHandle TestTRedisHandle = class(TTestCase) strict protected FRedisHandle: TRedisHandle; protected procedure InitHandle; public procedure SetUp; override; procedure TearDown; override; published procedure TestStringSetExpire; procedure TestStringGetSet; procedure TestKey; procedure TestListRPush; procedure TestListRPop; procedure TestListLPush; procedure TestListLPop; procedure TestListLen; procedure TestListRange; procedure TestListRemove; end; const C_Key_Pre = 'Ö÷¼ü:'; C_Value_Pre = '"Öµ": '; C_List_Key = 'Ö÷¼ü:list'; C_List_Value_Pre = 'Öµ-list-'; implementation procedure TestTRedisHandle.InitHandle; begin FRedisHandle.Password := 'tcrq1234'; FRedisHandle.Db := 0; FRedisHandle.Ip := '192.168.1.3'; FRedisHandle.Port := 6379; end; procedure TestTRedisHandle.SetUp; begin FRedisHandle := TRedisHandle.Create(); InitHandle(); end; procedure TestTRedisHandle.TearDown; begin FRedisHandle.Free; FRedisHandle := nil; end; procedure TestTRedisHandle.TestListLen; var aKey: string; aCount: Integer; begin aKey := C_List_Key; aCount := FRedisHandle.ListLen(aKey); Status('listlen: ' + aKey + ' ' + IntToStr(aCount)); end; procedure TestTRedisHandle.TestListLPop; var aValue: String; begin while True do begin aValue := FRedisHandle.ListLPop(C_List_Key); if aValue = '' then Break; Status(aValue); end; end; procedure TestTRedisHandle.TestListLPush; var i: Integer; aValue: String; begin for i := 0 to 9 do begin aValue := C_List_Value_Pre + IntToStr(i); FRedisHandle.ListLPush(C_List_Key, aValue); Status(C_List_Key + ' List LPush:' + aValue); end; FRedisHandle.ListLPush(C_List_Key, ['111','222','333']); end; procedure TestTRedisHandle.TestListRange; var aLen: Integer; aValues: TStringList; begin aLen := FRedisHandle.ListLen(C_List_Key); Status(C_List_Key + ' len: ' + IntToStr(aLen)); aValues := TStringList.Create(); try FRedisHandle.ListRange(C_List_Key, 0, aLen - 1, aValues); Status(aValues.Text); finally aValues.Free; end; end; procedure TestTRedisHandle.TestListRemove; var i, aRemoveCount: Integer; aValue: String; begin for i := 0 to 9 do begin aValue := C_List_Value_Pre + IntToStr(i); aRemoveCount := FRedisHandle.ListRemove(C_List_Key, aValue, 2); Status(C_List_Key + ' Remove ' + aValue + ' count:' + IntToStr(aRemoveCount)); end; end; procedure TestTRedisHandle.TestListRPop; var aValue: String; begin while True do begin aValue := FRedisHandle.ListRPop(C_List_Key); if aValue = '' then Break; Status(aValue); end; end; procedure TestTRedisHandle.TestListRPush; var i: Integer; aValue: String; begin for i := 0 to 9 do begin aValue := C_List_Value_Pre + IntToStr(i); FRedisHandle.ListRPush(C_List_Key, aValue); Status(C_List_Key + ' List RPush:' + aValue); end; FRedisHandle.ListRPush(C_List_Key, ['111','222','333']); end; procedure TestTRedisHandle.TestKey; var aKey: string; begin aKey := C_Key_Pre + IntToStr(100); FRedisHandle.StringSet(aKey, '123'); CheckTrue(FRedisHandle.KeyExist(aKey), 'KeyExist Fail'); Status('KeyExist ok'); FRedisHandle.KeySetExpire(aKey, 2); Sleep(2010); CheckTrue(not FRedisHandle.KeyExist(aKey), 'KeyExist Fail'); Status('KeySetExpire ok'); FRedisHandle.StringSet(aKey, '123'); FRedisHandle.KeyDelete(aKey); CheckTrue(not FRedisHandle.KeyExist(aKey), 'KeyDelete Fail'); Status('KeyDelete ok'); end; procedure TestTRedisHandle.TestStringGetSet; var aKey, aValue, aNewValue: string; i: Integer; begin for i := 0 to 9 do begin aKey := C_Key_Pre + IntToStr(i); aNewValue := 'new:' + IntToStr(i); aValue := 'old:' + IntToStr(i); FRedisHandle.StringSet(aKey, aValue); CheckTrue(aValue = FRedisHandle.StringGetSet(aKey, aNewValue)); CheckTrue(aNewValue = FRedisHandle.StringGet(aKey), 'StringGetSet fail'); Status(aKey + ' : ' + aValue + ',' + aNewValue); end; end; procedure TestTRedisHandle.TestStringSetExpire; var aValue: string; aKey: string; i: Integer; begin for i := 0 to 9 do begin aKey := C_Key_Pre + IntToStr(i); aValue := C_Value_Pre + IntToStr(i); FRedisHandle.StringSet(aKey, aValue, 15); Status('Set ' + aKey + ' : ' + aValue); end; end; initialization // Register any test cases with the test runner RegisterTest(TestTRedisHandle.Suite); end.
{ Date Created: 5/22/00 11:17:33 AM } unit InfoLENDERSOAREPORTHISTORYTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoLENDERSOAREPORTHISTORYRecord = record PAutoinc: Word; PUserid: String[5]; PReportDate: String[10]; PTitle: String[100]; PDataIncluded: SmallInt; PBeginingWith: SmallInt; PPrintZeros: SmallInt; PPrintNotes: SmallInt; PFromDate: String[10]; PToDate: String[10]; PLenderGroup: String[10]; PReportFileName: String[12]; PReportProcessed: Boolean; End; TInfoLENDERSOAREPORTHISTORYBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoLENDERSOAREPORTHISTORYRecord end; TEIInfoLENDERSOAREPORTHISTORY = (InfoLENDERSOAREPORTHISTORYPrimaryKey, InfoLENDERSOAREPORTHISTORYUser, InfoLENDERSOAREPORTHISTORYDate); TInfoLENDERSOAREPORTHISTORYTable = class( TDBISAMTableAU ) private FDFAutoinc: TWordField; FDFUserid: TStringField; FDFReportDate: TStringField; FDFTitle: TStringField; FDFDataIncluded: TSmallIntField; FDFBeginingWith: TSmallIntField; FDFPrintZeros: TSmallIntField; FDFPrintNotes: TSmallIntField; FDFFromDate: TStringField; FDFToDate: TStringField; FDFLenderGroup: TStringField; FDFLenderString: TBlobField; FDFReportFileName: TStringField; FDFReportProcessed: TBooleanField; procedure SetPAutoinc(const Value: Word); function GetPAutoinc:Word; procedure SetPUserid(const Value: String); function GetPUserid:String; procedure SetPReportDate(const Value: String); function GetPReportDate:String; procedure SetPTitle(const Value: String); function GetPTitle:String; procedure SetPDataIncluded(const Value: SmallInt); function GetPDataIncluded:SmallInt; procedure SetPBeginingWith(const Value: SmallInt); function GetPBeginingWith:SmallInt; procedure SetPPrintZeros(const Value: SmallInt); function GetPPrintZeros:SmallInt; procedure SetPPrintNotes(const Value: SmallInt); function GetPPrintNotes:SmallInt; procedure SetPFromDate(const Value: String); function GetPFromDate:String; procedure SetPToDate(const Value: String); function GetPToDate:String; procedure SetPLenderGroup(const Value: String); function GetPLenderGroup:String; procedure SetPReportFileName(const Value: String); function GetPReportFileName:String; procedure SetPReportProcessed(const Value: Boolean); function GetPReportProcessed:Boolean; procedure SetEnumIndex(Value: TEIInfoLENDERSOAREPORTHISTORY); function GetEnumIndex: TEIInfoLENDERSOAREPORTHISTORY; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoLENDERSOAREPORTHISTORYRecord; procedure StoreDataBuffer(ABuffer:TInfoLENDERSOAREPORTHISTORYRecord); property DFAutoinc: TWordField read FDFAutoinc; property DFUserid: TStringField read FDFUserid; property DFReportDate: TStringField read FDFReportDate; property DFTitle: TStringField read FDFTitle; property DFDataIncluded: TSmallIntField read FDFDataIncluded; property DFBeginingWith: TSmallIntField read FDFBeginingWith; property DFPrintZeros: TSmallIntField read FDFPrintZeros; property DFPrintNotes: TSmallIntField read FDFPrintNotes; property DFFromDate: TStringField read FDFFromDate; property DFToDate: TStringField read FDFToDate; property DFLenderGroup: TStringField read FDFLenderGroup; property DFLenderString: TBlobField read FDFLenderString; property DFReportFileName: TStringField read FDFReportFileName; property DFReportProcessed: TBooleanField read FDFReportProcessed; property PAutoinc: Word read GetPAutoinc write SetPAutoinc; property PUserid: String read GetPUserid write SetPUserid; property PReportDate: String read GetPReportDate write SetPReportDate; property PTitle: String read GetPTitle write SetPTitle; property PDataIncluded: SmallInt read GetPDataIncluded write SetPDataIncluded; property PBeginingWith: SmallInt read GetPBeginingWith write SetPBeginingWith; property PPrintZeros: SmallInt read GetPPrintZeros write SetPPrintZeros; property PPrintNotes: SmallInt read GetPPrintNotes write SetPPrintNotes; property PFromDate: String read GetPFromDate write SetPFromDate; property PToDate: String read GetPToDate write SetPToDate; property PLenderGroup: String read GetPLenderGroup write SetPLenderGroup; property PReportFileName: String read GetPReportFileName write SetPReportFileName; property PReportProcessed: Boolean read GetPReportProcessed write SetPReportProcessed; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoLENDERSOAREPORTHISTORY read GetEnumIndex write SetEnumIndex; end; { TInfoLENDERSOAREPORTHISTORYTable } procedure Register; implementation procedure TInfoLENDERSOAREPORTHISTORYTable.CreateFields; begin FDFAutoinc := CreateField( 'Autoinc' ) as TWordField; FDFUserid := CreateField( 'Userid' ) as TStringField; FDFReportDate := CreateField( 'ReportDate' ) as TStringField; FDFTitle := CreateField( 'Title' ) as TStringField; FDFDataIncluded := CreateField( 'DataIncluded' ) as TSmallIntField; FDFBeginingWith := CreateField( 'BeginingWith' ) as TSmallIntField; FDFPrintZeros := CreateField( 'PrintZeros' ) as TSmallIntField; FDFPrintNotes := CreateField( 'PrintNotes' ) as TSmallIntField; FDFFromDate := CreateField( 'FromDate' ) as TStringField; FDFToDate := CreateField( 'ToDate' ) as TStringField; FDFLenderGroup := CreateField( 'LenderGroup' ) as TStringField; FDFLenderString := CreateField( 'LenderString' ) as TBlobField; FDFReportFileName := CreateField( 'ReportFileName' ) as TStringField; FDFReportProcessed := CreateField( 'ReportProcessed' ) as TBooleanField; end; { TInfoLENDERSOAREPORTHISTORYTable.CreateFields } procedure TInfoLENDERSOAREPORTHISTORYTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoLENDERSOAREPORTHISTORYTable.SetActive } procedure TInfoLENDERSOAREPORTHISTORYTable.Validate; begin { Enter Validation Code Here } end; { TInfoLENDERSOAREPORTHISTORYTable.Validate } procedure TInfoLENDERSOAREPORTHISTORYTable.SetPAutoinc(const Value: Word); begin DFAutoinc.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPAutoinc:Word; begin result := DFAutoinc.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPUserid(const Value: String); begin DFUserid.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPUserid:String; begin result := DFUserid.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPReportDate(const Value: String); begin DFReportDate.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPReportDate:String; begin result := DFReportDate.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPTitle(const Value: String); begin DFTitle.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPTitle:String; begin result := DFTitle.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPDataIncluded(const Value: SmallInt); begin DFDataIncluded.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPDataIncluded:SmallInt; begin result := DFDataIncluded.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPBeginingWith(const Value: SmallInt); begin DFBeginingWith.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPBeginingWith:SmallInt; begin result := DFBeginingWith.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPPrintZeros(const Value: SmallInt); begin DFPrintZeros.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPPrintZeros:SmallInt; begin result := DFPrintZeros.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPPrintNotes(const Value: SmallInt); begin DFPrintNotes.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPPrintNotes:SmallInt; begin result := DFPrintNotes.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPFromDate(const Value: String); begin DFFromDate.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPFromDate:String; begin result := DFFromDate.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPToDate(const Value: String); begin DFToDate.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPToDate:String; begin result := DFToDate.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPLenderGroup(const Value: String); begin DFLenderGroup.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPLenderGroup:String; begin result := DFLenderGroup.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPReportFileName(const Value: String); begin DFReportFileName.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPReportFileName:String; begin result := DFReportFileName.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetPReportProcessed(const Value: Boolean); begin DFReportProcessed.Value := Value; end; function TInfoLENDERSOAREPORTHISTORYTable.GetPReportProcessed:Boolean; begin result := DFReportProcessed.Value; end; procedure TInfoLENDERSOAREPORTHISTORYTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Autoinc, Word, 0, N'); Add('Userid, String, 5, N'); Add('ReportDate, String, 10, N'); Add('Title, String, 100, N'); Add('DataIncluded, SmallInt, 0, N'); Add('BeginingWith, SmallInt, 0, N'); Add('PrintZeros, SmallInt, 0, N'); Add('PrintNotes, SmallInt, 0, N'); Add('FromDate, String, 10, N'); Add('ToDate, String, 10, N'); Add('LenderGroup, String, 10, N'); Add('LenderString, Blob, 0, N'); Add('ReportFileName, String, 12, N'); Add('ReportProcessed, Boolean, 0, N'); end; end; procedure TInfoLENDERSOAREPORTHISTORYTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, Autoinc, Y, Y, N, N'); Add('User, Userid;Autoinc, N, N, N, N'); Add('Date, ReportDate, N, N, N, N'); end; end; procedure TInfoLENDERSOAREPORTHISTORYTable.SetEnumIndex(Value: TEIInfoLENDERSOAREPORTHISTORY); begin case Value of InfoLENDERSOAREPORTHISTORYPrimaryKey : IndexName := ''; InfoLENDERSOAREPORTHISTORYUser : IndexName := 'User'; InfoLENDERSOAREPORTHISTORYDate : IndexName := 'Date'; end; end; function TInfoLENDERSOAREPORTHISTORYTable.GetDataBuffer:TInfoLENDERSOAREPORTHISTORYRecord; var buf: TInfoLENDERSOAREPORTHISTORYRecord; begin fillchar(buf, sizeof(buf), 0); buf.PAutoinc := DFAutoinc.Value; buf.PUserid := DFUserid.Value; buf.PReportDate := DFReportDate.Value; buf.PTitle := DFTitle.Value; buf.PDataIncluded := DFDataIncluded.Value; buf.PBeginingWith := DFBeginingWith.Value; buf.PPrintZeros := DFPrintZeros.Value; buf.PPrintNotes := DFPrintNotes.Value; buf.PFromDate := DFFromDate.Value; buf.PToDate := DFToDate.Value; buf.PLenderGroup := DFLenderGroup.Value; buf.PReportFileName := DFReportFileName.Value; buf.PReportProcessed := DFReportProcessed.Value; result := buf; end; procedure TInfoLENDERSOAREPORTHISTORYTable.StoreDataBuffer(ABuffer:TInfoLENDERSOAREPORTHISTORYRecord); begin DFAutoinc.Value := ABuffer.PAutoinc; DFUserid.Value := ABuffer.PUserid; DFReportDate.Value := ABuffer.PReportDate; DFTitle.Value := ABuffer.PTitle; DFDataIncluded.Value := ABuffer.PDataIncluded; DFBeginingWith.Value := ABuffer.PBeginingWith; DFPrintZeros.Value := ABuffer.PPrintZeros; DFPrintNotes.Value := ABuffer.PPrintNotes; DFFromDate.Value := ABuffer.PFromDate; DFToDate.Value := ABuffer.PToDate; DFLenderGroup.Value := ABuffer.PLenderGroup; DFReportFileName.Value := ABuffer.PReportFileName; DFReportProcessed.Value := ABuffer.PReportProcessed; end; function TInfoLENDERSOAREPORTHISTORYTable.GetEnumIndex: TEIInfoLENDERSOAREPORTHISTORY; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoLENDERSOAREPORTHISTORYPrimaryKey; if iname = 'USER' then result := InfoLENDERSOAREPORTHISTORYUser; if iname = 'DATE' then result := InfoLENDERSOAREPORTHISTORYDate; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoLENDERSOAREPORTHISTORYTable, TInfoLENDERSOAREPORTHISTORYBuffer ] ); end; { Register } function TInfoLENDERSOAREPORTHISTORYBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PAutoinc; 2 : result := @Data.PUserid; 3 : result := @Data.PReportDate; 4 : result := @Data.PTitle; 5 : result := @Data.PDataIncluded; 6 : result := @Data.PBeginingWith; 7 : result := @Data.PPrintZeros; 8 : result := @Data.PPrintNotes; 9 : result := @Data.PFromDate; 10 : result := @Data.PToDate; 11 : result := @Data.PLenderGroup; 12 : result := @Data.PReportFileName; 13 : result := @Data.PReportProcessed; end; end; end. { InfoLENDERSOAREPORTHISTORYTable }
{ Mark Sattolo 428500 CSI-1100A DGD-1 TA: Chris Lankester Class Notes p.79, Question 6 } program GetSomething (input,output); { This program finds the most frequently occurring word in a string. } { Data Dictionary Givens: S - a string consisting of words separated by single spaces. Intermediates: Words - an array filled with the individual words in S. NumWords - the number of words in Words. Results: FreqWord - the most frequently occuring word in S. Uses: SWAP } const Maxsize = 27; type CharArray = array[1..MaxSize] of char; { ************************************************************************ } procedure FillArray(var ArrayName : CharArray; var ArraySize : integer); var K : integer; { K - an index in the prompt for values. } begin { procedure FillArray } repeat write('Please enter the size [ from 1 to ', MaxSize, ' ] of the array: '); readln(ArraySize); writeln; until (ArraySize <= MaxSize) and (ArraySize > 0); for K := 1 to ArraySize do begin writeln('Please enter array value #', K, '?'); read(ArrayName[K]) end; { for } end; { procedure FillArray } {*************************************************************************************} var A, B : CharArray; N, M, X, i, r : integer; begin { Read in the program's givens. } repeat { start input loop } { Get the input values } writeln('For the array to be searched,'); FillArray(A, N); writeln; writeln('Enter the # of spaces to rotate the array,'); write(' +ve for right, -ve for left, 0 to exit: '); readln(X); { body } if X <> 0 then begin M := X mod N; if M < 0 then M := N + M; for i := 1 to N do if (i - M) > 0 then B[i] := A[i-M] else B[i] := A[N+i-M]; { write out the results } writeln; writeln('***************************************************'); writeln(' CSI-1100 Class Notes p.79, Question 6'); writeln('***************************************************'); writeln; writeln; write('The altered array is: '); for r := 1 to N do write(B[r]:3); writeln; writeln; end; { if X <> 0 } until X = 0; end.
unit RotateTextDemoMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.TypInfo, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.RotatingText, FMX.Controls.Presentation, FMX.StdCtrls, FMX.Ani, FMX.Layouts, FMX.ListBox; type TRotatingTextDemoForm = class(TForm) rbTopToBottom: TRadioButton; rbBottomToTop: TRadioButton; GroupBox1: TGroupBox; FMXRotatingText1: TFMXRotatingText; Text1: TText; ListBox1: TListBox; GroupBox2: TGroupBox; rbSelectRight: TRadioButton; rbSelectLeft: TRadioButton; GridPanelLayout1: TGridPanelLayout; FMXRotatingText2: TFMXRotatingText; TextLeft: TText; TextRight: TText; Layout1: TLayout; procedure FormCreate(Sender: TObject); procedure rbTopToBottomChange(Sender: TObject); procedure ListBox1Change(Sender: TObject); private { Private declarations } function GetMoveTypeName(AType: TInterpolationType): string; function GetSelectRotatingText: TFMXRotatingText; function GetSelectText: TText; public { Public declarations } end; var RotatingTextDemoForm: TRotatingTextDemoForm; implementation {$R *.fmx} procedure TRotatingTextDemoForm.FormCreate(Sender: TObject); begin ListBox1.ItemIndex := 0; TextLeft.Text := GetMoveTypeName(FMXRotatingText1.MovingType); TextRight.Text := GetMoveTypeName(FMXRotatingText2.MovingType); FMXRotatingText1.Start; FMXRotatingText2.Start; end; function TRotatingTextDemoForm.GetMoveTypeName(AType: TInterpolationType): string; begin Result := GetEnumName(TypeInfo(TInterpolationType),Ord(AType)); end; function TRotatingTextDemoForm.GetSelectRotatingText: TFMXRotatingText; begin if rbSelectLeft.IsChecked then Result := FMXRotatingText1 else Result := FMXRotatingText2; end; function TRotatingTextDemoForm.GetSelectText: TText; begin if rbSelectLeft.IsChecked then Result := TextLeft else Result := TextRight; end; procedure TRotatingTextDemoForm.ListBox1Change(Sender: TObject); begin GetSelectRotatingText().MovingType := TInterpolationType(ListBox1.ItemIndex); GetSelectText().Text := GetMoveTypeName(TInterpolationType(ListBox1.ItemIndex)); end; procedure TRotatingTextDemoForm.rbTopToBottomChange(Sender: TObject); begin if rbTopToBottom.IsChecked then begin FMXRotatingText1.RotatingDirection := TRotatingDirection.TopToBottom; FMXRotatingText2.RotatingDirection := TRotatingDirection.TopToBottom; end else begin FMXRotatingText1.RotatingDirection := TRotatingDirection.BottomToTop; FMXRotatingText2.RotatingDirection := TRotatingDirection.BottomToTop; end; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.4 2/7/2004 7:20:18 PM JPMugaas DotNET to go!! and YES - I want fries with that :-). Rev 1.3 2004.02.03 5:44:38 PM czhower Name changes Rev 1.2 10/25/2003 06:52:18 AM JPMugaas Updated for new API changes and tried to restore some functionality. Rev 1.1 2003.10.12 6:36:48 PM czhower Now compiles. Rev 1.0 11/13/2002 08:03:38 AM JPMugaas } unit IdTrivialFTPBase; interface {$i IdCompilerDefines.inc} uses IdGlobal, IdUDPBase, IdUDPClient, SysUtils; type TIdTFTPMode = (tfNetAscii, tfOctet); // Procs function MakeActPkt(const BlockNumber: Word): TIdBytes; procedure SendError(UDPBase: TIdUDPBase; APeerIP: string; const APort: TIdPort; const ErrNumber: Word; const ErrString: string); overload; procedure SendError(UDPClient: TIdUDPClient; const ErrNumber: Word; const ErrString: string); overload; procedure SendError(UDPBase: TIdUDPBase; APeerIP: string; const APort: TIdPort; E: Exception); overload; procedure SendError(UDPClient: TIdUDPClient; E: Exception); overload; const // TFTP opcodes TFTP_RRQ = 1; TFTP_WRQ = 2; TFTP_DATA = 3; TFTP_ACK = 4; TFTP_ERROR = 5; TFTP_OACK = 6; // see RFC 1782 and 1783 const // TFTP error codes ErrUndefined = 0; ErrFileNotFound = 1; ErrAccessViolation = 2; ErrAllocationExceeded = 3; ErrIllegalOperation = 4; ErrUnknownTransferID = 5; ErrFileAlreadyExists = 6; ErrNoSuchUser = 7; ErrOptionNegotiationFailed = 8; const // TFTP options sBlockSize = 'blksize'; {do not localize} sTransferSize = 'tsize'; {do not localize} implementation uses IdGlobalProtocols, IdExceptionCore, IdStack; function MakeActPkt(const BlockNumber: Word): TIdBytes; begin SetLength(Result, 4); CopyTIdWord(GStack.HostToNetwork(Word(TFTP_ACK)), Result, 0); CopyTIdWord(GStack.HostToNetwork(BlockNumber), Result, 2); end; procedure SendError(UDPBase: TIdUDPBase; APeerIP: string; const APort: TIdPort; const ErrNumber: Word; const ErrString: string); var Buffer, LErrStr: TIdBytes; begin LErrStr := ToBytes(ErrString); SetLength(Buffer, 4 + Length(LErrStr) + 1); CopyTIdWord(GStack.HostToNetwork(Word(TFTP_ERROR)), Buffer, 0); CopyTIdWord(GStack.HostToNetwork(ErrNumber), Buffer, 2); CopyTIdBytes(LErrStr, 0, Buffer, 4, Length(LErrStr)); Buffer[4 + Length(LErrStr)] := 0; UDPBase.SendBuffer(APeerIP, APort, Buffer); end; procedure SendError(UDPClient: TIdUDPClient; const ErrNumber: Word; const ErrString: string); begin SendError(UDPClient, UDPClient.Host, UDPClient.Port, ErrNumber, ErrString); end; procedure SendError(UDPBase: TIdUDPBase; APeerIP: string; const APort: TIdPort; E: Exception); var ErrNumber: Word; begin ErrNumber := ErrUndefined; if E is EIdTFTPFileNotFound then begin ErrNumber := ErrFileNotFound; end; if E is EIdTFTPAccessViolation then begin ErrNumber := ErrAccessViolation; end; if E is EIdTFTPAllocationExceeded then begin ErrNumber := ErrAllocationExceeded; end; if E is EIdTFTPIllegalOperation then begin ErrNumber := ErrIllegalOperation; end; if E is EIdTFTPUnknownTransferID then begin ErrNumber := ErrUnknownTransferID; end; if E is EIdTFTPFileAlreadyExists then begin ErrNumber := ErrFileAlreadyExists; end; if E is EIdTFTPNoSuchUser then begin ErrNumber := ErrNoSuchUser; end; if E is EIdTFTPOptionNegotiationFailed then begin ErrNumber := ErrOptionNegotiationFailed; end; SendError(UDPBase, APeerIP, APort, ErrNumber, E.Message); end; procedure SendError(UDPClient: TIdUDPClient; E: Exception); begin SendError(UDPClient, UDPClient.Host, UDPClient.Port, E); end; end.
unit UserListKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы UserList } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\Admin\UserListKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "UserListKeywordsPack" MUID: (551DFEBFD5FA) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If Defined(Admin) AND NOT Defined(NoScripts)} uses l3IntfUses , vtPanel {$If Defined(Nemesis)} , nscContextFilter {$IfEnd} // Defined(Nemesis) , eeTreeView ; {$IfEnd} // Defined(Admin) AND NOT Defined(NoScripts) implementation {$If Defined(Admin) AND NOT Defined(NoScripts)} uses l3ImplUses , UserList_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_UserList = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы UserList ---- *Пример использования*: [code] 'aControl' форма::UserList TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_UserList Tkw_UserList_Control_BackgroundPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UserList_Control_BackgroundPanel Tkw_UserList_Control_BackgroundPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола BackgroundPanel ---- *Пример использования*: [code] контрол::BackgroundPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UserList_Control_BackgroundPanel_Push Tkw_UserList_Control_ContextFilter = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ContextFilter ---- *Пример использования*: [code] контрол::ContextFilter TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UserList_Control_ContextFilter Tkw_UserList_Control_ContextFilter_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола ContextFilter ---- *Пример использования*: [code] контрол::ContextFilter:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UserList_Control_ContextFilter_Push Tkw_UserList_Control_trUserList = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола trUserList ---- *Пример использования*: [code] контрол::trUserList TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UserList_Control_trUserList Tkw_UserList_Control_trUserList_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола trUserList ---- *Пример использования*: [code] контрол::trUserList:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_UserList_Control_trUserList_Push TkwEfUserListBackgroundPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TefUserList.BackgroundPanel } private function BackgroundPanel(const aCtx: TtfwContext; aefUserList: TefUserList): TvtPanel; {* Реализация слова скрипта .TefUserList.BackgroundPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEfUserListBackgroundPanel TkwEfUserListContextFilter = {final} class(TtfwPropertyLike) {* Слово скрипта .TefUserList.ContextFilter } private function ContextFilter(const aCtx: TtfwContext; aefUserList: TefUserList): TnscContextFilter; {* Реализация слова скрипта .TefUserList.ContextFilter } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEfUserListContextFilter TkwEfUserListTrUserList = {final} class(TtfwPropertyLike) {* Слово скрипта .TefUserList.trUserList } private function trUserList(const aCtx: TtfwContext; aefUserList: TefUserList): TeeTreeView; {* Реализация слова скрипта .TefUserList.trUserList } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwEfUserListTrUserList function Tkw_Form_UserList.GetString: AnsiString; begin Result := 'efUserList'; end;//Tkw_Form_UserList.GetString class function Tkw_Form_UserList.GetWordNameForRegister: AnsiString; begin Result := 'форма::UserList'; end;//Tkw_Form_UserList.GetWordNameForRegister function Tkw_UserList_Control_BackgroundPanel.GetString: AnsiString; begin Result := 'BackgroundPanel'; end;//Tkw_UserList_Control_BackgroundPanel.GetString class procedure Tkw_UserList_Control_BackgroundPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_UserList_Control_BackgroundPanel.RegisterInEngine class function Tkw_UserList_Control_BackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel'; end;//Tkw_UserList_Control_BackgroundPanel.GetWordNameForRegister procedure Tkw_UserList_Control_BackgroundPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('BackgroundPanel'); inherited; end;//Tkw_UserList_Control_BackgroundPanel_Push.DoDoIt class function Tkw_UserList_Control_BackgroundPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::BackgroundPanel:push'; end;//Tkw_UserList_Control_BackgroundPanel_Push.GetWordNameForRegister function Tkw_UserList_Control_ContextFilter.GetString: AnsiString; begin Result := 'ContextFilter'; end;//Tkw_UserList_Control_ContextFilter.GetString class procedure Tkw_UserList_Control_ContextFilter.RegisterInEngine; begin inherited; TtfwClassRef.Register(TnscContextFilter); end;//Tkw_UserList_Control_ContextFilter.RegisterInEngine class function Tkw_UserList_Control_ContextFilter.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter'; end;//Tkw_UserList_Control_ContextFilter.GetWordNameForRegister procedure Tkw_UserList_Control_ContextFilter_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('ContextFilter'); inherited; end;//Tkw_UserList_Control_ContextFilter_Push.DoDoIt class function Tkw_UserList_Control_ContextFilter_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::ContextFilter:push'; end;//Tkw_UserList_Control_ContextFilter_Push.GetWordNameForRegister function Tkw_UserList_Control_trUserList.GetString: AnsiString; begin Result := 'trUserList'; end;//Tkw_UserList_Control_trUserList.GetString class procedure Tkw_UserList_Control_trUserList.RegisterInEngine; begin inherited; TtfwClassRef.Register(TeeTreeView); end;//Tkw_UserList_Control_trUserList.RegisterInEngine class function Tkw_UserList_Control_trUserList.GetWordNameForRegister: AnsiString; begin Result := 'контрол::trUserList'; end;//Tkw_UserList_Control_trUserList.GetWordNameForRegister procedure Tkw_UserList_Control_trUserList_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('trUserList'); inherited; end;//Tkw_UserList_Control_trUserList_Push.DoDoIt class function Tkw_UserList_Control_trUserList_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::trUserList:push'; end;//Tkw_UserList_Control_trUserList_Push.GetWordNameForRegister function TkwEfUserListBackgroundPanel.BackgroundPanel(const aCtx: TtfwContext; aefUserList: TefUserList): TvtPanel; {* Реализация слова скрипта .TefUserList.BackgroundPanel } begin Result := aefUserList.BackgroundPanel; end;//TkwEfUserListBackgroundPanel.BackgroundPanel class function TkwEfUserListBackgroundPanel.GetWordNameForRegister: AnsiString; begin Result := '.TefUserList.BackgroundPanel'; end;//TkwEfUserListBackgroundPanel.GetWordNameForRegister function TkwEfUserListBackgroundPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwEfUserListBackgroundPanel.GetResultTypeInfo function TkwEfUserListBackgroundPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfUserListBackgroundPanel.GetAllParamsCount function TkwEfUserListBackgroundPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefUserList)]); end;//TkwEfUserListBackgroundPanel.ParamsTypes procedure TkwEfUserListBackgroundPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству BackgroundPanel', aCtx); end;//TkwEfUserListBackgroundPanel.SetValuePrim procedure TkwEfUserListBackgroundPanel.DoDoIt(const aCtx: TtfwContext); var l_aefUserList: TefUserList; begin try l_aefUserList := TefUserList(aCtx.rEngine.PopObjAs(TefUserList)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefUserList: TefUserList : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(BackgroundPanel(aCtx, l_aefUserList)); end;//TkwEfUserListBackgroundPanel.DoDoIt function TkwEfUserListContextFilter.ContextFilter(const aCtx: TtfwContext; aefUserList: TefUserList): TnscContextFilter; {* Реализация слова скрипта .TefUserList.ContextFilter } begin Result := aefUserList.ContextFilter; end;//TkwEfUserListContextFilter.ContextFilter class function TkwEfUserListContextFilter.GetWordNameForRegister: AnsiString; begin Result := '.TefUserList.ContextFilter'; end;//TkwEfUserListContextFilter.GetWordNameForRegister function TkwEfUserListContextFilter.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TnscContextFilter); end;//TkwEfUserListContextFilter.GetResultTypeInfo function TkwEfUserListContextFilter.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfUserListContextFilter.GetAllParamsCount function TkwEfUserListContextFilter.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefUserList)]); end;//TkwEfUserListContextFilter.ParamsTypes procedure TkwEfUserListContextFilter.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ContextFilter', aCtx); end;//TkwEfUserListContextFilter.SetValuePrim procedure TkwEfUserListContextFilter.DoDoIt(const aCtx: TtfwContext); var l_aefUserList: TefUserList; begin try l_aefUserList := TefUserList(aCtx.rEngine.PopObjAs(TefUserList)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefUserList: TefUserList : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ContextFilter(aCtx, l_aefUserList)); end;//TkwEfUserListContextFilter.DoDoIt function TkwEfUserListTrUserList.trUserList(const aCtx: TtfwContext; aefUserList: TefUserList): TeeTreeView; {* Реализация слова скрипта .TefUserList.trUserList } begin Result := aefUserList.trUserList; end;//TkwEfUserListTrUserList.trUserList class function TkwEfUserListTrUserList.GetWordNameForRegister: AnsiString; begin Result := '.TefUserList.trUserList'; end;//TkwEfUserListTrUserList.GetWordNameForRegister function TkwEfUserListTrUserList.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TeeTreeView); end;//TkwEfUserListTrUserList.GetResultTypeInfo function TkwEfUserListTrUserList.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwEfUserListTrUserList.GetAllParamsCount function TkwEfUserListTrUserList.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TefUserList)]); end;//TkwEfUserListTrUserList.ParamsTypes procedure TkwEfUserListTrUserList.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству trUserList', aCtx); end;//TkwEfUserListTrUserList.SetValuePrim procedure TkwEfUserListTrUserList.DoDoIt(const aCtx: TtfwContext); var l_aefUserList: TefUserList; begin try l_aefUserList := TefUserList(aCtx.rEngine.PopObjAs(TefUserList)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aefUserList: TefUserList : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(trUserList(aCtx, l_aefUserList)); end;//TkwEfUserListTrUserList.DoDoIt initialization Tkw_Form_UserList.RegisterInEngine; {* Регистрация Tkw_Form_UserList } Tkw_UserList_Control_BackgroundPanel.RegisterInEngine; {* Регистрация Tkw_UserList_Control_BackgroundPanel } Tkw_UserList_Control_BackgroundPanel_Push.RegisterInEngine; {* Регистрация Tkw_UserList_Control_BackgroundPanel_Push } Tkw_UserList_Control_ContextFilter.RegisterInEngine; {* Регистрация Tkw_UserList_Control_ContextFilter } Tkw_UserList_Control_ContextFilter_Push.RegisterInEngine; {* Регистрация Tkw_UserList_Control_ContextFilter_Push } Tkw_UserList_Control_trUserList.RegisterInEngine; {* Регистрация Tkw_UserList_Control_trUserList } Tkw_UserList_Control_trUserList_Push.RegisterInEngine; {* Регистрация Tkw_UserList_Control_trUserList_Push } TkwEfUserListBackgroundPanel.RegisterInEngine; {* Регистрация efUserList_BackgroundPanel } TkwEfUserListContextFilter.RegisterInEngine; {* Регистрация efUserList_ContextFilter } TkwEfUserListTrUserList.RegisterInEngine; {* Регистрация efUserList_trUserList } TtfwTypeRegistrator.RegisterType(TypeInfo(TefUserList)); {* Регистрация типа TefUserList } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TnscContextFilter)); {* Регистрация типа TnscContextFilter } TtfwTypeRegistrator.RegisterType(TypeInfo(TeeTreeView)); {* Регистрация типа TeeTreeView } {$IfEnd} // Defined(Admin) AND NOT Defined(NoScripts) end.
unit UCircle; interface uses UFigure, SysUtils, Graphics, ExtCtrls, Windows; const Pi = 3.1415; type TCircle = class(TFigure) private FRadius: integer; public constructor Create(APoint: TPoint; AColor:TColor; ARadius:integer); function Area:real; override; procedure Draw(Image: TImage); override; class function WhatItIs:string; override; property radius:integer read FRadius write FRadius; end; implementation class function TCircle.WhatItIs:string; begin Result:= 'Круг'; end; constructor TCircle.Create(APoint: TPoint; AColor:TColor; ARadius:integer); begin inherited Create(APoint, AColor); FRadius:= ARadius; end; function TCircle.Area:real; begin Result:= Pi * sqr(radius); end; procedure TCircle.Draw(Image: TImage); begin Image.Canvas.Brush.Color:= Color; Image.Canvas.Ellipse(point.X - radius, point.Y - radius, point.X + radius, point.Y + radius); end; end.
unit atQueryExecutor; // Модуль: "w:\quality\test\garant6x\AdapterTest\SearchHelpers\atQueryExecutor.pas" // Стереотип: "UtilityPack" // Элемент модели: "atQueryExecutor" MUID: (483AD11C02A1) interface uses l3IntfUses , l3_Base , SearchUnit , BaseTypesUnit , DynamicDocListUnit ; type TatQueryExecutor = class(Tl3_Base) private f_Query: IQuery; protected {$If NOT Defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} // NOT Defined(DesignTimeLibrary) procedure ClearFields; override; public constructor Create(const aQuery: IQuery); reintroduce; function Execute(const aFiltrateList: IDynList = nil): ISearchEntity; virtual; end;//TatQueryExecutor IatProgressIndicator = interface ['{59BF112D-CDE3-4018-8B4E-20DC822248E9}'] function Get_SearchResult: ISearchEntity; function HasFinished: Boolean; {* Проверить, завершено ли выполнение запроса } procedure WaitForFinish; {* Ждать завершения выполнения запроса } property SearchResult: ISearchEntity read Get_SearchResult; {* результат поиска } end;//IatProgressIndicator implementation uses l3ImplUses , SearchProgressIndicatorUnit , SyncObjs , atLogger , SysUtils , Windows //#UC START# *483AD11C02A1impl_uses* //#UC END# *483AD11C02A1impl_uses* ; type TatProgressIndicator = class(Tl3_Base, IProgressIndicatorForSearch, IatProgressIndicator) {* Класс, реализующий интерфейс IQueryexecuteProgressIndicator. Для передачи в метод Query:Execute } private f_SearchResult: ISearchEntity; f_Event: TSimpleEvent; protected procedure SetCurrent(cur_count: Integer; arg: Integer {* Дополнительный параметр. }); stdcall; {* Изменение состояния длительного процесса. В качестве параметра cur_count подается либо число уже обработанных элементов, принимающих участие в длительном процессе, либо число <=100 (при индикации в %). } function GetMaxCount: Integer; stdcall; procedure FinishProcess(const entity: ISearchEntity); stdcall; function Get_SearchResult: ISearchEntity; function HasFinished: Boolean; {* Проверить, завершено ли выполнение запроса } procedure WaitForFinish; {* Ждать завершения выполнения запроса } {$If NOT Defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} // NOT Defined(DesignTimeLibrary) procedure ClearFields; override; public constructor Create; reintroduce; virtual; class function Make: IatProgressIndicator; reintroduce; end;//TatProgressIndicator constructor TatQueryExecutor.Create(const aQuery: IQuery); //#UC START# *483AD15D03AA_483AD1320001_var* //#UC END# *483AD15D03AA_483AD1320001_var* begin //#UC START# *483AD15D03AA_483AD1320001_impl* inherited Create; // Assert(aQuery <> nil, 'aQuery <> nil'); f_Query := aQuery; //#UC END# *483AD15D03AA_483AD1320001_impl* end;//TatQueryExecutor.Create function TatQueryExecutor.Execute(const aFiltrateList: IDynList = nil): ISearchEntity; //#UC START# *483AD178007E_483AD1320001_var* var l_ProgressIndicator : IatProgressIndicator; l_CancelSearch : ICancelSearch; //#UC END# *483AD178007E_483AD1320001_var* begin //#UC START# *483AD178007E_483AD1320001_impl* l_ProgressIndicator := TatProgressIndicator.Make; // запускаем выполнение запроса try f_Query.Execute(aFiltrateList, l_ProgressIndicator as IProgressIndicatorForSearch, l_CancelSearch); except on ex : Exception do begin Logger.Exception(ex, 'Исключение во время выполнения Query.Execute'); Raise; end; else Raise; end; if NOT Assigned(l_CancelSearch) then Logger.Warning('l_CancelSearch не присвоен после вызова Query.Execute'); // ждем окончания выполнения l_ProgressIndicator.WaitForFinish; // и возвращаем результат Result := l_ProgressIndicator.SearchResult; //#UC END# *483AD178007E_483AD1320001_impl* end;//TatQueryExecutor.Execute {$If NOT Defined(DesignTimeLibrary)} class function TatQueryExecutor.IsCacheable: Boolean; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } //#UC START# *47A6FEE600FC_483AD1320001_var* //#UC END# *47A6FEE600FC_483AD1320001_var* begin //#UC START# *47A6FEE600FC_483AD1320001_impl* Result := true; //#UC END# *47A6FEE600FC_483AD1320001_impl* end;//TatQueryExecutor.IsCacheable {$IfEnd} // NOT Defined(DesignTimeLibrary) procedure TatQueryExecutor.ClearFields; //#UC START# *5000565C019C_483AD1320001_var* //#UC END# *5000565C019C_483AD1320001_var* begin //#UC START# *5000565C019C_483AD1320001_impl* f_Query := nil; // inherited; //#UC END# *5000565C019C_483AD1320001_impl* end;//TatQueryExecutor.ClearFields constructor TatProgressIndicator.Create; //#UC START# *483AD6A203E0_483AD19A008E_var* //#UC END# *483AD6A203E0_483AD19A008E_var* begin //#UC START# *483AD6A203E0_483AD19A008E_impl* inherited Create; // f_Event := TSimpleEvent.Create; f_Event.ResetEvent; //#UC END# *483AD6A203E0_483AD19A008E_impl* end;//TatProgressIndicator.Create class function TatProgressIndicator.Make: IatProgressIndicator; var l_Inst : TatProgressIndicator; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TatProgressIndicator.Make procedure TatProgressIndicator.SetCurrent(cur_count: Integer; arg: Integer {* Дополнительный параметр. }); {* Изменение состояния длительного процесса. В качестве параметра cur_count подается либо число уже обработанных элементов, принимающих участие в длительном процессе, либо число <=100 (при индикации в %). } //#UC START# *45EEE00A025D_483AD19A008E_var* //#UC END# *45EEE00A025D_483AD19A008E_var* begin //#UC START# *45EEE00A025D_483AD19A008E_impl* try Logger.Info( 'Идет поиск... Выполнено %d%%', [aCurCount] ); except on ex : Exception do begin Logger.Exception(ex, 'TatProgressIndicator.SetCurrent'); Raise; end; end; //#UC END# *45EEE00A025D_483AD19A008E_impl* end;//TatProgressIndicator.SetCurrent function TatProgressIndicator.GetMaxCount: Integer; //#UC START# *45EEE02703C5_483AD19A008Eget_var* //#UC END# *45EEE02703C5_483AD19A008Eget_var* begin //#UC START# *45EEE02703C5_483AD19A008Eget_impl* Result := 100; // потому что мы хотим получать ход выполнения в процентах //#UC END# *45EEE02703C5_483AD19A008Eget_impl* end;//TatProgressIndicator.GetMaxCount procedure TatProgressIndicator.FinishProcess(const entity: ISearchEntity); //#UC START# *462741D0012E_483AD19A008E_var* //#UC END# *462741D0012E_483AD19A008E_var* begin //#UC START# *462741D0012E_483AD19A008E_impl* try f_SearchResult := aEntity; f_Event.SetEvent; except on ex : Exception do begin Logger.Exception(ex, 'TatProgressIndicator.FinishProcess'); Raise; end; else Raise; end; //#UC END# *462741D0012E_483AD19A008E_impl* end;//TatProgressIndicator.FinishProcess function TatProgressIndicator.Get_SearchResult: ISearchEntity; //#UC START# *483AD1D1039B_483AD19A008Eget_var* //#UC END# *483AD1D1039B_483AD19A008Eget_var* begin //#UC START# *483AD1D1039B_483AD19A008Eget_impl* Result := f_SearchResult; //#UC END# *483AD1D1039B_483AD19A008Eget_impl* end;//TatProgressIndicator.Get_SearchResult function TatProgressIndicator.HasFinished: Boolean; {* Проверить, завершено ли выполнение запроса } //#UC START# *483AD1F1009D_483AD19A008E_var* //#UC END# *483AD1F1009D_483AD19A008E_var* begin //#UC START# *483AD1F1009D_483AD19A008E_impl* Result := (f_Event.WaitFor(0) = wrSignaled); //#UC END# *483AD1F1009D_483AD19A008E_impl* end;//TatProgressIndicator.HasFinished procedure TatProgressIndicator.WaitForFinish; {* Ждать завершения выполнения запроса } //#UC START# *483AD202033D_483AD19A008E_var* //#UC END# *483AD202033D_483AD19A008E_var* begin //#UC START# *483AD202033D_483AD19A008E_impl* f_Event.WaitFor(INFINITE); //#UC END# *483AD202033D_483AD19A008E_impl* end;//TatProgressIndicator.WaitForFinish {$If NOT Defined(DesignTimeLibrary)} class function TatProgressIndicator.IsCacheable: Boolean; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } //#UC START# *47A6FEE600FC_483AD19A008E_var* //#UC END# *47A6FEE600FC_483AD19A008E_var* begin //#UC START# *47A6FEE600FC_483AD19A008E_impl* Result := true; //#UC END# *47A6FEE600FC_483AD19A008E_impl* end;//TatProgressIndicator.IsCacheable {$IfEnd} // NOT Defined(DesignTimeLibrary) procedure TatProgressIndicator.ClearFields; //#UC START# *5000565C019C_483AD19A008E_var* //#UC END# *5000565C019C_483AD19A008E_var* begin //#UC START# *5000565C019C_483AD19A008E_impl* f_SearchResult := nil; FreeAndNil(f_Event); // inherited; //#UC END# *5000565C019C_483AD19A008E_impl* end;//TatProgressIndicator.ClearFields end.
unit GX_ConfigureExperts; {$I GX_CondDefine.inc} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Forms, Controls, Dialogs, StdCtrls, ComCtrls, ExtCtrls; type TfrConfigureExperts = class(TFrame) pnlExpertsFilter: TPanel; lblFilter: TLabel; edtFilter: TEdit; sbxExperts: TScrollBox; pnlExpertLayout: TPanel; imgExpert: TImage; chkExpert: TCheckBox; edtExpert: THotKey; btnExpert: TButton; btnEnableAll: TButton; btnDisableAll: TButton; btnClear: TButton; btnClearAll: TButton; btnSetAllDefault: TButton; btnDefault: TButton; procedure edtFilterChange(Sender: TObject); procedure btnEnableAllClick(Sender: TObject); procedure btnDisableAllClick(Sender: TObject); procedure btnClearClick(Sender: TObject); procedure FrameMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure FrameMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure btnClearAllClick(Sender: TObject); procedure btnSetAllDefaultClick(Sender: TObject); private FThumbSize: Integer; FExperts: TList; procedure ConfigureExpertClick(_Sender: TObject); procedure FilterVisibleExperts; procedure SetAllEnabled(_Value: Boolean); procedure SetDefaultShortcutClick(_Sender: TObject); public constructor Create(_Owner: TComponent); override; destructor Destroy; override; procedure Init(_Experts: TList); procedure SaveExperts; end; implementation {$R *.dfm} uses Menus, Themes, GX_GenericUtils, GX_BaseExpert, GX_dzVclUtils, GX_DbugIntf; function IsThemesEnabled: Boolean; begin {$IF CompilerVersion >= 23} Result := StyleServices.Enabled; {$ELSE} {$IF CompilerVersion >= 18} Result := ThemeServices.ThemesEnabled; {$ELSE} Result := False; {$IFEND} {$IFEND} end; type THintImage = class(TImage) procedure CMHintShow(var _Msg: TCMHintShow); message CM_HINTSHOW; end; { THintImage } procedure THintImage.CMHintShow(var _Msg: TCMHintShow); var hi: PHintInfo; begin hi := _Msg.HintInfo; hi.HideTimeout := -1; hi.HintMaxWidth := 400; hi.HintPos := ClientToScreen(Point(0, BoundsRect.Bottom)); end; { TfrConfigureEditorExperts } constructor TfrConfigureExperts.Create(_Owner: TComponent); begin inherited; FExperts := TList.Create; if IsThemesEnabled then begin btnClear.Top := edtFilter.Top - 1; btnClear.Height := edtFilter.Height + 2; end else begin btnClear.Top := edtFilter.Top; btnClear.Height := edtFilter.Height; end; pnlExpertsFilter.FullRepaint := False; end; destructor TfrConfigureExperts.Destroy; begin FreeAndNil(FExperts); inherited; end; procedure TfrConfigureExperts.edtFilterChange(Sender: TObject); begin FilterVisibleExperts; end; function TryGetControl(_Owner: TControl; _CtrlClass: TControlClass; out _ctrl: TControl): Boolean; var i: Integer; begin Result := False; for i := 0 to _Owner.ComponentCount - 1 do begin _ctrl := _Owner.Components[i] as TControl; if _ctrl is _CtrlClass then begin Result := True; Exit; end; end; end; function GetCheckbox(_Pnl: TPanel): TCheckBox; resourcestring STR_NO_CHECKBOX = 'No checkbox found.'; begin if not TryGetControl(_Pnl, TCheckBox, TControl(Result)) then raise Exception.Create(STR_NO_CHECKBOX); end; function GetHotkeyCtrl(_Pnl: TPanel): THotKey; resourcestring STR_NO_HOTKEY = 'No hotkey control found.'; begin if not TryGetControl(_Pnl, THotKey, TControl(Result)) then raise Exception.Create(STR_NO_HOTKEY); end; function GetPanel(_sbx: TScrollBox; _Tag: Integer): TPanel; resourcestring STR_NO_PANEL = 'No panel found.'; var i: Integer; ctrl: TControl; begin for i := 0 to _sbx.ComponentCount - 1 do begin ctrl := _sbx.Components[i] as TControl; if (ctrl.Tag = _Tag) and (ctrl is TPanel) then begin Result := ctrl as TPanel; Exit; end; end; raise Exception.Create(STR_NO_PANEL); end; procedure TfrConfigureExperts.SetAllEnabled(_Value: Boolean); var i: Integer; AControl: TControl; begin for i := 0 to sbxExperts.ComponentCount - 1 do begin AControl := sbxExperts.Components[i] as TControl; if AControl is TPanel then GetCheckbox(AControl as TPanel).Checked := _Value; end; end; procedure TfrConfigureExperts.btnClearClick(Sender: TObject); begin edtFilter.Text := ''; edtFilter.SetFocus; end; procedure TfrConfigureExperts.btnDisableAllClick(Sender: TObject); begin SetAllEnabled(False); end; procedure TfrConfigureExperts.btnEnableAllClick(Sender: TObject); begin SetAllEnabled(True); end; procedure TfrConfigureExperts.btnClearAllClick(Sender: TObject); resourcestring SWarning = 'This will clear the keyboard shortcuts for all experts.'#13#10 + 'Are you sure you want to do that?'; var i: Integer; AControl: TControl; begin if MessageDlg(SWarning, mtWarning, [mbYes, mbCancel], 0) = mrYes then for i := 0 to sbxExperts.ComponentCount - 1 do begin AControl := sbxExperts.Components[i] as TControl; if AControl is TPanel then GetHotkeyCtrl(AControl as TPanel).HotKey := 0; end; end; procedure TfrConfigureExperts.btnSetAllDefaultClick(Sender: TObject); resourcestring SWarning = 'This will set the keyboard shortcuts of all experts to their defaults.'#13#10 + 'Are you sure you want to do that?'; var i: Integer; AControl: TControl; AnExpert: TGX_BaseExpert; begin if (MessageDlg(SWarning, mtWarning, [mbYes, mbCancel], 0) = mrYes) then for i := 0 to sbxExperts.ComponentCount - 1 do begin AControl := sbxExperts.Components[i] as TControl; if AControl is TPanel then begin AnExpert := FExperts[AControl.Tag]; THotkey_SetHotkey(GetHotkeyCtrl(AControl as TPanel), AnExpert.GetDefaultShortCut); end; end; end; procedure TfrConfigureExperts.ConfigureExpertClick(_Sender: TObject); var AnExpert: TGX_BaseExpert; Idx: Integer; begin Idx := (_Sender as TButton).Tag; AnExpert := FExperts[Idx]; AnExpert.Configure; end; procedure TfrConfigureExperts.SetDefaultShortcutClick(_Sender: TObject); var AnExpert: TGX_BaseExpert; Idx: Integer; begin Idx := (_Sender as TButton).Tag; AnExpert := FExperts[Idx]; THotkey_SetHotkey(GetHotkeyCtrl(GetPanel(sbxExperts, Idx)), AnExpert.GetDefaultShortCut); end; type THotKeyHack = class(thotkey) procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; end; { THotKeyHack } function AppendToCsvStr(const _AppendTo: string; const _s: string): string; begin if _AppendTo = '' then Result := _s else Result := _AppendTo + ', ' + _s; end; {$IFOPT D+} function ModifierStr(_Modifiers: THKModifiers): string; begin Result := ''; if hkShift in _Modifiers then Result := AppendToCsvStr(Result, 'hkShift'); if hkCtrl in _Modifiers then Result := AppendToCsvStr(Result, 'hkCtrl'); if hkAlt in _Modifiers then Result := AppendToCsvStr(Result, 'hkAlt'); if hkExt in _Modifiers then Result := AppendToCsvStr(Result, 'hkExt'); end; function ShiftStateToStr(_Shift: TShiftState): string; begin Result := ''; if ssShift in _Shift then Result := AppendToCsvStr(Result, 'ssShift'); if ssAlt in _Shift then Result := AppendToCsvStr(Result, 'ssAlt'); if ssCtrl in _Shift then Result := AppendToCsvStr(Result, 'ssCtrl'); if ssLeft in _Shift then Result := AppendToCsvStr(Result, 'ssLeft'); if ssRight in _Shift then Result := AppendToCsvStr(Result, 'ssRight'); if ssMiddle in _Shift then Result := AppendToCsvStr(Result, 'ssMiddle'); if ssDouble in _Shift then Result := AppendToCsvStr(Result, 'ssDouble'); end; {$ENDIF} procedure THotKeyHack.KeyDown(var Key: Word; Shift: TShiftState); var HkMods: THKModifiers; begin inherited; // This is a fix for THotkey behaving very oddly: // When pressing a key without modifiers (e.g. A) it is displayed as "A" or sometimes as "Shift + A" // even though InvalidKeys is [hcNone, hcShift] so neihter should be a valid hotkey. // This explicitly sets the Modifiers property to get the documented behaviour. // It has a side effect, though: // Pressing Shift followed by F2 will first show Alt+ followed by Shift+F2. // But that's better than the original behaviour. HkMods := Modifiers; if ssShift in Shift then Include(HkMods, hkShift) else Exclude(HkMods, hkShift); if ssCtrl in Shift then Include(HkMods, hkCtrl) else Exclude(HkMods, hkCtrl); if ssAlt in Shift then Include(HkMods, hkAlt) else Exclude(HkMods, hkAlt); if (hkmods = []) or (HkMods = [hkShift]) then begin HkMods := [hkAlt]; end; Modifiers := HkMods; {$IFOPT D+} SendDebugFmt('KeyDown(Key: %4x, Shift: [%s], ShortCut: %s, Modifiers: [%s]', [Key, ShiftStateToStr(Shift), ShortCutToText(HotKey), ModifierStr(Modifiers)]); {$ENDIF} end; procedure THotKeyHack.KeyUp(var Key: Word; Shift: TShiftState); begin inherited; inherited; {$IFOPT D+} SendDebugFmt('KeyUp(Key: %4x, Shift: [%s], ShortCut: %s, Modifiers: [%s]', [Key, ShiftStateToStr(Shift), ShortCutToText(HotKey), ModifierStr(Modifiers)]); {$ENDIF} end; procedure TfrConfigureExperts.Init(_Experts: TList); resourcestring SConfigureButtonCaption = 'Configure...'; var i: Integer; AnExpert: TGX_BaseExpert; RowWidth: Integer; RowHeight: Integer; pnl: TPanel; img: TImage; chk: TCheckBox; hk: THotKey; btn: TButton; begin FExperts.Assign(_Experts); if IsThemesEnabled then begin btnDefault.Top := edtExpert.Top - 1; btnDefault.Height := edtExpert.Height + 2; end else begin btnDefault.Top := edtExpert.Top; btnDefault.Height := edtExpert.Height; end; btnExpert.Top := btnDefault.Top; btnExpert.Height := btnDefault.Height; RowWidth := sbxExperts.Width + 3; RowHeight := pnlExpertLayout.Height; FThumbSize := RowHeight; for i := 0 to FExperts.Count - 1 do begin AnExpert := FExperts[i]; pnl := TPanel.Create(sbxExperts); pnl.Parent := sbxExperts; pnl.SetBounds(0, i * RowHeight, RowWidth, RowHeight); pnl.Anchors := pnlExpertLayout.Anchors; pnl.Tag := i; pnl.FullRepaint := False; img := THintImage.Create(pnl); img.Parent := pnl; img.BoundsRect := imgExpert.BoundsRect; img.Picture.Bitmap.Assign(AnExpert.GetBitmap); img.Transparent := True; img.Center := True; img.Stretch := False; img.Hint := AnExpert.GetHelpString; img.ShowHint := True; img.Tag := i; chk := TCheckBox.Create(pnl); chk.Parent := pnl; chk.BoundsRect := chkExpert.BoundsRect; chk.Caption := AnExpert.GetDisplayName; chk.Checked := AnExpert.Active; chk.Tag := i; hk := THotKeyHack.Create(pnl); hk.Parent := pnl; hk.BoundsRect := edtExpert.BoundsRect; hk.Anchors := edtExpert.Anchors; hk.DoubleBuffered := False; hk.InvalidKeys := [hcNone, hcShift]; hk.Modifiers := [hkAlt]; THotkey_SetHotkey(hk, AnExpert.ShortCut); hk.Visible := AnExpert.CanHaveShortCut; hk.Tag := i; btn := TButton.Create(pnl); btn.Parent := pnl; btn.BoundsRect := btnDefault.BoundsRect; btn.Anchors := btnDefault.Anchors; btn.Caption := 'Default'; if AnExpert.GetDefaultShortCut <> 0 then begin btn.Hint := ShortCutToText(AnExpert.GetDefaultShortCut); btn.ShowHint := True; btn.OnClick := SetDefaultShortcutClick; end else btn.Enabled := False; btn.Tag := i; hk.Width := btn.Left - hk.Left; if AnExpert.HasConfigOptions then begin btn := TButton.Create(pnl); btn.Parent := pnl; btn.Caption := SConfigureButtonCaption; btn.BoundsRect := btnExpert.BoundsRect; btn.Anchors := btnExpert.Anchors; btn.OnClick := ConfigureExpertClick; btn.Tag := i; end; end; sbxExperts.VertScrollBar.Range := FExperts.Count * RowHeight; pnlExpertLayout.Visible := False; end; procedure TfrConfigureExperts.SaveExperts; var AControl: TControl; AnExpert: TGX_BaseExpert; i: Integer; pnl: TPanel; begin for i := 0 to sbxExperts.ComponentCount - 1 do begin AControl := sbxExperts.Components[i] as TControl; if AControl is TPanel then begin AnExpert := FExperts[AControl.Tag]; pnl := AControl as TPanel; AnExpert.Active := GetCheckbox(pnl).Checked; AnExpert.ShortCut := GetHotkeyCtrl(pnl).HotKey; end; end; for i := 0 to FExperts.Count - 1 do begin TGX_BaseExpert(FExperts[i]).SaveSettings; end; end; procedure TfrConfigureExperts.FrameMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin sbxExperts.VertScrollBar.Position := sbxExperts.VertScrollBar.Position + FThumbSize; Handled := True; end; procedure TfrConfigureExperts.FrameMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin sbxExperts.VertScrollBar.Position := sbxExperts.VertScrollBar.Position - FThumbSize; Handled := True; end; procedure TfrConfigureExperts.FilterVisibleExperts; var Panel: TPanel; CheckBox: TCheckBox; i, CurrTop: Integer; SubText: string; begin sbxExperts.VertScrollBar.Position := 0; SubText := Trim(edtFilter.Text); CurrTop := 0; for i := 0 to sbxExperts.ControlCount - 1 do begin Panel := sbxExperts.Controls[i] as TPanel; if Panel <> pnlExpertLayout then begin if SubText = '' then Panel.Visible := True else begin CheckBox := Panel.Controls[1] as TCheckBox; Panel.Visible := StrContains(SubText, CheckBox.Caption, False); end; end; if Panel.Visible then begin Panel.Top := CurrTop; Inc(CurrTop, Panel.Height); end; end; sbxExperts.VertScrollBar.Range := CurrTop; end; end.
unit DAO.ControleBaixasTFO; interface uses FireDAC.Comp.Client, System.SysUtils, DAO.Conexao, Control.Sistema, Model.ControleBaixasTFO; type TControleBaixaTFODAO = class private FConexao: TConexao; public constructor Create; function Insert(aControle: TControleBaixasTFO): Boolean; function Update(aControle: TControleBaixasTFO): Boolean; function Detele(aControle: TControleBaixasTFO): Boolean; function Find(aParam:array of Variant): TFDQuery; end; const TABLENAME = 'exp_controle_baixas_TFO'; implementation { TControleBaixaTFODAO } constructor TControleBaixaTFODAO.Create; begin FConexao := TConexao.Create; end; function TControleBaixaTFODAO.Detele(aControle: TControleBaixasTFO): Boolean; var FDQuery : TFDQuery; begin try FDQuery := FConexao.ReturnQuery; Result := False; FDQuery.ExecSQL('DELETE FROM ' + TABLENAME + 'WHERE ID_CONTROLE = :PID_CONTROLE', [aControle.Id]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TControleBaixaTFODAO.Find(aParam: array of Variant): TFDQuery; var FDQuery: TFDQuery; begin FDQuery := FConexao.ReturnQuery(); if Length(aParam) < 2 then Exit; FDQuery.SQL.Clear; FDQuery.SQL.Add('select * from ' + TABLENAME); if aParam[0] = 'ID' then begin FDQuery.SQL.Add('WHERE ID_CONTROLE = :PID_CONTROLE'); FDQuery.ParamByName('PID_CONTROLE').AsInteger := aParam[1]; end; if aParam[0] = 'DATA' then begin FDQuery.SQL.Add('WHERE DAT_CONTROLE = :PDAT_CONTROLE'); FDQuery.ParamByName('PDAT_CONTROLE').AsDateTime := aParam[1]; end; if aParam[0] = 'STATUS' then begin FDQuery.SQL.Add('WHERE DOM_STATUS = :PDOM_STATUS'); FDQuery.ParamByName('PDOM_STATUS').AsInteger := aParam[1]; end; if aParam[0] = 'FILTRO' then begin FDQuery.SQL.Add('WHERE ' + aParam[1]); end; if aParam[0] = 'APOIO' then begin FDQuery.SQL.Clear; FDQuery.SQL.Add('SELECT ' + aParam[1] + ' FROM ' + TABLENAME + ' ' + aParam[2]); end; FDQuery.Open(); Result := FDQuery; end; function TControleBaixaTFODAO.Insert(aControle: TControleBaixasTFO): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('INSERT INTO ' + TABLENAME + ' (ID_CONTROLE, DAT_CONTROLE, DOM_STATUS, DES_LOG) VALUES ' + '(:PID_CONTROLE, :PDAT_CONTROLE, :PDOM_STATUS, :PDES_LOG)', [aControle.Id, aControle.Data, aControle.Status, aControle.Log]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; function TControleBaixaTFODAO.Update(aControle: TControleBaixasTFO): Boolean; var FDQuery : TFDQuery; begin try Result := False; FDQuery := FConexao.ReturnQuery; FDQuery.ExecSQL('UPDATE ' + TABLENAME + ' SET DAT_CONTROLE = :PDAT_CONTROLE, DOM_STATUS = :PDOM_STATUS, DES_LOG = :PDES_LOG ' + 'WHERE ID_CONTROLE = :PID_CONTROLE', [aControle.Data, aControle.Status, aControle.Log, aControle.Id]); Result := True; finally FDQuery.Connection.Close; FDQuery.Free; end; end; end.
unit FullAddressBookContactProviderUnit; interface uses IAddressBookContactProviderUnit, AddressBookContactUnit; type TFullAddressBookContactProvider = class(TInterfacedObject, IAddressBookContactProvider) public function AddressBookContact: TAddressBookContact; end; implementation { TFullAddressBookContactProvider } function TFullAddressBookContactProvider.AddressBookContact: TAddressBookContact; begin Result := TAddressBookContact.Create('17205 RICHMOND TNPK, MILFORD, VA, 22514', 38.024654, -77.338814); Result.AddressGroup := 'AddressGroup'; Result.Alias := '301 MARKET SHELL'; Result.Address2 := 'Address2'; Result.FirstName := 'Gela'; Result.LastName := 'Gorason'; Result.Email := 'ggora@gmail.com'; Result.PhoneNumber := '8046335852'; Result.City := 'Tbilisi'; Result.StateId := 'TB'; Result.CountryId := 'GEO'; Result.Zip := '00167'; Result.Color := 'Red'; Result.AddCustomData('sales rep id', '545'); Result.AddCustomData('sales rep name', 'Kellye Foster'); Result.AddCustomData('retailer id', '173907'); end; end.
unit UListHandler; // Fully annotated interface uses Classes, UInterface; type TListHandler = class private List: Array of Array of integer; LastIndex, NextEmpty, ListSize: integer; public constructor Create(ListLength: integer; fill: boolean); function GetItem(Position, ItemNo: integer): integer; procedure AddItem(x, y: integer); procedure RemoveItem(Position: integer); function FindSetOfItems(ItemsToFind: TwoDArray; ItemsToFindLength: integer) : OneDArray; function GetLastIndex: integer; end; implementation // Initialises the objects constructor TListHandler.Create(ListLength: integer; fill: boolean); var i1, i2, pastIndex, index: integer; begin ListSize := ListLength * ListLength; LastIndex := ListSize - 1; setLength(List, ListSize, 2); // If fill is true, fill it with the coordinates of cells in the maze if fill then begin for i1 := 0 to (ListLength - 1) do begin pastIndex := ListLength * i1; for i2 := 0 to (ListLength - 1) do begin index := i2 + pastIndex; List[index, 0] := i1; List[index, 1] := i2; end; end; NextEmpty := -1; end // If fill is not true, create a list with enough room for each coordinates // and fill it with null values else begin for i1 := 0 to LastIndex do begin List[i1, 0] := -1; List[i1, 1] := -1; end; NextEmpty := 0; LastIndex := -1; end; end; // Returns the x or y value depending on the value of ItemNo of a specified // position in the list function TListHandler.GetItem(Position, ItemNo: integer): integer; begin result := List[Position, ItemNo]; end; // Adds a coordinate to the end of the list procedure TListHandler.AddItem(x, y: integer); begin // Checks the list is not full if not(NextEmpty = -1) then begin // Sets the next empty position as the coordinate passed to the procedure List[NextEmpty, 0] := x; List[NextEmpty, 1] := y; // Set the position where a coordinate was just added as the last occupied // position in the list inc(LastIndex); // Checks that the position modified is not the last position in the list if (NextEmpty + 1) = ListSize then begin // If it is, ensures that no more items will be added NextEmpty := -1; end // Otherwise set the position after the one just modified as the next empty // position else begin inc(NextEmpty); end; end; end; // Removes an item at the given position, and moves the item in the last index // to that position instead procedure TListHandler.RemoveItem(Position: integer); begin // Ensures that the position where an item is being removed holds a value if not(List[Position, 0] = -1) then begin // Checks whether the list already has contents if LastIndex > 0 then begin // Moves the coordinate in the last position to the position of the item // being removed List[Position, 0] := List[LastIndex, 0]; List[Position, 1] := List[LastIndex, 1]; // Sets the values of the last position to null List[LastIndex, 0] := -1; List[LastIndex, 1] := -1; // Adjusts the pointer to the LastIndex and NextEmpty considering this // change dec(LastIndex); NextEmpty := LastIndex + 1; end // If the list is empty else begin // Sets the 0th index to null List[0, 0] := -1; List[0, 1] := -1; // Adjusts the pointer to the LastIndex and NextEmpty considering this // change LastIndex := -1; NextEmpty := 0; end; end; end; // Finds the position of each cooridnate from a set of coordinates given function TListHandler.FindSetOfItems(ItemsToFind: TwoDArray; ItemsToFindLength: integer): OneDArray; var i1, i2: integer; begin i1 := 0; i2 := 0; // Initialises the list where the positions will be stored setLength(result, ItemsToFindLength); // For every index in the list of coordinates to be found for i1 := 0 to (ItemsToFindLength - 1) do begin result[i1] := -1; // For every index in the list of coordinates handled by the class for i2 := 0 to LastIndex do begin // If the index contains the coordinate to be found if ((List[i2, 0] = ItemsToFind[i1, 0]) and (List[i2, 1] = ItemsToFind[i1, 1])) then begin // Record its position result[i1] := i2; break; end; end; end; end; // Returns the position of the last index in the list function TListHandler.GetLastIndex: integer; begin result := LastIndex; end; end.
// *************************************************************************** // // A Simple Firemonkey Rating Bar Component // // Copyright 2017 谢顿 (zhaoyipeng@hotmail.com) // // https://github.com/zhaoyipeng/FMXComponents // // *************************************************************************** // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // *************************************************************************** } // version history // 2017-01-20, v0.1.0.0 : // first release // 2017-09-22, v0.2.0.0 : // merge Aone's version // add Data(TPathData) property, support user define rating shape // thanks Aone, QQ: 1467948783 // http://www.cnblogs.com/onechen unit FMX.RatingBar; interface uses System.Classes, System.SysUtils, System.Math, System.Math.Vectors, System.Types, System.UITypes, System.UIConsts, FMX.Types, FMX.Layouts, FMX.Graphics, FMX.Controls, FMX.Objects, FMX.ComponentsCommon; type [ComponentPlatformsAttribute(TFMXPlatforms)] TFMXRatingBar = class(TShape, IPathObject) private FData: TPathData; FCount: Integer; FMaximum: Single; FValue: Single; FSpace: Single; FActiveColor: TAlphaColor; FInActiveColor: TAlphaColor; FActiveBrush: TBrush; FInActiveBrush: TBrush; procedure SetPathData(const Value: TPathData); procedure SetCount(const Value: Integer); procedure SetMaximum(const Value: Single); procedure SetValue(const Value: Single); procedure SetSpace(const Value: Single); procedure SetActiveColor(const Value: TAlphaColor); procedure SetInActiveColor(const Value: TAlphaColor); { IPathObject } function GetPath: TPathData; procedure CreateBrush; procedure FreeBrush; protected procedure Resize; override; procedure Paint; override; procedure DrawRating(ARect: TRectF; AValue: Single); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; published property Align; property Anchors; property ClipChildren default False; property ClipParent default False; property Cursor default crDefault; property DragMode default TDragMode.dmManual; property EnableDragHighlight default True; property Enabled default True; property Fill; property Locked default False; property Height; property HitTest default True; property Padding; property Opacity; property Margins; property PopupMenu; property Position; property RotationAngle; property RotationCenter; property Scale; property Size; property Stroke; property Visible default True; property Width; { Drag and Drop events } property OnDragEnter; property OnDragLeave; property OnDragOver; property OnDragDrop; property OnDragEnd; { Mouse events } property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnMouseWheel; property OnMouseEnter; property OnMouseLeave; property OnPainting; property OnPaint; property OnResize; {$IF (RTLVersion >= 32)} // Tokyo property OnResized; {$ENDIF} property Data: TPathData read FData write SetPathData; property ActiveColor: TAlphaColor read FActiveColor write SetActiveColor; property InActiveColor: TAlphaColor read FInActiveColor write SetInActiveColor; property Space: Single read FSpace write SetSpace; property Count: Integer read FCount write SetCount default 5; property Value: Single read FValue write SetValue; property Maximum: Single read FMaximum write SetMaximum; end; implementation { THHRating } constructor TFMXRatingBar.Create(AOwner: TComponent); begin inherited; Width := 180; Height := 30; HitTest := False; FData := TPathData.Create; FData.Data := 'm 4677,2657 -1004,727 385,1179 -1002,-731 -1002,731 386,-1179 -1005,-727 1240,3 381,-1181 381,1181 z'; // 星 (瘦) FCount := 5; FMaximum := 5; FValue := 0; FSpace := 6; FActiveColor := claRoyalblue; FInActiveColor := $30000000; Stroke.Color := claNull; // 不顯示外框 end; destructor TFMXRatingBar.Destroy; begin FData.Free; FreeBrush; inherited; end; procedure TFMXRatingBar.CreateBrush; begin if not Assigned(FActiveBrush) then FActiveBrush := TBrush.Create(TBrushKind.Solid, FActiveColor); if not Assigned(FInActiveBrush) then FInActiveBrush := TBrush.Create(TBrushKind.Solid, FInActiveColor); end; procedure TFMXRatingBar.FreeBrush; begin FreeAndNil(FActiveBrush); FreeAndNil(FInActiveBrush); end; procedure TFMXRatingBar.Assign(Source: TPersistent); var src: TFMXRatingBar; begin if Source is TFMXRatingBar then begin src := TFMXRatingBar(Source); Stroke := src.Stroke; FData.Assign(src.FData); FCount := src.FCount; FMaximum := src.FMaximum; FValue := src.FValue; FSpace := src.FSpace; FActiveColor := src.FActiveColor; FInActiveColor := src.FInActiveColor; FreeBrush; Repaint; end else inherited; end; procedure TFMXRatingBar.DrawRating(ARect: TRectF; AValue: Single); var State: TCanvasSaveState; l: Single; R: TRectF; begin FData.FitToRect(ARect); Canvas.BeginScene; if AValue = 0 then begin Canvas.FillPath(FData, Opacity, FInActiveBrush); end else if AValue = 1 then begin Canvas.FillPath(FData, Opacity, FActiveBrush); end else begin Canvas.FillPath(FData, Opacity, FInActiveBrush); l := Min(ARect.Height, ARect.Width); R := RectF(ARect.CenterPoint.X - l, ARect.Top, ARect.CenterPoint.X + l * (AValue - 0.5), ARect.Bottom); State := Canvas.SaveState; Canvas.IntersectClipRect(R); Canvas.FillPath(FData, Opacity, FActiveBrush); Canvas.RestoreState(State); end; // 顯示外框 Canvas.DrawPath(FData, Opacity); Canvas.EndScene; end; procedure TFMXRatingBar.Paint; var l, w: Single; I: Integer; R: TRectF; DV, V: Single; begin inherited; CreateBrush; w := (Width - FSpace * 4) / Count; DV := (FValue / FMaximum) * Count; for I := 0 to Count - 1 do begin l := (w + FSpace) * I; R := RectF(l, 0, l + w, Height); if DV - I >= 1 then V := 1 else if DV <= I then V := 0 else V := DV - I; DrawRating(R, V); end; end; procedure TFMXRatingBar.Resize; begin inherited; Repaint; end; function TFMXRatingBar.GetPath: TPathData; begin Result := FData; end; procedure TFMXRatingBar.SetPathData(const Value: TPathData); begin FData.Assign(Value); end; procedure TFMXRatingBar.SetActiveColor(const Value: TAlphaColor); begin if FActiveColor <> Value then begin FActiveColor := Value; FreeAndNil(FActiveBrush); Repaint; end; end; procedure TFMXRatingBar.SetCount(const Value: Integer); begin if FCount <> Value then begin FCount := Value; Repaint; end; end; procedure TFMXRatingBar.SetInActiveColor(const Value: TAlphaColor); begin if FInActiveColor <> Value then begin FInActiveColor := Value; FreeAndNil(FInActiveBrush); Repaint; end; end; procedure TFMXRatingBar.SetMaximum(const Value: Single); begin if FMaximum <> Value then begin FMaximum := Value; Repaint; end; end; procedure TFMXRatingBar.SetSpace(const Value: Single); begin if FSpace <> Value then begin FSpace := Value; Repaint; end; end; procedure TFMXRatingBar.SetValue(const Value: Single); begin if FValue <> Value then begin FValue := Value; Repaint; end; end; end.
unit TSP; interface procedure GreedySort(tiles: array of TFoundTile); procedure QuickSort(tiles: array of TFoundTile; left,right: Integer); implementation function square(x:LongInt) : LongInt; begin result := x * x; end; function distanceTo(tile:TFoundTile) : Integer; begin result := Round(sqrt(square(GetX(self)-tile.X)+square(GetY(self)-tile.Y))); end; function distanceBetween(tile1, tile2:TFoundTile) : Real; begin result := sqrt(square(tile1.x - tile2.X) + square(tile1.y - tile2.Y)); end; function TourLength(tiles: array of TFoundTile) : Real; var i : Integer; totalLength : Real; begin totalLength := 0.0; for i := 0 to (Length(tiles) - 2) do begin totalLength := totalLength + distanceBetween(tiles[i], tiles[i + 1]) end; Result := totalLength + distanceBetween(tiles[Length(tiles) -1], tiles[0]); end; function DrawLine(x_1, y_1, x_2, y_2: Integer; color : Cardinal) : Cardinal; var Figure: TMapFigure; Begin Figure.kind := fkLine; Figure.coord := fcWorld; Figure.x1 := x_1; Figure.y1 := y_1; Figure.x2 := x_2; Figure.y2 := y_2; Figure.brushStyle := bsClear; Figure.brushColor := $000000; Figure.color := color; Figure.text := ''; Result := AddFigure(Figure); End; function TileToStr(tile : TFoundTile) : String; begin Result := '(' + IntToStr(tile.X) + ', ' + IntToStr(tile.Y) + ')'; end; function EdgeToStr(startVertex, endVertex : TFoundTile) : String; begin Result := TileToStr(startVertex) + '->' + TileToStr(endVertex); end; function DrawTour (tiles: array of TFoundTile) : array of Cardinal; var i : Integer; edges : array of Cardinal; begin ClearFigures(); SetArrayLength(edges, Length(tiles)); for i := 0 to (Length(tiles) - 2) do begin edges[i] := DrawLine(tiles[i].X, tiles[i].Y, tiles[i + 1].X, tiles[i + 1].Y, $00FF00); end; edges[Length(tiles) -1] := DrawLine(tiles[Length(tiles) - 1].X, tiles[Length(tiles) - 1].Y, tiles[0].X, tiles[0].Y, $00FF00); Result := edges; end; procedure QuickSort(tiles: array of TFoundTile; left,right: Integer); var i, j: Integer; x, y: TFoundTile; begin i := left; j := right; x := tiles[((left + right) div 2)]; repeat while distanceTo(tiles[i]) < distanceTo(x) do inc(i); while distanceTo(x) < distanceTo(tiles[j]) do dec(j); if not (i>j) then begin y:= tiles[i]; tiles[i]:= tiles[j]; tiles[j]:= y; inc(i); dec(j); end; until i>j; if left < j then QuickSort(tiles, left,j); if i < right then QuickSort(tiles, i,right); end; procedure GreedySort(tiles: array of TFoundTile); var i, j, closest : Integer; currentDistance, minDistance : Real; auxTile : TFoundTile; begin AddToSystemJournal('Greedy sorting tiles ...'); for i := 0 to (Length(tiles) - 3) do begin minDistance := -1.0; for j := i + 1 to (Length(tiles) - 1) do begin currentDistance := distanceBetween(tiles[i], tiles[j]); if (minDistance < 0.0) or (currentDistance < minDistance) then begin minDistance := currentDistance; closest := j; end; end; auxTile := tiles[i + 1]; tiles[i + 1] := tiles[closest]; tiles[closest] := auxTile; end; AddToSystemJournal('Done.'); end; function reverseTour(tiles : array of TFoundTile; startVertex, endVertex : Integer): array of TFoundTile; var i,j : Integer; aux : TFoundTile; begin i := startVertex; j := endVertex; repeat aux := tiles[j]; tiles[j] := tiles[i]; tiles[i] := aux; i := i + 1; j := j - 1; until j <= i; Result := tiles; end; procedure twoOpt(tiles: array of TFoundTile); var edge1start, edge2Start, edge1End, edge2End : Integer; improved : Boolean; begin AddToSystemJournal('TwoOpt sorting tiles ...'); if Length(tiles) <= 3 then Exit; repeat improved := false; for edge1start := 0 to High(tiles) - 2 do begin for edge2Start := edge1start + 2 to High(tiles) - 1 do begin edge1End := (edge1start + 1) Mod Length(tiles); edge2End := (edge2Start + 1) Mod Length(tiles); // AddToSystemJournal('Testing ' + // IntToStr(edge1Start) + ' -> ' + IntToStr(edge1End) + ' ' + EdgeToStr(tiles[edge1Start], tiles[edge1End]) + // ' against ' + // IntToStr(edge2Start) + ' -> ' + IntToStr(edge2End) + ' ' + EdgeToStr(tiles[edge2Start], tiles[edge2End]) + // ': ' + // FloatToStr((distanceBetween(tiles[edge1Start], tiles[edge1End]) + distanceBetween(tiles[edge2Start], tiles[edge2End]))) + ' ' + // FloatToStr(distanceBetween(tiles[edge1Start], tiles[edge2Start]) + distanceBetween(tiles[edge1End], tiles[edge2End]))); // Wait(250); if (distanceBetween(tiles[edge1Start], tiles[edge1End]) + distanceBetween(tiles[edge2Start], tiles[edge2End])) > (distanceBetween(tiles[edge1Start], tiles[edge2Start]) + distanceBetween(tiles[edge1End], tiles[edge2End])) then begin //AddToSystemJournal('improved!'); improved := True; tiles := reverseTour(tiles, edge1End, edge2Start); //DrawTour(tiles); end; if improved then break; end; if improved then break; end; until not improved; AddToSystemJournal('Done.'); end; end.
unit Support; interface uses SysUtils, Device.SMART.List; type TTotalWriteType = (WriteNotSupported, WriteSupportedAsCount, WriteSupportedAsValue); TSupportStatus = record Supported: Boolean; FirmwareUpdate: Boolean; TotalWriteType: TTotalWriteType; end; TTotalWriteInCount = record ValueInCount: UInt64 end; TTotalWriteInValue = record TrueHostWriteFalseNANDWrite: Boolean; ValueInMiB: UInt64; end; TTotalWrite = record case Integer of 0: (InCount: TTotalWriteInCount); 1: (InValue: TTotalWriteInValue); end; TReadEraseError = record TrueReadErrorFalseEraseError: Boolean; Value: UInt64; end; TSMARTAlert = record ReplacedSector: Boolean; ReadEraseError: Boolean; CriticalError: Boolean; end; TSMARTInterpreted = record UsedHour: UInt64; TotalWrite: TTotalWrite; ReadEraseError: TReadEraseError; ReplacedSectors: UInt64; SMARTAlert: TSMARTAlert; end; TNSTSupport = class abstract private FModel, FFirmware: String; protected property Model: String read FModel; property Firmware: String read FFirmware; public constructor Create; overload; constructor Create(const ModelToCheck, FirmwareToCheck: String); overload; procedure SetModelAndFirmware(const ModelToCheck, FirmwareToCheck: String); function GetSupportStatus: TSupportStatus; virtual; abstract; function GetSMARTInterpreted(SMARTValueList: TSMARTValueList): TSMARTInterpreted; virtual; abstract; end; implementation { TNSTSupport } constructor TNSTSupport.Create(const ModelToCheck, FirmwareToCheck: String); begin SetModelAndFirmware(ModelToCheck, FirmwareToCheck); end; constructor TNSTSupport.Create; begin ;// Intended to empty because of overloading rule end; procedure TNSTSupport.SetModelAndFirmware(const ModelToCheck, FirmwareToCheck: String); begin FModel := UpperCase(ModelToCheck); FFirmware := UpperCase(FirmwareToCheck); end; end.
unit playerhandling; {$mode objfpc}{$H+} interface uses Classes, SysUtils, typehandling, functionhandling; procedure gaingold(amount: integer); procedure losegold(amount: integer); procedure healplayer(amount: integer); procedure damageplayer(amount: integer); procedure teleportplayer(x, y: integer); procedure gaindamage(amount: integer); implementation //Gives the player the specified amount of gold procedure gaingold(amount: integer); begin player^.gold := player^.gold + amount; writeln('You have gained ' + IntToStr(amount) + ' gold (You now have ' + IntToStr(player^.gold) + ' gold)'); end; //Removes the specified amount of gold from the player procedure losegold(amount: integer); begin player^.gold := player^.gold - amount; writeln('You have lost ' + IntToStr(amount) + ' gold (You now have ' + IntToStr(player^.gold) + ' gold)'); end; //Increases the players health by the specified amount procedure healplayer(amount: integer); begin player^.health := player^.health + amount; writeln('You have gained ' + IntToStr(amount) + ' health (You now have ' + IntToStr(player^.health) + ')'); end; //Reduces the players health by the specified amount procedure damageplayer(amount: integer); begin player^.health := player^.health - amount; writeln('You have taken ' + IntToStr(amount) + ' damage and have ' + IntToStr(player^.health) + ' health remaining'); end; //Sets player coordinates to a specific value procedure teleportplayer(x, y: integer); begin player^.x := x; player^.y := y; end; //Increases the players damage by the specified amount procedure gaindamage(amount: integer); begin Write('Your damage has increased from ' + IntToStr(player^.damage) + ' to '); player^.damage := player^.damage + amount; writeln(IntToStr(player^.damage)); end; end.
unit Seasons; interface uses MetaInstances; type TSeason = (seasWinter, seasSpring, seasSummer, seasFall); type TWeatherEnvelope = class( TMetaInstance ) private fValues : array[TSeason] of single; fDeviation : single; fCurrVal : single; private function GetValue( Season : TSeason ) : single; procedure SetValue( Season : TSeason; value : single ); public property Value[Season : TSeason] : single read GetValue write SetValue; property Deviation : single read fDeviation write fDeviation; property CurrValue : single read fCurrVal; public procedure Update( Season : TSeason; SeasonProgress : single ); end; const tidClassFamily_WeatherEnvelopes = 'WeatherEnvelopes'; implementation function TWeatherEnvelope.GetValue( Season : TSeason ) : single; begin result := fValues[Season]; end; procedure TWeatherEnvelope.SetValue( Season : TSeason; value : single ); begin fValues[Season] := value; end; procedure TWeatherEnvelope.Update( Season : TSeason; SeasonProgress : single ); function PrevSeason( Season : TSeason ) : TSeason; begin if Season > low(Season) then result := pred(Season) else result := high(Season); end; begin fCurrVal := (1 - SeasonProgress)*fValues[PrevSeason( Season )] + SeasonProgress*fValues[Season] + fDeviation*(50 - random(100))/50; end; end.
unit csServerStatusRequest; interface uses Classes, CsDataPipe, csRequestTask, DT_types; type TddServerStatusRequest = class(TddRequestTask) private f_LineLength: Integer; f_ServerStatus: string; f_UsersCount: Integer; protected procedure LoadFrom(aStream: TStream; aIsPipe: Boolean); override; public constructor Create(aOwner: TObject; aUserID: TUserID); override; procedure SaveTo(aStream: TStream; aIsPipe: Boolean); override; procedure SaveToPipe(aPipe: TCsDataPipe); override; property LineLength: Integer read f_LineLength; property ServerStatus: string read f_ServerStatus; property UsersCount: Integer read f_UsersCount; end; implementation uses CsTaskTypes, ddServerTask; { **************************** TddServerStatusRequest **************************** } constructor TddServerStatusRequest.Create(aOwner: TObject; aUserID: TUserID); begin inherited; TaskType := cs_ttServerStatus; end; procedure TddServerStatusRequest.LoadFrom(aStream: TStream; aIsPipe: Boolean); begin inherited LoadFrom(aStream, aIsPipe); end; procedure TddServerStatusRequest.SaveTo(aStream: TStream; aIsPipe: Boolean); begin inherited SaveTo(aStream, aIsPipe); end; procedure TddServerStatusRequest.SaveToPipe(aPipe: TCsDataPipe); begin inherited SaveToPipe(aPipe); f_ServerStatus := aPipe.ReadStr; f_UsersCount := aPipe.ReadInteger; f_LineLength := aPipe.ReadInteger; end; initialization {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\cs\csServerStatusRequest.pas initialization enter'); {$EndIf} RegisterTaskClass(cs_ttServerStatus, TddServerStatusRequest, 'запрос статуса сервера'); {!touched!}{$IfDef LogInit} WriteLn('W:\common\components\rtl\Garant\cs\csServerStatusRequest.pas initialization leave'); {$EndIf} end.
unit eeCheckBox; {$Include vtDefine.inc} interface uses Windows, Messages, Graphics, SysUtils, Classes, Controls, StdCtrls; type TeeCustomCheckBox = class(TCustomCheckBox) private f_PrevCharCode : Word; protected function IsHandledShortcut(var Msg: TWMKeyDown): Boolean; procedure WMChar(Var Msg: TWMChar); message WM_CHAR; procedure WMKeyDown(Var Msg: TWMKeyDown); message WM_KEYDOWN; procedure WMSysKeyDown(var Msg: TWMSysKeyDown); message WM_SYSKEYDOWN; public // public methods constructor Create(AOwner:TComponent); override; {-} protected property ParentFont default false; {-} end;//TeeCustomCheckBox TeeCheckBox = class(TeeCustomCheckBox) published property Action; property Alignment; property AllowGrayed; property Anchors; property BiDiMode; property Caption; property Checked; property Color nodefault; property Constraints; property Ctl3D; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentBiDiMode; property ParentColor; property ParentCtl3D; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property State; property TabOrder; property TabStop; property Visible; property WordWrap; property OnClick; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnKeyDown; property OnKeyPress; property OnKeyUp; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end;//TeeCheckBox TeeCheckBox1 = class(TeeCheckBox) private procedure WMMouseActivate(var Message: TMessage); message WM_MOUSEACTIVATE; procedure WMLButtonDown(var Msg : TMessage{TWMLButtonDown}); message WM_LBUTTONDOWN; {-} protected function CanFocus: Boolean; override; procedure WndProc(var Message: TMessage); override; end;//TeeCheckBox1 implementation uses {$IfDef eeNeedOvc} OvcBase, OvcCmd, OvcConst, {$EndIf eeNeedOvc} afwFont, afwVCL ; constructor TeeCustomCheckBox.Create(AOwner:TComponent); //override; {-} begin inherited Create(AOwner); afwHackControlFont(Self); end; function TeeCustomCheckBox.IsHandledShortcut(var Msg: TWMKeyDown): Boolean; {$IfDef eeNeedOvc} var l_Controller : TOvcController; {$EndIf eeNeedOvc} begin f_PrevCharCode := 0; Result := false; {$IfDef eeNeedOvc} l_Controller := GetDefController; if Assigned(l_Controller) then with l_Controller.EntryCommands do if TranslateUsing([], TMessage(Msg), GetTickCount) = ccShortCut then begin Msg.Result := 0; {indicate that this message was processed} f_PrevCharCode := Msg.CharCode; Result := true; end; {$EndIf eeNeedOvc} end; procedure TeeCustomCheckBox.WMChar(Var Msg: TWMChar); begin if (f_PrevCharCode <> 0) and (Msg.CharCode = f_PrevCharCode) then Exit; inherited; end; procedure TeeCustomCheckBox.WMKeyDown(Var Msg: TWMKeyDown); begin if IsHandledShortcut(Msg) then Exit; inherited; end; procedure TeeCustomCheckBox.WMSysKeyDown(var Msg: TWMSysKeyDown); begin if IsHandledShortcut(Msg) then Exit; inherited; end; // start class TeeCheckBox1 procedure TeeCheckBox1.WMMouseActivate(var Message: TMessage); begin if not (csDesigning in ComponentState) then Message.Result := MA_NOACTIVATE else inherited; end; procedure TeeCheckBox1.WMLButtonDown(var Msg : TMessage{TWMLButtonDown}); //message WM_LBUTTONDOWN; {-} begin if not (csDesigning in ComponentState) then Checked := not Checked else inherited; end; function TeeCheckBox1.CanFocus: Boolean; begin if not (csDesigning in ComponentState) then Result := false else Result := inherited CanFocus; end; procedure TeeCheckBox1.WndProc(var Message: TMessage); begin case Message.Msg of WM_LBUTTONDOWN, WM_LBUTTONDBLCLK: if not (csDesigning in ComponentState) then begin Checked := not Checked; Exit; end;//not (csDesigning in ComponentState) end;//case Message.Msg inherited; end; end.
unit BufferLoaders; // Copyright (c) 1998 Jorge Romero Gomez, Merchise interface uses Classes, Windows, SysUtils, Buffer, ImageLoaders; procedure LoadBuffer( Buffer : TBuffer; Stream : TStream ); procedure LoadBufferFromFile( Buffer : TBuffer; const Filename : string ); procedure LoadBufferFromResName( Buffer : TBuffer; Instance : THandle; const ResourceName : string ); procedure LoadBufferFromResId( Buffer : TBuffer; Instance : THandle; ResourceId : Integer ); implementation uses Dibs; procedure LoadBuffer( Buffer : TBuffer; Stream : TStream ); var Images : TImages; begin Buffer.Release; Images := GetImageLoader( Stream, nil ); if Assigned( Images ) then with Images, DibHeader^ do begin Buffer.CreateSized( biWidth, -abs(biHeight), biBitCount ); Buffer.ChangePaletteEntries( 0, DibNumColors( Buffer.DibHeader ), DibColors( DibHeader)^ ); with Images.Image[0], Origin, Buffer do Decode( PixelAddr[ x, y ], StorageWidth ); end; end; procedure LoadBufferFromFile( Buffer : TBuffer; const Filename : string ); var Stream : TStream; begin Stream := TFileStream.Create( Filename, fmOpenRead or fmShareDenyWrite ); try LoadBuffer( Buffer, Stream ); finally Stream.Free; end; end; procedure LoadBufferFromResName( Buffer : TBuffer; Instance : THandle; const ResourceName : string ); var Stream : TStream; begin Stream := TResourceStream.Create( Instance, ResourceName, RT_RCDATA ); try LoadBuffer( Buffer, Stream ); finally Stream.Free; end; end; procedure LoadBufferFromResId( Buffer : TBuffer; Instance : THandle; ResourceId : Integer ); var Stream : TStream; begin Stream := TResourceStream.CreateFromID( Instance, ResourceId, RT_RCDATA ); try LoadBuffer( Buffer, Stream ); finally Stream.Free; end; end; end.
unit UserLicenseUnit; interface uses SysUtils, BaseExampleUnit, EnumsUnit; type TUserLicense = class(TBaseExample) public function Execute(MemberId, SessionId: integer; DeviceId: String; DeviceType: TDeviceType; Subscription: String; Token: String; Payload: String): boolean; end; implementation function TUserLicense.Execute(MemberId, SessionId: integer; DeviceId: String; DeviceType: TDeviceType; Subscription: String; Token: String; Payload: String): boolean; var ErrorString: String; begin Result := Route4MeManager.User.UserLicense(MemberId, SessionId, DeviceId, DeviceType, Subscription, Token, Payload, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin if Result then WriteLn('UserLicense successfully, user is licensed') else WriteLn('UserLicense successfully, user is not licensed'); WriteLn(''); end else WriteLn(Format('UserLicense error: "%s"', [ErrorString])); end; end.
unit RTF2HTML; {$mode objfpc}{$H+} interface uses Classes, SysUtils, RTFPars_lzRichEdit, LCLType, LCLProc, Dialogs, Graphics; type TRTFPict = record PictType, W, H, WG, HG: integer; HEX: string; end; TRSFontAttributes=record Charset: TFontCharset; Color: TColor; Name: TFontName; Pitch: TFontPitch; fProtected: Boolean; Size: Integer; Style: TFontStyles; end; { TRtf2HTML } TRtf2HTML = class(TObject) private FRTFParser: TRTFParser; FRTFPict: TRTFPict; FIsPict: boolean; FGroups: integer; FSkipGroup:Integer; FAlign: TAlignment; FFirstIndent: Integer; FLeftIndent: Integer; FRightIndent: Integer; FFontParams: TRSFontAttributes; FLastFontParams: TRSFontAttributes; FBullet:Boolean; //-- FSpan:String; FCloseSPan:boolean; FParZero:Boolean; //-- FDirectory:String; FFileNum:Integer; private procedure DoGroup; procedure DoWrite; procedure DoCtrl; procedure DoSpecialChar; procedure DoParAttr; procedure DoCharAttr; procedure DoPictAttr; procedure DoBeginPict; procedure DoEndPict; public SunFontSize:Integer; private FHTML:String; FPar: String; public function Convert(RTFStream: TStream; DirectoryHTML: String; HTMLFileName:String): Boolean; end; function SaveMedia(const S: string; DataType: integer; FileName:String): boolean; implementation function SaveMedia(const S: string; DataType: integer; FileName:String): boolean; var MStream: TMemoryStream; I: integer = 1; B: byte = 0; L: integer; S2: string; begin Result := False; MStream := TMemoryStream.Create; MStream.Seek(0, soBeginning); L := UTF8Length(S); while True do begin S2 := S[I] + S[I + 1]; if (S2 <> '') then B := StrToInt('$' + trim(S2)) else B := $0; MStream.Write(B, 1); I := I + 2; if (I > L) then Break; end; MStream.SaveToFile(FileName); MStream.Free; Result:= true; end; { TRtf2HTML } procedure TRtf2HTML.DoGroup; begin if (FRTFParser.RTFMajor = rtfBeginGroup) then FGroups := FGroups + 1 else FGroups := FGroups - 1; if (FGroups < FSkipGroup) then FSkipGroup := -1; end; procedure TRtf2HTML.DoWrite; var C: TUTF8char; L: integer; begin C := UnicodeToUTF8(FRTFParser.RTFMajor); if FIsPict then FRTFPict.HEX := FRTFPict.HEX + C else begin if (FSkipGroup = -1) and (FRTFParser.RTFMajor = 183) then begin FBullet:= True; DoCharAttr; C := chr($0); end; if (FSkipGroup = -1) and (C <> chr($0)) then begin if (FSpan <> '') then begin if (FCloseSPan) then FPar:= FPar + '</SPAN>'; FPar:= FPar + FSpan; FCloseSPan:= True; FSpan:= ''; end; FPar:= FPar + C; FParZero:= false; end; end; end; procedure TRtf2HTML.DoCtrl; begin case FRTFParser.RTFMajor of rtfSpecialChar: DoSpecialChar; rtfParAttr: DoParAttr; rtfCharAttr: DoCharAttr; rtfPictAttr: DoPictAttr; end; end; procedure TRtf2HTML.DoSpecialChar; const PAling: array [TAlignment] of String = ('style="text-align:left', 'style="text-align:right', 'style="text-align:center'); function GenSpan:String; var face:String=''; color: String=''; size: String=''; begin Result:= '<SPAN style="'; //-- if (FFontParams.Name <> '') then face:= 'font-family:' + FFontParams.Name + '; '; if (FFontParams.Size <> 0) then size:= 'font-size:' + IntToStr(FFontParams.Size + SunFontSize) + 'px; '; color:= 'color:#' + IntToHex(Red(FFontParams.Color), 2) + IntToHex(green(FFontParams.Color), 2) + IntToHex(blue(FFontParams.Color), 2); Result:= Result + face + size + color + '">'; end; var InitIdent:String=''; begin case FRTFParser.rtfMinor of rtfPar: begin if (FSkipGroup = -1) then begin if (fsBold in FFontParams.Style) then FPar:= FPar + '</b>'; if (fsItalic in FFontParams.Style) then FPar:= FPar + '</i>'; if (fsUnderline in FFontParams.Style) then FPar:= FPar + '</u>'; if (FCloseSPan) then FPar:= FPar + '</SPAN>'; if not(FParZero) then begin if (FFirstIndent <> 0) then begin InitIdent:= '; text-indent:'+ IntToStr(FFirstIndent div 20) +'px'; end; if (FLeftIndent <> 0) then begin InitIdent:= InitIdent + '; padding-left:'+ IntToStr(FLeftIndent div 20) +'px'; end; if (FRightIndent <> 0) then begin InitIdent:= InitIdent + '; padding-right:'+ IntToStr(FRightIndent div 20) +'px'; end; if FBullet then begin FPar:= '<ul><li>' + FPar + '</li></ul>'; FBullet:= False; end; FHTML:= FHTML + '<P ' + PAling[FAlign] + InitIdent + '">' + FPar + '</P>' + #10; FPar:= ''; end else begin FHTML:= FHTML + '<BR>' + #10; FPar:= ''; end; //--- if (fsBold in FFontParams.Style) then FPar:= FPar + '<b>'; if (fsItalic in FFontParams.Style) then FPar:= FPar + '<i>'; if (fsUnderline in FFontParams.Style) then FPar:= FPar + '<u>'; //-- FSpan:= GenSpan; FPar:= FPar + FSpan; FSpan:= ''; FParZero:= True; end; end; rtfTab: begin if (FSkipGroup = -1) then FPar:= FPar + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'; end; rtfOptDest: begin if (FSkipGroup = -1) then; FSkipGroup := FGroups; end; end; end; procedure TRtf2HTML.DoParAttr; begin case FRTFParser.rtfMinor of rtfParDef: begin FAlign := taLeftJustify; FLeftIndent := 0; FRightIndent := 0; FFirstIndent:= 0; end; rtfQuadLeft: begin FAlign := taLeftJustify; end; rtfQuadRight: begin FAlign := taRightJustify; end; rtfQuadJust: begin FAlign := taLeftJustify; end; rtfQuadCenter: begin FAlign := taCenter; end; rtfFirstIndent: begin FFirstIndent:= FRTFParser.rtfParam; end; rtfLeftIndent: begin FLeftIndent := FRTFParser.rtfParam; end; rtfRightIndent: begin FRightIndent := FRTFParser.rtfParam; end; end; end; procedure TRtf2HTML.DoCharAttr; var c: PRTFColor; f: PRTFFont; function Styles(S: TFontStyle): boolean; begin if (s in FFontParams.Style) then FFontParams.Style := FFontParams.Style - [S] else FFontParams.Style := FFontParams.Style + [S]; Result := (S in FFontParams.Style); end; function GenSpan:String; var face:String=''; color: String=''; size: String=''; begin Result:= '<SPAN style="'; //-- if (FFontParams.Name <> '') then face:= 'font-family:' + FFontParams.Name + '; '; if (FFontParams.Size <> 0) then size:= 'font-size:' + IntToStr(FFontParams.Size + SunFontSize) + 'px; '; color:= 'color:#' + IntToHex(Red(FFontParams.Color), 2) + IntToHex(green(FFontParams.Color), 2) + IntToHex(blue(FFontParams.Color), 2); Result:= Result + face + size + color + '">'; end; begin FLastFontParams.Name:= FFontParams.Name; FLastFontParams.Size:= FFontParams.Size; FLastFontParams.Color:= FFontParams.Color; FLastFontParams.Style:= FFontParams.Style; //-- case FRTFParser.rtfMinor of rtfBold: begin Styles(fsBold); end; rtfItalic: begin Styles(fsItalic); end; rtfStrikeThru: begin Styles(fsStrikeOut); end; rtfFontNum: begin f := FRTFParser.Fonts[FRTFParser.rtfParam]; if (f = nil) then FFontParams.Name := 'Sans' else FFontParams.Name := f^.rtfFName; end; rtfFontSize: begin FFontParams.Size := FRTFParser.rtfParam div 2; end; rtfUnderline: begin if not(fsUnderline in FFontParams.Style) then FFontParams.Style := FFontParams.Style + [fsUnderline] end; rtfNoUnderline: begin if (fsUnderline in FFontParams.Style) then FFontParams.Style := FFontParams.Style - [fsUnderline] end; rtfForeColor: begin C := FRTFParser.Colors[FRTFParser.rtfParam]; if (C = nil) or (FRTFParser.rtfParam = 0) then FFontParams.Color := clWindowText else FFontParams.Color := RGBToColor(C^.rtfCRed, C^.rtfCGreen, C^.rtfCBlue); end; end; if (FLastFontParams.Style <> FFontParams.Style) then begin if (fsBold in FFontParams.Style) and not(fsBold in FLastFontParams.Style) then FPar:= FPar + '<b>' else if not(fsBold in FFontParams.Style) and (fsBold in FLastFontParams.Style) then FPar:= FPar + '</b>'; if (fsItalic in FFontParams.Style) and not(fsItalic in FLastFontParams.Style) then FPar:= FPar + '<i>' else if not(fsItalic in FFontParams.Style) and (fsItalic in FLastFontParams.Style) then FPar:= FPar + '</i>'; if (fsUnderline in FFontParams.Style) and not(fsUnderline in FLastFontParams.Style) then FPar:= FPar + '<u>' else if not(fsUnderline in FFontParams.Style) and (fsUnderline in FLastFontParams.Style) then FPar:= FPar + '</u>'; end; FSpan:= GenSpan; end; procedure TRtf2HTML.DoPictAttr; begin if (FRTFParser.rtfMajor = rtfPictAttr) and (FRTFParser.rtfMinor in [rtfMacQD .. rtfpngblip]) then case FRTFParser.rtfMinor of rtfPicWid: FRTFPict.W := FRTFParser.rtfParam; rtfPicHt: FRTFPict.H := FRTFParser.rtfParam; rtfPicGoalWid: FRTFPict.WG := FRTFParser.rtfParam; rtfPicGoalHt: FRTFPict.HG := FRTFParser.rtfParam; rtfpngblip: FRTFPict.PictType := rtfpngblip; rtfWinMetafile: FRTFPict.PictType := rtfWinMetafile; end; end; procedure TRtf2HTML.DoBeginPict; begin FRTFPict.HEX := ''; FRTFPict.H := 0; FRTFPict.HG := 0; FRTFPict.W := 0; FRTFPict.WG := 0; FRTFPict.PictType := -1; FIsPict := True; end; procedure TRtf2HTML.DoEndPict; var R: boolean = False; L:Integer; FileName:String; PFileType: array [0..18] of String = ('', '.wmf', '.bmp', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '.png'); begin FIsPict := False; FileName:= FDirectory + 'img' + IntToStr(FFileNum) + PFileType[FRTFPict.PictType]; if (SaveMedia(FRTFPict.HEX, FRTFPict.PictType, FileName)) then Inc(FFileNum); if (FRTFPict.WG = 0) and (FRTFPict.HG = 0) or (FRTFPict.WG = FRTFPict.W) and (FRTFPict.HG = FRTFPict.H) then FPar:= FPar + '<img src="' + ExtractFileName(FileName) + '">' else FPar:= FPar + '<img src="' + ExtractFileName(FileName) + '" style=width:' + IntToStr(FRTFPict.WG) + 'px; height:' + IntToStr(FRTFPict.HG) + 'px">'; FParZero:= false; end; function TRtf2HTML.Convert(RTFStream: TStream; DirectoryHTML: String; HTMLFileName:String): Boolean; var FileName:String; HTML: TStringList; begin Result:= False; if not(DirectoryExists(DirectoryHTML)) then Exit; //-- if (RightStr(DirectoryHTML, 1) <> DirectorySeparator) then begin FileName:= DirectoryHTML + DirectorySeparator + HTMLFileName; FDirectory:= DirectoryHTML + DirectorySeparator; end else begin FileName:= DirectoryHTML + HTMLFileName; FDirectory:= DirectoryHTML; end; // FFontParams.Name:=''; FFontParams.Size:=0; FFontParams.Color:=$000000; FFontParams.Style:=[]; // FPar:= ''; FFileNum:= 0; //-- FCloseSPan:= False; FSpan:= ''; FParZero:= true; FBullet:= False; //-- FHTML:= '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"' + #10 + '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">' + #10 + '<html>' + #10 + '<head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8" /></head>' + #10 + '<body>' + #10; //-- HTML:= TStringList.Create; HTML.Clear; //-- FGroups := 0; FSkipGroup := -1; //-- FRTFParser := TRTFParser.Create(RTFStream); FRTFParser.classcallbacks[rtfText] := @DoWrite; FRTFParser.classcallbacks[rtfcontrol] := @DoCtrl; FRTFParser.classcallbacks[rtfGroup] := @DoGroup; FRTFParser.OnRTFBeginPict := @DoBeginPict; FRTFParser.OnRTFEndPict := @DoEndPict; FRTFParser.StartReading; FRTFParser.Free; //-- FHTML := FHTML + #10 +'</body>' + #10 + '</html>'; //-- HTML.Text:= FHTML; HTML.SaveToFile(FileName); HTML.Free; Result:= True; end; end.
program typeOfLetter(input, output); var letter : char; begin write(': '); read(letter); case letter of 'a', 'e', 'i', 'o', 'u' : write('Vowel'); '.', ',', ';', '!', '?' : write('Punctuation'); else begin if (letter >= 'a') and (letter <= 'z') then write('Consonant') else write('Strange character') end end; writeln('.') end.
unit uMusicMenu; interface uses // Own units Audio, UCommon; type TMusicMenu = class(THODObject) private FAudio: TAudio; public constructor Create; destructor Destroy; override; procedure Play; procedure Stop; procedure SetVolume(Value: Byte); end; var MusicMenu: TMusicMenu; implementation uses uUtils; { TMusicMenu } constructor TMusicMenu.Create; begin FAudio := TAudio.Create; FAudio.Add(Path + 'Data\Music\Camptrck.wav', True); end; destructor TMusicMenu.Destroy; begin FAudio.Free; inherited; end; procedure TMusicMenu.Play; begin FAudio.Play; end; procedure TMusicMenu.SetVolume(Value: Byte); begin FAudio.Volume := Value; end; procedure TMusicMenu.Stop; begin FAudio.Stop; end; initialization MusicMenu := TMusicMenu.Create; finalization MusicMenu.Free; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpDerVideotexString; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpArrayUtils, ClpCryptoLibTypes, ClpAsn1Object, ClpAsn1Tags, ClpAsn1OctetString, ClpDerOutputStream, ClpIProxiedInterface, ClpIDerVideotexString, ClpIAsn1TaggedObject, ClpDerStringBase, ClpConverters; resourcestring SIllegalObject = 'Illegal Object in GetInstance: %s'; SEncodingError = 'Encoding Error in GetInstance: %s "obj"'; type TDerVideotexString = class(TDerStringBase, IDerVideotexString) strict private var FmString: TCryptoLibByteArray; function GetmString: TCryptoLibByteArray; inline; protected function Asn1GetHashCode(): Int32; override; function Asn1Equals(const asn1Object: IAsn1Object): Boolean; override; public property mString: TCryptoLibByteArray read GetmString; /// <summary> /// basic constructor - with bytes. /// </summary> /// <param name="encoding"> /// the byte encoding of the characters making up the string. /// </param> constructor Create(const encoding: TCryptoLibByteArray); function GetString(): String; override; function GetOctets(): TCryptoLibByteArray; inline; procedure Encode(const derOut: TStream); override; /// <summary> /// return a Videotex String from the passed in object /// </summary> /// <param name="obj"> /// a DerVideotexString or an object that can be converted into one. /// </param> /// <returns> /// return a DerVideotexString instance, or null. /// </returns> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the object cannot be converted. /// </exception> class function GetInstance(const obj: TObject): IDerVideotexString; overload; static; inline; class function GetInstance(const obj: TCryptoLibByteArray) : IDerVideotexString; overload; static; /// <summary> /// return a Videotex string from a tagged object. /// </summary> /// <param name="obj"> /// the tagged object holding the object we want /// </param> /// <param name="isExplicit"> /// true if the object is meant to be explicitly tagged false otherwise. /// </param> /// <exception cref="ClpCryptoLibTypes|EArgumentCryptoLibException"> /// if the tagged object cannot be converted. /// </exception> class function GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerVideotexString; overload; static; inline; end; implementation { TDerVideotexString } function TDerVideotexString.GetmString: TCryptoLibByteArray; begin result := FmString; end; function TDerVideotexString.Asn1Equals(const asn1Object: IAsn1Object): Boolean; var other: IDerVideotexString; begin if (not Supports(asn1Object, IDerVideotexString, other)) then begin result := false; Exit; end; result := TArrayUtils.AreEqual(mString, other.mString); end; function TDerVideotexString.Asn1GetHashCode: Int32; begin result := TArrayUtils.GetArrayHashCode(mString); end; constructor TDerVideotexString.Create(const encoding: TCryptoLibByteArray); begin Inherited Create(); FmString := System.Copy(encoding); end; procedure TDerVideotexString.Encode(const derOut: TStream); begin (derOut as TDerOutputStream).WriteEncoded(TAsn1Tags.VideotexString, mString); end; class function TDerVideotexString.GetInstance(const obj: TObject) : IDerVideotexString; begin if ((obj = Nil) or (obj is TDerVideotexString)) then begin result := obj as TDerVideotexString; Exit; end; raise EArgumentCryptoLibException.CreateResFmt(@SIllegalObject, [obj.ClassName]); end; class function TDerVideotexString.GetInstance(const obj: IAsn1TaggedObject; isExplicit: Boolean): IDerVideotexString; var o: IAsn1Object; begin o := obj.GetObject(); if ((isExplicit) or (Supports(o, IDerVideotexString))) then begin result := GetInstance(o as TAsn1Object); Exit; end; result := TDerVideotexString.Create (TAsn1OctetString.GetInstance(o as TAsn1Object).GetOctets()); end; class function TDerVideotexString.GetInstance(const obj: TCryptoLibByteArray) : IDerVideotexString; begin try result := FromByteArray(obj) as IDerVideotexString; except on e: Exception do begin raise EArgumentCryptoLibException.CreateResFmt(@SEncodingError, [e.Message]); end; end; end; function TDerVideotexString.GetOctets: TCryptoLibByteArray; begin result := System.Copy(mString); end; function TDerVideotexString.GetString: String; begin result := TConverters.ConvertBytesToString(mString, TEncoding.ANSI) end; end.
unit Weather.Classes; interface uses Generics.Collections, Rest.Json, System.JSON; type TSysClass = class private FCountry: string; FMessage: Extended; FSunrise: Extended; FSunset: Extended; public property country: string read FCountry write FCountry; property message: Extended read FMessage write FMessage; property sunrise: Extended read FSunrise write FSunrise; property sunset: Extended read FSunset write FSunset; function ToJsonString: string; class function FromJsonString(AJsonString: string): TSysClass; end; TCloudsClass = class private FAll: Extended; public property all: Extended read FAll write FAll; function ToJsonString: string; class function FromJsonString(AJsonString: string): TCloudsClass; end; TWindClass = class private FDeg: Extended; FSpeed: Extended; public property deg: Extended read FDeg write FDeg; property speed: Extended read FSpeed write FSpeed; function ToJsonString: string; class function FromJsonString(AJsonString: string): TWindClass; end; TWeatherData = class private FGrnd_level: Extended; FHumidity: Extended; FPressure: Extended; FSea_level: Extended; FTemp: Extended; FTemp_max: Extended; FTemp_min: Extended; public property grnd_level: Extended read FGrnd_level write FGrnd_level; property humidity: Extended read FHumidity write FHumidity; property pressure: Extended read FPressure write FPressure; property sea_level: Extended read FSea_level write FSea_level; property temp: Extended read FTemp write FTemp; property temp_max: Extended read FTemp_max write FTemp_max; property temp_min: Extended read FTemp_min write FTemp_min; function ToJsonString: string; class function FromJsonString(AJsonString: string): TWeatherData; end; TWeatherItem = class private FDescription: string; FIcon: string; FId: Extended; FMain: string; public property description: string read FDescription write FDescription; property icon: string read FIcon write FIcon; property id: Extended read FId write FId; property main: string read FMain write FMain; function ToJsonString: string; class function FromJsonString(AJsonString: string): TWeatherItem; end; TGeoCoords = class private FLat: Extended; FLon: Extended; public property lat: Extended read FLat write FLat; property lon: Extended read FLon write FLon; function ToJsonString: string; class function FromJsonString(AJsonString: string): TGeoCoords; end; TWeather = class private FBase: string; FClouds: TCloudsClass; FCod: Extended; FCoord: TGeoCoords; FDt: Extended; FId: Extended; FMain: TWeatherData; FName: string; FSys: TSysClass; FTimezone: Extended; FWeather: TArray<TWeatherItem>; FWind: TWindClass; public property base: string read FBase write FBase; property clouds: TCloudsClass read FClouds write FClouds; property cod: Extended read FCod write FCod; property coord: TGeoCoords read FCoord write FCoord; property dt: Extended read FDt write FDt; property id: Extended read FId write FId; property main: TWeatherData read FMain write FMain; property name: string read FName write FName; property sys: TSysClass read FSys write FSys; property timezone: Extended read FTimezone write FTimezone; property weather: TArray<TWeatherItem> read FWeather write FWeather; property wind: TWindClass read FWind write FWind; constructor Create; destructor Destroy; override; function ToJsonString: string; class function FromJsonString(AJsonString: string): TWeather; procedure ParseFromJson(AJsonObject: TJSOnObject); end; implementation {TSysClass} function TSysClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TSysClass.FromJsonString(AJsonString: string): TSysClass; begin result := TJson.JsonToObject<TSysClass>(AJsonString) end; {TCloudsClass} function TCloudsClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TCloudsClass.FromJsonString(AJsonString: string): TCloudsClass; begin result := TJson.JsonToObject<TCloudsClass>(AJsonString) end; {TWindClass} function TWindClass.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TWindClass.FromJsonString(AJsonString: string): TWindClass; begin result := TJson.JsonToObject<TWindClass>(AJsonString) end; {TWeatherData} function TWeatherData.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TWeatherData.FromJsonString(AJsonString: string): TWeatherData; begin result := TJson.JsonToObject<TWeatherData>(AJsonString) end; {TWeatherItem} function TWeatherItem.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TWeatherItem.FromJsonString(AJsonString: string): TWeatherItem; begin result := TJson.JsonToObject<TWeatherItem>(AJsonString) end; {TGeoCoords} function TGeoCoords.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TGeoCoords.FromJsonString(AJsonString: string): TGeoCoords; begin result := TJson.JsonToObject<TGeoCoords>(AJsonString) end; {TWeather} constructor TWeather.Create; begin inherited; FCoord := TGeoCoords.Create(); FMain := TWeatherData.Create(); FWind := TWindClass.Create(); FClouds := TCloudsClass.Create(); FSys := TSysClass.Create(); end; destructor TWeather.Destroy; var LweatherItem: TWeatherItem; begin for LweatherItem in FWeather do LweatherItem.Free; FCoord.Free; FMain.Free; FWind.Free; FClouds.Free; FSys.Free; inherited; end; function TWeather.ToJsonString: string; begin result := TJson.ObjectToJsonString(self); end; class function TWeather.FromJsonString(AJsonString: string): TWeather; begin Result := TJson.JsonToObject<TWeather>(AJsonString) end; procedure TWeather.ParseFromJson(AJsonObject: TJsonObject); var LweatherItem: TWeatherItem; begin for LweatherItem in FWeather do LweatherItem.Free; TJson.JsonToObject(Self, AJsonObject); end; end.
object QuickExportSetupForm: TQuickExportSetupForm Left = 204 Top = 279 BorderStyle = bsDialog Caption = 'FB2_2_rtf quick' ClientHeight = 184 ClientWidth = 185 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -13 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = False Position = poScreenCenter Scaled = False OnCreate = FormCreate PixelsPerInch = 120 TextHeight = 16 object SkipImages: TCheckBox Left = 8 Top = 8 Width = 153 Height = 17 Caption = 'Skip all images' TabOrder = 0 OnClick = SkipImagesClick OnKeyPress = SkipImagesKeyPress end object Button1: TButton Left = 13 Top = 148 Width = 75 Height = 25 Caption = '&Ok' Default = True ModalResult = 1 TabOrder = 1 OnClick = Button1Click end object Button2: TButton Left = 100 Top = 148 Width = 75 Height = 25 Cancel = True Caption = '&Cancel' ModalResult = 2 TabOrder = 2 end object SkipCover: TCheckBox Left = 8 Top = 32 Width = 153 Height = 17 Caption = 'No cover image' TabOrder = 3 end object SkipDescr: TCheckBox Left = 8 Top = 56 Width = 153 Height = 17 Caption = 'Skip description' TabOrder = 4 end object EncCompat: TCheckBox Left = 8 Top = 80 Width = 153 Height = 17 Caption = 'Compatible encoding' TabOrder = 5 end object ImgCompat: TCheckBox Left = 8 Top = 104 Width = 153 Height = 17 Caption = 'Compatible images' TabOrder = 6 end end
{******************************************************************************* 作者: dmzn@163.com 2009-6-19 描述: 皮肤状况管理 *******************************************************************************} unit UFormSkinType; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UFormNormal, dxLayoutControl, StdCtrls, cxControls, cxMemo, cxTextEdit, cxDropDownEdit, cxContainer, cxEdit, cxMaskEdit, cxCalendar, cxGraphics, cxMCListBox, cxImage, cxButtonEdit; type TfFormSkinType = class(TfFormNormal) EditMemo: TcxMemo; dxLayout1Item6: TdxLayoutItem; dxGroup2: TdxLayoutGroup; InfoItems: TcxComboBox; dxLayout1Item7: TdxLayoutItem; dxLayout1Item8: TdxLayoutItem; EditInfo: TcxTextEdit; BtnAdd: TButton; dxLayout1Item9: TdxLayoutItem; BtnDel: TButton; dxLayout1Item10: TdxLayoutItem; ListInfo1: TcxMCListBox; dxLayout1Item11: TdxLayoutItem; dxLayout1Group2: TdxLayoutGroup; ImagePic: TcxImage; dxLayout1Item3: TdxLayoutItem; dxLayout1Group4: TdxLayoutGroup; dxLayout1Group5: TdxLayoutGroup; dxLayout1Group7: TdxLayoutGroup; EditID: TcxButtonEdit; dxLayout1Item4: TdxLayoutItem; EditPart: TcxComboBox; dxLayout1Item12: TdxLayoutItem; EditName: TcxTextEdit; dxLayout1Item13: TdxLayoutItem; procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure BtnAddClick(Sender: TObject); procedure BtnDelClick(Sender: TObject); procedure BtnOKClick(Sender: TObject); procedure ImagePicDblClick(Sender: TObject); procedure ListInfo1Click(Sender: TObject); procedure EditIDPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); protected FSkinTypeID: string; //标识 FPrefixID: string; //前缀编号 FIDLength: integer; //前缀长度 FImageFile: string; //照片文件 function OnVerifyCtrl(Sender: TObject; var nHint: string): Boolean; override; //基类方法 procedure InitFormData(const nID: string); //初始化数据 procedure GetData(Sender: TObject; var nData: string); //获取数据 function SetData(Sender: TObject; const nData: string): Boolean; //设置数据 public { Public declarations } class function CreateForm(const nPopedom: string = ''; const nParam: Pointer = nil): TWinControl; override; class function FormID: integer; override; end; implementation {$R *.dfm} uses IniFiles, UMgrControl, UAdjustForm, UFormCtrl, ULibFun, UDataModule, UFormBase, USysFun, USysGrid, USysConst, USysDB; var gForm: TfFormSkinType = nil; //------------------------------------------------------------------------------ class function TfFormSkinType.CreateForm(const nPopedom: string; const nParam: Pointer): TWinControl; var nP: PFormCommandParam; begin Result := nil; if Assigned(nParam) then nP := nParam else Exit; case nP.FCommand of cCmd_AddData: with TfFormSkinType.Create(Application) do begin FSkinTypeID := ''; Caption := '皮肤状况 - 添加'; InitFormData(''); nP.FCommand := cCmd_ModalResult; nP.FParamA := ShowModal; Free; end; cCmd_EditData: with TfFormSkinType.Create(Application) do begin FSkinTypeID := nP.FParamA; Caption := '皮肤状况 - 修改'; InitFormData(FSkinTypeID); nP.FCommand := cCmd_ModalResult; nP.FParamA := ShowModal; Free; end; cCmd_ViewData: begin if not Assigned(gForm) then begin gForm := TfFormSkinType.Create(Application); gForm.Caption := '皮肤状况 - 查看'; gForm.BtnOK.Visible := False; gForm.BtnAdd.Enabled := False; gform.BtnDel.Enabled := False; end; with gForm do begin FSkinTypeID := nP.FParamA; InitFormData(FSkinTypeID); if not gForm.Showing then gForm.Show; end; end; cCmd_FormClose: begin if Assigned(gForm) then FreeAndNil(gForm); end; end; end; class function TfFormSkinType.FormID: integer; begin Result := cFI_FormSkinType; end; procedure TfFormSkinType.FormCreate(Sender: TObject); var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try LoadFormConfig(Self); LoadMCListBoxConfig(Name, ListInfo1); FPrefixID := nIni.ReadString(Name, 'IDPrefix', 'PF'); FIDLength := nIni.ReadInteger(Name, 'IDLength', 8); finally nIni.Free; end; AdjustCtrlData(Self); ResetHintAllCtrl(Self, 'T', sTable_SkinType); end; procedure TfFormSkinType.FormClose(Sender: TObject; var Action: TCloseAction); var nIni: TIniFile; begin nIni := TIniFile.Create(gPath + sFormConfig); try SaveFormConfig(Self); SaveMCListBoxConfig(Name, ListInfo1); finally nIni.Free; end; gForm := nil; Action := caFree; ReleaseCtrlData(Self); end; //------------------------------------------------------------------------------ procedure TfFormSkinType.GetData(Sender: TObject; var nData: string); begin end; function TfFormSkinType.SetData(Sender: TObject; const nData: string): Boolean; begin Result := False; end; procedure TfFormSkinType.InitFormData(const nID: string); var nStr: string; begin if InfoItems.Properties.Items.Count < 1 then begin InfoItems.Clear; nStr := MacroValue(sQuery_SysDict, [MI('$Table', sTable_SysDict), MI('$Name', sFlag_SkinType)]); //数据字典中皮肤状况信息项 with FDM.QueryTemp(nStr) do begin First; while not Eof do begin InfoItems.Properties.Items.Add(FieldByName('D_Value').AsString); Next; end; end; end; if EditPart.Properties.Items.Count < 1 then begin nStr := 'B_ID=Select B_ID,B_Text From %s Where B_Group=''%s'''; nStr := Format(nStr, [sTable_BaseInfo, sFlag_SkinPart]); FDM.FillStringsData(EditPart.Properties.Items, nStr, -1, sDunHao); AdjustStringsItem(EditPart.Properties.Items, False); end; if nID <> '' then begin nStr := 'Select * From %s Where T_ID=''%s'''; nStr := Format(nStr, [sTable_SkinType, nID]); LoadDataToCtrl(FDM.QueryTemp(nStr), Self, '', SetData); FDM.LoadDBImage(FDM.SqlTemp, 'T_Image', ImagePic.Picture); ListInfo1.Clear; nStr := MacroValue(sQuery_ExtInfo, [MI('$Table', sTable_ExtInfo), MI('$Group', sFlag_SkinType), MI('$ID', nID)]); //扩展信息 with FDM.QueryTemp(nStr) do if RecordCount > 0 then begin First; while not Eof do begin nStr := FieldByName('I_Item').AsString + ListInfo1.Delimiter + FieldByName('I_Info').AsString; ListInfo1.Items.Add(nStr); Next; end; end; end; end; //------------------------------------------------------------------------------ //Desc: 添加信息项 procedure TfFormSkinType.BtnAddClick(Sender: TObject); begin InfoItems.Text := Trim(InfoItems.Text); if InfoItems.Text = '' then begin ListInfo1.SetFocus; ShowMsg('请填写 或 选择有效的名称', sHint); Exit; end; EditInfo.Text := Trim(EditInfo.Text); if EditInfo.Text = '' then begin EditInfo.SetFocus; ShowMsg('请填写有效的信息内容', sHint); Exit; end; ListInfo1.Items.Add(InfoItems.Text + ListInfo1.Delimiter + EditInfo.Text); end; //Desc: 删除信息项 procedure TfFormSkinType.BtnDelClick(Sender: TObject); var nIdx: integer; begin if ListInfo1.ItemIndex < 0 then begin ShowMsg('请选择要删除的内容', sHint); Exit; end; nIdx := ListInfo1.ItemIndex; ListInfo1.Items.Delete(ListInfo1.ItemIndex); if nIdx >= ListInfo1.Count then Dec(nIdx); ListInfo1.ItemIndex := nIdx; ShowMsg('已成功删除', sHint); end; //Desc: 查看信息 procedure TfFormSkinType.ListInfo1Click(Sender: TObject); var nStr: string; nPos: integer; begin if ListInfo1.ItemIndex > -1 then begin nStr := ListInfo1.Items[ListInfo1.ItemIndex]; nPos := Pos(ListInfo1.Delimiter, nStr); InfoItems.Text := Copy(nStr, 1, nPos - 1); System.Delete(nStr, 1, nPos + Length(ListInfo1.Delimiter) - 1); EditInfo.Text := nStr; end; end; //Desc: 选择照片 procedure TfFormSkinType.ImagePicDblClick(Sender: TObject); begin with TOpenDialog.Create(Application) do begin Title := '照片'; FileName := FImageFile; Filter := '图片文件|*.bmp;*.png;*.jpg'; if Execute then FImageFile := FileName; Free; end; if FileExists(FImageFile) then ImagePic.Picture.LoadFromFile(FImageFile); end; //Desc: 随机编号 procedure TfFormSkinType.EditIDPropertiesButtonClick(Sender: TObject; AButtonIndex: Integer); begin EditID.Text := FDM.GetRandomID(FPrefixID, FIDLength); end; //------------------------------------------------------------------------------ //Desc: 验证数据 function TfFormSkinType.OnVerifyCtrl(Sender: TObject; var nHint: string): Boolean; begin Result := True; if Sender = EditID then begin EditID.Text := Trim(EditID.Text); Result := EditID.Text <> ''; nHint := '请填写有效的编号'; end else if Sender = EditName then begin EditName.Text := Trim(EditName.Text); Result := EditName.Text <> ''; nHint := '请填写有效的名称'; end; end; //Desc: 保存数据 procedure TfFormSkinType.BtnOKClick(Sender: TObject); var i,nCount,nPos: integer; nStr,nSQL,nTmp: string; begin if not IsDataValid then Exit; if FSkinTypeID = '' then begin nStr := 'Select Count(*) From %s Where T_ID=''%s'''; nStr := Format(nStr, [sTable_SkinType, EditID.Text]); //查询编号是否存在 with FDM.QueryTemp(nStr) do if Fields[0].AsInteger > 0 then begin EditID.SetFocus; ShowMsg('该编号的记录已经存在', sHint); Exit; end; nSQL := MakeSQLByForm(Self, sTable_SkinType, '', True, GetData); end else begin EditID.Text := FSkinTypeID; nStr := 'T_ID=''' + FSkinTypeID + ''''; nSQL := MakeSQLByForm(Self, sTable_SkinType, nStr, False, GetData); end; FDM.ADOConn.BeginTrans; try FDM.ExecuteSQL(nSQL); if FileExists(FImageFile) then begin nStr := 'Select * From %s Where T_ID=''%s'''; nStr := Format(nStr, [sTable_SkinType, EditID.Text]); FDM.QueryTemp(nStr); FDM.SaveDBImage(FDM.SqlTemp, 'T_Image', FImageFile); end; if FSkinTypeID <> '' then begin nSQL := 'Delete From %s Where I_Group=''%s'' and I_ItemID=''%s'''; nSQL := Format(nSQL, [sTable_ExtInfo, sFlag_SkinType, FSkinTypeID]); FDM.ExecuteSQL(nSQL); end; nCount := ListInfo1.Items.Count - 1; for i:=0 to nCount do begin nStr := ListInfo1.Items[i]; nPos := Pos(ListInfo1.Delimiter, nStr); nTmp := Copy(nStr, 1, nPos - 1); System.Delete(nStr, 1, nPos + Length(ListInfo1.Delimiter) - 1); nSQL := 'Insert Into %s(I_Group, I_ItemID, I_Item, I_Info) ' + 'Values(''%s'', ''%s'', ''%s'', ''%s'')'; nSQL := Format(nSQL, [sTable_ExtInfo, sFlag_SkinType, EditID.Text, nTmp, nStr]); FDM.ExecuteSQL(nSQL); end; FDM.ADOConn.CommitTrans; ModalResult := mrOK; ShowMsg('数据已保存', sHint); except FDM.ADOConn.RollbackTrans; ShowMsg('数据保存失败', '未知原因'); end; end; initialization gControlManager.RegCtrl(TfFormSkinType, TfFormSkinType.FormID); end.
unit functions; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Windows, Registry, Math, USock; type MEMORYSTATUSEX = record dwLength: DWORD; dwMemoryLoad: DWORD; ullTotalPhys: uint64; ullAvailPhys: uint64; ullTotalPageFile: uint64; ullAvailPageFile: uint64; ullTotalVirtual: uint64; ullAvailVirtual: uint64; ullAvailExtendedVirtual: uint64; end; function GetMemory: Double; function GetComputerNetDescription: String; function GetRegData(Key, Name: String): String; function GetEnvironment(Name: String): String; function GetOS: String; function GetBit: String; function GetOSVersion: String; function GetProcessorInfo: String; function IsWindows64: Boolean; function GetIpAddress: String; function GetResolution: String; function GlobalMemoryStatusEx(var Buffer: MEMORYSTATUSEX): Boolean; stdcall; external 'kernel32' Name 'GlobalMemoryStatusEx'; implementation function GetMemory: Double; var PhysRam: MEMORYSTATUSEX; MemSize: Double; begin PhysRam.dwLength := SizeOf(PhysRam); GlobalMemoryStatusEx(PhysRam); MemSize := PhysRam.ullTotalPhys / 1024 / 1024 / 1024; if MemSize < 1 then MemSize := RoundTo(MemSize, -1) else MemSize := Round(MemSize); Result := MemSize; end; function IsWindows64: Boolean; { Detect if we are running on 64 bit Windows or 32 bit Windows, independently of bitness of this program. Original source: http://www.delphipraxis.net/118485-ermitteln-ob-32-bit-oder-64-bit-betriebssystem.html modified for FreePascal in German Lazarus forum: http://www.lazarusforum.de/viewtopic.php?f=55&t=5287 } {$ifdef WIN32} //Modified KpjComp for 64bit compile mode type TIsWow64Process = function( // Type of IsWow64Process API fn Handle: Windows.THandle; var Res: Windows.BOOL): Windows.BOOL; stdcall; var IsWow64Result: Windows.BOOL; // Result from IsWow64Process IsWow64Process: TIsWow64Process; // IsWow64Process fn reference begin IsWow64Result := false; // Try to load required function from kernel32 IsWow64Process := TIsWow64Process(Windows.GetProcAddress( Windows.GetModuleHandle('kernel32'), 'IsWow64Process')); if Assigned(IsWow64Process) then begin // Function is implemented: call it if not IsWow64Process(Windows.GetCurrentProcess, IsWow64Result) then raise SysUtils.Exception.Create('IsWindows64: bad process handle'); // Return result of function Result := IsWow64Result; end else // Function not implemented: can't be running on Wow64 Result := False; {$else} //if were running 64bit code, OS must be 64bit :) begin Result := True; {$endif} end; function GetRegData(Key, Name: String): String; var Reg: TRegistry; begin Result := ''; Reg := TRegistry.Create; Reg.RootKey := HKEY_LOCAL_MACHINE; Reg.OpenKeyReadOnly(Key); Result := Reg.ReadString(Name); Reg.CloseKey; Reg.Free; end; function GetComputerNetDescription: String; begin Result := GetRegData('SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters', 'SrvComment'); end; function GetOS: String; begin Result := GetRegData('SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ProductName'); end; function GetBit: String; begin Result := '32'; if IsWindows64 = true then Result := '64'; end; function GetOSVersion: String; begin Result := GetRegData('SOFTWARE\Microsoft\Windows NT\CurrentVersion', 'ReleaseId'); end; function GetProcessorInfo: String; begin Result := GetRegData('\HARDWARE\DESCRIPTION\System\CentralProcessor\0', 'ProcessorNameString'); end; function GetEnvironment(Name: String): String; begin Result := GetRegData('SYSTEM\CurrentControlSet\Control\Session manager\Environment', Name); end; function GetIpAddress: String; var ipAddress: String; begin ipAddress := ''; EnumInterfaces(ipAddress); Result := ipAddress; end; function GetResolution: String; begin Result := IntToStr(GetSystemMetrics(SM_CXSCREEN)) + 'x' + IntToStr(GetSystemMetrics(SM_CYSCREEN)); end; end.
unit Unbound.Game; interface uses System.SysUtils, Pengine.IntMaths, Pengine.Vector, Pengine.ICollections, Pengine.EventHandling, Pengine.Color, Pengine.Lua, Pengine.Lua.Header, Pengine.Interfaces, Unbound.Game.Serialization; type EUnboundError = class(Exception); TWorld = class; TChunk = class; /// <summary>A block aligned position in a world.</summary> IBlockPosition = interface(ISerializable) function GetWorld: TWorld; function GetPosition: TIntVector3; procedure SetPosition(const Value: TIntVector3); function GetChunk: TChunk; property World: TWorld read GetWorld; property Position: TIntVector3 read GetPosition write SetPosition; property Chunk: TChunk read GetChunk; end; TBlockPosition = class(TInterfaceBase, IBlockPosition, ISerializable) private FWorld: TWorld; FPosition: TIntVector3; // IBlockPosition function GetWorld: TWorld; function GetPosition: TIntVector3; procedure SetPosition(const Value: TIntVector3); function GetChunk: TChunk; public constructor Create(AWorld: TWorld); overload; constructor Create(AWorld: TWorld; const APosition: TIntVector3); overload; // IBlockPosition property World: TWorld read GetWorld; property Position: TIntVector3 read GetPosition write SetPosition; property Chunk: TChunk read GetChunk; // ISerializable procedure Serialize(ASerializer: TSerializer); end; /// <summary>A location (position and rotation) in a world.</summary> IWorldLocation = interface(ISerializable) function GetWorld: TWorld; function GetLocation: TLocation3; procedure SetLocation(const Value: TLocation3); function GetChunk: TChunk; function Copy: IWorldLocation; procedure Assign(const AFrom: IWorldLocation); property World: TWorld read GetWorld; property Location: TLocation3 read GetLocation write SetLocation; property Chunk: TChunk read GetChunk; end; TWorldLocation = class(TInterfacedObject, IWorldLocation, ISerializable) private FWorld: TWorld; FLocation: TLocation3; function GetWorld: TWorld; function GetLocation: TLocation3; procedure SetLocation(const Value: TLocation3); function GetChunk: TChunk; public constructor Create(AWorld: TWorld); overload; constructor Create(AWorld: TWorld; ALocation: TLocation3); overload; destructor Destroy; override; function Copy: IWorldLocation; procedure Assign(const AFrom: IWorldLocation); property World: TWorld read GetWorld; property Location: TLocation3 read GetLocation write SetLocation; property Chunk: TChunk read GetChunk; // ISerializable procedure Serialize(ASerializer: TSerializer); end; /// <summary>A material, which chunk terrain is made up of.</summary> TTerrainMaterial = class(TInterfaceBase, ISerializable) private FColor: TColorRGBA; public function Copy: TTerrainMaterial; property Color: TColorRGBA read FColor; // ISerializable procedure Serialize(ASerializer: TSerializer); end; TTerrainMaterialEditable = class(TTerrainMaterial) public procedure SetColor(AColor: TColorRGBA); end; /// <summary>The terrain which a chunk is made up of.</summary> TTerrain = class(TInterfaceBase, ISerializable) public const MaxVolume = $10000; private FSize: TIntVector3; FMaterials: IObjectList<TTerrainMaterial>; FData: array of Word; FOnChange: TEvent<TTerrain>; function PosToIndex(const APos: TIntVector3): Integer; inline; procedure Change; inline; function GetMaterials: IReadonlyList<TTerrainMaterial>; function GetMaterialIDAt(const APos: TIntVector3): Integer; procedure SetMaterialIDAt(const APos: TIntVector3; const Value: Integer); function GetMaterialAt(const APos: TIntVector3): TTerrainMaterial; procedure SetMaterialAt(const APos: TIntVector3; const Value: TTerrainMaterial); function GetOnChange: TEvent<TTerrain>.TAccess; public constructor Create(const ASize: TIntVector3); property Materials: IReadonlyList<TTerrainMaterial> read GetMaterials; function GetMaterialID(AMaterial: TTerrainMaterial): Integer; procedure RemoveUnusedMaterials; property Size: TIntVector3 read FSize; property MaterialIDAt[const APos: TIntVector3]: Integer read GetMaterialIDAt write SetMaterialIDAt; property MaterialAt[const APos: TIntVector3]: TTerrainMaterial read GetMaterialAt write SetMaterialAt; default; property OnChange: TEvent<TTerrain>.TAccess read GetOnChange; // ISerializable procedure Serialize(ASerializer: TSerializer); end; /// <summary>Block aligned models, which can take up multiple block spaces per model.</summary> TDesign = class(TInterfaceBase, ISerializable) public // ISerializable procedure Serialize(ASerializer: TSerializer); end; /// <summary>An entity, which can be placed and moved freely in the world.</summary> TEntity = class(TInterfaceBase, ISerializable) private FGUID: TGUID; FLocation: IWorldLocation; procedure SetLocation(const Value: IWorldLocation); public constructor Create(const ALocation: IWorldLocation); property GUID: TGUID read FGUID; property Location: IWorldLocation read FLocation write SetLocation; // ISerializable procedure Serialize(ASerializer: TSerializer); virtual; end; /// <summary>A cuboid chunk of a world, made up of terrain, design and entities.</summary> TChunk = class(TInterfaceBase, ISerializable) private FWorld: TWorld; FChunkPos: TIntVector3; FTerrain: TTerrain; FDesign: TDesign; FEntities: IObjectList<TEntity>; function GetWorldPos: TIntVector3; function GetSize: TIntVector3; function GetEntities: IReadonlyList<TEntity>; public constructor Create(AWorld: TWorld; const AChunkPos, ASize: TIntVector3); destructor Destroy; override; property World: TWorld read FWorld; property ChunkPos: TIntVector3 read FChunkPos; property WorldPos: TIntVector3 read GetWorldPos; property Size: TIntVector3 read GetSize; property Terrain: TTerrain read FTerrain; property Design: TDesign read FDesign; property Entities: IReadonlyList<TEntity> read GetEntities; // ISerializable procedure Serialize(ASerializer: TSerializer); end; TWorldGenerator = class; TWorldFeatureClass = class of TWorldFeature; /// <summary>A feature, that generates a chunk via the "Apply" method.</summary> TWorldFeature = class(TInterfaceBase, ISerializable) protected procedure Assign(AFrom: TWorldFeature); virtual; abstract; public constructor Create; virtual; class function CreateSame: TWorldFeature; function Copy: TWorldFeature; class function CreateTyped(AUBSMap: TUBSMap): TWorldFeature; class function GetName: string; virtual; abstract; procedure Serialize(ASerializer: TSerializer); virtual; procedure Apply(AChunk: TChunk); virtual; abstract; end; /// <summary>A list of world features, which get applied in order, making up a world generator.</summary> TWorldGenerator = class(TInterfaceBase, ISerializable) private FFeatures: IObjectList<TWorldFeature>; function CreateFeature(AUBSMap: TUBSMap): TWorldFeature; function GetFeatures: IReadonlyList<TWorldFeature>; public constructor Create; function Copy: TWorldGenerator; procedure GenerateChunk(AChunk: TChunk); property Features: IReadonlyList<TWorldFeature> read GetFeatures; // ISerializable procedure Serialize(ASerializer: TSerializer); end; TWorldGeneratorEditable = class(TWorldGenerator) public procedure AddFeature(AFeature: TWorldFeature); procedure RemoveFeature(AFeature: TWorldFeature); end; TGame = class; /// <summary>A close to infinite world, consisting of cuboid chunks.</summary> TWorld = class(TInterfaceBase, ISerializable) public const DefaultChunkSize: TIntVector3 = (X: 32; Y: 32; Z: 32); private FGame: TGame; FGenerator: TWorldGenerator; FChunks: IToObjectMap<TIntVector3, TChunk>; FChunkSize: TIntVector3; function GetChunks: IReadonlyMap<TIntVector3, TChunk>; public constructor Create(AGame: TGame); overload; constructor Create(AGame: TGame; AGenerator: TWorldGenerator); overload; property Game: TGame read FGame; property Generator: TWorldGenerator read FGenerator; property Chunks: IReadonlyMap<TIntVector3, TChunk> read GetChunks; property ChunkSize: TIntVector3 read FChunkSize; // ISerializable procedure Serialize(ASerializer: TSerializer); end; /// <summary>Contains game resources and behaviors.</summary> TGamePack = class(TInterfaceBase, ISerializable) private FName: string; FGUID: TGUID; // FVersion: TVersion; FDependencyGUIDs: IList<TGUID>; FMaterials: IObjectList<TTerrainMaterial>; FWorldGenerators: IObjectList<TWorldGenerator>; function GetDependencyGUIDs: IReadonlyList<TGUID>; function GetWorldGenerators: IReadonlyList<TWorldGenerator>; function GetMaterials: IReadonlyList<TTerrainMaterial>; public constructor Create; function Copy: TGamePack; property Name: string read FName; property GUID: TGUID read FGUID; property DependencyGUIDs: IReadonlyList<TGUID> read GetDependencyGUIDs; property WorldGenerators: IReadonlyList<TWorldGenerator> read GetWorldGenerators; property Materials: IReadonlyList<TTerrainMaterial> read GetMaterials; // ISerializable procedure Serialize(ASerializer: TSerializer); end; /// <summary>An editable version of TGamePack, which can be edited without the means of serialization.</summary> TGamePackEditable = class(TGamePack) public procedure SetName(AName: string); procedure GenerateNewGUID; procedure AddDependency(AGamePack: TGamePack); procedure RemoveDependency(AGamepack: TGamePack); procedure AddMaterial(AMaterial: TTerrainMaterial); procedure RemoveMaterial(AMaterial: TTerrainMaterial); procedure AddWorldGenerator(AGenerator: TWorldGenerator); procedure RemoveWorldGenerator(AGenerator: TWorldGenerator); end; /// <summary>A game, consisting of multiple worlds and global game settings.</summary> TGame = class(TInterfaceBase, ISerializable) private FLua: TLua; FGamePacks: IObjectList<TGamePack>; FWorlds: IObjectList<TWorld>; function CreateWorld: TWorld; function GetLuaState: TLuaState; function GetGamePacks: IReadonlyList<TGamePack>; function GetWorlds: IReadonlyList<TWorld>; public constructor Create; destructor Destroy; override; property Lua: TLua read FLua; property LuaState: TLuaState read GetLuaState; property GamePacks: IReadonlyList<TGamePack> read GetGamePacks; procedure AddGamePack(AGamePack: TGamePack); property Worlds: IReadonlyList<TWorld> read GetWorlds; function AddWorld(AGenerator: TWorldGenerator): TWorld; // ISerializable procedure Serialize(ASerializer: TSerializer); end; // TODO: Move this /// <summary>A special kind of entity, that reacts to physics.</summary> TPhysicsEntity = class(TEntity, ISerializable) private FVelocity: TVector3; procedure SetVelocity(const Value: TVector3); public property Velocity: TVector3 read FVelocity write SetVelocity; // ISerializable procedure Serialize(ASerializer: TSerializer); override; end; /// <summary>A player entity, usually controlled by an actual player.</summary> TPlayer = class(TPhysicsEntity, ISerializable) private FName: string; public property Name: string read FName; // ISerializable procedure Serialize(ASerializer: TSerializer); override; end; implementation uses Unbound.Game.WorldFeatures; { TBlockPosition } function TBlockPosition.GetWorld: TWorld; begin Result := FWorld; end; function TBlockPosition.GetPosition: TIntVector3; begin Result := FPosition; end; procedure TBlockPosition.SetPosition(const Value: TIntVector3); begin FPosition := Value; end; function TBlockPosition.GetChunk: TChunk; begin raise ENotImplemented.Create('TBlockPosition.GetChunk'); end; constructor TBlockPosition.Create(AWorld: TWorld); begin FWorld := AWorld; end; constructor TBlockPosition.Create(AWorld: TWorld; const APosition: TIntVector3); begin FWorld := AWorld; FPosition := APosition; end; procedure TBlockPosition.Serialize(ASerializer: TSerializer); begin ASerializer.Define('Position', FPosition); end; { TWorldFeature } function TWorldFeature.Copy: TWorldFeature; begin Result := CreateSame; Result.Assign(Self); end; constructor TWorldFeature.Create; begin // nothing end; class function TWorldFeature.CreateSame: TWorldFeature; begin Result := Create; end; class function TWorldFeature.CreateTyped(AUBSMap: TUBSMap): TWorldFeature; var FeatureType: string; FeatureClass: TWorldFeatureClass; begin FeatureType := AUBSMap['FeatureType'].Cast<TUBSString>.Value; for FeatureClass in WorldFeatureClasses do if FeatureClass.GetName = FeatureType then Exit(FeatureClass.Create); raise EUnboundError.CreateFmt('Invalid World-Feature type: %s', [FeatureType]); end; procedure TWorldFeature.Serialize(ASerializer: TSerializer); begin ASerializer.WriteOnly('FeatureType', GetName); end; { TWorldGenerator } function TWorldGenerator.CreateFeature(AUBSMap: TUBSMap): TWorldFeature; begin Result := TWorldFeature.CreateTyped(AUBSMap); end; function TWorldGenerator.GetFeatures: IReadonlyList<TWorldFeature>; begin Result := FFeatures.ReadonlyList; end; constructor TWorldGenerator.Create; begin FFeatures := TObjectList<TWorldFeature>.Create; end; function TWorldGenerator.Copy: TWorldGenerator; var Feature: TWorldFeature; begin Result := TWorldGenerator.Create; for Feature in Features do Result.FFeatures.Add(Feature.Copy); end; procedure TWorldGenerator.GenerateChunk(AChunk: TChunk); var Feature: TWorldFeature; begin for Feature in Features do Feature.Apply(AChunk); end; procedure TWorldGenerator.Serialize(ASerializer: TSerializer); begin ASerializer.Define<TWorldFeature>('Features', FFeatures, CreateFeature); end; { TTerrainMaterial } function TTerrainMaterial.Copy: TTerrainMaterial; begin Result := TTerrainMaterial.Create; Result.FColor := Color; end; procedure TTerrainMaterial.Serialize(ASerializer: TSerializer); begin ASerializer.Define('Color', FColor); end; { TTerrain } function TTerrain.PosToIndex(const APos: TIntVector3): Integer; begin Result := (APos.X * Size.Y + APos.Y) * Size.Z + APos.Z; end; function TTerrain.GetMaterials: IReadonlyList<TTerrainMaterial>; begin Result := FMaterials.ReadonlyList; end; function TTerrain.GetMaterialIDAt(const APos: TIntVector3): Integer; begin Result := FData[PosToIndex(APos)]; end; procedure TTerrain.SetMaterialIDAt(const APos: TIntVector3; const Value: Integer); var Index: Integer; begin Index := PosToIndex(APos); if FData[Index] = Value then Exit; FData[Index] := Value; Change; end; function TTerrain.GetMaterialAt(const APos: TIntVector3): TTerrainMaterial; begin Result := FMaterials[MaterialIDAt[APos]]; end; procedure TTerrain.SetMaterialAt(const APos: TIntVector3; const Value: TTerrainMaterial); begin MaterialIDAt[APos] := GetMaterialID(Value); end; function TTerrain.GetOnChange: TEvent<TTerrain>.TAccess; begin Result := FOnChange.Access; end; procedure TTerrain.Change; begin FOnChange.Execute(Self); end; constructor TTerrain.Create(const ASize: TIntVector3); begin Assert(ASize.Volume <= MaxVolume, Format('Terrain volume must be at most %d.', [MaxVolume])); FSize := ASize; end; function TTerrain.GetMaterialID(AMaterial: TTerrainMaterial): Integer; begin Result := FMaterials.IndexOf(AMaterial); if Result = -1 then begin FMaterials.Add(AMaterial); Result := FMaterials.MaxIndex; end; end; procedure TTerrain.RemoveUnusedMaterials; var UsedIDs: ISet<Word>; I, J: Integer; begin UsedIDs := TSet<Word>.Create(FData); for I := FMaterials.MaxIndex downto 0 do begin if not UsedIDs.Contains(FData[I]) then begin FMaterials.RemoveAt(I); for J := 0 to Length(FData) do if FData[J] > I then Dec(FData[J]); end; end; end; procedure TTerrain.Serialize(ASerializer: TSerializer); begin end; { TDesign } procedure TDesign.Serialize(ASerializer: TSerializer); begin end; { TChunk } function TChunk.GetWorldPos: TIntVector3; begin Result := FChunkPos * Size; end; function TChunk.GetSize: TIntVector3; begin Result := World.ChunkSize; end; function TChunk.GetEntities: IReadonlyList<TEntity>; begin Result := FEntities.ReadonlyList; end; constructor TChunk.Create(AWorld: TWorld; const AChunkPos, ASize: TIntVector3); begin FWorld := AWorld; FChunkPos := AChunkPos; FTerrain := TTerrain.Create(Size); end; destructor TChunk.Destroy; begin FTerrain.Free; FDesign.Free; inherited; end; procedure TChunk.Serialize(ASerializer: TSerializer); begin // TODO end; { TWorldLocation } function TWorldLocation.GetWorld: TWorld; begin Result := FWorld; end; function TWorldLocation.GetLocation: TLocation3; begin Result := FLocation; end; procedure TWorldLocation.SetLocation(const Value: TLocation3); begin FLocation.Assign(Value); end; function TWorldLocation.GetChunk: TChunk; begin raise ENotImplemented.Create('Calculate Chunk from location.'); end; constructor TWorldLocation.Create(AWorld: TWorld); begin FWorld := AWorld; FLocation := TLocation3.Create; end; destructor TWorldLocation.Destroy; begin FLocation.Free; inherited; end; function TWorldLocation.Copy: IWorldLocation; begin Result := TWorldLocation.Create(World); Result.Location.Assign(Location); end; constructor TWorldLocation.Create(AWorld: TWorld; ALocation: TLocation3); begin Create(AWorld); FLocation.Assign(ALocation); end; procedure TWorldLocation.Assign(const AFrom: IWorldLocation); begin FWorld := AFrom.World; Location.Assign(AFrom.Location); end; procedure TWorldLocation.Serialize(ASerializer: TSerializer); begin // TODO end; { TWorld } function TWorld.GetChunks: IReadonlyMap<TIntVector3, TChunk>; begin Result := FChunks.ReadonlyMap; end; constructor TWorld.Create(AGame: TGame); begin FGame := AGame; FChunks := TToObjectMap<TIntVector3, TChunk>.Create; FChunkSize := DefaultChunkSize; end; constructor TWorld.Create(AGame: TGame; AGenerator: TWorldGenerator); begin Create(AGame); FGenerator := AGenerator; end; procedure TWorld.Serialize(ASerializer: TSerializer); begin // TODO: Reference stuff, see other comment, use Generator reference from GamePack // ASerializer.Define('Generator', FGenerator, CreateGenerator); end; { TEntity } procedure TEntity.SetLocation(const Value: IWorldLocation); begin FLocation.Assign(Value); end; constructor TEntity.Create(const ALocation: IWorldLocation); begin FGUID := TGUID.NewGuid; FLocation := ALocation.Copy; end; procedure TEntity.Serialize(ASerializer: TSerializer); begin // TODO end; { TPhysicsEntity } procedure TPhysicsEntity.SetVelocity(const Value: TVector3); begin FVelocity := Value; end; procedure TPhysicsEntity.Serialize(ASerializer: TSerializer); begin inherited; // TODO end; { TPlayer } procedure TPlayer.Serialize(ASerializer: TSerializer); begin inherited; ASerializer.Define('Name', FName); end; { TGamePack } function TGamePack.GetDependencyGUIDs: IReadonlyList<TGUID>; begin Result := FDependencyGUIDs.ReadonlyList; end; function TGamePack.GetWorldGenerators: IReadonlyList<TWorldGenerator>; begin Result := FWorldGenerators.ReadonlyList; end; function TGamePack.GetMaterials: IReadonlyList<TTerrainMaterial>; begin Result := FMaterials.ReadonlyList; end; constructor TGamePack.Create; begin FDependencyGUIDs := TList<TGUID>.Create; FMaterials := TObjectList<TTerrainMaterial>.Create; FWorldGenerators := TObjectList<TWorldGenerator>.Create; end; function TGamePack.Copy: TGamePack; var Material: TTerrainMaterial; WorldGenerator: TWorldGenerator; begin Result := TGamePack.Create; Result.FName := Name; Result.FGUID := GUID; Result.FDependencyGUIDs.AddRange(DependencyGUIDs); for Material in Materials do Result.FMaterials.Add(Material.Copy); for WorldGenerator in WorldGenerators do Result.FWorldGenerators.Add(WorldGenerator.Copy); end; procedure TGamePack.Serialize(ASerializer: TSerializer); begin ASerializer.Define('Name', FName); ASerializer.Define('GUID', FGUID); ASerializer.Define('DependencyGUIDs', FDependencyGUIDs); ASerializer.Define<TTerrainMaterial>('Materials', FMaterials); ASerializer.Define<TWorldGenerator>('WorldGenerators', FWorldGenerators); end; { TGamePackEditable } procedure TGamePackEditable.SetName(AName: string); begin FName := AName; end; procedure TGamePackEditable.GenerateNewGUID; begin FGUID := TGUID.NewGuid; end; procedure TGamePackEditable.AddDependency(AGamePack: TGamePack); begin FDependencyGUIDs.Add(AGamePack.GUID); end; procedure TGamePackEditable.RemoveDependency(AGamepack: TGamePack); begin FDependencyGUIDs.Remove(AGamePack.GUID); end; procedure TGamePackEditable.AddMaterial(AMaterial: TTerrainMaterial); begin FMaterials.Add(AMaterial.Copy); end; procedure TGamePackEditable.RemoveMaterial(AMaterial: TTerrainMaterial); begin FMaterials.Remove(AMaterial); end; procedure TGamePackEditable.AddWorldGenerator(AGenerator: TWorldGenerator); begin FWorldGenerators.Add(AGenerator.Copy); end; procedure TGamePackEditable.RemoveWorldGenerator(AGenerator: TWorldGenerator); begin FWorldGenerators.Remove(AGenerator); end; { TGame } function TGame.CreateWorld: TWorld; begin Result := TWorld.Create(Self); end; function TGame.GetLuaState: TLuaState; begin Result := FLua.L; end; function TGame.GetGamePacks: IReadonlyList<TGamePack>; begin Result := FGamePacks.ReadonlyList; end; function TGame.GetWorlds: IReadonlyList<TWorld>; begin Result := FWorlds.ReadonlyList; end; constructor TGame.Create; begin FLua := TLua.Create; FGamePacks := TObjectList<TGamePack>.Create; FWorlds := TObjectList<TWorld>.Create; end; destructor TGame.Destroy; begin FLua.Free; inherited; end; procedure TGame.AddGamePack(AGamePack: TGamePack); var Generator: TWorldGenerator; begin AGamePack := AGamePack.Copy; FGamePacks.Add(AGamePack); for Generator in AGamePack.WorldGenerators do AddWorld(Generator); end; function TGame.AddWorld(AGenerator: TWorldGenerator): TWorld; begin Result := TWorld.Create(Self, AGenerator); FWorlds.Add(Result); end; procedure TGame.Serialize(ASerializer: TSerializer); begin ASerializer.Define<TGamePack>('GamePacks', FGamePacks); ASerializer.Define<TWorld>('Worlds', FWorlds, CreateWorld); end; { TTerrainMaterialEditable } procedure TTerrainMaterialEditable.SetColor(AColor: TColorRGBA); begin FColor := AColor; end; { TWorldGeneratorEditable } procedure TWorldGeneratorEditable.AddFeature(AFeature: TWorldFeature); begin FFeatures.Add(AFeature.Copy); end; procedure TWorldGeneratorEditable.RemoveFeature(AFeature: TWorldFeature); begin FFeatures.Remove(AFeature); end; end.
{********************************************************************} { TLISTLINK component } { for Delphi & C++Builder } { } { written by } { TMS Software } { copyright © 1997-2011 } { Email : info@tmssoftware.com } { Web : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The source } { code remains property of the author and may not be distributed } { freely as such nor sold in any form. } {********************************************************************} unit listlink; {$I TMSDEFS.INC} interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, stdctrls, comctrls; const MAJ_VER = 1; // Major version nr. MIN_VER = 3; // Minor version nr. REL_VER = 0; // Release nr. BLD_VER = 0; // Build nr. // version history // v1.0.0.0 : First release type TClickEvent = procedure (Sender:TObject) of object; TDragDropMode = (ddCopy,ddMove); TLinkMode = (lmListBox, lmListView); {$IFDEF DELPHIXE2_LVL} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TListLink = class(TComponent) private FLinkMode: TLinkMode; FMoveLR:TButton; FMoveRL:TButton; FMoveSelLR:TButton; FMoveSelRL:TButton; FCopyLR:TButton; FCopyRL:TButton; FCopySelLR:TButton; FCopySelRL:TButton; FLList:TListBox; FRList:TListBox; FLListView:TListView; FRListView:TListView; FMoveLRClick:tclickevent; FMoveRLClick:tclickevent; FMoveSelLRClick:tclickevent; FMoveSelRLClick:tclickevent; FCopyLRClick:tclickevent; FCopyRLClick:tclickevent; FCopySelLRClick:tclickevent; FCopySelRLClick:tclickevent; FOnModified: TNotifyEvent; MoveLRAssigned:boolean; MoveRLAssigned:boolean; MoveSelLRAssigned:boolean; MoveSelRLAssigned:boolean; CopyLRAssigned:boolean; CopyRLAssigned:boolean; CopySelLRAssigned:boolean; CopySelRLAssigned:boolean; FDragDropMode:TDragDropMode; procedure SetMoveLR(abutton:TButton); procedure SetMoveRL(abutton:TButton); procedure SetMoveSelLR(abutton:TButton); procedure SetMoveSelRL(abutton:TButton); procedure SetCopyLR(abutton:TButton); procedure SetCopyRL(abutton:TButton); procedure SetCopySelLR(abutton:TButton); procedure SetCopySelRL(abutton:TButton); procedure SetLList(alist:TListBox); procedure SetRList(alist:TListBox); procedure MoveLRClick(Sender:TObject); procedure MoveRLClick(Sender:TObject); procedure MoveSelLRClick(Sender:TObject); procedure MoveSelRLClick(Sender:TObject); procedure CopyLRClick(Sender:TObject); procedure CopyRLClick(Sender:TObject); procedure CopySelLRClick(Sender:TObject); procedure CopySelRLClick(Sender:TObject); procedure DragOverLList(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure DragOverRList(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure DragDropLList(Sender, Source: TObject;X, Y: Integer); procedure DragDropRList(Sender, Source: TObject;X, Y: Integer); procedure DragOverLListView(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure DragOverRListView(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure DragDropLListView(Sender, Source: TObject;X, Y: Integer); procedure DragDropRListView(Sender, Source: TObject;X, Y: Integer); procedure MoveListData(sourcelist,targetlist:TListBox); procedure MoveSelListData(sourcelist,targetlist:TListBox); procedure MoveSelListViewData(sourcelist,targetlist:TListView); procedure CopyListData(sourcelist,targetlist:TListBox;idx:integer); procedure CopySelListData(sourcelist,targetlist:TListBox); procedure CopySelListViewData(sourcelist,targetlist:TListView); procedure CopyEntireList(sourcelist,targetlist:TListBox); procedure MoveEntireList(sourcelist,targetlist:TListBox); procedure CopyEntireListView(sourcelist,targetlist:TListView); procedure MoveEntireListView(sourcelist,targetlist:TListView); procedure SetLListView(const Value: TListView); procedure SetRListView(const Value: TListView); function GetVersion: string; procedure SetVersion(const Value: string); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; protected function GetVersionNr: Integer; virtual; procedure Notification(AComponent: TComponent; Operation: TOperation); override; published property MoveLR:TButton read FMoveLR write SetMoveLR; property MoveRL:TButton read FMoveRL write SetMoveRL; property MoveSelLR:TButton read FMoveSelLR write SetMoveSelLR; property MoveSelRL:TButton read FMoveSelRL write SetMoveSelRL; property CopyLR:TButton read FCopyLR write SetCopyLR; property CopyRL:TButton read FCopyRL write SetCopyRL; property CopySelLR:TButton read FCopySelLR write SetCopySelLR; property CopySelRL:TButton read FCopySelRL write SetCopySelRL; property LinkMode:TLinkMode read fLinkMode write fLinkMode; property LList:TListBox read FLList write SetLList; property RList:TListBox read FRList write SetRList; property LListView:TListView read FLListView write SetLListView; property RListView:TListView read FRListView write SetRListView; property DragDropMode:TDragDropMode read FDragDropMode write FDragDropMode; property OnModified: TNotifyEvent read FOnModified write FOnModified; property Version: string read GetVersion write SetVersion; end; implementation constructor TListLink.Create(AOwner: TComponent); begin inherited Create(AOwner); MoveLRAssigned:=false; MoveRLAssigned:=false; MoveSelLRAssigned:=false; MoveSelRLAssigned:=false; CopyLRAssigned:=false; CopyRLAssigned:=false; CopySelLRAssigned:=false; CopySelRLAssigned:=false; end; destructor TListLink.Destroy; begin inherited; end; procedure TListLink.SetLList(alist:TListBox); begin FLList:=alist; if aList=nil then exit; FLList.OnDragDrop:=DragDropLList; FLList.OnDragOver:=DragOverLList; end; procedure TListLink.SetRList(alist:TListBox); begin FRList:=alist; if aList=nil then exit; FRList.OnDragDrop:=DragDropRList; FRList.onDragOver:=DragOverRList; end; procedure TListLink.SetMoveLR(abutton:TButton); begin MoveLRAssigned:=false; FMoveLR:=abutton; if abutton=nil then exit; if assigned(FMoveLR.OnClick) then begin FMoveLRClick:=FMoveLR.OnClick; MoveLRAssigned:=true; end; FMoveLR.OnClick:=MoveLRClick; end; procedure TListLink.SetMoveRL(abutton:TButton); begin MoveRLAssigned:=false; FMoveRL:=abutton; if abutton=nil then exit; if assigned(FMoveRL.OnClick) then begin FMoveRLClick:=FMoveRL.OnClick; MoveRLAssigned:=true; end; FMoveRL.OnClick:=MoveRLClick; end; procedure TListLink.SetMoveSelLR(abutton:TButton); begin MoveSelLRAssigned:=false; FMoveSelLR:=abutton; if abutton=nil then exit; if assigned(FMoveSelLR.OnClick) then begin FMoveSelLRClick:=FMoveSelLR.OnClick; MoveSelLRAssigned:=true; end; FMoveSelLR.OnClick:=MoveSelLRClick; end; procedure TListLink.SetMoveSelRL(abutton:TButton); begin MoveSelRLAssigned:=false; FMoveSelRL:=abutton; if abutton=nil then exit; if assigned(FMoveSelRL.OnClick) then begin FMoveSelRLClick:=FMoveSelRL.OnClick; MoveSelRLAssigned:=true; end; FMoveSelRL.OnClick:=MoveSelRLClick; end; procedure TListLink.SetCopyLR(abutton:TButton); begin CopyLRAssigned:=false; FCopyLR:=abutton; if abutton=nil then exit; if assigned(FCopyLR.OnClick) then begin FCopyLRClick:=FCopyLR.OnClick; CopyLRAssigned:=true; end; FCopyLR.OnClick:=CopyLRClick; end; procedure TListLink.SetCopyRL(abutton:TButton); begin CopyRLAssigned:=false; FCopyRL:=abutton; if abutton=nil then exit; if assigned(FCopyRL.OnClick) then begin FCopyRLClick:=FCopyRL.OnClick; CopyRLAssigned:=true; end; FCopyRL.OnClick:=CopyRLClick; end; procedure TListLink.SetCopySelLR(abutton:TButton); begin CopySelLRAssigned:=false; FCopySelLR:=abutton; if abutton=nil then exit; if assigned(FCopySelLR.OnClick) then begin FCopySelLRClick:=FCopySelLR.OnClick; CopySelLRAssigned:=true; end; FCopySelLR.OnClick:=CopySelLRClick; end; procedure TListLink.SetCopySelRL(abutton:TButton); begin CopySelRLAssigned:=false; FCopySelRL:=abutton; if abutton=nil then exit; if assigned(FCopySelRL.OnClick) then begin FCopySelRLClick:=FCopySelRL.OnClick; CopySelRLAssigned:=true; end; FCopySelRL.OnClick:=CopySelRLClick; end; procedure TListLink.MoveEntireList(sourcelist,targetlist:TListBox); begin CopyEntireList(sourcelist,targetlist); sourceList.items.clear; end; procedure TListLink.MoveEntireListView(sourcelist,targetlist:TListView); begin CopyEntireListView(sourcelist,targetlist); sourceList.items.clear; end; procedure TListLink.CopyEntireList(sourcelist,targetlist:TListBox); begin if not assigned(sourceList) then exit; if not assigned(targetList) then exit; if sourceList.items.count = 0 then exit; targetList.items.Addstrings(sourceList.items); if assigned(FOnModified) then FOnModified(Self); end; procedure TListLink.CopyEntireListView(sourcelist,targetlist:TListView); begin if not assigned(sourceList) then exit; if not assigned(targetList) then exit; if sourceList.items.count = 0 then exit; targetlist.items.Assign(sourcelist.items); if assigned(FOnModified) then FOnModified(Self); end; procedure TListLink.MoveListData(sourcelist,targetlist:TListBox); var data:longint; idx:integer; begin data:=sendmessage(sourcelist.handle,lb_getitemdata,sourcelist.itemindex,0); idx:=targetlist.items.add(sourcelist.items[sourcelist.itemindex]); sendmessage(targetlist.handle,lb_setitemdata,idx,data); targetlist.itemindex:=idx; if targetlist.multiselect then targetlist.selected[idx]:=true; idx:=sourcelist.itemindex; sourcelist.items.delete(sourcelist.itemindex); if (idx>=sourcelist.items.count) then idx:=sourcelist.items.count-1; sourcelist.itemindex:=idx; if sourcelist.multiselect then sourcelist.selected[idx]:=true; if assigned(FOnModified) then FOnModified(Self); end; procedure TListLink.CopyListData(sourcelist,targetlist:TListBox;idx:integer); var data:longint; pos:integer; begin data:=sendmessage(sourcelist.handle,lb_getitemdata,idx,0); pos:=targetlist.items.add(sourcelist.items[idx]); sendmessage(targetlist.handle,lb_setitemdata,pos,data); targetlist.itemindex:=pos; if targetlist.multiselect then targetlist.selected[pos]:=true; if assigned(FOnModified) then FOnModified(Self); end; procedure TListLink.CopySelListData(sourcelist,targetlist:TListBox); var i:integer; begin if not assigned(SourceList) then exit; if not assigned(TargetList) then exit; if SourceList.Items.Count<=0 then exit; for i:=0 to sourcelist.items.count-1 do begin if sourcelist.selected[i] then begin CopyListData(sourcelist,targetlist,i); end; end; end; procedure TListLink.CopySelListViewData(sourcelist,targetlist:TListView); var i:integer; begin if not assigned(SourceList) then exit; if not assigned(TargetList) then exit; if SourceList.Items.Count<=0 then exit; for i:=0 to sourcelist.items.count-1 do begin if sourcelist.Items[i].Selected then begin targetlist.Items.Add.Assign(sourcelist.Items[i]); end; end; if assigned(FOnModified) then FOnModified(Self); end; procedure TListLink.MoveSelListData(sourcelist,targetlist:TListBox); var i,j:integer; begin if not assigned(SourceList) then exit; if not assigned(TargetList) then exit; if SourceList.Items.Count<=0 then exit; for i:=0 to sourcelist.items.count-1 do begin if sourcelist.selected[i] then begin CopyListData(sourcelist,targetlist,i); end; end; i:=0; j:=0; while (i<=sourcelist.items.count-1) and (sourcelist.items.count>=0) do begin if sourcelist.selected[i] then begin sourcelist.items.delete(i); j:=i; end else inc(i); end; if (j>=sourcelist.items.count) then dec(j); if (j>=0) then sourcelist.itemindex:=j; end; procedure TListLink.MoveSelListViewData(sourcelist,targetlist:TListView); var i,j:integer; begin if not assigned(SourceList) then exit; if not assigned(TargetList) then exit; if SourceList.Items.Count<=0 then exit; for i:=0 to sourcelist.items.count-1 do begin if sourcelist.Items[i].Selected then begin targetlist.Items.Add.Assign(sourcelist.Items[i]); end; end; i:=0; j:=0; while (i<=sourcelist.items.count-1) and (sourcelist.items.count>=0) do begin if sourcelist.items[i].selected then begin sourcelist.items[i].Free; j:=i; end else inc(i); end; if (j>=sourcelist.items.count) then dec(j); if (j>=0) then begin sourcelist.Selected:=sourcelist.items[j]; sourcelist.items[j].Selected:=true; end; if assigned(FOnModified) then FOnModified(Self); end; procedure TListLink.MoveSelRLClick(Sender:TObject); begin if MoveSelRLassigned then begin try FMoveSelRLClick(Sender); except end; end; if fLinkMode=lmListBox then MoveSelListData(FRList,FLList) else MoveSelListViewData(FRListView,FLListView); end; procedure TListLink.MoveRLClick(sender:tobject); begin if MoveRLassigned then begin try FMoveRLClick(Sender); except end; end; if fLinkMode=lmListBox then MoveEntireList(FRList,FLList) else MoveEntireListView(FRListView,FLListView); end; procedure TListLink.MoveLRClick(sender:tobject); begin if MoveLRassigned then begin try FMoveLRClick(Sender); except end; end; if fLinkMode=lmListBox then MoveEntireList(FLList,FRList) else MoveEntireListView(FLListView,FRListView); end; procedure TListLink.MoveSelLRClick(Sender:TObject); begin if MoveSelLRassigned then begin try FMoveSelLRClick(Sender); except end; end; if fLinkMode=lmListBox then MoveSelListData(FLList,FRList) else MoveSelListViewData(FLListView,FRListView); end; procedure TListLink.CopySelRLClick(Sender:TObject); begin if CopySelRLassigned then begin try FCopySelRLClick(Sender); except end; end; if fLinkMode=lmListBox then CopySelListData(FRList,FLList) else CopySelListViewData(FRListView,FLListView) end; procedure TListLink.CopyRLClick(sender:tobject); begin if CopyRLassigned then begin try FCopyRLClick(Sender); except end; end; if fLinkMode=lmListBox then CopyEntireList(FRList,FLList) else CopyEntireListView(FRListView,FLListView); end; procedure TListLink.CopyLRClick(sender:tobject); begin if CopyLRassigned then begin try FCopyLRClick(Sender); except end; end; if fLinkMode=lmListBox then CopyEntireList(FLList,FRList) else CopyEntireListView(FLListView,FRListView); end; procedure TListLink.CopySelLRClick(Sender:TObject); begin if CopySelLRassigned then begin try FCopySelLRClick(Sender); except end; end; if fLinkMode=lmListBox then CopySelListData(FLList,FRList) else CopySelListViewData(FLListView,FRListView); end; procedure TListLink.DragOverLList(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin accept:=(source=rlist); end; procedure TListLink.DragOverRList(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin accept:=(source=llist); end; procedure TListLink.DragDropLList(Sender, Source: TObject;X, Y: Integer); begin if (FRList.itemindex<>-1) and (source=FRList) then begin if (FDragDropMode=ddMove) then begin if FRList.multiselect then MoveSelListData(FRList,FLList) else MoveListData(FRList,FLList); end else begin if FRList.multiselect then CopySelListData(FRList,FLList) else CopyListData(FRList,FLList,FRList.itemindex); end; end; end; procedure TListLink.DragDropRList(Sender, Source: TObject;X, Y: Integer); begin if (FLList.itemindex<>-1) and (source=FLList) then begin if (FDragDropMode=ddMove) then begin if FLList.multiselect then MoveSelListData(FLList,FRList) else MoveListData(FLList,FRList); end else begin if FLList.multiselect then CopySelListData(FLList,FRList) else CopyListData(FLList,FRList,FLList.Itemindex); end; end; end; procedure TListLink.Notification(AComponent: TComponent; Operation: TOperation); begin inherited Notification(AComponent, Operation); if (Operation = opRemove) and (AComponent = fLList) then fLList := nil; if (Operation = opRemove) and (AComponent = fRList) then fRList := nil; if (Operation = opRemove) and (AComponent = fLListView) then fLListView := nil; if (Operation = opRemove) and (AComponent = fRListView) then fRListView := nil; if (Operation = opRemove) and (AComponent = fMoveLR) then fMoveLR := nil; if (Operation = opRemove) and (AComponent = fMoveRL) then fMoveRL := nil; if (Operation = opRemove) and (AComponent = fMoveSelLR) then fMoveSelLR := nil; if (Operation = opRemove) and (AComponent = fMoveSelRL) then fMoveSelRL := nil; if (Operation = opRemove) and (AComponent = fCopyLR) then fCopyLR := nil; if (Operation = opRemove) and (AComponent = fCopyRL) then fCopyRL := nil; if (Operation = opRemove) and (AComponent = fCopySelLR) then fCopySelLR := nil; if (Operation = opRemove) and (AComponent = fCopySelRL) then fCopySelRL := nil; end; procedure TListLink.SetLListView(const Value: TListView); begin FLListView := Value; FLListView.OnDragDrop:=DragDropLListView; FLListView.OnDragOver:=DragOverLListView; end; procedure TListLink.SetRListView(const Value: TListView); begin FRListView := Value; FRListView.OnDragDrop:=DragDropRListView; FRListView.OnDragOver:=DragOverRListView; end; procedure TListLink.DragDropLListView(Sender, Source: TObject; X, Y: Integer); begin if assigned(FRListView.Selected) and (source=FRListView) then begin if (FDragDropMode=ddMove) then begin MoveSelListViewData(FRListView,FLListView); end else begin CopySelListViewData(FRListView,FLListView); end; end; end; procedure TListLink.DragDropRListView(Sender, Source: TObject; X, Y: Integer); begin if assigned(FLListView.Selected) and (source=FLListView) then begin if (FDragDropMode=ddMove) then begin MoveSelListViewData(FLListView,FRListView); end else begin CopySelListViewData(FLListView,FRListView); end; end; end; procedure TListLink.DragOverLListView(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin accept:=(source=rlistview); end; procedure TListLink.DragOverRListView(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin accept:=(source=llistview); end; function TListLink.GetVersion: string; var vn: Integer; begin vn := GetVersionNr; Result := IntToStr(Hi(Hiword(vn)))+'.'+IntToStr(Lo(Hiword(vn)))+'.'+IntToStr(Hi(Loword(vn)))+'.'+IntToStr(Lo(Loword(vn))); end; function TListLink.GetVersionNr: Integer; begin Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER)); end; procedure TListLink.SetVersion(const Value: string); begin end; end.
{$I ACBr.inc} unit pciotVeiculoR; interface uses SysUtils, Classes, {$IFNDEF VER130} Variants, {$ENDIF} pcnConversao, pciotCIOT, ASCIOTUtil; type TVeiculoR = class(TPersistent) private FLeitor: TLeitor; FVeiculo: TVeiculo; FSucesso: Boolean; FMensagem: String; FOperacao: TpciotOperacao; public constructor Create(AOwner: TVeiculo; AOperacao: TpciotOperacao = opObter); destructor Destroy; override; function LerXml: boolean; published property Leitor: TLeitor read FLeitor write FLeitor; property Veiculo: TVeiculo read FVeiculo write FVeiculo; property Sucesso: Boolean read FSucesso write FSucesso; property Mensagem: String read FMensagem write FMensagem; end; implementation { TVeiculoR } constructor TVeiculoR.Create(AOwner: TVeiculo; AOperacao: TpciotOperacao = opObter); begin FLeitor := TLeitor.Create; FVeiculo := AOwner; FOperacao := AOperacao; end; destructor TVeiculoR.Destroy; begin FLeitor.Free; inherited Destroy; end; function TVeiculoR.LerXml: boolean; var ok: boolean; begin case FOperacao of opObter: begin if Leitor.rExtrai(1, 'ObterPorPlacaRequest') <> '' then begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); end; end; opAdicionar: begin if Leitor.rExtrai(1, 'GravarResult') <> '' then //GravarResponse begin FSucesso := Leitor.rCampo(tcStr, 'Sucesso ' + NAME_SPACE_EFRETE_OBJECTS, '/Sucesso') = 'true'; FMensagem := Leitor.rCampo(tcStr, 'Mensagem'); end; end; end; if Leitor.rExtrai(1, 'Veiculo') <> '' then begin Veiculo.AnoFabricacao := Leitor.rCampo(tcInt, 'AnoFabricacao'); Veiculo.AnoModelo := Leitor.rCampo(tcInt, 'AnoModelo'); Veiculo.CapacidadeKg := Leitor.rCampo(tcInt, 'CapacidadeKg'); Veiculo.CapacidadeM3 := Leitor.rCampo(tcInt, 'CapacidadeM3'); Veiculo.Chassi := Leitor.rCampo(tcStr, 'Chassi'); Veiculo.Placa := Leitor.rCampo(tcStr, 'Placa'); Veiculo.Cor := Leitor.rCampo(tcStr, 'Cor'); Veiculo.Marca := Leitor.rCampo(tcStr, 'Marca'); Veiculo.Modelo := Leitor.rCampo(tcStr, 'Modelo'); Veiculo.NumeroDeEixos := Leitor.rCampo(tcInt, 'NumeroDeEixos'); Veiculo.CodigoMunicipio := Leitor.rCampo(tcStr, 'CodigoMunicipio'); Veiculo.RNTRC := Leitor.rCampo(tcInt, 'RNTRC'); Veiculo.Renavam := Leitor.rCampo(tcInt, 'Renavam'); Veiculo.Tara := Leitor.rCampo(tcInt, 'Tara'); Veiculo.TipoCarroceria := StrToTpCarroceria(ok, Leitor.rCampo(tcStr, 'TipoCarroceria')); Veiculo.TipoRodado := StrToTpRodado(ok, Leitor.rCampo(tcStr, 'TipoRodado')); end; //VR01 GravarResponse RAIZ - - - - - - //VR02 Excecao RAIZ - - - - - - // VR03 Mensagem E VR02 S 1-1 - - Mensagem de erro. Só terá valor no caso de Sucesso for False. //VR04 Sucesso E VR01 S 1-1 - - Indicativo de sucesso na solicitação do serviço. Os valores para este campo são: · True (sucesso na solicitação) · False (erro na solicitação). //VR05 Veiculo RAIZ VR01 - 1-1 - - - // VR06 AnoFabricacao E VR05 N 1-1 4 - De 1930 até o ano atual. // VR07 AnoModelo E VR05 N 1-1 4 - De 1930 até o ano atual. // VR08 CapacidadeKg E VR05 N 1-1 - - Capacidade do veículo em Kg. // VR09 CapacidadeM3 E VR05 N 1-1 - - Capacidade do veículo em M3. // VR10 Chassi E VR05 S 1-1 - - Chassi do veículo. // VR11 CodigoMunicipio E VR05 S 1-1 7 - Código do Município segundo IBGE. // VR12 Cor E VR05 S 1-1 - - Cor do veículo. // VR13 Marca E VR05 S 1-1 - - Marca do veículo. // VR14 Modelo E VR05 S 1-1 - - Modelo do veículo. // VR15 NumeroDeEixos E VR05 N 1-1 - - Número de eixos do veículo. // VR16 Placa E VR05 S 1-1 7 - Exemplo: AAA1234. // VR17 RNTRC E VR05 N 1-1 8 - RNTRC do veículo. // VR18 Renavam E VR05 N 1-1 0-11 - RENAVAM do veículo. // VR19 Tara E VR05 N 1-1 - - Peso do veículo. // VR20 TipoCarroceria E VR05 S 0-1 - - - // VR21 TipoRodado E VR05 S 0-1 - - - //VR22 Versão E VR01 N 1-1 1 - Versão = 1 Result := true; end; end.
{ Demo-Program for TLMDShapeHint. This small demo demonstrates some extended features of the TLMDShapeHint- property. Note the very strong LMDCP[..]-routines with which you can manipulate LMD-objects or standard-objects in the same way like the LMD-Tools package does internally. © 95 - 97 by LMD Innovative ------------------------------------------------------------------ } unit Lmddehi1; interface uses Windows, SysUtils, Messages, Classes, Graphics, Controls, Forms, Dialogs, LMDCustomShapeHint, LMDShapeHint, LMDCustomComponent, LMDWndProcComponent, LMDFormStyler, LMDCustomComboBox, LMDCustomColorComboBox, LMDColorComboBox, LMDControl, LMDBaseControl, LMDBaseGraphicControl, LMDBaseShape, LMDShapeControl, LMDCustomHint, StdCtrls; type TfrmshapeHint = class(TForm) shape: TLMDShapeControl; memo: TMemo; Label1: TLabel; cmb: TComboBox; Label2: TLabel; ccmb: TLMDColorComboBox; bcmb: TLMDColorComboBox; Label3: TLabel; Label4: TLabel; cmbstyle: TComboBox; Label5: TLabel; LMDFormStyler1: TLMDFormStyler; shint: TLMDShapeHint; Button1: TButton; procedure memoChange(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cmbChange(Sender: TObject); procedure ccmbChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure Button1Click(Sender: TObject); private { Private-Deklarationen } public { Public-Deklarationen } end; var frmshapeHint: TfrmshapeHint; implementation {$R *.DFM} procedure TfrmshapeHint.memoChange(Sender: TObject); begin shape.Hint:=memo.Text; end; procedure TfrmshapeHint.FormCreate(Sender: TObject); begin ccmb.SelectedColor:=shint.Color; bcmb.SelectedColor:=shint.BorderColor; end; procedure TfrmshapeHint.cmbChange(Sender: TObject); begin if sender=cmb then shint.position:=TLMDHintPosition(ord(cmb.itemindex)) else if sender=cmbstyle then shint.style:=TLMDHintStyle(ord(cmbstyle.itemindex)); end; procedure TfrmshapeHint.ccmbChange(Sender: TObject); begin if sender=ccmb then shint.color:=ccmb.selectedColor else if sender=bcmb then shint.bordercolor:=bcmb.selectedColor; end; procedure TfrmshapeHint.FormClose(Sender: TObject; var Action: TCloseAction); begin sHint.Enabled:=False; end; procedure TfrmshapeHint.Button1Click(Sender: TObject); begin Close end; end.
unit l3Reader; { Библиотека "L3 (Low Level Library)" } { Автор: Люлин А.В. © } { Модуль: l3Reader - } { Начат: 10.03.2006 18:55 } { $Id: l3Reader.pas,v 1.2 2008/02/14 17:09:15 lulin Exp $ } // $Log: l3Reader.pas,v $ // Revision 1.2 2008/02/14 17:09:15 lulin // - cleanup. // // Revision 1.1 2006/03/10 18:22:08 lulin // - работа над заливкой/выливкой строковых ресурсов. // {$Include l3Define.inc } interface uses l3Interfaces, l3Types, l3Base, l3Filer, l3CacheableBase ; type Tl3Reader = class(Tl3CacheableBase, Il3Reader) private // internal fields f_Filer : Tl3CustomFiler; protected // internal methods procedure DoRead; virtual; abstract; {-} procedure Execute; {-} procedure Cleanup; override; {-} protected // internal properties property Filer: Tl3CustomFiler read f_Filer; {-} public // public methods constructor Create(const aFileName: String); reintroduce; overload; {-} constructor Create(const aStream: IStream); reintroduce; overload; {-} class function Make(const aFileName: String): Il3Reader; reintroduce; overload; {-} class function Make(const aStream: IStream): Il3Reader; reintroduce; overload; {-} end;//Tl3Reader implementation // start class Tl3Reader constructor Tl3Reader.Create(const aFileName: String); //reintroduce; {-} begin inherited Create; f_Filer := Tl3CustomDOSFiler.Make(aFileName, l3_fmRead); end; constructor Tl3Reader.Create(const aStream: IStream); //reintroduce; {-} begin inherited Create; f_Filer := Tl3CustomFiler.Create; f_Filer.COMStream := aStream; end; class function Tl3Reader.Make(const aFileName: String): Il3Reader; //reintroduce; //overload; {-} var l_Writer : Tl3Reader; begin l_Writer := Create(aFileName); try Result := l_Writer; finally l3Free(l_Writer); end;//try..finally end; class function Tl3Reader.Make(const aStream: IStream): Il3Reader; //reintroduce; //overload; {-} var l_Writer : Tl3Reader; begin l_Writer := Create(aStream); try Result := l_Writer; finally l3Free(l_Writer); end;//try..finally end; procedure Tl3Reader.Cleanup; //override; {-} begin l3Free(f_Filer); inherited; end; procedure Tl3Reader.Execute; {-} begin Filer.Open; try DoRead; finally Filer.Close; end;//try..finally end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit Languages; interface uses Classes, TypInfo, QTypes, IniFiles, Forms, ComCtrls, SysUtils; type TMultiLanguages = class(TComponent) private FActiveLanguage: string; FActiveFileName: string; FLanguages: TStrings; FOwner: TComponent; FProperties: TStrings; function GetObjectCaption(obj:TComponent; PropertyName: string): string; function GetTreeNodesCaptions(Nodes: TTreeNodes): string; procedure SetObjectCaption(obj: TComponent; AValue: string; PropertyName: string); procedure SetTreeNodesCaptions(Nodes: TTreeNodes; const CommaText: string); public property ActiveLanguage: string read FActiveLanguage write FActiveLanguage; property Languages: TStrings read FLanguages write FLanguages; procedure SaveObjectList; procedure Translate; procedure Add(LanguageName, FilePath: string); procedure SaveDefault(LanguageName: string); function TranslateSentence(ASentence: string): string; constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; function ChangeSentence(ASentence, Default: string): string; function ReadAllLanguages: TStrings; function ReadDefaultLanguage: String; implementation const FileCommo = '='; function ReadAllLanguages: TStrings; begin result := TStringList.Create; with TIniFile.create(changefileext(paramstr(0),'.ini')) do try ReadSectionValues('Language Files', Result); finally free; end; end; function ReadDefaultLanguage: String; begin with TIniFile.create(changefileext(paramstr(0),'.ini')) do try Result := ReadString('Language Options','DefaultLanguage', 'English'); finally free; end; end; function ChangeSentence(ASentence, Default: string): string; var lng: TMultiLanguages; DefaultLanguage: string; Lnglist: TStrings; begin Lnglist := TStringList.Create; with TIniFile.create(changefileext(paramstr(0),'.ini')) do try DefaultLanguage := ReadString('Language Options','DefaultLanguage', 'English'); ReadSectionValues('Language Files', Lnglist); finally free; end; lng := TMultiLanguages.Create(nil); try lng.ActiveLanguage := DefaultLanguage; lng.Languages := LngList; result := lng.TranslateSentence(ASentence); finally lng.Free; end; if result = '' then result := Default; end; constructor TMultiLanguages.Create(AOwner: TComponent); begin inherited Create(AOwner); FOwner := AOwner; FLanguages := TStringList.Create(); FProperties := TStringList.Create(); FProperties.Add('Caption'); FProperties.Add('Hint'); FProperties.Add('Columns.Caption.Text'); end; destructor TMultiLanguages.Destroy; begin FLanguages.Free(); FProperties.Free(); inherited Destroy(); end; procedure TMultiLanguages.Add(LanguageName, FilePath: string); begin FLanguages.Add(LanguageName+FileCommo+FilePath); with TIniFile.create(changefileext(paramstr(0),'.ini')) do try WriteString('Language Files', LanguageName, FilePath); finally free; end; end; procedure TMultiLanguages.SaveDefault(LanguageName: string); begin with TIniFile.create(changefileext(paramstr(0),'.ini')) do try WriteString('Language Options','DefaultLanguage', LanguageName); finally free; end; end; procedure TMultiLanguages.SaveObjectList; var i,x: integer; aCaption: string; LngIni: TIniFile; formName: string; begin for i := 0 to Languages.Count -1 do begin if pos(FActiveLanguage, Languages.Strings[i])> 0 then FActiveFileName := copy(Languages.Strings[i], Pos(FileCommo, Languages.Strings[i])+1, length(Languages.Strings[i])); end; LngIni := TIniFile.Create(ExtractFilePath(Application.ExeName)+FActiveFileName); if pos('_',TForm(FOwner).Name) > 0 then formName := copy(TForm(FOwner).Name, 1, pos('_',TForm(FOwner).Name) -1) else formName := TForm(FOwner).Name; for i:= 0 to FOwner.ComponentCount -1 do begin for x := 0 to FProperties.Count -1 do begin try aCaption := GetObjectCaption(FOwner.Components[i], FProperties.Strings[x]); except aCaption := ''; end; if aCaption <> '' then LngIni.WriteString(formName, FOwner.Components[i].Name+'.'+FProperties.Strings[x], aCaption); end; end; LngIni.Free; end; function TMultiLanguages.GetObjectCaption(obj: TComponent; PropertyName: string): string; var ptrPropInfo : PPropInfo; CollObj: TStringList; AClass: boolean; PropObjValue: TPersistent; CollPropInfo: PPropInfo; i: integer; begin ptrPropInfo := GetPropInfo(obj.ClassInfo, PropertyName); result := ''; if not Assigned(ptrPropInfo) then Exit; case ptrPropInfo^.PropType^.Kind of tkString, tkLString, tkWString, tkChar, tkWChar: result := GetStrProp(obj, ptrPropInfo); tkClass: begin AClass := False; PropObjValue := TPersistent(GetOrdProp(Obj, ptrPropInfo)); if PropObjValue is TStrings then begin Result := TStrings(PropObjValue).CommaText; AClass := True; end; if PropObjValue is TTreeNodes then begin Result := GetTreeNodesCaptions(TTreeNodes(PropObjValue)); AClass := True; end; if PropObjValue is TCollection then begin AClass := True; CollObj := TStringList.Create; try for i:=0 to TCollection(PropObjValue).Count-1 do begin CollPropInfo := GetPropInfo(TCollection(PropObjValue).Items[i], PropertyName); if not Assigned(CollPropInfo) then Continue; case CollPropInfo^.PropType^.Kind of tkString, tkLString, tkWString, tkChar, tkWChar: CollObj.Add(GetStrProp(TCollection(PropObjValue).Items[i], CollPropInfo)); tkClass: GetPropValue(TCollection(PropObjValue).Items[i], PropertyName) end end; Result := CollObj.CommaText; finally CollObj.Free; end; end; if not AClass then Result := GetPropValue(PropObjValue, PropertyName); end; end; end; function TMultiLanguages.GetTreeNodesCaptions(Nodes: TTreeNodes): string; var I: integer; Captions: TStrings; begin if not Assigned(Nodes) then Exit; Captions := TStringList.Create(); try for I := 0 to Nodes.Count - 1 do Captions.Add(Nodes[I].Text); Result := Captions.CommaText; finally Captions.Free(); end; end; procedure TMultiLanguages.Translate; var i: integer; LngIni: TIniFile; Lnglist: TStrings; PropObj: TComponent; Index: integer; PropName, PropValue, ObjName: string; formName : string; begin for i := 0 to Languages.Count -1 do begin if pos(FActiveLanguage, Languages.Strings[i])> 0 then FActiveFileName := copy(Languages.Strings[i], Pos(FileCommo, Languages.Strings[i])+1, length(Languages.Strings[i])); end; if pos('_',TForm(FOwner).Name) > 0 then formName := copy(TForm(FOwner).Name, 1, pos('_',TForm(FOwner).Name) -1) else formName := TForm(FOwner).Name; LngIni := TIniFile.Create(ExtractFilePath(Application.ExeName)+FActiveFileName); Lnglist := TStringList.Create; LngIni.ReadSectionValues(formName, Lnglist); if Lnglist.Count = 0 then begin SaveObjectList; exit; end; for i:= 0 to Lnglist.Count -1 do begin PropValue := Lnglist.Strings[i]; Index := pos('.', PropValue); if Index = 0 then PropName := PropValue else begin ObjName := Copy(PropValue, 1, Index-1); Delete(PropValue, 1, Index); PropName := Copy(PropValue, 1, pos('=',PropValue)-1 ); Delete(PropValue, 1, pos('=',PropValue)); end; PropObj := FOwner.FindComponent(ObjName); try SetObjectCaption(PropObj, PropValue, PropName); except end; end; LngIni.Free; end; procedure TMultiLanguages.SetObjectCaption(obj: TComponent; AValue: string; PropertyName: string); var CollObj: TCollection; PropInfo: PPropInfo; i: integer; obj1: TObject; isClass: boolean; CollList: TStringList; ColPropInfo: PPropInfo; begin PropInfo := GetPropInfo(obj.ClassInfo, PropertyName); if not Assigned(PropInfo) then Exit; CollObj := nil; Obj1 := Obj; if PropInfo^.PropType^.Kind = tkClass then begin Obj1 := GetObjectProp(Obj1, PropInfo); if Obj1 is TCollection then CollObj := Obj1 as TCollection; end; isClass := False; if (CollObj = nil) then begin if Obj1 is TStrings then begin TStrings(Obj1).CommaText := AValue; isClass := True end; if Obj1 is TTreeNodes then begin isClass := True; SetTreeNodesCaptions(TTreeNodes(Obj1), AValue); end; if not isClass then if (Assigned(PropInfo)) then if (GetStrProp(Obj1, PropInfo) <> '') then SetStrProp(Obj1, PropInfo, AValue) end else begin if CollObj.Count = 0 then Exit; CollList := TStringList.Create; try CollList.CommaText := AValue; for i:=0 to CollObj.Count-1 do begin ColPropInfo := GetPropInfo(CollObj.Items[i], PropertyName); if Assigned(ColPropInfo) and (i < CollList.Count) then if (GetStrProp(CollObj.Items[i], ColPropInfo) <> '') then SetStrProp(CollObj.Items[i], ColPropInfo, CollList[i]); end; finally CollList.Free; end; end; end; procedure TMultiLanguages.SetTreeNodesCaptions(Nodes: TTreeNodes; const CommaText: string); var I: integer; Captions: TStrings; begin if not Assigned(Nodes) then Exit; Captions := TStringList.Create(); try Captions.CommaText := CommaText; Nodes.BeginUpdate(); try for I := 0 to Captions.Count - 1 do if I < Nodes.Count then Nodes.Item[I].Text := Captions[I] else Break; finally Nodes.EndUpdate(); end; finally Captions.Free(); end; end; function TMultiLanguages.TranslateSentence(ASentence: string): string; var i: integer; LngIni: TIniFile; begin for i := 0 to Languages.Count -1 do begin if pos(FActiveLanguage, Languages.Strings[i])> 0 then FActiveFileName := copy(Languages.Strings[i], Pos(FileCommo, Languages.Strings[i])+1, length(Languages.Strings[i])); end; LngIni := TIniFile.Create(ExtractFilePath(Application.ExeName)+FActiveFileName); try result := LngIni.ReadString('Resourcestring', ASentence, ''); finally LngIni.Free; end; end; end.
unit l3LongintListReverseSorter; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "L3" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/L3/l3LongintListReverseSorter.pas" // Начат: 08.06.2011 22:32 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Low Level::L3::Containers::Tl3LongintListReverseSorter // // Пример списка, который сортирует исходный список в обратном порядке // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\L3\l3Define.inc} interface uses l3CustomLongintListView, l3PureMixIns ; type Tl3LongintListReverseSorter = class(Tl3CustomLongintListView) {* Пример списка, который сортирует исходный список в обратном порядке } protected // realized methods function CompareData(const anItem1: _ItemType_; const anItem2: _ItemType_): Integer; override; end;//Tl3LongintListReverseSorter implementation // start class Tl3LongintListReverseSorter function Tl3LongintListReverseSorter.CompareData(const anItem1: _ItemType_; const anItem2: _ItemType_): Integer; //#UC START# *4DEFB2D90167_4DEFC02E01CF_var* //#UC END# *4DEFB2D90167_4DEFC02E01CF_var* begin //#UC START# *4DEFB2D90167_4DEFC02E01CF_impl* Result := (anItem2 - anItem1); //#UC END# *4DEFB2D90167_4DEFC02E01CF_impl* end;//Tl3LongintListReverseSorter.CompareData end.
program listOOP; type listNode = ^listPtr; listPtr = record val : integer; next : listNode; end; list = ^listObj; listObj = OBJECT private startList : listNode; sizeList : integer; public constructor init; procedure add(val : integer); virtual; function contains(val : integer) : boolean; virtual; function size : integer; procedure remove(val : integer); virtual; procedure clear; procedure printList; private procedure removeNextNode(var node : listNode); end; sortedList = ^sortedListObj; sortedListObj = object(listObj) public procedure add(val : integer); virtual; function contains(val : integer) : boolean; virtual; procedure remove(val : integer); virtual; end; constructor listObj.init; begin startList := NIL; sizeList := 0; end; procedure listObj.add(val : integer); var nextList : listNode; buffList : listNode; begin new(nextList); nextList^.val := val; if(size = 0) then startList := nextList else begin buffList := startList; while(buffList <> NIL) and (buffList^.next <> NIL) do buffList := buffList^.next; buffList^.next := nextList; end; inc(sizeList); end; function listObj.contains(val : integer) : boolean; var curList : listNode; finished : boolean; begin contains := FALSE; finished := FALSE; curList := startList; while(NOT finished) do begin if(curList^.val = val) then begin contains := TRUE; finished := TRUE; end else begin if(curList^.next = NIL) then begin finished := TRUE; end else begin curList := curList^.next; end; end; end; end; function listObj.size : integer; var tSize : integer; buffList : listNode; begin buffList := startList; tSize := 0; while(buffList <> NIL) do begin inc(tSize); buffList := buffList^.next; end; size := tSize; end; procedure listObj.remove(val : integer); var buffList : listNode; begin if(size = 0) then begin writeLn('Cannot remove from empty list'); exit; end; buffList := startList; while(buffList^.next <> NIL) do begin if(buffList^.next^.val = val) then begin removeNextNode(buffList); end else buffList := buffList^.next; end; if(startList^.val = val) then begin buffList := startList^.next; dispose(startList); dec(sizeList); startList := buffList; end; end; procedure listObj.clear; var buffList : listNode; begin buffList := startList; while(buffList^.next <> NIL) do begin removeNextNode(buffList); end; dispose(startList); sizeList := 0; startList := NIL; end; procedure listObj.removeNextNode(var node : listNode); var buffList : listNode; begin buffList := node^.next^.next; dispose(node^.next); node^.next := buffList; dec(sizeList); end; procedure listObj.printList; var buffList : listNode; begin buffList := startList; while(buffList <> NIL) do begin writeLn(buffList^.val); buffList := buffList^.next; end; end; procedure sortedListObj.add(val : integer); var nextList : listNode; buffList : listNode; finished : boolean; begin finished := FALSE; new(nextList); nextList^.val := val; if(size = 0) then startList := nextList else if startList^.val >= nextList^.val then begin nextList^.next := startList; startList := nextList; end else begin buffList := startList; while(buffList <> NIL) and (buffList^.next <> NIL) and (NOT finished) do begin if(buffList^.next^.val >= val) then begin nextList^.next := buffList^.next; finished := TRUE; end else buffList := buffList^.next; end; buffList^.next := nextList; end; inc(sizeList); end; function sortedListObj.contains(val : integer) : boolean; var curList : listNode; finished : boolean; begin contains := FALSE; finished := FALSE; curList := startList; while(NOT finished) do begin if(curList^.val = val) then begin contains := TRUE; finished := TRUE; end else begin if(curList^.next = NIL) or (curList^.val < val) then begin finished := TRUE; end else begin curList := curList^.next; end; end; end; end; procedure sortedListObj.remove(val : integer); var buffList : listNode; finished : boolean; begin finished := FALSE; if(size = 0) then begin writeLn('Cannot remove from empty list'); exit; end; buffList := startList; while(buffList^.next <> NIL) and (NOT finished) do begin if(buffList^.next^.val = val) then begin removeNextNode(buffList); end else buffList := buffList^.next; if(buffList^.val > val) then finished := TRUE; end; if(startList^.val = val) then begin buffList := startList^.next; dispose(startList); dec(sizeList); startList := buffList; end; end; var tList : sortedList; i : integer; begin new(tList, init); tList^.add(3); tList^.add(3); tList^.add(3); tList^.add(2); tList^.add(2); tList^.add(2); tList^.add(3); writeLn('Size: ', tList^.size); tList^.printList; tList^.remove(3); writeLn('Size: ', tList^.size); tList^.clear; end.
unit UnitFTP; interface uses Windows, Messages, SysUtils, Variants, Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdFTP, ExtCtrls, Controls, IdFTPList, StdCtrls, Classes, forms, IdGlobal{, IdExplicitTLSClientServerBase}; type TForm2 = class(TForm) IdFTP1: TIdFTP; procedure FormDestroy(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; type T_Connection= Record _Host : string;//'ftp.turstolica.by'; _Username :string;//= 'givojno1'; _Password :string;//= 'xdEW5QA1'; _Port : integer;//= 21; end;{T_Connection} Procedure _InitConnectFtp(__HOST,__NAME, __PASSWORD : ansistring;__ftpPort : integer; var _ConnectFtp : T_Connection); procedure ConnectToFTP(IdFtp1 : Tidftp;_d : T_Connection;_Memo : Tmemo); procedure DisconnectFTP(IdFTP1 : TIdFtp; _Memo : Tmemo); procedure CopyFtpFile(IdFTP1 : TIdFTP; _Memo : Tmemo; _source, _destin : string); procedure PutFtpFile(IdFTP1 : TIdFTP; _Memo : Tmemo; _source, _destin : string); procedure ReadFTPDirToStrings(IdFtp1 : Tidftp; _Memo : Tmemo; MyStringList : Tstrings); procedure ChangeFtpDir(IdFTP1 : TIdFTP; __strs : ansistring; _Memo : Tmemo); procedure RenameFtpFile(IdFTP1 : TIdFTP; _Memo : Tmemo; _source, _destin : string); var Form2: TForm2; _ConnectFtp : T_Connection; implementation {$R *.dfm} Procedure _InitConnectFtp(__HOST,__NAME, __PASSWORD : ansistring;__ftpPort : integer; var _ConnectFtp : T_Connection); begin with _ConnectFtp do begin _Host := __HOST;//'192.168.150.2'; _Username :=__NAME;//'tep' {'givojno1'}; _Password :=__PASSWORD;//'tep'{'xdEW5QA1'}; _Port := __ftpPort;//21; end;{_ConnectFtp} end;{_InitConnectFtp} procedure ConnectToFTP(IdFtp1 : Tidftp;_d : T_Connection;_Memo : Tmemo); begin IdFTP1.Host := _d._Host; IdFTP1.Username :=_d._Username; IdFTP1.Password :=_d._Password;; IdFTP1.Port :=_d._Port; // IdFTP1.PassiveUseControlHost := True; IdFTP1.Passive := True; ///обязательно try IdFTP1.Connect; if _Memo<> Nil then _Memo.Lines.Add('Присоединились к порту ' + IdFTP1.Host); except if _Memo<> Nil then _Memo.Lines.Add('Ошибка соединения с портом ' + IdFTP1.Host); end; // IdFTP1.ChangeDir('www'); // IdFTP1.ChangeDir('turstolica.by'); // IdFTP1.ChangeDir('tep'); end; procedure DisconnectFTP(IdFTP1 : TIdFtp; _Memo : Tmemo); begin if Assigned(IdFTP1) then begin Sleep(500); IdFTP1.Disconnect; if _Memo<> Nil then _Memo.Lines.Add('Отключились от порта ' + IdFTP1.Host); end; end; procedure ReadFTPDirToStrings(IdFtp1 : Tidftp; _Memo : Tmemo; MyStringList : Tstrings); var i:integer; Afiles : TstringList; begin AFiles := TStringList.Create; IdFTP1.List(AFiles, '', True); if _Memo<>Nil then _Memo.Lines.Add('Прочитали список фалов с сайта'); if MyStringList=Nil then Exit; MyStringList.Clear; for i:=0 to AFiles.Count-1 do MyStringList.Add(AFiles.Strings[i]); Afiles.Destroy; sleep(500); (* for i:=0 to idFTP1.DirectoryListing.Count-1 do MyStringList.Add(idFTP1.DirectoryListing.Items[i].FileName); *) end; procedure ReadFtpDirectory(IdFTP1 : TIdFTP; _Memo : Tmemo; Listbox1 : Tlistbox); var i:integer; Afiles : TstringList; begin AFiles := TStringList.Create; IdFTP1.List(AFiles, '', True); Afiles.Destroy; if _Memo<>Nil then _Memo.Lines.Add('Прочитали список фалов с сайта'); if ListBox1=Nil then Exit; ListBox1.Items.Clear; for i:=0 to idFTP1.DirectoryListing.Count-1 do ListBox1.Items.Add(idFTP1.DirectoryListing.Items[i].FileName); end; procedure CopyFtpFile(IdFTP1 : TIdFTP; _Memo : Tmemo; _source, _destin : string); var filePath, dir, serverName, pageName: string; begin dir := IDFTP1.RetrieveCurrentDir; if IdFTP1.Connected then begin filePath := _destin; pageName := _source; DeleteFile(filePath); IdFTP1.Get(pageName, filePath, False); serverName := dir + '/' + pageName; if _Memo<> Nil then _Memo.Lines.Add('Файл ' + serverName + ' успешно скопирован из сервера по адресу ' + filePath); end; end;{CopyFtpFile} procedure PutFtpFile(IdFTP1 : TIdFTP; _Memo : Tmemo; _source, _destin : string); var filePath, dir, serverName, pageName: string; begin dir := IDFTP1.RetrieveCurrentDir; if IdFTP1.Connected then begin filePath := _source; pageName := _destin; IdFTP1.Put(filePath, pageName, False); serverName := dir + '/' + filePath; if _Memo<> Nil then _Memo.Lines.Add('Файл ' + serverName + ' успешно скопирован на сервер по адресу ' + filePath); end; end;{PutftpFile} procedure RenameFtpFile(IdFTP1 : TIdFTP; _Memo : Tmemo; _source, _destin : string); var filePath, dir, serverName, pageName: string; begin dir := IDFTP1.RetrieveCurrentDir; if IdFTP1.Connected then begin filePath := _source; pageName := _destin; IdFTP1.Rename(filePath, pageName); serverName := dir + '/' + filePath; if _Memo<> Nil then _Memo.Lines.Add('Файл ' + serverName + ' успешно переименован в ' + filePath); end; end;{RenameftpFile} procedure ChangeFtpDir(IdFTP1 : TIdFTP; __strs : ansistring; _Memo : Tmemo); begin Try if IdFTP1.Connected then begin IdFTP1.ChangeDir(__strs); if _Memo<>Nil then _Memo.Lines.Add('Сменили директорий'); end;{if} Except end;{Try .. Except} end; (* procedure TForm1.Button7Click(Sender: TObject); begin if OpenDialog1.Execute then DiskFileEdit.Text := OpenDialog1.FileName; end; procedure TForm1.Button8Click(Sender: TObject); begin PageNameEdit.Text := ExtractFileName(DiskFileEdit.Text); end; procedure TForm1.Button3Click(Sender: TObject); var filePath, dir, serverName, pageName: string; begin // ConnectToFTP(IdFtp1,_ConnectFtp,Memo1); try dir := IDFTP1.RetrieveCurrentDir; if IdFTP1.Connected then begin filePath := DiskFileEdit.Text; pageName := PageNameEdit.Text; IdFTP1.Put(filePath, pageName, False); serverName := dir + '/' + pageName; Memo1.Lines.Add('Файл ' + filePath + ' успешно скопирован на сервер по адресу ' + serverName); end; except end; // DisconnectFTP(IdFtp1,Memo1); end; procedure TForm1.ListBox1DblClick(Sender: TObject); var __strs : ansistring; i : integer; begin with Sender as Tlistbox do begin if itemindex<0 then Exit; __strs:=items[itemindex]; for i:=0 to idFTP1.DirectoryListing.Count-1 do if __strs=(idFTP1.DirectoryListing.Items[i].FileName) then if not (ditDirectory in [idFTP1.DirectoryListing.Items[i].ItemType]) then Exit; Try if IdFTP1.Connected then begin IdFTP1.ChangeDir(__strs); ReadFtpDirectory(IDFTP1, Memo1, Sender as Tlistbox); end;{if} Except end;{Try .. Except} end;{if} end; procedure TForm1.BmkdirClick(Sender: TObject); begin IDFTP1.MakeDir(Eddirname.text); ReadFtpDirectory(IDFTP1, Memo1, listbox1); end; procedure TForm1.Button1Click(Sender: TObject); var __strs, __strd : ansistring; begin with Listbox1 do begin if itemindex<0 then Exit; __strs:=items[itemindex]; if __strs='' then Exit; if not SaveDialog1.Execute then Exit; __strd := SaveDialog1.filename; Try CopyFtpFile(IdFTP1, Memo1, __strs, __strd); ReadFtpDirectory(IDFTP1, Memo1, Listbox1); Except end;{Try .. Except} end;{if} end; procedure TForm1.Button2Click(Sender: TObject); var __strs : ansistring; dir, serverName, pageName: string; i : integer; flag_dir : Boolean; begin with Listbox1 do begin if itemindex<0 then Exit; __strs:=items[itemindex]; if __strs='' then Exit; flag_dir:=True; for i:=0 to idFTP1.DirectoryListing.Count-1 do if __strs=(idFTP1.DirectoryListing.Items[i].FileName) then if not (ditDirectory in [idFTP1.DirectoryListing.Items[i].ItemType]) then Flag_dir:=False; Try dir := IDFTP1.RetrieveCurrentDir; if IdFTP1.Connected then begin pageName := __strs; if flag_dir then IdFTP1.RemoveDir(pageName) else IdFTP1.Delete(pageName); serverName := dir + '/' + pageName; Memo1.Lines.Add('Файл ' + serverName + ' успешно удален.'); ReadFtpDirectory(IDFTP1, Memo1, Listbox1); end; Except end;{Try .. Except} end;{if} end; *) procedure TForm2.FormCreate(Sender: TObject); begin // SaveDialog1.InitialDir:=ExtractFilePath(Application.exename); // OpenDialog1.InitialDir:=ExtractFilePath(Application.exename); (* _InitConnectFtp(_ConnectFtp); ConnectToFTP(IdFtp1,_ConnectFtp,NIL{Memo1}); ReadFtpDirectory(IDFTP1, NIL, NIL{Listbox1}); DisconnectFTP(IdFtp1,NIL); *) end; (* procedure TForm1.Button4Click(Sender: TObject); begin ReadFtpDirectory(IDFTP1, Memo1, Listbox1); end; *) procedure TForm2.FormDestroy(Sender: TObject); begin DisconnectFTP(IdFtp1,NIL); end; end.
unit ChromeLikeTabSetControlRes; // Модуль: "w:\common\components\gui\Garant\ChromeLikeControls\ChromeLikeTabSetControlRes.pas" // Стереотип: "UtilityPack" // Элемент модели: "ChromeLikeTabSetControlRes" MUID: (553E255C00B2) interface {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3IntfUses , l3StringIDEx ; const {* Локализуемые строки ChromeLikeTabSetControllConst } str_NewTab: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'NewTab'; rValue : 'Новая вкладка'); {* 'Новая вкладка' } str_MakeClone: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'MakeClone'; rValue : 'Дублировать'); {* 'Дублировать' } str_CloseTab: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'CloseTab'; rValue : 'Закрыть вкладку'); {* 'Закрыть вкладку' } str_CloseOtherTabs: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'CloseOtherTabs'; rValue : 'Закрыть другие вкладки'); {* 'Закрыть другие вкладки' } str_CloseRightTabs: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'CloseRightTabs'; rValue : 'Закрыть вкладки справа'); {* 'Закрыть вкладки справа' } str_ReopenClosedTab: Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'ReopenClosedTab'; rValue : 'Открыть закрытую вкладку'); {* 'Открыть закрытую вкладку' } {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) implementation {$If NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs)} uses l3ImplUses //#UC START# *553E255C00B2impl_uses* //#UC END# *553E255C00B2impl_uses* ; initialization str_NewTab.Init; {* Инициализация str_NewTab } str_MakeClone.Init; {* Инициализация str_MakeClone } str_CloseTab.Init; {* Инициализация str_CloseTab } str_CloseOtherTabs.Init; {* Инициализация str_CloseOtherTabs } str_CloseRightTabs.Init; {* Инициализация str_CloseRightTabs } str_ReopenClosedTab.Init; {* Инициализация str_ReopenClosedTab } {$IfEnd} // NOT Defined(NoVGScene) AND NOT Defined(NoVCM) AND NOT Defined(NoTabs) end.
PROGRAM Decryption(INPUT, OUTPUT); {Переводит символы из INPUT в код согласно Chiper и печатает новые символы в OUTPUT} CONST Len = 20; TYPE Str = ARRAY [1 .. Len] OF ' ' .. 'Z'; Chiper = ARRAY [' ' .. 'Z'] OF CHAR; CharSet = SET OF CHAR; VAR Msg: Str; Code: Chiper; I: INTEGER; Length: 0..Len; ChiperFile: TEXT; AvailableSet: CharSet; ErrorFlag, LengthFlag: BOOLEAN; PROCEDURE Initialize(VAR Code: Chiper; VAR Chip: TEXT; VAR AvSet: CharSet; VAR Error: BOOLEAN); {Присвоить Code шифр замены} VAR Ch1, Ch2, Ch3: CHAR; BEGIN {Initialize} RESET(Chip); Ch1 := ''; Ch2 := ''; Ch3 := ''; READ(Chip, Ch1); WHILE NOT EOF(Chip) DO BEGIN IF Ch2 = '=' THEN BEGIN IF Ch1 = ' ' THEN Error := TRUE; Code[Ch3] := Ch1; AvSet := AvSet + [Ch1] END; Ch3 := Ch2; Ch2 := Ch1; READ(Chip, Ch1) END END; {Initialize} PROCEDURE Decode(VAR S: Str; VAR FullSet: CharSet); VAR Index: 1 .. Len; I: CHAR; BEGIN {Encode} FOR Index := 1 TO Len DO BEGIN IF NOT (S[Index] IN FullSet) THEN WRITE(S[Index]) ELSE FOR I:= ' ' TO 'Z' DO BEGIN IF S[Index] = Code[I] THEN WRITE(I) END END; WRITELN END; {Encode} BEGIN {Encryption} ErrorFlag := FALSE; LengthFlag := FALSE; AvailableSet:= []; ASSIGN(ChiperFile, 'code.txt'); Initialize(Code, ChiperFile, AvailableSet, ErrorFlag); IF NOT ErrorFlag THEN WHILE NOT EOF DO BEGIN I := 0; WHILE NOT EOLN AND (I < Len) DO BEGIN I := I + 1; Length := I; READ(Msg[I]) END; READLN; IF (I > 0) THEN Decode(Msg, AvailableSet) END ELSE WRITE('error'); READLN END. {Encryption}
unit OSUtils; {$mode objfpc}{$H+} interface uses Classes, SysUtils; type TOSFamily = (F_WINDOWS, F_LINUX, F_MAC, F_UNKNOWN); const // TODO add preprocessor PATH_SEPARATOR = '/'; OS_FAMILY = F_LINUX; function IsAbsolutePath(Path : String) : Boolean; function GetAbsolutePath(Path : String) : String; implementation function IsAbsolutePath(Path: String): Boolean; const ALPHA_CHARS = ['A'..'Z', 'a'..'z']; begin case OS_FAMILY of F_LINUX, F_MAC: Result := Path[1] = '/'; F_WINDOWS: begin if (Length(Path) >=3) then Result := (Path[1] in ALPHA_CHARS) and (Path[2] = ':') and (Path[3] = PATH_SEPARATOR) else Result := False; end else Result := False; end; end; function GetAbsolutePath(Path: String): String; begin if (not IsAbsolutePath(Path)) then Result := GetCurrentDir() + PATH_SEPARATOR + Path else Result := Path; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.6 11/29/2004 2:45:28 AM JPMugaas Support for DOS attributes (Read-Only, Archive, System, and Hidden) for use by the Distinct32, OS/2, and Chameleon FTP list parsers. Rev 1.5 10/26/2004 9:51:16 PM JPMugaas Updated refs. Rev 1.4 4/19/2004 5:05:46 PM JPMugaas Class rework Kudzu wanted. Rev 1.3 2004.02.03 5:45:28 PM czhower Name changes Rev 1.2 10/19/2003 3:36:14 PM DSiders Added localization comments. Rev 1.1 10/1/2003 05:27:36 PM JPMugaas Reworked OS/2 FTP List parser for Indy. The aprser wasn't detecting OS/2 in some more samples I was able to get ahold of. Rev 1.0 2/19/2003 05:50:28 PM JPMugaas Parsers ported from old framework. } unit IdFTPListParseOS2; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; { This parser is based on some data that I had managed to obtain second hand from what people posted on the newsgroups. } type TIdOS2FTPListItem = class(TIdDOSBaseFTPListItem); TIdFTPLPOS2 = class(TIdFTPLPBaseDOS) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; public class function GetIdent : String; override; class function CheckListing(AListing : TStrings; const ASysDescript : String = ''; const ADetails : Boolean = True): Boolean; override; end; const OS2PARSER = 'OS/2'; {do not localize} // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseOS2"'*) implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, SysUtils; { TIdFTPLPOS2 } class function TIdFTPLPOS2.CheckListing(AListing: TStrings; const ASysDescript: String; const ADetails: Boolean): Boolean; var LBuf, LBuf2 : String; LNum : String; begin { " 73098 A 04-06-97 15:15 ds0.internic.net1996052434624.txt" " 0 DIR 12-11-95 13:55 z" or maybe this: taken from the FileZilla source-code comments " 0 DIR 05-12-97 16:44 PSFONTS" "36611 A 04-23-103 10:57 OS2 test1.file" " 1123 A 07-14-99 12:37 OS2 test2.file" " 0 DIR 02-11-103 16:15 OS2 test1.dir" " 1123 DIR A 10-05-100 23:38 OS2 test2.dir" } Result := False; if AListing.Count > 0 then begin LBuf := TrimLeft(AListing[0]); LNum := Fetch(LBuf); if not IsNumeric(LNum) then begin Exit; end; repeat LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); if LBuf2 = 'DIR' then {do not localize} begin LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); end; if IsMMDDYY(LBuf2, '-') then begin //we found a date Break; end; if not IsValidAttr(LBuf2) then begin Exit; end; until False; //there must be two spaces between the date and time if not TextStartsWith(LBuf, ' ') then begin {do not localize} Exit; end; if (Length(LBuf) >= 3) and (LBuf[3] = ' ') then begin {do not localize} Exit; end; LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); Result := IsHHMMSS(LBuf2, ':'); end; end; class function TIdFTPLPOS2.GetIdent: String; begin Result := OS2PARSER; end; class function TIdFTPLPOS2.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdOS2FTPListItem.Create(AOwner); end; class function TIdFTPLPOS2.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LBuf, lBuf2, LNum : String; LOSItem : TIdOS2FTPListItem; begin { Assume layout such as: 0 DIR 02-18-94 19:47 BC 79836 A 11-19-96 19:08 w.txt 12345678901234567890123456789012345678901234567890123456789012345678 1 2 3 4 5 6 } Result := False; LBuf := AItem.Data; LBuf := TrimLeft(LBuf); LNum := Fetch(LBuf); AItem.Size := IndyStrToInt64(LNum, 0); LOSItem := AItem as TIdOS2FTPListItem; repeat //keep going until we find a date LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); if LNum = '0' then begin if LBuf2 = 'DIR' then {do not localize} begin LOSItem.ItemType := ditDirectory; LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); end; end; if IsMMDDYY(LBuf2, '-') then begin //we found a date LOSItem.ModifiedDate := DateMMDDYY(LBuf2); Break; end; LOSItem.Attributes.AddAttribute(LBuf2); if LBuf = '' then begin Exit; end; until False; //time LBuf := TrimLeft(LBuf); LBuf2 := Fetch(LBuf); if IsHHMMSS(LBuf2, ':') then begin {do not localize} LOSItem.ModifiedDate := LOSItem.ModifiedDate + TimeHHMMSS(LBuf2); end; //fetch removes one space. We ned to remove an additional one //before the filename as a filename might start with a space Delete(LBuf, 1, 1); LOSItem.FileName := LBuf; Result := True; end; initialization RegisterFTPListParser(TIdFTPLPOS2); finalization UnRegisterFTPListParser(TIdFTPLPOS2); end.
unit BigDataUtils; interface type BigData=Record class var DefaultPrec : Cardinal; var Positive : integer; Power : integer; Precise : Cardinal; DATA : TArray<Cardinal>; class constructor InitBigData; constructor Create(Prec : Cardinal); procedure TrimData; function ToString: String; overload; class operator Implicit(a: Int64): BigData; class operator Explicit(a: BigData): int64; class operator Implicit(a: UInt64): BigData; class operator Explicit(a: BigData): Uint64; class operator Implicit(a: Double): BigData; class operator Explicit(a: BigData): Double; class operator Explicit(a: String): BigData; End; implementation uses Generics.Collections, System.SysUtils, Math; resourcestring StrBigDataTooBig = 'BigData is too big for assigned'; StrNegToUnSigned = 'Assigning a Negative Value to an Unsigned Variable'; StrBadNumberFormat = 'Bad Number Format'; function Div64_9(var a :UInt64):Cardinal; inline; begin {$IFDEF CPU64BITS} Result := a div 1000000000; a := a-Result*1000000000; {$ELSE} var d : Cardinal; var c : Uint64; Result := 0; c := 1000000000 shl 29; d := 1 shl 29; while a>=1000000000 do begin if a>=c then begin a := a-c; Result := Result+d; end; c := c shr 1; d := d shr 1; end; {$ENDIF} end; function Div64_2(var a :UInt64):Cardinal; inline; begin {$IFDEF CPU64BITS} Result := a div 1000000000000000000; a := a-Result*1000000000000000000; {$ELSE} var d : Cardinal; var c : Uint64; Result := 0; c := UInt64(1000000000000000000) shl 4; d := 1 shl 4; while a>=1000000000000000000 do begin if a>=c then begin a := a-c; Result := Result+d; end; c := c shr 1; d := d shr 1; end; {$ENDIF} end; function Div64_1(var a :UInt64):Cardinal; inline; begin {$IFDEF CPU64BITS} Result := a div 1000000000; a := a-Result*1000000000; {$ELSE} var d : Cardinal; var c : Uint64; Result := 0; c := UInt64(1000000000) shl 3; d := 1 shl 3; while a>=1000000000 do begin if a>=c then begin a := a-c; Result := Result+d; end; c := c shr 1; d := d shr 1; end; {$ENDIF} end; { BigData } constructor BigData.Create(Prec: Cardinal); begin Precise := Prec; Positive := 0; Data := nil; end; class operator BigData.Implicit(a: UInt64): BigData; var b : UInt64; c : Cardinal; begin if a=0 then begin Result.Positive := 0; exit; end; Result.Positive := 1; if a<1000000000 then begin SetLength(Result.DATA,1); Result.Power := 1; Result.DATA[0] := a; end else if a<1000000000000000000 then begin b := Div64_9(a); SetLength(Result.DATA,2); Result.Power := 2; Result.DATA[0] := b; Result.DATA[1] := a; end else begin c := Div64_2(a); b := Div64_9(a); SetLength(Result.DATA,3); Result.Power := 3; Result.DATA[0] := c; Result.DATA[1] := b; Result.DATA[2] := a; end; end; class operator BigData.Explicit(a: String): BigData; var c : char; e,ep,dp,i,j,st,ed : integer; begin a := a.Replace(',',''); a := UpperCase(a); st := 0; if a.Chars[0]='-' then begin Result.Positive := -1; st := 1; end else begin Result.Positive := 1; if a.Chars[0]='+' then st := 1; end; ed := a.Length; ep := a.IndexOf('E'); if ep>-1 then begin if not TryStrToInt(a.Substring(ep+1),e) then raise Exception.Create(StrBadNumberFormat); ed := ep; end else e := 0; while (st<ed)and(a.Chars[st]='0') do inc(st); if st=ed then begin Result.Positive := 0; exit; end; dp := a.IndexOf('.',st); if dp=-1 then dp := ed; for j := st to dp-1 do if not(a.Chars[j] in ['0'..'9']) then raise Exception.Create(StrBadNumberFormat); while (dp<ed-1)and(a.Chars[ed-1]='0') do dec(ed); if dp=ed-1 then ed := dp; if st=ed then begin Result.Positive := 0; exit; end; for j := dp+1 to ed-1 do if not(a.Chars[j] in ['0'..'9']) then raise Exception.Create(StrBadNumberFormat); if st=dp then while (st<ed)and(a.Chars[st+1]='0') do inc(st); e := e+dp-st-1; if e<0 then Result.Power := (e+1) div 9 -1 else Result.Power := e div 9; dp := st+1+e-Result.Power*9; if dp<0 then begin a := a.PadLeft(a.Length-dp,'0'); dp := 0; end else if dp>a.Length then a := a.PadRight(dp,'0'); i := dp mod 9; SetLength(Result.DATA,(a.Length-i+8) div 9+ord(i>0)); a:= a.PadRight((a.Length-i+8)div 9 * 9+i,'0'); if i>0 then begin Result.DATA[0] := StrToUint(a.Substring(0,i)); j:=1; end else j := 0; while i<a.Length do begin Result.DATA[j] := StrToUint(a.Substring(i,9)); inc(j); inc(i,9); end; Result.TrimData; end; class operator BigData.Implicit(a: Double): BigData; begin if a=0 then begin Result.Positive := 0; exit; end else if a<0 then begin Result.Positive := -1; a := -a; end else Result.Positive := 1; Result.Power := Floor(ln(a)/ln(1000000000))+1; a := Power10(a,-(Result.Power-1)*9); SetLength(Result.DATA,3); Result.Data[0] := trunc(a); a := (a-Result.DATA[0])*1000000000; Result.DATA[1] := trunc(a); a := (a-Result.DATA[1])*1000000000; Result.DATA[2] := trunc(a); Result.TrimData; end; class constructor BigData.InitBigData; begin DefaultPrec := 4; end; function BigData.ToString: String; var S : TStringBuilder; i,j : integer; begin if Positive=0 then exit('0'); S := TStringBuilder.Create; if Positive<0 then S.Append('-'); i := 0; if Power>0 then begin S.Append(Data[0]); i := 1; while (i<Power)and(i<Length(Data)) do begin S.Append(Data[i].ToString.PadLeft(9,'0')); inc(i); end; while i<Power do begin S.Append('000000000'); inc(i); end; end else begin S.Append('0'); end; if i<Length(Data) then S.Append('.'); if Power<0 then begin i := Power; while i<0 do begin S.Append('000000000'); inc(i); end; end; while i<Length(data)-1 do begin S.Append(Data[i].ToString.PadLeft(9,'0')); inc(i); end; if i>=Power then begin j := Data[i]; while j Mod 10 = 0 do J := j div 10; S.Append(J.ToString); end; Result:= S.ToString; end; procedure BigData.TrimData; var i : Cardinal; j : integer; begin if Length(Data)=0 then begin Positive := 0; exit; end; i := 0; while (i<Length(Data))and(Data[i]=0) do inc(i); if i=Length(data) then begin Data := nil; Positive := 0; end else if i>0 then begin Move(Data[i],Data[0],SizeOf(Cardinal)*(Length(Data)-i)); Power := Power -i; end; j := Length(Data)-1-i; while (j>0)and(Data[j]=0) do dec(j); SetLength(Data,j+1); end; class operator BigData.Explicit(a: BigData): int64; var i : integer; j : UInt64; begin i := a.Positive; try if i=-1 then a.Positive := 1; J := UInt64(a); if ((i=-1)and(J>$8000000000000000))or((i=1)and(J>$7fffffffffffffff)) then raise Exception.Create(StrBigDataTooBig); Result := i*J; finally a.Positive := i; end; end; class operator BigData.Implicit(a: Int64): BigData; var c : UInt64; begin if a<0 then begin c := -a; Result := c; Result.Positive := -1 end else begin c := a; Result := c; end; end; class operator BigData.Explicit(a: BigData): Uint64; const c1 = High(UInt64) div 1000000000000000000; c2 = (High(UInt64) mod 1000000000000000000) div 1000000000; c3 = High(UInt64) mod 1000000000; var c : Cardinal; begin if a.Positive<0 then raise Exception.Create(StrNegToUnSigned); if (a.Positive=0)or(a.Power<1) then exit(0); if a.Power>3 then raise Exception.Create(StrBigDataTooBig); if a.Power=1 then exit(a.DATA[0]); if a.Power=2 then exit(a.DATA[0]*1000000000+a.DATA[1]); if a.DATA[0]>c1 then raise Exception.Create(StrBigDataTooBig); if a.DATA[0]=c1 then begin if a.DATA[1]>c2 then raise Exception.Create(StrBigDataTooBig); if (a.DATA[1]=c2)and(a.DATA[2]>c3) then raise Exception.Create(StrBigDataTooBig); end; Result:=a.DATA[0]*1000000000000000000+a.DATA[1]*1000000000+a.DATA[2] end; class operator BigData.Explicit(a: BigData): Double; var i,j : integer; d : double; begin if a.Positive=0 then exit(0.0); i := 3; if i>Length(a.DATA) then i := Length(a.DATA); j := i-1; d := 1; Result := 0; repeat Result := Result+a.DATA[j]*d; d := d*1000000000; dec(j); until (j<0); Result := a.Positive*Power10(Result,(a.Power-i)*9); end; end.
unit Modbus; interface uses Constants, ProtocolCommon, DateUtils, System.SysUtils, IdGlobal; type TOrionDataBuf = array[0..251] of Byte; type TOrionPacket = packed record Adres : Uint8; Func : Uint8; DataBuf : TOrionDataBuf; CRC : UInt16; end; type TOrionSetTimePacket = packed record Adres : Uint8; Func : Uint8; RegNum : Uint16; CntReg : Uint16; CntByte : Uint8; Hours : Uint8; Minutes : Uint8; Seconds : Uint8; Day : Uint8; Month : Uint8; Year : Uint8; CRC : UInt16; end; type TOrionTimePacket = packed record Adres : Uint8; Func : Uint8; CntByte : Uint8; Hours : Uint8; Minutes : Uint8; Seconds : Uint8; Day : Uint8; Month : Uint8; Year : Uint8; CRC : UInt16; end; type TTrainPP = class(TObject) ZoneID : integer; PpkID : integer; NumModbus : word; AdresPPK : word; NumTrain : word; NumPart : byte; ZoneType : byte; end; type TRelayPP = class(TObject) RelayID : integer; PpkID : integer; NumModbus : word; AdresPPK : word; NumRelay : word; end; type TKeyPP = class(TObject) NumModbus : word; KeyCode : int64; end; type TS2000_PP = class(TObject) ID : integer; PARID : integer; DEV_CLASS : byte; NAME : string; MODE : byte; ADRES_MODBUS : word; ADRES_ORION : word; ADRES_PP : word; Trains : array of TTrainPP; Relays : array of TRelayPP; Keys : array of TKeyPP; function GetOrionSetTimePacket: TBuf15; function DecodeOrionPacket: boolean; end; const READ_COIL_STATUS = 1; //Чтение значений из нескольких регистров флагов READ_HOLD_REGS = 3; //Чтение значений из нескольких регистров хранения FORCE_SINGLE_COIL = 5; //Запись значения одного флага SET_SINGLE_REG = 6; //Запись значения в один регистр хранения FORCE_MULIPLE_COILS = 15; //Запись значений в несколько регистров флагов SET_MULTIPLE_REGS = 16; //Запись значений в несколько регистров хранения REG_TIME = 46165; P_16 = $A001; var Protos : array of TS2000_PP; Crc_tab16 :array[0..255] of word; implementation uses PublicUtils, Service, Global; procedure init_crc16_tab; var i,j,crc,c:word; begin for i:=0 to 255 do begin crc:=0; c:=i; for j:=0 to 7 do begin if (crc xor c) and 1=1 then crc:=(crc shr 1) xor P_16 else crc:=crc shr 1; c:=c shr 1; end; crc_tab16[i]:=crc; end; end; function update_crc_16(crc,c:word):word; var tmp, short_c:word; begin tmp:=crc xor c; crc:=(crc shr 8) xor crc_tab16[tmp and $ff]; Result:=crc; end; function CRC16(buf:pointer; size:word):word; var i,crc_16_modbus:word; begin init_crc16_tab; crc_16_modbus:=$ffff; for i:=0 to size-1 do crc_16_modbus:=update_crc_16(crc_16_modbus,pbytearray(buf)^[i]); Result:=crc_16_modbus; end; function TS2000_PP.GetOrionSetTimePacket: TBuf15; var Rec: TOrionSetTimePacket; AYear, AMonth, ADay, AHour, AMin, ASec, AMSec: Word; Bytes: TIdBytes; begin DecodeDateTime(Now, AYear, AMonth, ADay, AHour, AMin, ASec, AMSec); Rec.Adres := ADRES_MODBUS; Rec.Func := SET_MULTIPLE_REGS; Rec.RegNum := Swap(REG_TIME); Rec.CntReg := 3; Rec.CntByte := 6; Rec.Hours := AHour; Rec.Minutes := AMin; Rec.Seconds := ASec; Rec.Day := ADay; Rec.Month := AMonth - 2000; Rec.Year := AYear; // 00 10 55 B4 03 00 06 17 03 25 0B 3C E3 F9 C0 Bytes := RawToBytes(Rec, SizeOf(Rec)); Rec.CRC := Swap(CRC16(@Bytes, SizeOf(Rec) - 2)); Bytes := RawToBytes(Rec, SizeOf(Rec)); LogOut(BytesToHex(Bytes, ' ')); end; function TS2000_PP.DecodeOrionPacket: boolean; var Rec: TOrionSetTimePacket; AYear, AMonth, ADay, AHour, AMin, ASec, AMSec: Word; Bytes: TIdBytes; begin DecodeDateTime(Now, AYear, AMonth, ADay, AHour, AMin, ASec, AMSec); Rec.Adres := ADRES_MODBUS; Rec.Func := SET_MULTIPLE_REGS; Rec.RegNum := Swap(REG_TIME); Rec.CntReg := 3; Rec.CntByte := 6; Rec.Hours := AHour; Rec.Minutes := AMin; Rec.Seconds := ASec; Rec.Day := ADay; Rec.Month := AMonth - 2000; Rec.Year := AYear; // 00 10 55 B4 03 00 06 17 03 25 0B 3C E3 F9 C0 Bytes := RawToBytes(Rec, SizeOf(Rec)); Rec.CRC := Swap(CRC16(@Bytes, SizeOf(Rec) - 2)); Bytes := RawToBytes(Rec, SizeOf(Rec)); LogOut(BytesToHex(Bytes, ' ')); end; end.
unit format_vmrk; //support for BrainProducts VHDR format .. interface uses eeg_type, sysutils,dialogs, DateUtils,IniFiles, StrUtils,classes; type TEvent = record Typ,Desc: string; OnsetSamp,DurationSamp,Channel : integer; end; TVMRK = record Datafile: string; CurrentEvent: integer; Events: array of TEvent; end; function LoadVMRK(lFilename: string; var lV: TVMRK): boolean; function WriteVMRK(lFilename: string; var lV: TVMRK): boolean; //function LoadVMRKdummy(var lV: TVMRK): boolean; function CreateEmptyVMRK(var lV: TVMRK; N: integer): boolean; implementation function WriteVMRK(lFilename: string; var lV: TVMRK): boolean; var t,lN: integer; lVMRK: TStringList; begin result := false; lN := length(lV.Events); if lN < 1 then exit; lVMRK := TStringList.Create; lVMRK.Add('Brain Vision Data Exchange Marker File, Version 1.0'); lVMRK.Add('[Common Infos]'); //showmessage(lV.DataFile); if lV.Datafile <> '' then lVMRK.Add('DataFile='+lV.Datafile); lVMRK.Add('[Marker Infos]'); lVMRK.Add('; Each entry: Mk{Marker number}={Type},{Description},{Position in data points},'); lVMRK.Add('; {Size in data points}, {Trace number (0 = marker is related to all Traces)}'); lVMRK.Add('; Fields are delimited by commas, some fields might be omitted (empty).'); for t := 0 to lN-1 do lVMRK.Add('Mk'+inttostr(t+1)+'=Stimulus, '+lV.Events[t].Desc+', '+inttostr(lV.Events[t].OnsetSamp)+', '+inttostr(lV.Events[t].DurationSamp)+', '+inttostr(lV.Events[t].Channel)); //lFilename := extractfiledir(paramstr(0))+'\tms_'+ (FormatDateTime('yyyymmdd_hhnnss', (now)))+'.tab'; lVMRK.SaveToFile(lFilename); //Clipboard.AsText:= lVMRK.Text; lVMRK.free; result := true; end; { TEvent = record Typ,Desc: string; OnsetSamp,DurationSamp,Channel : integer; end; for t := 0 to n-1 do begin lV.Events[t].Typ:= 'Stimulus'; lV.Events[t].Desc := inttostr(t)+'desc'; lV.Events[t].OnsetSamp := (t) * 2048* 10; lV.Events[t].DurationSamp := 204; lV.Events[t].Channel := 0; end; } function NextCSV(lStr: string; var lP: integer): string; //reports text prior to comma... var len: integer; begin result := ''; len := length(lStr); if len < lP then exit; repeat if lStr[lP] = ',' then begin lP := lP + 1; exit; end; if lStr[lP] <> ' ' then result := result + lStr[lP]; lP := lP + 1; until (lP > len); end; procedure ReadEvent(lIniFile: TIniFile; lSection, lIdent: string; var lV: TEvent); //read or write a string value to the initialization file var lS: string; lP: integer; begin lS := lIniFile.ReadString(lSection,lIdent, ''); if lS = '' then exit; //Stimulus, Cond2, 0, 307, 0 lP := 1; lV.Typ := NextCSV(lS, lP); lV.Desc := NextCSV(lS, lP); lV.OnsetSamp := StrToInt(NextCSV(lS, lP)); lV.DurationSamp := StrToInt(NextCSV(lS, lP)); lV.Channel := StrToInt(NextCSV(lS, lP)); end; //IniStr function LoadVMRK(lFilename: string; var lV: TVMRK): boolean; const lRead = true; var lIniFile: TIniFile; t,N: integer; lS: string; begin result := false; if (not Fileexists(lFilename)) then exit; lIniFile := TIniFile.Create(lFilename); lV.Datafile := lIniFile.ReadString('Common Infos','DataFile',''); N := 0; repeat inc(N); lS := lIniFile.ReadString('Marker Infos','Mk'+inttostr(N),''); until (lS = ''); dec(N); lIniFile.Free; if N < 1 then exit; //2nd passs: read events setlength(lV.Events,n); lIniFile := TIniFile.Create(lFilename); lV.Datafile := lIniFile.ReadString('Common Infos','DataFile',''); for t := 1 to N do ReadEvent(lIniFile,'Marker Infos','Mk'+inttostr(t),lV.Events[t-1]); lIniFile.Free; end; function CreateEmptyVMRK(var lV: TVMRK; N: integer): boolean; var t: integer; begin //result := false; //if not Fileexists(lFilename) then // exit; lV.Datafile := 'Test'; lV.CurrentEvent := 0; //n := 30; setlength(lV.Events,n); for t := 0 to n-1 do begin lV.Events[t].Typ:= 'Stimulus'; lV.Events[t].Desc := 'Cond'+inttostr(t); lV.Events[t].OnsetSamp := (t) * 2048* 10; lV.Events[t].DurationSamp := 100; lV.Events[t].Channel := 0; end; result := true; end; end.
{ Subroutine SST_FLAG_USED_VAR (V) * * Flag all symbols as USED that are eventually referenced by the "variable" * desecriptor V. } module sst_FLAG_USED_VAR; define sst_flag_used_var; %include 'sst2.ins.pas'; procedure sst_flag_used_var ( {flag symbols eventually used from var desc} in v: sst_var_t); {var descriptor that may reference symbols} begin sst_flag_used_symbol (v.mod1.top_sym_p^); if v.dtype_p <> nil then begin sst_flag_used_dtype (v.dtype_p^); end; end;
uses math; const maxn=20; max_num=1e10; eps=1e-6; type extended=real; Tdot=record x,y,z:extended; end; var dot:array[1..maxn]of Tdot; n:longint; maxdis:extended; procedure setup; begin assign(input,'input.txt'); reset(input); end; procedure endit; begin close(input); close(output); end; procedure init; var i:longint; lat,lon:extended; begin readln(n); for i:=1 to n do begin read(lat,lon); lat:=lat/180*pi; lon:=lon/180*pi; dot[i].x:=cos(lat)*cos(lon); dot[i].y:=cos(lat)*sin(lon); dot[i].z:=sin(lat); end; end; function line_dist(a,b:Tdot):extended; begin exit(sqrt(sqr(a.x-b.x)+sqr(a.y-b.y)+sqr(a.z-b.z))); end; function sphere_dist(a,b:Tdot):extended; var t:extended; begin t:=line_dist(a,b); t:=t/2; if t>1 then t:=1; exit(2*arcsin(t)); end; operator -(a,b:Tdot) c:Tdot; begin c.x:=a.x-b.x; c.y:=a.y-b.y; c.z:=a.z-b.z; end; operator *(a,b:Tdot) c:Tdot; begin c.x:=a.y*b.z-a.z*b.y; c.y:=a.z*b.x-a.x*b.z; c.z:=a.x*b.y-a.y*b.x; end; procedure normalize(var a:Tdot); var dist:extended; begin dist:=sqrt(a.x*a.x+a.y*a.y+a.z*a.z); a.x:=a.x/dist; a.y:=a.y/dist; a.z:=a.z/dist; end; function getmid(a,b:Tdot):Tdot; var c:Tdot; begin c.x:=a.x+b.x; c.y:=a.y+b.y; c.z:=a.z+b.z; if (abs(c.x)<eps) and (abs(c.y)<eps) and (abs(c.z)<eps) then if a.x<1-eps then begin c.x:=0; c.y:=-a.z; c.z:=a.y; end else if a.y<1-eps then begin c.x:=-a.z; c.y:=0; c.z:=a.x; end else begin c.x:=-a.y; c.y:=a.x; c.z:=0; end else assert(false); normalize(c); exit(c); end; procedure chk(a:Tdot); var i:longint; t,mindis:extended; begin mindis:=max_num; for i:=1 to n do begin t:=sphere_dist(a,dot[i]); if t<mindis then mindis:=t; end; if mindis>maxdis then maxdis:=mindis; end; procedure main; var i,j,k:longint; t:Tdot; begin if n=1 then begin writeln(pi:0:6); exit; end; maxdis:=0; for i:=1 to n-1 do for j:=i+1 to n do begin t:=getmid(dot[i],dot[j]); normalize(t); chk(t); t.x:=-t.x; t.y:=-t.y; t.z:=-t.z; chk(t); end; for i:=1 to n-2 do for j:=i+1 to n-1 do for k:=j+1 to n do begin t:=(dot[j]-dot[i])*(dot[k]-dot[i]); normalize(t); chk(t); t.x:=-t.x; t.y:=-t.y; t.z:=-t.z; chk(t); end; writeln(maxdis:0:6); end; begin setup; init; main; endit; end.
unit frmInIOCPAdmin; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ActnList, iocp_clients, iocp_base, ComCtrls; type TFormInIOCPAdmin = class(TForm) InCertifyClient1: TInCertifyClient; InConnection1: TInConnection; InMessageClient1: TInMessageClient; btnLogin: TButton; btnBroacast: TButton; btnCapScreen: TButton; btnDisconnect: TButton; btnClose: TButton; ActionList1: TActionList; actLogin: TAction; actBroadcast: TAction; actTransmitFile: TAction; actDisconnect: TAction; actLogout: TAction; actClose: TAction; btnRegister: TButton; btnModify: TButton; actRegister: TAction; actModify: TAction; actSendMsg: TAction; btnSendMsg: TButton; lvClientView: TListView; pgcInfo: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; Memo1: TMemo; Button1: TButton; actBackground: TAction; procedure FormCreate(Sender: TObject); procedure InCertifyClient1ReturnResult(Sender: TObject; Result: TResultParams); procedure actLoginExecute(Sender: TObject); procedure actLogoutExecute(Sender: TObject); procedure InCertifyClient1Certify(Sender: TObject; Action: TActionType; ActResult: Boolean); procedure actBroadcastExecute(Sender: TObject); procedure actTransmitFileExecute(Sender: TObject); procedure actDisconnectExecute(Sender: TObject); procedure actCloseUpdate(Sender: TObject); procedure actCloseExecute(Sender: TObject); procedure InCertifyClient1ListClients(Sender: TObject; Count, No: Cardinal; const Client: PClientInfo); procedure InConnection1ReceiveMsg(Sender: TObject; Msg: TResultParams); procedure actRegisterExecute(Sender: TObject); procedure InConnection1ReturnResult(Sender: TObject; Result: TResultParams); procedure actModifyExecute(Sender: TObject); procedure actSendMsgExecute(Sender: TObject); procedure actBackgroundExecute(Sender: TObject); private { Private declarations } function FindClientItem(const ClientName: String): TListItem; procedure AddMemoMessage(Msg: TResultParams); procedure AddClientItem(Msg: TResultParams); overload; procedure AddClientItem(No: Integer; Info: PClientInfo); overload; procedure UpdateClientItem(Item: TListItem; Msg: TResultParams; Login: Boolean); public { Public declarations } end; var FormInIOCPAdmin: TFormInIOCPAdmin; implementation uses iocp_varis, iocp_utils, frmInIOCPLogin, frmInIOCPRegister; var FormInIOCPLogin: TFormInIOCPLogin = nil; {$R *.dfm} procedure TFormInIOCPAdmin.actBackgroundExecute(Sender: TObject); begin // 服务端用后台线程执行,完毕后推送消息,客户端下载一个文件(假设是列出文件的结果) // 见:客户端 TFormInIOCPAdmin.InConnection1ReceiveMsg、服务端 InFileManager1QueryFiles with TMessagePack.Create(InConnection1) do begin Msg := '列出文件,假设很耗时。'; Post(atFileList); // 列出文件 end; end; procedure TFormInIOCPAdmin.actBroadcastExecute(Sender: TObject); begin // 广播,但不推送给自己 // 请先登录普通客户端 with TMessagePack.Create(InConnection1) do begin Msg := '广播一条消息AAA'; Post(atTextBroadcast); // 广播 end; end; procedure TFormInIOCPAdmin.actTransmitFileExecute(Sender: TObject); begin // 上传文件某客户端 // 请让客户端 aaa 离线、在线,观察客户端消息 with TMessagePack.Create(InConnection1) do begin Msg := '请下载这个文件,更新本地的相应文件.'; ToUser := 'aaa,bbb'; // 告诉 aaa,bbb 下载这个文件 LoadFromFile('bin\sqlite3-w64.dll'); Post(atFileUpShare); // 共享给对方 end; // 下载服务端的文件 // (默认的存放路径:InConnection1.LocalPath) { with TMessagePack.Create(InConnection1) do begin FileName := 'sqlite3-w64.dll'; // 具体位置在服务端解析 LocalPath := 'temp'; // 指定临时的存放路径, 新版增加 Post(atFileDownload); // 下载 end; // 断点上传 with TMessagePack.Create(InConnection1) do begin LoadFromFile('F:\Backup\MSOffice2003.7z'); Post(atFileUpChunk); end; } end; procedure TFormInIOCPAdmin.actCloseExecute(Sender: TObject); begin if InConnection1.Logined then InCertifyClient1.Logout; if InConnection1.Active then InConnection1.Active := False; Close; end; procedure TFormInIOCPAdmin.actCloseUpdate(Sender: TObject); begin if InConnection1.Logined then btnLogin.Action := actLogout // 登出 else btnLogin.Action := actLogin; // 登录 actRegister.Enabled := InConnection1.Logined; actBroadcast.Enabled := InConnection1.Logined; actTransmitFile.Enabled := InConnection1.Logined; actModify.Enabled := InConnection1.Logined; actSendMsg.Enabled := InConnection1.Logined; actDisconnect.Enabled := InConnection1.Logined; actBackground.Enabled := InConnection1.Logined; end; procedure TFormInIOCPAdmin.actDisconnectExecute(Sender: TObject); begin // 断开,无对应的操作 TActionType, // 可以发一条普通文本消息到服务端,服务端根据消息含义中断特定客户端 with TMessagePack.Create(InConnection1) do begin Msg := 'DISCONNECT'; // 断开 ToUser := 'aaa'; // 断开 aaa Post(atTextSend); // 发送文本消息 end; end; procedure TFormInIOCPAdmin.actLoginExecute(Sender: TObject); begin // 登录 FormInIOCPLogin := TFormInIOCPLogin.Create(Self); with FormInIOCPLogin do begin FConnection := InConnection1; FCertifyClient := InCertifyClient1; ShowModal; if InConnection1.Logined then begin lvClientView.Items.Clear; // 清除客户端列表 InCertifyClient1.QueryClients; // 查询全部连接过的客户端 end; Free; end; end; procedure TFormInIOCPAdmin.actLogoutExecute(Sender: TObject); begin // 登出 lvClientView.Items.Clear; InCertifyClient1.Logout; // 服务端 SQL 名称 [USER_LOGOUT] end; procedure TFormInIOCPAdmin.actModifyExecute(Sender: TObject); begin // 服务端会检查登录用户的权限,权限大才能删除 { with TMessagePack.Create(InConnection1) do begin ToUser := 'ADDNEW'; // 要修改的用户 = TargetUser AsString['user_password'] := 'aaa'; AsInteger['user_level'] := 1; AsString['user_real_name'] := '实名'; AsString['user_telephone'] := '01023456789'; Post(atUserModify); // 修改 end; } // 注意:UserName 是登录用户名,不能删除自己 with TMessagePack.Create(InConnection1) do begin ToUser := 'ADDNEW'; // 要删除的用户 = TargetUser Post(atUserDelete); // 删除 end; end; procedure TFormInIOCPAdmin.actRegisterExecute(Sender: TObject); begin // 注册 pgcInfo.ActivePageIndex := 1; with TFormInIOCPRegister.Create(Self) do begin FConnection := InConnection1; ShowModal; Free; end; end; procedure TFormInIOCPAdmin.actSendMsgExecute(Sender: TObject); begin // 请先登录普通客户端 with TMessagePack.Create(InConnection1) do begin ToUser := 'aaa,bbb'; // 目的用户 = TargetUser,可以推送给多用户: aaa,bbb,ccc Msg := '推送一条消息'; Post(atTextPush); // 提交 end; end; procedure TFormInIOCPAdmin.AddClientItem(Msg: TResultParams); var Item: TListItem; begin // 客户端登录:加入信息 Item := lvClientView.Items.Add; Item.Caption := IntToStr(Item.Index + 1); Item.SubItems.Add(Msg.UserGroup + ':' + Msg.UserName); Item.SubItems.Add(Msg.PeerIPPort); Item.SubItems.Add(IntToStr(Integer(Msg.Role))); Item.SubItems.Add(DateTimeToStr(Msg.AsDateTime['action_time'])); Item.SubItems.Add('-'); end; procedure TFormInIOCPAdmin.AddClientItem(No: Integer; Info: PClientInfo); var Item: TListItem; begin // 查询客户端:加入信息(见 TClientInfo) Item := lvClientView.Items.Add; Item.Caption := IntToStr(No); Item.SubItems.Add(Info^.Group + ':' + Info^.Name); Item.SubItems.Add(Info^.PeerIPPort); Item.SubItems.Add(IntToStr(Integer(Info^.Role))); Item.SubItems.Add(DateTimeToStr(Info^.LoginTime)); if (Info^.LogoutTime = 0) then Item.SubItems.Add('-') else Item.SubItems.Add(DateTimeToStr(Info^.LogoutTime)); end; procedure TFormInIOCPAdmin.AddMemoMessage(Msg: TResultParams); begin Memo1.Lines.Add(DateTimeToStr(Now) + '>' + Msg.PeerIPPort + ',' + Msg.UserName + ',' + Msg.Msg); end; function TFormInIOCPAdmin.FindClientItem(const ClientName: String): TListItem; var i: Integer; begin for i := 0 to lvClientView.Items.Count - 1 do begin Result := lvClientView.Items[i]; if (Result.SubItems[0] = ClientName) then // 找到客户端 Exit; // 返回 end; Result := Nil; end; procedure TFormInIOCPAdmin.FormCreate(Sender: TObject); begin InConnection1.LocalPath := gAppPath + 'data\data_admin'; // 文件存放路径 CreateDir(InConnection1.LocalPath); end; procedure TFormInIOCPAdmin.InCertifyClient1Certify(Sender: TObject; Action: TActionType; ActResult: Boolean); begin if not InConnection1.Logined then // 此时 Action = atUserLogout and ActResult = True InConnection1.Active := False; // 同时断开 end; procedure TFormInIOCPAdmin.InCertifyClient1ListClients(Sender: TObject; Count, No: Cardinal; const Client: PClientInfo); var Item: TListItem; begin // 列出全部连接过的客户端信息 if (Client^.LogoutTime = 0) then // 在线已登录的客户端 begin Item := FindClientItem(Client^.Group + ':' + Client^.Name); if Assigned(Item) then // 更新客户端信息 Item.Caption := IntToStr(No) else // 加入客户端信息(见 TClientInfo) AddClientItem(No, Client); end; end; procedure TFormInIOCPAdmin.InCertifyClient1ReturnResult(Sender: TObject; Result: TResultParams); begin // 返回 InCertifyClient1 的操作结果 case Result.Action of atUserLogin: begin if InConnection1.Logined then FormInIOCPLogin.Close; AddMemoMessage(Result); end; atUserQuery: { 已在 OnListClients 中列出客户端 } ; end; end; procedure TFormInIOCPAdmin.InConnection1ReceiveMsg(Sender: TObject; Msg: TResultParams); var Item: TListItem; begin // 客户端登录时,服务端要推送足够多的信息 case Msg.Action of atUserLogin: begin Item := FindClientItem(Msg.UserGroup + ':' + Msg.UserName); if Assigned(Item) then UpdateClientItem(Item, Msg, True) else AddClientItem(Msg); end; atUserLogout: begin Item := FindClientItem(Msg.UserGroup + ':' + Msg.UserName); if Assigned(Item) then UpdateClientItem(Item, Msg, False); // 也可以清除端列表,重新查询(最保险,但延迟) // lvClientView.Items.Clear; // 清除客户端列表 // InCertifyClient1.QueryClients; // 查询全部已连接的客户端 end; atFileList: begin Memo1.Lines.Add('服务端用后台执行,唤醒客户端了,可以在此下载服务端的结果.'); with TMessagePack.Create(InConnection1) do begin LocalPath := 'temp'; // 临时的文件存放路径 FileName := 'sqlite运行库.txt'; // 下载后台执行的结果文件! Post(atFileDownload); end; end; end; // 加入客户端活动 memo AddMemoMessage(Msg); end; procedure TFormInIOCPAdmin.InConnection1ReturnResult(Sender: TObject; Result: TResultParams); begin // 加入客户端活动 memo AddMemoMessage(Result); end; procedure TFormInIOCPAdmin.UpdateClientItem(Item: TListItem; Msg: TResultParams; Login: Boolean); begin // 更新客户端信息 if Login then // 登录 begin Item.SubItems[1] := Msg.PeerIPPort; Item.SubItems[2] := IntToStr(Integer(Msg.Role)); Item.SubItems[3] := DateTimeToStr(Msg.AsDateTime['action_time']); Item.SubItems[4] := '-'; end else Item.SubItems[4] := DateTimeToStr(Msg.AsDateTime['action_time']); end; end.
unit uCliente; interface uses uProtocolo, System.SysUtils, System.Classes, System.Generics.Collections, blcksock, Web.Win.Sockets; type EClienteErro = class(Exception); TCliente<T: class> = class private Socket: TTCPBlockSocket; FHost: string; FPorta: string; function Execute(Protocolo: TOperacaoProtocolo; Mensagem: String): TProtocoloResposta; function GetModelName: string; public constructor Create(const AHost, APorta: string); destructor Destroy; override; function ExecuteIncluir(Mensagem: String): TProtocoloResposta; function ExecuteAlterar(Mensagem: String): TProtocoloResposta; function ExecuteExcluir(Mensagem: String): TProtocoloResposta; function ExecuteListar(Mensagem: String): TProtocoloResposta; property Host: string read FHost; property Porta: string read FPorta; property ModelName: string read GetModelName; end; implementation { TCliente } uses uMJD.Messages; constructor TCliente<T>.Create(const AHost, APorta: string); begin FHost := AHost; FPorta := APorta; Socket := TTCPBlockSocket.create; end; destructor TCliente<T>.Destroy; begin Socket.Free; inherited; end; function TCliente<T>.Execute(Protocolo: TOperacaoProtocolo; Mensagem: String): TProtocoloResposta; var cmd: AnsiString; begin cmd := Format(FORMAT_PROTOCOLO_REQ + CRLF, [TOperacaoProtocoloString[Protocolo], ModelName, Mensagem]); try Socket.Connect(Host, Porta); if (Socket.LastError <> 0) then raise EClienteErro.CreateFmt(rsConexaoFalhou, [Socket.LastErrorDesc, Socket.GetErrorDescEx]); Socket.SendString(cmd); if Socket.CanRead(50000) then begin Result := TProtocoloResposta.CreateFromString(Socket.RecvString(1000)); end else raise EClienteErro.Create(rsServidorNaoRespondendo); finally Socket.CloseSocket(); Socket.Purge; end; end; function TCliente<T>.ExecuteAlterar(Mensagem: String): TProtocoloResposta; begin Result := Execute(opAlterar, Mensagem); end; function TCliente<T>.ExecuteExcluir(Mensagem: String): TProtocoloResposta; begin Result := Execute(opExcluir, Mensagem); end; function TCliente<T>.ExecuteIncluir(Mensagem: String): TProtocoloResposta; begin Result := Execute(opIncluir, Mensagem); end; function TCliente<T>.ExecuteListar(Mensagem: String): TProtocoloResposta; begin Result := Execute(opListar, Mensagem); end; function TCliente<T>.GetModelName: string; begin Result := StringReplace(T.ClassName, 'T', '', []); end; end.
unit uFlashQuestion; interface uses ExtCtrls, Controls, uFormData, uFlashRect, Messages, Dialogs; type //TFlashQuestion = class(TPanel) TFlashQuestion = class(TShape) private FData: TQuestionData; procedure SetData(const Value: TQuestionData); protected procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK; procedure Paint; override; public procedure AfterConstruction;override; property Data: TQuestionData read FData write SetData; //positioning procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override; var FFlashPos: TFlashRect; FZoomBusy: Boolean; class var EditMode: Boolean; end; implementation uses SysUtils, Forms, IOUtils, fImagePopup, Graphics; { TFlashQuestion } procedure TFlashQuestion.AfterConstruction; begin inherited; // Self.ShowCaption := False; // Self.BevelOuter := bvNone; //exit; // with TShape.Create(Self) do // begin // Align := alClient; Shape := stEllipse; Brush.Style := bsSolid; Brush.Color := clWhite; Pen.Color := clGreen; Pen.Width := 2; // Parent := Self; // end; end; procedure TFlashQuestion.Paint; var x, y: Integer; begin inherited Paint; Canvas.Font.Size := Self.Height div 2; x := (Self.Width div 2) - (Canvas.TextWidth('?') div 2); y := (Self.Height div 2) - (Canvas.TextHeight('?') div 2); Canvas.TextOut(x, y, '?'); end; procedure TFlashQuestion.SetBounds(ALeft, ATop, AWidth, AHeight: Integer); var scrollb: TScrollBox; begin if not FZoomBusy then begin scrollb := Parent as TScrollBox; if scrollb <> nil then begin FFlashPos.ScreenLeft := ALeft + scrollb.HorzScrollBar.Position; FFlashPos.ScreenTop := ATop + scrollb.VertScrollBar.Position; end else begin FFlashPos.ScreenLeft := ALeft; FFlashPos.ScreenTop := ATop; end; FFlashPos.ScreenWidth := AWidth; FFlashPos.ScreenHeigth := AHeight; end; if FData <> nil then begin FData.QuestionPos.Top := FFlashPos.FlashTop; FData.QuestionPos.Left := FFlashPos.FlashLeft; FData.QuestionPos.Width := FFlashPos.FlashWidth; FData.QuestionPos.Height := FFlashPos.FlashHeigth; end; inherited; Self.Invalidate; end; procedure TFlashQuestion.SetData(const Value: TQuestionData); var scrollb: TScrollBox; begin FData := Value; if FData = nil then Exit; FFlashPos.FlashTop := FData.QuestionPos.Top; FFlashPos.FlashLeft := FData.QuestionPos.Left; FFlashPos.FlashWidth := FData.QuestionPos.Width; FFlashPos.FlashHeigth := FData.QuestionPos.Height; scrollb := Parent as TScrollBox; if scrollb <> nil then begin Self.SetBounds(Self.FFlashPos.ScreenLeft - scrollb.HorzScrollBar.Position, Self.FFlashPos.ScreenTop - scrollb.VertScrollBar.Position, Self.FFlashPos.ScreenWidth, Self.FFlashPos.ScreenHeigth) end else Self.SetBounds(Self.FFlashPos.ScreenLeft, Self.FFlashPos.ScreenTop, Self.FFlashPos.ScreenWidth, Self.FFlashPos.ScreenHeigth); end; procedure TFlashQuestion.WMLButtonDblClk(var Message: TWMLButtonDblClk); var sDir, sFile, sRel: string; begin //if frmMainBmp.chkEditMode.Checked then if EditMode then begin with TOpenDialog.Create(nil) do try DefaultExt := '*.jpg'; if Execute then begin sFile := FileName; sDir := ExtractFilePath(Application.ExeName); sRel := ExtractRelativePath(sDir, sFile); Self.Data.ImageFile := sRel; end; finally Free; end; end else begin TfrmImagePopup.ShowImage(Self.Data.ImageFile); end; end; end.
{!DOCTOPIC}{ Random module } {!DOCREF} { @method: var Rand = TObjRandom; @desc: This module provides you with a few Random-functions. More functions will probably be introduced later. if SRL-6 is imported module is renamed to "Randm" :/ } {!DOCREF} { @method: function Rand.Random(): Extended; @desc: Return the next random floating point number in the range c'0.0..1.0'. Same as c'Random();' } function TObjRandom.Random(): Extended; begin Result := RandomE(); end; {!DOCREF} { @method: function Rand.RandInt(a,b:Int32): Int32; @desc: Return a random integer [i]N[/i] such that c'a <= N <= b'. Same as c'RandomRange(a,b);' } function TObjRandom.RandInt(a,b:Int32): Int32; begin Result := RandomRange(a,b); end; {!DOCREF} { @method: function Rand.Uniform(a,b:Extended): Extended; @desc: Return a random floating-point [i]N[/i] such that c'a <= N <= b'. } function TObjRandom.Uniform(a,b:Extended): Extended; begin Result := a + (b-a) * Random(); end; {!DOCREF} { @method: function Rand.Gauss(mu,sigma:Extended): Extended; @desc: Gaussian distribution. mu is the mean, and sigma is the standard deviation. } function TObjRandom.Gauss(mu,sigma:Extended): Extended; var scale,theta:Extended; begin Scale := sigma * Sqrt(-2 * Ln(Random())); Theta := 2 * PI * Random(); Result := mu + Scale * Cos(theta); end; {!DOCREF} { @method: function Rand.TPA(Amount:Integer; MinX,MinY,MaxX,MaxY:Integer): TPointArray; @desc: Returns a randomized TPA spread within the given bounds } function TObjRandom.TPA(Amount:Integer; MinX,MinY,MaxX,MaxY:Integer): TPointArray; begin Result := exp_RandomTPA(Amount,MinX,MinY,MaxX,MaxY); end; {!DOCREF} { @method: function Rand.CenterTPA(Amount:Integer; CX,CY,RadX,RadY:Integer): TPointArray; @desc: Returns a randomized TPA spread within the given radius, weighted towards center. Much faster then to do the same with some complex gaussian computation. } function TObjRandom.CenterTPA(Amount:Integer; CX,CY,RadX,RadY:Integer): TPointArray; begin Result := exp_RandomCenterTPA(Amount,CX,CY,RadX,RadY); end; {!DOCREF} { @method: function Rand.TIA(Amount:Integer; Low,Hi:Integer): TIntArray; @desc: Returns a randomized TIA spread within the given bounds } function TObjRandom.TIA(Amount:Integer; Low,Hi:Integer): TIntArray; begin Result := exp_RandomTIA(Amount,Low,Hi); end; {!DOCREF} { @method: function Rand.GaussPt(MeanPt:TPoint; Stddev:Extended): TPoint; @desc: Generates a gaussian ("normally" distributed) TPoint using Box-Muller transform. } function TObjRandom.GaussPt(MeanPt:TPoint; Stddev:Extended): TPoint; var Theta,Scale:Extended; begin Scale := Stddev * Sqrt(-2 * Ln(Random())); Theta := 2 * PI * Random(); Result.x := Round(MeanPt.x + Scale * Cos(theta)); Result.y := Round(MeanPt.y + Scale * Sin(theta)); end; {!DOCREF} { @method: function Rand.GaussPt(MeanPt:TPoint; StdDev, MaxDev:Extended): TPoint; overload; @desc: Generates a gaussian ("normally" distributed) TPoint using Box-Muller transform. Takes an extra parameter to encapsule the point within a given range (maxDev). } function TObjRandom.GaussPt(MeanPt:TPoint; StdDev, MaxDev:Extended): TPoint; overload; var Theta,Scale:Extended; begin if MaxDev < 1 then MaxDev := 1; Scale := Stddev * Sqrt(-2 * Ln(Random())); while Scale > MaxDev do Scale := Stddev * Sqrt(-2 * Ln(Random())); Theta := 2 * PI * Random(); Result.x := Round(MeanPt.x + Scale * Cos(theta)); Result.y := Round(MeanPt.y + Scale * Sin(theta)); end; {!DOCREF} { @method: function Rand.GaussPtOval(MeanPt:TPoint; StddevX, StdDevY:Extended): TPoint; @desc: Generates a gaussian ("normally" distributed) TPoint using Box-Muller transform. Takes separate x, and y parameters for Standard deviation. } function TObjRandom.GaussPtOval(MeanPt:TPoint; StdDevX, StdDevY:Extended): TPoint; var ScaleX,ScaleY:Extended; begin ScaleX := StdDevX * Sqrt(-2 * Ln(Random())); ScaleY := StdDevY * Sqrt(-2 * Ln(Random())); Result.x := Round(MeanPt.x + ScaleX * Cos(2 * PI * Random())); Result.y := Round(MeanPt.y + ScaleY * Sin(2 * PI * Random())); end; {!DOCREF} { @method: function Rand.GaussPtOval(MeanPt:TPoint; StddevX, StdDevY, MaxDevX, MaxDevY:Extended): TPoint; overload; @desc: Generates a gaussian ("normally" distributed) TPoint using Box-Muller transform. Takes separate x, and y parameters for Standard deviation. Takes two extra parameter to encapsule the point within a given range (maxDevX & maxDevY). } function TObjRandom.GaussPtOval(MeanPt:TPoint; StddevX, StdDevY, MaxDevX, MaxDevY:Extended): TPoint; overload; var ScaleX,ScaleY:Extended; begin ScaleX := StddevX * Sqrt(-2 * Ln(Random())); while ScaleX > MaxDevX do ScaleX := StddevX * Sqrt(-2 * Ln(Random())); ScaleY := StddevY * Sqrt(-2 * Ln(Random())); while ScaleY > MaxDevY do ScaleY := StddevY * Sqrt(-2 * Ln(Random())); Result.x := Round(MeanPt.x + ScaleX * Cos(2 * PI * Random())); Result.y := Round(MeanPt.y + ScaleY * Sin(2 * PI * Random())); end; {!DOCREF} { @method: function Rand.GaussPtDonut(MeanPt:TPoint; StdDev, MaxDev:Extended; Radius:LongInt): TPoint; @desc: Generates a gaussian ("normally" distributed) TPoint using Box-Muller transform. Result in "Donut"-like shape with a gaussian distribution around the circumsphere. } function TObjRandom.GaussPtDonut(MeanPt:TPoint; StdDev, MaxDev:Extended; Radius:LongInt): TPoint; var PtG, Mid:TPoint; begin PtG := Self.GaussPt(MeanPt, StdDev, MaxDev); Mid := Self.GaussPt(MeanPt, StdDev, MaxDev); Result := se.ScalePoint(PtG, Mid, Radius); end;
unit DispatchGetterAsMethodPatch; {$D-,L-} { Calling indexed properties like Microsoft Word's .CentimetersToPoint - COM exception is thrown due to broken DispatchInvoke routine in ComObj.pas ( System.Win.ComObj.pas in newer Delphi ) To quote IDispatch original documentation from http://msdn.microsoft.com/en-us/library/windows/desktop/ms221486.aspx " Some languages cannot distinguish between retrieving a property and calling a method. In this case, you should set the flags DISPATCH_PROPERTYGET and DISPATCH_METHOD." And erroneous check for non-zero ArgCount is breaking correct behavior instead. Bug is reported to EMBT as http://qc.embarcadero.com/wc/qcmain.aspx?d=115373 Bug is reported to FPC team as http://bugs.freepascal.org/view.php?id=24352 More low-level info: * http://stackoverflow.com/questions/16279098/ * http://stackoverflow.com/questions/16285138/ } interface implementation uses Windows, SysConst, SysUtils, ComObj; //var // _EmptyBSTR: PWideChar = nil; (**** patch target: XE2 Upd4 Hotfix 1 Win32: Call Invoke method on the given IDispatch interface using the given call descriptor, dispatch IDs, parameters, and result procedure DispatchInvoke(const Dispatch: IDispatch; CallDesc: PCallDesc; DispIDs: PDispIDList; Params: Pointer; Result: PVariant); System.Win.ComObj.pas.1764: begin 004A1FA0 55 push ebp 004A1FA1 8BEC mov ebp,esp 004A1FA3 81C4C4FCFFFF add esp,$fffffcc4 .... System.Win.ComObj.pas.1784: InvKind := DISPATCH_PROPERTYPUTREF; 004A2083 BE08000000 mov esi,$00000008 System.Win.ComObj.pas.1785: DispIDs[0] := DISPID_PROPERTYPUT; 004A2088 C707FDFFFFFF mov [edi],$fffffffd System.Win.ComObj.pas.1786: DispParams.rgdispidNamedArgs := @DispIDs[0]; 004A208E 89BDC8FCFFFF mov [ebp-$00000338],edi System.Win.ComObj.pas.1787: Inc(DispParams.cNamedArgs); 004A2094 FF85D0FCFFFF inc dword ptr [ebp-$00000330] 004A209A EB16 jmp $004a20b2 -- jump short - relative System.Win.ComObj.pas.1789: else if (InvKind = DISPATCH_METHOD) and (CallDesc^.ArgCount = 0) and (Result <> nil) then 004A209C 83FE01 cmp esi,$01 004A209F 7511 jnz $004a20b2 -- jump conditional: relative 004A20A1 807B0100 cmp byte ptr [ebx+$01],$00 *** WIPE !!! *** 004A20A5 750B jnz $004a20b2 -- jump conditional: relative *** WIPE !!! *** 004A20A7 837D0800 cmp dword ptr [ebp+$08],$00 004A20AB 7405 jz $004a20b2 -- jump conditional: relative System.Win.ComObj.pas.1790: InvKind := DISPATCH_METHOD or DISPATCH_PROPERTYGET; 004A20AD BE03000000 mov esi,$00000003 System.Win.ComObj.pas.1792: FillChar(ExcepInfo, SizeOf(ExcepInfo), 0); 004A20B2 8D45DC lea eax,[ebp-$24] 004A20B5 33C9 xor ecx,ecx 004A20B7 BA20000000 mov edx,$00000020 004A20BC E8532AF6FF call @FillChar -- 0xE8 - relative offset, yet SmartLinker can change it per-project System.Win.ComObj.pas.1793: Status := Dispatch.Invoke(DispID, GUID_NULL, 0, InvKind, DispParams, 004A20C1 6A00 push $00 004A20C3 8D45DC lea eax,[ebp-$24] 004A20C6 50 push eax 004A20C7 8B4508 mov eax,[ebp+$08] 004A20CA 50 push eax 004A20CB 8D85C4FCFFFF lea eax,[ebp-$0000033c] 004A20D1 50 push eax 004A20D2 56 push esi 004A20D3 6A00 push $00 004A20D5 A1CC985300 mov eax,[$005398cc] -- !!! kill abs. reloc. offset !!! 004A20DA 50 push eax 004A20DB 8B85D4FCFFFF mov eax,[ebp-$0000032c] 004A20E1 50 push eax 004A20E2 8B85D8FCFFFF mov eax,[ebp-$00000328] 004A20E8 50 push eax 004A20E9 8B00 mov eax,[eax] 004A20EB FF5018 call dword ptr [eax+$18] -- call v-table method - relative System.Win.ComObj.pas.1795: if Status <> 0 then 004A20EE 85C0 test eax,eax 004A20F0 7408 jz $004a20fa -- jump conditional: relative ***) Const patch_maybe_proc_base = $004A1FA0; patch_pattern_start = $004A2083 - patch_maybe_proc_base; patch_pattern_end = $004A20F0 + 2 - patch_maybe_proc_base; patch_pattern_len = patch_pattern_end - patch_pattern_start; patch_target_start = $004A20A1 - patch_maybe_proc_base; patch_target_end = $004A20A7 - patch_maybe_proc_base; patch_target_len = patch_target_end - patch_target_start; patch_target_ignore_dword_1 = $004A20D5 + 1 - patch_maybe_proc_base; patch_target_ignore_dword_2 = $004A20BC + 1 - patch_maybe_proc_base; patch_x86_NOP = $90; TargetPattern : array [ 0 .. patch_pattern_len - 1] of byte = ( $BE, $08, $00, $00, $00, // mov esi,$00000008 $C7, $07, $FD, $FF, $FF, $FF, // mov [edi],$fffffffd $89, $BD, $C8, $FC, $FF, $FF, // mov [ebp-$00000338],edi $FF, $85, $D0, $FC, $FF, $FF, // inc dword ptr [ebp-$00000330] $EB, $16, // jmp $004a20b2 -- jump short - relative $83, $FE, $01, // cmp esi,$01 $75, $11, // jnz $004a20b2 -- jump conditional: relative $80, $7B, $01, $00, // cmp byte ptr [ebx+$01],$00 *** WIPE !!! *** $75, $0B, // jnz $004a20b2 -- jump conditional: relative *** WIPE !!! *** $83, $7D, $08, $00, // cmp dword ptr [ebp+$08],$00 $74, $05, // jz $004a20b2 -- jump conditional: relative $BE, $03, $00, $00, $00, // mov esi,$00000003 $8D, $45, $DC, // lea eax,[ebp-$24] $33, $C9, // xor ecx,ecx $BA, $20, $00, $00, $00, // mov edx,$00000020 $E8, 0*$53, 0*$2A, 0*$F6, 0*$FF, // call @FillChar -- !!! kill outer offset !!! $6A, $00, // push $00 $8D, $45, $DC, // lea eax,[ebp-$24] $50, // push eax $8B, $45, $08, // mov eax,[ebp+$08] $50, // push eax $8D, $85, $C4, $FC, $FF, $FF, // lea eax,[ebp-$0000033c] $50, // push eax $56, // push esi $6A, $00, // push $00 $A1, 0*$CC, 0*$98, 0*$53, 0*$00, // mov eax,[$005398cc] -- !!! kill abs. reloc. offset !!! $50, // push eax $8B, $85, $D4, $FC, $FF, $FF, // mov eax,[ebp-$0000032c] $50, // push eax $8B, $85, $D8, $FC, $FF, $FF, // mov eax,[ebp-$00000328] $50, // push eax $8B, $00, // mov eax,[eax] $FF, $50, $18, // call dword ptr [eax+$18] -- call v-table method - relative $85, $C0, // test eax,eax $74, $08 // jz $004a20fa -- jump conditional: relative ); Var Patched: boolean = False; function GetActualAddr(Proc: Pointer): Pointer; forward; procedure Init; var Base, Pad, Target: PByte; PDW: PDWORD; n: SIZE_T; Success: Boolean; PadBuff: array [ 0 .. patch_pattern_len - 1] of byte; NopBuff: array [ 0 .. patch_target_len - 1] of byte; begin Base := GetActualAddr( @ComObj.DispatchInvoke ); Pad := Base + patch_pattern_start; Move(Pad^, PadBuff[0], patch_pattern_len); PDW := @PadBuff[patch_target_ignore_dword_1 - patch_pattern_start]; PDW^ := 0; PDW := @PadBuff[patch_target_ignore_dword_2 - patch_pattern_start]; PDW^ := 0; Success := CompareMem(@TargetPattern[0], @PadBuff[0], patch_pattern_len); if Success then begin Target := Base + patch_target_start; FillChar(NopBuff[0], patch_target_len, patch_x86_NOP); Success := WriteProcessMemory(GetCurrentProcess, Target, @NopBuff[0], patch_target_len, n) and (n = SizeOf(NopBuff)); end; if not Success then raise EOleError.Create('ComObj.DispatchInvoke patching failed'); Patched := True; // _EmptyBSTR := StringToOleStr(''); // leaks memory end; procedure Fini; var Base, Pad, Target: PByte; n: SIZE_T; begin // Restore original opcodes if not Patched then exit; Base := GetActualAddr( @ComObj.DispatchInvoke ); Target := Base + patch_target_start; Pad := @TargetPattern[patch_target_start - patch_pattern_start]; WriteProcessMemory(GetCurrentProcess, Target, Pad, patch_target_len, n); Patched := False; end; function GetActualAddr(Proc: Pointer): Pointer; type PWin9xDebugThunk = ^TWin9xDebugThunk; TWin9xDebugThunk = packed record PUSH: Byte; Addr: Pointer; JMP: Byte; Rel: Integer; end; PAbsoluteIndirectJmp = ^TAbsoluteIndirectJmp; TAbsoluteIndirectJmp = packed record OpCode: Word; Addr: ^Pointer; end; begin Result := Proc; if Result <> nil then begin {$IFDEF CPUX64} if PAbsoluteIndirectJmp(Result).OpCode = $25FF then Result := PPointer(PByte(@PAbsoluteIndirectJmp(Result).OpCode) + SizeOf(TAbsoluteIndirectJmp) + Integer(PAbsoluteIndirectJmp(Result).Addr))^; {$ELSE} if (Win32Platform <> VER_PLATFORM_WIN32_NT) and (PWin9xDebugThunk(Result).PUSH = $68) and (PWin9xDebugThunk(Result).JMP = $E9) then Result := PWin9xDebugThunk(Result).Addr; if PAbsoluteIndirectJmp(Result).OpCode = $25FF then Result := PAbsoluteIndirectJmp(Result).Addr^; {$ENDIF CPUX64} end; end; initialization Init; finalization Fini; end.
unit ddPicture; // Модуль: "w:\common\components\rtl\Garant\dd\ddPicture.pas" // Стереотип: "SimpleClass" // Элемент модели: "TddPicture" MUID: (51E8DC3E0361) {$Include w:\common\components\rtl\Garant\dd\ddDefine.inc} interface uses l3IntfUses , ddTextParagraph , Classes , l3Base , l3MetafileHeader , l3Filer , ddParagraphProperty , ddDocumentAtom , ddCustomDestination , k2Interfaces , ddTypes , l3ProtoObject ; type TddPicture = class(TddTextParagraph) private f_NeedWMFHeader: Boolean; f_WMFHeader: Tl3MetafileHeader; f_IsBinary: Boolean; f_BPP: Integer; f_CropL: Integer; f_CropR: Integer; f_CropB: Integer; f_CropT: Integer; f_ExternalHandle: Integer; f_ExternalPath: AnsiString; f_Format: Integer; f_GoalX: Integer; f_GoalY: Integer; f_Height: Integer; f_ScaleX: Integer; f_ScaleY: Integer; f_Width: Integer; f_Stream: TStream; f_Picture: Tl3String; f_WidthInPixels: Integer; f_HeightInPixels: Integer; private procedure CropPicture; function HexToBinEx(aText: Tl3String; Buffer: PAnsiChar; BufSize: Integer): Integer; {* Преобразование из 16-ричной текстовй строки в бинарные данные с пропуском символов переноса стоки и поддержки заглавных букв. } function Try2ReadEMF(const aFiler: Tl3CustomFiler): Tl3String; {* Чтение текстового 16-ричного потока EMF. } {$If Defined(InsiderTest)} procedure SavePicture2File(aSize: Integer); {$IfEnd} // Defined(InsiderTest) function Try2ReadWMF(const aFiler: Tl3CustomFiler): Tl3String; {* Чтение текстового 16-ричного потока WMF. } procedure Try2RecalcPictureProps; protected procedure pm_SetIsBinary(aValue: Boolean); function pm_GetFormat: Integer; function pm_GetStream: TStream; procedure pm_SetStream(aValue: TStream); procedure pm_SetWidthInPixels(aValue: Integer); procedure pm_SetHeightInPixels(aValue: Integer); procedure ConvertToBin; procedure ConvertToHex; procedure Cleanup; override; {* Функция очистки полей объекта. } function GetEmpty: Boolean; override; procedure ClearFields; override; public procedure AddHexData(aHexStream: Tl3String); {* Добавляем строку с 16-ричными символами. } function Try2ReadKnownPicture(const aFiler: Tl3CustomFiler): Tl3String; {* Пытаемся передать обработку "знающим" объектам. } function Clone(aPAP: TddParagraphProperty): TddPicture; class function CreateFromFile(const aPath: AnsiString): TddPicture; procedure Try2ReadBinaryData(const aFiler: Tl3CustomFiler; aSize: Integer); procedure Clear; override; procedure Write2Generator(const Generator: Ik2TagGenerator; aNeedProcessRow: Boolean; LiteVersion: TddLiteVersion); override; constructor Create(aDetination: TddCustomDestination); override; function IsTextPara: Boolean; override; function IsPicture: Boolean; override; function GetLastPara: TddDocumentAtom; override; procedure Assign(const aDocAtomObj: Tl3ProtoObject); override; function CanWrite: Boolean; override; {* Проверяет возможность записи объекта. Например, если у картинки нет размеров ширины и высоты, то она не записывается. } public property IsBinary: Boolean read f_IsBinary write pm_SetIsBinary; property BPP: Integer read f_BPP write f_BPP; property CropL: Integer read f_CropL write f_CropL; property CropR: Integer read f_CropR write f_CropR; property CropB: Integer read f_CropB write f_CropB; property CropT: Integer read f_CropT write f_CropT; property ExternalHandle: Integer read f_ExternalHandle write f_ExternalHandle; property ExternalPath: AnsiString read f_ExternalPath write f_ExternalPath; property Format: Integer read pm_GetFormat write f_Format; property GoalX: Integer read f_GoalX write f_GoalX; property GoalY: Integer read f_GoalY write f_GoalY; property Height: Integer read f_Height write f_Height; property ScaleX: Integer read f_ScaleX write f_ScaleX; property ScaleY: Integer read f_ScaleY write f_ScaleY; property Width: Integer read f_Width write f_Width; property Stream: TStream read pm_GetStream write pm_SetStream; property Picture: Tl3String read f_Picture; property WidthInPixels: Integer write pm_SetWidthInPixels; property HeightInPixels: Integer write pm_SetHeightInPixels; end;//TddPicture implementation uses l3ImplUses {$If NOT Defined(NoImageEn)} , imageenview {$IfEnd} // NOT Defined(NoImageEn) , l3Chars , l3Memory , SysUtils , ddRTFUnits {$If NOT Defined(NoImageEn)} , imageenio {$IfEnd} // NOT Defined(NoImageEn) , k2Tags , l3Math , evdTypes , ddEVDTypesSupport , ddConst , l3ImageUtils , l3Metafile , Graphics , ddHexCharReader , Windows , ddPicturePathListner //#UC START# *51E8DC3E0361impl_uses* //#UC END# *51E8DC3E0361impl_uses* ; procedure TddPicture.pm_SetIsBinary(aValue: Boolean); //#UC START# *521AE2E301F2_51E8DC3E0361set_var* //#UC END# *521AE2E301F2_51E8DC3E0361set_var* begin //#UC START# *521AE2E301F2_51E8DC3E0361set_impl* if aValue <> f_IsBinary then begin f_IsBinary:= aValue; if f_IsBinary then ConvertToBin else ConvertToHex; end; //#UC END# *521AE2E301F2_51E8DC3E0361set_impl* end;//TddPicture.pm_SetIsBinary function TddPicture.pm_GetFormat: Integer; //#UC START# *521AE90802CC_51E8DC3E0361get_var* var l_Format: Integer; l_Detector: TImageEnIO; //#UC END# *521AE90802CC_51E8DC3E0361get_var* begin //#UC START# *521AE90802CC_51E8DC3E0361get_impl* if f_Format = -1 then begin if f_Stream.Size > 1 then begin f_Stream.Seek(0, 0); l_Detector:= TImageEnIO.Create(nil); try l_Detector.LoadFromStream(Stream); f_Format:= l_Detector.Params.FileType; if f_Format <> ioUnknown then begin { нужно выставить значения ширины, высоты, цветности и т.д. } if f_Height = 0 then f_Height := l_Detector.Params.Height; if f_Width = 0 then f_Width := l_Detector.Params.Width; f_BPP := l_Detector.Params.BitsPerSample; end; // l_Format <> ioUnknown finally FreeAndNil(l_Detector); end; end; // f_Stream.Size > 1 f_Stream.Seek(0, 0); end; Result := f_Format; //#UC END# *521AE90802CC_51E8DC3E0361get_impl* end;//TddPicture.pm_GetFormat function TddPicture.pm_GetStream: TStream; //#UC START# *521AEA490067_51E8DC3E0361get_var* //#UC END# *521AEA490067_51E8DC3E0361get_var* begin //#UC START# *521AEA490067_51E8DC3E0361get_impl* if not f_IsBinary then ConvertToBin; Result:= f_Stream; //#UC END# *521AEA490067_51E8DC3E0361get_impl* end;//TddPicture.pm_GetStream procedure TddPicture.pm_SetStream(aValue: TStream); //#UC START# *521AEA490067_51E8DC3E0361set_var* //#UC END# *521AEA490067_51E8DC3E0361set_var* begin //#UC START# *521AEA490067_51E8DC3E0361set_impl* f_IsBinary:= True; aValue.Seek(0, 0); f_Stream.CopyFrom(aValue, aValue.Size); f_Stream.Position := 0; //#UC END# *521AEA490067_51E8DC3E0361set_impl* end;//TddPicture.pm_SetStream procedure TddPicture.pm_SetWidthInPixels(aValue: Integer); //#UC START# *55EE870702AD_51E8DC3E0361set_var* //#UC END# *55EE870702AD_51E8DC3E0361set_var* begin //#UC START# *55EE870702AD_51E8DC3E0361set_impl* f_WidthInPixels := aValue; //#UC END# *55EE870702AD_51E8DC3E0361set_impl* end;//TddPicture.pm_SetWidthInPixels procedure TddPicture.pm_SetHeightInPixels(aValue: Integer); //#UC START# *55EE872A0092_51E8DC3E0361set_var* //#UC END# *55EE872A0092_51E8DC3E0361set_var* begin //#UC START# *55EE872A0092_51E8DC3E0361set_impl* f_HeightInPixels := aValue; //#UC END# *55EE872A0092_51E8DC3E0361set_impl* end;//TddPicture.pm_SetHeightInPixels procedure TddPicture.CropPicture; //#UC START# *521AEAB901C0_51E8DC3E0361_var* var l_Pic: TImageEnView; x1, x2, y1, y2: Integer; l_DPIX, l_DPIY: Integer; //#UC END# *521AEAB901C0_51E8DC3E0361_var* begin //#UC START# *521AEAB901C0_51E8DC3E0361_impl* if (CropL <> 0) or (CropR <> 0) or (CropT <> 0) or (CropB <> 0) then begin l_Pic := TImageEnView.Create(nil); try l_Pic.IO.LoadFromStream(f_Stream); l_DPIX := l_Pic.DpiX; l_DPIY := l_Pic.DpiY; if l_Pic.DpiX > 96 then l_Pic.DpiX := 96; if l_Pic.DpiY > 96 then l_Pic.DpiY := 96; x1 := Twip2Pixel(CropL, l_PIC.DpiX); x2 := Twip2Pixel(CropR, l_PIC.DpiX); y1 := Twip2Pixel(CropT, l_PIC.DpiY); y2 := Twip2Pixel(CropB, l_PIC.DpiY); Height := 0; Width := 0; l_Pic.SelectionBase := iesbBitmap; l_Pic.Select(x1, y1, l_Pic.IO.Params.Width - x2, l_Pic.IO.Params.Height - y2, iespReplace); l_Pic.Proc.CropSel; if l_Pic.IO.Params.DPI > 96 then l_Pic.IO.Params.DPI := 96; f_Stream.Seek(0, 0); f_Stream.Size := 0; l_Pic.IO.SaveToStreamPNG(f_Stream); f_Stream.Seek(0, 0); finally FreeAndNil(l_Pic); end; end; // (CropL <> 0) or (CropR <> 0) or (CropT <> 0) or (CropB <> 0) //#UC END# *521AEAB901C0_51E8DC3E0361_impl* end;//TddPicture.CropPicture procedure TddPicture.ConvertToBin; //#UC START# *521AEACF0234_51E8DC3E0361_var* var l_Buf : PAnsiChar; l_Size: Integer; //#UC END# *521AEACF0234_51E8DC3E0361_var* begin //#UC START# *521AEACF0234_51E8DC3E0361_impl* if not f_Picture.Empty then begin l_Size := f_Picture.Len * 2 + 1; l3System.GetLocalMem(l_Buf, l_Size); try l3FillChar(l_Buf^, l_Size, 0); HexToBinEx(f_Picture, l_Buf, l_Size); f_Stream.Write(l_Buf^, l_Size); f_Stream.Seek(0, soBeginning); finally l3System.FreeLocalMem(l_Buf); end; f_Picture.Clear; end; f_IsBinary:= True; //#UC END# *521AEACF0234_51E8DC3E0361_impl* end;//TddPicture.ConvertToBin procedure TddPicture.ConvertToHex; //#UC START# *521AEAE60288_51E8DC3E0361_var* const l_EOL : PAnsiChar = cc_EOL; var l_Bin : array [0..8 * 1024 - 1] of AnsiChar; l_Hex : array [0..8 * 1024 * 2 - 1] of AnsiChar; l_Count : Longint; l_BinStream : TStream; l_HexStream : Tl3StringStream; //#UC END# *521AEAE60288_51E8DC3E0361_var* begin //#UC START# *521AEAE60288_51E8DC3E0361_impl* if f_Stream.Size > 0 then begin l_HexStream := Tl3StringStream.Create(f_Picture); try f_Stream.Seek(0, 0); l_BinStream := f_Stream; while true do begin l_Count := l_BinStream.Read(l_Bin, SizeOf(l_Bin)); if (l_Count = 0) then break; BinToHex(l_Bin, l_Hex, l_Count); l_HexStream.Write(l_Hex, l_Count * 2); end;//while true finally FreeAndNil(l_HexStream); end;//try..finally end; f_IsBinary:= False; //#UC END# *521AEAE60288_51E8DC3E0361_impl* end;//TddPicture.ConvertToHex procedure TddPicture.AddHexData(aHexStream: Tl3String); {* Добавляем строку с 16-ричными символами. } //#UC START# *5343AC66009C_51E8DC3E0361_var* var l_WMF : Tl3Metafile; l_Size : Int64; l_BinBuf : PAnsiChar; //#UC END# *5343AC66009C_51E8DC3E0361_var* begin //#UC START# *5343AC66009C_51E8DC3E0361_impl* if (aHexStream = nil) or (aHexStream.Len = 0) then Exit; l_Size := aHexStream.Len div 2; try l3System.GetLocalMem(l_BinBuf, l_Size); try l_Size := HexToBinEx(aHexStream, l_BinBuf, l_Size); // Буфер может стать меньше... if f_NeedWMFHeader then f_Stream.Write(f_WMFHeader, SizeOf(f_WMFHeader)); f_Stream.Write(l_BinBuf^, l_Size); finally l3System.FreeLocalMem(l_BinBuf); end; if f_Format = pictWMF then // Старый WMF, конвертируем в EMF begin l_WMF := Tl3Metafile.Create; try f_Stream.Seek(0, soBeginning); if f_NeedWMFHeader then begin l_WMF.LoadWMFFromStream(Stream); f_NeedWMFHeader := False; end // if f_NeedWMFHeader then else l_WMF.LoadFromStream(f_Stream); l_WMF.Enhanced := True; f_Stream.Seek(0, soBeginning); f_Stream.Size := 0; l_WMF.SaveToStream(f_Stream); l_Size := f_Stream.Size; finally l3Free(l_WMF); end; end; // if f_NeedWMFHeader then f_IsBinary := True; {$IFDEF InsiderTest} if f_Format > pictNONE then SavePicture2File(l_Size); {$ENDIF InsiderTest} except on EInvalidGraphic do f_Format := pictNONE; end; //#UC END# *5343AC66009C_51E8DC3E0361_impl* end;//TddPicture.AddHexData function TddPicture.HexToBinEx(aText: Tl3String; Buffer: PAnsiChar; BufSize: Integer): Integer; {* Преобразование из 16-ричной текстовй строки в бинарные данные с пропуском символов переноса стоки и поддержки заглавных букв. } //#UC START# *5343AD9A009A_51E8DC3E0361_var* const Convert: array['0'..'f'] of SmallInt = ( 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, -1,10,11,12,13,14,15); var I : Integer; l_Char : AnsiChar; l_Next : AnsiChar; l_CharSkipper: TddHexCharReader; //#UC END# *5343AD9A009A_51E8DC3E0361_var* begin //#UC START# *5343AD9A009A_51E8DC3E0361_impl* I := BufSize; Result := 0; l_CharSkipper := TddHexCharReader.Create; try l_CharSkipper.Init(aText); while I > 0 do begin l_Char := l_CharSkipper.GetChar; if l_Char = #0 then Break; l_Next := l_CharSkipper.GetChar; if l_Next = #0 then Break; Buffer[0] := AnsiChar((Convert[l_Char] shl 4) + Convert[l_Next]); Inc(Buffer); Dec(I); end; // while I > 0 do Result := BufSize - I; finally l3Free(l_CharSkipper); end; //#UC END# *5343AD9A009A_51E8DC3E0361_impl* end;//TddPicture.HexToBinEx function TddPicture.Try2ReadKnownPicture(const aFiler: Tl3CustomFiler): Tl3String; {* Пытаемся передать обработку "знающим" объектам. } //#UC START# *5346587A0043_51E8DC3E0361_var* //#UC END# *5346587A0043_51E8DC3E0361_var* begin //#UC START# *5346587A0043_51E8DC3E0361_impl* if f_Format = pictEMF then Result := Try2ReadEMF(aFiler) else if f_Format = pictWMF then Result := Try2ReadWMF(aFiler) else Result := nil; //#UC END# *5346587A0043_51E8DC3E0361_impl* end;//TddPicture.Try2ReadKnownPicture function TddPicture.Try2ReadEMF(const aFiler: Tl3CustomFiler): Tl3String; {* Чтение текстового 16-ричного потока EMF. } //#UC START# *534658AC032F_51E8DC3E0361_var* var l_BufSize : Integer; l_EnhHeader : TEnhMetaheader; l_HeaderStr : Tl3String; l_HeaderSize: Integer; //#UC END# *534658AC032F_51E8DC3E0361_var* begin //#UC START# *534658AC032F_51E8DC3E0361_impl* Result := nil; l_HeaderSize := SizeOf(l_EnhHeader); l_BufSize := l_HeaderSize * 2; l_HeaderStr := aFiler.MakeReadString(l_BufSize, CP_ANSI); try HexToBinEx(l_HeaderStr, @l_EnhHeader, l_HeaderSize); finally l3Free(l_HeaderStr) end; if l_EnhHeader.dSignature = ENHMETA_SIGNATURE then begin aFiler.UngetChars(l_BufSize); Result := aFiler.MakeReadString(l_EnhHeader.nBytes, CP_ANSI); end // if l_EnhHeader.dSignature = ENHMETA_SIGNATURE then else begin aFiler.UngetChars(l_BufSize); f_Format := -1; // // Пусть определяет ImageEn... end; //#UC END# *534658AC032F_51E8DC3E0361_impl* end;//TddPicture.Try2ReadEMF {$If Defined(InsiderTest)} procedure TddPicture.SavePicture2File(aSize: Integer); //#UC START# *534BBC6B006F_51E8DC3E0361_var* var l_Str : AnsiString; l_FileStream : TFileStream; //#UC END# *534BBC6B006F_51E8DC3E0361_var* begin //#UC START# *534BBC6B006F_51E8DC3E0361_impl* if TddPicturePathListner.Instance.EnableSave then begin f_Stream.Position := 0; l_Str := TddPicturePathListner.Instance.GetUniqPictureNameWithPath(f_Format, True); l_FileStream := TFileStream.Create(l_Str, fmCreate); try l_FileStream.CopyFrom(f_Stream, aSize); finally l3Free(l_FileStream); end; TddPicturePathListner.Instance.AddPicturePath(l_Str); end; // if TddPicturePathListner.Instance.EnableSave then //#UC END# *534BBC6B006F_51E8DC3E0361_impl* end;//TddPicture.SavePicture2File {$IfEnd} // Defined(InsiderTest) function TddPicture.Try2ReadWMF(const aFiler: Tl3CustomFiler): Tl3String; {* Чтение текстового 16-ричного потока WMF. } //#UC START# *54B77D750163_51E8DC3E0361_var* var l_WMFHeader : Tl3MetafileHeader; l_ReverseSize: Integer; l_MetaHeader : TMetaHeader; function lp_ReadMETA_PLACEABLERecord: Boolean; var l_BufSize : Integer; l_HeaderStr : Tl3String; l_HeaderSize: Integer; begin Result := False; l_HeaderSize := SizeOf(l_WMFHeader); l_BufSize := l_HeaderSize * 2; l_HeaderStr := aFiler.MakeReadString(l_BufSize, CP_ANSI); try HexToBinEx(l_HeaderStr, @l_WMFHeader, l_HeaderSize); if l3IsValidMetafileHeader(l_WMFHeader) then begin Result := True; l_ReverseSize := l_BufSize; end // if IsValidMetafileHeader(l_WMFHeader) then else aFiler.UngetChars(l_BufSize); finally l3Free(l_HeaderStr) end; end; function lp_ReadMETA_HEADERRecord: Boolean; var l_BufSize : Integer; l_HeaderStr : Tl3String; l_HeaderSize: Integer; begin Result := False; l_HeaderSize := SizeOf(l_MetaHeader); l_BufSize := l_HeaderSize * 2; Inc(l_ReverseSize, l_BufSize); l_HeaderStr := aFiler.MakeReadString(l_BufSize, CP_ANSI); try HexToBinEx(l_HeaderStr, @l_MetaHeader, l_HeaderSize); Result := l3IsValidMETA_HEADERRecord(l_MetaHeader); l_ReverseSize := l_BufSize; finally l3Free(l_HeaderStr) end; end; var l_StrData: Tl3String absolute Result; procedure lp_ReadData(aReverseSize: Integer); begin aFiler.UngetChars(l_ReverseSize); Result := aFiler.MakeReadString(l_MetaHeader.mtSize, CP_ANSI); end; procedure lp_InitMETA_PLACEABLER; begin if (f_Width >= High(SmallInt)) or (f_Height >= High(SmallInt)) then Exit; l3FillChar(f_WMFHeader, SizeOf(f_WMFHeader), 0); f_WMFHeader.Key := c_WMFKey; f_WMFHeader.Inch := l3DefaultWMFDPI; with f_WMFHeader.Box do begin Right := f_Width; Bottom := f_Height; end; // with f_WMFHeader.Box do f_WMFHeader.CheckSum := l3ComputeAldusChecksum(f_WMFHeader); f_NeedWMFHeader := True; end; var l_MetaFileH : TMetaHeader; //#UC END# *54B77D750163_51E8DC3E0361_var* begin //#UC START# *54B77D750163_51E8DC3E0361_impl* Result := nil; l_ReverseSize := 0; if not lp_ReadMETA_PLACEABLERecord then lp_InitMETA_PLACEABLER; if lp_ReadMETA_HEADERRecord then lp_ReadData(l_ReverseSize) else begin if Result = nil then aFiler.UngetChars(l_ReverseSize); f_NeedWMFHeader := False; f_Format := -1; // Пусть определяет ImageEn... end; //#UC END# *54B77D750163_51E8DC3E0361_impl* end;//TddPicture.Try2ReadWMF function TddPicture.Clone(aPAP: TddParagraphProperty): TddPicture; //#UC START# *54F71A0201D3_51E8DC3E0361_var* //#UC END# *54F71A0201D3_51E8DC3E0361_var* begin //#UC START# *54F71A0201D3_51E8DC3E0361_impl* Result := TddPicture.Create(f_Destination); Result.Assign(Self); if aPAP <> nil then Result.PAP := aPAP; //#UC END# *54F71A0201D3_51E8DC3E0361_impl* end;//TddPicture.Clone class function TddPicture.CreateFromFile(const aPath: AnsiString): TddPicture; //#UC START# *554C7AD301AD_51E8DC3E0361_var* var l_Picture : TddPicture; l_FileStream: TFileStream; //#UC END# *554C7AD301AD_51E8DC3E0361_var* begin //#UC START# *554C7AD301AD_51E8DC3E0361_impl* Result := nil; if not FileExists(aPath) then Exit; l_FileStream := TFileStream.Create(aPath, fmOpenRead); try l_Picture := TddPicture.Create(nil); l_Picture.Stream.CopyFrom(l_FileStream, l_FileStream.Size); Result := l_Picture; finally l3Free(l_FileStream); end; //#UC END# *554C7AD301AD_51E8DC3E0361_impl* end;//TddPicture.CreateFromFile procedure TddPicture.Try2ReadBinaryData(const aFiler: Tl3CustomFiler; aSize: Integer); //#UC START# *55D6FFCC03AA_51E8DC3E0361_var* var l_Size : Integer; l_Buffer: PAnsiChar; //#UC END# *55D6FFCC03AA_51E8DC3E0361_var* begin //#UC START# *55D6FFCC03AA_51E8DC3E0361_impl* l3System.GetLocalMem(l_Buffer, aSize); try aFiler.Read(l_Buffer, aSize); Stream.WriteBuffer(l_Buffer^, aSize); finally l3System.FreeLocalMem(l_Buffer); end; f_IsBinary := True; //#UC END# *55D6FFCC03AA_51E8DC3E0361_impl* end;//TddPicture.Try2ReadBinaryData procedure TddPicture.Try2RecalcPictureProps; //#UC START# *55EE87A90390_51E8DC3E0361_var* var l_Pic : TImageEnView; l_DPIX : Integer; l_DPIY : Integer; l_NeedSave: Boolean; //#UC END# *55EE87A90390_51E8DC3E0361_var* begin //#UC START# *55EE87A90390_51E8DC3E0361_impl* l_Pic := TImageEnView.Create(nil); try l_Pic.IO.LoadFromStream(f_Stream); l_NeedSave := False; l_DPIX := l_Pic.DpiX; l_DPIY := l_Pic.DpiY; if (l_DPIY <> 0) and (l_DPIY <> 0) then begin f_Width := Pixel2Twip(l_Pic.Width); f_Height := Pixel2Twip(Trunc(l_Pic.Height * f_HeightInPixels / f_WidthInPixels)); if l_DPIX > 96 then begin l_Pic.DpiX := 96; l_NeedSave := True; end; // if l_Pic.DpiX > 96 then if l_DPIY > 96 then begin l_Pic.DpiY := 96; l_NeedSave := True; end; // if l_Pic.DpiY > 96 then if l_NeedSave then begin f_Stream.Seek(0, 0); f_Stream.Size := 0; l_Pic.IO.SaveToStreamPNG(f_Stream); f_Stream.Seek(0, 0); end; // if l_NeedSave then end; // if (l_DPIY <> 0) and (l_DPIY <> 0) then finally FreeAndNil(l_Pic); end; //#UC END# *55EE87A90390_51E8DC3E0361_impl* end;//TddPicture.Try2RecalcPictureProps procedure TddPicture.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_51E8DC3E0361_var* //#UC END# *479731C50290_51E8DC3E0361_var* begin //#UC START# *479731C50290_51E8DC3E0361_impl* FreeAndNil(f_Picture); FreeAndNil(f_Stream); inherited; //#UC END# *479731C50290_51E8DC3E0361_impl* end;//TddPicture.Cleanup function TddPicture.GetEmpty: Boolean; //#UC START# *4A54E03B009A_51E8DC3E0361_var* //#UC END# *4A54E03B009A_51E8DC3E0361_var* begin //#UC START# *4A54E03B009A_51E8DC3E0361_impl* Result := f_Stream.Size = 0; //#UC END# *4A54E03B009A_51E8DC3E0361_impl* end;//TddPicture.GetEmpty procedure TddPicture.Clear; //#UC START# *518A48F500CF_51E8DC3E0361_var* //#UC END# *518A48F500CF_51E8DC3E0361_var* begin //#UC START# *518A48F500CF_51E8DC3E0361_impl* inherited; f_Picture.Clear; f_Stream.Seek(0, 0); f_Stream.Size:= 0; f_Format := -1; f_Height := 0; f_Width := 0; f_ScaleX := 100; f_ScaleY := 100; f_GoalX := 0; f_GoalY := 0; f_BPP := 0; f_CropL := 0; f_CropR := 0; f_CropT := 0; f_CropB := 0; f_NeedWMFHeader := False; //#UC END# *518A48F500CF_51E8DC3E0361_impl* end;//TddPicture.Clear procedure TddPicture.Write2Generator(const Generator: Ik2TagGenerator; aNeedProcessRow: Boolean; LiteVersion: TddLiteVersion); //#UC START# *518A504F00F5_51E8DC3E0361_var* var l_Width : Integer; l_Height : Integer; //#UC END# *518A504F00F5_51E8DC3E0361_var* begin //#UC START# *518A504F00F5_51E8DC3E0361_impl* if Width = 0 then l_Width := 0 else l_Width := l3MulDiv(Width, ScaleX, 100); if Height = 0 then l_Height := 0 else l_Height := l3MulDiv(Height, ScaleY, 100); if (l_Width = 0) and (l_Height = 0) then if (f_WidthInPixels > 0) and (f_HeightInPixels > 0) then begin Try2RecalcPictureProps; l_Height := Height; l_Width := Width; end; // if (f_WidthInPixel > 0) and (f_HeightInPixel > 0) then if (l_Width > 0) and (l_Height > 0) then begin CropPicture; if (f_Destination = nil) or (l_Width >= f_Destination.GetMinPictureWidth) or (l_Height >= f_Destination.GetMinPictureHeight) then begin StartBitmapPara(Generator); try Generator.AddIntegerAtom(k2_tiExternalHandle, ExternalHandle); Generator.AddStringAtom(k2_tiExternalpath, ExternalPath); Generator.AddIntegerAtom(k2_tiWidth, l_Width); Generator.AddIntegerAtom(k2_tiHeight, l_Height); with PAP do begin case Just of justR: Generator.AddIntegerAtom(k2_tiJustification, Ord(ev_itRight)); justC: Generator.AddIntegerAtom(k2_tiJustification, Ord(ev_itCenter)); justF: Generator.AddIntegerAtom(k2_tiJustification, Ord(ev_itWidth)); else Generator.AddIntegerAtom(k2_tiJustification, Ord(ev_itLeft)); end; { case Just} Border.Write2Generator(Generator); end; { with } if not f_IsBinary then ConvertToBin; Generator.AddStreamAtom(k2_tiData, Stream); finally Generator.Finish; end; end; // if (l_Width > f_Destination.GetMinPictureWidth) and (l_Width < f_Destination.GetMinPictureWidth) then end; // if (l_Width >= 0) and (l_Height >= 0) then //#UC END# *518A504F00F5_51E8DC3E0361_impl* end;//TddPicture.Write2Generator constructor TddPicture.Create(aDetination: TddCustomDestination); //#UC START# *51E91BA80051_51E8DC3E0361_var* //#UC END# *51E91BA80051_51E8DC3E0361_var* begin //#UC START# *51E91BA80051_51E8DC3E0361_impl* inherited Create(aDetination); f_Picture := Tl3String.Create; f_Format := -1; f_Stream := Tl3MemoryStream.Make; f_IsBinary := False; f_ScaleX := 100; f_ScaleY := 100; f_NeedWMFHeader := False; //#UC END# *51E91BA80051_51E8DC3E0361_impl* end;//TddPicture.Create function TddPicture.IsTextPara: Boolean; //#UC START# *5268D5950076_51E8DC3E0361_var* //#UC END# *5268D5950076_51E8DC3E0361_var* begin //#UC START# *5268D5950076_51E8DC3E0361_impl* Result := False; //#UC END# *5268D5950076_51E8DC3E0361_impl* end;//TddPicture.IsTextPara function TddPicture.IsPicture: Boolean; //#UC START# *5268D62B022C_51E8DC3E0361_var* //#UC END# *5268D62B022C_51E8DC3E0361_var* begin //#UC START# *5268D62B022C_51E8DC3E0361_impl* Result := True; //#UC END# *5268D62B022C_51E8DC3E0361_impl* end;//TddPicture.IsPicture function TddPicture.GetLastPara: TddDocumentAtom; //#UC START# *5268DBC503E2_51E8DC3E0361_var* //#UC END# *5268DBC503E2_51E8DC3E0361_var* begin //#UC START# *5268DBC503E2_51E8DC3E0361_impl* Result := nil; //#UC END# *5268DBC503E2_51E8DC3E0361_impl* end;//TddPicture.GetLastPara procedure TddPicture.Assign(const aDocAtomObj: Tl3ProtoObject); //#UC START# *528C8C2F02D9_51E8DC3E0361_var* var l_Count : Integer; l_Picture: TddPicture; //#UC END# *528C8C2F02D9_51E8DC3E0361_var* begin //#UC START# *528C8C2F02D9_51E8DC3E0361_impl* if aDocAtomObj is TddPicture then begin l_Picture := TddPicture(aDocAtomObj); if l_Picture.Picture.Empty then begin l_Count := f_Stream.CopyFrom(l_Picture.Stream, 0); f_Stream.Seek(0, 0); f_IsBinary := l_Picture.IsBinary; end // if TddPicture(aDocAtomObj).Picture.Empty then else f_Picture.Assign(l_Picture.Picture); f_Format := l_Picture.Format; f_Height := l_Picture.Height; f_Width := l_Picture.Width; f_ScaleX := l_Picture.ScaleX; f_ScaleY := l_Picture.ScaleY; f_GoalX := l_Picture.GoalX; f_GoalY := l_Picture.GoalY; f_BPP := l_Picture.BPP; f_CropL := l_Picture.CropL; f_CropR := l_Picture.CropR; f_CropT := l_Picture.CropT; f_CropB := l_Picture.CropB; f_HeightInPixels := l_Picture.f_HeightInPixels; f_WidthInPixels := l_Picture.f_WidthInPixels; end // if aDocAtomObj is TddPicture then else inherited; //#UC END# *528C8C2F02D9_51E8DC3E0361_impl* end;//TddPicture.Assign function TddPicture.CanWrite: Boolean; {* Проверяет возможность записи объекта. Например, если у картинки нет размеров ширины и высоты, то она не записывается. } //#UC START# *55D71C0C0164_51E8DC3E0361_var* //#UC END# *55D71C0C0164_51E8DC3E0361_var* begin //#UC START# *55D71C0C0164_51E8DC3E0361_impl* Result := (Width <> 0) and (Height <> 0) //#UC END# *55D71C0C0164_51E8DC3E0361_impl* end;//TddPicture.CanWrite procedure TddPicture.ClearFields; begin ExternalPath := ''; inherited; end;//TddPicture.ClearFields end.
unit l3EventedRecListView; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "L3" // Автор: Люлин А.В. // Модуль: "w:/common/components/rtl/Garant/L3/l3EventedRecListView.pas" // Начат: 08.06.2011 23:06 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi Low Level::L3::RecListView::Tl3EventedRecListView // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\L3\l3Define.inc} interface uses l3ProtoPtrRecListPrim, l3CustomRecListView ; type Tl3CompareItemsEvent = function (anItem1: PItemType; anItem2: PItemType): Integer of object; Tl3EventedRecListView = class(Tl3CustomRecListView) private // private fields f_CompareItemsEvent : Tl3CompareItemsEvent; protected // realized methods function CompareRecs(aRec1: PItemType; aRec2: PItemType): Integer; override; public // public methods constructor Create(aList: Tl3ProtoPtrRecListPrim; aCompareItemsEvent: Tl3CompareItemsEvent); reintroduce; end;//Tl3EventedRecListView implementation // start class Tl3EventedRecListView constructor Tl3EventedRecListView.Create(aList: Tl3ProtoPtrRecListPrim; aCompareItemsEvent: Tl3CompareItemsEvent); //#UC START# *4DEFC86E0263_4DEFC812022F_var* //#UC END# *4DEFC86E0263_4DEFC812022F_var* begin //#UC START# *4DEFC86E0263_4DEFC812022F_impl* Assert(Assigned(aCompareItemsEvent)); f_CompareItemsEvent := aCompareItemsEvent; inherited Create(aList); //#UC END# *4DEFC86E0263_4DEFC812022F_impl* end;//Tl3EventedRecListView.Create function Tl3EventedRecListView.CompareRecs(aRec1: PItemType; aRec2: PItemType): Integer; //#UC START# *4DEFCA7603C4_4DEFC812022F_var* //#UC END# *4DEFCA7603C4_4DEFC812022F_var* begin //#UC START# *4DEFCA7603C4_4DEFC812022F_impl* Result := f_CompareItemsEvent(aRec1, aRec2); //#UC END# *4DEFCA7603C4_4DEFC812022F_impl* end;//Tl3EventedRecListView.CompareRecs end.
namespace Sugar; interface type Range = public record {$IF TOFFEE}mapped to Foundation.NSRange{$ENDIF} public class method MakeRange(aLocation, aLength: Integer): Range; property Location: Integer {$IF TOFFEE}read mapped.location write mapped.location{$ENDIF}; property Length: Integer {$IF TOFFEE} read mapped.length write mapped.length{$ENDIF}; end; RangeHelper = public static class public method Validate(aRange: Range; BufferSize: Integer); end; Binary = public class {$IF ECHOES}mapped to System.IO.MemoryStream{$ELSEIF TOFFEE}mapped to Foundation.NSMutableData{$ENDIF} {$IF COOPER} private fData: java.io.ByteArrayOutputStream := new java.io.ByteArrayOutputStream(); {$ENDIF} public constructor; {$IF TOFFEE OR ECHOES}mapped to constructor();{$ELSE}empty;{$ENDIF} constructor(anArray: array of Byte); constructor(Bin: Binary); method Assign(Bin: Binary); method Clear; method &Read(Range: Range): array of Byte; method &Read(Count: Integer): array of Byte; method Subdata(Range: Range): Binary; method &Write(Buffer: array of Byte; Offset: Integer; Count: Integer); method &Write(Buffer: array of Byte; Count: Integer); method &Write(Buffer: array of Byte); method &Write(Bin: Binary); method ToArray: array of Byte; property Length: Integer read {$IF COOPER}fData.size{$ELSEIF ECHOES}mapped.Length{$ELSEIF TOFFEE}mapped.length{$ENDIF}; {$IF TOFFEE} operator Implicit(aData: NSData): Binary; {$ENDIF} end; implementation { Range } class method Range.MakeRange(aLocation: Integer; aLength: Integer): Range; begin exit new Range(Location := aLocation, Length := aLength); end; { RangeHelper } class method RangeHelper.Validate(aRange: Range; BufferSize: Integer); begin if aRange.Location < 0 then raise new SugarArgumentOutOfRangeException(ErrorMessage.NEGATIVE_VALUE_ERROR, "Location"); if aRange.Length < 0 then raise new SugarArgumentOutOfRangeException(ErrorMessage.NEGATIVE_VALUE_ERROR, "Length"); if aRange.Location >= BufferSize then raise new SugarArgumentOutOfRangeException(ErrorMessage.ARG_OUT_OF_RANGE_ERROR, "Location"); if aRange.Length > BufferSize then raise new SugarArgumentOutOfRangeException(ErrorMessage.ARG_OUT_OF_RANGE_ERROR, "Length"); if aRange.Location + aRange.Length > BufferSize then raise new SugarArgumentOutOfRangeException(ErrorMessage.OUT_OF_RANGE_ERROR, aRange.Location, aRange.Length, BufferSize); end; { Binary } constructor Binary(anArray: array of Byte); begin if anArray = nil then raise new SugarArgumentNullException("Array"); {$IF COOPER} &Write(anArray, anArray.length); {$ELSEIF ECHOES} var ms := new System.IO.MemoryStream; ms.Write(anArray, 0, anArray.Length); exit ms; {$ELSEIF TOFFEE} exit NSMutableData.dataWithBytes(anArray) length(length(anArray)); {$ENDIF} end; constructor Binary(Bin: Binary); begin SugarArgumentNullException.RaiseIfNil(Bin, "Bin"); {$IF COOPER} Assign(Bin); {$ELSEIF ECHOES} var ms := new System.IO.MemoryStream; System.IO.MemoryStream(Bin).WriteTo(ms); exit ms; {$ELSEIF TOFFEE} exit NSMutableData.dataWithData(Bin); {$ENDIF} end; method Binary.Assign(Bin: Binary); begin {$IF COOPER} Clear; if Bin <> nil then fData.Write(Bin.ToArray, 0, Bin.Length); {$ELSEIF ECHOES} Clear; if Bin <> nil then System.IO.MemoryStream(Bin).WriteTo(System.IO.MemoryStream(self)); {$ELSEIF TOFFEE} mapped.setData(Bin); {$ENDIF} end; method Binary.Read(Range: Range): array of Byte; begin if Range.Length = 0 then exit []; RangeHelper.Validate(Range, self.Length); result := new Byte[Range.Length]; {$IF COOPER} System.arraycopy(fData.toByteArray, Range.Location, result, 0, Range.Length); {$ELSEIF ECHOES} mapped.Position := Range.Location; mapped.Read(result, 0, Range.Length); {$ELSEIF TOFFEE} mapped.getBytes(result) range(Range); {$ENDIF} end; method Binary.Read(Count: Integer): array of Byte; begin exit &Read(Range.MakeRange(0, Math.Min(Count, self.Length))); end; method Binary.Subdata(Range: Range): Binary; begin exit new Binary(&Read(Range)); end; method Binary.&Write(Buffer: array of Byte; Offset: Integer; Count: Integer); begin if Buffer = nil then raise new SugarArgumentNullException("Buffer"); if Count = 0 then exit; RangeHelper.Validate(Range.MakeRange(Offset, Count), Buffer.Length); {$IF COOPER} fData.write(Buffer, Offset, Count); {$ELSEIF ECHOES} mapped.Seek(0, System.IO.SeekOrigin.End); mapped.Write(Buffer, Offset, Count); {$ELSEIF TOFFEE} mapped.appendBytes(@Buffer[Offset]) length(Count); {$ENDIF} end; method Binary.Write(Buffer: array of Byte; Count: Integer); begin &Write(Buffer, 0, Count); end; method Binary.&Write(Buffer: array of Byte); begin &Write(Buffer, RemObjects.Oxygene.System.length(Buffer)); end; method Binary.Write(Bin: Binary); begin SugarArgumentNullException.RaiseIfNil(Bin, "Bin"); {$IF COOPER OR ECHOES} &Write(Bin.ToArray, Bin.Length); {$ELSEIF TOFFEE} mapped.appendData(Bin); {$ENDIF} end; method Binary.ToArray: array of Byte; begin {$IF COOPER} exit fData.toByteArray; {$ELSEIF ECHOES} exit mapped.ToArray; {$ELSEIF TOFFEE} result := new Byte[mapped.length]; mapped.getBytes(result) length(mapped.length); {$ENDIF} end; method Binary.Clear; begin {$IF COOPER} fData.reset; {$ELSEIF ECHOES} mapped.SetLength(0); mapped.Position := 0; {$ELSEIF TOFFEE} mapped.setLength(0); {$ENDIF} end; {$IF TOFFEE} operator Binary.Implicit(aData: NSData): Binary; begin if aData is NSMutableData then result := aData as NSMutableData else result := aData:mutableCopy; end; {$ENDIF} end.
unit Movimentacoes; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Vcl.StdCtrls, Vcl.Grids, Vcl.DBGrids, Vcl.ComCtrls; type TFrmMovimentacoes = class(TForm) Label1: TLabel; Label2: TLabel; Label3: TLabel; Label4: TLabel; lblTotal: TLabel; Label7: TLabel; lblVlrEntradas: TLabel; Label8: TLabel; lblVlrSaidas: TLabel; dataInicial: TDateTimePicker; gridVendas: TDBGrid; dataFinal: TDateTimePicker; cbEntradaSaida: TComboBox; procedure FormShow(Sender: TObject); procedure cbEntradaSaidaChange(Sender: TObject); procedure dataInicialChange(Sender: TObject); procedure dataFinalChange(Sender: TObject); private { Private declarations } procedure buscarTudo; procedure buscarData; procedure totalizarEntradas; procedure totalizarSaidas; procedure totalizar; procedure formatarGrid; public { Public declarations } end; var FrmMovimentacoes: TFrmMovimentacoes; TotEntradas: real; TotSaidas: real; implementation {$R *.dfm} uses Modulo; procedure TFrmMovimentacoes.buscarData; begin totalizarEntradas; totalizarSaidas; totalizar; dm.query_mov.Close; dm.query_mov.SQL.Clear; if cbEntradaSaida.Text = 'Tudo' then begin dm.query_mov.SQL.Add('select * from movimentacoes where data >= :dataInicial and data <= :dataFinal order by id desc') ; end else begin dm.query_mov.SQL.Add('select * from movimentacoes where data >= :dataInicial and data <= :dataFinal and tipo = :tipo order by id desc') ; dm.query_mov.ParamByName('tipo').Value := cbEntradaSaida.Text; end; dm.query_mov.ParamByName('dataInicial').Value := FormatDateTime('yyyy/mm/dd', dataInicial.Date); dm.query_mov.ParamByName('dataFinal').Value := FormatDateTime('yyyy/mm/dd', dataFinal.Date); dm.query_mov.Open; formatarGrid; end; procedure TFrmMovimentacoes.buscarTudo; begin totalizarEntradas; totalizarSaidas; totalizar; dm.query_mov.Close; dm.query_mov.SQL.Clear; dm.query_mov.SQL.Add('select * from movimentacoes WHERE data = curDate() order by id desc') ; dm.query_mov.Open; TFloatField( dm.query_mov.FieldByName('valor')).DisplayFormat:='R$ #,,,,0.00'; formatarGrid; end; procedure TFrmMovimentacoes.cbEntradaSaidaChange(Sender: TObject); begin buscarData; end; procedure TFrmMovimentacoes.dataFinalChange(Sender: TObject); begin buscarData; end; procedure TFrmMovimentacoes.dataInicialChange(Sender: TObject); begin buscarData; end; procedure TFrmMovimentacoes.formatarGrid; begin gridVendas.Columns.Items[0].FieldName := 'id'; gridVendas.Columns.Items[0].Title.Caption := 'Id'; gridVendas.Columns.Items[0].Visible := false; gridVendas.Columns.Items[1].FieldName := 'tipo'; gridVendas.Columns.Items[1].Title.Caption := 'Tipo'; gridVendas.Columns.Items[2].FieldName := 'movimento'; gridVendas.Columns.Items[2].Title.Caption := 'Movimento'; gridVendas.Columns.Items[3].FieldName := 'valor'; gridVendas.Columns.Items[3].Title.Caption := 'Valor'; gridVendas.Columns.Items[4].FieldName := 'funcionario'; gridVendas.Columns.Items[4].Title.Caption := 'Funcionário'; gridVendas.Columns.Items[5].FieldName := 'data'; gridVendas.Columns.Items[5].Title.Caption := 'Data'; gridVendas.Columns.Items[6].Visible := false; end; procedure TFrmMovimentacoes.FormShow(Sender: TObject); begin lblVlrEntradas.Caption := FormatFloat('R$ #,,,,0.00', strToFloat(lblVlrEntradas.Caption)); lblVlrSaidas.Caption := FormatFloat('R$ #,,,,0.00', strToFloat(lblVlrSaidas.Caption)); lblTotal.Caption := FormatFloat('R$ #,,,,0.00', strToFloat(lblTotal.Caption)); cbEntradaSaida.ItemIndex := 0; dm.tb_mov.Active := False; dm.tb_mov.Active := True; dataInicial.Date := Date; dataFinal.Date := Date; totalizarEntradas; totalizarSaidas; totalizar; buscarTudo; end; procedure TFrmMovimentacoes.totalizar; var tot: real; begin tot := TotEntradas - TotSaidas; if tot >= 0 then begin lblTotal.Font.Color := clGreen; end else begin lblTotal.Font.Color := clRed; end; lblTotal.Caption := FormatFloat('R$ #,,,,0.00', tot); end; procedure TFrmMovimentacoes.totalizarEntradas; var tot: real; begin dm.query_mov.Close; dm.query_mov.SQL.Clear; dm.query_mov.SQL.Add('select sum(valor) as total from movimentacoes where data >= :dataInicial and data <= :dataFinal and tipo = "Entrada" ') ; dm.query_mov.ParamByName('dataInicial').Value := FormatDateTime('yyyy/mm/dd', dataInicial.Date); dm.query_mov.ParamByName('dataFinal').Value := FormatDateTime('yyyy/mm/dd', dataFinal.Date); dm.query_mov.Prepare; dm.query_mov.Open; tot := dm.query_mov.FieldByName('total').AsFloat; TotEntradas := tot; lblVlrEntradas.Caption := FormatFloat('R$ #,,,,0.00', tot); end; procedure TFrmMovimentacoes.totalizarSaidas; var tot: real; begin dm.query_mov.Close; dm.query_mov.SQL.Clear; dm.query_mov.SQL.Add('select sum(valor) as total from movimentacoes where data >= :dataInicial and data <= :dataFinal and tipo = "Saída" ') ; dm.query_mov.ParamByName('dataInicial').Value := FormatDateTime('yyyy/mm/dd', dataInicial.Date); dm.query_mov.ParamByName('dataFinal').Value := FormatDateTime('yyyy/mm/dd', dataFinal.Date); dm.query_mov.Prepare; dm.query_mov.Open; tot := dm.query_mov.FieldByName('total').AsFloat; TotSaidas := tot; lblVlrSaidas.Caption := FormatFloat('R$ #,,,,0.00', tot); end; end.
program tp1ej7; const corte = -1; type novela = record codigo:integer; nombre:string; genero:string; precio:real; end; bin_novela = file of novela; procedure leerNovela(var n:novela); begin with n do begin writeln('codigo: ');readln(codigo); if (codigo <> corte) then begin writeln('nombre: ');readln(nombre); writeln('genero: ');readln(genero); writeln('precio: ');readln(precio); writeln('-----------'); end; end; end; procedure crearBinarioDesdeTxt(var archivo:bin_novela;var txt:Text); var n:novela; begin reset(txt); Rewrite(archivo); while(not eof(txt)) do begin with n do begin readln(txt, codigo, precio, genero); readln(txt,nombre); write(archivo, n); end; end; close(archivo); close(txt); end; procedure agregarNovela(var archivo:bin_novela); var n:novela; begin reset(archivo); leerNovela(n); while(n.codigo <> corte) do begin seek(archivo, FileSize(archivo) - 1); write(archivo, n); leerNovela(n); end; end; procedure modificarNovela(var archivo:bin_novela); var n:novela; encontro: boolean; codigo, opcion:integer; begin opcion := -1; encontro:=false; reset(archivo); writeln('Ingrese el codigo de la novela que desea modificar: '); ReadLn(codigo); while(not eof(archivo) and not encontro) do begin read(archivo, n); if(codigo = n.codigo) then begin encontro := true; end; end; if encontro then begin while(opcion <> 0) do begin writeln('Ingrese el campo a modificar y su nuevo valor o 0 para salir: '); writeln('1. Nombre'); writeln('2. Precio'); writeln('3. Genero'); readln(opcion); case opcion of 1: ReadLn(n.nombre); 2: ReadLn(n.precio); 3: ReadLn(n.genero); end; Write(archivo, n); Writeln('Registro modificado: '); with n do begin writeln(nombre:5, codigo:5, precio:4:2, genero); end; end; end else Writeln('No se encontro ninguna novela con ese codigo'); end; var novelas_binario_logico: bin_novela; novelas_txt_logico: Text; opcion:integer; begin Assign(novelas_binario_logico, 'novelas'); Assign(novelas_txt_logico, 'novelas.txt'); opcion := -1; while opcion <> 0 do begin writeln('1. Crear un archivo binario a partir a partir del archivo novelas.txt'); writeln('2. Actualizar contenido de archivo novelas'); ReadLn(opcion); case opcion of 1: crearBinarioDesdeTxt(novelas_binario_logico, novelas_txt_logico); 2: modificarNovela(novelas_binario_logico); end; end; end.
unit Model.PlanilhaMovimentacaoJornal; interface uses Generics.Collections, System.Classes, System.SysUtils, Common.Utils; type TPlanilhaListagem = class private FLogradouro: String; FCodigoAssinante: String; FBairro: String; FNomeAssinante: String; FSiglaProduto: String; FComplemento: String; FModalidade: String; FDescricaoStatus: String; FDescricaoAgente: String; FCodigoAgente: String; public property CodigoAgente: String read FCodigoAgente write FCodigoAgente; property DescricaoAgente: String read FDescricaoAgente write FDescricaoAgente; property DescricaoStatus: String read FDescricaoStatus write FDescricaoStatus; property Logradouro: String read FLogradouro write FLogradouro; property Complemento: String read FComplemento write FComplemento; property Bairro: String read FBairro write FBairro; property CodigoAssinante: String read FCodigoAssinante write FCodigoAssinante; property NomeAssinante: String read FNomeAssinante write FNomeAssinante; property SiglaProduto: String read FSiglaProduto write FSiglaProduto; property Modalidade: String read FModalidade write FModalidade; function GetPlanilha(FFile: String): TObjectList<TPlanilhaListagem>; end; implementation { TPlanilhaListagem } function TPlanilhaListagem.GetPlanilha(FFile: String): TObjectList<TPlanilhaListagem>; var ArquivoCSV: TextFile; sLinha: String; sDetalhe: TStringList; lista : TObjectList<TPlanilhaListagem>; i : Integer; begin lista := TObjectList<TPlanilhaListagem>.Create; if not FileExists(FFile) then begin TUtils.Dialog('Atenção', 'Arquivo ' + FFile + ' não foi encontrado!', 0); Exit; end; AssignFile(ArquivoCSV, FFile); if FFile.IsEmpty then Exit; sDetalhe := TStringList.Create; sDetalhe.StrictDelimiter := True; sDetalhe.Delimiter := ';'; Reset(ArquivoCSV); Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha; if Pos('LISTAGEM DE MOVIMENTA',sLinha) = 0 then begin TUtils.Dialog('Atenção', 'Arquivo informado não foi identificado como a Planilha de Movimentações Assinaturas do Jornal!', 0); Exit; end; i := 0; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha + ';'; if TUtils.ENumero(sDetalhe[0]) then begin lista.Add(TPlanilhaListagem.Create); i := lista.Count - 1; lista[i].CodigoAgente := sDetalhe[0]; lista[i].DescricaoAgente := sDetalhe[1]; lista[i].DescricaoStatus := sDetalhe[2]; lista[i].Logradouro := sDetalhe[3]; lista[i].Complemento := sDetalhe[4]; lista[i].Bairro := sDetalhe[5]; lista[i].CodigoAssinante := sDetalhe[6]; lista[i].NomeAssinante := sDetalhe[7]; lista[i].SiglaProduto := sDetalhe[8]; lista[i].Modalidade := sDetalhe[9]; end; end; Result := lista; CloseFile(ArquivoCSV); end; end.