hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
163 values
lang
stringclasses
53 values
max_stars_repo_path
stringlengths
3
945
max_stars_repo_name
stringlengths
4
112
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
10
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
945
max_issues_repo_name
stringlengths
4
113
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
10
max_issues_count
float64
1
116k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
945
max_forks_repo_name
stringlengths
4
113
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
10
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
3
1.05M
avg_line_length
float64
1
966k
max_line_length
int64
1
977k
alphanum_fraction
float64
0
1
c3ff1b5e08e85e40e2fbe4a2842f5bb38648e558
5,043
pas
Pascal
ee_export.pas
PerryvandenHondel/NS-000148-export-events
5892966cc1bb253d5c7f2c4af1390462771373d7
[ "Apache-2.0" ]
null
null
null
ee_export.pas
PerryvandenHondel/NS-000148-export-events
5892966cc1bb253d5c7f2c4af1390462771373d7
[ "Apache-2.0" ]
4
2015-10-05T08:32:07.000Z
2015-11-04T08:55:59.000Z
ee_export.pas
PerryvandenHondel/NS-148-export-events
5892966cc1bb253d5c7f2c4af1390462771373d7
[ "Apache-2.0" ]
1
2018-03-13T21:31:27.000Z
2018-03-13T21:31:27.000Z
// // EE_EXPORT -- Export procedures and functions // unit ee_export; {$MODE OBJFPC} interface uses Crt, Classes, DateUtils, // For SecondsBetween Process, SysUtils, USupportLibrary, UTextFile, ee_global; function ExportEventLog(el: string) : string; implementation function GetPathLastRun(sEventLog: string): string; // // Create a path fro the lastrun file containing the date time of the last run. // var r: string; begin //r := GetProgramFolder() + '\' + gsComputerName + '\' + sEventLog + '.lastexport'; //MakeFolderTree(r); r := GetLocalExportFolder(sEventLog) + '\lastexport.dtm'; MakeFolderTree(r); GetPathLastRun := r; end; // of function GetPathLastRun function LastRunGet(sEventLog: string): string; // // Returns the date and time in proper format YYYY-MM-DD HH:MM:SS back from a file in variable sPath // When the file does not exist, create one, otherwise read the datatime in the file. // var sPath: string; f: TextFile; r: string; begin sPath := GetPathLastRun(sEventLog); //WriteLn(' LastRunGet(): ', sPath); if FileExists(sPath) = true then begin //WriteLn('LastRunGet(): Read the line with the last date time from ' + sPath); AssignFile(f, sPath); {I+} // Open the file in read mode. Reset(f); ReadLn(f, r); CloseFile(f); end else begin //WriteLn('LastRunGet(): File ' + sPath + ' not found create a new file'); AssignFile(f, sPath); {I+} // Open the file in write mode. ReWrite(f); r := GetProperDateTime(Now()); WriteLn(f, r); CloseFile(f); end; LastRunGet := r; end; function LastRunPut(sEventLog: string): string; // // Put the current date time using Now() in the file sPath. // var sPath: string; f: TextFile; r: string; begin sPath := GetPathLastRun(sEventLog); if FileExists(sPath) = true then begin AssignFile(f, sPath); {I+} // Open the file in write mode. ReWrite(f); r := GetProperDateTime(Now()); WriteLn(f, r); CloseFile(f); end else begin WriteLn('ERROR LastRunPut(): can''t find the file ' + sPath); end; LastRunPut := r; end; // of function LastRunPut. function RunLogparser(sPathLpr: string; sEventLog: string; sDateTimeLast: string; sDateTimeNow: string): integer; // // Run Logparser.exe for a specific Event Log. // // sPathLpr Full path to the export file; d:\folder\folder\file.lpr // sEventLog Name of Event Log to export. // sDateTimeLast Date Time of the last export; format: YYYY-MM-DD HH:MM:SS // sDateTimeNow Current Date Time; format: YYYY-MM-DD HH:MM:SS // // Returns a integer containing the error level value of the Logparser command. // var p: TProcess; // Process c: AnsiString; // Command Line begin // logparser.exe -i:EVT -o:TSV // "SELECT TimeGenerated,EventLog,ComputerName,EventId,EventType,REPLACE_STR(Strings,'\u000d\u000a','|') AS Strings FROM \\NS00DC066\Security WHERE TimeGenerated>'2015-06-02 13:48:00' AND TimeGenerated<='2015-06-02 13:48:46'" -stats:OFF -oSeparator:"|" // >"D:\ADBEHEER\Scripts\000134\export\NS00DC066\20150602-134800-72Od1Q7jYYJsZqFW.lpr" // // Added export fields (Issue2): // - EventLog // - ComputerName c := 'logparser.exe -i:EVT -o:TSV '; c := c + '"SELECT TimeGenerated,EventLog,ComputerName,EventId,EventType,REPLACE_STR(Strings,''\u000d\u000a'',''|'') AS Strings '; c := c + 'FROM '+ sEventLog + ' '; // Issue1 fix: https://github.com/PerryvandenHondel/NS-148-export-events/issues/1 c := c + 'WHERE TimeGenerated>=''' + sDateTimeLast + ''' AND TimeGenerated<''' + sDateTimeNow + '''" '; c := c + '-stats:OFF -oSeparator:"|" '; c := c + '>' + sPathLpr; WriteLn('RunLogparser(): running command line:'); WriteLn; WriteLn(c); WriteLn; // Setup the process to be executed. p := TProcess.Create(nil); p.Executable := 'cmd.exe'; p.Parameters.Add('/c ' + c); // Check if the output is cleaner on the screen. p.Options := [poWaitOnExit, poUsePipes]; // OLD: p.Options := [poWaitOnExit]; // Run the sub process. p.Execute; RunLogparser := p.ExitStatus; end; // of procedure RunLogparser function ExportEventLog(el: string) : string; // // Export Event logs // // el Name of the event log to export // // Returns the full path to the export file // var sDateTimeLast: string; sDateTimeNow: string; sPathLpr: string; intResult: integer; r: string; begin // Initialize all variables r := ''; sDateTimeLast := LastRunGet(el); sDateTimeNow := LastRunPut(el); // Build the path of the export file sPathLpr := GetPathExport(el, sDateTimeLast) + EXTENSION_LPR; WriteLn('ExportEventLog()'); WriteLn(' Event log: ', el); WriteLn(' DT Last: ', sDateTimeLast); WriteLn(' DT Now: ', sDateTimeNow); WriteLn(' Export to: ', sPathLpr); WriteLn; intResult := RunLogparser(sPathLpr, el, sDateTimeLast, sDateTimeNow); if intResult = 0 then begin WriteLn('Logparser ran OK!'); r := sPathLpr; end else begin WriteLn('Logparser returned an error: ', intResult); end; // if else ExportEventLog := r; end; // procedure ExportEventLog end. // end of unit ee_export
23.455814
254
0.682927
e112665e51e4f65a846e01dfe046cbaede96a698
7,319
pas
Pascal
Source/Propagator/COM/BoldPropagatorHandleCOM.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
121
2020-09-22T10:46:20.000Z
2021-11-17T12:33:35.000Z
Source/Propagator/COM/BoldPropagatorHandleCOM.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
8
2020-09-23T12:32:23.000Z
2021-07-28T07:01:26.000Z
Source/Propagator/COM/BoldPropagatorHandleCOM.pas
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
42
2020-09-22T14:37:20.000Z
2021-10-04T10:24:12.000Z
unit BoldPropagatorHandleCOM; interface uses BoldAbstractPropagatorHandle, BoldComClientHandles, BoldPropagatorInterfaces_TLB, BoldSubscription, BoldDefs, comobj, Classes ; type {forward declarations} TBoldPropagatorHandleCOM = class; TBoldPropagatorHandleCOM = class(TBoldAbstractPropagatorHandle) private FActive: Boolean; FConnectionHandle: TBoldComConnectionHandle; FPassthroughSubscriber: TBoldPassthroughSubscriber; FOnPropagatorCallFailed: TBoldNotifyEventWithErrorMessage; FEventPropagator: IBoldEventPropagator; FClientHandler: IBoldClientHandler; procedure SetActive(Value: Boolean); function GetEventPropagatorObject: IBoldEventPropagator; procedure DoConnect; procedure DoDisconnect; procedure SetConnectionHandle(const Value: TBoldComConnectionHandle); function GetClientHandlerObject: IBoldClientHandler; procedure SetOnPropagatorCallFailed(const Value: TBoldNotifyEventWithErrorMessage); protected procedure Notification(AComponent: TComponent; Operation: TOperation); override; function GetClientHandler: IBoldClientHandler; override; function GetEventPropagator: IBoldEventPropagator; override; procedure _Receive(Originator: TObject; OriginalEvent: TBoldEvent; RequestedEvent: TBoldRequestedEvent); function GetConnected: Boolean; override; procedure SetConnected(const Value: Boolean); override; property ClientHandlerObject: IBoldClientHandler read GetClientHandlerObject; property EventPropagatorObject: IBoldEventPropagator read GetEventPropagatorObject; public constructor Create(Owner: TComponent); override; destructor Destroy; override; procedure DoPropagatorCallFailed(Sender: TObject; const ErrorMessage: string); override; property Connected: Boolean read GetConnected write SetConnected; published property Active: Boolean read FActive write SetActive; property ConnectionHandle: TBoldComConnectionHandle read FConnectionHandle write SetConnectionHandle; property OnPropagatorCallFailed: TBoldNotifyEventWithErrorMessage read FOnPropagatorCallFailed write SetOnPropagatorCallFailed; end; implementation uses SysUtils, BoldUtils, BoldComUtils, BoldPropagatorConstants, BoldComClient, ActiveX; { TBoldPropagatorHandleCOM } constructor TBoldPropagatorHandleCOM.Create(Owner: TComponent); begin inherited; fPassthroughSubscriber := TBoldPassthroughSubscriber.Create(_Receive); fActive := True; end; destructor TBoldPropagatorHandleCOM.Destroy; begin DoDisconnect; Active := false; fPassthroughSubscriber.CancelAllSubscriptions; FreeAndNil(fPassthroughSubscriber); inherited; end; procedure TBoldPropagatorHandleCOM.DoPropagatorCallFailed(Sender: TObject; const ErrorMessage: string); begin if Assigned(FOnPropagatorCallFailed) then FOnPropagatorCallFailed(Sender, ErrorMessage); end; procedure TBoldPropagatorHandleCOM.DoConnect; begin SendEvent(self, beConnected); end; procedure TBoldPropagatorHandleCOM.DoDisconnect; begin SendEvent(self, beDisconnected); FEventPropagator := nil; FClientHandler := nil; end; function TBoldPropagatorHandleCOM.GetClientHandler: IBoldClientHandler; begin Result := nil; if fActive then try Result := (ClientHandlerObject as IBoldClientHandler); except on E: Exception do DoPropagatorCallFailed(self, E.Message); end; end; function TBoldPropagatorHandleCOM.GetClientHandlerObject: IBoldClientHandler; begin if Connected then begin if not Assigned(FClientHandler) then begin if Assigned(ConnectionHandle.BoldProvider) then FClientHandler := ConnectionHandle.BoldProvider.GetObject(CLIENT_HANDLER_OBJECT_NAME) as IBoldClientHandler else DoPropagatorCallFailed(self, Format('Failed to get IBoldClientHandler interface: %s', [SysErrorMessage(ConnectionHandle.ECode)])); end; Result := FClientHandler; end else Result := nil; end; function TBoldPropagatorHandleCOM.GetConnected: Boolean; begin Result := Active and Assigned(ConnectionHandle) and ConnectionHandle.Connected; end; function TBoldPropagatorHandleCOM.GetEventPropagator: IBoldEventPropagator; begin Result := nil; if fActive then try Result := (EventPropagatorObject as IBoldEventPropagator); except on E: Exception do DoPropagatorCallFailed(self, E.Message); end; end; function TBoldPropagatorHandleCOM.GetEventPropagatorObject: IBoldEventPropagator; begin if Connected then begin if not Assigned(FEventPropagator)then begin if Assigned(ConnectionHandle.BoldProvider) then FEventPropagator := ConnectionHandle.BoldProvider.GetObject(ENQUEUER_OBJECT_NAME) as IBoldEventPropagator else DoPropagatorCallFailed(self,Format('Failed to get IBoldEventPropagator interface: %s', [SysErrorMessage(ConnectionHandle.ECode)])); end; Result := FEventPropagator; end else Result := nil; end; procedure TBoldPropagatorHandleCOM.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (AComponent=FConnectionHandle) and (Operation=opRemove) then FConnectionHandle := nil; end; procedure TBoldPropagatorHandleCOM.SetActive(Value: Boolean); begin if Value <> FActive then begin if Value then begin FActive := Value; if not (csDesigning in ComponentState) and not (csLoading in ComponentState) and Connected then DoConnect; end else begin if not (csDesigning in ComponentState) and not (csLoading in ComponentState) and Connected then DoDisconnect; FActive := Value; end; end; end; procedure TBoldPropagatorHandleCOM.SetConnectionHandle( const Value: TBoldComConnectionHandle); begin if (Value <> FConnectionHandle) then begin fPassthroughSubscriber.CancelAllSubscriptions; if Connected then DoDisconnect; FConnectionHandle := Value; if Assigned(FConnectionHandle) then begin FConnectionHandle.AddSmallSubscription(fPassthroughsubscriber, [bceDisconnected, bceConnected], 0); FConnectionHandle.AddSmallSubscription(fPassthroughSubscriber, [beDestroying], 0); if Connected then DoConnect; end; end; end; procedure TBoldPropagatorHandleCOM.SetOnPropagatorCallFailed( const Value: TBoldNotifyEventWithErrorMessage); begin FOnPropagatorCallFailed := Value; SendEvent(self, beModified); end; procedure TBoldPropagatorHandleCOM._Receive(Originator: TObject; OriginalEvent: TBoldEvent; RequestedEvent: TBoldRequestedEvent); begin case OriginalEvent of bceConnected: if Active then begin SendEvent(Self, bceConnected); DoConnect; end; bceDisconnected: if Active then begin SendEvent(Self, bceDisconnected); DoDisconnect; end; beDestroying: ConnectionHandle := nil; end; //end end; procedure TBoldPropagatorHandleCOM.SetConnected(const Value: Boolean); begin if (Connected <> Value) then begin if Value then begin //request connection FConnectionHandle.Connected := True; DoConnect; // is this necessary?? end else begin //request disconnect FConnectionHandle.Connected := false; DoDisconnect; //is this necessary?? end; end; end; end.
28.701961
139
0.7721
c336f1725ab8538af57e67950318c111b22871b4
1,630
pas
Pascal
VirtualMachine/uStringObject.pas
penavon/BookPart2
c73e83331b95c2b5cad9e0c8e0bbc7fa3f7de472
[ "Apache-2.0" ]
6
2020-03-22T09:49:46.000Z
2021-11-28T19:47:20.000Z
VirtualMachine/uStringObject.pas
Irwin1985/BookPart_2
4e8c2e47cd09b77c6e5bd3455ddfe7492adf26bf
[ "Apache-2.0" ]
null
null
null
VirtualMachine/uStringObject.pas
Irwin1985/BookPart_2
4e8c2e47cd09b77c6e5bd3455ddfe7492adf26bf
[ "Apache-2.0" ]
3
2020-11-05T17:02:37.000Z
2021-12-21T04:56:54.000Z
unit uStringObject; // Ths source is distributed under Apache 2.0 // Copyright (C) 2019-2020 Herbert M Sauro // Author Contact Information: // email: hsauro@gmail.com interface uses Classes, uMemoryManager; type TStringObject = class (TRhodusObject) value : string; function isEqualTo (str1 : TStringObject) : boolean; class function add (str1, str2 : TStringObject) : TStringObject; function clone : TStringObject; constructor createConstantObj (value : string); function getSize() : integer; constructor create (value : string); destructor Destroy; override; end; implementation function createStringObject (value : string) : TStringObject; begin result := TStringObject.Create (value); end; constructor TStringObject.createConstantObj (value : string); begin blockType := btConstant; self.value := value; end; constructor TStringObject.Create (value : string); begin blockType := btGarbage; self.value := value; memoryList.addNode (self); end; destructor TStringObject.Destroy; begin value := ''; inherited; end; function TStringObject.clone : TStringObject; begin result := TStringObject.Create (value); end; function TStringObject.getSize() : integer; begin result := self.InstanceSize; result := result + Length (value); end; function TStringObject.isEqualTo (str1 : TStringObject) : boolean; begin result := self.value = str1.value; end; class function TStringObject.add (str1, str2 : TStringObject) : TStringObject; begin result := TStringObject.Create (str1.value + str2.value); end; end.
19.404762
78
0.709816
fc4bc20679fa693f2ec92fda4bbaf3a9c42d72f1
3,801
pas
Pascal
delphi/equipamentos/delphi/U_remessas.pas
vitorebatista/my-tests
696b2290259d8179d0b3399569dd9e77e6eaa750
[ "MIT" ]
null
null
null
delphi/equipamentos/delphi/U_remessas.pas
vitorebatista/my-tests
696b2290259d8179d0b3399569dd9e77e6eaa750
[ "MIT" ]
null
null
null
delphi/equipamentos/delphi/U_remessas.pas
vitorebatista/my-tests
696b2290259d8179d0b3399569dd9e77e6eaa750
[ "MIT" ]
null
null
null
unit U_remessas; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids,DB, DBtables, StdCtrls, Mask, DBCtrls, Buttons, ExtCtrls; type TFrm_remessas = class(TForm) Panel1: TPanel; Spprimeiro: TSpeedButton; SpAnterior: TSpeedButton; SpProximo: TSpeedButton; SpUltimo: TSpeedButton; SpInserir: TSpeedButton; Spdeletar: TSpeedButton; Speditar: TSpeedButton; SpGravar: TSpeedButton; SpCancelar: TSpeedButton; SpSair: TSpeedButton; Label1: TLabel; DBEdit1: TDBEdit; Label2: TLabel; DBEdit2: TDBEdit; Label3: TLabel; DBEdit3: TDBEdit; Label4: TLabel; DBEdit4: TDBEdit; Label5: TLabel; DBEdit5: TDBEdit; Label6: TLabel; DBEdit6: TDBEdit; Label7: TLabel; DBEdit7: TDBEdit; Label8: TLabel; DBEdit8: TDBEdit; Label9: TLabel; DBEdit9: TDBEdit; Label10: TLabel; DBEdit10: TDBEdit; Label11: TLabel; DBEdit11: TDBEdit; Label12: TLabel; DBEdit12: TDBEdit; Label13: TLabel; DBEdit13: TDBEdit; Label14: TLabel; DBEdit14: TDBEdit; Label15: TLabel; DBEdit15: TDBEdit; DBGrid1: TDBGrid; procedure validanavegacao; procedure validainsercaodedados; procedure SpprimeiroClick(Sender: TObject); procedure SpAnteriorClick(Sender: TObject); procedure SpProximoClick(Sender: TObject); procedure SpUltimoClick(Sender: TObject); procedure SpInserirClick(Sender: TObject); procedure SpdeletarClick(Sender: TObject); procedure SpeditarClick(Sender: TObject); procedure SpGravarClick(Sender: TObject); procedure SpCancelarClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Frm_remessas: TFrm_remessas; implementation uses U_DM; {$R *.DFM} procedure TFrm_remessas.validanavegacao; begin Spprimeiro.Enabled:=not(DM.q_remessa.bof); Spanterior.enabled:=not(DM.q_remessa.bof); Spproximo.enabled:=not(DM.q_remessa.eof); Spultimo.enabled:=not(DM.q_remessa.eof); end; procedure TFrm_remessas.SpprimeiroClick(Sender: TObject); begin Dm.q_remessa.First; validanavegacao; end; procedure TFrm_remessas.SpAnteriorClick(Sender: TObject); begin DM.q_remessa.Prior; validanavegacao; end; procedure TFrm_remessas.SpProximoClick(Sender: TObject); begin DM.q_remessa.Next; validanavegacao; end; procedure TFrm_remessas.SpUltimoClick(Sender: TObject); begin DM.q_remessa.Last; validanavegacao; end; procedure TFrm_remessas.validainsercaodedados; begin Spprimeiro.enabled:=(DM.q_remessa.state=dsbrowse); Spanterior.enabled:=(DM.q_remessa.state=dsbrowse); Spproximo.enabled:=(DM.q_remessa.state=dsbrowse); Spultimo.enabled:=(DM.q_remessa.state=dsbrowse); Spinserir.enabled:=(DM.q_remessa.state=dsbrowse); Speditar.enabled:=(DM.q_remessa.state=dsbrowse); Spdeletar.enabled:=(DM.q_remessa.state=dsbrowse); spgravar.enabled:=(DM.q_remessa.state in [dsinsert,dsedit]); spcancelar.enabled:=(DM.q_remessa.state in [dsinsert,dsedit]); spsair.enabled:=(DM.q_remessa.state in [dsinsert,dsedit]); end; procedure TFrm_remessas.SpInserirClick(Sender: TObject); begin DM.Q_remessa.insert; validainsercaodedados; end; procedure TFrm_remessas.SpdeletarClick(Sender: TObject); begin DM.Q_remessa.delete; validainsercaodedados; end; procedure TFrm_remessas.SpeditarClick(Sender: TObject); begin DM.Q_remessa.Edit; validainsercaodedados; end; procedure TFrm_remessas.SpGravarClick(Sender: TObject); begin DM.Q_remessa.Post; validainsercaodedados; end; procedure TFrm_remessas.SpCancelarClick(Sender: TObject); begin DM.Q_remessa.Cancel; validainsercaodedados; end; end.
24.365385
76
0.726651
c33a4b9e2f06791913f1f52817a1250c3d10eeea
12,321
pas
Pascal
unencry1.pas
keep94/pasprg
6b0daa3863ca525d591b94410eda84981e8719ba
[ "Apache-2.0" ]
null
null
null
unencry1.pas
keep94/pasprg
6b0daa3863ca525d591b94410eda84981e8719ba
[ "Apache-2.0" ]
null
null
null
unencry1.pas
keep94/pasprg
6b0daa3863ca525d591b94410eda84981e8719ba
[ "Apache-2.0" ]
null
null
null
program unencrypt; uses crt,dos,rand,IOunit; const MAXARRAY = 32760; MAXARRAY2 = 16380; SENTINAL = 315926832; REMINDFILE = 'REGISMES.TXT'; type arraytype = array[1..MAXARRAY] of byte; tabletype = array[0..255] of byte; paritytype = array[1..MAXARRAY2] of integer; parraytype = ^arraytype; ptrtype=^node; node=record data:searchrec; next:ptrtype end; var lastdir,username,userid,passkey,temp,path:string; subdir:dirstr; name:namestr; ext:extstr; subdirlen,errorcode,error,filecount:integer; done,escpressed:boolean; p,top:ptrtype; Function fileacc(filename:string):boolean; var f:file; numread,numwritten:word; error:integer; dummy:byte; dt:longint; begin error := 0; assign(f,filename); {$I-} reset(f,1); {$I+} error := IOresult; if error = 0 then begin {$I-} getftime(f,dt); seek(f,0); blockread(f,dummy,1,numread); {$I+} error := IOresult; if error = 0 then begin {$I-} seek(f,0); blockwrite(f,dummy,1,numwritten); {$I+} error := IOresult; if error = 0 then begin {$I-} setftime(f,dt); {$I+} error := IOresult end end; close(f) end; fileacc := (error = 0) end; Function minval(x,y:longint):longint; begin if y < x then minval := y else minval := x end; Procedure getcurdir(var x:string); var path:pathstr; d:dirstr; n:namestr; e:extstr; begin path := 'dummy.pas'; path := fexpand(path); fsplit(path,d,n,e); if d[0]>chr(3) then d[0] := chr(ord(d[0])-1); x := d end; procedure encinput(var x:string;inplen:integer;var escpressed:boolean); var done:boolean; temp,stemp:char; cnt:integer; begin done := false; x := ''; while (not done) do begin temp := readkey; if temp = chr(27) then begin done := true; escpressed := true end else if temp = chr(13) then begin done := true; escpressed := false end else if temp = chr(8) then begin if length(x) > 0 then begin x := copy(x,1,length(x) - 1); gotoxy(wherex - 1,wherey); write(' '); gotoxy(wherex - 1,wherey) end end else if temp = chr(0) then begin stemp := readkey; if stemp = chr(75) then begin if length(x) > 0 then begin x := copy(x,1,length(x) - 1); gotoxy(wherex - 1,wherey); write(' '); gotoxy(wherex - 1,wherey) end end end else if length(x) < inplen then begin if (temp in ['0'..'9','A'..'Z','a'..'z']) then begin x := x + temp; write('X') end end end end; function pord(x:char):longint; begin if x in ['0'..'9'] then pord := ord(x) - 21 else if x in ['A'..'Z'] then pord := ord(x) - 64 else if x in ['a'..'z'] then pord := ord(x) - 96 else pord := -1 end; procedure getkeys(x:string;var ekey:longint;var ikey:integer); var cnt:integer; begin ekey := 0; ikey := 0; for cnt := 1 to 3 do ikey := ikey*37+pord(x[cnt]); for cnt := 4 to 9 do if cnt <= length(x) then ekey := ekey*37+pord(x[cnt]) else ekey := ekey*37 end; procedure gentable(var t:tabletype); var cnt:integer; pos,temp:byte; begin for cnt := 0 to 255 do t[cnt] := cnt; for cnt := 256 downto 2 do begin setmax(cnt); pos := longrnd; temp := t[cnt - 1]; t[cnt - 1] := t[pos]; t[pos] := temp end end; procedure geninvtable(var t:tabletype;var invt:tabletype); var cnt:integer; begin for cnt := 0 to 255 do invt[t[cnt]] := cnt end; function codestr(x:string):string; var cnt:integer; offset:byte; lastseed:rndinfotype; pt:tabletype; begin getrndstat(lastseed); initrnd(925241837); gentable(pt); for cnt := 1 to length(x) do begin offset := rnd; x[cnt] := chr((pt[ord(x[cnt])] + offset) mod 256) end; codestr := x; setrndstat(lastseed) end; Procedure printauthor; begin write(codestr(chr(21)+chr(41)+chr(111)+chr(204)+chr(208)+chr(130)+ chr(223)+chr(126)+chr(108)+chr(225)+chr(145)+chr(99)+ chr(89)+chr(12))) end; procedure checkseg(var x:arraytype;size:integer;var invt:tabletype;var parity:integer); var cnt:integer; p:^paritytype; offset:byte; begin p := addr(x); for cnt := 1 to size do begin offset := rnd; x[cnt] := invt[byte(x[cnt] - offset)] end; for cnt := 1 to size div 2 do parity := parity xor p^[cnt]; if (size mod 2 > 0) then parity := parity xor x[size] end; procedure unencriptseg(var x:arraytype;size:integer;var invt:tabletype); var cnt:integer; offset:byte; begin for cnt := 1 to size do begin offset := rnd; x[cnt] := invt[byte(x[cnt] - offset)] end end; procedure unencriptfile(filename:string;passkey:string;var errorcode:integer); var x:parraytype; t,invt:tabletype; numread,numwritten:word; earmark,enckey,curpos,filetime,filelength:longint; error,signature,filesignat,parity,parkey:integer; f:file; rndstat:rndinfotype; alreadyunenc:boolean; begin getmem(x,MAXARRAY); getkeys(passkey,enckey,parkey); initrnd(enckey); gentable(t); geninvtable(t,invt); assign(f,filename); reset(f,1); filelength := filesize(f); alreadyunenc := true; if filelength >= 6 then begin seek(f,filelength-4); blockread(f,earmark,4,numread); alreadyunenc := (earmark <> SENTINAL); seek(f,0) end; if not alreadyunenc then begin parity := 0; getrndstat(rndstat); curpos := 0; while (curpos < filelength - 6) do begin blockread(f,x^,minval(MAXARRAY,filelength - curpos - 6),numread); checkseg(x^,numread,invt,parity); curpos := curpos + numread end; blockread(f,filesignat,2,numread); signature := parity + parkey; setrndstat(rndstat); if signature <> filesignat then errorcode := 1 else begin getftime(f,filetime); errorcode := 0; seek(f,curpos); truncate(f); seek(f,0); while (not eof(f)) do begin curpos := filepos(f); blockread(f,x^,MAXARRAY,numread); unencriptseg(x^,numread,invt); seek(f,curpos); blockwrite(f,x^,numread,numwritten) end; setftime(f,filetime) end end else errorcode := 2; close(f); freemem(x,MAXARRAY) end; Procedure getdirectory(path:string;var top:ptrtype); var bottom,p:ptrtype; error:integer; dirinfo:searchrec; begin top := nil; bottom := nil; findfirst(path,32,dirinfo); error := doserror; while error = 0 do begin new(p); p^.data := dirinfo; p^.next := nil; if top = nil then begin top := p; bottom := p end else begin bottom^.next := p; bottom := p end; findnext(dirinfo); error := doserror end end; Procedure cleardirectory(var top:ptrtype); var p,q:ptrtype; begin p := top; while p <> nil do begin q := p^.next; dispose(p); p := q end end; Procedure registrationinfo; var g:text; curline:string; begin clrscr; if not fileexists(REMINDFILE) then begin writeln(chr(7)+'Cannot find '+REMINDFILE); halt end; assign(g,REMINDFILE); reset(g); write(chr(7)); while not eof(g) do begin readln(g,curline); writeln(curline) end; writeln; write('Written by: '); printauthor; gotoxy(1,24); write('Press ENTER to continue: ':52); readln; clrscr end; begin userid := '1234567890'; username := '12345678901234567890'; if codestr(copy(userid,6,5)) <> chr(130)+chr(14)+chr(234)+chr(11)+chr(7) then registrationinfo else begin write('Written by: '); printauthor; writeln; writeln('This copy licensed to: '+username); writeln end; write('Enter files to unencrypt: '); getinput(temp,escpressed); writeln; writeln; if escpressed then exit; fsplit(temp,subdir,name,ext); subdirlen := length(subdir); if subdirlen > 3 then if subdir[subdirlen] = '\' then subdir := copy(subdir,1,subdirlen-1); path := name+ext; repeat write('Enter encryption key: '); encinput(temp,9,escpressed); writeln; writeln; if escpressed then exit; caps(temp); if length(temp) < 4 then begin writeln(chr(7)+'Encryption key must be at least 4 characters.'); writeln end until length(temp) >= 4; passkey := temp; getcurdir(lastdir); {$I-} chdir(subdir); {$I+} error := IOresult; if error <> 0 then begin writeln(chr(7)+'Path does not exist.'); exit end; getdirectory(path,top); p := top; done := false; filecount := 0; while (p <> nil) and (not done) do begin if p^.data.size > 0 then begin if fileacc(p^.data.name) then begin unencriptfile(p^.data.name,passkey,errorcode); if errorcode = 0 then begin writeln(fexpand(p^.data.name)+' unencrypted successfully.'); filecount := filecount + 1 end else if errorcode = 2 then writeln(fexpand(p^.data.name)+' is already unencrypted.') else if errorcode = 1 then writeln(fexpand(p^.data.name)+': Data false or encryption key incorrect.') end else writeln('Access denied to '+fexpand(p^.data.name)) end else writeln(fexpand(p^.data.name)+' is empty.'); p := p^.next end; writeln; writeln(filecount,' files unencrypted successfully.'); {$I-} chdir(lastdir); {$I+} cleardirectory(top) end.
25.144898
94
0.465628
c350e93e8dc5a140e2ff784dd6fa698222315e4a
31,204
dfm
Pascal
windows/src/ext/jedi/jvcl/jvcl/examples/JVCLMegaDemo/hello.dfm
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jvcl/jvcl/examples/JVCLMegaDemo/hello.dfm
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jvcl/jvcl/examples/JVCLMegaDemo/hello.dfm
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
object WelcomeForm: TWelcomeForm Left = 341 Top = 60 Width = 539 Height = 537 HelpContext = 1 Caption = 'Welcome' Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] OldCreateOrder = True OnShow = FormShow PixelsPerInch = 96 TextHeight = 13 object JvImage1: TJvImage Left = 0 Top = 0 Width = 529 Height = 155 Align = alTop Center = True Picture.Data = { 0A544A504547496D6167653F260000FFD8FFE000104A46494600010001004800 480000FFFE001F4C45414420546563686E6F6C6F6769657320496E632E205631 2E303100FFDB008400150E0F120F0D15121112171615191F34221F1D1D1F402E 3026344C43504F4B434948545F79665459725B4849698F6A727D818789875165 959F93849E79858782011617171F1B1F3E22223E825749578282828282828282 8282828282828282828282828282828282828282828282828282828282828282 82828282828282828282FFC401A2000001050101010101010000000000000000 0102030405060708090A0B010003010101010101010101000000000000010203 0405060708090A0B100002010303020403050504040000017D01020300041105 122131410613516107227114328191A1082342B1C11552D1F02433627282090A 161718191A25262728292A3435363738393A434445464748494A535455565758 595A636465666768696A737475767778797A838485868788898A929394959697 98999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3 D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EAF1F2F3F4F5F6F7F8F9FA1100020102 0404030407050404000102770001020311040521310612415107617113223281 08144291A1B1C109233352F0156272D10A162434E125F11718191A262728292A 35363738393A434445464748494A535455565758595A636465666768696A7374 75767778797A82838485868788898A92939495969798999AA2A3A4A5A6A7A8A9 AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE2E3E4E5 E6E7E8E9EAF2F3F4F5F6F7F8F9FAFFC0001108008A01DB030111000211010311 01FFDA000C03010002110311003F00BBE35678F4D8CA315F9FB13401C699EE37 0FDFC98FF7CFF8D0310DD5C67779EF9FF78F4A3410B25E4C0002E253FF000339 A00699EE3218CF285F50E7FC680145DDC0C0FB44993E8E7228005BBB8539134A DFF033FE3400AF7B3311FBF9571FED9FF1A0047BDB86E1669001FED9FF001A00 69B9B9EAB712E3FDF3400EFB45CEDC8B8973ECE68D506820BAB8073E7CB9F5DE 79A770DFA0AB7570CA41B89171CE771A5A8B950D17371B7227931EEE68D45CA8 7457770CC774D21C7FB668BB1F2A13ED538208B8931EEE68BB0B213ED772C702 E24E3FDA346A1CA85FB4DC02713CBD3FBE68D43957610DCDC00337128CFF00B4 68D439509F6AB861812CB9F5DC68D4395760FB55C7FCF793FEFA346A3B2EC02E AE307F7F2EEFF78D1A8ACBB0A6EE70B8F3A5CFFBC68D439500BBB82389E5FF00 BE8D1A872A1E2E67FF009EF2FF00DF46A85CA83ED33FFCF693FEFB340590A2E6 71FF002DA4FF00BE8D01641F689FFE7BC9FF007D1A02C85FB44FFF003DA4FF00 BE8D0164396E27FF009ED27FDF4698AC87ACF37FCF593FEFA34C5644EB24DFF3 D5FF00334C2C8B092CA07FAC63F89A0564383CA7F8DFF3340F950F5F3BBBBFE6 69D82C89544A7F89BF3340AC891639BFBEDF99A02C3FCA97FBCDF99A02C27972 FF007DBF334EC1618E92FF0079BF334582C56944BFF3D1C7E269582C8858CC07 FAC7FCCD161684464987FCB593F334582C861927FF009E927FDF468B05908669 7FE7AC9FF7D1A2C16437CE9BFE7B49FF007D1A2C16437CF9FA79B27FDF469587 A079D381FEB64FFBE8D2B0EC83CF9B6E3CE7CFFBC680B21BF689C7FCB593FEFB 340590C3713FFCF697FEFA3482C85173391FEBA5CFFBC698590AD2CE3FE5B49F F7D9A076447F699F3FEBA4FF00BE8D4D98590BF689F77FAE93FEFB340ECBB01B 99FB4D27FDF4680B2EC27DA6E3FE7B49FF007D9A4164385CCC3ACD27FDF46985 90E8AE6637118F3A4C6F19F98D176092EC7A7A7DC5FA0A928E7BC6E33A6C63FD BA00E15570725491EB4008C013C1CD0038A8CE4374F5A009109202F0401F9D0F 418C556603E5208EE452BA10AA9F295C32E3DA8BA0030E790DF811D69DC06046 E70ADCFB517431487202ED23F0A575DC4037AF4CA8A6ACC0923DAC8039E474A0 2E46558B676B633D314AEBB80A46EFE161ED8A2E806E0A633903D69E9D0008E4 E08FA62900E66254044FC4536D2005491727631FC29732EE039C48CABB949E3F BB4732EE030315F50698027040C1EB400A705885E3DCD0020561FC04F3E94AE8 030C4FDD207D28BA01DF313D0FE54D3400A2A842D002F7A2C21EA39A63250B93 C5161132A7CA29889E38CE334580B11C249C629812BB456E9FBD6551480AB26A F0C67F75197345C2C577D6EE1BEEA20A2E3B09FDB7783BAD2B858923F10DCA1F 9D11853B858BB6FE22B791B1342C9EF4EE16352092DAED7F732AB1F4EF4EE032 6B4C0CE38A0562A496D8ED4EC2B159E0F6A2C2B113C4695844263F6A2C030C78 ED40C66DC3671400D20E4D218C29839A5601A714009D39A432D59C4B21C1EB56 8096FAD443F768685733597BD4142753400700F348619C0228B002F4C9A00742 01B88CAF4DE3F9D007AA27FAB5FA0A919CEF8E3034D889FEFD0070C1D8F43D0F 028002FCEE1DFAD00264163E86802F68D1ABEA5106C32E7A1AC6BB6A9B6868EF 7EC16BFF003C13F2AF03DBD4EE69641F60B5FF009E29F951EDA7DC7646078AED E186DE168E3553BC72057A180A929B69B224AC6AE9B696D35844E61424AFA572 D6A938CDAB94916BEC16BFF3C13F2AC7DB4FB859191E26B3863D2D9A28D5581E A057660EAC9D4B36292B1CE6831093548A3900209E6BD2C449AA6DA262775F60 B5FF009E09F95783EDAA772EC83EC16BFF003C53F2A5EDAA770B238FF134712E A7B11428031C7AD7B5836DD3BB21A34F47F0DC0D024F779676FE1AE5C463657E 5814A26DC7A659C43096F18FA0AE1788A8FA8EC893EC900FF9629F954FB59F71 D901B4B739CC4BCFB51EDA7DC2C8826D1EC66077DBA7D40AB589A8B662B2398F 106809631F9F6A4F97FC4A79C57AB85C53A9EECB725AB18B6A3FD26346191BAB B26F4B908F4386C2D8C284C29F77D2BE7A55A69EE6B61FF60B5FF9E29F9547B6 9F71D9193E25B5822D319922556F502BB7075652A966C992B1C78E9C57B6642F 5A00728E69889556802C471E69889D139A605A8A2C292C70077A00A975AA2A02 96D8CF726A6E3B196CCF29DCC4B11DEA6E3184F6A00434C033400500283CFB50 0490CAD0B878D995BD45311D1699E202C4457A011D9E981B2F6E92A6F8CEE53D C5526329CB6F838C53B8AC55787DA99362BB4005202368B02815885A3E7A5202 22BC74A008C8E050031C7B7E34806641238A43248A4F28EE5E0D301F7174D301 934360536CD494263D2801DBC98FCBED9CE3DE900D2001EF400A8BE61D8383EF 40C58462E231D838E9F5A00F544FF56BF4152339CF1D7FC8323FF7E803887002 AE7AF7A0068418068005504E39CD005FD086DD5621EF58623F86C6B73D12BE70 D428039CF191C5A447FDA15E965DF132665FF0DCBE66951FB715863236A8C713 52B90665F88D7768F2FB0CD7560DFEF509EC731E1805F588CE338AF5B1AED4DD 888EE7775F3E6819A00E1F500D75E26280F1BC57BD4AD0A17FEB733EA76EAA15 401D00AF09EED9A0B52014C02800A00A9AAC226D36743DD4D6D879B8D44C1EC7 9F5B80B771F3921F15F453F84C51E930FF00A84FF7457CCCB766C3EA40C7F147 FC82DBEB5DB82FE2132D8E2718E86BDF321450224514C0B08B408B31AFA5302D C51E064E001EB4D819FA95F998F9700D918E323BD436519DC8A2E0588631F672 49C6E3FA561295A563D0A142F4DB6566E0E056C79F61B40053016908314C63C0 A622CC49BB8A64DCDBD2AFA5B460872D11EC7B5161A66FB4693461D4E41A3628 A92DB9F4AAB88ACF0FB530B103C5CF4A62B1049152B1362BC91E28115DD68022 71C631C5219190076A9189F7474CD00211800E6818C34804085BEED0305183C8 A0046EB4801976A839CFB5003A0FF5D17BB8FE740CF538FF00D5AFD0548CE77C 71FF0020D8B3FDFA00E211B70209C93ED4008FB81005002AB0DD9E334016F42E 75587EBD6B0C47F0D8D6E7A2D7CE1A850073BE32E6D22007F157A5976EFF00AE E4CC7783E40D60E83F85AA731569A6103A0AF3CA28EB6BBB49B81FECD746174A A81EC733E115CEA2E4F05457A9983FDDFF005E4671DCED2BC346823F084FB516 0386B3733788C93FDFAF7EA2E5A1FD7733EA775DABC0340A0662789F509AC6D6 33036D62DD6BBF054A351D9912762F69170F75A7C72C9F788E6B9F11050A9645 22ED61D408AE87FA24A3FD93574FE240CF3B4C1BF5E31893FAD7D24BE0323D1A 1FF509FEE8AF9A96ECD47D4818FE28FF009059FAD76E07F8A4CB638AF6AF7CC8 78033C53112C639A04598D7DA9817208FE6E28020D56E8C686DD0F5FBC693633 1F38A918A39200EF49E8095DD8DBFB284D2FCCFF006B03E95CADDF53DE4941AA 48C390618D74C5DD1E3D6872CD8DAA320C53421473D28DC0912376E82B48D394 85725585FA95ABF61517426E5BB58F27A5459ADD08D2861E00A761A35F4D731F EE8FDD6E47B1A9659A0F18351702BC96E2AD302ACD0629DC0A7245542B15655C D22195644F4A045775FCA90C8DD0023BFD29011B0E7AD031BB79348069A06045 201338C8078A0634D0018C8C8A403EDBFD7A061B8EE1FCE819EA71FF00AB5FA0 A919CDF8E7FE4191FF00BF401C42E772EC001F5A00189EA581DB40005FBD9038 19E2802F68991AAC2318E6B0C47F0D8D6E7A1D7CE1A850073BE3262B6D091D77 57A5976EC9915FC16F869D3B139AD3315A2628763AAAF24B2B6A2BBAC261FECD 6B45DAA206735E1040350B9C72001FD6BD4C7FC0BFAEC440EBABC62C8AEDF65A C8DE8A6AE9EB2480E1B456DFAD231EA58D7BF8956A36325B9DF57CE9A8500735 E3219822FF007ABD3CBBE264CCD3F0F7FC82A3AE6C5AFDE31C4D2AE51915D7FC 7ACBFEE9ABA7F120679D45FF002101E9E61FE75F492F84C8F4787FD427FBA2BE 6A5BB351F52063F8A3FE416DF5AEEC0FF14996C715DABDF311E806462802CC62 988B512D005C2E2081A46E31401CF49219646763C9A9288FA5202C5926F9813D 00ACEABB23AF074FDA5457D8E86F93CBD2205E99E6B07A23D383E6A8CE6E75F9 B8ADA0CF3F131D486B53885A044D0C3BCF2700575D1A57D58AE5F8E255E82BD3 8D351D486C9C229F4AA2440A633B979C76ACAA528CC66AD98591415AF3670709 5997135218475EF5948A2EA8C8E7AD66302A0D17021922041E2A93114278B15A 211425414C968A72AD2B08ACFD29015DBAD2023228188C466900D3C76FC68189 8CD003703E9486371C1A06276A044B09024880C6778E7F1A433D4A3FF56BF415 2339DF1B0074E8B2091BFB50070C1B0DB57A76A007C912A00A7EF0E4D0023AA8 1BC1F6DB4017B4401754838C66B0C47F098D6E7A0D7CE1A850073BE3119B6847 FB42BD3CBBE264CCCFF0A384D50C606014FF000AE9C746F4C51DCECABC32C8AE 46EB6907FB26AA1A49319CEF8423C3DC377CE3F535E9E3DECBFAE86713A7AF28 B296B0FE5E9B2B7B62B7C3C79AA207B1C568031ABC5CFAD7B989FE13328EE7A1 57CE1A8500735E3307ECF163FBD5E9E5DBB26655D3BC4A967689098F247BD6F5 B04EA4AF7254AC5A1E3043FF002C081EB9AC7FB3DF71F311CDE2D8DE368FC83C 823AD5472F69DEE1CC73F6F231BB41D9DF3FAD7A53D23626E7A343FEA53FDD15 F332DD9A8FA9031FC51FF20B3F5AEEC07F10996C715DEBDF312541CD005A8C53 117215C1C1A008F5890ADB2C63F8BAD4B198F48621F5A00BF60988F247DE35CD 55DF43DAC053B41C9FF5B9B9AD1C5BC083B0A99EC8BC32BB6CE6EE07A55C1986 262573D7201C56E8F2DA01570576497EDD70A2BD4A5648865B4AEA5B126A5A69 52DCC5BD4715CB5311183B0D44A7344619191BA8ADE32E6574058D224D975E56 786E7F1AC3130BC79822CE9635005794D9A8EA900A00080451702ADC2706B44C 465CEB8AB114655A64952414892BB0ED48631B1B703AD201845218CC1C500046 31CD031BDE90099005031B8E6801D081E6C7D73BC7F3A433D523FF0056BF4152 339DF1B0274D8F19FBF401C3FC8C542039A005CED0C197231C500308557E848C 5006868873AA438047A56188FE1B1ADCF42AF9C350A00E7BC5EC12DA2DDFDEAF 4B2EF89FF5DC99987E1E94A6AF1F276918E7DEBBF14AF499317A9DED7CF1A0D9 066361EA0D388187E184DBF6AE3FE5A1FE66BBF1CEED7F5D8989BD5E79465F88 D80D2D81EF5DD808DEA7F5E644F44727A1E06AF0F4AF5713FC264C773D02BE70 D428039CF18A97B68F03BD7AB972D5FF005DC89B39160AA9B71F367AD7ADD0CC 563B942654628E83181724E4F4A009EDBFE3EA13FED5673D9823D261FF00529F EE8AF9A96ECD87D4818FE28FF9059FAD77607F884CB638A02BDF31278C73408B 510A605D839619A00A1AD37FA42AFA54B1A33B24521820DEC17D4E287A151577 646C5BA00E883A035C4DF348FA5843929D8BDAD3E5D00EC2AA4CC70CBDD6CC39 8669C4C6B21B6FA7DCDD9C4284FB9E95AFB5843E267953896EE3C3F7D6EA1C28 907A0EB534B174DBDCCDC5A228D5A33B5D4A91EB5EDD29C65AA664CB28D8C576 27A126DD8EB5F6687CB2B9C74AE2AB85E795CA4EC67DD5C1B899A43C64D74D38 72AB12D8BA71FF00898C5D2A711FC31C4EB13A578ACD45A402D00140104FD2B4 4232AE3193562294B412CA52504959BD3BD2191118A4034F5A004C9C6DA4310F 0402280187DA90C69EA0503B872A08EFDE80160FF8F88FD378FE74867AA47FEA D7E82A46739E392574C8F07F8E803851800E7D7A8A2C0397692033673400AAAB E6633401A3A3393AAC49D81E0D6188FE131ADCEFEBE70D428039CF197FC7AC58 38F9ABD3CBBE264C8E734D221D42170DD180AF4AAABC1A211E8AA72A0FAD7CD1 A8A46411ED421997A247B05C1F590FF3AEBC54AF62626A5720CE7FC5D294B58D 47735E9E5FF137FD7522673FA1BEED5E1AF4313FC264C4F40AF9C350A00E7BC5 CFB6DE3FAD7AB973D5FF005DCCE6721C039C64FBD7AC4A1548009E33DC525A0C 628CE72718E99A3D044F6FB7CF876F3F30A996CC2C7A443FEA13FDD15F332DD9 B0FA9031FC51FF0020B3F5AEEC0FF1099EC7180F15EF1892C62988B708A605EB 7EA28032F59FF8FD1F4A9634513D695C09ACC133EEF4E6A2ABB23B7090E7A86A DB7FAF5AE38EE7BF53E1D0BD716535ECA1A31F2FAD2A95231DCE355614959962 0D0205C34C4B9F43D2B8E78B6BE1386A577234E389225DA8A147B572CAACA5B9 CFEA3B1F954263D3A904F6704EA43C60FBF7AEAA38DAB4B67F992E0999F3684A 0661908FF6715EE50CEBA4D7F5F798CA976332789EDE4D8E0035EFD2AD1AB1E6 8EC62D5B719BB15AE822C696375E6F3D10706B8B113D2C3474F04A08AF35A342 C03C545862D00358F14015A76E2B442332E0F26AC4CA529A0965493BD04959FA D218D03775038A00465C50046460607E74806B1C1C9E4D218CCE0E681899C126 90C6E7E60726801D09CCF1E3FBE3F9D007A9C7FEAD7E82A0A39CF1D7FC8323FF 007E80397D274D935091D6265CA8C918AC2B565495D8D2B9A1FF000895CF5DE3 39AE7FED080F9187FC22775DDC6477A5F5F807232A69909B6D6A3808CB29E4D6 D565CD45B425B9DED7CF9A8500739E32E2D623FED0AF4F2EF89932396830B2A3 162006041F5E6BD67B107A3DBB6FB78DBD457CC4D59D8D56C4B5232AD847B11F DD8FF3AD6ACB9848B55901CA78C24CCF1479FE1CD7B197C7DD6C89193A09FF00 89B43EF5D589FE13256E7A0D7CE9A8500737E32E6DE2FAD7A9976EFF00AEE44C ADA6786E1BBB3495A4209ABAD8C74E56051B96CF846DCE7F786B2FED09761F28 DB8F0AC0B1BC86424A8AA863E4DDAC2E53988B02F900E007C57A72F86E49E910 FF00A94FF7457CD4B766A3EA40C7F147FC82CFD6BBB01FC4267B1C5A8E6BDF31 278FAF1408B319E94C0BB6DD68028EB6989A36F5152C68CC34865FB24023DC7A 935CD565D0F6F2EA768F33FEB72EDBF0F9AC16E7A13D517EDEEA58F943C7A563 5A0A5B9E362E3CB3352DAF639B01BE46AE09D271D8E6B96B1588F70C52011C84 196205349BD80A935D16E13E515BC616DC4D9CF6A773BAE88E98E39AFAFC17EE E925FD6E734F529894B9DA9D7D6BA655ADB106AD9010A050724F27EB5C729396 E069C37040EB52D0EE5FB79F7B019ACDA2CB44E2A008A49303AD5240519E5E0F 35A24233E57E4D5589656739A4495643408AEF9CF4A43114F5A0046A00888A40 31A8188508049E3140C61EF48771B4807407F7F1FF00BE3F9D007AA47FEA93FD D15051CE78EBFE41917FBF40197E0CFF008FBB8FF74579D987C28B81D7578C58 1E868038A42A7C4D8039DDD6BDD7FC0FEBB99F53B5AF08D028039CF191C5A444 7F7ABD2CBBE264C8E4F780C31DF191E95EC74333D0F497DFA6C27FD915F37885 6A8D1AAD8B958B1888A1060536EE02D20388F15C85F53C0E760C1AF77051B533 27B95F421FF13580E2B5C4FF000982DCEFEBE74D4280399F1A7FC7B45F5AF4F2 EDD933353C3DFF0020B8EB9717FC4638EC695730C8AEBFE3D65FF74D5D3F8903 3CEA303EDCB8EBE61FE75F4B2F80C8F4787FD427FBA2BE665BB351F52063F89F 9D2DBEB5DD80FE27F5E64CF638B5F4ED5EF98934470791408B51D302E40D8A00 66AF1EFB5DE0676F4A9634619E690D1A7105540011D335C73526CFA4C3CE9A82 4993C671CD46C6EE49F527B77CA95F7ACE6B43CCC7C568FF00AE84DF4E3DEB13 CE2CDB5F4909C312CBEF594E9296C3B97CDEA32029D4D73FB369EA55CAF248CE 72C7F0AD124B6248FAD5A577613396BC25AF64DDC906BE869C9A8D8E790E81B6 91818ABE66C92FC52F4E6988B714F8A608D5D28F99233F615123445D965C77A5 6029CB375AA480A92484E698AE5576A64DC819B9A422BC868110B120F1486373 8340084F1400C607D2900850B5031648DB03E9401118CD03B8C618A91DC211FB F8FF00DF1FCE90CF548FFD527FBA2A4673DE36DBFD9D16EE9BE8032BC1A3FD2E 7FF74579B983F717F5D8B81D6D78E5884707E9401C54781E28207F7B9AF75FFB BFF5DCCFA9DB5784681401CEF8C016B7840FEF0AF4F2EF899333921185E4F241 ED5EB999DD786A4F33498FDB8AF071B1B55D0D626AD718C2800ED42D7403CFF5 C9049A9CAD9EF8AFA3C3AE5A69193DC3416CEAD082723B5189FE1305B9E815F3 86A1401CDF8CB0618B271F357A9976EC899A5E1FE74B8EB9317FC46547634AB9 864575FF001EB2FF00BA6AE9FC4819E731E3FB4171FF003D3FAD7D2BF80C8F48 87FD427FBA2BE665BB351F52063F8A79D2DBEB5DD81FE27F5E64CF638B5EB5EF 9892A75A04588DB9A605A89B14C0BA14490B21C61854B19CE4F0986564231E95 235643012BD091F8D268B5292D98EF3E5C001DB8F7A5C91EC5AC4545D4B7A54E CD7055989056B1AD0F76C81D5949FBCEE6C579C014016ADF98BAD653DC63C9A9 18D7601092718AD6946F214B439390E66739CE4F5AF711CEC721C1ABB92CB08F 8A622C452670067269823A7B08FECD64A0F0CC326A59688E69C55586549243CD 3115DE4E0D226E40EDC5022266A0442C69011B1A0633DE9001A0091222C320D0 05B86CCB76AA02796C781C76A40519EDB6D3028CA98A968A432003CF4DC48F98 63F3A928F538BFD527FBA2A0673DE352069F16467E7A00CAF071C5E4E074DA2B CDCC3E05FD762E075B5E39607A1A00E5069F38F11190447686CEEAF63DB43D85 AFFD5C8B1D5D78E5850073DE31245A478383BBAD7A797EEFFAEE4C8E44065036 3735EB999D7F84252F62EA7F84D78D9846D24CD227415E7141400D90ED89CFA0 A71DC0F38BD606EA563DDCF26BE9A9AB46C64CB3A211FDA909039FD2B3C4FF00 0D82DCF40AF9C350A00C2F155A4B736B1F929B886AEFC0D48C1BE62248BFA242 F069D1A4830C074AC3132529B68A5A17AB9D8C8AEBFE3D64FF0074D5D3F89033 CEA3522F558636F99FD6BE95FC2647A3C3FEA53FDD15F332DD9A8FA9032FC430 4971A798E252CD9E95D7839C613BC852472BFD8B7D9E6135ECFD6A977FC8CB94 AF24325BC9E5C836B0ED5BC66A6AE84D5892338157B1162D44714C65C85FB66A 40AFAA5A79C9E6A72CBE94866211C91E948625003A391A270E9D450F50B9B569 7F1CE00FB920FE135C55285B589A265BED9ED5C6D1459B7FF57F8D653DC68733 0552CC4003B9AA853727640D9837FAB34DBA287023C726BD4A38750D5993919C 3835D440F538A62648AD4C5636343B3F365F3A41FBB5E9EE698EC6D4F3633834 C65192424D315C8198D02B903352111B1A0446C68018E703DE90C8DBAE050034 FDEC74A40039A065DB58F24706992743A75A82809149B2D22ECB6B1B29E3B54A 6558C2D42DF63118AD0CCC3BA4C66931A2AC1CDC2023AB0EBDB9A8651EA517FA A4FA0A828E7FC6A33A745D07CFD4D0062784E409A8302C3E7000AE0C72BC0A83 3B2E95E21A05001819CE28BB185020A00E5FC64FB8C3103EE457AD97C746C991 CC84C67E720E3815EA199D2F8364F9A68CF53CD799984744CB89D4D790585004 17CFB2CA53FEC9AD292BC903D8F3661F36E739CD7D368625AB093C9D4227CF19 E959D55CD0B02DCF45520A822BE64DC5A3D0418CD00147A8050055D4E41169D3 B13D14D6B423CD51048F3E879BD8FD77E71F8D7D1CBE16647A443FEA13FDD15F 332DD9A8FA900A0028B81C47884E357939EC2BE8B06FF74BFAEA6332946C4815 D6413C672704E29816236C1A00B9138231ED486676A1A7658CB0AFD452B0CCA2 A41C11CD2010D0000E0E4718E940CD3B2D4BF8273927A3573D4A2A5AC77294AC 6BB5C476F6DE63B0DBDB1DEB85509CA562DC91857FA83DDC836E52303EEFAD7A 34A8A87A993653C7BD6C48A2980F04753C5005ED3EC24BC901C623CF24D588E9 37A430AC51F0AB4EC3B95A4933EB458457793AD3110B3F3484309A0444CD400C 27078A40318D031A4E3A5202339CE49E6801637C1A0669D9CB82338A649D2E9F 3298F19A97A9A265A7955149CD4A43B9817F73B998F15A233660DD4C4B1E9430 4548DB33C7FEF8FE75059EA517FAA4FA0A828E7BC6C33A745919F9E80391B4B8 36570B32F054D67521CF1B02D0EDAC75AB3BC452B28573D54D787570B3874354 D178488DD1D7F3AC3925D87A06F5FEF0FCE9724BB00191075751F8D3E49F602A DCEAD676AA4BCCBC761D6B4861AA49E8857388D5EF9B52BE32E085070A2BDDA1 4BD94394CDB2BAAAA91939E2B611AFE1897C8D498C876AB2D716360E50F74B89 D7FDAA0FF9EABF9D78BECA7D8B0FB4C3FF003D17F3A7ECA7D80A1ADDD4634D94 248A5BD01AE8C35297B45744B670837FCAA3903B57BC6601BE6CF718C51B0CEC 745F105B496C915C3EC95477AF1B11839293715A16A46D25C44E32B229FC6B85 D39AE855C7EF4FEF2FE753CAFB05C4F313FBC3F3A3965D808E5BCB7846649500 FAD5C694DEC82E733E24D723B880DB5AB6E53F79ABD4C2615C5F3C910E5739EB 727ED31331FE2EB5E8497BA41E8B15CC0214CCAA3E51DEBE7654E77D8DAE3FED 507FCF55FCEA3D94FB05C3ED507FCF55FCE9FB29F60D03ED50FF00CF45FCE8F6 53EC174719AF3ABEAB2329046073F9D7BF848B8D24998CCA0871D6BA88264603 BD302746C9A009E36C500598E5046290C82EF4E8EE0164F95A9580C89ECE680F CC9F88A455C8318A004C66988716665DA5891D81E828B59DC350C1CD1D042819 A064D0DACB2FDC434C4695B68C4E1E73803A8F5AB480D65748A3D91A8503A62A 90103C82826E40F271D680B91331A42232D4086EEF43400D249E6900C271C8EB 40C616C8C76A006134806B5031A1B9A00B304FB714C46A5BDFEDC60D302C4FA8 92A39ED4AC3B9957375B89A0467CAFB89E693191C1CDC47FEF8FE750CB47AA45 FEA93FDD152339DF1C67FB322C67FD6500714D965C139CD00370D19C9C8F7145 93DC0984B2820ACEEA3FDEA9F6717D0079BC9C0E2690E3A9DD53ECA1D877644D 3CEE30D33903AFCC79A6A9C5740BB10CAFB496EDD09E6AD462B616A28CB20246 DA006C5804E0F2450048728DF393BB1C60D1656B0081DDDBE77607D8D2505D80 53E68FBACFF89A7C8BB0AE35DA444019987AE4D1CA9740B91B7CA32A4B7BD031 070C0E0B1F7A0090927E63C0F4A01122348ABF248E31FED54B845EE8016E6E88 3FBE7E3DEA7D9C3B0EE37ED574F906693FEFAA6A9C1740BB180B3E43C8E7F1AA B25D0427723B530107DE03A1ED45807ABBB213E6B647BD2E58DF60104AFF00DE 7FFBEA8E58F601C1DCFF001BFF00DF54722EC2B8BBDBFBEFF9D3E45D804C9249 39CE2A924B4421EBD78E6801EADCD31132B63BD302547A604C9262802C4731A0 09C32B8E71480825D32DE539FBBF4A561DCACDA1AFF0B9A2C1713FB098F490D0 04B1E803F8E4345865C8745B688E4FCD458572E058A04C22815490AE549A6E78 E2A91372BB4B4C2E44D2E69088CBE681885B8EB4843738183D4D0034B05E78A0 6337119A006E7079E9400C63814806673400D6CF41CD219196A2E55872B9A2E2 B12ACC47434EE4D8925B825473DA8B8EC576933D4D2B8EC465B340EC2C3CCF1F AEF1FCEA58CF558BFD527FBA2A4673FE34491F4E8FCA46621FA019A00E3D6CE7 0819ADA627FDC3400D6B5B91FF002EF2F3DB69A0056B3B9D8336F27E08680116 D2E54E45ACA79E850FF850037EC974BC0B69B1FF005CCD003CDADC201FE8F337 B7967FC28015AD6E594620947B6C3400C36373B430B7941FF70D002B5B5D3119 B59CB0EFE59A009EDED27F3B2D6F263FDC35484CBF2E9A5610444E49FF0064D5 E8419B25B5C6EC8B694F6E54F4ACD96884DADDA9005BC981FEC1A4324FB1DD19 06209003D7E434008F65739DBE44A71D0EC3400A2CAE718F225FFBE4D0002CEE 78FDCCBFF7C1A6037EC770AE48B69B1FEE1A4037EC77433FE8F363FEB99FF0A0 077D92E7685FB3CD91DFCB3FE140082D2E00FF008F7989F5D86800FB1DCA8C8B 69BFEFD9A003EC973C7FA34DFF007ECFF85004B1DB5C679825FF00BE0D5123E4 B59B3F2DBC9FF7C1A77023FB25C7FCFBCBFF007C1A4002D6E32316F281FEE1A0 63C5ADC7FCF093FEF834EE4D8916DAE33FEA24FF00BE4D170B12ADBDC600F264 FF00BE4D170B122C13E3FD4C9FF7C9A770B122C337FCF293FEF934F40B122A4E 07FAA7FF00BE4D2D02C4AAB37FCF37FF00BE4D0161EBE70FF964FF00F7C9A616 241E70FF00966FF91A3401E0CA3FE59BFE468D0053E6FF0071FF00EF934681A9 14BE6E3FD5BFFDF269DD0B5294D1CE4FFAA93FEF9345D0ACC88C53FF00CF193F EF9345D05988609F19F264FF00BE4D17416637C99F9FDCC9FF007C9A2E83510D BCEBCF932E7FDD345D06A060B82A3F7327FDF268BA0D46F913E7FD4487FE0268 BA0D4436D70467C993FEF9345D06A345BCF8FF0053263FDD34AE87A8D36F7047 FA993FEF934AE87A8C6B6B81D2097FEF8345C2C06D2E36E44120FF00809A2E16 23FB25CE7FE3DE5FFBE0D2189F64B9FF009E12FF00DF26900A2D2E7FE784BFF7 C1A770B120B2B8239825FF00BE0D3B80C7B2B91FF2C25FFBE4D2B80DFB1DCE33 E44BFF007C1A2E3161B4B913479825C071FC07D6A40F508C62241EC290C75002 D0025001400B400500140050025002D0021A002810503168012800A002800A00 5A004A00280168012800A002800A002800A002800A005A0028012800A4014005 0014C02800A002800A002800A002800A002800A002800A002800A002800A0028 00A005A004A002800A005A00FFD9} Pictures.PicEnter.Data = { 0A544A504547496D6167650F090000FFD8FFE000104A4649460001000100C800 C80000FFFE001F4C45414420546563686E6F6C6F6769657320496E632E205631 2E303100FFDB008400150E0F120F0D15121112171615191F34221F1D1D1F402E 3026344C43504F4B434948545F79665459725B4849698F6A727D818789875165 959F93849E79858782011617171F1B1F3E22223E825749578282828282828282 8282828282828282828282828282828282828282828282828282828282828282 82828282828282828282FFC401A2000001050101010101010000000000000000 0102030405060708090A0B010003010101010101010101000000000000010203 0405060708090A0B100002010303020403050504040000017D01020300041105 122131410613516107227114328191A1082342B1C11552D1F02433627282090A 161718191A25262728292A3435363738393A434445464748494A535455565758 595A636465666768696A737475767778797A838485868788898A929394959697 98999AA2A3A4A5A6A7A8A9AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3 D4D5D6D7D8D9DAE1E2E3E4E5E6E7E8E9EAF1F2F3F4F5F6F7F8F9FA1100020102 0404030407050404000102770001020311040521310612415107617113223281 08144291A1B1C109233352F0156272D10A162434E125F11718191A262728292A 35363738393A434445464748494A535455565758595A636465666768696A7374 75767778797A82838485868788898A92939495969798999AA2A3A4A5A6A7A8A9 AAB2B3B4B5B6B7B8B9BAC2C3C4C5C6C7C8C9CAD2D3D4D5D6D7D8D9DAE2E3E4E5 E6E7E8E9EAF2F3F4F5F6F7F8F9FAFFC000110800460099030111000211010311 01FFDA000C03010002110311003F00EC6800A00AF2DCAC726CEFC66802432056 DA724FB0A007820F7A0028016800A002800A002800A002800A002800A002800A 002800A00280239A55862691BA0A00C0696679492E577364D006A240B73FBC57 78E4031B94D004CA248F1E664E3B8EF400EF3C6F0A15F9E9C7140130391400B4 0050014005001400500140050014005001400500140050043748B25BBAB1C0C7 5A00E7E571180719A00D059A5B6B44995786F6A00B1697924CBFBC8C8CF7038A 008A713437036CA029ECD4016EDA51213F3EE2074C6050058A002800A002800A 004A002800A0028010B01D48A00AD26A30240F329322A1C36C19C5572B02C46D BD15B18C8CE2A407520169808CA194A919068039BD4E0F22F36E7E538C1A00D9 8AE22680220DF85E4628025B764D9F20017D3D2802B5F7CF711A08D9C91D4741 40166D6110A74C13DB39C5004F4005001400500577BD8118A6EDCE3AAA8C914F 940641A8C13CE611BD24033B5D4AE47B5371690129BA84305F314927000E79A5 CAC08E0BD59EEA580232B458C96E334DC6CAE053B8B8B9FB74B6C642B98F7C3B 1793F5FD2A92D2E21250F6DA8DB4B23A869D3CB7C9C8DDD7814277880B6D1B47 2DF5ABA131C84BAB05C0E4722876B26049A7DD2C10416D732C667E1708739A52 8DF54068D45C62D0014019BABDBEF8C4A1412BD734011D8452C9132891941E87 23F95004F6D13C19563BB9A00BA8303DE8016800A002801934D1C11992575441 D598F0284806C570933109BB819C91C1A6E2D014E7C5B6B104800093A98D8FFB 439154AEE22175688BB5AB46079AB30DA71DBBFE9441F4190A28B5D4A78D0384 70250A89904F423F4A77BC508926568AF96F03470868B63873CE7A8A4B556029 DC6A368258A5692496688100C7F2835A469BD82E4171ACDCDCB298A055E70A4A EE39AB5492DC570FB26A37132477533A0933824F19F4E28E6847602B59AA45AE 2C31B8711C80161EB439F341858EBAB94A16800A00A5A8480C5E5AB0DC48C8A0 0AB01DADF2C786F514017E3438C9EB4013E401CF6A00AAFA84223DD16E9B9231 18CF4EB55CAFA80B6376D791097CA291B282B9393F8D2924808A598BEA62D5C9 54F2F7800FDE39A6B45702316E16EA6B5C96B79622C4373B4F4A77D2E21DA3B3 B5A2F9BE6EE51B4EF181C7A513B5F4042EA4D6D2468B25C796518382BC9E288A 60CAADA947110F144EEC780F21E2AD53E8C2E39FEDD3BC91B4E23611EF0231F7 87D695E2BA015A6B28A42D1C792EF079AACE771E0F34D5569DC07C5696AD0A88 A1F9DE2F3519B9391D4527524162C4CC658C9882ECF2D678703A11D4566057BD BE8562FB47DA2311EE592344FBCCDDF34D277B0CCFB592397C4025854AC52480 8C8EFDEB7B3507724EB6B98A0A00AF7D3ADBDB176380485EBDC9C534AE05286C A78A625A40F191D877A1DAC037EDE89E76CB7918C040903614FE1EB55C96D409 239E69EEEE2D5A4F2FF741E3D830403FD68695AE229D9DC8492096E4C89B418E 4949CABB67183E95725D10176C1BCABCB981518C45B7A10BF28C8E467EB512DA E049A6C32DA47224A1122DE593E6C9009EF4A4EE316EDED2503CD1BD97A15EA3 F1A693115DAF59158C10ED07AB1E4D528F70209BCF9A20CD70416059533F780E B8A7CD18B018B140C91C71A65E58CBAB93DC76A1CDEE16219A5379A412A8A8D0 306C0F4EF4AF6F780B7A7DCA4966CCF20592153824F514548D9DC115AE754B61 73653DB12DB410EA074523FC688C1B02A9D4AE59912D6208239098C91B9B07B5 5AA4BA8AE3A2D2F53BA4556322A2E71BDB681F853BC2205DB7F0CC6B8334BF82 0C7EB52EB7643B1A76DA65A5B3068E11B87463C9ACE55252DC762DD400500327 8639E268E540E8C39523AD09D80C99ACAD3CA0D6323A4CAC360591BAE7A11E95 A272EA22CBDA4875659C44A6331E1CB1E323A103D695D72D80965B557BD8EE7C D6528A542A8EBF5A9BE9618B1DBC10990C717321CB9639DDF9D36DBD1885791F 180703DA8B015E4C9EA49FAD5AD35020715480584CAC7233E5C4A4945FE33E95 13480A96F22430C22E9F64D6EDBB18CF07B526AE05782FA44899A3815B6C8C61 DE70541AA50BA0B91C1637335AB420484B93B9978EB5A5A295988BB0E8133205 9595140C63A9A4EAA5A21D8BF06856917DF0D21F73C566EACBA058BF141142B8 8E3541EC3150DB7B8C7D200A0028016800A0028018B1A212551549EB81400A54 1EB4006D03B5001B07A50034C487B53B80D36D19EC7F3A2E034D9C27B1FCE9F3 301A6C622A5417507AED6C52726046BA45A2E76A364F53B8F34D4D8589A3B2B7 8BEEC4B9F53CD0E6D8589C0C0C0A9016800A002800A002800A002803FFD9} end object JvHotLink2: TJvLabel Left = 0 Top = 155 Width = 529 Height = 18 Cursor = crHandPoint Align = alTop Alignment = taCenter AutoSize = False Caption = 'Click here to send Ralf Grenzing (MegaDemo developer) a mail' Font.Charset = DEFAULT_CHARSET Font.Color = clBlue Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] Layout = tlCenter ParentFont = False AutoOpenURL = False HotTrack = True HotTrackFont.Charset = DEFAULT_CHARSET HotTrackFont.Color = clBlue HotTrackFont.Height = -11 HotTrackFont.Name = 'MS Sans Serif' HotTrackFont.Style = [fsBold, fsUnderline] ImageIndex = 0 URL = 'mailto:RalfGSpam@gmx.de?subject=JVCL MegaDemo' end object JvHotLink3: TJvLabel Left = 0 Top = 173 Width = 529 Height = 24 Cursor = crHandPoint Align = alTop Alignment = taCenter AutoSize = False Caption = 'Click here to see the standard JVCL about dialog with JVCL relat' + 'ed links' Font.Charset = DEFAULT_CHARSET Font.Color = clBlue Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] Layout = tlCenter ParentFont = False OnClick = JvHotLink3Click AutoOpenURL = False HotTrack = True HotTrackFont.Charset = DEFAULT_CHARSET HotTrackFont.Color = clBlue HotTrackFont.Height = -11 HotTrackFont.Name = 'MS Sans Serif' HotTrackFont.Style = [fsBold, fsUnderline] ImageIndex = 0 URL = ' ' end object frmh_st: TJvScrollText Left = 8 Top = 203 Width = 521 Height = 137 Alignment = taLeftJustify Items.Strings = ( 'Welcome to the Demo Program of the JEDI-VCL components.' '' 'Please read the text above as in introduction.' '' 'This MegaDemo was created by:' ' ' 'Ralf Grenzing ' 'Uwe Rupprecht' '' 'of course using the existing demos ...' '' '' '' 'completly reworked in 2005 by Ralf Grenzing') BackgroundColor = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'MS Sans Serif' Font.Style = [] end object JvRichEdit1: TJvRichEdit Left = 11 Top = 345 Width = 513 Height = 182 BorderStyle = bsNone Color = clBtnFace Lines.Strings = ( 'These MegaDemo offers you various possibilties to look at the ve' + 'ry many demos which are availible:' '' '1. Right at the top you find a PageControl, in which are all com' + 'ponents listed as they are in' 'the Delphi IDE! Just click at one you are in iterested in! Note ' + 'that only comps are listed' 'for which demos exists!' '' '2. On the left you find "search by component". These is useful w' + 'hen you want to know if there is' 'a demo for a specific component you are in terestedin! Type only' + ' the first letter and you are done!' '' '3. "browse all demo stuff": Beside the demos which show the usag' + 'e of JVCL component, the ' 'MegaDemo contains also stuff which is not specific for a compone' + 'nt. E.g Hidden Gems,' 'Ressources etc. In this list are all availible MegaDemo stuff is' + ' listed! So if you do not miss ' 'anyhing you should go from here! It is probably the best startin' + 'g point if you are new to the' 'JVCL MegaDemo!') ReadOnly = True ScrollBars = ssNone TabOrder = 1 end object JvJVCLAboutComp: TJvJVCLAboutComponent Left = 425 Top = 248 end end
57.571956
76
0.862261
fcf618ba26c2465ab1bbef2ba634d112a18a1283
369
pas
Pascal
PascalCompiler/Tests/Generator/ArraysAndRecords/08.pas
GoldFeniks/PascalCompiler
4a7325c385c133dd360eaba06bebaedd30b4078d
[ "MIT" ]
2
2018-07-06T09:50:57.000Z
2019-10-06T12:57:57.000Z
PascalCompiler/Tests/Generator/ArraysAndRecords/08.pas
GoldFeniks/PascalCompiler
4a7325c385c133dd360eaba06bebaedd30b4078d
[ "MIT" ]
null
null
null
PascalCompiler/Tests/Generator/ArraysAndRecords/08.pas
GoldFeniks/PascalCompiler
4a7325c385c133dd360eaba06bebaedd30b4078d
[ "MIT" ]
null
null
null
program test; var a: array [1..10] of integer; b: record i: integer; r: real; c: char; end; i, j: integer; begin i := 2; j := 5; b.i := 3; b.r := 1.5; b.c := #10; a[b.i] := 318; a[integer(b.r)] := 221; a[integer(b.c)] := -9033; write(a[b.i], b.c, a[integer(b.r)], b.c, a[integer(b.c)]); end.
16.772727
62
0.425474
477c7eda7687ecd8dd598f781db3a3573eba4129
10,597
pas
Pascal
Provect.ModalController.pas
homolibere/provect-delphi
ee019dcccad7fde7b2903679f9710550befa18d5
[ "MIT" ]
null
null
null
Provect.ModalController.pas
homolibere/provect-delphi
ee019dcccad7fde7b2903679f9710550befa18d5
[ "MIT" ]
1
2017-12-14T05:34:49.000Z
2017-12-14T09:10:36.000Z
Provect.ModalController.pas
homolibere/provect-delphi
ee019dcccad7fde7b2903679f9710550befa18d5
[ "MIT" ]
null
null
null
unit Provect.ModalController; interface uses System.SysUtils, System.Classes, System.UITypes, System.Threading, FMX.Controls, FMX.TabControl, FMX.Forms, FMX.Types, FMX.Objects; type TFrameClass = class of TFrame; TModalController = class(TTabControl) private FWaitTask: ITask; FWaitTaskFuture: IFuture<Boolean>; FModalResult: TModalResult; function InternalCheckCurrent(const AClassName: string): Boolean; procedure InternalModal(const ATab: TTabItem; const AProc: TProc; const AFunc: TFunc<Boolean>); protected function IsInitialized: Boolean; function IsModal: Boolean; function IsWaitingTask: Boolean; procedure CallOnShow; property ModalResult: TModalResult read FModalResult write FModalResult; public class procedure CloseHide; class function CheckCurrent(const AFrame: TFrame): Boolean; overload; class function CheckCurrent(const AFrame: TFrameClass): Boolean; overload; class procedure EscapeHide; class procedure Hide(ANumber: Integer); reintroduce; overload; class procedure Hide(const AControl: TFrame); reintroduce; overload; class procedure HideModal(ANumber: Integer; AModalResult: TModalResult); reintroduce; overload; class procedure HideModal(const AControl: TFrame; AModalResult: TModalResult); reintroduce; overload; class procedure SetStyle(const AStyleName: string); class function Show(const AControl: TFrame): Integer; reintroduce; overload; class function Show(const AFrame: TFrameClass): Integer; reintroduce; overload; class function ShowModal(const AControl: TFrame; const AProc: TProc): TModalResult; overload; class function ShowModal(const AFrame: TFrameClass; const AProc: TProc): TModalResult; overload; class function ShowModal(const AFrame: TFrameClass; const AFunc: TFunc<Boolean>): TModalResult; overload; end; implementation uses System.Rtti, FMX.ActnList, FMX.Ani; var _ModalController: TModalController; function CheckModalController: Boolean; begin if not Assigned(_ModalController) then _ModalController := TModalController.Create(nil); Result := Assigned(_ModalController); end; { TModalController } class procedure TModalController.Hide(ANumber: Integer); begin if CheckModalController and _ModalController.IsInitialized and (_ModalController.TabCount > ANumber) and not _ModalController.IsWaitingTask and (_ModalController.ActiveTab.Index = ANumber) and not _ModalController.IsModal then begin if _ModalController.TabCount = 1 then begin TAnimator.AnimateFloat(_ModalController, 'Opacity', 0); _ModalController.Visible := False end else _ModalController.Previous(TTabTransition.Slide, TTabTransitionDirection.Reversed); _ModalController.Tabs[ANumber].Enabled := False; end; end; class procedure TModalController.Hide(const AControl: TFrame); var Item: TTabItem; I: Integer; begin if CheckModalController and Assigned(AControl) and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin for I := 0 to Pred(_ModalController.TabCount) do begin Item := _ModalController.Tabs[I]; if Item.StylesData['object-link'].AsType<TFrame> = AControl then begin TModalController.Hide(Item.Index); Break; end; end; end; end; class procedure TModalController.HideModal(ANumber: Integer; AModalResult: TModalResult); begin if CheckModalController then begin _ModalController.ModalResult := AModalResult; _ModalController.Hide(ANumber); end; end; class procedure TModalController.HideModal(const AControl: TFrame; AModalResult: TModalResult); begin if CheckModalController then begin _ModalController.ModalResult := AModalResult; _ModalController.Hide(AControl); end; end; procedure TModalController.CallOnShow; var Rtti: TRttiMethod; RttiClass: TObject; begin RttiClass := _ModalController.ActiveTab.StylesData['object-link'].AsObject; for Rtti in TRttiContext.Create.GetType(RttiClass.ClassInfo).GetDeclaredMethods do begin if CompareText(Rtti.Name, 'FrameShow') = 0 then Rtti.Invoke(RttiClass, []); end; end; class function TModalController.CheckCurrent(const AFrame: TFrameClass): Boolean; begin Result := _ModalController.InternalCheckCurrent(AFrame.ClassName); end; class function TModalController.CheckCurrent(const AFrame: TFrame): Boolean; begin Result := _ModalController.InternalCheckCurrent(AFrame.ClassName); end; class procedure TModalController.CloseHide; begin if CheckModalController and _ModalController.IsInitialized and _ModalController.Visible and not _ModalController.IsWaitingTask then begin while Assigned(_ModalController.ActiveTab) do begin _ModalController.ModalResult := mrAbort; _ModalController.Hide(_ModalController.ActiveTab.Index); end; end; end; class procedure TModalController.EscapeHide; begin if CheckModalController and _ModalController.IsInitialized and _ModalController.Visible and not _ModalController.IsWaitingTask then begin _ModalController.ModalResult := mrAbort; _ModalController.Hide(_ModalController.ActiveTab.Index); end; end; function TModalController.InternalCheckCurrent(const AClassName: string): Boolean; begin Result := False; if CheckModalController and _ModalController.IsInitialized and _ModalController.Visible then Result := _ModalController.ActiveTab.StylesData['object-link'].AsType<TFrame>.ClassName = AClassName; end; procedure TModalController.InternalModal(const ATab: TTabItem; const AProc: TProc; const AFunc: TFunc<Boolean>); begin ATab.StylesData['IsModal'] := True; try if Assigned(AProc) then begin FWaitTask := TTask.Create(AProc); FWaitTask.Start; while IsWaitingTask do begin Application.ProcessMessages; Sleep(100); end; HideModal(ATab.Index, mrOk); FWaitTask := nil; end else if Assigned(AFunc) then begin FWaitTaskFuture := TFuture<Boolean>.Create(TObject(nil), TFunctionEvent<Boolean>(nil), AFunc, TThreadPool.Default); FWaitTaskFuture.Start; while IsWaitingTask do begin Application.ProcessMessages; Sleep(1); end; if FWaitTaskFuture.Value then HideModal(ATab.Index, mrOk) else HideModal(ATab.Index, mrCancel); FWaitTaskFuture := nil; end else begin while ATab.Enabled do begin Application.ProcessMessages; Sleep(100); end; end; finally ATab.StylesData['IsModal'] := False; end; end; function TModalController.IsInitialized: Boolean; var I: Integer; TabsDisabled: Boolean; begin Result := Assigned(Parent); if not Result then begin if Assigned(Application) and Assigned(Application.MainForm) then begin Application.MainForm.AddObject(_ModalController); _ModalController.Align := TAlignLayout.Contents; _ModalController.TabPosition := TTabPosition.None; _ModalController.Visible := False; _ModalController.Opacity := 0; end; Result := Assigned(Parent); end else begin TabsDisabled := True; while TabsDisabled and (TabCount > 0) do begin for I := 0 to Pred(TabCount) do begin TabsDisabled := False; if not Tabs[I].Enabled then begin Delete(I); TabsDisabled := True; Break; end; end; end; end; end; function TModalController.IsModal: Boolean; begin Result := ActiveTab.StylesData['IsModal'].AsBoolean and (ModalResult = mrNone); end; function TModalController.IsWaitingTask: Boolean; begin Result := (Assigned(FWaitTask) and not FWaitTask.Wait(10)) or (Assigned(FWaitTaskFuture) and not FWaitTaskFuture.Wait(10)); end; class function TModalController.Show(const AControl: TFrame): Integer; var Item: TTabItem; begin Result := -1; if CheckModalController and Assigned(AControl) and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin _ModalController.ModalResult := mrNone; _ModalController.BeginUpdate; try Item := _ModalController.Add; Item.AddObject(AControl); AControl.Align := TAlignLayout.Center; Item.StylesData['object-link'] := AControl; Result := Item.Index; finally _ModalController.EndUpdate; end; _ModalController.BringToFront; _ModalController.Visible := True; if _ModalController.TabCount = 1 then begin _ModalController.ActiveTab := Item; TAnimator.AnimateFloat(_ModalController, 'Opacity', 1); end else _ModalController.Next(TTabTransition.Slide, TTabTransitionDirection.Reversed); _ModalController.CallOnShow; end; end; class procedure TModalController.SetStyle(const AStyleName: string); begin if CheckModalController then _ModalController.StyleLookup := AStyleName; end; class function TModalController.Show(const AFrame: TFrameClass): Integer; var TempFrame: TFrame; begin Result := -1; if CheckModalController and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin TempFrame := AFrame.Create(nil); Result := TModalController.Show(TempFrame); end; end; class function TModalController.ShowModal(const AFrame: TFrameClass; const AFunc: TFunc<Boolean>): TModalResult; var Tab: TTabItem; begin Result := -1; if CheckModalController and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin Tab := _ModalController.Tabs[Show(AFrame)]; _ModalController.InternalModal(Tab, nil, AFunc); Result := _ModalController.ModalResult; end; end; class function TModalController.ShowModal(const AFrame: TFrameClass; const AProc: TProc): TModalResult; var Tab: TTabItem; begin Result := -1; if Assigned(AProc) and CheckModalController and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin Tab := _ModalController.Tabs[Show(AFrame)]; _ModalController.InternalModal(Tab, AProc, nil); Result := _ModalController.ModalResult; end; end; class function TModalController.ShowModal(const AControl: TFrame; const AProc: TProc): TModalResult; var Tab: TTabItem; begin Result := -1; if Assigned(AProc) and CheckModalController and _ModalController.IsInitialized and not _ModalController.IsWaitingTask then begin Tab := _ModalController.Tabs[Show(AControl)]; _ModalController.InternalModal(Tab, AProc, nil); Result := _ModalController.ModalResult; end; end; end.
30.105114
127
0.74304
c339cb32ba4e9d7c5c3dc0175a0351ffd89d7b41
11,743
pas
Pascal
src/libraries/hashlib4pascal/HlpBlake2BP.pas
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
384
2016-07-16T10:07:28.000Z
2021-12-29T11:22:56.000Z
src/libraries/hashlib4pascal/HlpBlake2BP.pas
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
165
2016-09-11T11:06:04.000Z
2021-12-05T23:31:55.000Z
src/libraries/hashlib4pascal/HlpBlake2BP.pas
rabarbers/PascalCoin
7a87031bc10a3e1d9461dfed3c61036047ce4fb0
[ "MIT" ]
210
2016-08-26T14:49:47.000Z
2022-02-22T18:06:33.000Z
unit HlpBlake2BP; {$I HashLib.inc} interface uses SysUtils, {$IFDEF USE_DELPHI_PPL} System.Classes, System.Threading, {$ENDIF USE_DELPHI_PPL} {$IFDEF USE_PASMP} PasMP, {$ENDIF USE_PASMP} {$IFDEF USE_MTPROCS} MTProcs, {$ENDIF USE_MTPROCS} HlpHash, HlpIHashResult, HlpBlake2B, HlpIBlake2BParams, HlpBlake2BParams, HlpIHash, HlpIHashInfo, HlpArrayUtils, HlpHashLibTypes; type TBlake2BP = class sealed(THash, ICryptoNotBuildIn, ITransformBlock) strict private type PDataContainer = ^TDataContainer; TDataContainer = record PtrData: PByte; Counter: UInt64; end; const BlockSizeInBytes = Int32(128); OutSizeInBytes = Int32(64); ParallelismDegree = Int32(4); var // had to use the classes directly for performance purposes FRootHash: TBlake2B; FLeafHashes: THashLibGenericArray<TBlake2B>; FBuffer, FKey: THashLibByteArray; FBufferLength: UInt64; /// <summary> /// <br />Blake2B defaults to setting the expected output length <br /> /// from the <c>HashSize</c> in the <c>TBlake2BConfig</c> class. <br />In /// some cases, however, we do not want this, as the output length <br /> /// of these instances is given by <c>TBlake2BTreeConfig.InnerSize</c> /// instead. <br /> /// </summary> function Blake2BPCreateLeafParam(const ABlake2BConfig: IBlake2BConfig; const ABlake2BTreeConfig: IBlake2BTreeConfig): TBlake2B; function Blake2BPCreateLeaf(AOffset: UInt64): TBlake2B; function Blake2BPCreateRoot(): TBlake2B; procedure ParallelComputation(AIdx: Int32; ADataContainer: PDataContainer); procedure DoParallelComputation(ADataContainer: PDataContainer); function DeepCloneBlake2BInstances(const ALeafHashes : THashLibGenericArray<TBlake2B>): THashLibGenericArray<TBlake2B>; procedure Clear(); constructor CreateInternal(AHashSize: Int32); {$IFDEF USE_PASMP} procedure PasMPParallelComputationWrapper(const AJob: PPasMPJob; const AThreadIndex: LongInt; const ADataContainer: Pointer; const AFromIndex, AToIndex: TPasMPNativeInt); inline; {$ENDIF USE_PASMP} {$IFDEF USE_MTPROCS} procedure MTProcsParallelComputationWrapper(AIdx: PtrInt; ADataContainer: Pointer; AItem: TMultiThreadProcItem); inline; {$ENDIF USE_MTPROCS} strict protected function GetName: String; override; public constructor Create(AHashSize: Int32; const AKey: THashLibByteArray); destructor Destroy; override; procedure Initialize; override; procedure TransformBytes(const AData: THashLibByteArray; AIndex, ADataLength: Int32); override; function TransformFinal: IHashResult; override; function Clone(): IHash; override; end; implementation { TBlake2BP } function TBlake2BP.Blake2BPCreateLeafParam(const ABlake2BConfig: IBlake2BConfig; const ABlake2BTreeConfig: IBlake2BTreeConfig): TBlake2B; begin Result := TBlake2B.Create(ABlake2BConfig, ABlake2BTreeConfig); end; function TBlake2BP.Blake2BPCreateLeaf(AOffset: UInt64): TBlake2B; var LBlake2BConfig: IBlake2BConfig; LBlake2BTreeConfig: IBlake2BTreeConfig; begin LBlake2BConfig := TBlake2BConfig.Create(HashSize); LBlake2BConfig.Key := FKey; LBlake2BTreeConfig := TBlake2BTreeConfig.Create(); LBlake2BTreeConfig.FanOut := ParallelismDegree; LBlake2BTreeConfig.MaxDepth := 2; LBlake2BTreeConfig.NodeDepth := 0; LBlake2BTreeConfig.LeafSize := 0; LBlake2BTreeConfig.NodeOffset := AOffset; LBlake2BTreeConfig.InnerHashSize := OutSizeInBytes; if AOffset = (ParallelismDegree - 1) then begin LBlake2BTreeConfig.IsLastNode := True; end; Result := Blake2BPCreateLeafParam(LBlake2BConfig, LBlake2BTreeConfig); end; function TBlake2BP.Blake2BPCreateRoot(): TBlake2B; var LBlake2BConfig: IBlake2BConfig; LBlake2BTreeConfig: IBlake2BTreeConfig; begin LBlake2BConfig := TBlake2BConfig.Create(HashSize); LBlake2BConfig.Key := FKey; LBlake2BTreeConfig := TBlake2BTreeConfig.Create(); LBlake2BTreeConfig.FanOut := ParallelismDegree; LBlake2BTreeConfig.MaxDepth := 2; LBlake2BTreeConfig.NodeDepth := 1; LBlake2BTreeConfig.LeafSize := 0; LBlake2BTreeConfig.NodeOffset := 0; LBlake2BTreeConfig.InnerHashSize := OutSizeInBytes; LBlake2BTreeConfig.IsLastNode := True; Result := TBlake2B.Create(LBlake2BConfig, LBlake2BTreeConfig, False); end; procedure TBlake2BP.Clear; begin TArrayUtils.ZeroFill(FKey); end; function TBlake2BP.DeepCloneBlake2BInstances(const ALeafHashes : THashLibGenericArray<TBlake2B>): THashLibGenericArray<TBlake2B>; var LIdx: Int32; begin System.SetLength(Result, System.Length(ALeafHashes)); for LIdx := System.Low(ALeafHashes) to System.High(ALeafHashes) do begin Result[LIdx] := ALeafHashes[LIdx].CloneInternal(); end; end; function TBlake2BP.Clone(): IHash; var LHashInstance: TBlake2BP; begin LHashInstance := TBlake2BP.CreateInternal(HashSize); LHashInstance.FKey := System.Copy(FKey); if FRootHash <> Nil then begin LHashInstance.FRootHash := FRootHash.CloneInternal(); end; LHashInstance.FLeafHashes := DeepCloneBlake2BInstances(FLeafHashes); LHashInstance.FBuffer := System.Copy(FBuffer); LHashInstance.FBufferLength := FBufferLength; Result := LHashInstance as IHash; Result.BufferSize := BufferSize; end; constructor TBlake2BP.CreateInternal(AHashSize: Int32); begin Inherited Create(AHashSize, BlockSizeInBytes); end; constructor TBlake2BP.Create(AHashSize: Int32; const AKey: THashLibByteArray); var LIdx: Int32; begin Inherited Create(AHashSize, BlockSizeInBytes); System.SetLength(FBuffer, ParallelismDegree * BlockSizeInBytes); System.SetLength(FLeafHashes, ParallelismDegree); FKey := System.Copy(AKey); FRootHash := Blake2BPCreateRoot; for LIdx := 0 to System.Pred(ParallelismDegree) do begin FLeafHashes[LIdx] := Blake2BPCreateLeaf(LIdx); end; end; destructor TBlake2BP.Destroy; var LIdx: Int32; begin Clear(); FRootHash.Free; FRootHash := Nil; for LIdx := System.Low(FLeafHashes) to System.High(FLeafHashes) do begin FLeafHashes[LIdx].Free; FLeafHashes[LIdx] := Nil; end; FLeafHashes := Nil; inherited Destroy; end; function TBlake2BP.GetName: String; begin Result := Format('%s_%u', [Self.ClassName, Self.HashSize * 8]); end; procedure TBlake2BP.Initialize; var LIdx: Int32; begin FRootHash.Initialize; for LIdx := 0 to System.Pred(ParallelismDegree) do begin FLeafHashes[LIdx].Initialize; FLeafHashes[LIdx].HashSize := OutSizeInBytes; end; TArrayUtils.ZeroFill(FBuffer); FBufferLength := 0; end; procedure TBlake2BP.ParallelComputation(AIdx: Int32; ADataContainer: PDataContainer); var LLeafHashes: THashLibGenericArray<TBlake2B>; LTemp: THashLibByteArray; LCounter: UInt64; LPtrData: PByte; begin System.SetLength(LTemp, BlockSizeInBytes); LPtrData := ADataContainer^.PtrData; LCounter := ADataContainer^.Counter; System.Inc(LPtrData, AIdx * BlockSizeInBytes); LLeafHashes := FLeafHashes; while (LCounter >= (ParallelismDegree * BlockSizeInBytes)) do begin System.Move(LPtrData^, LTemp[0], BlockSizeInBytes); LLeafHashes[AIdx].TransformBytes(LTemp, 0, BlockSizeInBytes); System.Inc(LPtrData, UInt64(ParallelismDegree * BlockSizeInBytes)); LCounter := LCounter - UInt64(ParallelismDegree * BlockSizeInBytes); end; end; {$IFDEF USE_PASMP} procedure TBlake2BP.PasMPParallelComputationWrapper(const AJob: PPasMPJob; const AThreadIndex: LongInt; const ADataContainer: Pointer; const AFromIndex, AToIndex: TPasMPNativeInt); begin ParallelComputation(AFromIndex, ADataContainer); end; {$ENDIF} {$IFDEF USE_MTPROCS} procedure TBlake2BP.MTProcsParallelComputationWrapper(AIdx: PtrInt; ADataContainer: Pointer; AItem: TMultiThreadProcItem); begin ParallelComputation(AIdx, ADataContainer); end; {$ENDIF} {$IF DEFINED(USE_DELPHI_PPL)} procedure TBlake2BP.DoParallelComputation(ADataContainer: PDataContainer); function CreateTask(AIdx: Int32; ADataContainer: PDataContainer): ITask; begin Result := TTask.Create( procedure() begin ParallelComputation(AIdx, ADataContainer); end); end; var LArrayTasks: array of ITask; LIdx: Int32; begin System.SetLength(LArrayTasks, ParallelismDegree); for LIdx := 0 to System.Pred(ParallelismDegree) do begin LArrayTasks[LIdx] := CreateTask(LIdx, ADataContainer); LArrayTasks[LIdx].Start; end; TTask.WaitForAll(LArrayTasks); end; {$ELSEIF DEFINED(USE_PASMP) OR DEFINED(USE_MTPROCS)} procedure TBlake2BP.DoParallelComputation(ADataContainer: PDataContainer); begin {$IF DEFINED(USE_PASMP)} TPasMP.CreateGlobalInstance; GlobalPasMP.Invoke(GlobalPasMP.ParallelFor(ADataContainer, 0, ParallelismDegree - 1, PasMPParallelComputationWrapper)); {$ELSEIF DEFINED(USE_MTPROCS)} ProcThreadPool.DoParallel(MTProcsParallelComputationWrapper, 0, ParallelismDegree - 1, ADataContainer); {$ELSE} {$MESSAGE ERROR 'Unsupported Threading Library.'} {$IFEND USE_PASMP} end; {$ELSE} procedure TBlake2BP.DoParallelComputation(ADataContainer: PDataContainer); var LIdx: Int32; begin for LIdx := 0 to System.Pred(ParallelismDegree) do begin ParallelComputation(LIdx, ADataContainer); end; end; {$IFEND USE_DELPHI_PPL} procedure TBlake2BP.TransformBytes(const AData: THashLibByteArray; AIndex, ADataLength: Int32); var LLeft, LFill, LDataLength: UInt64; LPtrData: PByte; LIdx: Int32; LLeafHashes: THashLibGenericArray<TBlake2B>; LPtrDataContainer: PDataContainer; begin LLeafHashes := FLeafHashes; LDataLength := UInt64(ADataLength); LPtrData := PByte(AData) + AIndex; LLeft := FBufferLength; LFill := UInt64(System.Length(FBuffer)) - LLeft; if (LLeft > 0) and (LDataLength >= LFill) then begin System.Move(LPtrData^, FBuffer[LLeft], LFill); for LIdx := 0 to System.Pred(ParallelismDegree) do begin LLeafHashes[LIdx].TransformBytes(FBuffer, LIdx * BlockSizeInBytes, BlockSizeInBytes); end; System.Inc(LPtrData, LFill); LDataLength := LDataLength - LFill; LLeft := 0; end; LPtrDataContainer := New(PDataContainer); try LPtrDataContainer^.PtrData := LPtrData; LPtrDataContainer^.Counter := LDataLength; DoParallelComputation(LPtrDataContainer); finally Dispose(LPtrDataContainer); end; System.Inc(LPtrData, LDataLength - (LDataLength mod UInt64(ParallelismDegree * BlockSizeInBytes))); LDataLength := LDataLength mod UInt64(ParallelismDegree * BlockSizeInBytes); if (LDataLength > 0) then begin System.Move(LPtrData^, FBuffer[LLeft], LDataLength); end; FBufferLength := UInt32(LLeft) + UInt32(LDataLength); end; function TBlake2BP.TransformFinal: IHashResult; var LHash: THashLibMatrixByteArray; LIdx: Int32; LLeft: UInt64; LLeafHashes: THashLibGenericArray<TBlake2B>; LRootHash: TBlake2B; begin LLeafHashes := FLeafHashes; LRootHash := FRootHash; System.SetLength(LHash, ParallelismDegree); for LIdx := System.Low(LHash) to System.High(LHash) do begin System.SetLength(LHash[LIdx], OutSizeInBytes); end; for LIdx := 0 to System.Pred(ParallelismDegree) do begin if (FBufferLength > (LIdx * BlockSizeInBytes)) then begin LLeft := FBufferLength - UInt64(LIdx * BlockSizeInBytes); if (LLeft > BlockSizeInBytes) then begin LLeft := BlockSizeInBytes; end; LLeafHashes[LIdx].TransformBytes(FBuffer, LIdx * BlockSizeInBytes, Int32(LLeft)); end; LHash[LIdx] := LLeafHashes[LIdx].TransformFinal().GetBytes(); end; for LIdx := 0 to System.Pred(ParallelismDegree) do begin LRootHash.TransformBytes(LHash[LIdx], 0, OutSizeInBytes); end; Result := LRootHash.TransformFinal(); Initialize(); end; end.
27.893112
80
0.749127
c3cab6ff009bd86b5fe66ab388e86245f6e8da7b
3,937
pas
Pascal
src/core/UAccountKeyStorage.pas
SkybuckFlying/PascalCoinSimplified
a3dbc67aa47bfe87a207e15abe8a31ea238fa74a
[ "MIT" ]
null
null
null
src/core/UAccountKeyStorage.pas
SkybuckFlying/PascalCoinSimplified
a3dbc67aa47bfe87a207e15abe8a31ea238fa74a
[ "MIT" ]
null
null
null
src/core/UAccountKeyStorage.pas
SkybuckFlying/PascalCoinSimplified
a3dbc67aa47bfe87a207e15abe8a31ea238fa74a
[ "MIT" ]
null
null
null
unit UAccountKeyStorage; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Classes, SysUtils, UAccounts, UThread, UBaseTypes; type TAccountKeyStorateData = record ptrAccountKey : PAccountKey; counter : Integer; end; PAccountKeyStorageData = ^TAccountKeyStorateData; { TAccountKeyStorage } // This class reduces memory because allows to reuse account keys // Based on tests, allows a 10-20% memory reduction when multiple accounts use the same Account key TAccountKeyStorage = Class private FAccountKeys : TPCThreadList; Function Find(list : TList; const accountKey: TAccountKey; var Index: Integer): Boolean; public constructor Create; destructor Destroy; override; function AddAccountKey(Const accountKey: TAccountKey) : PAccountKey; procedure RemoveAccountKey(Const accountKey: TAccountKey); class function KS : TAccountKeyStorage; function LockList : TList; procedure UnlockList; end; implementation uses ULog; var _aks : TAccountKeyStorage = Nil; { TAccountKeyStorage } function TAccountKeyStorage.Find(list : TList; const accountKey: TAccountKey; var Index: Integer): Boolean; var L, H, I: Integer; C : Integer; begin Result := False; L := 0; H := list.Count - 1; while L <= H do begin I := (L + H) shr 1; C := Integer(PAccountKeyStorageData(list[i])^.ptrAccountKey^.EC_OpenSSL_NID) - Integer(accountKey.EC_OpenSSL_NID); if C=0 then begin C := TBaseType.BinStrComp(PAccountKeyStorageData(list[i])^.ptrAccountKey^.x,accountKey.x); if C=0 then begin C := TBaseType.BinStrComp(PAccountKeyStorageData(list[i])^.ptrAccountKey^.y,accountKey.y); end; end; if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; L := I; end; end; end; Index := L; end; constructor TAccountKeyStorage.Create; begin FAccountKeys := TPCThreadList.Create('TAccountKeyStorage'); end; destructor TAccountKeyStorage.Destroy; Var l : TList; i : Integer; P1 : PAccountKeyStorageData; P2 : PAccountKey; begin l := FAccountKeys.LockList; try For i:=0 to l.Count-1 do begin P1 := l[i]; P2 := P1^.ptrAccountKey; Dispose(P1); Dispose(P2); end; l.Clear; finally FAccountKeys.UnlockList; end; FreeAndNil(FAccountKeys); inherited Destroy; end; function TAccountKeyStorage.AddAccountKey(const accountKey: TAccountKey): PAccountKey; var l : TList; i : Integer; P : PAccountKeyStorageData; begin Result := Nil; l := FAccountKeys.LockList; try If Find(l,accountKey,i) then begin Result := PAccountKeyStorageData(l[i]).ptrAccountKey; inc( PAccountKeyStorageData(l[i]).counter ); end else begin New(P); New(P^.ptrAccountKey); P^.counter:=1; P^.ptrAccountKey^:=accountKey; Result := P^.ptrAccountKey; l.Insert(i,P); end; finally FAccountKeys.UnlockList; end; end; procedure TAccountKeyStorage.RemoveAccountKey(const accountKey: TAccountKey); var l : TList; i : Integer; P : PAccountKeyStorageData; begin l := FAccountKeys.LockList; try If Find(l,accountKey,i) then begin P := PAccountKeyStorageData(l[i]); dec( P^.counter ); If P^.counter<0 then begin TLog.NewLog(lterror,Self.ClassName,'ERROR DEV 20171110-2'); end; end else begin TLog.NewLog(lterror,Self.ClassName,'ERROR DEV 20171110-1'); end; finally FAccountKeys.UnlockList; end; end; class function TAccountKeyStorage.KS: TAccountKeyStorage; begin if Not Assigned(_aks) then begin _aks := TAccountKeyStorage.Create; end; Result := _aks; end; function TAccountKeyStorage.LockList: TList; begin Result := FAccountKeys.LockList; end; procedure TAccountKeyStorage.UnlockList; begin FAccountKeys.UnlockList; end; initialization _aks := Nil; finalization FreeAndNil(_aks); end.
22.889535
118
0.688341
f1714127cf9a0281857cf4518d6bf331b4432729
44,629
pas
Pascal
windows/src/ext/jedi/jcl/jcl/source/windows/JclMultimedia.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jcl/jcl/source/windows/JclMultimedia.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jcl/jcl/source/windows/JclMultimedia.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
{**************************************************************************************************} { } { Project JEDI Code Library (JCL) } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 (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.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF } { ANY KIND, either express or implied. See the License for the specific language governing rights } { and limitations under the License. } { } { The Original Code is JclMultimedia.pas. } { } { The Initial Developers of the Original Code are Marcel van Brakel and Bernhard Berger. } { Portions created by these individuals are Copyright (C) of these individuals. } { All Rights Reserved. } { } { Contributor(s): } { Marcel van Brakel } { Robert Marquardt (marquardt) } { Robert Rossmair (rrossmair) } { Matthias Thoma (mthoma) } { Petr Vones (pvones) } { } {**************************************************************************************************} { } { Contains a high performance timer based on the MultiMedia API and a routine to open or close the } { CD-ROM drive. } { } {**************************************************************************************************} { } { Last modified: $Date:: $ } { Revision: $Rev:: $ } { Author: $Author:: $ } { } {**************************************************************************************************} unit JclMultimedia; {$I jcl.inc} {$I windowsonly.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} {$IFDEF HAS_UNITSCOPE} Winapi.Windows, System.Classes, Winapi.MMSystem, System.Contnrs, {$ELSE ~HAS_UNITSCOPE} Windows, Classes, MMSystem, Contnrs, {$ENDIF ~HAS_UNITSCOPE} JclBase, JclSynch, JclStrings; type // Multimedia timer TMmTimerKind = (tkOneShot, tkPeriodic); TMmNotificationKind = (nkCallback, nkSetEvent, nkPulseEvent); TJclMultimediaTimer = class(TObject) private FEvent: TJclEvent; FKind: TMmTimerKind; FNotification: TMmNotificationKind; FOnTimer: TNotifyEvent; FPeriod: Cardinal; FStartTime: Cardinal; FTimeCaps: TTimeCaps; FTimerId: Cardinal; function GetMinMaxPeriod(Index: Integer): Cardinal; procedure SetPeriod(Value: Cardinal); protected procedure Timer(Id: Cardinal); virtual; public constructor Create(Kind: TMmTimerKind; Notification: TMmNotificationKind); destructor Destroy; override; class function GetTime: Cardinal; class function BeginPeriod(const Period: Cardinal): Boolean; { TODO -cHelp : Doc } class function EndPeriod(const Period: Cardinal): Boolean; { TODO -cHelp : Doc } procedure BeginTimer(const Delay, Resolution: Cardinal); procedure EndTimer; function Elapsed(const Update: Boolean): Cardinal; function WaitFor(const TimeOut: Cardinal): TJclWaitResult; property Event: TJclEvent read FEvent; property Kind: TMmTimerKind read FKind; property MaxPeriod: Cardinal index 0 read GetMinMaxPeriod; property MinPeriod: Cardinal index 1 read GetMinMaxPeriod; property Notification: TMmNotificationKind read FNotification; property OnTimer: TNotifyEvent read FOnTimer write FOnTimer; property Period: Cardinal read FPeriod write SetPeriod; end; EJclMmTimerError = class(EJclError); // Audio Mixer { TODO -cDoc : mixer API wrapper code. Author: Petr Vones } EJclMixerError = class(EJclError); TJclMixerDevice = class; TJclMixerLine = class; TJclMixerDestination = class; TJclMixerLineControl = class(TObject) private FControlInfo: TMixerControl; FIsList: Boolean; FIsMultiple: Boolean; FIsUniform: Boolean; FListText: TStringList; FMixerLine: TJclMixerLine; function GetIsDisabled: Boolean; function GetID: DWORD; function GetListText: TStrings; function GetName: string; function GetUniformValue: Cardinal; function GetValue: TDynCardinalArray; function GetValueString: string; procedure SetUniformValue(const Value: Cardinal); procedure SetValue(const Value: TDynCardinalArray); protected procedure PrepareControlDetailsStruc(out ControlDetails: TMixerControlDetails; AUniform, AMultiple: Boolean); public constructor Create(AMixerLine: TJclMixerLine; const AControlInfo: TMixerControl); destructor Destroy; override; function FormatValue(AValue: Cardinal): string; property ControlInfo: TMixerControl read FControlInfo; property ID: DWORD read GetID; property IsDisabled: Boolean read GetIsDisabled; property IsList: Boolean read FIsList; property IsMultiple: Boolean read FIsMultiple; property IsUniform: Boolean read FIsUniform; property ListText: TStrings read GetListText; property MixerLine: TJclMixerLine read FMixerLine; property Name: string read GetName; property UniformValue: Cardinal read GetUniformValue write SetUniformValue; property Value: TDynCardinalArray read GetValue write SetValue; property ValueString: string read GetValueString; end; TJclMixerLine = class(TObject) private FLineControls: TObjectList; FLineInfo: TMixerLine; FMixerDevice: TJclMixerDevice; function GetComponentString: string; function GetLineControlByType(ControlType: DWORD): TJclMixerLineControl; function GetLineControlCount: Integer; function GetLineControls(Index: Integer): TJclMixerLineControl; function GetHasControlType(ControlType: DWORD): Boolean; function GetID: DWORD; function GetName: string; protected procedure BuildLineControls; public constructor Create(AMixerDevice: TJclMixerDevice); destructor Destroy; override; class function ComponentTypeToString(const ComponentType: DWORD): string; property ComponentString: string read GetComponentString; property HasControlType[ControlType: DWORD]: Boolean read GetHasControlType; property ID: DWORD read GetID; property LineControlByType[ControlType: DWORD]: TJclMixerLineControl read GetLineControlByType; property LineControls[Index: Integer]: TJclMixerLineControl read GetLineControls; default; property LineControlCount: Integer read GetLineControlCount; property LineInfo: TMixerLine read FLineInfo; property Name: string read GetName; property MixerDevice: TJclMixerDevice read FMixerDevice; end; TJclMixerSource = class(TJclMixerLine) private FMixerDestination: TJclMixerDestination; public constructor Create(AMixerDestination: TJclMixerDestination; ASourceIndex: Cardinal); property MixerDestination: TJclMixerDestination read FMixerDestination; end; TJclMixerDestination = class(TJclMixerLine) private FSources: TObjectList; function GetSourceCount: Integer; function GetSources(Index: Integer): TJclMixerSource; protected procedure BuildSources; public constructor Create(AMixerDevice: TJclMixerDevice; ADestinationIndex: Cardinal); destructor Destroy; override; property Sources[Index: Integer]: TJclMixerSource read GetSources; default; property SourceCount: Integer read GetSourceCount; end; TJclMixerDevice = class(TObject) private FCapabilities: TMixerCaps; FDestinations: TObjectList; FDeviceIndex: Cardinal; FHandle: HMIXER; FLines: TList; function GetProductName: string; function GetDestinationCount: Integer; function GetDestinations(Index: Integer): TJclMixerDestination; function GetLineCount: Integer; function GetLines(Index: Integer): TJclMixerLine; function GetLineByComponentType(ComponentType: DWORD): TJclMixerLine; function GetLineByID(LineID: DWORD): TJclMixerLine; function GetLineControlByID(ControlID: DWORD): TJclMixerLineControl; function GetLineUniformValue(ComponentType, ControlType: DWORD): Cardinal; procedure SetLineUniformValue(ComponentType, ControlType: DWORD; const Value: Cardinal); protected procedure BuildDestinations; procedure BuildLines; procedure Close; procedure Open(ACallBackWnd: THandle); public constructor Create(ADeviceIndex: Cardinal; ACallBackWnd: THandle); destructor Destroy; override; function FindLineControl(ComponentType, ControlType: DWORD): TJclMixerLineControl; property Capabilities: TMixerCaps read FCapabilities; property DeviceIndex: Cardinal read FDeviceIndex; property Destinations[Index: Integer]: TJclMixerDestination read GetDestinations; default; property DestinationCount: Integer read GetDestinationCount; property Handle: HMIXER read FHandle; property LineByID[LineID: DWORD]: TJclMixerLine read GetLineByID; property LineByComponentType[ComponentType: DWORD]: TJclMixerLine read GetLineByComponentType; property Lines[Index: Integer]: TJclMixerLine read GetLines; property LineCount: Integer read GetLineCount; property LineControlByID[ControlID: DWORD]: TJclMixerLineControl read GetLineControlByID; property LineUniformValue[ComponentType, ControlType: DWORD]: Cardinal read GetLineUniformValue write SetLineUniformValue; property ProductName: string read GetProductName; end; TJclMixer = class(TObject) private FCallbackWnd: THandle; FDeviceList: TObjectList; function GetDeviceCount: Integer; function GetDevices(Index: Integer): TJclMixerDevice; function GetFirstDevice: TJclMixerDevice; function GetLineMute(ComponentType: Integer): Boolean; function GetLineVolume(ComponentType: Integer): Cardinal; function GetLineByID(MixerHandle: HMIXER; LineID: DWORD): TJclMixerLine; function GetLineControlByID(MixerHandle: HMIXER; LineID: DWORD): TJclMixerLineControl; procedure SetLineMute(ComponentType: Integer; const Value: Boolean); procedure SetLineVolume(ComponentType: Integer; const Value: Cardinal); protected procedure BuildDevices; public constructor Create(ACallBackWnd: THandle = 0); destructor Destroy; override; property CallbackWnd: THandle read FCallbackWnd; property Devices[Index: Integer]: TJclMixerDevice read GetDevices; default; property DeviceCount: Integer read GetDeviceCount; property FirstDevice: TJclMixerDevice read GetFirstDevice; property LineByID[MixerHandle: HMIXER; LineID: DWORD]: TJclMixerLine read GetLineByID; property LineControlByID[MixerHandle: HMIXER; LineID: DWORD]: TJclMixerLineControl read GetLineControlByID; property LineMute[ComponentType: Integer]: Boolean read GetLineMute write SetLineMute; property LineVolume[ComponentType: Integer]: Cardinal read GetLineVolume write SetLineVolume; property SpeakersMute: Boolean index MIXERLINE_COMPONENTTYPE_DST_SPEAKERS read GetLineMute write SetLineMute; property SpeakersVolume: Cardinal index MIXERLINE_COMPONENTTYPE_DST_SPEAKERS read GetLineVolume write SetLineVolume; end; function MixerLeftRightToArray(Left, Right: Cardinal): TDynCardinalArray; const {$IFDEF BORLAND} INVALID_MIXER_HANDLE: HMIXER = -1; {$ENDIF BORLAND} {$IFDEF FPC} INVALID_MIXER_HANDLE: HMIXER = $FFFFFFFF; {$ENDIF FPC} type // MCI Error checking EJclMciError = class(EJclError) private FMciErrorNo: DWORD; FMciErrorMsg: string; public constructor Create(MciErrNo: MCIERROR; const Msg: string); constructor CreateFmt(MciErrNo: MCIERROR; const Msg: string; const Args: array of const); constructor CreateRes(MciErrNo: MCIERROR; Ident: Integer; Dummy: Integer); property MciErrorNo: DWORD read FMciErrorNo; property MciErrorMsg: string read FMciErrorMsg; end; function MMCheck(const MciError: MCIERROR; const Msg: string = ''): MCIERROR; function GetMciErrorMessage(const MciErrNo: MCIERROR): string; // CD Drive MCI Routines function OpenCdMciDevice(out OpenParams: TMCI_Open_Parms; Drive: Char = #0): MCIERROR; function CloseCdMciDevice(var OpenParams: TMCI_Open_Parms): MCIERROR; // CD Drive specific routines procedure OpenCloseCdDrive(OpenMode: Boolean; Drive: Char = #0); function IsMediaPresentInDrive(Drive: Char = #0): Boolean; type TJclCdMediaInfo = (miProduct, miIdentity, miUPC); TJclCdTrackType = (ttAudio, ttOther); TJclCdTrackInfo = record Minute: Byte; Second: Byte; TrackType: TJclCdTrackType; end; TJclCdTrackInfoArray = array of TJclCdTrackInfo; function GetCdInfo(InfoType: TJclCdMediaInfo; Drive: Char = #0): string; function GetCDAudioTrackList(out TrackList: TJclCdTrackInfoArray; Drive: Char = #0): TJclCdTrackInfo; overload; function GetCDAudioTrackList(TrackList: TStrings; IncludeTrackType: Boolean = False; Drive: Char = #0): string; overload; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL$'; Revision: '$Revision$'; Date: '$Date$'; LogPath: 'JCL\source\windows'; Extra: ''; Data: nil ); {$ENDIF UNITVERSIONING} implementation uses {$IFDEF HAS_UNITSCOPE} System.SysUtils, {$ELSE ~HAS_UNITSCOPE} SysUtils, {$ENDIF ~HAS_UNITSCOPE} JclResources, JclSysUtils; //=== { TJclMultimediaTimer } ================================================ constructor TJclMultimediaTimer.Create(Kind: TMmTimerKind; Notification: TMmNotificationKind); begin FKind := Kind; FNotification := Notification; FPeriod := 0; FTimerID := 0; FEvent := nil; ResetMemory(FTimeCaps, SizeOf(FTimeCaps)); if timeGetDevCaps(@FTimeCaps, SizeOf(FTimeCaps)) = TIMERR_STRUCT then raise EJclMmTimerError.CreateRes(@RsMmTimerGetCaps); FPeriod := FTimeCaps.wPeriodMin; if Notification <> nkCallback then FEvent := TJclEvent.Create(nil, Notification = nkSetEvent, False, ''); end; destructor TJclMultimediaTimer.Destroy; begin EndTimer; FreeAndNil(FEvent); FOnTimer := nil; inherited Destroy; end; procedure MmTimerCallback(TimerId, Msg: Cardinal; User, dw1, dw2: DWORD); stdcall; begin TJclMultimediaTimer(User).Timer(TimerId); end; class function TJclMultimediaTimer.BeginPeriod(const Period: Cardinal): Boolean; begin Result := timeBeginPeriod(Period) = TIMERR_NOERROR; end; procedure TJclMultimediaTimer.BeginTimer(const Delay, Resolution: Cardinal); var Event: Cardinal; TimerCallback: TFNTimeCallBack; begin if FTimerId <> 0 then raise EJclMmTimerError.CreateRes(@RsMmTimerActive); Event := 0; TimerCallback := nil; case FKind of tkPeriodic: Event := TIME_PERIODIC; tkOneShot: Event := TIME_ONESHOT; end; case FNotification of nkCallback: begin Event := Event or TIME_CALLBACK_FUNCTION; TimerCallback := @MmTimerCallback; end; nkSetEvent: begin Event := Event or TIME_CALLBACK_EVENT_SET; TimerCallback := TFNTimeCallback(FEvent.Handle); end; nkPulseEvent: begin Event := Event or TIME_CALLBACK_EVENT_PULSE; TimerCallback := TFNTimeCallback(FEvent.Handle); end; end; FStartTime := GetTime; if timeBeginPeriod(FPeriod) = TIMERR_NOERROR then FTimerId := timeSetEvent(Delay, Resolution, TimerCallBack, DWORD_PTR(Self), Event); if FTimerId = 0 then raise EJclMmTimerError.CreateRes(@RsMmSetEvent); end; function TJclMultimediaTimer.Elapsed(const Update: Boolean): Cardinal; var CurrentTime: Cardinal; begin if FTimerId = 0 then Result := 0 else begin CurrentTime := GetTime; if CurrentTime >= FStartTime then Result := CurrentTime - FStartTime else Result := (High(Cardinal) - FStartTime) + CurrentTime; if Update then FStartTime := CurrentTime; end; end; class function TJclMultimediaTimer.EndPeriod(const Period: Cardinal): Boolean; begin Result := timeEndPeriod(Period) = TIMERR_NOERROR; end; procedure TJclMultimediaTimer.EndTimer; begin if FTimerId <> 0 then begin if FKind = tkPeriodic then timeKillEvent(FTimerId); timeEndPeriod(FPeriod); FTimerId := 0; end; end; function TJclMultimediaTimer.GetMinMaxPeriod(Index: Integer): Cardinal; begin case Index of 0: Result := FTimeCaps.wPeriodMax; 1: Result := FTimeCaps.wPeriodMin; else Result := 0; end; end; class function TJclMultimediaTimer.GetTime: Cardinal; begin Result := timeGetTime; end; procedure TJclMultimediaTimer.SetPeriod(Value: Cardinal); begin if FTimerId <> 0 then raise EJclMmTimerError.CreateRes(@RsMmTimerActive); FPeriod := Value; end; { TODO -cHelp : Applications should not call any system-defined functions from inside a callback function, except for PostMessage, timeGetSystemTime, timeGetTime, timeSetEvent, timeKillEvent, midiOutShortMsg, midiOutLongMsg, and OutputDebugString. } procedure TJclMultimediaTimer.Timer(Id: Cardinal); begin { TODO : A exception in the callbacl i very likely very critically } if Id <> FTimerId then raise EJclMmTimerError.CreateRes(@RsMmInconsistentId); if Assigned(FOnTimer) then FOnTimer(Self); end; function TJclMultimediaTimer.WaitFor(const TimeOut: Cardinal): TJclWaitResult; begin if FNotification = nkCallback then Result := wrError else Result := FEvent.WaitFor(TimeOut); end; //=== { TJclMixerLineControl } =============================================== function MixerLeftRightToArray(Left, Right: Cardinal): TDynCardinalArray; begin SetLength(Result, 2); Result[0] := Left; Result[1] := Right; end; constructor TJclMixerLineControl.Create(AMixerLine: TJclMixerLine; const AControlInfo: TMixerControl); begin FControlInfo := AControlInfo; FMixerLine := AMixerLine; FIsList := (ControlInfo.dwControlType and MIXERCONTROL_CT_CLASS_MASK) = MIXERCONTROL_CT_CLASS_LIST; FIsMultiple := FControlInfo.fdwControl and MIXERCONTROL_CONTROLF_MULTIPLE <> 0; FIsUniform := FControlInfo.fdwControl and MIXERCONTROL_CONTROLF_UNIFORM <> 0; end; destructor TJclMixerLineControl.Destroy; begin FreeAndNil(FListText); inherited Destroy; end; function TJclMixerLineControl.FormatValue(AValue: Cardinal): string; begin case FControlInfo.dwControlType and MIXERCONTROL_CT_UNITS_MASK of MIXERCONTROL_CT_UNITS_BOOLEAN: Result := BooleanToStr(Boolean(AValue)); MIXERCONTROL_CT_UNITS_SIGNED: Result := Format('%d', [AValue]); MIXERCONTROL_CT_UNITS_UNSIGNED: Result := Format('%u', [AValue]); MIXERCONTROL_CT_UNITS_DECIBELS: Result := Format('%.1fdB', [AValue / 10]); MIXERCONTROL_CT_UNITS_PERCENT: Result := Format('%.1f%%', [AValue / 10]); else Result := ''; end; end; function TJclMixerLineControl.GetID: DWORD; begin Result := ControlInfo.dwControlID; end; function TJclMixerLineControl.GetIsDisabled: Boolean; begin Result := FControlInfo.fdwControl and MIXERCONTROL_CONTROLF_DISABLED <> 0; end; function TJclMixerLineControl.GetListText: TStrings; var ControlDetails: TMIXERCONTROLDETAILS; ListTexts, P: ^MIXERCONTROLDETAILS_LISTTEXT; I: Cardinal; begin if FListText = nil then begin FListText := TStringList.Create; if IsMultiple and IsList then begin PrepareControlDetailsStruc(ControlDetails, True, IsMultiple); ControlDetails.cbDetails := SizeOf(MIXERCONTROLDETAILS_LISTTEXT); GetMem(ListTexts, SizeOf(MIXERCONTROLDETAILS_LISTTEXT) * ControlDetails.cMultipleItems); try ControlDetails.paDetails := ListTexts; if mixerGetControlDetails(MixerLine.MixerDevice.Handle, @ControlDetails, MIXER_GETCONTROLDETAILSF_LISTTEXT) = MMSYSERR_NOERROR then begin P := ListTexts; for I := 1 to ControlDetails.cMultipleItems do begin FListText.AddObject(P^.szName, Pointer(P^.dwParam1)); Inc(P); end; end; finally FreeMem(ListTexts); end; end; end; Result := FListText; end; function TJclMixerLineControl.GetName: string; begin Result := FControlInfo.szName; end; function TJclMixerLineControl.GetUniformValue: Cardinal; var ControlDetails: TMixerControlDetails; begin PrepareControlDetailsStruc(ControlDetails, True, False); ControlDetails.cbDetails := SizeOf(Cardinal); ControlDetails.paDetails := @Result; MMCheck(mixerGetControlDetails(MixerLine.MixerDevice.Handle, @ControlDetails, MIXER_GETCONTROLDETAILSF_VALUE)); end; function TJclMixerLineControl.GetValue: TDynCardinalArray; var ControlDetails: TMixerControlDetails; ItemCount: Cardinal; begin PrepareControlDetailsStruc(ControlDetails, IsUniform, IsMultiple); if IsUniform then ItemCount := 1 else ItemCount := ControlDetails.cChannels; if IsMultiple then ItemCount := ItemCount * ControlDetails.cMultipleItems; SetLength(Result, ItemCount); ControlDetails.cbDetails := SizeOf(Cardinal); ControlDetails.paDetails := @Result[0]; MMCheck(mixerGetControlDetails(MixerLine.MixerDevice.Handle, @ControlDetails, MIXER_GETCONTROLDETAILSF_VALUE)); end; function TJclMixerLineControl.GetValueString: string; var TempValue: TDynCardinalArray; I: Integer; begin TempValue := Value; Result := ''; for I := Low(TempValue) to High(TempValue) do Result := Result + ',' + FormatValue(TempValue[I]); Delete(Result, 1, 1); end; procedure TJclMixerLineControl.PrepareControlDetailsStruc(out ControlDetails: TMixerControlDetails; AUniform, AMultiple: Boolean); begin ResetMemory(ControlDetails, SizeOf(ControlDetails)); ControlDetails.cbStruct := SizeOf(ControlDetails); ControlDetails.dwControlID := FControlInfo.dwControlID; if AUniform then ControlDetails.cChannels := MIXERCONTROL_CONTROLF_UNIFORM else ControlDetails.cChannels := MixerLine.LineInfo.cChannels; if AMultiple then ControlDetails.cMultipleItems := FControlInfo.cMultipleItems; end; procedure TJclMixerLineControl.SetUniformValue(const Value: Cardinal); var ControlDetails: TMixerControlDetails; begin PrepareControlDetailsStruc(ControlDetails, True, False); ControlDetails.cbDetails := SizeOf(Cardinal); ControlDetails.paDetails := @Value; MMCheck(mixerSetControlDetails(MixerLine.MixerDevice.Handle, @ControlDetails, MIXER_GETCONTROLDETAILSF_VALUE)); end; procedure TJclMixerLineControl.SetValue(const Value: TDynCardinalArray); var ControlDetails: TMixerControlDetails; {$IFDEF ASSERTIONS_ON} ItemCount: Cardinal; {$ENDIF ASSERTIONS_ON} begin PrepareControlDetailsStruc(ControlDetails, IsUniform, IsMultiple); {$IFDEF ASSERTIONS_ON} if IsUniform then ItemCount := 1 else ItemCount := ControlDetails.cChannels; if IsMultiple then ItemCount := ItemCount * ControlDetails.cMultipleItems; Assert(ItemCount = Cardinal(Length(Value))); {$ENDIF ASSERTIONS_ON} ControlDetails.cbDetails := SizeOf(Cardinal); ControlDetails.paDetails := @Value[0]; MMCheck(mixerSetControlDetails(MixerLine.MixerDevice.Handle, @ControlDetails, MIXER_GETCONTROLDETAILSF_VALUE)); end; //=== { TJclMixerLine } ====================================================== function MixerLineCompareID(Item1, Item2: Pointer): Integer; begin Result := Integer(TJclMixerLine(Item1).ID) - Integer(TJclMixerLine(Item2).ID); end; function MixerLineSearchID(Param: Pointer; ItemIndex: Integer; const Value): Integer; begin Result := Integer(TJclMixerDevice(Param).Lines[ItemIndex].ID) - Integer(Value); end; constructor TJclMixerLine.Create(AMixerDevice: TJclMixerDevice); begin FMixerDevice := AMixerDevice; FLineControls := TObjectList.Create; end; destructor TJclMixerLine.Destroy; begin FreeAndNil(FLineControls); inherited Destroy; end; procedure TJclMixerLine.BuildLineControls; var MixerControls: TMixerLineControls; Controls, P: PMixerControl; I: Cardinal; Item: TJclMixerLineControl; begin GetMem(Controls, SizeOf(TMixerControl) * FLineInfo.cControls); try MixerControls.cbStruct := SizeOf(MixerControls); MixerControls.dwLineID := FLineInfo.dwLineID; MixerControls.cControls := FLineInfo.cControls; MixerControls.cbmxctrl := SizeOf(TMixerControl); MixerControls.pamxctrl := Controls; if mixerGetLineControls(FMixerDevice.Handle, @MixerControls, MIXER_GETLINECONTROLSF_ALL) = MMSYSERR_NOERROR then begin P := Controls; for I := 1 to FLineInfo.cControls do begin Item := TJclMixerLineControl.Create(Self, P^); FLineControls.Add(Item); Inc(P); end; end; finally FreeMem(Controls); end; end; class function TJclMixerLine.ComponentTypeToString(const ComponentType: DWORD): string; begin case ComponentType of MIXERLINE_COMPONENTTYPE_DST_UNDEFINED: Result := LoadResString(@RsMmMixerUndefined); MIXERLINE_COMPONENTTYPE_DST_DIGITAL, MIXERLINE_COMPONENTTYPE_SRC_DIGITAL: Result := LoadResString(@RsMmMixerDigital); MIXERLINE_COMPONENTTYPE_DST_LINE, MIXERLINE_COMPONENTTYPE_SRC_LINE: Result := LoadResString(@RsMmMixerLine); MIXERLINE_COMPONENTTYPE_DST_MONITOR: Result := LoadResString(@RsMmMixerMonitor); MIXERLINE_COMPONENTTYPE_DST_SPEAKERS: Result := LoadResString(@RsMmMixerSpeakers); MIXERLINE_COMPONENTTYPE_DST_HEADPHONES: Result := LoadResString(@RsMmMixerHeadphones); MIXERLINE_COMPONENTTYPE_DST_TELEPHONE, MIXERLINE_COMPONENTTYPE_SRC_TELEPHONE: Result := LoadResString(@RsMmMixerTelephone); MIXERLINE_COMPONENTTYPE_DST_WAVEIN: Result := LoadResString(@RsMmMixerWaveIn); MIXERLINE_COMPONENTTYPE_DST_VOICEIN: Result := LoadResString(@RsMmMixerVoiceIn); MIXERLINE_COMPONENTTYPE_SRC_MICROPHONE: Result := LoadResString(@RsMmMixerMicrophone); MIXERLINE_COMPONENTTYPE_SRC_SYNTHESIZER: Result := LoadResString(@RsMmMixerSynthesizer); MIXERLINE_COMPONENTTYPE_SRC_COMPACTDISC: Result := LoadResString(@RsMmMixerCompactDisc); MIXERLINE_COMPONENTTYPE_SRC_PCSPEAKER: Result := LoadResString(@RsMmMixerPcSpeaker); MIXERLINE_COMPONENTTYPE_SRC_WAVEOUT: Result := LoadResString(@RsMmMixerWaveOut); MIXERLINE_COMPONENTTYPE_SRC_AUXILIARY: Result := LoadResString(@RsMmMixerAuxiliary); MIXERLINE_COMPONENTTYPE_SRC_ANALOG: Result := LoadResString(@RsMmMixerAnalog); else Result := ''; end; end; function TJclMixerLine.GetComponentString: string; begin Result := ComponentTypeToString(FLineInfo.dwComponentType); end; function TJclMixerLine.GetHasControlType(ControlType: DWORD): Boolean; begin Result := LineControlByType[ControlType] <> nil; end; function TJclMixerLine.GetID: DWORD; begin Result := LineInfo.dwLineID; end; function TJclMixerLine.GetLineControlByType(ControlType: DWORD): TJclMixerLineControl; var I: Integer; begin Result := nil; for I := 0 to LineControlCount - 1 do if LineControls[I].ControlInfo.dwControlType = ControlType then begin Result := LineControls[I]; Break; end; end; function TJclMixerLine.GetLineControlCount: Integer; begin Result := FLineControls.Count; if Result = 0 then begin BuildLineControls; Result := FLineControls.Count; end; end; function TJclMixerLine.GetLineControls(Index: Integer): TJclMixerLineControl; begin Result := TJclMixerLineControl(FLineControls[Index]); end; function TJclMixerLine.GetName: string; begin Result := FLineInfo.szName; end; //=== { TJclMixerSource } ==================================================== constructor TJclMixerSource.Create(AMixerDestination: TJclMixerDestination; ASourceIndex: Cardinal); begin inherited Create(AMixerDestination.MixerDevice); FMixerDestination := AMixerDestination; FLineInfo.cbStruct := SizeOf(FLineInfo); FLineInfo.dwDestination := FMixerDestination.LineInfo.dwDestination; FLineInfo.dwSource := ASourceIndex; MMCheck(mixerGetLineInfo(FMixerDestination.MixerDevice.Handle, @FLineInfo, MIXER_GETLINEINFOF_SOURCE)); end; //=== { TJclMixerDestination } =============================================== constructor TJclMixerDestination.Create(AMixerDevice: TJclMixerDevice; ADestinationIndex: Cardinal); begin inherited Create(AMixerDevice); FLineInfo.cbStruct := SizeOf(FLineInfo); FLineInfo.dwDestination := ADestinationIndex; MMCheck(mixerGetLineInfo(AMixerDevice.Handle, @FLineInfo, MIXER_GETLINEINFOF_DESTINATION)); FSources := TObjectList.Create; end; destructor TJclMixerDestination.Destroy; begin FreeAndNil(FSources); inherited Destroy; end; procedure TJclMixerDestination.BuildSources; var I: Cardinal; Item: TJclMixerSource; begin for I := 1 to LineInfo.cConnections do begin Item := TJclMixerSource.Create(Self, I - 1); FSources.Add(Item); end; end; function TJclMixerDestination.GetSourceCount: Integer; begin Result := FSources.Count; if Result = 0 then begin BuildSources; Result := FSources.Count; end; end; function TJclMixerDestination.GetSources(Index: Integer): TJclMixerSource; begin Result := TJclMixerSource(FSources[Index]); end; //=== { TJclMixerDevice } ==================================================== constructor TJclMixerDevice.Create(ADeviceIndex: Cardinal; ACallBackWnd: THandle); begin FDeviceIndex := ADeviceIndex; FHandle := INVALID_MIXER_HANDLE; FDestinations := TObjectList.Create; FLines := TList.Create; MMCheck(mixerGetDevCaps(ADeviceIndex, @FCapabilities, SizeOf(FCapabilities))); Open(ACallBackWnd); BuildDestinations; end; destructor TJclMixerDevice.Destroy; begin Close; FreeAndNil(FDestinations); FreeAndNil(FLines); inherited Destroy; end; procedure TJclMixerDevice.BuildDestinations; var I: Cardinal; Item: TJclMixerDestination; begin for I := 1 to FCapabilities.cDestinations do begin Item := TJclMixerDestination.Create(Self, I - 1); FDestinations.Add(Item); end; end; procedure TJclMixerDevice.BuildLines; var D, I: Integer; Dest: TJclMixerDestination; begin for D := 0 to DestinationCount - 1 do begin Dest := Destinations[D]; FLines.Add(Dest); for I := 0 to Dest.SourceCount - 1 do FLines.Add(Dest.Sources[I]); end; FLines.Sort(MixerLineCompareID); end; procedure TJclMixerDevice.Close; begin if FHandle <> INVALID_MIXER_HANDLE then begin mixerClose(FHandle); FHandle := INVALID_MIXER_HANDLE; end; end; function TJclMixerDevice.FindLineControl(ComponentType, ControlType: DWORD): TJclMixerLineControl; var TempLine: TJclMixerLine; begin Result := nil; TempLine := LineByComponentType[ComponentType]; if TempLine <> nil then Result := TempLine.LineControlByType[ControlType]; end; function TJclMixerDevice.GetDestinationCount: Integer; begin Result := FDestinations.Count; end; function TJclMixerDevice.GetDestinations(Index: Integer): TJclMixerDestination; begin Result := TJclMixerDestination(FDestinations[Index]); end; function TJclMixerDevice.GetLineByComponentType(ComponentType: DWORD): TJclMixerLine; var I: Integer; begin Result := nil; for I := 0 to LineCount - 1 do if Lines[I].LineInfo.dwComponentType = ComponentType then begin Result := Lines[I]; Break; end; end; function TJclMixerDevice.GetLineByID(LineID: DWORD): TJclMixerLine; var I: Integer; begin I := SearchSortedUntyped(Self, LineCount, MixerLineSearchID, LineID); if I = -1 then Result := nil else Result := Lines[I]; end; function TJclMixerDevice.GetLineControlByID(ControlID: DWORD): TJclMixerLineControl; var L, C: Integer; TempLine: TJclMixerLine; begin Result := nil; for L := 0 to LineCount - 1 do begin TempLine := Lines[L]; for C := 0 to TempLine.LineControlCount - 1 do if TempLine.LineControls[C].ID = ControlID then begin Result := TempLine.LineControls[C]; Break; end; end; end; function TJclMixerDevice.GetLineCount: Integer; begin Result := FLines.Count; if Result = 0 then begin BuildLines; Result := FLines.Count; end; end; function TJclMixerDevice.GetLines(Index: Integer): TJclMixerLine; begin Result := TJclMixerLine(FLines[Index]); end; function TJclMixerDevice.GetLineUniformValue(ComponentType, ControlType: DWORD): Cardinal; var LineControl: TJclMixerLineControl; begin LineControl := FindLineControl(ComponentType, ControlType); if LineControl <> nil then Result := LineControl.UniformValue else Result := 0; end; function TJclMixerDevice.GetProductName: string; begin Result := FCapabilities.szPname; end; procedure TJclMixerDevice.Open(ACallBackWnd: THandle); var Flags: DWORD; begin if FHandle = INVALID_MIXER_HANDLE then begin Flags := MIXER_OBJECTF_HMIXER; if ACallBackWnd <> 0 then Inc(Flags, CALLBACK_WINDOW); MMCheck(mixerOpen(@FHandle, DeviceIndex, ACallBackWnd, 0, Flags)); end; end; procedure TJclMixerDevice.SetLineUniformValue(ComponentType, ControlType: DWORD; const Value: Cardinal); var LineControl: TJclMixerLineControl; begin LineControl := FindLineControl(ComponentType, ControlType); if LineControl <> nil then LineControl.UniformValue := Value else raise EJclMixerError.CreateResFmt(@RsMmMixerCtlNotFound, [TJclMixerLine.ComponentTypeToString(ComponentType), ControlType]); end; //=== { TJclMixer } ========================================================== constructor TJclMixer.Create(ACallBackWnd: THandle); begin FDeviceList := TObjectList.Create; FCallbackWnd := ACallBackWnd; BuildDevices; end; destructor TJclMixer.Destroy; begin FreeAndNil(FDeviceList); inherited Destroy; end; procedure TJclMixer.BuildDevices; var I: Cardinal; Item: TJclMixerDevice; begin for I := 1 to mixerGetNumDevs do begin Item := TJclMixerDevice.Create(I - 1, FCallbackWnd); FDeviceList.Add(Item); end; end; function TJclMixer.GetDeviceCount: Integer; begin Result := FDeviceList.Count; end; function TJclMixer.GetDevices(Index: Integer): TJclMixerDevice; begin Result := TJclMixerDevice(FDeviceList.Items[Index]); end; function TJclMixer.GetFirstDevice: TJclMixerDevice; begin if DeviceCount = 0 then raise EJclMixerError.CreateRes(@RsMmMixerNoDevices); Result := Devices[0]; end; function TJclMixer.GetLineByID(MixerHandle: HMIXER; LineID: DWORD): TJclMixerLine; var I: Integer; TempDevice: TJclMixerDevice; begin Result := nil; for I := 0 to DeviceCount - 1 do begin TempDevice := Devices[I]; if TempDevice.Handle = MixerHandle then begin Result := TempDevice.LineByID[LineID]; if Result <> nil then Break; end; end; end; function TJclMixer.GetLineControlByID(MixerHandle: HMIXER; LineID: DWORD): TJclMixerLineControl; var I: Integer; TempDevice: TJclMixerDevice; begin Result := nil; for I := 0 to DeviceCount - 1 do begin TempDevice := Devices[I]; if TempDevice.Handle = MixerHandle then begin Result := TempDevice.LineControlByID[LineID]; if Result <> nil then Break; end; end; end; function TJclMixer.GetLineMute(ComponentType: Integer): Boolean; begin Result := Boolean(FirstDevice.LineUniformValue[Cardinal(ComponentType), MIXERCONTROL_CONTROLTYPE_MUTE]); end; function TJclMixer.GetLineVolume(ComponentType: Integer): Cardinal; begin Result := FirstDevice.LineUniformValue[Cardinal(ComponentType), MIXERCONTROL_CONTROLTYPE_VOLUME]; end; procedure TJclMixer.SetLineMute(ComponentType: Integer; const Value: Boolean); begin FirstDevice.LineUniformValue[Cardinal(ComponentType), MIXERCONTROL_CONTROLTYPE_MUTE] := Cardinal(Value); end; procedure TJclMixer.SetLineVolume(ComponentType: Integer; const Value: Cardinal); begin FirstDevice.LineUniformValue[Cardinal(ComponentType), MIXERCONTROL_CONTROLTYPE_VOLUME] := Value; end; //=== { EJclMciError } ======================================================= constructor EJclMciError.Create(MciErrNo: MCIERROR; const Msg: string); begin FMciErrorNo := MciErrNo; FMciErrorMsg := GetMciErrorMessage(MciErrNo); inherited Create(Msg + NativeLineBreak + LoadResString(@RsMmMciErrorPrefix) + FMciErrorMsg); end; constructor EJclMciError.CreateFmt(MciErrNo: MCIERROR; const Msg: string; const Args: array of const); begin FMciErrorNo := MciErrNo; FMciErrorMsg := GetMciErrorMessage(MciErrNo); inherited CreateFmt(Msg + NativeLineBreak + LoadResString(@RsMmMciErrorPrefix) + FMciErrorMsg, Args); end; constructor EJclMciError.CreateRes(MciErrNo: MCIERROR; Ident: Integer; Dummy: Integer); begin FMciErrorNo := MciErrNo; FMciErrorMsg := GetMciErrorMessage(MciErrNo); inherited Create(LoadStr(Ident)+ NativeLineBreak + LoadResString(@RsMmMciErrorPrefix) + FMciErrorMsg); end; function GetMciErrorMessage(const MciErrNo: MCIERROR): string; var Buffer: array [0..{$IFDEF HAS_UNITSCOPE}Winapi.{$ENDIF}MMSystem.MAXERRORLENGTH - 1] of Char; begin if mciGetErrorString(MciErrNo, Buffer, Length(Buffer)) then Result := Buffer else Result := Format(LoadResString(@RsMmUnknownError), [MciErrNo]); end; function MMCheck(const MciError: MCIERROR; const Msg: string): MCIERROR; begin if MciError <> MMSYSERR_NOERROR then raise EJclMciError.Create(MciError, Msg); Result := MciError; end; //=== CD Drive MCI Routines ================================================== function OpenCdMciDevice(out OpenParams: TMCI_Open_Parms; Drive: Char): MCIERROR; var OpenParam: DWORD; DriveName: array [0..2] of Char; begin ResetMemory(OpenParams, SizeOf(OpenParams)); OpenParam := MCI_OPEN_TYPE or MCI_OPEN_TYPE_ID or MCI_OPEN_SHAREABLE; OpenParams.lpstrDeviceType := PChar(MCI_DEVTYPE_CD_AUDIO); if Drive <> #0 then begin OpenParams.lpstrElementName := StrFmt(DriveName, '%s:', [UpCase(Drive)]); Inc(OpenParam, MCI_OPEN_ELEMENT); end; Result := mciSendCommand(0, MCI_OPEN, OpenParam, TJclAddr(@OpenParams)); end; function CloseCdMciDevice(var OpenParams: TMCI_Open_Parms): MCIERROR; begin Result := mciSendCommand(OpenParams.wDeviceID, MCI_CLOSE, MCI_WAIT, 0); if Result = MMSYSERR_NOERROR then ResetMemory(OpenParams, SizeOf(OpenParams)); end; //=== CD Drive specific routines ============================================= procedure OpenCloseCdDrive(OpenMode: Boolean; Drive: Char); const OpenCmd: array [Boolean] of DWORD = (MCI_SET_DOOR_CLOSED, MCI_SET_DOOR_OPEN); var Mci: TMCI_Open_Parms; begin MMCheck(OpenCdMciDevice(Mci, Drive), LoadResString(@RsMmNoCdAudio)); try MMCheck(mciSendCommand(Mci.wDeviceID, MCI_SET, OpenCmd[OpenMode], 0)); finally CloseCdMciDevice(Mci); end; end; function IsMediaPresentInDrive(Drive: Char): Boolean; var Mci: TMCI_Open_Parms; StatusParams: TMCI_Status_Parms; begin MMCheck(OpenCdMciDevice(Mci, Drive), LoadResString(@RsMmNoCdAudio)); try ResetMemory(StatusParams, SizeOf(StatusParams)); StatusParams.dwItem := MCI_STATUS_MEDIA_PRESENT; MMCheck(mciSendCommand(Mci.wDeviceID, MCI_STATUS, MCI_STATUS_ITEM or MCI_WAIT, TJclAddr(@StatusParams))); Result := Boolean(StatusParams.dwReturn); finally CloseCdMciDevice(Mci); end; end; function GetCdInfo(InfoType: TJclCdMediaInfo; Drive: Char): string; const InfoConsts: array [TJclCdMediaInfo] of DWORD = (MCI_INFO_PRODUCT, MCI_INFO_MEDIA_IDENTITY, MCI_INFO_MEDIA_UPC); var Mci: TMCI_Open_Parms; InfoParams: TMCI_Info_Parms; Buffer: array [0..255] of Char; begin Result := ''; MMCheck(OpenCdMciDevice(Mci, Drive), LoadResString(@RsMmNoCdAudio)); try ResetMemory(Buffer, SizeOf(Buffer)); InfoParams.dwCallback := 0; InfoParams.lpstrReturn := Buffer; InfoParams.dwRetSize := Length(Buffer) - 1; if mciSendCommand(Mci.wDeviceID, MCI_INFO, InfoConsts[InfoType], TJclAddr(@InfoParams)) = MMSYSERR_NOERROR then Result := Buffer; finally CloseCdMciDevice(Mci); end; end; function GetCDAudioTrackList(out TrackList: TJclCdTrackInfoArray; Drive: Char): TJclCdTrackInfo; var Mci: TMCI_Open_Parms; SetParams: TMCI_Set_Parms; TrackCnt, Ret: Cardinal; I: Integer; function GetTrackInfo(Command, Item, Track: DWORD): DWORD; var StatusParams: TMCI_Status_Parms; begin ResetMemory(StatusParams, SizeOf(StatusParams)); StatusParams.dwItem := Item; StatusParams.dwTrack := Track; if mciSendCommand(Mci.wDeviceID, MCI_STATUS, Command, TJclAddr(@StatusParams)) = MMSYSERR_NOERROR then Result := StatusParams.dwReturn else Result := 0; end; begin MMCheck(OpenCdMciDevice(Mci, Drive), LoadResString(@RsMmNoCdAudio)); try ResetMemory(SetParams, SizeOf(SetParams)); SetParams.dwTimeFormat := MCI_FORMAT_MSF; MMCheck(mciSendCommand(Mci.wDeviceID, MCI_SET, MCI_SET_TIME_FORMAT, TJclAddr(@SetParams))); Result.TrackType := ttOther; TrackCnt := GetTrackInfo(MCI_STATUS_ITEM, MCI_STATUS_NUMBER_OF_TRACKS, 0); SetLength(TrackList, TrackCnt); for I := 0 to TrackCnt - 1 do begin Ret := GetTrackInfo(MCI_STATUS_ITEM or MCI_TRACK, MCI_STATUS_LENGTH, I + 1); TrackList[I].Minute := mci_MSF_Minute(Ret); TrackList[I].Second := mci_MSF_Second(Ret); Ret := GetTrackInfo(MCI_STATUS_ITEM or MCI_TRACK, MCI_CDA_STATUS_TYPE_TRACK, I + 1); if Ret = MCI_CDA_TRACK_AUDIO then begin Result.TrackType := ttAudio; TrackList[I].TrackType := ttAudio; end else TrackList[I].TrackType := ttOther; end; Ret := GetTrackInfo(MCI_STATUS_ITEM, MCI_STATUS_LENGTH, 0); Result.Minute := mci_MSF_Minute(Ret); Result.Second := mci_MSF_Second(Ret); finally CloseCdMciDevice(Mci); end; end; function GetCDAudioTrackList(TrackList: TStrings; IncludeTrackType: Boolean; Drive: Char): string; var Tracks: TJclCdTrackInfoArray; TotalTime: TJclCdTrackInfo; I: Integer; S: string; begin TotalTime := GetCDAudioTrackList(Tracks, Drive); TrackList.BeginUpdate; try for I := Low(Tracks) to High(Tracks) do with Tracks[I] do begin if IncludeTrackType then begin case TrackType of ttAudio: S := LoadResString(@RsMMTrackAudio); ttOther: S := LoadResString(@RsMMTrackOther); end; S := Format('[%s]', [S]); end else S := ''; S := Format(LoadResString(@RsMmCdTrackNo), [I + 1]) + ' ' + S; S := S + ' ' + Format(LoadResString(@RsMMCdTimeFormat), [I + 1, Minute, Second]); TrackList.Add(S); end; finally TrackList.EndUpdate; end; Result := Format(LoadResString(@RsMMCdTimeFormat), [TotalTime.Minute, TotalTime.Second]); end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
32.912242
139
0.698335
c330e45efd316b37e761cc993a341b75a3fb873a
711
dpr
Pascal
ThemidaSDK/ExamplesSDK/Custom Message DLL/Delphi/CustomMsgs.dpr
qzhsjz/LXDInjector
44c34e9677b4e3543e58584fad3844eb7bb33ff8
[ "MIT" ]
1
2021-05-22T11:10:43.000Z
2021-05-22T11:10:43.000Z
ThemidaSDK/ExamplesSDK/Custom Message DLL/Delphi/CustomMsgs.dpr
luoxiandu/LXDInjector
44c34e9677b4e3543e58584fad3844eb7bb33ff8
[ "MIT" ]
null
null
null
ThemidaSDK/ExamplesSDK/Custom Message DLL/Delphi/CustomMsgs.dpr
luoxiandu/LXDInjector
44c34e9677b4e3543e58584fad3844eb7bb33ff8
[ "MIT" ]
null
null
null
library CustomMsgs; { Important note about DLL memory management: ShareMem must be the first unit in your library's USES clause AND your project's (select Project-View Source) USES clause if your DLL exports any procedures or functions that pass strings as parameters or function results. This applies to all strings passed to and from your DLL--even those that are nested in records and classes. ShareMem is the interface unit to the BORLNDMM.DLL shared memory manager, which must be deployed along with your DLL. To avoid using BORLNDMM.DLL, pass string information using PChar or ShortString parameters. } uses SysUtils, Classes, Unit1 in 'Unit1.pas' {Form1}; {$R *.res} begin end.
32.318182
72
0.767932
4762074152cf800fb2213f13cec67aee0afe61aa
2,028
pas
Pascal
units/uround.pas
BishopWolf/DelphiMath
bc03e918f2cbe6aad91e8153f5c7ae35abef75e2
[ "Apache-2.0" ]
1
2019-11-20T02:18:47.000Z
2019-11-20T02:18:47.000Z
units/uround.pas
BishopWolf/DelphiMath
bc03e918f2cbe6aad91e8153f5c7ae35abef75e2
[ "Apache-2.0" ]
null
null
null
units/uround.pas
BishopWolf/DelphiMath
bc03e918f2cbe6aad91e8153f5c7ae35abef75e2
[ "Apache-2.0" ]
2
2017-05-14T03:56:55.000Z
2019-11-20T02:18:48.000Z
{ ****************************************************************** Rounding functions Based on FreeBASIC version contributed by R. Keeling ****************************************************************** } unit uround; interface uses uConstants, math, umath, utypes; function Round(X: Float): Integer; {$IFDEF INLININGSUPPORTED} inline; {$ENDIF}overload; { Rounds X } function RoundN(X: Float; N: Integer): Float; { Rounds X to N decimal places } function Round(V: TVector; Ub: Integer): TIntVector; overload; { convert a float vector into an integer vector rounding } function Round(V: TMatrix; Ub1, Ub2: Integer): TIntMatrix; overload; { convert a float matrix into an integer matrix rounding } function Round(V: T3DMatrix; Ub1, Ub2, Ub3: Integer): T3DIntMatrix; overload; { convert a float 3D matrix into an integer 3D matrix rounding } implementation function Round(X: Float): Integer; begin result := system.Round(X); end; function RoundN(X: Float; N: Integer): Float; const MaxRoundPlaces = 18; var ReturnAnswer, Dec_Place: Float; I: Integer; begin if (N >= 0) and (N < MaxRoundPlaces) then I := N else I := 0; Dec_Place := Exp10(I); ReturnAnswer := Int((Abs(X) * Dec_Place) + 0.5); RoundN := Sign(X) * ReturnAnswer / Dec_Place; end; function Round(V: TVector; Ub: Integer): TIntVector; var I: Integer; begin DimVector(result, Ub); for I := 1 to Ub do result[I] := system.Round(V[I]); end; function Round(V: TMatrix; Ub1, Ub2: Integer): TIntMatrix; var I, j: Integer; begin DimMatrix(result, Ub1, Ub2); for I := 1 to Ub1 do for j := 1 to Ub2 do result[I, j] := system.Round(V[I, j]); end; function Round(V: T3DMatrix; Ub1, Ub2, Ub3: Integer): T3DIntMatrix; var I, j, k: Integer; begin DimMatrix(result, Ub1, Ub2, Ub3); for I := 1 to Ub1 do for j := 1 to Ub2 do for k := 1 to Ub3 do result[I, j, k] := system.Round(V[I, j, k]); end; end.
24.433735
78
0.598126
c3fa823f08fb5b81e2b128da94e788ff45961e23
25,258
pas
Pascal
Server/FHIR.Server.OpenMHealth.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
Server/FHIR.Server.OpenMHealth.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
Server/FHIR.Server.OpenMHealth.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
unit FHIR.Server.OpenMHealth; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, IdContext, IdCustomHTTPServer, FHIR.Support.Base, FHIR.Support.Json, FHIR.Support.Utilities, FHIR.Base.Objects, FHIR.Base.Lang, FHIR.Server.Session, FHIR.Version.Types, FHIR.Version.Resources, FHIR.Version.Utilities; type TOpenMHealthAdaptor = class (TFHIRFormatAdaptor) private function loadDataPoint(stream : TStream) : TFHIRObservation; function readDataPoint(json : TJsonObject) : TFHIRObservation; function readHeader(hdr: TJsonObject; obs: TFhirObservation) : String; procedure readPhysicalActivity(body: TJsonObject; obs: TFhirObservation); procedure readBloodGlucose(body: TJsonObject; obs: TFhirObservation); function readTimeInterval(obj : TJsonObject) : TFHIRPeriod; function readQuantity(obj : TJsonObject) : TFHIRQuantity; function convertUCUMUnit(s : String) : String; function convertObsStat(s : String) : String; procedure writeObservation(obs : TFHIRObservation; json : TJsonObject); procedure writeBundle(obs : TFHIRBundle; json : TJsonObject); function writeHeader(obs : TFHIRObservation; hdr : TJsonObject) : String; procedure writePhysicalActivity(obs : TFHIRObservation; body : TJsonObject); procedure writeBloodGlucose(obs : TFHIRObservation; body : TJsonObject); function writePeriod(period : TFHIRPeriod) : TJsonObject; function writeQuantity(qty : TFHIRQuantity) : TJsonObject; function unconvertUCUMUnit(s : String) : String; function unconvertObsStat(s : String) : String; public procedure load(req : TFHIRRequest; stream : TStream); override; function NewIdStatus : TCreateIdState; override; function ResourceName : String; override; procedure compose(response : TFHIRResponse; stream : TStream); override; function MimeType : String; override; procedure editSearch(req : TFHIRRequest); override; end; implementation { TOpenMHealthAdaptor } procedure TOpenMHealthAdaptor.compose(response: TFHIRResponse; stream: TStream); var json : TJsonObject; begin json := TJsonObject.Create; try if response.Resource = nil then raise EFHIRException.create('Cannot represent a resource of (nil) as an OpenMHealth data point') else if response.Resource is TFHIRObservation then writeObservation(response.Resource as TFHIRObservation, json) else if response.Resource is TFHIRBundle then writeBundle(response.Resource as TFHIRBundle, json) else raise EFHIRException.create('Cannot represent a resource of type '+response.Resource.fhirType+' as an OpenMHealth data point'); TJSONWriter.writeObject(stream, json, true); finally json.Free; end; end; function TOpenMHealthAdaptor.convertObsStat(s: String): String; begin if (s = 'average') then result := 'average' else if (s = 'maximum') then result := 'maximum' else if (s = 'minimum') then result := 'minimum' else if (s = 'count') then result := 'count' else if (s = 'median') then result := 'median' else if (s = 'standard deviation') then result := 'std-dev' else if (s = 'sum') then result := 'sum' else if (s = 'variance') then result := 'variance' else if (s = '20th percentile') then result := '%20' else if (s = '80th percentile') then result := '%80' else if (s = 'lower quartile') then result := '4-lower' else if (s = 'upper quartile') then result := '4-upper' else if (s = 'quartile deviation') then result := '4-dev' else if (s = '1st quintile') then result := '5-1' else if (s = '2nd quintile') then result := '5-2' else if (s = '3rd quintile') then result := '5-3' else if (s = '4th quintile') then result := '5-4' else result := s; end; function TOpenMHealthAdaptor.convertUCUMUnit(s: String): String; begin if (s = 'in') then result := '[in_i]' else if (s = 'ft') then result := '[ft_i]' else if (s = 'yd') then result := '[yd_i]' else if (s = 'mi') then result := '[mi_i]' else if (s = 'sec') then result := 's' else if (s = 'Mo') then result := 'mo' else if (s = 'yr') then result := 'a' else result := s; end; procedure TOpenMHealthAdaptor.editSearch(req: TFHIRRequest); var p : String; begin if req.Parameters.GetVar('schema_namespace') <> 'omh' then raise EFHIRException.create('Unknown schema namespace'); if req.Parameters.GetVar('schema_version') <> '1.0' then raise EFHIRException.create('Unknown schema version for OMH 1.0'); p := '_profile=http://www.openmhealth.org/schemas/fhir/'+req.Parameters.GetVar('schema_namespace')+'/'+req.Parameters.GetVar('schema_version')+'/'+req.Parameters.GetVar('schema_name'); if req.Parameters.VarExists('created_on_or_after') then p := p + '&date=ge'+req.Parameters.getvar('created_on_or_after'); if req.Parameters.VarExists('created_before') then p := p + '&date=le'+req.Parameters.getvar('created_before'); req.LoadParams(p); end; procedure TOpenMHealthAdaptor.load(req: TFHIRRequest; stream : TStream); begin req.PostFormat := ffJson; req.Resource := loadDataPoint(stream); req.ResourceName := 'Observation'; req.Id := req.Resource.id; end; function TOpenMHealthAdaptor.loadDataPoint(stream: TStream): TFHIRObservation; var json : TJsonObject; begin json := TJSONParser.Parse(stream); try result := readDataPoint(json); finally json.Free; end; end; function TOpenMHealthAdaptor.MimeType: String; begin result := 'application/json'; end; function TOpenMHealthAdaptor.NewIdStatus: TCreateIdState; begin result := idCheckNew; end; function TOpenMHealthAdaptor.readDataPoint(json: TJsonObject): TFHIRObservation; var schema : string; begin result := TFHIRObservation.Create; try result.meta := TFHIRMeta.Create; // not set by OMH result.status := ObservationStatusFinal; // final is reasonable for most mobilde data if (not json.has('header')) then // it must, but check anyway raise EFHIRException.create('Cannot process without header'); schema := readHeader(json.obj['header'], result); if (schema = 'physical-activity') then readPhysicalActivity(json.obj['body'], result) else if (schema = 'blood-glucose') then readBloodGlucose(json.obj['body'], result) else raise EFHIRException.create('Unsupported schema type '+schema); result.Link; finally result.Free; end; end; function TOpenMHealthAdaptor.readHeader(hdr: TJsonObject; obs: TFhirObservation) : String; var ext : TFHIRExtension; obj : TJsonObject; begin // id --> resource.id. obs.id := hdr['id']; // creation_date_time --> extension on metadata. What is the significance of this value? why does it matter? or is it actually last_updated? ext := obs.meta.extensionList.Append; ext.url := 'http://healthintersections.com.au/fhir/StructureDefinition/first-created'; ext.value := TFhirDateTime.Create(TDateTimeEx.fromXml(hdr['creation_date_time'])); // schema_id --> this maps to a profile on observation. todo: what is the correct URL? obj := hdr.obj['schema_id']; result := obj['name']; obs.meta.profileList.Add(TFHIRUri.create('http://www.openmhealth.org/schemas/fhir/'+obj['namespace']+'/'+obj['version']+'/'+obj['name'])); obj := hdr.obj['acquisition_provenance']; if (obj <> nil) then begin // acquisition_provenance.source_name --> observation.device if obj.has('source_name') then // though this is required begin obs.device := TFhirReference.Create; obs.device.display := obj['source_name']; end; // acquisition_provenance.source_creation_date_time --> observation. if obj.has('source_creation_date_time') then begin obs.issued := TDateTimeEx.fromXml(obj['source_creation_date_time']); end; // acquisition_provenance.modality --> observation.method if obj.has('modality') then begin obs.method := TFhirCodeableConcept.Create; obs.method.text := obj['modality']; end; end; // user_id --> Observation.subject if hdr.has('user_id') then begin obs.subject := TFhirReference.Create; obs.subject.reference := 'Patient/'+hdr['user_id']; end; end; procedure TOpenMHealthAdaptor.readPhysicalActivity(body: TJsonObject; obs: TFhirObservation); var c : TFHIRCoding; obj : TJsonObject; begin // physical activity is the category c := obs.categoryList.Append.codingList.Append; c.system := 'http://openmhealth.org/codes'; c.code := 'omh'; c.display := 'OpenMHealth Data'; // code comes from activity name obs.code := TFhirCodeableConcept.Create; obs.code.text := body['activity_name']; // effective_time_frame --> Observation.effective obj := body.obj['effective_time_frame']; if (obj <> nil) then begin if (obj.has('time_interval')) then obs.effective := readTimeInterval(obj.obj['time_interval']) else if (obj.has('date_time')) then obs.effective := TFhirDateTime.Create(TDateTimeEx.fromXml(obj['date_time'])); end; // distance --> Observation.value if body.has('distance') then obs.value := readQuantity(body.obj['distance']); if body.has('kcal_burned') then obs.addComponent('http://loinc.org', '41981-2').value := readQuantity(body.obj['kcal_burned']); if body.has('reported_activity_intensity') then obs.addComponent('http://openmhealth.org/codes', 'reported_activity_intensity').value := TFHIRString.create(body['reported_activity_intensity']); if body.has('met_value') then obs.addComponent('http://snomed.info/sct', '698834005').value := readQuantity(body.obj['met_value']); end; function TOpenMHealthAdaptor.readQuantity(obj: TJsonObject): TFHIRQuantity; begin result := TFhirQuantity.Create; try result.value := obj['value']; result.system := 'http://unitsofmeasure.org'; result.unit_ := obj['unit']; result.code := convertUCUMUnit(result.unit_); result.Link; finally result.Free; end; end; function TOpenMHealthAdaptor.readTimeInterval(obj: TJsonObject): TFHIRPeriod; var qty : TFHIRQuantity; ext : TFHIRExtension; day : TDateTimeEx; s : String; begin result := TFHIRPeriod.create; try // creation_date_time --> extension on metadata. What is the significance of this value? why does it matter? or is it actually last_updated? ext := result.extensionList.Append; ext.url := 'http://healthintersections.com.au/fhir/StructureDefinition/period-form'; if obj.has('start_date_time') and obj.has('end_date_time') then begin // The interval is defined by a precise start and end time result.start := TDateTimeEx.fromXml(obj['start_date_time']); result.end_ := TDateTimeEx.fromXml(obj['end_date_time']); ext.value := TFhirCode.Create('normal'); end else if obj.has('start_date_time') and obj.has('duration') then begin // The interval is defined by a precise start time and a duration result.start := TDateTimeEx.fromXml(obj['start_date_time']); qty := readQuantity(obj.obj['duration']); try result.end_ := result.start.add(qty.asDuration); finally qty.Free; end; ext.value := TFhirCode.Create('start.duration'); end else if obj.has('end_date_time') and obj.has('duration') then begin // The interval is defined by a duration and a precise end time result.end_ := TDateTimeEx.fromXml(obj['end_date_time']); qty := readQuantity(obj.obj['duration']); try result.start := result.start.subtract(qty.asDuration); finally qty.Free; end; ext.value := TFhirCode.Create('end.duration'); end else begin // the interval is defined by a date and a part of the day (morning, afternoon, evening, night) day := TDateTimeEx.fromXml(obj['date']); s := obj['part_of_day']; if (s = 'morning') then begin ext.value := TFhirCode.Create('day.morning'); result.start := day.add(0.25); // 6am --> 12noon result.end_ := day.add(0.5); end else if (s = 'afternoon') then begin ext.value := TFhirCode.Create('day.afternoon'); result.start := day.add(0.5); // 12noon --> 6pm result.end_ := day.add(0.75); end else if (s = 'evening') then begin ext.value := TFhirCode.Create('day.evening'); result.start := day.add(0.75); // 6pm --> midnight result.end_ := day.add(1); end else if (s = 'night') then begin ext.value := TFhirCode.Create('day.night'); result.start := day.add(0); // midnight --> 6am - but is it the next day? result.end_ := day.add(0.25); end; end; result.link; finally result.free; end; end; function TOpenMHealthAdaptor.ResourceName: String; begin result := 'Observation'; end; function TOpenMHealthAdaptor.unconvertObsStat(s: String): String; begin if (s = 'average') then result := 'average' else if (s = 'maximum') then result := 'maximum' else if (s = 'minimum') then result := 'minimum' else if (s = 'count') then result := 'count' else if (s = 'median') then result := 'median' else if (s = 'std-dev') then result := 'standard deviation' else if (s = 'sum') then result := 'sum' else if (s = 'variance') then result := 'variance' else if (s = '%20') then result := '20th percentile' else if (s = '%80') then result := '80th percentile' else if (s = '4-lower') then result := 'lower quartile' else if (s = '4-upper') then result := 'upper quartile' else if (s = '4-dev') then result := 'quartile deviation' else if (s = '5-1') then result := '1st quintile' else if (s = '5-2') then result := '2nd quintile' else if (s = '5-3') then result := '3rd quintile' else if (s = '5-4') then result := '4th quintile' else result := s; end; function TOpenMHealthAdaptor.unconvertUCUMUnit(s: String): String; begin if (s = '[in_i]') then result := 'in' else if (s = '[ft_i]') then result := 'ft' else if (s = '[yd_i]') then result := 'yd' else if (s = '[mi_i]') then result := 'mi' else if (s = 's') then result := 'sec' else if (s = 'mo') then result := 'Mo' else if (s = 'a') then result := 'yr' else result := s; end; procedure TOpenMHealthAdaptor.writeObservation(obs: TFHIRObservation; json: TJsonObject); var schema : String; begin schema := writeHeader(obs, json.forceObj['header']); if (schema = 'physical-activity') then writePhysicalActivity(obs, json.forceObj['body']) else if (schema = 'blood-glucose') then writeBloodGlucose(obs, json.forceObj['body']) else raise EFHIRException.create('Unsupported schema type '+schema); end; function TOpenMHealthAdaptor.writePeriod(period: TFHIRPeriod): TJsonObject; var form : String; qty : TFhirQuantity; begin if (period.start.null) then raise EFHIRException.create('Can''t convert a period to OpenMHealth when periods are incomplete'); if (period.end_.null) then raise EFHIRException.create('Can''t convert a period to OpenMHealth when periods are incomplete'); result := TJsonObject.Create; try form := period.getExtensionString('http://healthintersections.com.au/fhir/StructureDefinition/period-form'); if (form = 'start.duration') then begin result['start_date_time'] := period.start.toXml; qty := TFHIRQuantity.fromDuration(period.end_.UTC.dateTime - period.start.UTC.dateTime); try result.obj['duration'] := writeQuantity(qty); finally qty.Free; end; end else if (form = 'end.duration') then begin result['end_date_time'] := period.end_.toXml; qty := TFHIRQuantity.fromDuration(period.start.UTC.dateTime - period.end_.UTC.dateTime); try result.obj['duration'] := writeQuantity(qty); finally qty.Free; end; end else if (form = 'day.morning') then begin result['date'] := period.start.toXml.Substring(0, 10); result.str['part_of_day'] := 'morning'; end else if (form = 'day.afternoon') then begin result['date'] := period.start.toXml.Substring(0, 10); result.str['part_of_day'] := 'afternoon'; end else if (form = 'day.evening') then begin result['date'] := period.start.toXml.Substring(0, 10); result.str['part_of_day'] := 'evening'; end else if (form = 'day.night') then begin result['date'] := period.start.toXml.Substring(0, 10); result.str['part_of_day'] := 'night'; end else begin result['start_date_time'] := period.start.toXml; result['end_date_time'] := period.end_.toXml; end; result.Link; finally result.Free; end; end; procedure TOpenMHealthAdaptor.writePhysicalActivity(obs: TFHIRObservation; body: TJsonObject); var comp : TFhirObservationComponent; begin body['activity_name'] := obs.code.text; if (obs.effective <> nil) then begin if (obs.effective is TFhirPeriod) then body.forceObj['effective_time_frame'].obj['time_interval'] := writePeriod(TFhirPeriod(obs.effective)) else if (obs.effective is TFhirDateTime) then body.forceObj['effective_time_frame']['date_time'] := TFhirDateTime(obs.effective).value.toXml; end; if obs.value is TFHIRQuantity then body.obj['distance'] := writeQuantity(obs.value as TFhirQuantity); if obs.getComponent('http://loinc.org', '41981-2', comp) then body.obj['kcal_burned'] := writeQuantity(comp.value as TFhirQuantity); if obs.getComponent('http://openmhealth.org/codes', 'reported_activity_intensity', comp) then body['reported_activity_intensity'] := (comp.value as TFhirString).value; if obs.getComponent('http://snomed.info/sct', '698834005', comp) then body.obj['met_value'] := writeQuantity(comp.value as TFhirQuantity); end; function TOpenMHealthAdaptor.writeQuantity(qty: TFHIRQuantity): TJsonObject; begin result := TJsonObject.Create; try result['value'] := qty.value; result['unit'] := unconvertUCUMUnit(qty.code); result.Link; finally result.Free; end; end; function TOpenMHealthAdaptor.writeHeader(obs: TFHIRObservation; hdr: TJsonObject) : String; var obj : TJsonObject; u : TFHIRUri; s : String; p : TArray<String>; begin hdr['id'] := obs.id; if (obs.meta.hasExtension('http://healthintersections.com.au/fhir/StructureDefinition/first-created')) then hdr['creation_date_time'] := obs.meta.getExtensionString('http://healthintersections.com.au/fhir/StructureDefinition/first-created'); s := ''; for u in obs.meta.profileList do if u.value.StartsWith('http://www.openmhealth.org/schemas/fhir/') then s := u.value; if (s = '') then // todo: try doing it anyway raise EFHIRException.create('Cannot represent an observation with no OpenMHealth profile as an OpenMHealth data point'); p := s.Split(['/']); obj := hdr.forceObj['schema_id']; obj['namespace'] := p[5]; obj['version'] := p[6]; obj['name'] := p[7]; result := p[7]; if (obs.device <> nil) or (obs.issued.notNull) or (obs.method <> nil) then begin obj := hdr.forceobj['acquisition_provenance']; if (obs.device <> nil) then obj['source_name'] := obs.device.display; if (obs.issued.notNull) then obj['source_creation_date_time'] := obs.issued.toXml; if (obs.method <> nil) then obj['modality'] := obs.method.text; end; if (obs.subject <> nil) and (obs.subject.reference.StartsWith('Patient/')) then hdr['user_id'] := obs.subject.reference.Substring(8); end; procedure TOpenMHealthAdaptor.readBloodGlucose(body: TJsonObject; obs: TFhirObservation); var c : TFHIRCoding; qty : TFhirQuantity; sp : TFHIRSpecimen; obj : TJsonObject; begin // physical activity is the category c := obs.categoryList.Append.codingList.Append; c.system := 'http://openmhealth.org/codes'; c.code := 'omh'; c.display := 'OpenMHealth Data'; // LOINC code depends on units.. qty := readQuantity(body.obj['blood_glucose']); obs.value := qty; obs.code := TFhirCodeableConcept.Create; c := obs.code.codingList.Append; c.system := 'http://loinc.org'; if (qty.code = 'mg/dL') then begin c.code := '2339-0'; c.display := 'Glucose [Mass/volume] in Blood'; end else begin c.code := '15074-8'; c.display := 'Glucose [Moles/volume] in Blood'; end; // specimen_source --> observation.specimen.code if (body.has('specimen_source')) then begin sp := TFhirSpecimen.Create; sp.id := 'sp'; obs.containedList.Add(sp); obs.specimen := TFhirReference.Create; obs.specimen.reference := '#sp'; sp.type_ := TFhirCodeableConcept.Create; sp.type_.text := body['specimen_source']; // todo: can this be coded? end; // effective_time_frame --> Observation.effective obj := body.obj['effective_time_frame']; if (obj <> nil) then begin if (obj.has('time_interval')) then obs.effective := readTimeInterval(obj.obj['time_interval']) else if (obj.has('date_time')) then obs.effective := TFhirDateTime.Create(TDateTimeEx.fromXml(obj['date_time'])); end; // temporal_relationship_to_meal/sleep --> component.value if (body.has('temporal_relationship_to_meal')) then obs.addComponent('http://snomed.info/sct', '309602000').value := TFHIRString.create(body['temporal_relationship_to_meal']); if (body.has('temporal_relationship_to_sleep')) then obs.addComponent('http://snomed.info/sct', '309609009').value := TFHIRString.create(body['temporal_relationship_to_sleep']); // descriptive stat- follow the $stats patterns if (body.has('descriptive_statistic')) then begin obs.addComponent('http://hl7.org/fhir/observation-statistics', convertObsStat(body['descriptive_statistic'])).value := obs.value.Link; obs.value := nil; end; // user_notes --> Observation.comment if (body.has('user_notes')) then obs.comment := body['user_notes']; end; procedure TOpenMHealthAdaptor.writeBloodGlucose(obs: TFHIRObservation; body: TJsonObject); var comp : TFhirObservationComponent; sp : TFHIRSpecimen; begin if obs.getComponent('http://hl7.org/fhir/observation-statistics', comp) then begin body.obj['blood_glucose'] := writeQuantity(comp.value as TFHIRQuantity); body['descriptive_statistic'] := unconvertObsStat(comp.code.codingList[0].code); end else body.obj['blood_glucose'] := writeQuantity(obs.value as TFHIRQuantity); sp := obs.Contained['sp'] as TFhirSpecimen; if (sp <> nil) then body['specimen_source'] := sp.type_.text; if (obs.effective <> nil) then begin if (obs.effective is TFhirPeriod) then body.forceObj['effective_time_frame'].obj['time_interval'] := writePeriod(TFhirPeriod(obs.effective)) else if (obs.effective is TFhirDateTime) then body.forceObj['effective_time_frame']['date_time'] := TFhirDateTime(obs.effective).value.toXml; end; if obs.getComponent('http://snomed.info/sct', '309602000', comp) then body['temporal_relationship_to_meal'] := (comp.value as TFhirString).value; if obs.getComponent('http://snomed.info/sct', '309609009', comp) then body['temporal_relationship_to_sleep'] := (comp.value as TFhirString).value; if obs.comment <> '' then body['user_notes'] := obs.comment; end; procedure TOpenMHealthAdaptor.writeBundle(obs: TFHIRBundle; json: TJsonObject); var arr : TJsonArray; be : TFhirBundleEntry; begin arr := json.forceArr['matches']; for be in obs.entryList do begin if be.resource is TFHIRObservation then writeObservation(be.resource as TFHIRObservation, arr.addObject()); end; end; end.
33.76738
186
0.686594
c321521d6f6ea33a60b3a62f98436b784f371651
746
dfm
Pascal
windows/src/engine/keyman/UfrmKeymanMenu.dfm
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
1
2021-03-08T09:31:47.000Z
2021-03-08T09:31:47.000Z
windows/src/engine/keyman/UfrmKeymanMenu.dfm
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
null
null
null
windows/src/engine/keyman/UfrmKeymanMenu.dfm
ermshiperete/keyman
0eeef1b5794fd698447584e531e2a6c1ef4c05aa
[ "MIT" ]
null
null
null
object frmKeymanMenu: TfrmKeymanMenu Left = 0 Top = 0 BorderIcons = [] BorderStyle = bsNone ClientHeight = 632 ClientWidth = 707 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] FormStyle = fsStayOnTop OldCreateOrder = False OnClick = FormClick OnCreate = TntFormCreate OnDestroy = TntFormDestroy OnHide = TntFormHide OnKeyDown = TntFormKeyDown OnMouseLeave = FormMouseLeave OnMouseMove = FormMouseMove OnShow = TntFormShow PixelsPerInch = 96 TextHeight = 13 object imgTitle: TImage Left = 28 Top = 29 Width = 109 Height = 36 AutoSize = True Transparent = True Visible = False end end
20.722222
36
0.697051
c379a5afb09f62ec7862f53663c0faec363628b2
2,971
pas
Pascal
engine/Lib/particles/tdpe.lib.particle.abstract.restriction.pas
jomael/thundax-delphi-physics-engine
a86f38cdaba1f00c5ef5296a8ae67b816a59448e
[ "MIT" ]
56
2015-03-15T10:22:50.000Z
2022-02-22T11:58:08.000Z
engine/Lib/particles/tdpe.lib.particle.abstract.restriction.pas
jomael/thundax-delphi-physics-engine
a86f38cdaba1f00c5ef5296a8ae67b816a59448e
[ "MIT" ]
2
2016-07-10T07:57:05.000Z
2019-10-14T15:49:06.000Z
engine/Lib/particles/tdpe.lib.particle.abstract.restriction.pas
jomael/thundax-delphi-physics-engine
a86f38cdaba1f00c5ef5296a8ae67b816a59448e
[ "MIT" ]
18
2015-07-17T19:24:39.000Z
2022-01-20T05:40:46.000Z
(* * Copyright (c) 2010-2012 Thundax Delphi Physics Engine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'TDPE' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit tdpe.lib.particle.abstract.restriction; interface Uses tdpe.lib.particle.abstractElement, tdpe.lib.render, tdpe.lib.writer.contract; type TAbstractRestriction = Class(TAbstractElement) Private Fstiffness: double; FRenderer: TAbstractRenderer; FLogger: IWriter; Public constructor Create(Stiffness: double); Reintroduce; Function Stiffness: double; Overload; Procedure Stiffness(Value: double); Overload; Procedure Init; Override; Procedure SetRenderer(aRenderer: TAbstractRenderer); procedure setLog(const Value: IWriter); Procedure Resolve; Virtual; Abstract; property Renderer: TAbstractRenderer read FRenderer; end; implementation { AbstractRestriction } constructor TAbstractRestriction.Create(Stiffness: double); begin Inherited Create; Self.Stiffness(Stiffness); end; function TAbstractRestriction.Stiffness: double; begin Result := Fstiffness; end; procedure TAbstractRestriction.Init; begin inherited; end; procedure TAbstractRestriction.SetRenderer(aRenderer: TAbstractRenderer); begin FRenderer := aRenderer; end; procedure TAbstractRestriction.Stiffness(Value: double); begin Fstiffness := Value; end; procedure TAbstractRestriction.setLog(const Value: IWriter); begin FLogger := Value; end; end.
31.946237
78
0.74655
c3d71d7fd64a76580cc36307f8fdde894c1d19e2
9,799
pas
Pascal
src/Security/PasswordHash/Implementations/Argon2i/Argon2iPasswordHashImpl.pas
atkins126/fano
472679437cb42637b0527dda8255ec52a3e1e953
[ "MIT" ]
null
null
null
src/Security/PasswordHash/Implementations/Argon2i/Argon2iPasswordHashImpl.pas
atkins126/fano
472679437cb42637b0527dda8255ec52a3e1e953
[ "MIT" ]
null
null
null
src/Security/PasswordHash/Implementations/Argon2i/Argon2iPasswordHashImpl.pas
atkins126/fano
472679437cb42637b0527dda8255ec52a3e1e953
[ "MIT" ]
null
null
null
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit Argon2iPasswordHashImpl; interface {$MODE OBJFPC} {$H+} uses InjectableObjectImpl, PasswordHashIntf, HlpIHashInfo, HlpArgon2TypeAndVersion; type (*!------------------------------------------------ * Argon2i password hash * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-----------------------------------------------*) TArgon2iPasswordHash = class (TInjectableObject, IPasswordHash) private fSalt : string; fCost : integer; fHashLen : integer; fSecret : string; fMemoryAsKB : integer; fParallelism : integer; fArgon2Version : TArgon2Version; fArgon2ParametersBuilder : IArgon2ParametersBuilder; public constructor create( const defSecret : string; const defSalt : string = ''; const defCost : integer = 10; const defLen : integer = 64; const defMemAsKb : integer = 32; const defParallel : integer = 4 ); destructor destroy(); override; (*!------------------------------------------------ * set hash generator cost *----------------------------------------------- * @param algorithmCost cost of hash generator * @return current instance *-----------------------------------------------*) function cost(const algorithmCost : integer) : IPasswordHash; (*!------------------------------------------------ * set hash memory cost (if applicable) *----------------------------------------------- * @param memCost cost of memory * @return current instance *-----------------------------------------------*) function memory(const memCost : integer) : IPasswordHash; (*!------------------------------------------------ * set hash paralleism cost (if applicable) *----------------------------------------------- * @param paralleismCost cost of paralleisme * @return current instance *-----------------------------------------------*) function paralleism(const paralleismCost : integer) : IPasswordHash; (*!------------------------------------------------ * set hash length *----------------------------------------------- * @param hashLen length of hash * @return current instance *-----------------------------------------------*) function len(const hashLen : integer) : IPasswordHash; (*!------------------------------------------------ * set password salt *----------------------------------------------- * @param saltValue salt * @return current instance *-----------------------------------------------*) function salt(const saltValue : string) : IPasswordHash; (*!------------------------------------------------ * set secret key *----------------------------------------------- * @param secretValue a secret value * @return current instance *-----------------------------------------------*) function secret(const secretValue : string) : IPasswordHash; (*!------------------------------------------------ * generate password hash *----------------------------------------------- * @param plainPassw input password * @return password hash *-----------------------------------------------*) function hash(const plainPassw : string) : string; (*!------------------------------------------------ * verify plain password against password hash *----------------------------------------------- * @param plainPassw input password * @param hashedPassw password hash * @return true if password match password hash *-----------------------------------------------*) function verify( const plainPassw : string; const hashedPasswd : string ) : boolean; end; implementation uses Classes, SysUtils, HlpIHash, HlpHashFactory, HlpConverters, HlpPBKDF_Argon2NotBuildInAdapter; constructor TArgon2iPasswordHash.create( const defSecret : string; const defSalt : string = ''; const defCost : integer = 10; const defLen : integer = 64; const defMemAsKb : integer = 32; const defParallel : integer = 4 ); begin fSecret := defSecret; fSalt := defSalt; fCost := defCost; fHashLen := defLen; fMemoryAsKB := defMemAsKb; fParallelism := defParallel; fArgon2Version := TArgon2Version.a2vARGON2_VERSION_10; fArgon2ParametersBuilder := TArgon2iParametersBuilder.Builder(); end; destructor TArgon2iPasswordHash.destroy(); begin fArgon2ParametersBuilder := nil; inherited destroy(); end; (*!------------------------------------------------ * set hash generator cost *----------------------------------------------- * @param algorithmCost cost of hash generator * @return current instance *-----------------------------------------------*) function TArgon2iPasswordHash.cost(const algorithmCost : integer) : IPasswordHash; begin fCost := algorithmCost; result := self; end; (*!------------------------------------------------ * set hash memory cost (if applicable) *----------------------------------------------- * @param memCost cost of memory * @return current instance *-----------------------------------------------*) function TArgon2iPasswordHash.memory(const memCost : integer) : IPasswordHash; begin fMemoryAsKB := memCost; result := self; end; (*!------------------------------------------------ * set hash paralleism cost (if applicable) *----------------------------------------------- * @param paralleismCost cost of paralleisme * @return current instance *-----------------------------------------------*) function TArgon2iPasswordHash.paralleism(const paralleismCost : integer) : IPasswordHash; begin fParallelism := paralleismCost; result := self; end; (*!------------------------------------------------ * set hash length *----------------------------------------------- * @param hashLen length of hash * @return current instance *-----------------------------------------------*) function TArgon2iPasswordHash.len(const hashLen : integer) : IPasswordHash; begin fHashLen := hashLen; result := self; end; (*!------------------------------------------------ * set password salt *----------------------------------------------- * @param salt * @return current instance *-----------------------------------------------*) function TArgon2iPasswordHash.salt(const saltValue : string) : IPasswordHash; begin fSalt := saltValue; result := self; end; (*!------------------------------------------------ * set secret key *----------------------------------------------- * @param secretValue a secret value * @return current instance *-----------------------------------------------*) function TArgon2iPasswordHash.secret(const secretValue : string) : IPasswordHash; begin fSecret := secretValue; result := self; end; (*!------------------------------------------------ * generate password hash *----------------------------------------------- * @param plainPassw input password * @return password hash *-----------------------------------------------*) function TArgon2iPasswordHash.hash(const plainPassw : string) : string; var LGenerator: IPBKDF_Argon2; LSecret, LSalt, LPassword: TBytes; LArgon2Parameter: IArgon2Parameters; begin LSecret := TConverters.ConvertHexStringToBytes(fSecret); LSalt := TConverters.ConvertHexStringToBytes(fSalt); LPassword := TConverters.ConvertHexStringToBytes(plainPassw); fArgon2ParametersBuilder.WithVersion(fArgon2Version) .WithIterations(fCost) .WithMemoryAsKB(fMemoryAsKB) .WithParallelism(fParallelism) .WithSecret(LSecret) .WithSalt(LSalt); // // Set the password. // LArgon2Parameter := fArgon2ParametersBuilder.Build(); fArgon2ParametersBuilder.Clear(); LGenerator := TKDF.TPBKDF_Argon2.CreatePBKDF_Argon2( LPassword, LArgon2Parameter ); result := TConverters.ConvertBytesToHexString( LGenerator.GetBytes(fHashLen), false ); LArgon2Parameter.Clear(); LGenerator.Clear(); end; (*!------------------------------------------------ * verify plain password against password hash *----------------------------------------------- * @param plainPassw input password * @param hashedPassw password hash * @return true if password match password hash *-----------------------------------------------*) function TArgon2iPasswordHash.verify( const plainPassw : string; const hashedPasswd : string ) : boolean; begin result := (hash(plainPassw) = hashedPasswd); end; end.
34.262238
93
0.448719
fcdb937d8dc28a47df9be27874788eee5d295e80
4,834
pas
Pascal
Tests/WebMock.Dynamic.Responder.Tests.pas
atkins126/Delphi-WebMocks
bd6287fcf983368c8b3de63cc5e9323440ad9c10
[ "Apache-2.0" ]
30
2019-11-03T16:31:41.000Z
2022-03-30T12:46:03.000Z
Tests/WebMock.Dynamic.Responder.Tests.pas
atkins126/Delphi-WebMocks
bd6287fcf983368c8b3de63cc5e9323440ad9c10
[ "Apache-2.0" ]
21
2019-11-11T16:55:53.000Z
2021-04-05T09:17:59.000Z
Tests/WebMock.Dynamic.Responder.Tests.pas
atkins126/Delphi-WebMocks
bd6287fcf983368c8b3de63cc5e9323440ad9c10
[ "Apache-2.0" ]
6
2019-11-12T19:51:50.000Z
2021-07-06T00:42:14.000Z
{******************************************************************************} { } { Delphi-WebMocks } { } { Copyright (c) 2020 Richard Hatherall } { } { richard@appercept.com } { https://appercept.com } { } {******************************************************************************} { } { 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. } { } {******************************************************************************} unit WebMock.Dynamic.Responder.Tests; interface uses DUnitX.TestFramework, Mock.Indy.HTTPRequestInfo, WebMock.Dynamic.Responder, WebMock.HTTP.Messages, WebMock.HTTP.Request; type [TestFixture] TWebMockDynamicResponderTests = class(TObject) private Responder: TWebMockDynamicResponder; IndyRequest: TMockIdHTTPRequestInfo; Request: IWebMockHTTPRequest; public [Setup] procedure Setup; [TearDown] procedure TearDown; [Test] procedure GetResponseTo_Always_ReturnsResponse; [Test] procedure GetResponseTo_Always_CallsProcWithRequest; [Test] procedure GetResponseTo_Always_CallsProcWithInitialisedResponseBuilder; [Test] procedure GetResponseTo_Always_ReturnsBuiltResponse; end; implementation uses WebMock.Response; { TWebMockDynamicResponderTests } procedure TWebMockDynamicResponderTests.GetResponseTo_Always_CallsProcWithInitialisedResponseBuilder; var LResponse: IWebMockResponse; begin Responder := TWebMockDynamicResponder.Create( procedure(const ARequest: IWebMockHTTPRequest; const AResponse: IWebMockResponseBuilder) begin Assert.IsNotNull(AResponse, 'Response builder should be initialised.'); end ); LResponse := Responder.GetResponseTo(Request); Responder.Free; end; procedure TWebMockDynamicResponderTests.GetResponseTo_Always_CallsProcWithRequest; var LResponse: IWebMockResponse; begin Responder := TWebMockDynamicResponder.Create( procedure(const ARequest: IWebMockHTTPRequest; const AResponse: IWebMockResponseBuilder) begin Assert.AreSame(Request, ARequest); end ); LResponse := Responder.GetResponseTo(Request); Responder.Free; end; procedure TWebMockDynamicResponderTests.GetResponseTo_Always_ReturnsBuiltResponse; var LResponse: IWebMockResponse; begin Responder := TWebMockDynamicResponder.Create( procedure(const ARequest: IWebMockHTTPRequest; const AResponse: IWebMockResponseBuilder) begin AResponse.WithStatus(401); end ); LResponse := Responder.GetResponseTo(Request); Assert.AreEqual(401, LResponse.Status.Code); Responder.Free; end; procedure TWebMockDynamicResponderTests.GetResponseTo_Always_ReturnsResponse; var LResponse: IWebMockResponse; begin Responder := TWebMockDynamicResponder.Create( procedure(const ARequest: IWebMockHTTPRequest; const AResponse: IWebMockResponseBuilder) begin // Do nothing. end ); LResponse := Responder.GetResponseTo(nil); Assert.IsNotNull(LResponse); Responder.Free; end; procedure TWebMockDynamicResponderTests.Setup; begin IndyRequest := TMockIdHTTPRequestInfo.Mock; Request := TWebMockHTTPRequest.Create(IndyRequest); end; procedure TWebMockDynamicResponderTests.TearDown; begin Request := nil; IndyRequest.Free; end; initialization TDUnitX.RegisterTestFixture(TWebMockDynamicResponderTests); end.
33.109589
101
0.574266
c35a66e59cf38692824a511cf1c062aa96cfddd3
28,832
pas
Pascal
Ext/SVGIconImageList/Image32/source/Img32.Fmt.BMP.pas
EtheaDev/SVGShellExtensions
ef9bb5373d4a8b72d97b4f3861888c36aa179d2b
[ "Apache-2.0" ]
63
2021-02-05T15:47:56.000Z
2022-03-09T11:36:39.000Z
Ext/SVGIconImageList/Image32/source/Img32.Fmt.BMP.pas
EtheaDev/SVGShellExtensions
ef9bb5373d4a8b72d97b4f3861888c36aa179d2b
[ "Apache-2.0" ]
13
2021-02-11T08:39:38.000Z
2022-03-28T22:48:09.000Z
Ext/SVGIconImageList/Image32/source/Img32.Fmt.BMP.pas
EtheaDev/SVGShellExtensions
ef9bb5373d4a8b72d97b4f3861888c36aa179d2b
[ "Apache-2.0" ]
5
2021-02-12T15:35:55.000Z
2021-07-11T02:34:40.000Z
unit Img32.Fmt.BMP; (******************************************************************************* * Author : Angus Johnson * * Version : 3.0 * * Date : 20 July 2021 * * Website : http://www.angusj.com * * Copyright : Angus Johnson 2019-2021 * * Purpose : BMP file format extension for TImage32 * * License : http://www.boost.org/LICENSE_1_0.txt * *******************************************************************************) interface {$I Img32.inc} uses {$IFDEF MSWINDOWS} Windows,{$ENDIF} SysUtils, Classes, Math, Img32; type //TImage32Fmt_BMP.LoadFromFile() loads correctly all 'good' BMP images //in Jason Summers' test suite - see http://entropymine.com/jason/bmpsuite/ //For notes on RLE bitmap compression, see ... //https://docs.microsoft.com/en-us/windows/desktop/gdi/bitmap-compression TImageFormat_BMP = class(TImageFormat) private fUseClipboardFormat: Boolean; fIncludeFileHeaderInSaveStream: Boolean; public class function IsValidImageStream(stream: TStream): Boolean; override; function LoadFromStream(stream: TStream; img32: TImage32): Boolean; override; function SaveToFile(const filename: string; img32: TImage32): Boolean; override; procedure SaveToStream(stream: TStream; img32: TImage32); override; {$IFDEF MSWINDOWS} class function CanCopyToClipboard: Boolean; override; class function CopyToClipboard(img32: TImage32): Boolean; override; class function CanPasteFromClipboard: Boolean; override; class function PasteFromClipboard(img32: TImage32): Boolean; override; {$ENDIF} property IncludeFileHeaderInSaveStream: Boolean read fIncludeFileHeaderInSaveStream write fIncludeFileHeaderInSaveStream; end; {$IFDEF MSWINDOWS} function LoadFromHBITMAP(img32: TImage32; bm: HBITMAP; pal: HPALETTE = 0): Boolean; {$ENDIF} implementation resourcestring s_cf_dib_error = 'TImage32 - clipboard CF_DIB format error'; type PTriColor32 = ^TTriColor32; TTriColor32 = array [0..2] of TColor32; TArrayOfByte = array of Byte; TBitmapFileHeader = packed record bfType: Word; bfSize: Cardinal; bfReserved1: Word; bfReserved2: Word; bfOffBits: Cardinal; end; TBitmapInfoHeader = packed record biSize: Cardinal; biWidth: Longint; biHeight: Longint; biPlanes: Word; biBitCount: Word; biCompression: Cardinal; biSizeImage: Cardinal; biXPelsPerMeter: Longint; biYPelsPerMeter: Longint; biClrUsed: Cardinal; biClrImportant: Cardinal; end; PBitmapCoreHeader = ^TBitmapCoreHeader; TBitmapCoreHeader = packed record bcSize: Cardinal; bcWidth: Word; bcHeight: Word; bcPlanes: Word; bcBitCount: Word; end; TCIEXYZ = record ciexyzX: Longint; ciexyzY: Longint; ciexyzZ: Longint; end; TCIEXYZTriple = record ciexyzRed: TCIEXYZ; ciexyzGreen: TCIEXYZ; ciexyzBlue: TCIEXYZ; end; TBitmapV4Header = packed record bV4Size: Cardinal; bV4Width: Longint; bV4Height: Longint; bV4Planes: Word; bV4BitCount: Word; bV4V4Compression: Cardinal; bV4SizeImage: Cardinal; bV4XPelsPerMeter: Longint; bV4YPelsPerMeter: Longint; bV4ClrUsed: Cardinal; bV4ClrImportant: Cardinal; bV4RedMask: Cardinal; bV4GreenMask: Cardinal; bV4BlueMask: Cardinal; bV4AlphaMask: Cardinal; bV4CSType: Cardinal; bV4Endpoints: TCIEXYZTriple; bV4GammaRed: Cardinal; bV4GammaGreen: Cardinal; bV4GammaBlue: Cardinal; end; const BI_RGB = 0; BI_RLE24 = 4; BI_RLE8 = 1; BI_RLE4 = 2; BI_BITFIELDS = 3; //------------------------------------------------------------------------------ // Loading (reading) BMP images from file ... //------------------------------------------------------------------------------ function StreamReadPalette(stream: TStream; count, size: integer): TArrayOfColor32; var i: integer; c: TARGB; begin setLength(Result, count); for i := 0 to count -1 do begin stream.Read(c, size); with c do result[i] := $FF000000 + R shl 16 + G shl 8 + B; end; end; //------------------------------------------------------------------------------ function StreamReadImageWithBitfields(stream: TStream; width, height, bpp: integer; bitfields: TTriColor32): TArrayOfColor32; var i,j,bytesPerRow, bytesPerPix: integer; shift, size: array[0..2] of byte; buffer: PByte; dstPixel: PARGB; b: PCardinal; begin Result := nil; //from the 3 bitfields, get each bit mask offset (shift) and bit mask size for i := 0 to 2 do begin size[i] := 0; shift[i] := 0; for j := 0 to 31 do if (size[i] > 0) then begin if bitfields[i] and (1 shl j) > 0 then inc(size[i]) else break; end else if bitfields[i] and (1 shl j) > 0 then begin shift[i] := j; size[i] := 1; end; end; for i := 0 to 2 do begin //bitfields larger than 8 aren't supported if size[i] > 8 then Exit; //colorXBit.R = (buffer^ and bitfields[0]) shr shift[0] //and the largest possible value for colorXBit.R = (1 shl size[i]) - 1 //so convert size[x] to the maximum possible value for colorXBit.R ... size[i] := (1 shl size[i]) - 1; end; bytesPerPix := bpp div 8; bytesPerRow := ((31 + bpp * width) div 32) * 4; setLength(Result, width * height); GetMem(buffer, bytesPerRow); try for i := 0 to height -1 do begin stream.Read(buffer^, bytesPerRow); b := PCardinal(buffer); dstPixel := @result[i * width]; for j := 0 to width -1 do begin dstPixel.A := 255; //convert colorXBit.R to color32bit.R ... //dstPixel.R = colorXBit.R * 255 div size[0] dstPixel.R := DivTable[(b^ and bitfields[0]) shr shift[0], size[0]]; dstPixel.G := DivTable[(b^ and bitfields[1]) shr shift[1], size[1]]; dstPixel.B := DivTable[(b^ and bitfields[2]) shr shift[2], size[2]]; inc(dstPixel); inc(PByte(b), bytesPerPix); end; end; finally FreeMem(buffer); end; end; //------------------------------------------------------------------------------ {$RANGECHECKS OFF} function StreamReadImageWithPalette(stream: TStream; width, height, bpp: integer; const palette: TArrayOfColor32): TArrayOfColor32; var i,j, bytesPerRow, palHigh, pxCnt: integer; buffer: TArrayOfByte; b: PByte; dstPixel: PColor32; c, shift: byte; begin shift := 8 - bpp; bytesPerRow := ((31 + bpp * width) div 32) * 4; setLength(Result, width * height); palHigh := High(palette); SetLength(buffer, bytesPerRow); for i := 0 to height -1 do begin stream.Read(buffer[0], bytesPerRow); b := @buffer[0]; dstPixel := @result[i * width]; pxCnt := 0; for j := 0 to width -1 do begin pxCnt := (pxCnt + bpp) mod 8; c := Ord(b^) shr shift; if c > palHigh then dstPixel^ := clNone32 else dstPixel^ := palette[c]; if pxCnt = 0 then inc(b) else Byte(b^) := Ord(b^) shl bpp; inc(dstPixel); end; end; end; //------------------------------------------------------------------------------ function GetByte(stream: TStream): Byte; {$IFDEF INLINE} inline; {$ENDIF} begin stream.Read(Result, 1); end; //------------------------------------------------------------------------------ function GetNibble(stream: TStream; var bitsOffset: integer): Byte; begin stream.Read(Result, 1); if bitsOffset = 4 then begin result := result and $F; bitsOffset := 0; end else begin Stream.Position := Stream.Position -1; result := result shr 4; bitsOffset := 4; end; end; //------------------------------------------------------------------------------ function ReadRLE4orRLE8Compression(stream: TStream; width, height, bpp: integer; const palette: TArrayOfColor32): TArrayOfColor32; var i,j,k, cnt, idx: integer; w, delta, bitOffset: integer; dst: PColor32; byte1, byte2: byte; const COMMAND_BYTE = 0; DELTA_MODE = 2; begin setLength(Result, width * height); for i := 0 to height -1 do begin dst := @result[i * width]; w := 0; idx := 0; while w < width do begin byte1 := GetByte(stream); byte2 := GetByte(stream); if byte1 = COMMAND_BYTE then begin if byte2 < 2 then Exit //error else if byte2 = DELTA_MODE then begin cnt := GetByte(stream); delta := GetByte(stream); if delta > 0 then Exit; //Y-delta never seen & not supported for k := 1 to cnt do begin dst^ := palette[idx]; inc(w); inc(dst); end; end else //'absolute mode' begin cnt := byte2; bitOffset := 0; for k := 1 to cnt do begin if bpp = 4 then idx := GetNibble(stream, bitOffset) else idx := GetByte(stream); dst^ := palette[idx]; inc(w); if w = width then break; inc(dst); end; if bitOffset > 0 then GetByte(stream); if Odd(stream.Position) then GetByte(stream); //ie must be WORD aligned end; end else //'encoded mode' begin cnt := byte1; if bpp = 4 then begin for j := 1 to cnt do begin if Odd(j) then idx := byte2 shr 4 else idx := byte2 and $F; dst^ := palette[idx]; inc(w); if w = width then break; inc(dst); end; end else begin idx := byte2; for j := 1 to cnt do begin dst^ := palette[idx]; inc(w); inc(dst); end; end; end; end; byte1 := GetByte(stream); byte2 := GetByte(stream); if (byte1 <> 0) or (byte2 <> 0) then Exit; end; end; //------------------------------------------------------------------------------ function IsValidBitFields(const bitFields: TTriColor32): boolean; begin //make sure each color channel has a mask and that they don't overlap ... result := (bitFields[0] <> 0) and (bitFields[1] <> 0) and (bitFields[2] <> 0) and (bitFields[0] and bitFields[1] = 0) and (bitFields[0] and bitFields[2] = 0) and (bitFields[1] and bitFields[2] = 0); end; //------------------------------------------------------------------------------ function AlphaChannelAllZero(img32: TImage32): Boolean; var i: integer; pc: PARGB; begin result := false; pc := PARGB(img32.PixelBase); for i := 0 to img32.Width * img32.Height -1 do begin if (pc.A > 0) then Exit; inc(pc); end; result := true; end; //------------------------------------------------------------------------------ procedure ResetAlphaChannel(img32: TImage32); var i: integer; pc: PARGB; begin pc := PARGB(img32.PixelBase); for i := 0 to img32.Width * img32.Height -1 do begin pc.A := 255; inc(pc); end; end; //------------------------------------------------------------------------------ class function TImageFormat_BMP.IsValidImageStream(stream: TStream): Boolean; var savedPos: integer; flag: Cardinal; const SizeOfBitmapInfoHeader = 40; SizeOfBitmapV4Header = 108; SizeOfBitmapV5Header = 124; begin Result := false; savedPos := stream.position; if stream.size - savedPos <= 4 then Exit; stream.read(flag, SizeOf(flag)); stream.Position := savedPos; Result := ((flag and $FFFF) = $4D42) or (flag = SizeOfBitmapInfoHeader) or (flag = SizeOfBitmapV4Header) or (flag = SizeOfBitmapV5Header); end; //------------------------------------------------------------------------------ function TImageFormat_BMP.LoadFromStream(stream: TStream; img32: TImage32): Boolean; var palEntrySize: integer; bihStart: cardinal; bfh: TBitmapFileHeader; bih: TBitmapInfoHeader; tmp, pal: TArrayOfColor32; bitfields: TTriColor32; isTopDown, hasValidBitFields: boolean; pb: PByteArray; begin result := false; with stream do begin if Size < sizeof(bih) then Exit; bihStart := stream.Position; //some streams (eg resource streams) omit the file header ... Read(bfh, SizeOf(bfh)); if bfh.bfType = $4D42 then begin inc(bihStart, SizeOf(bfh)) end else begin bfh.bfOffBits := 0; stream.Position := bihStart; end; Read(bih, sizeof(bih)); if bih.biSize < sizeof(bih) then //accommodate dodgy TBitmapInfoHeader's begin if bih.biSize <sizeof(TBitmapCoreHeader) then Exit; pb := @bih.biSize; FillChar(pb[bih.biSize], sizeof(bih) - bih.biSize, 0); end; palEntrySize := 4; if bih.biSize = sizeof(TBitmapCoreHeader) then begin bih.biBitCount := PBitmapCoreHeader(@bih).bcBitCount; bih.biHeight := PBitmapCoreHeader(@bih).bcHeight; bih.biWidth := PBitmapCoreHeader(@bih).bcWidth; bih.biPlanes := 1; bih.biCompression := 0; bih.biClrUsed := 0; palEntrySize := 3; end; //make sure this is a valid BMP stream //(nb: embedded JPEG and PNG formats not supported) if (bih.biBitCount > 32) or (bih.biWidth > $3FFF) or (bih.biHeight > $3FFF) or //16,383 (bih.biCompression > BI_BITFIELDS) then Exit; isTopDown := bih.biHeight < 0; bih.biHeight := abs(bih.biHeight); if ((bih.biCompression and BI_BITFIELDS) = BI_BITFIELDS) then begin stream.Position := bihStart + 40; stream.Read(bitfields[0], Sizeof(TTriColor32)); hasValidBitFields := IsValidBitFields(bitfields); if stream.Position < bihStart + bih.biSize then stream.Position := bihStart + bih.biSize; end else begin hasValidBitFields := false; stream.Position := bihStart + bih.biSize; end; if not hasValidBitFields then begin if bih.biBitCount = 24 then begin bitfields[0] := $FF shl 16; bitfields[1] := $FF shl 8; bitfields[2] := $FF; hasValidBitFields := true; end else if bih.biBitCount = 16 then begin bitfields[0] := $1F shl 10; bitfields[1] := $1F shl 5; bitfields[2] := $1F; hasValidBitFields := true; end; end; if bih.biClrUsed > 256 then bih.biClrUsed := 0; if (bih.biClrUsed = 0) and (bih.biBitCount < 16) then bih.biClrUsed := Trunc(Power(2, bih.biBitCount)); if bih.biClrUsed > 0 then pal := StreamReadPalette(stream, bih.biClrUsed, palEntrySize); tmp := nil; result := true; img32.BeginUpdate; try img32.SetSize(bih.biWidth, bih.biHeight); //read pixels .... if stream.Position < bfh.bfOffBits then stream.Position := bfh.bfOffBits; if hasValidBitFields then tmp := StreamReadImageWithBitfields( stream, img32.Width, img32.Height, bih.biBitCount, bitfields) else if (bih.biBitCount = 32) then begin Read(img32.Pixels[0], bih.biWidth * bih.biHeight * sizeof(TColor32)); if AlphaChannelAllZero(img32) then ResetAlphaChannel(img32); end else if (bih.biCompression = BI_RLE8) or (bih.biCompression = BI_RLE4) then tmp := ReadRLE4orRLE8Compression( stream, img32.Width, img32.Height, bih.biBitCount, pal) else tmp := StreamReadImageWithPalette( stream, img32.Width, img32.Height, bih.biBitCount, pal); if assigned(tmp) and (length(tmp) = img32.Width * img32.Height) then move(tmp[0], img32.Pixels[0], length(tmp) * sizeof(TColor32)); if not isTopDown then img32.FlipVertical; finally img32.EndUpdate; end; end; end; //------------------------------------------------------------------------------ // Saving (writing) BMP images to file ... //------------------------------------------------------------------------------ function GetFileHeaderFromInfoHeader(stream: TStream; BitmapInfoHeaderOffset: integer): TBitmapFileHeader; var bih: TBitmapInfoHeader; begin FillChar(Result, sizeof(Result), #0); Result.bfType := $4D42; stream.Position := BitmapInfoHeaderOffset; stream.Read(bih, sizeof(bih)); if (bih.biWidth = 0) or (bih.biHeight = 0) then Exit; Result.bfSize := bih.biSizeImage; Result.bfOffBits := (stream.Size - bih.biSizeImage); end; //------------------------------------------------------------------------------ function MakeBitfields: TTriColor32; begin result[0] := $FF0000; result[1] := $00FF00; result[2] := $0000FF; end; //------------------------------------------------------------------------------ function GetRowSize(bitCount, imageWidth: integer): integer; begin result := ((31 + BitCount * imageWidth) div 32) * 4; end; //------------------------------------------------------------------------------ function Find(color: TColor32; const colors: TArrayOfColor32; colorsCnt: integer; out idx: integer): Boolean; var i,l,r: integer; begin //binary search a sorted list ... Result := False; l := 0; r := colorsCnt -1; while l <= r do begin idx := (l + r) shr 1; i := integer(colors[idx]) - integer(color); if i < 0 then l := idx +1 else begin r := idx -1; if i = 0 then begin result := true; l := idx; end; end; end; idx := l; end; //------------------------------------------------------------------------------ function IndexOf(color: TColor32; const colors: TArrayOfColor32): integer; var i,l,r: integer; begin //binary search a sorted list ... l := 0; r := Length(colors) -1; while l <= r do begin result := (l + r) shr 1; i := integer(colors[result]) - integer(color); if i < 0 then l := result +1 else begin r := result -1; if i = 0 then l := result; end; end; result := l; end; //------------------------------------------------------------------------------ procedure Insert256(color: TColor32; var colors256: TArrayOfColor32; cnt, idx: integer); begin if idx < cnt then move(colors256[idx], colors256[idx +1], (cnt - idx) * SizeOf(TColor32)); colors256[idx] := color; end; //------------------------------------------------------------------------------ function GetPaletteColors(img32: TImage32): TArrayOfColor32; var i, idx, palLen: integer; c: TColor32; pc: PColor32; begin Result := nil; if img32.IsEmpty then Exit; SetLength(Result, 256); palLen := 0; pc := PColor32(img32.PixelBase); for i := 0 to img32.Width * img32.Height -1 do begin c := pc^ and $FFFFFF; if not Find(c, result, palLen, idx) then begin if palLen = 256 then begin result := nil; //too many colors for a palette Exit; end; Insert256(c, result, palLen, idx); inc(palLen); end; inc(pc); end; SetLength(Result, palLen); end; //------------------------------------------------------------------------------ procedure StreamWriteLoBitImage(img32: TImage32; const pals: TArrayOfColor32; BitCount: integer; stream: TStream); var i, j, k, pxlPerByte, rowSize, delta, shiftSize, totalBytes: integer; buffer: TArrayOfByte; pSrc: PColor32; pDst: PByte; begin pxlPerByte := 8 div BitCount; rowSize := GetRowSize(BitCount, img32.Width); delta := rowSize - img32.Width div pxlPerByte; //delphi doesn't handle modulo of negatives as expected so ... shiftSize := img32.Width mod pxlPerByte; if shiftSize > 0 then shiftSize := pxlPerByte - shiftSize; totalBytes := rowSize * img32.Height; SetLength(buffer, totalBytes); fillChar(buffer[0], totalBytes, 0); pSrc := img32.PixelBase; pDst := @buffer[0]; for i := 1 to img32.Height do begin k := 0; for j := 1 to img32.Width do begin k := k shl BitCount + IndexOf(pSrc^ and $FFFFFF, pals); if (j mod pxlPerByte = 0) then begin Byte(pDst^) := k; inc(pDst); k := 0; end; inc(pSrc); end; if shiftSize > 0 then Byte(pDst^) := k shl shiftSize; inc(pDst, delta); end; stream.Write(buffer[0], totalBytes); end; //------------------------------------------------------------------------------ procedure StreamWrite24BitImage(img32: TImage32; stream: TStream); var i,j, delta, rowSize, totalBytes: integer; buffer: TArrayOfByte; pc: PColor32; pb: PByte; begin rowSize := GetRowSize(24, img32.Width); delta := rowSize - (img32.Width *3); totalBytes := rowSize * img32.Height; setLength(buffer, totalBytes); fillChar(buffer[0], totalBytes, 0); pb := @buffer[0]; pc := img32.PixelBase; for i := 0 to img32.Height -1 do begin for j := 0 to img32.Width -1 do begin Move(pc^, pb^, 3); //ie skipping the alpha byte inc(pc); inc(pb, 3); end; inc(pb, delta); end; stream.Write(buffer[0], totalBytes); //much faster to do this once end; //------------------------------------------------------------------------------ procedure TImageFormat_BMP.SaveToStream(stream: TStream; img32: TImage32); var bfh: TBitmapFileHeader; bih: TBitmapV4Header; palCnt, BitCount, rowSize, infoHeaderOffset: integer; UsesAlpha: Boolean; pals: TArrayOfColor32; tmp: TImage32; writeValue: TTriColor32; begin //write everything except a BMP file header because some streams //(eg resource streams) don't need a file header if fUseClipboardFormat then UsesAlpha := false else UsesAlpha := img32.HasTransparency; if fUseClipboardFormat or UsesAlpha then begin BitCount := 32; palCnt := 0; end else begin pals := GetPaletteColors(img32); palCnt := Length(pals); if palCnt = 0 then BitCount := 24 else if palCnt > 16 then BitCount := 8 else if palCnt > 2 then BitCount := 4 else BitCount := 1; end; if fIncludeFileHeaderInSaveStream then begin //Write empty BitmapFileHeader ... FillChar(bfh, sizeof(bfh), #0); stream.Write(bfh, sizeOf(bfh)); end; infoHeaderOffset := stream.Position; FillChar(bih, sizeof(bih), #0); rowSize := GetRowSize(BitCount, img32.Width); bih.bV4Width := img32.Width; bih.bV4Height := img32.Height; bih.bV4Planes := 1; bih.bV4BitCount := BitCount; bih.bV4ClrUsed := palCnt; bih.bV4SizeImage := rowSize * img32.Height; if UsesAlpha then begin bih.bV4Size := sizeof(TBitmapV4Header); bih.bV4V4Compression := BI_BITFIELDS; bih.bV4RedMask := $FF shl 16; bih.bV4GreenMask := $FF shl 8; bih.bV4BlueMask := $FF; bih.bV4AlphaMask := Cardinal($FF) shl 24; end else begin bih.bV4Size := sizeof(TBitmapInfoHeader); //Version2 header bih.bV4V4Compression := BI_RGB; end; tmp := TImage32.Create(img32); try tmp.FlipVertical; case BitCount of 1,4,8: begin stream.Write(bih, bih.bV4Size); SetLength(pals, palCnt); stream.Write(pals[0], palCnt * 4); StreamWriteLoBitImage(tmp, pals, BitCount, stream); end; 24: begin bih.bV4V4Compression := BI_BITFIELDS; stream.Write(bih, bih.bV4Size); writeValue := MakeBitfields; stream.Write(writeValue, SizeOf(TTriColor32)); StreamWrite24BitImage(tmp, stream); end else begin stream.Write(bih, bih.bV4Size); stream.Write(tmp.Pixels[0], tmp.Width * tmp.Height * sizeof(TColor32)); end; end; finally tmp.Free; end; if fIncludeFileHeaderInSaveStream then begin //finally update BitmapFileHeader ... bfh := GetFileHeaderFromInfoHeader(stream, infoHeaderOffset); stream.Position := infoHeaderOffset - sizeOf(bfh); stream.Write(bfh, sizeOf(bfh)); end; end; //------------------------------------------------------------------------------ function TImageFormat_BMP.SaveToFile(const filename: string; img32: TImage32): Boolean; var SaveStateIncludeFileHeader: Boolean; stream: TFilestream; begin result := not img32.IsEmpty; if not result then Exit; SaveStateIncludeFileHeader := fIncludeFileHeaderInSaveStream; stream := TFileStream.Create(filename, fmCreate); try fIncludeFileHeaderInSaveStream := true; fUseClipboardFormat := false; SaveToStream(stream, img32); finally stream.Free; fIncludeFileHeaderInSaveStream := SaveStateIncludeFileHeader; end; end; //------------------------------------------------------------------------------ {$IFDEF MSWINDOWS} class function TImageFormat_BMP.CanCopyToClipboard: Boolean; begin Result := true; end; //------------------------------------------------------------------------------ class function TImageFormat_BMP.CopyToClipboard(img32: TImage32): Boolean; var dataHdl: THandle; dataPtr: pointer; ms: TMemoryStream; begin result := OpenClipboard(0); if not Result then Exit; ms := TMemoryStream.Create; try with TImageFormat_BMP.Create do try fUseClipboardFormat := true; SaveToStream(ms, img32); finally free; end; dataHdl := GlobalAlloc(GMEM_MOVEABLE or GMEM_SHARE, ms.Size); try dataPtr := GlobalLock(dataHdl); try Move(ms.Memory^, dataPtr^, ms.Size); finally GlobalUnlock(dataHdl); end; if SetClipboardData(CF_DIB, dataHdl) = 0 then raise Exception.Create(s_cf_dib_error); except GlobalFree(dataHdl); raise; end; finally ms.free; CloseClipboard; end; end; //------------------------------------------------------------------------------ class function TImageFormat_BMP.CanPasteFromClipboard: Boolean; begin result := IsClipboardFormatAvailable(CF_DIB) or IsClipboardFormatAvailable(CF_BITMAP); end; //------------------------------------------------------------------------------ class function TImageFormat_BMP.PasteFromClipboard(img32: TImage32): Boolean; var dataHdl: THandle; bitmapHdl: HBITMAP; paletteHdl: HPALETTE; dataPtr: pointer; ms: TMemoryStream; begin result := OpenClipboard(0); if not Result then Exit; try if IsClipboardFormatAvailable(CF_DIB) then begin ms := TMemoryStream.Create; try dataHdl := GetClipboardData(CF_DIB); result := dataHdl > 0; if not result then Exit; ms.SetSize(GlobalSize(dataHdl)); dataPtr := GlobalLock(dataHdl); try Move(dataPtr^, ms.Memory^, ms.Size); finally GlobalUnlock(dataHdl); end; ms.Position := 0; with TImageFormat_BMP.Create do try LoadFromStream(ms, img32); finally Free; end; finally ms.free; end; end else if IsClipboardFormatAvailable(CF_BITMAP) then begin bitmapHdl := GetClipboardData(CF_BITMAP); if IsClipboardFormatAvailable(CF_PALETTE) then paletteHdl := GetClipboardData(CF_PALETTE) else paletteHdl := 0; result := bitmapHdl > 0; if result then LoadFromHBITMAP(img32, bitmapHdl, paletteHdl); end; finally CloseClipboard; end; end; //------------------------------------------------------------------------------ function LoadFromHBITMAP(img32: TImage32; bm: HBITMAP; pal: HPALETTE): Boolean; var w, h: integer; memDc: HDC; oldBitmap, oldPalette: HGDIOBJ; bi: BITMAPINFO; begin result := false; memDC := CreateCompatibleDC(0); try oldBitmap := SelectObject(memDC, bm); if (pal > 0) then begin oldPalette := SelectPalette(memDC, pal, FALSE); RealizePalette(memDc); end else oldPalette := 0; FillChar(bi, SizeOf(bi), 0); bi.bmiHeader.biSize := SizeOf(bi); if GetDIBits(memDc, bm, 0, 0, nil, bi, DIB_RGB_COLORS) = 0 then Exit; h := abs(bi.bmiHeader.biHeight); bi.bmiHeader.biHeight := h; w := bi.bmiHeader.biWidth; bi.bmiHeader.biBitCount := 32; bi.bmiHeader.biCompression := BI_RGB; img32.BeginUpdate; try img32.SetSize(w, h); if GetDIBits(memDc, bm, 0, h, PByte(img32.PixelBase), bi, DIB_RGB_COLORS) = 0 then Exit; img32.FlipVertical; finally img32.EndUpdate; end; SelectObject(memDC, oldBitmap); if (oldPalette > 0) then SelectObject(memDC, oldPalette); Result := true; finally DeleteDC(memDC); end; end; //------------------------------------------------------------------------------ {$ENDIF} initialization TImage32.RegisterImageFormatClass('BMP', TImageFormat_BMP, cpLow); end.
27.830116
85
0.572177
fc5ead379b541951e1987fbb2ff5f9f7aa85e22b
10,709
pas
Pascal
Units/Forms/UFRMPascalCoinWalletConfig.pas
blaisecoin/blaisecoin
4d769f2b4e79c8f232de9035d30c5cc0cb90f803
[ "MIT" ]
null
null
null
Units/Forms/UFRMPascalCoinWalletConfig.pas
blaisecoin/blaisecoin
4d769f2b4e79c8f232de9035d30c5cc0cb90f803
[ "MIT" ]
null
null
null
Units/Forms/UFRMPascalCoinWalletConfig.pas
blaisecoin/blaisecoin
4d769f2b4e79c8f232de9035d30c5cc0cb90f803
[ "MIT" ]
null
null
null
{ Copyright (c) 2016 by Albert Molina Copyright (c) 2017 by BlaiseCoin developers Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of BlaiseCoin, a P2P crypto-currency. } unit UFRMPascalCoinWalletConfig; {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses {$IFnDEF FPC} Windows, ShellApi, {$ELSE} LCLIntf, LCLType, LMessages, {$ENDIF} Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ComCtrls, UAppParams, UWalletKeys; type TMinerPrivateKey = (mpk_NewEachTime, mpk_Random, mpk_Selected); { TFRMPascalCoinWalletConfig } TFRMPascalCoinWalletConfig = class(TForm) cbJSONRPCMinerServerActive: TCheckBox; ebDefaultFee: TEdit; Label1: TLabel; cbSaveLogFiles: TCheckBox; cbShowLogs: TCheckBox; bbOk: TBitBtn; bbCancel: TBitBtn; udInternetServerPort: TUpDown; ebInternetServerPort: TEdit; Label2: TLabel; lblDefaultInternetServerPort: TLabel; bbUpdatePassword: TBitBtn; Label3: TLabel; ebMinerName: TEdit; Label4: TLabel; cbShowModalMessages: TCheckBox; Label5: TLabel; udJSONRPCMinerServerPort: TUpDown; ebJSONRPCMinerServerPort: TEdit; lblDefaultJSONRPCMinerServerPort: TLabel; gbMinerPrivateKey: TGroupBox; rbGenerateANewPrivateKeyEachBlock: TRadioButton; rbUseARandomKey: TRadioButton; rbMineAllwaysWithThisKey: TRadioButton; cbPrivateKeyToMine: TComboBox; cbSaveDebugLogs: TCheckBox; bbOpenDataFolder: TBitBtn; cbJSONRPCPortEnabled: TCheckBox; ebJSONRPCAllowedIPs: TEdit; Label6: TLabel; Label7: TLabel; procedure FormCreate(Sender: TObject); procedure bbOkClick(Sender: TObject); procedure bbUpdatePasswordClick(Sender: TObject); procedure cbSaveLogFilesClick(Sender: TObject); procedure bbOpenDataFolderClick(Sender: TObject); procedure cbJSONRPCPortEnabledClick(Sender: TObject); private FAppParams: TAppParams; FWalletKeys: TWalletKeys; procedure SetAppParams(const Value: TAppParams); procedure SetWalletKeys(const Value: TWalletKeys); procedure UpdateWalletConfig; { Private declarations } public { Public declarations } property AppParams : TAppParams read FAppParams write SetAppParams; property WalletKeys : TWalletKeys read FWalletKeys write SetWalletKeys; end; implementation uses UConst, UAccounts, ULog, UCrypto, UFolderHelper; {$IFnDEF FPC} {$R *.dfm} {$ELSE} {$R *.lfm} {$ENDIF} procedure TFRMPascalCoinWalletConfig.bbOkClick(Sender: TObject); var df : Int64; mpk : TMinerPrivateKey; i : Integer; begin if udInternetServerPort.Position = udJSONRPCMinerServerPort.Position then raise Exception.Create('Server port and JSON-RPC Server miner port are equal!'); if TAccountComp.TxtToMoney(ebDefaultFee.Text,df) then begin AppParams.ParamByName[CT_PARAM_DefaultFee].SetAsInt64(df); end else begin ebDefaultFee.Text := TAccountComp.FormatMoney(AppParams.ParamByName[CT_PARAM_DefaultFee].GetAsInt64(CT_DefaultFee)); raise Exception.Create('Invalid Fee value'); end; AppParams.ParamByName[CT_PARAM_InternetServerPort].SetAsInteger(udInternetServerPort.Position ); if rbGenerateANewPrivateKeyEachBlock.Checked then mpk := mpk_NewEachTime else if rbUseARandomKey.Checked then mpk := mpk_Random else if rbMineAllwaysWithThisKey.Checked then begin mpk := mpk_Selected; if cbPrivateKeyToMine.ItemIndex<0 then raise Exception.Create('Must select a private key'); i := PtrInt(cbPrivateKeyToMine.Items.Objects[cbPrivateKeyToMine.ItemIndex]); if (i<0) Or (i>=FWalletKeys.Count) then raise Exception.Create('Invalid private key'); AppParams.ParamByName[CT_PARAM_MinerPrivateKeySelectedPublicKey].SetAsString( TAccountComp.AccountKey2RawString( FWalletKeys.Key[i].AccountKey ) ); end else mpk := mpk_Random; AppParams.ParamByName[CT_PARAM_MinerPrivateKeyType].SetAsInteger(integer(mpk)); AppParams.ParamByName[CT_PARAM_JSONRPCMinerServerActive].SetAsBoolean(cbJSONRPCMinerServerActive.Checked ); AppParams.ParamByName[CT_PARAM_SaveLogFiles].SetAsBoolean(cbSaveLogFiles.Checked ); AppParams.ParamByName[CT_PARAM_ShowLogs].SetAsBoolean(cbShowLogs.Checked ); AppParams.ParamByName[CT_PARAM_SaveDebugLogs].SetAsBoolean(cbSaveDebugLogs.Checked); AppParams.ParamByName[CT_PARAM_MinerName].SetAsString(ebMinerName.Text); AppParams.ParamByName[CT_PARAM_ShowModalMessages].SetAsBoolean(cbShowModalMessages.Checked); AppParams.ParamByName[CT_PARAM_JSONRPCMinerServerPort].SetAsInteger(udJSONRPCMinerServerPort.Position); AppParams.ParamByName[CT_PARAM_JSONRPCEnabled].SetAsBoolean(cbJSONRPCPortEnabled.Checked); AppParams.ParamByName[CT_PARAM_JSONRPCAllowedIPs].SetAsString(ebJSONRPCAllowedIPs.Text); ModalResult := MrOk; end; procedure TFRMPascalCoinWalletConfig.bbOpenDataFolderClick(Sender: TObject); begin {$IFDEF FPC} OpenDocument(pchar(TFolderHelper.GetPascalCoinDataFolder)) {$ELSE} shellexecute(0, 'open', pchar(TFolderHelper.GetPascalCoinDataFolder), nil, nil, SW_SHOW) {$ENDIF} end; procedure TFRMPascalCoinWalletConfig.bbUpdatePasswordClick(Sender: TObject); var s,s2 : String; begin if not Assigned(FWalletKeys) then exit; if not FWalletKeys.IsValidPassword then begin s := ''; Repeat if not InputQuery('Wallet Password','Insert Wallet Password',s) then exit; FWalletKeys.WalletPassword := s; if not FWalletKeys.IsValidPassword then Application.MessageBox(PChar('Invalid password'),PChar(Application.Title),MB_ICONERROR+MB_OK); Until FWalletKeys.IsValidPassword; end; if FWalletKeys.IsValidPassword then begin s := ''; s2 := ''; if not InputQuery('Change password','Type new password',s) then exit; if trim(s)<>s then raise Exception.Create('Password cannot start or end with a space character'); if not InputQuery('Change password','Type new password again',s2) then exit; if s<>s2 then raise Exception.Create('Two passwords are different!'); FWalletKeys.WalletPassword := s; Application.MessageBox(PChar('Password changed!'+#10+#10+ 'Please note that your new password is "'+s+'"'+#10+#10+ '(If you lose this password, you will lose your Wallet forever !)'), PChar(Application.Title),MB_ICONWARNING+MB_OK); end; UpdateWalletConfig; end; procedure TFRMPascalCoinWalletConfig.cbJSONRPCPortEnabledClick(Sender: TObject); begin ebJSONRPCAllowedIPs.Enabled := cbJSONRPCPortEnabled.Checked; end; procedure TFRMPascalCoinWalletConfig.cbSaveLogFilesClick(Sender: TObject); begin cbSaveDebugLogs.Enabled := cbSaveLogFiles.Checked; end; procedure TFRMPascalCoinWalletConfig.FormCreate(Sender: TObject); begin lblDefaultInternetServerPort.Caption := Format('(Default %d)',[CT_NetServer_Port]); udInternetServerPort.Position := CT_NetServer_Port; ebDefaultFee.Text := TAccountComp.FormatMoney(0); ebMinerName.Text := ''; bbUpdatePassword.Enabled := false; UpdateWalletConfig; lblDefaultJSONRPCMinerServerPort.Caption := Format('(Default %d)',[CT_JSONRPCMinerServer_Port]); end; procedure TFRMPascalCoinWalletConfig.SetAppParams(const Value: TAppParams); begin FAppParams := Value; if not Assigned(Value) then exit; try udInternetServerPort.Position := AppParams.ParamByName[CT_PARAM_InternetServerPort].GetAsInteger(CT_NetServer_Port); ebDefaultFee.Text := TAccountComp.FormatMoney(AppParams.ParamByName[CT_PARAM_DefaultFee].GetAsInt64(CT_DefaultFee)); cbJSONRPCMinerServerActive.Checked := AppParams.ParamByName[CT_PARAM_JSONRPCMinerServerActive].GetAsBoolean(true); case TMinerPrivateKey(AppParams.ParamByName[CT_PARAM_MinerPrivateKeyType].GetAsInteger(Integer(mpk_Random))) of mpk_NewEachTime : rbGenerateANewPrivateKeyEachBlock.Checked := true; mpk_Random : rbUseARandomKey.Checked := true; mpk_Selected : rbMineAllwaysWithThisKey.Checked := true; else rbUseARandomKey.Checked := true; end; UpdateWalletConfig; cbSaveLogFiles.Checked := AppParams.ParamByName[CT_PARAM_SaveLogFiles].GetAsBoolean(false); cbShowLogs.Checked := AppParams.ParamByName[CT_PARAM_ShowLogs].GetAsBoolean(false); cbSaveDebugLogs.Checked := AppParams.ParamByName[CT_PARAM_SaveDebugLogs].GetAsBoolean(false); ebMinerName.Text := AppParams.ParamByName[CT_PARAM_MinerName].GetAsString(''); cbShowModalMessages.Checked := AppParams.ParamByName[CT_PARAM_ShowModalMessages].GetAsBoolean(false); udJSONRPCMinerServerPort.Position := AppParams.ParamByName[CT_PARAM_JSONRPCMinerServerPort].GetAsInteger(CT_JSONRPCMinerServer_Port); cbJSONRPCPortEnabled.Checked := AppParams.ParamByName[CT_PARAM_JSONRPCEnabled].GetAsBoolean(false); ebJSONRPCAllowedIPs.Text := AppParams.ParamByName[CT_PARAM_JSONRPCAllowedIPs].GetAsString('127.0.0.1;'); except on E:Exception do begin TLog.NewLog(lterror,ClassName,'Exception at SetAppParams: '+E.Message); end; End; cbSaveLogFilesClick(nil); cbJSONRPCPortEnabledClick(nil); end; procedure TFRMPascalCoinWalletConfig.SetWalletKeys(const Value: TWalletKeys); begin FWalletKeys := Value; UpdateWalletConfig; end; procedure TFRMPascalCoinWalletConfig.UpdateWalletConfig; var i, iselected : Integer; s : String; wk : TWalletKey; begin if Assigned(FWalletKeys) then begin if FWalletKeys.IsValidPassword then begin if FWalletKeys.WalletPassword='' then begin bbUpdatePassword.Caption := 'Wallet without password, protect it!'; end else begin bbUpdatePassword.Caption := 'Change Wallet password'; end; end else begin bbUpdatePassword.Caption := 'Wallet with password, change it!'; end; cbPrivateKeyToMine.Items.Clear; for i := 0 to FWalletKeys.Count - 1 do begin wk := FWalletKeys.Key[i]; if (wk.Name='') then begin s := TCrypto.ToHexaString( TAccountComp.AccountKey2RawString(wk.AccountKey)); end else begin s := wk.Name; end; if wk.CryptedKey<>'' then begin cbPrivateKeyToMine.Items.AddObject(s,TObject(i)); end; end; cbPrivateKeyToMine.Sorted := true; if Assigned(FAppParams) then begin s := FAppParams.ParamByName[CT_PARAM_MinerPrivateKeySelectedPublicKey].GetAsString(''); iselected := FWalletKeys.IndexOfAccountKey(TAccountComp.RawString2Accountkey(s)); if iselected>=0 then begin iselected := cbPrivateKeyToMine.Items.IndexOfObject(TObject(iselected)); cbPrivateKeyToMine.ItemIndex := iselected; end; end; end else bbUpdatePassword.Caption := '(Wallet password)'; bbUpdatePassword.Enabled := Assigned(FWAlletKeys); end; end.
39.083942
156
0.769073
c3c52aa7967a01c65c7d7f511b97b66fdea8c691
796
pas
Pascal
Examples/ObserverList/_frBar.pas
ryujt/ryulib4delphi
1269afeb5d55d5d6710cfb1d744d5a1596583a96
[ "MIT" ]
18
2015-05-18T01:55:45.000Z
2019-05-03T03:23:52.000Z
Examples/ObserverList/_frBar.pas
ryujt/ryulib4delphi
1269afeb5d55d5d6710cfb1d744d5a1596583a96
[ "MIT" ]
1
2019-11-08T08:27:34.000Z
2019-11-08T08:43:51.000Z
Examples/ObserverList/_frBar.pas
ryujt/ryulib4delphi
1269afeb5d55d5d6710cfb1d744d5a1596583a96
[ "MIT" ]
19
2015-05-14T01:06:35.000Z
2019-06-02T05:19:00.000Z
unit _frBar; interface uses ValueList, Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls; type TfrBar = class(TFrame) pbVolume: TProgressBar; private public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published procedure rp_CurrentVolume(AValueList:TValueList); end; implementation uses View; {$R *.dfm} { TfrBar } constructor TfrBar.Create(AOwner: TComponent); begin inherited; TView.Obj.Add(Self); end; destructor TfrBar.Destroy; begin TView.Obj.Remove(Self); inherited; end; procedure TfrBar.rp_CurrentVolume(AValueList: TValueList); begin pbVolume.Position := AValueList.Integers['Volume']; end; end.
15.92
84
0.742462
c345956fb6c65f7db30e0f59089437b48505ca02
733
pas
Pascal
Samples/Delphi/VCL/DFM/Unit1.pas
atkins126/I18N
4176f8991b4c572ac36d8b2667dc345c185ff26f
[ "MIT" ]
43
2019-11-04T09:35:05.000Z
2022-02-28T00:01:46.000Z
Samples/Delphi/VCL/DFM/Unit1.pas
tomajexpress/I18N
2cb4161cb70645e62675925089b15e6ece9bd915
[ "MIT" ]
47
2020-01-16T18:13:31.000Z
2022-02-15T15:06:25.000Z
Samples/Delphi/VCL/DFM/Unit1.pas
tomajexpress/I18N
2cb4161cb70645e62675925089b15e6ece9bd915
[ "MIT" ]
20
2019-10-09T03:44:00.000Z
2022-02-28T00:01:48.000Z
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm1 = class(TForm) Label1: TLabel; CloseButton: TButton; ShowButton: TButton; procedure CloseButtonClick(Sender: TObject); procedure ShowButtonClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} uses Unit2; procedure TForm1.CloseButtonClick(Sender: TObject); begin Close; end; procedure TForm1.ShowButtonClick(Sender: TObject); var form: TForm2; begin form := TForm2.Create(nil); form.Show; end; end.
15.934783
98
0.720327
c32cd45705201e0e12907205c8dd5665b65aa24e
5,885
pas
Pascal
Demos/Main Demos/LogFormUnit.pas
PopRe/HtmlViewer
e7e96247fb1b63f59ddfcd2888793b354275b319
[ "MIT" ]
320
2015-01-12T08:42:13.000Z
2022-03-26T14:49:32.000Z
Demos/Main Demos/LogFormUnit.pas
PopRe/HtmlViewer
e7e96247fb1b63f59ddfcd2888793b354275b319
[ "MIT" ]
217
2015-01-05T10:40:53.000Z
2022-03-17T13:49:52.000Z
Demos/Main Demos/LogFormUnit.pas
PopRe/HtmlViewer
e7e96247fb1b63f59ddfcd2888793b354275b319
[ "MIT" ]
133
2015-02-10T12:51:08.000Z
2022-03-17T13:51:32.000Z
{ Version 11.7 Copyright (c) 2008-2016 by HtmlViewer Team Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Note that the source modules HTMLGIF1.PAS and DITHERUNIT.PAS are covered by separate copyright notices located in those modules. } unit LogFormUnit; interface {$include htmlcons.inc} uses {$ifdef LCL} LCLIntf, LCLType, LMessages, {$else} WinTypes, WinProcs, Messages, {$endif} //Windows, SysUtils, Variants, Classes, Graphics, Controls, Forms, {$ifdef UseVCLStyles} Vcl.Styles, Vcl.Themes, Vcl.ActnPopup, {$endif} Dialogs, StdCtrls, IniFiles, Menus, SyncObjs; type ThtLogSubject = (laDiag, laHttpHeader, laHttpScript, laJavaScript); ThtLogSubjectSet = set of ThtLogSubject; {$ifdef UseVCLStyles} TPopupMenu = class(Vcl.ActnPopup.TPopupActionBar); {$endif} TLogForm = class(TForm) LogMemo: TMemo; PopupMenu: TPopupMenu; pCopy: TMenuItem; pClear: TMenuItem; pCopyAll: TMenuItem; procedure pClearClick(Sender: TObject); procedure pCopyAllClick(Sender: TObject); procedure pCopyClick(Sender: TObject); procedure LogMemoDblClick(Sender: TObject); procedure LogMemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormClose(Sender: TObject; var Action: TCloseAction); private FLogged: Boolean; FLogIt: ThtLogSubjectSet; function GetLogIt(Index: ThtLogSubject): Boolean; procedure SetLogIt(Index: ThtLogSubject; const Value: Boolean); public Lock: TCriticalSection; Strings: TStringList; constructor Create(AOwner: TComponent; ATop, ALeft, AWidth, AHeight: Integer); reintroduce; procedure Log(const AString: string); overload; procedure Log(const AStrings: TStrings); overload; procedure LogSynced(const AString: string); overload; procedure LogSynced(const AStrings: TStrings); overload; destructor Destroy; override; property LogActive[Index: ThtLogSubject]: Boolean read GetLogIt write SetLogIt; property Logged: Boolean read FLogged write FLogged; end; var LogForm: TLogForm; implementation {$ifdef LCL} {$R *.lfm} {$else} {$R *.dfm} {$endif} //-- BG ---------------------------------------------------------- 23.05.2016 -- constructor TLogForm.Create(AOwner: TComponent; ATop, ALeft, AWidth, AHeight: Integer); begin inherited Create(AOwner); Top := ATop; Left := ALeft; if AWidth > 0 then Width := AWidth; if AHeight > 0 then Height := AHeight; Lock := TCriticalSection.Create; Strings := TStringList.Create; end; destructor TLogForm.Destroy; begin Strings.Free; Lock.Free; inherited; end; //-- BG ---------------------------------------------------------- 23.05.2016 -- procedure TLogForm.Log(const AString: string); begin LogMemo.Lines.Add(AString); // Visible := True; end; //-- BG ---------------------------------------------------------- 23.05.2016 -- procedure TLogForm.Log(const AStrings: TStrings); begin LogMemo.Lines.AddStrings(AStrings); // Visible := True; end; //-- BG ---------------------------------------------------------- 23.05.2016 -- procedure TLogForm.LogSynced(const AString: string); begin Lock.Enter; try Log(AString); finally Lock.Leave; end; // Visible := True; end; //-- BG ---------------------------------------------------------- 23.05.2016 -- procedure TLogForm.LogSynced(const AStrings: TStrings); begin Lock.Enter; try Log(AStrings); finally Lock.Leave; end; // Visible := True; end; procedure TLogForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caHide; end; //-- BG ---------------------------------------------------------- 25.05.2016 -- function TLogForm.GetLogIt(Index: ThtLogSubject): Boolean; begin Result := Index in FLogIt; end; procedure TLogForm.LogMemoDblClick(Sender: TObject); begin LogMemo.Lines.Clear; end; procedure TLogForm.LogMemoKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key = VK_ESCAPE then Close; if Key = VK_CONTROL then exit; if NOT (ssCtrl in Shift) then exit; if Key = Ord ('C') then LogMemo.CopyToClipboard; if Key = Ord ('A') then begin LogMemo.SelectAll; LogMemo.CopyToClipboard; end; if Key = Ord ('X') then LogMemo.Lines.Clear; end; procedure TLogForm.pClearClick(Sender: TObject); begin LogMemo.Lines.Clear; end; procedure TLogForm.pCopyAllClick(Sender: TObject); begin LogMemo.SelectAll; LogMemo.CopyToClipboard; end; procedure TLogForm.pCopyClick(Sender: TObject); begin LogMemo.CopyToClipboard; end; //-- BG ---------------------------------------------------------- 25.05.2016 -- procedure TLogForm.SetLogIt(Index: ThtLogSubject; const Value: Boolean); begin if Value then Include(FLogIt, Index) else Exclude(FLogIt, Index); end; //initialization // Lock := TCriticalSection.Create; // Strings := TStringList.Create; //finalization // Strings.Free; // Lock.Free; end.
27.5
95
0.682923
c3205c5f771b6ab57da2feb035aeea19478c9e44
884
pas
Pascal
u_select_etudiant.pas
maximejournet54/Projet_IHM
fd849dc2c65069b464f3bbbe8d11af23126c3d30
[ "MIT" ]
null
null
null
u_select_etudiant.pas
maximejournet54/Projet_IHM
fd849dc2c65069b464f3bbbe8d11af23126c3d30
[ "MIT" ]
null
null
null
u_select_etudiant.pas
maximejournet54/Projet_IHM
fd849dc2c65069b464f3bbbe8d11af23126c3d30
[ "MIT" ]
null
null
null
unit u_select_etudiant; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls; type { Tf_select_etudiant } Tf_select_etudiant = class(TForm) btn_rechercher: TButton; edt_code: TEdit; edt_num: TEdit; edt_nom: TEdit; lbl_code: TLabel; lbl_nom: TLabel; lbl_num: TLabel; pnl_rechercher: TPanel; pnl_filiere_edit: TPanel; pnl_filiere_btn: TPanel; pnl_filiere: TPanel; pnl_etudiant_edit: TPanel; pnl_etudiant_btn: TPanel; pnl_etudiant: TPanel; pnl_tous_edit: TPanel; pnl_tous_btn: TPanel; pnl_tous: TPanel; pnl_choix: TPanel; pnl_titre: TPanel; private { private declarations } public { public declarations } end; var f_select_etudiant: Tf_select_etudiant; implementation {$R *.lfm} { Tf_select_etudiant } end.
16.37037
76
0.69457
f11b4f92eaaefea3d88c7cb2b1098ad50b5a2ce1
659
pas
Pascal
src/RESTRequest4D.Response.Contract.pas
atkins126/RESTRequest4Delphi
f50cb708efabff39be780367d178281b74cae290
[ "MIT" ]
1
2021-05-02T13:31:30.000Z
2021-05-02T13:31:30.000Z
src/RESTRequest4D.Response.Contract.pas
atkins126/RESTRequest4Delphi
f50cb708efabff39be780367d178281b74cae290
[ "MIT" ]
null
null
null
src/RESTRequest4D.Response.Contract.pas
atkins126/RESTRequest4Delphi
f50cb708efabff39be780367d178281b74cae290
[ "MIT" ]
1
2021-09-11T05:38:44.000Z
2021-09-11T05:38:44.000Z
unit RESTRequest4D.Response.Contract; interface uses {$IFDEF FPC} SysUtils, Classes, fpjson; {$ELSE} System.SysUtils, System.JSON, System.Classes; {$ENDIF} type IResponse = interface ['{A3BB1797-E99E-4C72-8C4A-925825A50C27}'] function Content: string; function ContentLength: Cardinal; function ContentType: string; function ContentEncoding: string; function ContentStream: TStream; function StatusCode: Integer; function RawBytes: TBytes; {$IFDEF FPC} function JSONValue: TJSONData; {$ELSE} function JSONValue: TJSONValue; {$ENDIF} function Headers: TStrings; end; implementation end.
19.969697
49
0.708649
c3fb8eb612060d7ffb863b159c62e2f2085903ef
404
pas
Pascal
code/ooFactory.Item.Intf.pas
VencejoSoftware/ooFactory
a23387d67674d2a36628bc4e398a75de291e76bb
[ "BSD-3-Clause" ]
1
2019-07-08T10:11:17.000Z
2019-07-08T10:11:17.000Z
code/ooFactory.Item.Intf.pas
VencejoSoftware/ooFactory
a23387d67674d2a36628bc4e398a75de291e76bb
[ "BSD-3-Clause" ]
null
null
null
code/ooFactory.Item.Intf.pas
VencejoSoftware/ooFactory
a23387d67674d2a36628bc4e398a75de291e76bb
[ "BSD-3-Clause" ]
2
2019-11-21T03:23:14.000Z
2021-01-26T04:53:40.000Z
{ Copyright (c) 2016, Vencejo Software Distributed under the terms of the Modified BSD License The full license is distributed with this software } unit ooFactory.Item.Intf; interface type TFactoryKey = String; IFactoryItem<TClassType> = interface ['{47E95B9B-25E7-491B-895E-F75E2B297F76}'] function Key: TFactoryKey; function ClassType: TClassType; end; implementation end.
18.363636
57
0.747525
c36542e9349f58d0e04fe15dfeb469d46e994e87
620
dpr
Pascal
ABM/Cliente/Project/Clientes.dpr
Civeloo/GeN-XE7
638b59def20424955972a568817d012df4cf2cde
[ "Apache-2.0" ]
null
null
null
ABM/Cliente/Project/Clientes.dpr
Civeloo/GeN-XE7
638b59def20424955972a568817d012df4cf2cde
[ "Apache-2.0" ]
null
null
null
ABM/Cliente/Project/Clientes.dpr
Civeloo/GeN-XE7
638b59def20424955972a568817d012df4cf2cde
[ "Apache-2.0" ]
null
null
null
program Clientes; uses Forms, UFClientes in '..\Form\UFClientes.pas' {FClientes}, DataModule in '..\..\..\DataModule\DataModule.pas' {DM: TDataModule}, UFBuscaCliente in '..\..\..\Buscar\Cliente\Form\UFBuscaCliente.pas' {FBuscaCliente}, BuscarVendedor in '..\..\..\Buscar\Vendedor\Form\BuscarVendedor.pas' {BuscarVendedorForm}, ImprimirDM in '..\..\..\DataModule\ImprimirDM.pas' {ImprimirDataModule: TDataModule}; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.Title := 'Cliente'; Application.CreateForm(TFClientes, FClientes); Application.Run; end.
31
92
0.722581
c3933d4c6e3d839bac2a067bb7260d70d49d3b81
2,031
pas
Pascal
datetime/0040.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
11
2015-12-12T05:13:15.000Z
2020-10-14T13:32:08.000Z
datetime/0040.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
null
null
null
datetime/0040.pas
nickelsworth/swag
7c21c0da2291fc249b9dc5cfe121a7672a4ffc08
[ "BSD-2-Clause" ]
8
2017-05-05T05:24:01.000Z
2021-07-03T20:30:09.000Z
{ As Robert Forbes said to All on 25 Apr 94... RF> Anyone have any idea how to make an algorithm to RF> calculate the moonphase given the date? Here ya go: TYPE DATETYPE = record day:WORD; MONTH:WORD; YEAR:WORD; dow:word; end; {=================================================================} Procedure GregorianToJulianDN(Year, Month, Day:Integer; var JulianDN :LongInt); var Century, XYear : LongInt; begin {GregorianToJulianDN} If Month <= 2 then begin Year := pred(Year); Month := Month + 12; end; Month := Month - 3; Century := Year div 100; XYear := Year mod 100; Century := (Century * D1) shr 2; XYear := (XYear * D0) shr 2; JulianDN := ((((Month * 153) + 2) div 5) + Day) + D2 + XYear + Century; end; {GregorianToJulianDN} {=================================================================} Function MoonPhase(Date:Datetype):Real; (***************************************************************) (* *) (* Determines APPROXIMATE phase of the moon (percentage lit) *) (* 0.00 = New moon, 1.00 = Full moon *) (* Due to rounding, full values may possibly never be reached *) (* Valid from Oct. 15, 1582 to Feb. 28, 4000 *) (* Calculations and BASIC program found in *) (* "119 Practical Programs For The TRS-80 Pocket Computer" by *) (* John Clark Craig, TAB Books, 1982 *) (* Conversion to Turbo Pascal by Alan Graff, Wheelersburg, OH *) (* *) (***************************************************************) var j:longint; m:real; Begin GregorianToJulianDN(Date.Year,Date.Month,Date.Day,J); M:=(J+4.867)/ 29.53058; M:=2*(M-Int(m))-1; MoonPhase:=Abs(M); end; 
31.246154
68
0.442147
c3e79c345d83f69c4eafdb0c9eade2c855698cc5
4,621
pas
Pascal
library/smart/FHIR.Smart.LoginFMX.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
library/smart/FHIR.Smart.LoginFMX.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
library/smart/FHIR.Smart.LoginFMX.pas
niaz819/fhirserver
fee45e1e57053a776b893dba543f700dd9cb9075
[ "BSD-3-Clause" ]
null
null
null
unit FHIR.Client.SmartLoginFMX; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.WebBrowser, FMX.StdCtrls, FMX.Controls.Presentation, FHIR.Support.Utilities, FHIR.Version.Resources, FHIR.Version.Client, FHIR.Client.SmartUtilities; type TCheckScopesProc = reference to procedure (scopes : TArray<String>; var ok : boolean; var msg : String); TSmartOnFhirLoginForm = class(TForm) Panel1: TPanel; Button2: TButton; WebBrowser1: TWebBrowser; private FLogoPath: String; FClient: TFHIRHTTPClient; FScopes: TArray<String>; FHandleError: boolean; FToken: TClientAccessToken; FErrorMessage: String; procedure SetClient(const Value: TFHIRHTTPClient); procedure SetToken(const Value: TClientAccessToken); public destructor Destroy; override; property logoPath : String read FLogoPath write FLogoPath; property client : TFHIRHTTPClient read FClient write SetClient; property scopes : TArray<String> read FScopes write FScopes; property handleError : boolean read FHandleError write FHandleError; // if modalResult = mrok, you'll get a token. otherwise, you'll get an error message property ErrorMessage : String read FErrorMessage write FErrorMessage; Property Token : TClientAccessToken read FToken write SetToken; end; var SmartOnFhirLoginForm: TSmartOnFhirLoginForm; function doSmartOnFHIRLogin(owner : TComponent; client : TFHIRHTTPClient; cs : TFhirCapabilityStatement; authorize, token : String; scopes : TArray<String>; checkproc : TCheckScopesProc) : boolean; implementation {$R *.fmx} function doSmartOnFHIRLogin(owner : TComponent; client : TFHIRHTTPClient; cs : TFhirCapabilityStatement; authorize, token : String; scopes : TArray<String>; checkproc : TCheckScopesProc) : boolean; var mr : integer; begin SmartOnFhirLoginForm := TSmartOnFhirLoginForm.Create(owner); try SmartOnFhirLoginForm.logoPath := path([ExtractFilePath(paramstr(0)), 'toolkit.png']); SmartOnFhirLoginForm.client := client.Link; SmartOnFhirLoginForm.scopes := scopes; // 'openid profile user/*.*'; SmartOnFhirLoginForm.handleError := true; SmartOnFhirLoginForm.Caption := 'Login to '+client.address; mr := SmartOnFhirLoginForm.ShowModal; if mr = mrOK then begin client.SmartToken := SmartOnFhirLoginForm.Token.Link; result := true; end else if (mr = mrAbort) and (SmartOnFhirLoginForm.ErrorMessage <> '') then MessageDlg(SmartOnFhirLoginForm.ErrorMessage, TMsgDlgType.mtError, [TMsgDlgBtn.mbNo], 0); finally SmartOnFhirLoginForm.Free; end; end; { TSmartOnFhirLoginForm } destructor TSmartOnFhirLoginForm.Destroy; begin FToken.free; FClient.Free; inherited; end; procedure TSmartOnFhirLoginForm.SetClient(const Value: TFHIRHTTPClient); begin FClient.Free; FClient := Value; end; procedure TSmartOnFhirLoginForm.SetToken(const Value: TClientAccessToken); begin FToken.free; FToken := Value; end; end.
37.877049
197
0.770612
c364eed4cf7ce1e941661f03b14442b2b85c2843
50,778
pas
Pascal
ZZ_DW_Template_Face.pas
Vaddix1394/Tes5Edit-Scripting
872cc2093f9085314042e421ffcd169212d13cfa
[ "MIT" ]
1
2018-04-12T13:35:09.000Z
2018-04-12T13:35:09.000Z
ZZ_DW_Template_Face.pas
Vaddix1394/Tes5Edit-Scripting
872cc2093f9085314042e421ffcd169212d13cfa
[ "MIT" ]
null
null
null
ZZ_DW_Template_Face.pas
Vaddix1394/Tes5Edit-Scripting
872cc2093f9085314042e421ffcd169212d13cfa
[ "MIT" ]
null
null
null
// How to install: // 1. Navigate to your Tes5Edit folder, then to the Edit Scripts folder // 2. Copy this file to this folder // How to use: // 1. Load up Tes5Edit // 2. Select only the "Deadly Wenches.esp" box (you can right-click, select none, and then select Deadly Wenches.esp) // 2a. (Optionally) Also select USLEP.esp to ensure the script uses USLEP changes when adding to vanilla leveled list // 3. Wait for background loader to finish // 4. Right click on any mod and select "Apply Script" // 5. Select this script and select "OK" // 6. Wait for the message in the message window [Apply Script done]... // 6a. If there's an error, let me know // 7. Double check bolded entries to see if script worked as intended (if you had expanded a group before, you might need to collapse and reexpand it to see new additions) // 7a. Also let me know if something didn't go right // 8. Exit and save/discard changes // How to Configure // There are three major functions that this script achieves // 1. Creates "variations" of a template record using IW References (see setupVariablesForVariation) // 2. Creates leveled lists with npcs that meet certain filtering criteria (see setupVariablesForLeveledList) // 3. Adds existing DW leveled lists to vanilla leveled lists (see setupVariablesForVanillaLeveledList) // // Each of these functions have a "Template for ...." section that describes how configure the script to your purposes. // unit userscript; var slRoleTemplateList, slRoleTemplateNameList, slRoleTemplateEditorIdList, slLevelListName : TStringList; lFaceTemplateList, lFullNameFilter, lRaceFilter, lFactionFilter, lEditorIdSubstringFilter, lVanillaLevelList, lVanillaLevelListCount, lVoiceFilter : TList; lVarFullNameFilter, lVarRaceFilter, lVarFactionFilter, lVarEditorIdSubstringFilter, lVarVoiceFilter, lVampireKeywordExclusion : TList; target_file, skyrimFile, dwFile, iwFile : IInterface; //--------------------------------------------------------------------------------------- // To Configure //--------------------------------------------------------------------------------------- procedure setupVariablesForVariations; var i : integer; template_index : integer; cur_full_name_filter, cur_race_filter, cur_faction_filter, cur_editorid_substring_filter, cur_voice_filter : TStringList; template_editorid, new_base_editorid, new_full_name : string; begin // TStringList and TList Init slRoleTemplateList := TStringList.Create; slRoleTemplateEditorIdList := TStringList.Create; slRoleTemplateNameList := TStringList.Create; lFaceTemplateList := TList.Create; lVarFullNameFilter := TList.Create; lVarRaceFilter := TList.Create; lVarFactionFilter := TList.Create; lVarEditorIdSubstringFilter := TList.Create; lVarVoiceFilter := TList.Create; lVampireKeywordExclusion := TList.Create; //------------------------------------------------------------------------------------------------------------- // Template for adding new variation //------------------------------------------------------------------------------------------------------------- // template_editorid := ''; // Fill in Editor ID of the template NPC record that has all of the relevant stats/traits/perks etc... // new_base_editorid := ''; // Fill in the desired "base" Editor ID of the new NPC records generated. New Editor ID = base + '_' + race + variation number // new_full_name := ''; // Fill in the desired FULL name of the new NPC records generated // // slRoleTemplateList.Add(template_editorid); // Just copy this block of code // slRoleTemplateEditorIdList.Add(new_base_editorid); // slRoleTemplateNameList.Add(new_full_name); // lFaceTemplateList.Add(TStringList.Create); // lVarFullNameFilter.Add(TStringList.Create); // lVarRaceFilter.Add(TStringList.Create); // lVarFactionFilter.Add(TStringList.Create); // lVarEditorIdSubstringFilter.Add(TStringList.Create); // lVarVoiceFilter.Add(TStringList.Create); // template_index := slRoleTemplateList.IndexOf(template_editorid); // cur_full_name_filter := TStringList(lVarFullNameFilter[template_index]); // cur_race_filter := TStringList(lVarRaceFilter[template_index]); // cur_faction_filter := TStringList(lVarFactionFilter[template_index]); // cur_editorid_substring_filter := TStringList(lVarEditorIdSubstringFilter[template_index]); // cur_voice_filter := TStringList(lVarVoiceFilter[template_index]); // // cur_full_name_filter.Add(''); // Each line here tells the script to use IW NPCs with these FULL names for variation. Comment out if not using filter. // // cur_race_filter.Add(''); // Each line here tells the script to use IW NPCs with these races (using the race EditorID) for variation. Comment out if not using filter. // // cur_faction_filter.Add(''); // Each line here tells the script to use IW NPCs with these factions (using the faction's Editor ID) for variation. Comment out if not using filter. // // cur_editorid_substring_filter.Add(''); // Each line here tells the script to use IW NPCs whose EditorID has the given substring for variation. Comment out if not using filter // // Example: Imperial Soldiers and Guards have the same full name and faction, but different in EditorIDs (ie DW_EncSoldier vs DW_EncGuard) // cur_voice_filter.Add('') // Each line here tells the script to use IW NPCs with these VTYP Editor ID references for variation. Comment out if not using filter. // // lVampireKeywordExclusion.Add(True) // Put either True or False (not in single quotes). Tells the script to ignore npcs with the Vampire Keyword since IW Vampire's are not part of VampireFaction // Must put either True or False //------------------------------------------------------------------------------------------------------------- // Example : Vampire Template //------------------------------------------------------------------------------------------------------------- template_editorid := 'DW_EncVampire06Template'; new_base_editorid := 'DW_EncVampire06Test'; new_full_name := 'Vampire'; slRoleTemplateList.Add(template_editorid); slRoleTemplateEditorIdList.Add(new_base_editorid); slRoleTemplateNameList.Add(new_full_name); lFaceTemplateList.Add(TStringList.Create); lVarFullNameFilter.Add(TStringList.Create); lVarRaceFilter.Add(TStringList.Create); lVarFactionFilter.Add(TStringList.Create); lVarEditorIdSubstringFilter.Add(TStringList.Create); lVarVoiceFilter.Add(TStringList.Create); template_index := slRoleTemplateList.IndexOf(template_editorid); cur_full_name_filter := TStringList(lVarFullNameFilter[template_index]); cur_race_filter := TStringList(lVarRaceFilter[template_index]); cur_faction_filter := TStringList(lVarFactionFilter[template_index]); cur_editorid_substring_filter := TStringList(lVarEditorIdSubstringFilter[template_index]); cur_voice_filter := TStringList(lVarVoiceFilter[template_index]); //cur_full_name_filter.Add(''); // Could also filter by "Vampire Wench" //cur_race_filter.Add('NordRace'); // No need to filter by race //cur_race_filter.Add('BretonRace'); //cur_race_filter.Add('ImperialRace'); //cur_race_filter.Add('RedguardRace'); //cur_race_filter.Add('DarkElfRace'); //cur_race_filter.Add('WoodElfRace'); //cur_race_filter.Add('HighElfRace'); //cur_faction_filter.Add(''); // No need to filter by Factions cur_editorid_substring_filter.Add('lalawenchYYDWDLC1vampire'); // Create variations using IW npcs with this substring in EditorID //cur_voice_filter.Add('FemaleCommander'); // No need to filter by voice //cur_voice_filter.Add('FemaleCommoner'); //cur_voice_filter.Add('FemaleCondescending'); //cur_voice_filter.Add('FemaleCoward'); //cur_voice_filter.Add('FemaleDarkElf'); //cur_voice_filter.Add('FemaleElfHaughty'); //cur_voice_filter.Add('FemaleEvenToned'); //cur_voice_filter.Add('FemaleNord'); //cur_voice_filter.Add('FemaleSultry'); //cur_voice_filter.Add('FemaleYoungEager'); lVampireKeywordExclusion.Add(False); // Do not exclude npcs with Vampire Keyword //------------------------------------------------------------------------------------------------------------- // Example : Warlock Template //------------------------------------------------------------------------------------------------------------- template_editorid := 'DW_EncBandit06MagicBretonF00backup'; new_base_editorid := 'DW_EncWarlock06MagicEventoned'; new_full_name := 'Warlock'; slRoleTemplateList.Add(template_editorid); slRoleTemplateEditorIdList.Add(new_base_editorid); slRoleTemplateNameList.Add(new_full_name); lFaceTemplateList.Add(TStringList.Create); lVarFullNameFilter.Add(TStringList.Create); lVarRaceFilter.Add(TStringList.Create); lVarFactionFilter.Add(TStringList.Create); lVarEditorIdSubstringFilter.Add(TStringList.Create); lVarVoiceFilter.Add(TStringList.Create); template_index := slRoleTemplateList.IndexOf(template_editorid); cur_full_name_filter := TStringList(lVarFullNameFilter[template_index]); cur_race_filter := TStringList(lVarRaceFilter[template_index]); cur_faction_filter := TStringList(lVarFactionFilter[template_index]); cur_editorid_substring_filter := TStringList(lVarEditorIdSubstringFilter[template_index]); cur_voice_filter := TStringList(lVarVoiceFilter[template_index]); //cur_full_name_filter.Add(''); // No need to filter by FULL name cur_race_filter.Add('NordRace'); // Create variations using IW npcs that are nords or bretons cur_race_filter.Add('BretonRace'); //cur_race_filter.Add('ImperialRace'); //cur_race_filter.Add('RedguardRace'); //cur_race_filter.Add('DarkElfRace'); //cur_race_filter.Add('WoodElfRace'); //cur_race_filter.Add('HighElfRace'); //cur_faction_filter.Add(''); // No need to filter by Factions //cur_editorid_substring_filter.Add(''); // No need to filter by substring //cur_voice_filter.Add('FemaleCommander'); // Create variations using IW npcs that have this voice type //cur_voice_filter.Add('FemaleCommoner'); //cur_voice_filter.Add('FemaleCondescending'); //cur_voice_filter.Add('FemaleCoward'); //cur_voice_filter.Add('FemaleDarkElf'); //cur_voice_filter.Add('FemaleElfHaughty'); cur_voice_filter.Add('FemaleEvenToned'); //cur_voice_filter.Add('FemaleNord'); //cur_voice_filter.Add('FemaleSultry'); //cur_voice_filter.Add('FemaleYoungEager'); lVampireKeywordExclusion.Add(True); // Exclude Vampires end; procedure setupVariablesForLeveledList; var cur_full_name_filter, cur_race_filter, cur_faction_filter, cur_editorid_substring_filter, cur_voice_filter : TStringList; i, index : integer; new_level_list_name : string; begin //TList and TString init slLevelListName := TStringList.Create; lFullNameFilter := TList.Create; lRaceFilter := TList.Create; lFactionFilter := TList.Create; lEditorIdSubstringFilter := TList.Create; lVoiceFilter := TList.Create; // For each leveled list string in slLevelListName, creates a leveled list entry with that name and adds npcs // from Deadly Wenches that meet the filters set below //------------------------------------------------------------------------------------------------------------- // Template for adding new leveled list //------------------------------------------------------------------------------------------------------------- // new_level_list_name := ''; // Name of new leveled list // // slLevelListName.Add(new_level_list_name); // Just copy code block // lFullNameFilter.Add(TStringList.Create); // lRaceFilter.Add(TStringList.Create); // lFactionFilter.Add(TStringList.Create); // lEditorIdSubstringFilter.Add(TStringList.Create); // lVoiceFilter.Add(TStringList.Create); // index := slLevelListName.IndexOf(new_level_list_name); // cur_full_name_filter := TStringList(lFullNameFilter[index]); // cur_race_filter := TStringList(lRaceFilter[index]); // cur_faction_filter := TStringList(lFactionFilter[index]); // cur_editorid_substring_filter := TStringList(lEditorIdSubstringFilter[index]); // cur_voice_filter := TStringList(lVoiceFilter[index]); // // cur_full_name_filter.Add(''); // Each line here tells the script to add DW NPCs with these FULL names. Comment out if not using filter. // // cur_race_filter.Add(''); // Each line here tells the script to add DW NPCs with these races (using the race EditorID). Comment out if not using filter. // // cur_faction_filter.Add(''); // Each line here tells the script to add DW NPCs with these factions (using the faction's Editor ID). Comment out if not using filter. // // cur_editorid_substring_filter.Add(''); // Each line here tells the script to add DW NPCs whose EditorID has the given substring. Comment out if not using filter // // Example: Imperial Soldiers and Guards have the same full name and faction, but different in EditorIDs (ie DW_EncSoldier vs DW_EncGuard) // cur_voice_filter.Add('') // Each line here tells the script to add DW NPCs with these VTYP Editor ID references. Comment out if not using filter. //------------------------------------------------------------------------------------------------------------- // Example : DW_WenchSubChar_Vampires_Test // Setups up variables to return a leveled list containing all DW NPCs part of the Vampire Faction //------------------------------------------------------------------------------------------------------------- new_level_list_name := 'DW_WenchSubChar_Vampires_Test'; slLevelListName.Add(new_level_list_name); lFullNameFilter.Add(TStringList.Create); lRaceFilter.Add(TStringList.Create); lFactionFilter.Add(TStringList.Create); lEditorIdSubstringFilter.Add(TStringList.Create); lVoiceFilter.Add(TStringList.Create); index := slLevelListName.IndexOf(new_level_list_name); cur_full_name_filter := TStringList(lFullNameFilter[index]); cur_race_filter := TStringList(lRaceFilter[index]); cur_faction_filter := TStringList(lFactionFilter[index]); cur_editorid_substring_filter := TStringList(lEditorIdSubstringFilter[index]); cur_voice_filter := TStringList(lVoiceFilter[index]); //cur_full_name_filter.Add(''); // No need to filter by FULL name //cur_race_filter.Add('NordRace'); // No need to filter by race //cur_race_filter.Add('BretonRace'); //cur_race_filter.Add('ImperialRace'); //cur_race_filter.Add('RedguardRace'); //cur_race_filter.Add('DarkElfRace'); //cur_race_filter.Add('WoodElfRace'); //cur_race_filter.Add('HighElfRace'); cur_faction_filter.Add('VampireFaction'); // Filter by VampireFaction //cur_faction_filter.Add('BanditFaction'); //cur_faction_filter.Add('ForswornFaction'); //cur_faction_filter.Add('CWImperialFaction'); //cur_faction_filter.Add('CWSonsFaction'); //cur_faction_filter.Add('VigilantOfStendarrFaction'); //cur_editorid_substring_filter.Add(''); // No need to filter by EDID substring //cur_voice_filter.Add('FemaleCommander'); // No need to filter by VTYP //cur_voice_filter.Add('FemaleCommoner'); //cur_voice_filter.Add('FemaleCondescending'); //cur_voice_filter.Add('FemaleCoward'); //cur_voice_filter.Add('FemaleDarkElf'); //cur_voice_filter.Add('FemaleElfHaughty'); //cur_voice_filter.Add('FemaleEvenToned'); //cur_voice_filter.Add('FemaleNord'); //cur_voice_filter.Add('FemaleSultry'); //cur_voice_filter.Add('FemaleYoungEager'); //------------------------------------------------------------------------------------------------------------- // Example : DW_WenchLCharForsworn_Magic_Test // Setups up variables to return a leveled list containing all magical DW NPCs part of the Forsworn Faction //------------------------------------------------------------------------------------------------------------- new_level_list_name := 'DW_WenchLCharForsworn_Magic_Test'; slLevelListName.Add(new_level_list_name); lFullNameFilter.Add(TStringList.Create); lRaceFilter.Add(TStringList.Create); lFactionFilter.Add(TStringList.Create); lEditorIdSubstringFilter.Add(TStringList.Create); lVoiceFilter.Add(TStringList.Create); index := slLevelListName.IndexOf(new_level_list_name); cur_full_name_filter := TStringList(lFullNameFilter[index]); cur_race_filter := TStringList(lRaceFilter[index]); cur_faction_filter := TStringList(lFactionFilter[index]); cur_editorid_substring_filter := TStringList(lEditorIdSubstringFilter[index]); cur_voice_filter := TStringList(lVoiceFilter[index]); cur_full_name_filter.Add('Forsworn Warmage'); // Add only Forsworn Warmages and Shamans cur_full_name_filter.Add('Forsworn Shaman'); //cur_race_filter.Add('NordRace'); // No need to filter by race //cur_race_filter.Add('BretonRace'); //cur_race_filter.Add('ImperialRace'); //cur_race_filter.Add('RedguardRace'); //cur_race_filter.Add('DarkElfRace'); //cur_race_filter.Add('WoodElfRace'); //cur_race_filter.Add('HighElfRace'); //cur_faction_filter.Add('VampireFaction'); // Filter by ForswornFaction //cur_faction_filter.Add('BanditFaction'); cur_faction_filter.Add('ForswornFaction'); //cur_faction_filter.Add('CWImperialFaction'); //cur_faction_filter.Add('CWSonsFaction'); //cur_faction_filter.Add('VigilantOfStendarrFaction'); //cur_editorid_substring_filter.Add(''); // No need to filter by EDID substring //cur_voice_filter.Add('FemaleCommander'); // No need to filter by VTYP //cur_voice_filter.Add('FemaleCommoner'); //cur_voice_filter.Add('FemaleCondescending'); //cur_voice_filter.Add('FemaleCoward'); //cur_voice_filter.Add('FemaleDarkElf'); //cur_voice_filter.Add('FemaleElfHaughty'); //cur_voice_filter.Add('FemaleEvenToned'); //cur_voice_filter.Add('FemaleNord'); //cur_voice_filter.Add('FemaleSultry'); //cur_voice_filter.Add('FemaleYoungEager'); //------------------------------------------------------------------------------------------------------------- // Example : DW_WenchLCharSoldierImperial_Test // Setups up variables to return a leveled list containing all soldier DW NPCs part of the Imperial Faction //------------------------------------------------------------------------------------------------------------- new_level_list_name := 'DW_WenchLCharSoldierImperial_Test'; slLevelListName.Add(new_level_list_name); lFullNameFilter.Add(TStringList.Create); lRaceFilter.Add(TStringList.Create); lFactionFilter.Add(TStringList.Create); lEditorIdSubstringFilter.Add(TStringList.Create); lVoiceFilter.Add(TStringList.Create); index := slLevelListName.IndexOf(new_level_list_name); cur_full_name_filter := TStringList(lFullNameFilter[index]); cur_race_filter := TStringList(lRaceFilter[index]); cur_faction_filter := TStringList(lFactionFilter[index]); cur_editorid_substring_filter := TStringList(lEditorIdSubstringFilter[index]); cur_voice_filter := TStringList(lVoiceFilter[index]); //cur_full_name_filter.Add(''); // No need to filter by FULL name //cur_race_filter.Add('NordRace'); // No need to filter by race //cur_race_filter.Add('BretonRace'); //cur_race_filter.Add('ImperialRace'); //cur_race_filter.Add('RedguardRace'); //cur_race_filter.Add('DarkElfRace'); //cur_race_filter.Add('WoodElfRace'); //cur_race_filter.Add('HighElfRace'); //cur_faction_filter.Add('VampireFaction'); // Filter by CWImperialFaction //cur_faction_filter.Add('BanditFaction'); //cur_faction_filter.Add('ForswornFaction'); cur_faction_filter.Add('CWImperialFaction'); //cur_faction_filter.Add('CWSonsFaction'); //cur_faction_filter.Add('VigilantOfStendarrFaction'); cur_editorid_substring_filter.Add('DW_EncSoldier'); // Filter on editor IDs so you don't get Imperial Guards //cur_voice_filter.Add('FemaleCommander'); // No need to filter by VTYP //cur_voice_filter.Add('FemaleCommoner'); //cur_voice_filter.Add('FemaleCondescending'); //cur_voice_filter.Add('FemaleCoward'); //cur_voice_filter.Add('FemaleDarkElf'); //cur_voice_filter.Add('FemaleElfHaughty'); //cur_voice_filter.Add('FemaleEvenToned'); //cur_voice_filter.Add('FemaleNord'); //cur_voice_filter.Add('FemaleSultry'); //cur_voice_filter.Add('FemaleYoungEager'); //------------------------------------------------------------------------------------------------------------- // Example : DW_WenchSubCharBandit_FemaleNord_magic_Test // Setups up variables to return a leveled list containing all magic nord DW NPCs part of the Bandit Faction //------------------------------------------------------------------------------------------------------------- new_level_list_name := 'DW_WenchSubCharBandit_FemaleNord_magic_Test'; slLevelListName.Add(new_level_list_name); lFullNameFilter.Add(TStringList.Create); lRaceFilter.Add(TStringList.Create); lFactionFilter.Add(TStringList.Create); lEditorIdSubstringFilter.Add(TStringList.Create); lVoiceFilter.Add(TStringList.Create); index := slLevelListName.IndexOf(new_level_list_name); cur_full_name_filter := TStringList(lFullNameFilter[index]); cur_race_filter := TStringList(lRaceFilter[index]); cur_faction_filter := TStringList(lFactionFilter[index]); cur_editorid_substring_filter := TStringList(lEditorIdSubstringFilter[index]); cur_voice_filter := TStringList(lVoiceFilter[index]); cur_full_name_filter.Add('Bandit Mage Marauder'); // Get only mage bandits cur_full_name_filter.Add('Bandit Necromancer'); cur_race_filter.Add('NordRace'); // Filter only nords //cur_race_filter.Add('BretonRace'); //cur_race_filter.Add('ImperialRace'); //cur_race_filter.Add('RedguardRace'); //cur_race_filter.Add('DarkElfRace'); //cur_race_filter.Add('WoodElfRace'); //cur_race_filter.Add('HighElfRace'); //cur_faction_filter.Add('VampireFaction'); // Filter by BanditFaction cur_faction_filter.Add('BanditFaction'); //cur_faction_filter.Add('ForswornFaction'); //cur_faction_filter.Add('CWImperialFaction'); //cur_faction_filter.Add('CWSonsFaction'); //cur_faction_filter.Add('VigilantOfStendarrFaction'); //cur_editorid_substring_filter.Add(''); // No need to filter by EDID substring //cur_voice_filter.Add('FemaleCommander'); // No need to filter by VTYP //cur_voice_filter.Add('FemaleCommoner'); //cur_voice_filter.Add('FemaleCondescending'); //cur_voice_filter.Add('FemaleCoward'); //cur_voice_filter.Add('FemaleDarkElf'); //cur_voice_filter.Add('FemaleElfHaughty'); //cur_voice_filter.Add('FemaleEvenToned'); //cur_voice_filter.Add('FemaleNord'); //cur_voice_filter.Add('FemaleSultry'); //cur_voice_filter.Add('FemaleYoungEager'); //------------------------------------------------------------------------------------------------------------- // Example : DW_WenchSubCharBanditBoss_EventonedTest // Setups up variables to return a leveled list containing bandit bosses with even toned voice type //------------------------------------------------------------------------------------------------------------- new_level_list_name := 'DW_WenchSubCharBanditBoss_EventonedTest'; slLevelListName.Add(new_level_list_name); lFullNameFilter.Add(TStringList.Create); lRaceFilter.Add(TStringList.Create); lFactionFilter.Add(TStringList.Create); lEditorIdSubstringFilter.Add(TStringList.Create); lVoiceFilter.Add(TStringList.Create); index := slLevelListName.IndexOf(new_level_list_name); cur_full_name_filter := TStringList(lFullNameFilter[index]); cur_race_filter := TStringList(lRaceFilter[index]); cur_faction_filter := TStringList(lFactionFilter[index]); cur_editorid_substring_filter := TStringList(lEditorIdSubstringFilter[index]); cur_voice_filter := TStringList(lVoiceFilter[index]); cur_full_name_filter.Add('Bandit Blademaster Marauder'); // Get only mage bandits cur_full_name_filter.Add('Bandit Berserker Marauder'); cur_full_name_filter.Add('Bandit Defender Marauder'); cur_full_name_filter.Add('Bandit Ranger Marauder'); cur_full_name_filter.Add('Bandit Warmage Marauder'); cur_full_name_filter.Add('Bandit Necromancer Marauder'); //cur_race_filter.Add('NordRace'); // Filter only nords //cur_race_filter.Add('BretonRace'); //cur_race_filter.Add('ImperialRace'); //cur_race_filter.Add('RedguardRace'); //cur_race_filter.Add('DarkElfRace'); //cur_race_filter.Add('WoodElfRace'); //cur_race_filter.Add('HighElfRace'); //cur_faction_filter.Add('VampireFaction'); // Filter by BanditFaction cur_faction_filter.Add('BanditFaction'); //cur_faction_filter.Add('ForswornFaction'); //cur_faction_filter.Add('CWImperialFaction'); //cur_faction_filter.Add('CWSonsFaction'); //cur_faction_filter.Add('VigilantOfStendarrFaction'); //cur_editorid_substring_filter.Add(''); // No need to filter by EDID substring //cur_voice_filter.Add('FemaleCommander'); // No need to filter by VTYP //cur_voice_filter.Add('FemaleCommoner'); //cur_voice_filter.Add('FemaleCondescending'); //cur_voice_filter.Add('FemaleCoward'); //cur_voice_filter.Add('FemaleDarkElf'); //cur_voice_filter.Add('FemaleElfHaughty'); cur_voice_filter.Add('FemaleEvenToned'); //cur_voice_filter.Add('FemaleNord'); //cur_voice_filter.Add('FemaleSultry'); //cur_voice_filter.Add('FemaleYoungEager'); end; procedure setupVariablesForVanillaLeveledList; var i, template_index : integer; dw_lvln_to_distribute : string; cur_vanilla_level_lists : TStringList; cur_vanilla_level_lists_count : TList; begin lVanillaLevelList := TList.Create; lVanillaLevelListCount := TList.Create; for i := 0 to slLevelListName.Count-1 do begin lVanillaLevelList.Add(TStringList.Create); lVanillaLevelListCount.Add(TList.Create); end; //------------------------------------------------------------------------------------------------------------- // Template for distributing a dw leveled list created in previous section to vanilla leveled lists //------------------------------------------------------------------------------------------------------------- //dw_lvln_to_distribute := ''; // Name of DW leveled list to distribute. Assumes name was also used in previous section // //template_index := slLevelListName.IndexOf(dw_lvln_to_distribute); // Just Copy //cur_vanilla_level_lists := TStringList(lVanillaLevelList[template_index]); //cur_vanilla_level_lists_count := TList(lVanillaLevelListCount[template_index]); // //cur_vanilla_level_lists.Add(); // For each vanilla leveled list you want to add the DW lvln to, add the vanilla lvln's editorID and an integer count //cur_vanilla_level_lists_count.Add(); // to tell how many times to add the lvln per level number (i.e. if lvln has entries for level 1 and level 9, a count) // // of three tells the script to add the dw lvln ref 6 times (3 times for level 1 and 3 times for level 9). //------------------------------------------------------------------------------------------------------------- // Example 1: Distributes the DW_WenchLCharForsworn_Magic_Test from the previous section to three vanilla // lvlns with the counts of 3, 2, and 4 respectively for each level number //------------------------------------------------------------------------------------------------------------- dw_lvln_to_distribute := 'DW_WenchLCharForsworn_Magic_Test'; template_index := slLevelListName.IndexOf(dw_lvln_to_distribute); cur_vanilla_level_lists := TStringList(lVanillaLevelList[template_index]); cur_vanilla_level_lists_count := TList(lVanillaLevelListCount[template_index]); cur_vanilla_level_lists.Add('LCharDawnguardMelee1HNordF'); cur_vanilla_level_lists_count.Add(3); cur_vanilla_level_lists.Add('LCharWarlockConjurerDarkElfF'); cur_vanilla_level_lists_count.Add(2); cur_vanilla_level_lists.Add('LCharWitchFire'); cur_vanilla_level_lists_count.Add(4); end; //-------------------------------------------------------------------------------------------- // Variation Code //-------------------------------------------------------------------------------------------- // Main loop that iterates through each "variation" group procedure makeWenches; var i : integer; template_str, baseEdid_str, full_str : string; slFacesNPCs : TStringList; begin populateVariationLists; for i := 0 to slRoleTemplateList.Count-1 do begin template_str := slRoleTemplateList[i]; baseEdid_str := slRoleTemplateEditorIdList[i]; full_str := slRoleTemplateNameList[i]; slFacesNPCs := TStringList(lFaceTemplateList[i]); makeWenchesFromTemplate(template_str, baseEdid_str, full_str, slFacesNPCs); end; end; // Handles making each variation record from the template procedure makeWenchesFromTemplate(template_str, baseEdid_str, full_str : string; slFaceNPCs : TStringList); var template_rec, new_rec, iw_rec : IInterface; i : integer; begin template_rec := MainRecordByEditorID(GroupBySignature(dwFile, 'NPC_'), template_str); for i := 0 to slFaceNPCs.Count-1 do begin new_rec := wbCopyElementToFile(template_rec, dwFile, True, True); // Copy as new record iw_rec := MainRecordByEditorID(GroupBySignature(iwFile, 'NPC_'), slFaceNPCs[i]); changeRecordEntries(new_rec, iw_rec, baseEdid_str, full_str); end; end; // Hack to avoid counters for the variation number function getVariationNumber(edid_str : string) : string; var num : integer; begin num := 0; while Assigned(MainRecordByEditorID(GroupBySignature(dwFile, 'NPC_'), edid_str + Format('%.*d', [3, num]))) do begin num := num + 1; end; Result := Format('%.*d', [3, num]); //IntToStr(num); end; // Changes the record entries as seen by the variable s procedure changeRecordEntries(new_rec, iw_rec : IInterface; baseEdid_str, full_str : string;); var s : string; baseEdidWithName : string; begin // Change FULL name s := 'FULL'; SetElementEditValues(new_rec, s, full_str); // Change Editor ID: baseEdid + '_' + race + variation_number s := 'EDID'; baseEdidWithName := baseEdid_str + '_' + EditorID(LinksTo(ElementBySignature(iw_rec, 'RNAM'))); SetElementEditValues(new_rec, s, baseEdidWithName + getVariationNumber(baseEdidWithName)); // Adjust Template Flags to inherit Traits and Attack Data s := 'ACBS\Template Flags'; SetElementNativeValues(new_rec, s, $0801); // Set template to the Immersive Wench reference s := 'TPLT'; SetElementEditValues(new_rec, s, Name(iw_rec)); // Should be handled by template inheritance but would bug me otherwise s := 'RNAM'; // Race SetElementEditValues(new_rec, s, GetElementEditValues(iw_rec, s)); s := 'VTCK'; // Voice SetElementEditValues(new_rec, s, GetElementEditValues(iw_rec, s)); end; procedure populateVariationLists; var iw_npc_list, full_name_filter, race_filter, faction_filter, editorid_substring_filter, voice_filter : TStringList; i : integer; lvln_name : string; is_vampire_keyword_excluded : boolean; begin for i := 0 to slRoleTemplateList.Count-1 do begin iw_npc_list := TStringList(lFaceTemplateList[i]); full_name_filter := TStringList(lVarFullNameFilter[i]); race_filter := TStringList(lVarRaceFilter[i]); faction_filter := TStringList(lVarFactionFilter[i]); editorid_substring_filter := TStringList(lVarEditorIdSubstringFilter[i]); voice_filter := TStringList(lVarVoiceFilter[i]); is_vampire_keyword_excluded := Boolean(lVampireKeywordExclusion[i]); populateVariationListsFromFilters(iw_npc_list, full_name_filter, race_filter, faction_filter, editorid_substring_filter, voice_filter, is_vampire_keyword_excluded); end; end; function checkVampireKeyword(npc : IInterface): boolean; var keyword_group : IInterface; i : integer; begin keyword_group := ElementByPath(npc, 'KWDA'); Result := False; for i := 0 to ElementCount(keyword_group)-1 do begin if EditorID(LinksTo(ElementByIndex(keyword_group, i))) = 'Vampire' then begin Result := True; Exit; end; end; end; procedure populateVariationListsFromFilters(iw_npc_list, full_name_filter, race_filter, faction_filter, editorid_substring_filter, voice_filter : TStringList; is_vampire_keyword_excluded : boolean); var lvln_rec : IInterface; npcs, npc : IInterface; i : integer; begin npcs := GroupBySignature(iwFile, 'NPC_'); for i := 0 to Pred(ElementCount(npcs)) do begin npc := ElementByIndex(npcs, i); // Ignore npcs without FULL names (likely a template record) if not Assigned(ElementBySignature(npc, 'FULL')) then Continue; if is_vampire_keyword_excluded and checkVampireKeyword(npc) then Continue; // apply filters if not isIncludedByFullFilter(npc, full_name_filter) then Continue; if not isIncludedBySignatureFilter(npc, race_filter, 'RNAM') then Continue; if not isIncludedByFactionFilter(npc, faction_filter) then Continue; if not isIncludedBySubstringFilter(npc, editorid_substring_filter) then Continue; if not isIncludedBySignatureFilter(npc, voice_filter, 'VTCK') then Continue; iw_npc_list.Add(EditorID(npc)); end; end; //-------------------------------------------------------------------------------------------- // Leveled List Code //-------------------------------------------------------------------------------------------- // Main loop that iterates over every leveled list group procedure makeDwLevedList; var full_name_filter, race_filter, faction_filter, editorid_substring_filter, voice_filter : TStringList; i : integer; lvln_name : string; begin for i := 0 to slLevelListName.Count-1 do begin lvln_name := slLevelListName[i]; full_name_filter := TStringList(lFullNameFilter[i]); race_filter := TStringList(lRaceFilter[i]); faction_filter := TStringList(lFactionFilter[i]); editorid_substring_filter := TStringList(lEditorIdSubstringFilter[i]); voice_filter := TStringList(lVoiceFilter[i]); makeLeveledListFromFilters(lvln_name, full_name_filter, race_filter, faction_filter, editorid_substring_filter, voice_filter); end; end; function isIncludedByFullFilter(npc : IInterface; filter : TStringList) : boolean; var i : integer; isGood : boolean; begin if filter.Count = 0 then begin Result := True; Exit; end; isGood := False; //AddMessage('1Next: ' + EditorID(npc)); for i := 0 to filter.Count-1 do begin //AddMessage(EditorID(npc) + ' | ' + EditorID(LinksTo(ElementBySignature(npc, signature))) + ' | ' + filter[i]); if GetElementEditValues(npc, 'FULL') = filter[i] then isGood := True; end; Result := isGood; end; function isIncludedBySignatureFilter(npc : IInterface; filter : TStringList; signature : string) : boolean; var i : integer; isGood : boolean; begin if filter.Count = 0 then begin Result := True; Exit; end; isGood := False; //AddMessage('1Next: ' + EditorID(npc)); for i := 0 to filter.Count-1 do begin //AddMessage(EditorID(npc) + ' | ' + EditorID(LinksTo(ElementBySignature(npc, 'RNAM'))) + ' | ' + filter[i]); if EditorID(LinksTo(ElementBySignature(npc, signature))) = filter[i] then isGood := True; end; Result := isGood; end; function isIncludedByFactionFilter(npc : IInterface; filter : TStringList) : boolean; var i, j : integer; isGood : boolean; factions, faction : IInterface; begin if filter.Count = 0 then begin Result := True; Exit; end; isGood := False; factions := ElementByName(npc, 'Factions'); //AddMessage('2Next: ' + EditorID(npc)); for i := 0 to filter.Count-1 do begin //AddMessage('Go'); for j := 0 to Pred(ElementCount(factions)) do begin faction := ElementByIndex(factions, j); faction := LinksTo(ElementByPath(faction, 'Faction')); //AddMessage('>>' + EditorID(faction)); if EditorID(faction) = filter[i] then begin //AddMessage('>>>> it''s good: ' + EditorID + ' | ' + filter[i]); isGood := True; end; end; end; Result := isGood; end; function isIncludedBySubstringFilter(npc : IInterface; filter : TStringList) : boolean; var i : integer; isGood : boolean; begin if filter.Count = 0 then begin Result := True; Exit; end; isGood := False; //AddMessage('3Next: ' + EditorID(npc)); for i := 0 to filter.Count-1 do begin //AddMessage(EditorID(npc) + ' | ' + filter[i] + ' | ' + IntToStr(pos(filter[i], EditorID(npc)))); if pos(filter[i], EditorID(npc)) <> 0 then begin isGood := True; end; end; Result := isGood; end; procedure makeLeveledListFromFilters(lvln_name : string; full_name_filter, race_filter, faction_filter, editorid_substring_filter, voice_filter : TStringList); var lvln_rec : IInterface; npcs, npc : IInterface; i : integer; begin lvln_rec := createLeveledList(dwFile, lvln_name); SetElementNativeValues(lvln_rec, 'LVLF', $3); npcs := GroupBySignature(dwFile, 'NPC_'); for i := 0 to Pred(ElementCount(npcs)) do begin npc := ElementByIndex(npcs, i); // Ignore npcs without FULL names (likely a template record) if not Assigned(ElementBySignature(npc, 'FULL')) then Continue; // apply filters if not isIncludedByFullFilter(npc, full_name_filter) then Continue; if not isIncludedBySignatureFilter(npc, race_filter, 'RNAM') then Continue; if not isIncludedByFactionFilter(npc, faction_filter) then Continue; if not isIncludedBySubstringFilter(npc, editorid_substring_filter) then Continue; if not isIncludedBySignatureFilter(npc, voice_filter, 'VTCK') then Continue; AddLeveledListEntry(lvln_rec, 1, npc, 1); end; end; // Creates a blank leveled npc record with the given name function createLeveledList(tar_file : IInterface; tar_filename : string): IInterface; var new_rec : IInterface; begin if not Assigned(tar_file) then begin AddMessage('createLevedList: Warning! Null file provided.'); Exit; end; // Create LVLN Group Signature if group isn't in file if not Assigned(GroupBySignature(tar_file, 'LVLN')) then begin Add(tar_file, 'LVLN', True); if not Assigned(GroupBySignature(tar_file, 'LVLN')) then begin AddMessage('createLevedList: Warning! LVLN group was not created.'); Exit; end; end; // Creates new LVLN in LVLN Group new_rec := Add(GroupBySignature(tar_file, 'LVLN'), 'LVLN', True); if not Assigned(new_rec) then begin AddMessage('createLevedList: Warning! LVLN record not created.'); Exit; end; SetEditorID(new_rec, tar_filename); RemoveElement(new_rec, 'Leveled List Entries'); Result := new_rec; end; //--------------------------------------------------------------------------------------- // https://www.reddit.com/r/skyrimmods/comments/5jkfz5/tes5edit_script_for_adding_to_leveled_lists/ function NewArrayElement(rec: IInterface; path: String): IInterface; var a: IInterface; begin a := ElementByPath(rec, path); if Assigned(a) then begin Result := ElementAssign(a, HighInteger, nil, false); end else begin a := Add(rec, path, true); Result := ElementByIndex(a, 0); end; end; procedure AddLeveledListEntry(rec: IInterface; level: Integer; reference: IInterface; count: Integer); var entry: IInterface; begin if not Assigned(rec) then begin AddMessage('AddLeveledListEntry: input "rec" not assigned.'); Exit; end; if not Assigned(reference) then begin AddMessage('AddLeveledListEntry: input "reference" not assigned.'); Exit; end; entry := NewArrayElement(rec, 'Leveled List Entries'); SetElementEditValues(entry, 'LVLO\Level', level); SetElementEditValues(entry, 'LVLO\Reference', IntToHex(GetLoadOrderFormID(reference), 8)); SetElementEditValues(entry, 'LVLO\Count', count); end; //-------------------------------------------------------------------------------------------- // Vanilla Leveled List Code //-------------------------------------------------------------------------------------------- // Main loop that iterates through each "variation" group procedure addDwLeveledListToVanilla; var i : integer; lvln_lists : TStringList; lvln_to_distribute : string; lvln_cnts : TList; begin for i := 0 to slLevelListName.Count-1 do begin lvln_to_distribute := slLevelListName[i]; lvln_lists := TStringList(lVanillaLevelList[i]); lvln_cnts := TList(lVanillaLevelListCount[i]); AddDwLevedListToVanillaLeveledList(lvln_to_distribute, lvln_lists, lvln_cnts); end; end; function getSignatureMasterRecordFromLoadedFiles(record_name, signature : string) : IInterface; var i : integer; f, cur_lvln : IInterface; s : string; begin for i := 0 to FileCount - 1 do begin f := FileByIndex(i); cur_lvln := MainRecordByEditorID(GroupBySignature(f, signature), record_name); if Assigned(cur_lvln) then begin Result := MasterOrSelf(cur_lvln); Exit; end; end; end; function getTargetLeveledListOverride(elem : IInterface): IInterface; var i : integer; cur_ovr, next_ovr, m : IInterface; s : string; begin if not Assigned(elem) then begin AddMessage('getTargetLeveledListOverride: input "elem" not assigned.'); Exit; end; m := MasterOrSelf(elem); cur_ovr := m; //AddMessage(EditorID(elem)); for i := 0 to Pred(OverrideCount(m)) do begin next_ovr := OverrideByIndex(m, i); s := Name(GetFile(next_ovr)); if SameText(GetFileName(GetFile(next_ovr)), 'deadly wenches.esp') then Break; cur_ovr := next_ovr; end; Result := cur_ovr; end; // Handles making each variation record from the template procedure AddDwLevedListToVanillaLeveledList(lvln_to_distribute : string; lvln_lists : TStringList; lvln_cnts : TList); var target_lvln, lvln_rec, m_lvln_rec, tar_lvln_rec : IInterface; lvln_ents, lvln_ent : IInterface; i, j, k, level_num : integer; slLevels : TStringList; begin // Get record of lvln to distribute to vanilla lvlns target_lvln := MainRecordByEditorID(GroupBySignature(dwFile, 'LVLN'), lvln_to_distribute); // For each vanilla lvln in the list, add the target lvln with a given count for each level number contained by the vanilla lvln entries for i := 0 to lvln_lists.Count-1 do begin lvln_rec := getSignatureMasterRecordFromLoadedFiles(lvln_lists[i], 'LVLN'); m_lvln_rec := MasterOrSelf(lvln_rec); // If there's not already an override in DW, add one if not SameText(GetFileName(GetFile(m_lvln_rec)), 'deadly wenches.esp') then begin m_lvln_rec := wbCopyElementToFile(m_lvln_rec, dwFile, False, True); end; tar_lvln_rec := getTargetLeveledListOverride(m_lvln_rec); // Get winning override before DW // Extract the level numbers used in lvln (i.e. three entries at level 1, three entries at level 9, etc...) slLevels := TStringList.Create; lvln_ents := ElementByName(tar_lvln_rec, 'Leveled List Entries'); for j := 0 to Pred(ElementCount(lvln_ents)) do begin lvln_ent := ElementByIndex(lvln_ents, j); level_num := GetElementEditValues(lvln_ent, 'LVLO\Level'); if slLevels.IndexOf(level_num) = -1 then slLevels.Add(level_num) end; // For each of the level numbers, add a new lvln entry containing a ref to the target lvln for the user-specified number of times. for j := 0 to slLevels.Count-1 do begin for k := 0 to Integer(lvln_cnts[i])-1 do begin AddLeveledListEntry(m_lvln_rec, StrToInt(slLevels[j]), target_lvln, 1); end; end; slLevels.Free; // end; end; //--------------------------------------------------------------------------------------- // Global Variables //--------------------------------------------------------------------------------------- procedure freeGlobalVariables; var i : integer; begin for i := 0 to slLevelListName.Count-1 do begin TStringList(lFullNameFilter[i]).Free; TStringList(lRaceFilter[i]).Free; TStringList(lFactionFilter[i]).Free; TStringList(lEditorIdSubstringFilter[i]).Free; TStringList(lVanillaLevelList[i]).Free; TStringList(lVoiceFilter[i]).Free; TList(lVanillaLevelListCount[i]).Free; end; lFullNameFilter.Free; lRaceFilter.Free; lFactionFilter.Free; lEditorIdSubstringFilter.Free; lVanillaLevelList.Free; lVanillaLevelListCount.Free; lVoiceFilter.Free; for i := 0 to slRoleTemplateList.Count-1 do begin TStringList(lFaceTemplateList[i]).Free; TStringList(lVarFullNameFilter[i]).Free; TStringList(lVarRaceFilter[i]).Free; TStringList(lVarFactionFilter[i]).Free; TStringList(lVarEditorIdSubstringFilter[i]).Free; TStringList(lVarVoiceFilter[i]).Free; end; lFaceTemplateList.Free; lVarFullNameFilter.Free; lVarRaceFilter.Free; lVarFactionFilter.Free; lVarEditorIdSubstringFilter.Free; lVarVoiceFilter.Free; slRoleTemplateList.Free; slRoleTemplateNameList.Free; slLevelListName.Free; end; function getFileObject(filename : string): IInterface; var i : integer; f : IInterface; s : string; begin for i := 0 to FileCount - 1 do begin f := FileByIndex(i); s := GetFileName(f); if SameText(s, filename) then begin Result := f; Exit; end; end; end; procedure setupGlobalVariables; var i : integer; template_index : integer; cur_template_faces : TStringList; s : string; begin skyrimFile := getFileObject('Skyrim.esm'); dwFile := getFileObject('Deadly Wenches.esp'); iwFile := GetFileObject('Immersive Wenches.esp'); end; //--------------------------------------------------------------------------------------- // Required Tes5Edit Script Functions //--------------------------------------------------------------------------------------- // Called before processing // You can remove it if script doesn't require initialization code function Initialize: integer; begin AddMessage('setupGlobalVariables...'); setupGlobalVariables; AddMessage('setupVariablesForVariations...'); setupVariablesForVariations; AddMessage('setupVariablesForLeveledList...'); setupVariablesForLeveledList; AddMessage('setupVariablesForVanillaLeveledList...'); setupVariablesForVanillaLeveledList; AddMessage('makeWenches...'); makeWenches; AddMessage('makeDwLevedList...'); makeDwLevedList; AddMessage('addDwLeveledListToVanilla...'); addDwLeveledListToVanilla; AddMessage('done...'); //replaceClass; Result := 0; end; // called for every record selected in xEdit function Process(e: IInterface): integer; begin Result := 0; // comment this out if you don't want those messages //AddMessage('Processing: ' + FullPath(e)); // processing code goes here end; // Called after processing // You can remove it if script doesn't require finalization code function Finalize: integer; begin freeGlobalVariables; Result := 0; end; end.
45.787196
200
0.634409
c3336eb0124f5734d865e1dafda3227ba9caafff
24,403
pas
Pascal
Libraries/SimpleServer/dwsWebEnvironment.pas
caxsf/dwscript
410a0416db3d4baf984e041b9cbf5707f2f8895f
[ "Condor-1.1" ]
null
null
null
Libraries/SimpleServer/dwsWebEnvironment.pas
caxsf/dwscript
410a0416db3d4baf984e041b9cbf5707f2f8895f
[ "Condor-1.1" ]
null
null
null
Libraries/SimpleServer/dwsWebEnvironment.pas
caxsf/dwscript
410a0416db3d4baf984e041b9cbf5707f2f8895f
[ "Condor-1.1" ]
null
null
null
{**********************************************************************} { } { "The contents of this file are subject to the Mozilla Public } { License Version 1.1 (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.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an } { "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express } { or implied. See the License for the specific language } { governing rights and limitations under the License. } { } { Copyright Creative IT. } { Current maintainer: Eric Grange } { } {**********************************************************************} unit dwsWebEnvironment; interface uses Classes, SysUtils, StrUtils, DateUtils, SynCrtSock, SynCommons, dwsExprs, dwsUtils, dwsWebUtils, dwsWebServerUtils, dwsWebServerHelpers, dwsSymbols, dwsExprList; type TWebRequestAuthentication = ( wraNone, wraFailed, wraBasic, wraDigest, wraNTLM, wraNegotiate, wraKerberos, wraAuthorization ); TWebRequestAuthentications = set of TWebRequestAuthentication; TWebRequestMethodVerb = ( wrmvUnknown, wrmvOPTIONS, wrmvGET, wrmvHEAD, wrmvPOST, wrmvPUT, wrmvDELETE, wrmvTRACE, wrmvCONNECT, wrmvTRACK, wrmvMOVE, wrmvCOPY, wrmvPROPFIND, wrmvPROPPATCH, wrmvMKCOL, wrmvLOCK, wrmvUNLOCK, wrmvSEARCH ); TWebRequestMethodVerbs = set of TWebRequestMethodVerb; TWebServerEventData = array of RawByteString; TWebRequest = class private FCookies : TStrings; FQueryFields : TStrings; FContentFields : TStrings; FCustom : TObject; FID : Int64; FAppUser : String; protected FPathInfo : String; FQueryString : String; function GetHeaders : TStrings; virtual; abstract; function GetCookies : TStrings; function GetQueryFields : TStrings; function GetContentFields : TStrings; function GetUserAgent : String; function GetAuthentication : TWebRequestAuthentication; virtual; function GetAuthenticatedUser : String; virtual; function PrepareCookies : TStrings; virtual; function PrepareQueryFields : TStrings; virtual; function PrepareContentFields : TStrings; virtual; public destructor Destroy; override; procedure ResetCookies; inline; procedure ResetQueryFields; inline; procedure ResetContentFields; inline; procedure ResetFields; inline; function Header(const headerName : String) : String; function RemoteIP : String; virtual; abstract; function RawURL : String; virtual; abstract; function URL : String; virtual; abstract; function FullURL : String; virtual; abstract; function Method : String; virtual; abstract; function MethodVerb : TWebRequestMethodVerb; virtual; abstract; function Security : String; virtual; abstract; function Secure : Boolean; virtual; abstract; function Host : String; virtual; function ContentLength : Integer; virtual; abstract; function ContentData : RawByteString; virtual; abstract; function ContentType : RawByteString; virtual; abstract; property PathInfo : String read FPathInfo write FPathInfo; property QueryString : String read FQueryString write FQueryString; property UserAgent : String read GetUserAgent; property Headers : TStrings read GetHeaders; property Cookies : TStrings read GetCookies; property QueryFields : TStrings read GetQueryFields; property ContentFields : TStrings read GetContentFields; function HasQueryField(const name : String) : Boolean; function HasContentField(const name : String) : Boolean; function IfModifiedSince : TDateTime; property Authentication : TWebRequestAuthentication read GetAuthentication; property AuthenticatedUser : String read GetAuthenticatedUser; // custom request ID property ID : Int64 read FID write FID; // custom Application User property AppUser : String read FAppUser write FAppUser; // custom object field, freed with the request property Custom : TObject read FCustom write FCustom; end; TWebResponseCookieFlag = (wrcfSecure = 1, wrcfHttpOnly = 2); TWebResponseCookieSameSite = (wrcssUnspecified = 0, wrcssStrict = 1, wrcssLax = 2); TWebResponseCookie = class (TRefCountedObject) public Name : String; Value : String; ExpiresGMT : TDateTime; Domain : String; Path : String; MaxAge : Integer; Flags : Integer; SameSite : TWebResponseCookieSameSite; procedure WriteStringLn(dest : TWriteOnlyBlockStream); end; TWebResponseCookies = class (TObjectList<TWebResponseCookie>) public function AddCookie(const name : String) : TWebResponseCookie; end; TWebResponseHint = (shStatic, shCompression); TWebResponseHints = set of TWebResponseHint; TWebResponse = class private FStatusCode : Integer; FContentData : RawByteString; FContentType : RawByteString; FContentEncoding : RawByteString; FHeaders : TStrings; FCookies : TWebResponseCookies; // lazy initialization FProcessingTime : Integer; FHints : TWebResponseHints; protected procedure SetContentText(const textType : RawByteString; const text : String); procedure SetContentJSON(const json : String); procedure SetLastModified(v : TDateTime); function GetCookies : TWebResponseCookies; function GetCompression : Boolean; inline; procedure SetCompression(v : Boolean); public constructor Create; destructor Destroy; override; procedure Clear; virtual; function HasHeaders : Boolean; inline; function HasCookies : Boolean; inline; function CompiledHeaders : RawByteString; property StatusCode : Integer read FStatusCode write FStatusCode; property ContentText[const textType : RawByteString] : String write SetContentText; property ContentJSON : String write SetContentJSON; property ContentData : RawByteString read FContentData write FContentData; property ContentType : RawByteString read FContentType write FContentType; property ContentEncoding : RawByteString read FContentEncoding write FContentEncoding; property Headers : TStrings read FHeaders; property Cookies : TWebResponseCookies read GetCookies; property Compression : Boolean read GetCompression write SetCompression; property LastModified : TDateTime write SetLastModified; property Hints : TWebResponseHints read FHints write FHints; // optional, informative, time it took to process the response in microseconds property ProcessingTime : Integer read FProcessingTime write FProcessingTime; end; IWebEnvironment = interface ['{797FDC50-0643-4290-88D1-8BD3C0D7C303}'] function GetWebRequest : TWebRequest; function GetWebResponse : TWebResponse; property WebRequest : TWebRequest read GetWebRequest; property WebResponse : TWebResponse read GetWebResponse; end; TWebEnvironment = class (TInterfacedSelfObject, IdwsEnvironment, IWebEnvironment) protected function GetWebRequest : TWebRequest; function GetWebResponse : TWebResponse; public WebRequest : TWebRequest; WebResponse : TWebResponse; end; TWebEnvironmentHelper = class helper for TProgramInfo function WebEnvironment : IWebEnvironment; inline; function WebRequest : TWebRequest; inline; function WebResponse : TWebResponse; inline; end; TWebEnvironmentRecordHelper = record helper for TExprBaseListExec function WebEnvironment : IWebEnvironment; inline; function WebRequest : TWebRequest; inline; function WebResponse : TWebResponse; inline; end; TWebStaticCacheEntry = class (TInterfacedSelfObject) private FStatusCode : Integer; FContentType : RawByteString; FContentData : RawByteString; FETag : String; FCacheControl : String; public constructor Create(fromResponse : TWebResponse); procedure HandleStatic(request : TWebRequest; response : TWebResponse); property StatusCode : Integer read FStatusCode write FStatusCode; property ContentData : RawByteString read FContentData write FContentData; property ContentType : RawByteString read FContentType write FContentType; property ETag : String read FETag write FETag; property CacheControl : String read FCacheControl write FCacheControl; function Size : Integer; end; TEmptyWebRequest = class(TWebRequest) protected FMethod : String; FHeaders : TStringList; function GetHeaders : TStrings; override; public destructor Destroy; override; function RemoteIP : String; override; function RawURL : String; override; function URL : String; override; function FullURL : String; override; function Method : String; override; function MethodVerb : TWebRequestMethodVerb; override; function Security : String; override; function Secure : Boolean; override; function Host : String; override; function ContentLength : Integer; override; function ContentData : RawByteString; override; function ContentType : RawByteString; override; property DirectMethod : String read FMethod write FMethod; end; const cWebRequestAuthenticationToString : array [TWebRequestAuthentication] of String = ( 'None', 'Failed', 'Basic', 'Digest', 'NTLM', 'Negotiate', 'Kerberos', 'Header' ); const cWebRequestMethodVerbs : array [TWebRequestMethodVerb] of String = ( '?', 'OPTIONS', 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'TRACE', 'CONNECT', 'TRACK', 'MOVE', 'COPY', 'PROPFIND', 'PROPPATCH', 'MKCOL', 'LOCK', 'UNLOCK', 'SEARCH' ); cHTMTL_UTF8_CONTENT_TYPE = 'text/html; charset=utf-8'; implementation // ------------------ // ------------------ TWebEnvironmentHelper ------------------ // ------------------ // WebEnvironment // function TWebEnvironmentHelper.WebEnvironment : IWebEnvironment; begin Result := (Execution.Environment as IWebEnvironment); end; // WebRequest // function TWebEnvironmentHelper.WebRequest : TWebRequest; begin Result := (Execution.Environment as IWebEnvironment).WebRequest; end; // WebResponse // function TWebEnvironmentHelper.WebResponse : TWebResponse; begin Result := (Execution.Environment as IWebEnvironment).WebResponse; end; // ------------------ // ------------------ TWebEnvironmentRecordHelper ------------------ // ------------------ // WebEnvironment // function TWebEnvironmentRecordHelper.WebEnvironment : IWebEnvironment; begin Result := (Exec.Environment as IWebEnvironment); end; // WebRequest // function TWebEnvironmentRecordHelper.WebRequest : TWebRequest; begin Result := (Exec.Environment as IWebEnvironment).WebRequest; end; // WebResponse // function TWebEnvironmentRecordHelper.WebResponse : TWebResponse; begin Result := (Exec.Environment as IWebEnvironment).WebResponse; end; // ------------------ // ------------------ TWebRequest ------------------ // ------------------ // Destroy // destructor TWebRequest.Destroy; begin FQueryFields.Free; FContentFields.Free; FCookies.Free; FCustom.Free; inherited; end; // ResetCookies // procedure TWebRequest.ResetCookies; begin if FCookies<>nil then begin FCookies.Free; FCookies:=nil; end; end; // ResetQueryFields // procedure TWebRequest.ResetQueryFields; begin if FQueryFields<>nil then begin FQueryFields.Free; FQueryFields:=nil; end; end; // ResetContentFields // procedure TWebRequest.ResetContentFields; begin if FContentFields<>nil then begin FContentFields.Free; FContentFields:=nil; end; end; // ResetFields // procedure TWebRequest.ResetFields; begin ResetQueryFields; ResetContentFields; end; // PrepareCookies // function TWebRequest.PrepareCookies : TStrings; procedure AddCookie(const name, value : String); var i : Integer; begin i := Result.IndexOfName(name); if i >= 0 then begin if value <> '' then Result[i] := name + '=' + value; end else begin Result.Add(name + '=' + value); end; end; var base, next, p : Integer; cookieField : String; begin Result:=TFastCompareTextList.Create; cookieField:=Header('Cookie'); base:=1; while True do begin p:=StrUtils.PosEx('=', cookieField, base); next:=StrUtils.PosEx(';', cookieField, p); if (p>base) and (next>p) then begin AddCookie(SysUtils.Trim(Copy(cookieField, base, p-base)), Copy(cookieField, p+1, pred(next-p))); base:=next+1; end else Break; end; if (p>base) and (base<Length(cookieField)) then AddCookie(SysUtils.Trim(Copy(cookieField, base, p-base)), Copy(cookieField, p+1)); end; // PrepareQueryFields // function TWebRequest.PrepareQueryFields : TStrings; begin Result:=TStringList.Create; WebUtils.ParseURLEncoded(ScriptStringToRawByteString(QueryString), Result); end; // PrepareContentFields // function TWebRequest.PrepareContentFields : TStrings; begin Result:=TStringList.Create; if StrBeginsWithA(ContentType, 'application/x-www-form-urlencoded') then begin // TODO: handle case where encoding isn't utf-8 WebUtils.ParseURLEncoded(ContentData, Result); end; end; // Header // function TWebRequest.Header(const headerName : String) : String; begin Result:=Headers.Values[headerName]; end; // Host // function TWebRequest.Host : String; begin Result:=Headers.Values['Host']; end; // GetCookies // function TWebRequest.GetCookies : TStrings; begin if FCookies=nil then FCookies:=PrepareCookies; Result:=FCookies; end; // GetQueryFields // function TWebRequest.GetQueryFields : TStrings; begin if FQueryFields=nil then FQueryFields:=PrepareQueryFields; Result:=FQueryFields; end; // GetContentFields // function TWebRequest.GetContentFields : TStrings; begin if FContentFields=nil then FContentFields:=PrepareContentFields; Result:=FContentFields; end; // HasQueryField // function TWebRequest.HasQueryField(const name : String) : Boolean; begin Result:=WebUtils.HasFieldName(QueryFields, name); end; // HasContentField // function TWebRequest.HasContentField(const name : String) : Boolean; begin Result:=WebUtils.HasFieldName(ContentFields, name); end; // IfModifiedSince // function TWebRequest.IfModifiedSince : TDateTime; var v : String; begin v:=Header('If-Modified-Since'); if v<>'' then Result:=WebUtils.RFC822ToDateTime(v) else Result:=0; end; // GetUserAgent // function TWebRequest.GetUserAgent : String; begin Result:=Header('User-Agent'); end; // GetAuthentication // function TWebRequest.GetAuthentication : TWebRequestAuthentication; begin Result:=wraNone; end; // GetAuthenticatedUser // function TWebRequest.GetAuthenticatedUser : String; begin Result:=''; end; // ------------------ // ------------------ TWebEnvironment ------------------ // ------------------ // GetWebRequest // function TWebEnvironment.GetWebRequest : TWebRequest; begin Result:=WebRequest; end; // GetWebResponse // function TWebEnvironment.GetWebResponse : TWebResponse; begin Result:=WebResponse; end; // ------------------ // ------------------ TWebResponse ------------------ // ------------------ // Create // constructor TWebResponse.Create; begin inherited; FHeaders:=TFastCompareStringList.Create; FHints:=[shCompression]; end; // Destroy // destructor TWebResponse.Destroy; begin FHeaders.Free; FCookies.Free; inherited; end; // Clear // procedure TWebResponse.Clear; begin FStatusCode:=200; FContentType:=cHTMTL_UTF8_CONTENT_TYPE; FContentData:=''; FContentEncoding:=''; FHeaders.Clear; if FCookies<>nil then FCookies.Clear; FHints:=[shCompression]; end; // HasCookies // function TWebResponse.HasCookies : Boolean; begin Result:=(FCookies<>nil) and (FCookies.Count>0); end; // HasHeaders // function TWebResponse.HasHeaders : Boolean; begin Result:=(FHeaders.Count>0) or HasCookies; end; // CompiledHeaders // function TWebResponse.CompiledHeaders : RawByteString; var i, p : Integer; wobs : TWriteOnlyBlockStream; buf : String; begin wobs:=TWriteOnlyBlockStream.AllocFromPool; try for i:=0 to Headers.Count-1 do begin buf:=FHeaders[i]; p:=Pos('=', buf); wobs.WriteSubString(buf, 1, p-1); wobs.WriteString(': '); wobs.WriteSubString(buf, p+1); wobs.WriteCRLF; end; if HasCookies then for i:=0 to Cookies.Count-1 do FCookies[i].WriteStringLn(wobs); Result:=wobs.ToUTF8String; finally wobs.ReturnToPool; end; end; // SetLastModified // procedure TWebResponse.SetLastModified(v : TDateTime); begin Headers.Add('Last-Modified='+WebUtils.DateTimeToRFC822(v)); end; // SetContentText // procedure TWebResponse.SetContentText(const textType : RawByteString; const text : String); begin ContentType:='text/'+textType+'; charset=utf-8'; ContentData:=StringToUTF8(text); end; // SetContentJSON // procedure TWebResponse.SetContentJSON(const json : String); begin ContentType:='application/json'; ContentData:=StringToUTF8(json); end; // GetCookies // function TWebResponse.GetCookies : TWebResponseCookies; begin if FCookies=nil then FCookies:=TWebResponseCookies.Create; Result:=FCookies; end; // GetCompression // function TWebResponse.GetCompression : Boolean; begin Result:=(shCompression in FHints); end; // SetCompression // procedure TWebResponse.SetCompression(v : Boolean); begin if v then Include(FHints, shCompression) else Exclude(FHints, shCompression); end; // ------------------ // ------------------ TWebResponseCookies ------------------ // ------------------ // WriteStringLn // procedure TWebResponseCookie.WriteStringLn(dest : TWriteOnlyBlockStream); const cMonths : array [1..12] of String = ( 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ); cWeekDays : array [1..7] of String = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ); var y, m, d : Word; h, n, s, z : Word; begin dest.WriteString('Set-Cookie: '); dest.WriteString(Name); dest.WriteChar('='); dest.WriteString(Value); if ExpiresGMT<>0 then begin dest.WriteString('; Expires='); if ExpiresGMT<0 then dest.WriteString('Sat, 01 Jan 2000 00:00:01 GMT') else begin dest.WriteString(cWeekDays[DayOfTheWeek(ExpiresGMT)]); DecodeDateTime(ExpiresGMT, y, m, d, h, n, s, z); dest.WriteString(Format(', %.02d %s %d %.02d:%.02d:%.02d GMT', [d, cMonths[m], y, h, n, s])); end; end; if MaxAge>0 then begin dest.WriteString('; Max-Age='); dest.WriteString(MaxAge); end; if Path<>'' then begin dest.WriteString('; Path='); dest.WriteString(Path); end; if Domain<>'' then begin dest.WriteString('; Domain='); dest.WriteString(Domain); end; if (Flags and Ord(wrcfSecure))<>0 then dest.WriteString('; Secure'); if (Flags and Ord(wrcfHttpOnly))<>0 then dest.WriteString('; HttpOnly'); case SameSite of wrcssStrict : dest.WriteString('; SameSite=Strict'); wrcssLax : dest.WriteString('; SameSite=Lax'); end; dest.WriteCRLF; end; // ------------------ // ------------------ TWebResponseCookie ------------------ // ------------------ // AddCookie // function TWebResponseCookies.AddCookie(const name : String) : TWebResponseCookie; begin Result:=TWebResponseCookie.Create; Result.Name:=name; Add(Result); end; // ------------------ // ------------------ TWebStaticCacheEntry ------------------ // ------------------ // Create // constructor TWebStaticCacheEntry.Create(fromResponse : TWebResponse); begin inherited Create; FContentType:=fromResponse.ContentType; FContentData:=fromResponse.ContentData; FStatusCode:=fromResponse.StatusCode; FCacheControl:=fromResponse.Headers.Values['Cache-Control']; FETag:=fromResponse.Headers.Values['ETag']; if FETag='' then begin FEtag:=WebServerUtils.ETag([FStatusCode, FCacheControl, FContentType, FContentData]); fromResponse.Headers.Values['ETag']:=FETag; end; end; // HandleStatic // procedure TWebStaticCacheEntry.HandleStatic(request : TWebRequest; response : TWebResponse); begin if request.Header('If-None-Match') = FETag then begin response.StatusCode := 304; Exit; end; response.Headers.Values['ETag'] := FETag; if FCacheControl<>'' then response.Headers.Values['Cache-Control'] := FCacheControl; response.ContentType := FContentType; response.ContentData := FContentData; response.StatusCode := FStatusCode; end; // Size // function TWebStaticCacheEntry.Size : Integer; begin Result:=Length(FContentData); end; // ------------------ // ------------------ TEmptyWebRequest ------------------ // ------------------ destructor TEmptyWebRequest.Destroy; begin inherited; FHeaders.Free; end; function TEmptyWebRequest.GetHeaders : TStrings; begin if FHeaders = nil then FHeaders := TStringList.Create; Result := FHeaders; end; function TEmptyWebRequest.RemoteIP : String; begin Result := ''; end; function TEmptyWebRequest.RawURL : String; begin Result := ''; end; function TEmptyWebRequest.URL : String; begin Result := ''; end; function TEmptyWebRequest.FullURL : String; begin Result := ''; end; function TEmptyWebRequest.Method : String; begin Result := FMethod; end; function TEmptyWebRequest.MethodVerb : TWebRequestMethodVerb; begin Result := wrmvUnknown; end; function TEmptyWebRequest.Security : String; begin Result := ''; end; function TEmptyWebRequest.Secure : Boolean; begin Result := False; end; function TEmptyWebRequest.Host : String; begin Result := ''; end; function TEmptyWebRequest.ContentLength : Integer; begin Result := 0; end; function TEmptyWebRequest.ContentData : RawByteString; begin Result := ''; end; function TEmptyWebRequest.ContentType : RawByteString; begin Result := ''; end; end.
27.144605
106
0.627792
c392d637323c064c2a581a093e752d22cd167c35
7,218
pas
Pascal
Libraries/DSharp/DSharp.DevExpress.TreeListPresenter.pas
jomael/Concepts
82d18029e41d55e897d007f826c021cdf63e53f8
[ "Apache-2.0" ]
62
2016-01-20T16:26:25.000Z
2022-02-28T14:25:52.000Z
Libraries/DSharp/DSharp.DevExpress.TreeListPresenter.pas
jomael/Concepts
82d18029e41d55e897d007f826c021cdf63e53f8
[ "Apache-2.0" ]
null
null
null
Libraries/DSharp/DSharp.DevExpress.TreeListPresenter.pas
jomael/Concepts
82d18029e41d55e897d007f826c021cdf63e53f8
[ "Apache-2.0" ]
20
2016-09-08T00:15:22.000Z
2022-01-26T13:13:08.000Z
(* Copyright (c) 2011, Stefan Glienke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - Neither the name of this library nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) unit DSharp.DevExpress.TreeListPresenter; interface uses Classes, System.UITypes, cxGraphics, cxTL, cxTLData, DSharp.DevExpress.PresenterDataSource, DSharp.Windows.CustomPresenter, //ImgList, Spring.Collections; type TTreeListPresenter = class(TCustomPresenter) private FDataSource: TTreeListPresenterDataSource; FTreeList: TcxVirtualTreeList; procedure DoCustomDrawDataCell(Sender: TcxCustomTreeList; Canvas: TcxCanvas; ViewInfo: TcxTreeListEditCellViewInfo; var Done: Boolean); procedure DoFocusedNodeChanged(Sender: TcxCustomTreeList; PrevFocusedNode, FocusedNode: TcxTreeListNode); procedure DoGetNodeImageIndex(Sender: TcxCustomTreeList; Node: TcxTreeListNode; IndexType: TcxTreeListImageIndexType; var Index: TImageIndex); procedure SetTreeList(const Value: TcxVirtualTreeList); protected procedure DoDblClick(Sender: TObject); override; function GetCurrentItem: TObject; override; procedure InitColumns; override; procedure InitEvents; override; procedure InitProperties; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure SetCurrentItem(const Value: TObject); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Refresh; override; published property TreeList: TcxVirtualTreeList read FTreeList write SetTreeList; end; implementation uses DSharp.Core.DataTemplates, DSharp.Windows.ControlTemplates, SysUtils, cxCustomData; { TTreeListPresenter } constructor TTreeListPresenter.Create(AOwner: TComponent); begin inherited; FDataSource := TTreeListPresenterDataSource.Create(Self); end; destructor TTreeListPresenter.Destroy; begin FDataSource.Free(); inherited; end; procedure TTreeListPresenter.DoCustomDrawDataCell(Sender: TcxCustomTreeList; Canvas: TcxCanvas; ViewInfo: TcxTreeListEditCellViewInfo; var Done: Boolean); var LItem: TObject; LItemTemplate: IControlTemplate; begin LItem := TcxVirtualTreeListNode(ViewInfo.Node).RecordHandle; if Supports(GetItemTemplate(LItem), IControlTemplate, LItemTemplate) then begin Done := LItemTemplate.CustomDraw(LItem, ViewInfo.Column.ItemIndex, Canvas.Canvas, ViewInfo.VisibleRect, ImageList, dmAfterCellPaint, ViewInfo.Selected); end; end; procedure TTreeListPresenter.DoDblClick(Sender: TObject); begin if FTreeList.HitTest.HitAtColumn and not FTreeList.IsEditing then begin inherited; end; end; procedure TTreeListPresenter.DoFocusedNodeChanged(Sender: TcxCustomTreeList; PrevFocusedNode, FocusedNode: TcxTreeListNode); begin if Assigned(FocusedNode) then begin View.ItemIndex := FocusedNode.Index; end else begin View.ItemIndex := -1; end; DoPropertyChanged('View'); end; procedure TTreeListPresenter.DoGetNodeImageIndex(Sender: TcxCustomTreeList; Node: TcxTreeListNode; IndexType: TcxTreeListImageIndexType; var Index: TImageIndex); var LItem: TObject; LItemTemplate: IDataTemplate; begin Index := -1; LItem := TcxVirtualTreeListNode(Node).RecordHandle; LItemTemplate := GetItemTemplate(LItem); if Assigned(LItemTemplate) then begin Index := LItemTemplate.GetImageIndex(LItem, 0); end; end; function TTreeListPresenter.GetCurrentItem: TObject; begin if Assigned(FTreeList) and (View.ItemIndex > -1) then begin Result := TcxVirtualTreeListNode(FTreeList.FocusedNode).RecordHandle; end else begin Result := nil; end; end; procedure TTreeListPresenter.InitColumns; var i: Integer; begin if Assigned(FTreeList) and UseColumnDefinitions then begin if Assigned(ColumnDefinitions) then begin for i := 0 to Pred(ColumnDefinitions.Count) do begin if i < FTreeList.ColumnCount then begin FTreeList.Columns[i].Caption.Text := ColumnDefinitions[i].Caption; FTreeList.Columns[i].Visible := ColumnDefinitions[i].Visible; FTreeList.Columns[i].Width := ColumnDefinitions[i].Width; end; end; end; end; end; procedure TTreeListPresenter.InitEvents; begin if Assigned(FTreeList) then begin FTreeList.OnCustomDrawDataCell := DoCustomDrawDataCell; FTreeList.OnDblClick := DoDblClick; FTreeList.OnFocusedNodeChanged := DoFocusedNodeChanged; FTreeList.OnGetNodeImageIndex := DoGetNodeImageIndex; end; end; procedure TTreeListPresenter.InitProperties; begin if Assigned(FTreeList) then begin FTreeList.Images := ImageList; FTreeList.PopupMenu := PopupMenu; FTreeList.OptionsData.SmartLoad := True; FTreeList.CustomDataSource := FDataSource; end; end; procedure TTreeListPresenter.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if Operation = opRemove then begin if AComponent = FTreeList then FTreeList := nil; end; end; procedure TTreeListPresenter.Refresh; begin if Assigned(FTreeList) and ([csLoading, csDesigning] * ComponentState = []) then begin FDataSource.DataChanged; end; end; procedure TTreeListPresenter.SetCurrentItem(const Value: TObject); begin if Assigned(FTreeList) then begin FDataSource.DataController.FocusedRecordIndex := FDataSource.GetRecordIndexByHandle(Value); end; end; procedure TTreeListPresenter.SetTreeList(const Value: TcxVirtualTreeList); begin if FTreeList <> Value then begin if Assigned(FTreeList) then begin FTreeList.RemoveFreeNotification(Self); end; FTreeList := Value; if Assigned(FTreeList) then begin FTreeList.FreeNotification(Self); end; InitControl(); end; end; end.
28.195313
95
0.762954
c342dbf62885ab83ef7a4aa1f2d3b18f84c3d5f6
520
pas
Pascal
utilities/generator/project/templates/TFhirElement.public.pas
danka74/fhirserver
1fc53b6fba67a54be6bee39159d3db28d42eb8e2
[ "BSD-3-Clause" ]
null
null
null
utilities/generator/project/templates/TFhirElement.public.pas
danka74/fhirserver
1fc53b6fba67a54be6bee39159d3db28d42eb8e2
[ "BSD-3-Clause" ]
null
null
null
utilities/generator/project/templates/TFhirElement.public.pas
danka74/fhirserver
1fc53b6fba67a54be6bee39159d3db28d42eb8e2
[ "BSD-3-Clause" ]
null
null
null
function noExtensions : TFhirElement; property DisallowExtensions : boolean read FDisallowExtensions write FDisallowExtensions; function hasExtensions : boolean; override; function hasExtension(url : string) : boolean; override; function getExtensionString(url : String) : String; override; function extensionCount(url : String) : integer; override; function extensions(url : String) : TFslList<TFHIRObject>; override; procedure addExtension(url : String; value : TFHIRObject); override;
57.777778
93
0.759615
fce9e8b2966adfc5363bf5ab70ed243e1785ffe9
2,947
pas
Pascal
windows/src/ext/jedi/jcl/jcl/examples/windows/debug/stacktrack/StackTrackDemoMain.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
219
2017-06-21T03:37:03.000Z
2022-03-27T12:09:28.000Z
windows/src/ext/jedi/jcl/jcl/examples/windows/debug/stacktrack/StackTrackDemoMain.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
4,451
2017-05-29T02:52:06.000Z
2022-03-31T23:53:23.000Z
windows/src/ext/jedi/jcl/jcl/examples/windows/debug/stacktrack/StackTrackDemoMain.pas
bravogeorge/keyman
c0797e36292de903d7313214d1f765e3d9a2bf4d
[ "MIT" ]
72
2017-05-26T04:08:37.000Z
2022-03-03T10:26:20.000Z
unit StackTrackDemoMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, AppEvnts, ActnList; type TMainForm = class(TForm) ExceptionLogMemo: TMemo; Button1: TButton; Button2: TButton; Button3: TButton; ListBox1: TListBox; Button4: TButton; ApplicationEvents: TApplicationEvents; Label1: TLabel; ActionList1: TActionList; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button4Click(Sender: TObject); procedure ApplicationEventsException(Sender: TObject; E: Exception); private { Private declarations } public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.DFM} uses JclDebug; { TMainForm } //-------------------------------------------------------------------------------------------------- // Simulation of various unhandled exceptions //-------------------------------------------------------------------------------------------------- procedure TMainForm.Button1Click(Sender: TObject); begin PInteger(nil)^ := 0; end; procedure TMainForm.Button2Click(Sender: TObject); begin ListBox1.Items[1] := 'a'; end; procedure AAA; begin PInteger(nil)^ := 0; end; procedure TMainForm.Button3Click(Sender: TObject); begin AAA; end; procedure TMainForm.Button4Click(Sender: TObject); begin ActionList1.Actions[0].Execute; end; //-------------------------------------------------------------------------------------------------- // Simple VCL application unhandled exception handler using JclDebug //-------------------------------------------------------------------------------------------------- procedure TMainForm.ApplicationEventsException(Sender: TObject; E: Exception); begin // Log time stamp ExceptionLogMemo.Lines.Add(DateTimeToStr(Now)); // Log unhandled exception stack info to ExceptionLogMemo JclLastExceptStackListToStrings(ExceptionLogMemo.Lines, False, True, True, False); // Insert empty line ExceptionLogMemo.Lines.Add(''); // Display default VCL unhandled exception dialog Application.ShowException(E); end; //-------------------------------------------------------------------------------------------------- // JclDebug initialization and finalization for VCL application //-------------------------------------------------------------------------------------------------- initialization // Enable raw mode (default mode uses stack frames which aren't always generated by the compiler) Include(JclStackTrackingOptions, stRawMode); // Disable stack tracking in dynamically loaded modules (it makes stack tracking code a bit faster) Include(JclStackTrackingOptions, stStaticModuleList); // Initialize Exception tracking JclStartExceptionTracking; finalization // Uninitialize Exception tracking JclStopExceptionTracking; end.
26.54955
101
0.603325
f1e30fd1ba716c39b7955a9bac6b676eb91acb11
4,483
pas
Pascal
examples/object_pascal/01.create.pas
Jdochoa/firebird
b5dee68393906b9cf2ccdd71b38f70171fd67e14
[ "Condor-1.1" ]
1,009
2015-05-28T12:34:39.000Z
2022-03-30T14:10:18.000Z
unittests/general/Several/bin/firebird/examples/interfaces/01.create.pas
FinCodeur/delphimvcframework
a45cb1383eaffc9e81a836247643390acbb7b9b0
[ "Apache-2.0" ]
574
2016-03-23T15:35:56.000Z
2022-03-31T07:11:03.000Z
unittests/general/Several/bin/firebird/examples/interfaces/01.create.pas
FinCodeur/delphimvcframework
a45cb1383eaffc9e81a836247643390acbb7b9b0
[ "Apache-2.0" ]
377
2015-05-28T16:29:21.000Z
2022-03-21T18:36:12.000Z
{ * PROGRAM: Object oriented API samples. * MODULE: 01.create.pas * DESCRIPTION: A sample of creating new database and new table in it. * Run second time (when database already exists) to see * how FbException is caught and handled by this code. * * Example for the following interfaces: * IMaster - main inteface to access all the rest * Status - returns the status of executed command * Provider - main interface to access DB / service * Attachment - database attachment interface * Transaction - transaction interface * Util - helper calls here and there * XpbBuilder - build various parameters blocks * * Run something like this to build: fpc -Fu<path-to-Firebird.pas> -Mdelphi 01.create.pas * * The contents of this file are subject to the Initial * Developer's Public License Version 1.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.ibphoenix.com/main.nfs?a=ibphoenix&page=ibp_idpl. * * Software distributed under the License is distributed AS IS, * WITHOUT WARRANTY OF ANY KIND, either express or implied. * See the License for the specific language governing rights * and limitations under the License. * * The Original Code was created by Alexander Peshkoff * for the Firebird Open Source RDBMS project. * * Copyright (c) 2015 Alexander Peshkoff <peshkoff@mail.ru> * and all contributors signed below. * * All Rights Reserved. * Contributor(s): ______________________________________. } Program create; uses Sysutils, Firebird; var // Declare pointers to required interfaces // Status is used to return wide error description to user st : IStatus; // This is main interface of firebird, and the only one // for getting which there is special function in our API master : IMaster; util : IUtil; // XpbBuilder helps to create various parameter blocks for API calls dpb : IXpbBuilder; // Provider is needed to start to work with database (or service) prov : IProvider; // Attachment and Transaction contain methods to work with // database attachment and transaction att : IAttachment; tra : ITransaction; procedure PrintError(s : IStatus); var maxMessage : Integer; outMessage : PAnsiChar; begin maxMessage := 256; outMessage := StrAlloc(maxMessage); util.formatStatus(outMessage, maxMessage, s); writeln(outMessage); StrDispose(outMessage); end; begin // Here we get access to master interface and helper utility interface // no error return may happen - these functions always succeed master := fb_get_master_interface; util := master.getUtilInterface; // status vector and main dispatcher are returned by calls to IMaster functions // no error return may happen - these functions always succeed st := master.getStatus; prov := master.getDispatcher; try // create DPB dpb := util.getXpbBuilder(st, IXpbBuilder.DPB, nil, 0); dpb.insertInt(st, isc_dpb_page_size, 4 * 1024); dpb.insertString(st, isc_dpb_user_name, 'sysdba'); dpb.insertString(st, isc_dpb_password, 'masterkey'); // create empty database att := prov.createDatabase(st, 'fbtests.fdb', dpb.getBufferLength(st), dpb.getBuffer(st)); writeln ('Database fbtests.fdb created'); // detach from database att.detach(st); att := nil; // remove unneeded any more tag from DPB if dpb.findFirst(st, isc_dpb_page_size) then dpb.removeCurrent(st); // attach it once again att := prov.attachDatabase(st, 'fbtests.fdb', dpb.getBufferLength(st), dpb.getBuffer(st)); writeln ('Re-attached database fbtests.fdb'); // start transaction tra := att.startTransaction(st, 0, nil); // create table att.execute(st, tra, 0, 'create table dates_table (d1 date)', 3, nil, nil, nil, nil); // Input parameters and output data not used // commit transaction retaining tra.commitRetaining(st); writeln ('Table dates_table created'); // insert a record into dates_table att.execute(st, tra, 0, 'insert into dates_table values (CURRENT_DATE)', 3, nil, nil, nil, nil); // Input parameters and output data not used // commit transaction (will close interface) tra.commit(st); tra := nil; writeln ('Record inserted into dates_table'); // detach from database (will close interface) att.detach(st); att := nil; dpb.dispose; dpb := nil; except on e: FbException do PrintError(e.getStatus); end; prov.release; end.
31.131944
93
0.7205
fc3a79b5f494dcc5cd931f23c23549297ff4848c
236
dpr
Pascal
Demo/01 - OpenUser/OpenUser.dpr
NickTucker42/ISNDS
98f620c10ca41ce0e307e39faccea97646730a8e
[ "MIT" ]
null
null
null
Demo/01 - OpenUser/OpenUser.dpr
NickTucker42/ISNDS
98f620c10ca41ce0e307e39faccea97646730a8e
[ "MIT" ]
null
null
null
Demo/01 - OpenUser/OpenUser.dpr
NickTucker42/ISNDS
98f620c10ca41ce0e307e39faccea97646730a8e
[ "MIT" ]
1
2021-06-19T15:34:08.000Z
2021-06-19T15:34:08.000Z
program OpenUser; uses Vcl.Forms, u_main in 'u_main.pas' {Form1}; {$R *.res} begin Application.Initialize; Application.MainFormOnTaskbar := True; Application.CreateForm(TForm1, Form1); Application.Run; end.
15.733333
41
0.677966
fc52ad1c53b9eafd0a11e3521d9dd6c88ec2841c
3,945
pas
Pascal
Catalogos/DomiciliosEdit.pas
NetVaIT/MAS
ebdbf2dc8ca6405186683eb713b9068322feb675
[ "Apache-2.0" ]
null
null
null
Catalogos/DomiciliosEdit.pas
NetVaIT/MAS
ebdbf2dc8ca6405186683eb713b9068322feb675
[ "Apache-2.0" ]
null
null
null
Catalogos/DomiciliosEdit.pas
NetVaIT/MAS
ebdbf2dc8ca6405186683eb713b9068322feb675
[ "Apache-2.0" ]
null
null
null
unit DomiciliosEdit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, _EditForm, dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel, dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle, dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast, dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky, dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue, dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver, dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver, dxSkinOffice2013White, dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus, dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008, dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010, dxSkinWhiteprint, dxSkinXmas2008Blue, dxSkinscxPCPainter, cxPCdxBarPopupMenu, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, Vcl.ImgList, System.Actions, Vcl.ActnList, Data.DB, Vcl.StdCtrls, Vcl.ExtCtrls, cxPC, cxContainer, cxEdit, cxMaskEdit, cxSpinEdit, cxDBEdit, cxTextEdit, Vcl.DBCtrls, cxCheckBox, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox; type TfrmDomiciliosEdit = class(T_frmEdit) Label1: TLabel; cxDBTextEdit1: TcxDBTextEdit; Label2: TLabel; cxDBTextEdit2: TcxDBTextEdit; Label3: TLabel; cxDBTextEdit3: TcxDBTextEdit; Label4: TLabel; cxDBTextEdit4: TcxDBTextEdit; Label5: TLabel; cxDBTextEdit5: TcxDBTextEdit; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; Label10: TLabel; cxDBTextEdit6: TcxDBTextEdit; cxDBLookupComboBox1: TcxDBLookupComboBox; cxDBLookupComboBox2: TcxDBLookupComboBox; cxDBLookupComboBox3: TcxDBLookupComboBox; cxDBLookupComboBox4: TcxDBLookupComboBox; dsPaises: TDataSource; dsEstados: TDataSource; dsMunicipios: TDataSource; dsPoblaciones: TDataSource; procedure FormShow(Sender: TObject); private FDataSetPaises: TDataSet; FDataSetPoblaciones: TDataSet; FDataSetMunicipios: TDataSet; FDataSetEstados: TDataSet; procedure SetDataSetEstados(const Value: TDataSet); procedure SetDataSetMunicipios(const Value: TDataSet); procedure SetDataSetPaises(const Value: TDataSet); procedure SetDataSetPoblaciones(const Value: TDataSet); { Private declarations } public { Public declarations } property DataSetPaises: TDataSet read FDataSetPaises write SetDataSetPaises; property DataSetEstados: TDataSet read FDataSetEstados write SetDataSetEstados; property DataSetMunicipios: TDataSet read FDataSetMunicipios write SetDataSetMunicipios; property DataSetPoblaciones: TDataSet read FDataSetPoblaciones write SetDataSetPoblaciones; end; implementation {$R *.dfm} uses DomiciliosDM; { TfrmDomiciliosEdit } procedure TfrmDomiciliosEdit.FormShow(Sender: TObject); begin inherited; cxDBLookupComboBox1.SetFocus; cxDBLookupComboBox2.SetFocus; cxDBLookupComboBox3.SetFocus; cxDBLookupComboBox4.SetFocus; cxDBTextEdit1.SetFocus; end; procedure TfrmDomiciliosEdit.SetDataSetEstados(const Value: TDataSet); begin FDataSetEstados := Value; dsEstados.DataSet:= Value; end; procedure TfrmDomiciliosEdit.SetDataSetMunicipios(const Value: TDataSet); begin FDataSetMunicipios := Value; dsMunicipios.DataSet:= Value; end; procedure TfrmDomiciliosEdit.SetDataSetPaises(const Value: TDataSet); begin FDataSetPaises := Value; dsPaises.DataSet:= Value; end; procedure TfrmDomiciliosEdit.SetDataSetPoblaciones(const Value: TDataSet); begin FDataSetPoblaciones := Value; dsPoblaciones.DataSet:= Value; end; end.
35.223214
99
0.777186
fcda89e2c06ca730e7ea9be84bd0cc82005fe829
2,531
pas
Pascal
src/Security/Validation/Validators/Ipv4ValidatorImpl.pas
zamronypj/fano-framework
559e385be5e1d26beada94c46eb8e760c4d855da
[ "MIT" ]
78
2019-01-31T13:40:48.000Z
2022-03-22T17:26:54.000Z
src/Security/Validation/Validators/Ipv4ValidatorImpl.pas
zamronypj/fano-framework
559e385be5e1d26beada94c46eb8e760c4d855da
[ "MIT" ]
24
2020-01-04T11:50:53.000Z
2022-02-17T09:55:23.000Z
src/Security/Validation/Validators/Ipv4ValidatorImpl.pas
zamronypj/fano-framework
559e385be5e1d26beada94c46eb8e760c4d855da
[ "MIT" ]
9
2018-11-05T03:43:24.000Z
2022-01-21T17:23:30.000Z
{*! * Fano Web Framework (https://fanoframework.github.io) * * @link https://github.com/fanoframework/fano * @copyright Copyright (c) 2018 - 2021 Zamrony P. Juhara * @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT) *} unit Ipv4ValidatorImpl; interface {$MODE OBJFPC} {$H+} uses ReadOnlyListIntf, ValidatorIntf, RequestIntf, BaseValidatorImpl; type (*!------------------------------------------------ * class having capability to validate if data * matched IP Address (IPV4) * * @author Zamrony P. Juhara <zamronypj@yahoo.com> *-------------------------------------------------*) TIpv4Validator = class(TBaseValidator) protected (*!------------------------------------------------ * actual data validation *------------------------------------------------- * @param dataToValidate input data * @return true if data is valid otherwise false *-------------------------------------------------*) function isValidData( const dataToValidate : string; const dataCollection : IReadOnlyList; const request : IRequest ) : boolean; override; public (*!------------------------------------------------ * constructor *-------------------------------------------------*) constructor create(); end; implementation uses SysUtils, sockets; resourcestring sErrFieldMustBeIpv4 = 'Field %s must be valid IP Address (IPv4)'; (*!------------------------------------------------ * constructor *-------------------------------------------------*) constructor TIpv4Validator.create(); begin inherited create(sErrFieldMustBeIpv4); end; (*!------------------------------------------------ * actual data validation *------------------------------------------------- * @param dataToValidate input data * @return true if data is valid otherwise false * @link https://lists.freepascal.org/pipermail/fpc-pascal/2016-July/048523.html *-------------------------------------------------*) function TIpv4Validator.isValidData( const dataToValidate : string; const dataCollection : IReadOnlyList; const request : IRequest ) : boolean; var tmpAddress : string; begin tmpAddress := HostAddrToStr(StrToHostAddr(dataToValidate)); result := (tmpAddress = dataToValidate); end; end.
28.761364
84
0.476492
fcd2ca348d406a14dcadea153d39ab93e0ffa3df
5,326
pas
Pascal
vc2/unaVcIDE.pas
cupples/vcp
0ade74b23dab087582942acb9673e7dbdca88d92
[ "Apache-2.0" ]
27
2018-04-17T07:56:29.000Z
2022-03-16T15:40:43.000Z
vc2/unaVcIDE.pas
cupples/vcp
0ade74b23dab087582942acb9673e7dbdca88d92
[ "Apache-2.0" ]
5
2018-05-17T20:04:55.000Z
2021-10-06T09:08:24.000Z
vc2/unaVcIDE.pas
cupples/vcp
0ade74b23dab087582942acb9673e7dbdca88d92
[ "Apache-2.0" ]
16
2018-04-17T07:56:32.000Z
2021-09-03T09:33:50.000Z
(* Copyright 2018 Alex Shamray 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. *) (* ---------------------------------------------- unaVCIDE.pas - VC 2.5 Pro components to be used with VCL/IDE Voice Communicator components version 2.5 Pro ---------------------------------------------- Copyright (c) 2002-2010 Lake of Soft All rights reserved http://lakeofsoft.com/ ---------------------------------------------- created by: Lake, 01 Jun 2002 modified by: Lake, Jun-Dec 2002 Lake, Jan-Dec 2003 Lake, Jan-May 2004 Lake, May-Oct 2005 Lake, Mar-Dec 2007 Lake, Jan-Feb 2008 ---------------------------------------------- *) {$I unaDef.inc } {$IFDEF DEBUG } {$DEFINE LOG_UNAVCIDE_INFOS } // log informational messages {$DEFINE LOG_UNAVCIDE_ERRORS } // log critical errors {$ENDIF DEBUG } {$IFNDEF VC_LIC_PUBLIC } {$DEFINE UNAVCIDE_SCRIPT_COMPONENT } // define to link scriptor component {$ENDIF VC_LIC_PUBLIC } {* @Author Lake Contains components and classes to be used in Delphi/C++Builder IDE. Wave components: @unorderedList( @itemSpacing Compact @item @link(unavclWaveInDevice WaveIn) @item @link(unavclWaveOutDevice WaveOut) @item @link(unavclWaveCodecDevice WaveCodec) @item @link(unavclWaveRiff WaveRiff) @item @link(unavclWaveMixer WaveMixer) @item @link(unavclWaveResampler WaveResampler) ) IP components: @unorderedList( @itemSpacing Compact @item @link(unavclIPClient IPClient) @item @link(unavclIPServer IPServer) @item @link(unavclIPBroadcastServer IPBroadcastServer) @item @link(unavclIPBroadcastClient IPBroadcastClient) ) Scripting: @unorderedList( @itemSpacing Compact @item @link(unavclScriptor Scriptor) ) Version 2.5.2008.03 Split into _pipe, _wave, _socks, _script units } unit unaVCIDE; interface uses Windows, unaTypes, unaClasses, Classes, unaVC_pipe, unaVC_wave, unaVC_socks {$IFDEF UNAVCIDE_SCRIPT_COMPONENT } , unaVC_script {$ENDIF UNAVCIDE_SCRIPT_COMPONENT } ; type // // redifine general pipes here unavclInOutPipe = unaVC_pipe.unavclInOutPipe; unavclInOutWavePipe = unaVC_wave.unavclInOutWavePipe; unavclInOutIpPipe = unaVC_socks.unavclInOutIpPipe; // -- // wave pipes // -- // WaveIn component. TunavclWaveInDevice = class(unavclWaveInDevice) end; // WaveOut component. TunavclWaveOutDevice = class(unavclWaveOutDevice) end; // WaveCodec component. TunavclWaveCodecDevice = class(unavclWaveCodecDevice) end; // WaveRIFF component. TunavclWaveRiff = class(unavclWaveRiff) end; // WaveMixer component. TunavclWaveMixer = class(unavclWaveMixer) end; // WaveResampler component. TunavclWaveResampler = class(unavclWaveResampler) end; // -- // IP pipes // -- // IPClient component. TunavclIPOutStream = class(unavclIPClient) end; // IPServer component. TunavclIPInStream = class(unavclIPServer) end; // BroadcastServer component. TunavclIPBroadcastServer = class(unavclIPBroadcastServer) end; // BroadcastClient component. TunavclIPBroadcastClient = class(unavclIPBroadcastClient) end; {$IFDEF VC_LIC_PUBLIC } {$ELSE } // -- // STUN // -- // STUN Client component. TunavclSTUNClient = class(unavclSTUNClient) end; // STUN Server component. TunavclSTUNServer = class(unavclSTUNServer) end; // -- // DNS // -- // DNS Client component. TunavclDNSClient = class(unavclDNSClient) end; {$ENDIF VC_LIC_PUBLIC } {$IFDEF UNAVCIDE_SCRIPT_COMPONENT } // -- // scripting // -- // Scriptor component. TunavclScriptor = class(unavclScriptor) end; {$ENDIF UNAVCIDE_SCRIPT_COMPONENT } {* Registers VC components in Delphi IDE Tools Palette. } procedure Register(); implementation uses unaUtils; // -- resister pipes in IDE -- // procedure Register(); begin RegisterComponents(c_VC_reg_core_section_name, [ // TunavclWaveInDevice, TunavclWaveOutDevice, TunavclWaveCodecDevice, TunavclWaveRiff, TunavclWaveMixer, TunavclWaveResampler, // TunavclIPOutStream, TunavclIPInStream, TunavclIPBroadcastServer, TunavclIPBroadcastClient // {$IFDEF UNAVCIDE_SCRIPT_COMPONENT } , TunavclScriptor {$ENDIF UNAVCIDE_SCRIPT_COMPONENT } ]); // RegisterComponents(c_VC_reg_IP_section_name, [ // {$IFDEF VC_LIC_PUBLIC } {$ELSE } // TunavclSTUNClient, TunavclSTUNServer, TunavclDNSClient {$ENDIF VC_LIC_PUBLIC } ]); end; initialization {$IFDEF LOG_UNAVCIDE_INFOS } logMessage('unaVCIDE - DEBUG is defined.'); {$ENDIF LOG_UNAVCIDE_INFOS } end.
22.191667
76
0.66748
c3c5bab4b54f4229a43c25b1e3a199cd0985bfb3
1,398
pas
Pascal
samples/jsonwebtokenplain/MainClientFormU.pas
lukaszsegiet/delphimvcframework
f78156a9618694ae32fb5d1e70dd545418587475
[ "Apache-2.0" ]
1
2018-01-02T09:13:27.000Z
2018-01-02T09:13:27.000Z
samples/jsonwebtokenplain/MainClientFormU.pas
lukaszsegiet/delphimvcframework
f78156a9618694ae32fb5d1e70dd545418587475
[ "Apache-2.0" ]
null
null
null
samples/jsonwebtokenplain/MainClientFormU.pas
lukaszsegiet/delphimvcframework
f78156a9618694ae32fb5d1e70dd545418587475
[ "Apache-2.0" ]
null
null
null
unit MainClientFormU; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm7 = class(TForm) Button1: TButton; Button2: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private FToken: String; procedure SetToken(const Value: String); { Private declarations } public property Token: String read FToken write SetToken; end; var Form7: TForm7; implementation uses MVCFramework.RESTClient, MVCFramework.RESTClient.Intf; {$R *.dfm} procedure TForm7.Button1Click(Sender: TObject); var lResp: IMVCRESTResponse; begin lResp := TMVCRESTClient.New .BaseURL('localhost', 8080) .Post('/login'); Token := lResp.Content; ShowMessage('In the next 15 seconds you can request protected resources. After your token will expires!'); end; procedure TForm7.Button2Click(Sender: TObject); var lResp: IMVCRESTResponse; begin lResp := TMVCRESTClient.New .BaseURL('localhost', 8080) .AddHeader('Authentication', 'bearer ' + FToken, True) .Get('/'); ShowMessage(lResp.StatusText + sLineBreak + lResp.Content); end; procedure TForm7.SetToken(const Value: String); begin FToken := Value; Memo1.Lines.Text := Value; end; end.
19.150685
108
0.709585
c3de6c092525fb07e76206b4dfc7037a367cd162
2,146
pas
Pascal
samples/a8/graph/rect_overlap.pas
zbyti/Mad-Pascal
546cae9724828f93047080109488be7d0d07d47e
[ "MIT" ]
1
2021-12-15T23:47:19.000Z
2021-12-15T23:47:19.000Z
samples/a8/graph/rect_overlap.pas
michalkolodziejski/Mad-Pascal
0a7a1e2f379e50b0a23878b0d881ff3407269ed6
[ "MIT" ]
null
null
null
samples/a8/graph/rect_overlap.pas
michalkolodziejski/Mad-Pascal
0a7a1e2f379e50b0a23878b0d881ff3407269ed6
[ "MIT" ]
null
null
null
uses crt, joystick, fastgraph; type TColision = (left=1, right, top, bottom); TTile = record width, height, centerX, centerY: byte; end; var A,B: TTile; Hero: record x,y, _x, _y: byte end; hit: byte; function CollisionTile(var B: TTile): byte; var w,h: byte; dx,dy,wy,hx: smallint; begin Result:=0; w := (A.width + B.width) shr 1; h := (A.height + B.height) shr 1; dx := A.centerX - B.centerX; dy := A.centerY - B.centerY; if (abs(dx) <= w) and (abs(dy) <= h) then begin (* collision! *) wy := w * dy; hx := h * dx; if (wy > hx) then begin if (wy > -hx) then (* collision at the bottom *) Result := ord(bottom) else (* on the left *) Result := ord(left); end else if (wy < -hx) then (* on the right *) Result := ord(top) else (* at the top *) Result := ord(right); end; end; procedure DrawTile(var a: TTile; color: Byte); var px,py,x,y,w,h: byte; begin w:=A.width; h:=A.height; x:=w shr 1; y:=h shr 1; px:=A.CenterX - x; py:=A.CenterY - y; SetColor(color); fRectangle(px,py,px+w,py+h); end; procedure HeroMovement; begin case joy_1 of joy_left: dec(Hero.X); joy_right: inc(Hero.X); joy_up: dec(Hero.Y); joy_down: inc(Hero.Y); end; if (Hero.x <> Hero._x) or (Hero.y <> Hero._y) then begin DrawTile(A, 0); A.CenterX := Hero.X; A.CenterY := Hero.Y; DrawTile(A, 1); Hero._x := Hero.x; Hero._y := Hero.y; DrawTile(B, 3); end; end; begin InitGraph(7); A.width:=8; A.height:=8; A.CenterX:=84; A.CenterY:=53; Hero.X:=A.CenterX; Hero.Y:=A.CenterY; B.width:=32; B.height:=16; B.CenterX:=93; B.CenterY:=45; repeat HeroMovement; hit:=CollisionTile(B); case hit of ord(left): writeln('left'); ord(right): writeln('right'); ord(top): writeln('top'); ord(bottom): writeln('bottom'); else writeln; end; until false; end.
14.902778
58
0.515377
e115617845ca3e5d52c0474cd3cbce82409c1c27
1,700
dfm
Pascal
BackupSettings.dfm
5cript/wiki-editor-vcl
273261ed92b653b06b9fe2cd90c52629d32f8abe
[ "MIT" ]
1
2016-12-14T07:12:11.000Z
2016-12-14T07:12:11.000Z
BackupSettings.dfm
5cript/wiki-editor-vcl
273261ed92b653b06b9fe2cd90c52629d32f8abe
[ "MIT" ]
8
2017-03-23T11:48:12.000Z
2017-03-25T18:04:38.000Z
BackupSettings.dfm
5cript/wiki-editor-vcl
273261ed92b653b06b9fe2cd90c52629d32f8abe
[ "MIT" ]
null
null
null
object BackupSettingsDialog: TBackupSettingsDialog Left = 0 Top = 0 BorderStyle = bsDialog Caption = '$BackupSettings' ClientHeight = 175 ClientWidth = 470 Color = clBtnFace Font.Charset = DEFAULT_CHARSET Font.Color = clWindowText Font.Height = -11 Font.Name = 'Tahoma' Font.Style = [] OldCreateOrder = False Position = poMainFormCenter OnCreate = FormCreate PixelsPerInch = 96 TextHeight = 13 object Label1: TLabel Left = 16 Top = 16 Width = 78 Height = 13 Caption = '$BackupInterval' end object Label2: TLabel Left = 16 Top = 67 Width = 65 Height = 13 Caption = '$MaxBackups' end object OldestBackup: TLabel Left = 16 Top = 112 Width = 71 Height = 13 Caption = '$OldestBackup' end object IntervalLabel: TLabel Left = 445 Top = 16 Width = 12 Height = 13 Caption = '15' end object Interval: TTrackBar Left = 200 Top = 12 Width = 239 Height = 35 Max = 120 Min = 5 Frequency = 5 Position = 15 TabOrder = 0 OnChange = MaxBackupsChange end object MaxBackups: TEdit Left = 200 Top = 64 Width = 239 Height = 21 NumbersOnly = True TabOrder = 1 Text = '100' OnChange = MaxBackupsChange end object Button1: TButton Left = 256 Top = 144 Width = 101 Height = 25 Caption = '$Ok' TabOrder = 2 OnClick = Button1Click end object Button2: TButton Left = 363 Top = 144 Width = 99 Height = 25 Caption = '$Cancel' TabOrder = 3 OnClick = Button2Click end end
19.318182
51
0.58
fc9f29770c665e92a31fe9735ac4388be5fd74e0
5,074
pas
Pascal
Projects/UninstProgressForm.pas
bovirus/issrc
bfa339a1a81e1844b63aabe53ba3b5cb2eaaab0d
[ "FSFAP" ]
1
2019-10-12T23:53:25.000Z
2019-10-12T23:53:25.000Z
Projects/UninstProgressForm.pas
Kulim13/issrc
9ff859dff77693dc3e800c93b84846e008ea8e3f
[ "FSFAP" ]
null
null
null
Projects/UninstProgressForm.pas
Kulim13/issrc
9ff859dff77693dc3e800c93b84846e008ea8e3f
[ "FSFAP" ]
1
2021-03-30T12:32:26.000Z
2021-03-30T12:32:26.000Z
unit UninstProgressForm; { Inno Setup Copyright (C) 1997-2019 Jordan Russell Portions by Martijn Laan For conditions of distribution and use, see LICENSE.TXT. Uninstaller progress form } interface {$I VERSION.INC} uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, SetupForm, StdCtrls, ExtCtrls, BitmapImage, NewProgressBar, NewStaticText, NewNotebook, BidiCtrls; type TUninstallProgressForm = class(TSetupForm) FOuterNotebook: TNewNotebook; FInnerPage: TNewNotebookPage; FInnerNotebook: TNewNotebook; FInstallingPage: TNewNotebookPage; FMainPanel: TPanel; FPageNameLabel: TNewStaticText; FPageDescriptionLabel: TNewStaticText; FWizardSmallBitmapImage: TBitmapImage; FBevel1: TBevel; FStatusLabel: TNewStaticText; FProgressBar: TNewProgressBar; FBeveledLabel: TNewStaticText; FBevel: TBevel; FCancelButton: TNewButton; private { Private declarations } protected procedure CreateParams(var Params: TCreateParams); override; public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Initialize(const ATitle, AAppName: String; const AModernStyle: Boolean); procedure UpdateProgress(const AProgress, ARange: Integer); published property OuterNotebook: TNewNotebook read FOuterNotebook; property InnerPage: TNewNotebookPage read FInnerPage; property InnerNotebook: TNewNotebook read FInnerNotebook; property InstallingPage: TNewNotebookPage read FInstallingPage; property MainPanel: TPanel read FMainPanel; property PageNameLabel: TNewStaticText read FPageNameLabel; property PageDescriptionLabel: TNewStaticText read FPageDescriptionLabel; property WizardSmallBitmapImage: TBitmapImage read FWizardSmallBitmapImage; property Bevel1: TBevel read FBevel1; property StatusLabel: TNewStaticText read FStatusLabel; property ProgressBar: TNewProgressBar read FProgressBar; property BeveledLabel: TNewStaticText read FBeveledLabel; property Bevel: TBevel read FBevel; property CancelButton: TNewButton read FCancelButton; end; var UninstallProgressForm: TUninstallProgressForm; implementation uses TaskbarProgressFunc, Main, Msgs, MsgIDs, CmnFunc; {$R *.DFM} { TUninstallProgressForm } procedure UninstallMessageBoxCallback(const Flags: LongInt; const After: Boolean; const Param: LongInt); const States: array [TNewProgressBarState] of TTaskbarProgressState = (tpsNormal, tpsError, tpsPaused); var UninstallProgressForm: TUninstallProgressForm; NewState: TNewProgressBarState; begin UninstallProgressForm := TUninstallProgressForm(Param); if After then NewState := npbsNormal else if (Flags and MB_ICONSTOP) <> 0 then NewState := npbsError else NewState := npbsPaused; with UninstallProgressForm.ProgressBar do begin State := NewState; Invalidate; end; SetAppTaskbarProgressState(States[NewState]); end; constructor TUninstallProgressForm.Create(AOwner: TComponent); begin inherited; SetMessageBoxCallbackFunc(UninstallMessageBoxCallback, LongInt(Self)); InitializeFont; {$IFDEF IS_D7} MainPanel.ParentBackGround := False; {$ENDIF} PageNameLabel.Font.Style := [fsBold]; PageNameLabel.Caption := SetupMessages[msgWizardUninstalling]; WizardSmallBitmapImage.Bitmap.Canvas.Brush.Color := clWindow; WizardSmallBitmapImage.Bitmap.Width := Application.Icon.Width; WizardSmallBitmapImage.Bitmap.Height := Application.Icon.Height; WizardSmallBitmapImage.Bitmap.Canvas.Draw(0, 0, Application.Icon); if SetupMessages[msgBeveledLabel] <> '' then begin BeveledLabel.Caption := ' ' + SetupMessages[msgBeveledLabel] + ' '; BeveledLabel.Visible := True; end; CancelButton.Caption := SetupMessages[msgButtonCancel]; end; destructor TUninstallProgressForm.Destroy; begin SetMessageBoxCallbackFunc(nil, 0); SetAppTaskbarProgressState(tpsNoProgress); inherited; end; procedure TUninstallProgressForm.Initialize(const ATitle, AAppName: String; const AModernStyle: Boolean); begin Caption := ATitle; PageDescriptionLabel.Caption := FmtSetupMessage1(msgUninstallStatusLabel, AAppName); StatusLabel.Caption := FmtSetupMessage1(msgStatusUninstalling, AAppName); if AModernStyle then begin OuterNotebook.Color := clWindow; Bevel1.Visible := False; end; end; procedure TUninstallProgressForm.CreateParams(var Params: TCreateParams); begin inherited; Params.WindowClass.style := Params.WindowClass.style or CS_NOCLOSE; end; procedure TUninstallProgressForm.UpdateProgress(const AProgress, ARange: Integer); var NewPos: Integer; begin NewPos := MulDiv(AProgress, ProgressBar.Max, ARange); if ProgressBar.Position <> NewPos then begin ProgressBar.Position := NewPos; SetAppTaskbarProgressValue(NewPos, ProgressBar.Max); end; end; end.
30.939024
106
0.753449
c367db29f585a345be0c6e2ba39ed65cb981b730
23,813
pas
Pascal
src/main/api/cwvirtualmachine.mos6502.pas
atkins126/cwVirtualMachine
c3ef2095a07402b16685adb4dc4243b9b519b90a
[ "BSD-3-Clause" ]
null
null
null
src/main/api/cwvirtualmachine.mos6502.pas
atkins126/cwVirtualMachine
c3ef2095a07402b16685adb4dc4243b9b519b90a
[ "BSD-3-Clause" ]
null
null
null
src/main/api/cwvirtualmachine.mos6502.pas
atkins126/cwVirtualMachine
c3ef2095a07402b16685adb4dc4243b9b519b90a
[ "BSD-3-Clause" ]
null
null
null
{$ifdef license} (* Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$endif} unit cwVirtualMachine.Mos6502; {$ifdef fpc}{$mode delphiunicode}{$endif} interface uses cwVirtualMachine ; const c66KB = 10000; type /// <summary> /// The 6502 CPU only has a 16-bit address bus, and therefore a /// maximum of 64KB of addressable memory. Early home, and business /// computers, got around this limitation using a device called a /// latch. A latch is hard-wired to the CPU between it and the /// memory devices, so that it can switch 'banks' of physical /// memory in to, and out of the CPU address space. <br/> /// For example, the Commodore64 was so named because it had 64KB /// of RAM, but it also had 20KB of ROM and could be expanded with /// more of each via the expansion port. Similarly the Commodore128 /// was almost the same system, but with 128KB of RAM. <br/> /// These Commodore systems used a latch called the PLA /// (programmable logic array) which was hard coded to addresses /// $0000 and $0001. Writing values to these addresses instructed /// the PLA to swap pieces of RAM and ROM into and out of the CPU /// address bus, giving the CPU access to more memory. <br/> /// The I6502VirtualMemory implementation allows for any /// amount of memory, from 64KB (minimum) to that permitted by /// the host system costraints, to be allocated for the virtual /// CPU to access. Providing access to large amounts of memory /// is done by setting up an array of 'banks'. <br/> /// A bank, in this case, is simply an offset /// into the virtual memory buffer, which represents an addressable /// 256 bytes. With 256 banks available, this allows all 64KB of the /// CPU address space to be populated by 256-byte chunks of the virtual /// memory buffer. <br/> /// The CPU implements a latch mechanism similar to the PLA from /// Commodore systems, in that, when setting any value at address /// $0001, an event handler is called and is passed a reference to /// an I6502VirtualMemory instance in order to alter the memory /// banking arrangement. <br/> /// Note that the initial state of the banks will map 1:1 onto /// the first 64KB of the virtual memory buffer, which has 64KB /// as its minimum allocation. /// Any attempt to set the size of virtual memory to less than /// 64KB will silently fail. /// </summary> I6502VirtualMemory = interface( IVirtualMemory ) ['{A029893B-AB25-4D3C-AD98-A20E3B6677B0}'] /// <summary> /// Returns the offset of the memory bank as specified by index. <br/> /// Getter for banks property. /// </summary> function getBank( const idx: uint8 ): nativeuint; /// <summary> /// Sets the offset of the memory bank as specified by index. <br/> /// Note: Any attempt to set a memory bank to a value outside the /// range of the virtual memory allocated, will result in a silent /// failure of the bank reassignment. /// Setter for banks property. /// </summary> procedure setBank( const idx: uint8; const value: nativeuint ); /// <summary> /// Get or Set the offset within the virtual memory buffer of /// a bank of memory for the 6502 CPU. <br/> /// Note: Any attempt to set a memory bank to a value outside the /// range of the virtual memory allocated, will result in a silent /// failure of the bank reassignment. /// </summary> property Banks[ const idx: uint8 ]: nativeuint read getBank write setBank; end; /// <summary> /// Provides methods for writing instruction code into a virtual memory /// buffer. Note: The bank-switching mechanism of the I6502VirtualMemory /// is ignored by I6502ByteCode. Instructions will be written to a cursor /// directly within the virtual memory buffer. Banks should therefore be /// configured accordingly. /// </summary> I6502ByteCode = interface( IBytecode ) ['{05BBBF78-A55F-458D-BE89-B500A615B33B}'] procedure ADC_abs_x ( const Address: uint16 ); procedure ADC_abs_y ( const Address: uint16 ); procedure ADC_abs ( const Address: uint16 ); procedure ADC_imm ( const value: uint8 ); procedure ADC_ind_y ( const Offset: uint8 ); procedure ADC_x_ind ( const Offset: uint8 ); procedure ADC_zpg_x ( const zpgOffset: uint8 ); procedure ADC_zpg ( const zpgOffset: uint8 ); procedure AND_abs_x ( const Address: uint16 ); procedure AND_abs_y ( const Address: uint16 ); procedure AND_abs ( const Address: uint16 ); procedure AND_imm ( const value: uint8 ); procedure AND_ind_y ( const Offset: uint8 ); procedure AND_x_ind ( const Offset: uint8 ); procedure AND_zpg_x ( const zpgOffset: uint8 ); procedure AND_zpg ( const zpgOffset: uint8 ); procedure ASL; procedure ASL_abs ( const Address: uint16 ); procedure ASL_abs_x ( const Address: uint16 ); procedure ASL_zpg_x ( const zpgOffset: uint8 ); procedure ASL_zpg ( const zpgOffset: uint8 ); procedure BCC_rel ( const relative: uint8 ); procedure BCS_rel ( const relative: uint8 ); procedure BEQ_rel ( const relative: uint8 ); procedure BIT_abs ( const Address: uint16 ); procedure BIT_zpg ( const zpgOffset: uint8 ); procedure BMI_rel ( const relative: uint8 ); procedure BNE_rel ( const relative: uint8 ); procedure BPL_rel ( const relative: uint8 ); procedure BRK; procedure BVC_rel ( const relative: uint8 ); procedure BVS_rel ( const relative: uint8 ); procedure CLC; procedure CLD; procedure CLI; procedure CLV; procedure CMP_abs_x ( const Address: uint16 ); procedure CMP_abs_y ( const Address: uint16 ); procedure CMP_abs ( const Address: uint16 ); procedure CMP_imm ( const value: uint8 ); procedure CMP_ind_y ( const Offset: uint8 ); procedure CMP_x_ind ( const Offset: uint8 ); procedure CMP_zpg_x ( const zpgOffset: uint8 ); procedure CMP_zpg ( const zpgOffset: uint8 ); procedure CPX_abs ( const Address: uint16 ); procedure CPX_imm ( const value: uint8 ); procedure CPX_zpg ( const zpgOffset: uint8 ); procedure CPY_abs ( const Address: uint16 ); procedure CPY_imm ( const value: uint8 ); procedure CPY_zpg ( const zpgOffset: uint8 ); procedure DEC_abs_x ( const Address: uint16 ); procedure DEC_abs ( const Address: uint16 ); procedure DEC_zpg_x ( const zpgOffset: uint8 ); procedure DEC_zpg ( const zpgOffset: uint8 ); procedure DEX; procedure DEY; procedure EOR_abs_x ( const Address: uint16 ); procedure EOR_abs_y ( const Address: uint16 ); procedure EOR_abs ( const Address: uint16 ); procedure EOR_imm ( const value: uint8 ); procedure EOR_ind_y ( const Offset: uint8 ); procedure EOR_X_ind ( const Offset: uint8 ); procedure EOR_zpg_x ( const zpgOffset: uint8 ); procedure EOR_zpg ( const zpgOffset: uint8 ); procedure INC_abs_x ( const Address: uint16 ); procedure INC_abs ( const Address: uint16 ); procedure INC_zpg_x ( const zpgOffset: uint8 ); procedure INC_zpg ( const zpgOffset: uint8 ); procedure INX; procedure INY; procedure JMP_abs ( const Address: uint16 ); procedure JMP_ind ( const Address: uint16 ); procedure JSR_abs ( const Address: uint16 ); procedure LDA_abs_x ( const Address: uint16 ); procedure LDA_abs_y ( const Address: uint16 ); procedure LDA_abs ( const Address: uint16 ); procedure LDA_imm ( const value: uint8 ); procedure LDA_ind_y ( const Offset: uint8 ); procedure LDA_x_ind ( const Offset: uint8 ); procedure LDA_zpg_x ( const zpgOffset: uint8 ); procedure LDA_zpg ( const zpgOffset: uint8 ); procedure LDX_zpg ( const zpgOffset: uint8 ); procedure LDX_abs_y ( const Address: uint16 ); procedure LDX_abs ( const Address: uint16 ); procedure LDX_imm ( const value: uint8 ); procedure LDX_zpg_y ( const zpgOffset: uint8 ); procedure LDY_abs_x ( const Address: uint16 ); procedure LDY_abs ( const Address: uint16 ); procedure LDY_imm ( const value: uint8 ); procedure LDY_zpg_x ( const zpgOffset: uint8 ); procedure LDY_zpg ( const zpgOffset: uint8 ); procedure LSR; procedure LSR_abs_x ( const Address: uint16 ); procedure LSR_abs ( const Address: uint16 ); procedure LSR_zpg_x ( const zpgOffset: uint8 ); procedure LSR_zpg ( const zpgOffset: uint8 ); procedure NOP; procedure ORA_abs_x ( const Address: uint16 ); procedure ORA_abs_y ( const Address: uint16 ); procedure ORA_abs ( const Address: uint16 ); procedure ORA_imm ( const value: uint8 ); procedure ORA_ind_y ( const Offset: uint8 ); procedure ORA_x_ind ( const Offset: uint8 ); procedure ORA_zpg_x ( const zpgOffset: uint8 ); procedure ORA_zpg ( const zpgOffset: uint8 ); procedure PHA; procedure PHP; procedure PLA; procedure PLP; procedure ROL; procedure ROL_abs_x ( const Address: uint16 ); procedure ROL_abs ( const Address: uint16 ); procedure ROL_zpg_x ( const zpgOffset: uint8 ); procedure ROL_zpg ( const zpgOffset: uint8 ); procedure ROR; procedure ROR_abs_x ( const Address: uint16 ); procedure ROR_abs ( const Address: uint16 ); procedure ROR_zpg_x ( const zpgOffset: uint8 ); procedure ROR_zpg ( const zpgOffset: uint8 ); procedure RTI; procedure RTS; procedure SBC_abs_y ( const Address: uint16 ); procedure SBC_abs_x ( const Address: uint16 ); procedure SBC_abs ( const Address: uint16 ); procedure SBC_imm ( const value: uint8 ); procedure SBC_ind_y ( const Offset: uint8 ); procedure SBC_x_ind ( const Offset: uint8 ); procedure SBC_zpg_x ( const zpgOffset: uint8 ); procedure SBC_zpg ( const zpgOffset: uint8 ); procedure SEC; procedure SED; procedure SEI; procedure STA_abs_x ( const Address: uint16 ); procedure STA_abs_y ( const Address: uint16 ); procedure STA_abs ( const Address: uint16 ); procedure STA_ind_y ( const Offset: uint8 ); procedure STA_x_ind ( const Offset: uint8 ); procedure STA_zpg_x ( const zpgOffset: uint8 ); procedure STA_zpg ( const zpgOffset: uint8 ); procedure STX_abs ( const Address: uint16 ); procedure STX_zpg_y ( const zpgOffset: uint8 ); procedure STX_zpg ( const zpgOffset: uint8 ); procedure STY_abs ( const Address: uint16 ); procedure STY_zpg_x ( const zpgOffset: uint8 ); procedure STY_zpg ( const zpgOffset: uint8 ); procedure TAX; procedure TAY; procedure TSX; procedure TXA; procedure TXS; procedure TYA; end; /// <summary> /// Callback type for I6502CPU OnLatch event. /// </summary> {$ifndef fpc} TLatchEvent = reference to procedure( const LatchValue: uint8; const Memory: I6502VirtualMemory ); {$else} TLatchEvent = procedure( const LatchValue: uint8; const Memory: I6502VirtualMemory ) of object; {$endif} /// <summary> /// An implementation of I6502CPU provides an Emulation of /// a Mos6502 8-bit microprocessor. This interface provides /// for the hardware specific features of that CPU. /// </summary> I6502CPU = interface( IVirtualCPU ) ['{BE394947-7D76-4F86-851C-AB70A76ECA7A}'] /// <summary> /// Returns the contents of the 6502 program counter (PC) register. <br/> /// Getter for the PC property. /// </summary> function getPC : uint16; /// <summary> /// Sets the contents of the 6502 program counter (PC) register. <br/> /// Setter for the PC property. /// </summary> procedure setPC( const value: uint16 ); /// <summary> /// Returns the contents of the 6502 accumulator (A) register. <br/> /// Getter for the A property. /// </summary> function getA : uint8; /// <summary> /// Sets the contents of the 6502 accumulator (A) register. <br/> /// Setter for the A property. /// </summary> procedure setA( const value: uint8 ); /// <summary> /// Returns the contents of the 6502 x-index (X) register. <br/> /// Getter for the X property. /// </summary> function getX : uint8; /// <summary> /// Sets the contents of the 6502 x-index (X) register. <br/> /// Setter for the X property. /// </summary> procedure setX( const value: uint8 ); /// <summary> /// Returns the contents of the 6502 y-index (Y) register. <br/> /// Getter for the Y property. /// </summary> function getY : uint8; /// <summary> /// Sets the contents of the 6502 y-index (Y) register. <br/> /// Setter for the Y property. /// </summary> procedure setY( const value: uint8 ); /// <summary> /// Returns the contents of the 6502 stack pointer (SP) register. <br/> /// Getter for the SP property. /// </summary> function getSP : uint8; /// <summary> /// Sets the contents of the 6502 stack pointer (SP) register. <br/> /// Setter for the SP property. /// </summary> procedure setSP( const value: uint8 ); /// <summary> /// Returns the contents of the 6502 status (SR) register. <br/> /// Getter for the SP property. /// </summary> function getSR : uint8; /// <summary> /// Sets the contents of the 6502 status (SR) register. <br/> /// Setter for the SP property. /// </summary> procedure setSR( const value: uint8 ); /// <summary> /// A utility to return the carry flag from the (SR) status register as a boolean. <br/> /// Getter for the CarryFlag property. /// </summary> function getCarryFlag: boolean; /// <summary> /// A utility to set the carry flag of the (SR) status register as a boolean. <br/> /// Setter for the CarryFlag property. /// </summary> procedure setCarryFlag( const value: boolean ); /// <summary> /// A utility to return the zero flag from the (SR) status register as a boolean. <br/> /// Getter for the ZeroFlag property. /// </summary> function getZeroFlag: boolean; /// <summary> /// A utility to set the zero flag of the (SR) status register as a boolean. <br/> /// Setter for the ZeroFlag property. /// </summary> procedure setZeroFlag( const value: boolean ); /// <summary> /// A utility to return the IRQ Disable flag from the (SR) status register as a boolean. <br/> /// Getter for the IRQDisableFlag property. /// </summary> function getIRQDisableFlag: boolean; /// <summary> /// A utility to set the IRQ Disable flag of the (SR) status register as a boolean. <br/> /// Setter for the IRQDisableFlag property. /// </summary> procedure setIRQDisableFlag( const value: boolean ); /// <summary> /// A utility to return the Decimal Mode flag from the (SR) status register as a boolean. <br/> /// Getter for the DecimalModeFlag property. /// </summary> function getDecimalModeFlag: boolean; /// <summary> /// A utility to set the Decimal Mode flag of the (SR) status register as a boolean. <br/> /// Setter for the DecimalModeFlag property. /// </summary> procedure setDecimalModeFlag( const value: boolean ); /// <summary> /// A utility to return the break flag from the (SR) status register as a boolean. <br/> /// Getter for the BreakFlag property. /// </summary> function getBreakFlag: boolean; /// <summary> /// A utility to set the break flag of the (SR) status register as a boolean. <br/> /// Setter for the BreakFlag property. /// </summary> procedure setBreakFlag( const value: boolean ); /// <summary> /// A utility to return the Overflow flag from the (SR) status register as a boolean. <br/> /// Getter for the OverflowFlag property. /// </summary> function getOverflowFlag: boolean; /// <summary> /// A utility to set the Overflow flag of the (SR) status register as a boolean. <br/> /// Setter for the OverflowFlag property. /// </summary> procedure setOverflowFlag( const value: boolean ); /// <summary> /// A utility to return the negative flag from the (SR) status register as a boolean. <br/> /// Getter for the NegativeFlag property. /// </summary> function getNegativeFlag: boolean; /// <summary> /// A utility to set the negative flag of the (SR) status register as a boolean. <br/> /// Setter for the NegativeFlag property. /// </summary> procedure setNegativeFlag( const value: boolean ); /// <summary> /// Returns a reference to an event handler to be /// called when the CPU alters the value at the latch /// address. (see I6502VirtualMemory for more information). <br/> /// </summary> function getOnLatch: TLatchEvent; /// <summary> /// Sets a reference to an event handler to be /// called when the CPU alters the value at the latch /// address. (see I6502VirtualMemory for more information). <br/> /// </summary> procedure setOnLatch( const value: TLatchEvent ); /// <summary> /// Get or Set an event handler to be called when the CPU /// alters the value at the latch address. /// (see I6502VirtualMemory for more information). /// </summary> property OnLatch: TLatchEvent read getOnLatch write setOnLatch; /// <summary> /// Get/Set the contents of the 6502 accumulator (A) register. <br/> /// </summary> property PC: uint16 read getPC write setPC; /// <summary> /// Get/Set the contents of the 6502 accumulator (A) register. <br/> /// </summary> property A: uint8 read getA write setA; /// <summary> /// Get/Set the contents of the 6502 x-index (X) register. <br/> /// </summary> property X: uint8 read getX write setX; /// <summary> /// Get/Set the contents of the 6502 y-index (Y) register. <br/> /// </summary> property Y: uint8 read getY write setY; /// <summary> /// Get/Set the contents of the 6502 stack pointer (SP) register. <br/> /// </summary> property SP: uint8 read getSP write setSP; /// <summary> /// Get/Set the contents of the 6502 status (SR) register. <br/> /// </summary> property SR: uint8 read getSR write setSR; /// <summary> /// Get/Set the carry flag of the (SR) status register as a boolean. /// </summary> property CarryFlag: boolean read getCarryFlag write setCarryFlag; /// <summary> /// Get/Set the zero flag of the (SR) status register as a boolean. /// </summary> property ZeroFlag: boolean read getZeroFlag write setZeroFlag; /// <summary> /// Get/Set the IRQ Disable flag of the (SR) status register as a boolean. /// </summary> property IRQDisableFlag: boolean read getIRQDisableFlag write setIRQDisableFlag; /// <summary> /// Get/Set the Decimal Mode flag of the (SR) status register as a boolean. /// </summary> property DecimalModeFlag: boolean read getDecimalModeFlag write setDecimalModeFlag; /// <summary> /// Get/Set the break flag of the (SR) status register as a boolean. /// </summary> property BreakFlag: boolean read getBreakFlag write setBreakFlag; /// <summary> /// Get/Set the Overflow flag of the (SR) status register as a boolean. /// </summary> property OverflowFlag: boolean read getOverflowFlag write setOverflowFlag; /// <summary> /// Get/Set the negative flag of the (SR) status register as a boolean. /// </summary> property NegativeFlag: boolean read getNegativeFlag write setNegativeFlag; end; /// <summary> /// A factory record for instancing the 6502 virtual CPU. /// </summary> T6502CPU = record /// <summary> /// Returns an instance of the 6502 CPU virtual CPU. /// </summary> class function Create( const Memory: I6502VirtualMemory ): I6502CPU; static; end; /// <summary> /// A factory record for instancing the 6502 byte code writer. /// </summary> T6502ByteCode = record /// <summary> /// Returns an instance of the I6502ByteCode implementation. /// </summary> class function Create( const Memory: I6502VirtualMemory ): I6502ByteCode; static; end; /// <summary> /// A factory record for instancing the 6502 virtual memory system. /// </summary> T6502VirtualMemory = record class function Create( const InitialSize: nativeuint = c66KB ): I6502VirtualMemory; static; end; implementation uses cwVirtualMachine.VirtualMemory.Mos6502 , cwVirtualMachine.VirtualCPU.Mos6502 , cwVirtualMachine.ByteCode.Mos6502 ; class function T6502VirtualMemory.Create(const InitialSize: nativeuint): I6502VirtualMemory; begin Result := cwVirtualMachine.VirtualMemory.Mos6502.T6502VirtualMemory.Create(InitialSize); end; class function T6502ByteCode.Create(const Memory: I6502VirtualMemory): I6502ByteCode; begin Result := cwVirtualMachine.ByteCode.Mos6502.T6502ByteCode.Create( Memory, $100 ); end; class function T6502CPU.Create(const Memory: I6502VirtualMemory): I6502CPU; begin Result := cwVirtualMachine.VirtualCPU.Mos6502.T6502CPU.Create( Memory ); end; end.
40.845626
102
0.644816
c3881e7a63969bcbed2aed165479bb10ff6ecb65
2,873
pas
Pascal
Source/Services/SimpleEmail/Base/Model/AWS.SES.Model.ListIdentitiesRequest.pas
herux/aws-sdk-delphi
4ef36e5bfc536b1d9426f78095d8fda887f390b5
[ "Apache-2.0" ]
67
2021-07-28T23:47:09.000Z
2022-03-15T11:48:35.000Z
Source/Services/SimpleEmail/Base/Model/AWS.SES.Model.ListIdentitiesRequest.pas
gabrielbaltazar/aws-sdk-delphi
ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a
[ "Apache-2.0" ]
5
2021-09-01T09:31:16.000Z
2022-03-16T18:19:21.000Z
Source/Services/SimpleEmail/Base/Model/AWS.SES.Model.ListIdentitiesRequest.pas
gabrielbaltazar/aws-sdk-delphi
ea1713b227a49cbbc5a2e1bf04cbf2de1f9b611a
[ "Apache-2.0" ]
13
2021-07-29T02:41:16.000Z
2022-03-16T10:22:38.000Z
unit AWS.SES.Model.ListIdentitiesRequest; interface uses Bcl.Types.Nullable, AWS.SES.Model.Request, AWS.SES.Enums; type TListIdentitiesRequest = class; IListIdentitiesRequest = interface function GetIdentityType: TIdentityType; procedure SetIdentityType(const Value: TIdentityType); function GetMaxItems: Integer; procedure SetMaxItems(const Value: Integer); function GetNextToken: string; procedure SetNextToken(const Value: string); function Obj: TListIdentitiesRequest; function IsSetIdentityType: Boolean; function IsSetMaxItems: Boolean; function IsSetNextToken: Boolean; property IdentityType: TIdentityType read GetIdentityType write SetIdentityType; property MaxItems: Integer read GetMaxItems write SetMaxItems; property NextToken: string read GetNextToken write SetNextToken; end; TListIdentitiesRequest = class(TAmazonSimpleEmailServiceRequest, IListIdentitiesRequest) strict private FIdentityType: Nullable<TIdentityType>; FMaxItems: Nullable<Integer>; FNextToken: Nullable<string>; function GetIdentityType: TIdentityType; procedure SetIdentityType(const Value: TIdentityType); function GetMaxItems: Integer; procedure SetMaxItems(const Value: Integer); function GetNextToken: string; procedure SetNextToken(const Value: string); strict protected function Obj: TListIdentitiesRequest; public function IsSetIdentityType: Boolean; function IsSetMaxItems: Boolean; function IsSetNextToken: Boolean; property IdentityType: TIdentityType read GetIdentityType write SetIdentityType; property MaxItems: Integer read GetMaxItems write SetMaxItems; property NextToken: string read GetNextToken write SetNextToken; end; implementation { TListIdentitiesRequest } function TListIdentitiesRequest.Obj: TListIdentitiesRequest; begin Result := Self; end; function TListIdentitiesRequest.GetIdentityType: TIdentityType; begin Result := FIdentityType.ValueOrDefault; end; procedure TListIdentitiesRequest.SetIdentityType(const Value: TIdentityType); begin FIdentityType := Value; end; function TListIdentitiesRequest.IsSetIdentityType: Boolean; begin Result := FIdentityType.HasValue; end; function TListIdentitiesRequest.GetMaxItems: Integer; begin Result := FMaxItems.ValueOrDefault; end; procedure TListIdentitiesRequest.SetMaxItems(const Value: Integer); begin FMaxItems := Value; end; function TListIdentitiesRequest.IsSetMaxItems: Boolean; begin Result := FMaxItems.HasValue; end; function TListIdentitiesRequest.GetNextToken: string; begin Result := FNextToken.ValueOrDefault; end; procedure TListIdentitiesRequest.SetNextToken(const Value: string); begin FNextToken := Value; end; function TListIdentitiesRequest.IsSetNextToken: Boolean; begin Result := FNextToken.HasValue; end; end.
27.103774
90
0.792899
ed139a8be06639e2bbd55729429fc2a2c784b316
733
pl
Perl
lib/unicore/lib/lb/OP.pl
basusingh/Nanny-Bot
4f3368c750b378f1b4d38a48dad6ac095af14056
[ "MIT" ]
1
2021-07-29T03:46:04.000Z
2021-07-29T03:46:04.000Z
lib/unicore/lib/lb/OP.pl
basusingh/Nanny-Bot
4f3368c750b378f1b4d38a48dad6ac095af14056
[ "MIT" ]
null
null
null
lib/unicore/lib/lb/OP.pl
basusingh/Nanny-Bot
4f3368c750b378f1b4d38a48dad6ac095af14056
[ "MIT" ]
null
null
null
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is built by mktables from e.g. UnicodeData.txt. # Any changes made here will be lost! # # Linebreak category 'Open_Punctuation' # return <<'END'; 0028 005B 007B 00A1 00BF 0F3A 0F3C 169B 201A 201E 2045 207D 208D 2329 2768 276A 276C 276E 2770 2772 2774 27C5 27E6 27E8 27EA 27EC 27EE 2983 2985 2987 2989 298B 298D 298F 2991 2993 2995 2997 29D8 29DA 29FC 2E18 2E22 2E24 2E26 2E28 3008 300A 300C 300E 3010 3014 3016 3018 301A 301D FD3E FE17 FE35 FE37 FE39 FE3B FE3D FE3F FE41 FE43 FE47 FE59 FE5B FE5D FF08 FF3B FF5B FF5F FF62 END
8.623529
59
0.593452
ed0260b947d5e417e610bff4626444e166f0411d
134
t
Perl
documents/cFiles/systemsProgramming/sed/data3.t
KeyMaker13/portfolio
a6c02fe09af4f9a86caf4cd7b74e215751977f88
[ "Zlib", "Apache-2.0" ]
null
null
null
documents/cFiles/systemsProgramming/sed/data3.t
KeyMaker13/portfolio
a6c02fe09af4f9a86caf4cd7b74e215751977f88
[ "Zlib", "Apache-2.0" ]
null
null
null
documents/cFiles/systemsProgramming/sed/data3.t
KeyMaker13/portfolio
a6c02fe09af4f9a86caf4cd7b74e215751977f88
[ "Zlib", "Apache-2.0" ]
null
null
null
int main (){ } # some comments here # more comments here yeah so this is a comment #we got another coment over there while()
8.933333
47
0.679104
73f844ff54a2c558c4e90e98d699e0162fdff565
120
pl
Perl
Lab1/kb1.pl
jennifernolan/Artificial-Intelligence-Labs
1e3b54fcf05d618d0338c353ac11ae79e538f112
[ "MIT" ]
null
null
null
Lab1/kb1.pl
jennifernolan/Artificial-Intelligence-Labs
1e3b54fcf05d618d0338c353ac11ae79e538f112
[ "MIT" ]
null
null
null
Lab1/kb1.pl
jennifernolan/Artificial-Intelligence-Labs
1e3b54fcf05d618d0338c353ac11ae79e538f112
[ "MIT" ]
null
null
null
wizard(harry). wizard(ron). wizard(hermione). muggle(uncle_vernon). muggle(aunt_petunia). chases(crookshanks,scabbars).
17.142857
29
0.791667
73e4caff9b6c839cb44f5a3e18ad81ba0fbadded
3,726
pm
Perl
modules/EnsEMBL/Web/Component/Regulation/Evidence.pm
dglemos/ensembl-webcode
08e53dcd0c4a32ec0bcbb4421ed4bd5f2c06d04a
[ "Apache-2.0", "MIT" ]
null
null
null
modules/EnsEMBL/Web/Component/Regulation/Evidence.pm
dglemos/ensembl-webcode
08e53dcd0c4a32ec0bcbb4421ed4bd5f2c06d04a
[ "Apache-2.0", "MIT" ]
null
null
null
modules/EnsEMBL/Web/Component/Regulation/Evidence.pm
dglemos/ensembl-webcode
08e53dcd0c4a32ec0bcbb4421ed4bd5f2c06d04a
[ "Apache-2.0", "MIT" ]
null
null
null
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::Component::Regulation::Evidence; use strict; use base qw(EnsEMBL::Web::Component::Regulation); sub _init { my $self = shift; $self->cacheable(0); $self->ajaxable(1); } sub content { my $self = shift; my $object = $self->object; my $context = $self->hub->param('context') || 200; my $object_slice = $object->get_bound_context_slice($context); $object_slice = $object_slice->invert if $object_slice->strand < 1; my $api_data = $object->get_evidence_data($object_slice,{}); my $evidence_data = $api_data->{'data'}; my $table = $self->new_table([], [], { data_table => 1, sorting => [ 'cell asc', 'type asc', 'location asc' ]}); $table->add_columns( { key => 'cell', title => 'Cell type', align => 'left', sort => 'string' }, { key => 'type', title => 'Evidence type', align => 'left', sort => 'string' }, { key => 'feature', title => 'Feature name', align => 'left', sort => 'string' }, { key => 'location', title => 'Location', align => 'left', sort => 'position' }, { key => 'source', title => 'Source', align => 'left', sort => 'position' }, ); my @rows; foreach my $cell_line (sort keys %$evidence_data) { # next unless !defined($cells) or scalar(grep { $_ eq $cell_line } @$cells); my $core_features = $evidence_data->{$cell_line}{'core'}{'block_features'}; my $non_core_features = $evidence_data->{$cell_line}{'non_core'}{'block_features'}; # Process core features first foreach my $features ($core_features, $non_core_features) { foreach my $f_set (sort { $features->{$a}[0]->start <=> $features->{$b}[0]->start } keys %$features) { foreach my $peak (sort { $a->start <=> $b->start } @{$features->{$f_set}}) { my $peak_start = $object_slice->start + $peak->start - 1; my $peak_end = $object_slice->start + $peak->end - 1; my $peak_calling = $peak->fetch_PeakCalling; my $source_link = $self->hub->url({ type => 'Experiment', action => 'Sources', ex => 'name-'.$peak_calling->name }); my $feature_type = $peak_calling->fetch_FeatureType; my $feature_name = $feature_type->name; push @rows, { type => $feature_type->evidence_type_label, location => $peak->slice->seq_region_name . ":$peak_start-$peak_end", feature => $feature_name, cell => $cell_line, source => sprintf(q(<a href="%s">%s</a>), $source_link, $peak_calling->fetch_source_label), }; } } } } $table->add_rows(@rows); # $self->cell_line_button('reg_summary'); if(scalar keys %$evidence_data) { return $table->render; } else { return "<p>There is no evidence for this regulatory feature in the selected cell lines</p>"; } } 1;
35.150943
114
0.600107
73e76cf8fd6adce7d290f6115ba5f987ec31089a
1,240
pm
Perl
perl/lib/BGTrainer/Word/Verb/I_150.pm
gflohr/Lingua-Poly
aea0d3c84c4a93ce39a54422a313e32b6d4c46db
[ "WTFPL" ]
3
2018-09-14T18:08:00.000Z
2021-01-18T23:52:20.000Z
perl/lib/BGTrainer/Word/Verb/I_150.pm
gflohr/Lingua-Poly
aea0d3c84c4a93ce39a54422a313e32b6d4c46db
[ "WTFPL" ]
12
2019-11-01T17:41:55.000Z
2022-02-18T03:38:40.000Z
perl/lib/BGTrainer/Word/Verb/I_150.pm
gflohr/Lingua-Poly
aea0d3c84c4a93ce39a54422a313e32b6d4c46db
[ "WTFPL" ]
1
2020-09-28T09:52:56.000Z
2020-09-28T09:52:56.000Z
#! /bin/false package BGTrainer::Word::Verb::I_150; use strict; use utf8; use base qw (BGTrainer::Word::Verb::I_145); sub new { my ($class, $word, %args) = @_; my $self = $class->SUPER::new ($word, %args); $self->{_stem} = $word; $self->{_aorist_stem1} = $word; $self->{_aorist_stem1} =~ s/а$/я/; $self->{_aorist_stem2} = $self->{_aorist_stem1}; undef $self->{_aorist_stresses}; $self->{_perfect_stem1} = $self->{_aorist_stem1}; $self->{_perfect_stem3} = $word; $self->{_perfect_stem3} =~ s/а$/е/; $self->{_perfect_stem4} = $self->{_perfect_stem3}; undef $self->{_perfect_stresses}; undef $self->{_gerund_stem}; return $self; } sub past_active_imperfect_participle { shift->past_active_aorist_participle; } sub present_active_participle { undef, undef, undef, undef, undef, undef, undef, undef, undef; } sub verbal_noun { undef, undef, undef, undef; } 1; #Local Variables: #mode: perl #perl-indent-level: 4 #perl-continued-statement-offset: 4 #perl-continued-brace-offset: 0 #perl-brace-offset: -4 #perl-brace-imaginary-offset: 0 #perl-label-offset: -4 #cperl-indent-level: 4 #cperl-continued-statement-offset: 2 #tab-width: 8 #coding: utf-8 #End:
20
54
0.654839
73d30d8653700718f12547b0c07774c76daee2bc
108,908
pl
Perl
detect.phasedSNP.reads.17.pl
lufuhao/WheatRNAssembler
8459b70eaba793b62a36ab3216e0a37c549198ba
[ "MIT" ]
1
2015-08-24T14:54:46.000Z
2015-08-24T14:54:46.000Z
detect.phasedSNP.reads.17.pl
lufuhao/WheatRNAssembler
8459b70eaba793b62a36ab3216e0a37c549198ba
[ "MIT" ]
null
null
null
detect.phasedSNP.reads.17.pl
lufuhao/WheatRNAssembler
8459b70eaba793b62a36ab3216e0a37c549198ba
[ "MIT" ]
null
null
null
#!/usr/bin/env perl use strict; use warnings; #use lib '/usr/users/celldev/luf/bin/webperl/perl5lib/20150917'; use Cwd; use FindBin qw($Bin); use Getopt::Long; use Bio::DB::Sam; use Scalar::Util; use File::Path qw/remove_tree rmtree/; use File::Copy qw/move/; use FuhaoPerl5Lib::BamKit qw/ReduceReadNameLength SamCleanHeader SortBam IndexBam CalcFPKM ReadSam/; use FuhaoPerl5Lib::VcfKit qw/ExtractVcf ReadVcf RunFreebayes ReadVariantType HapcompassVcf HcFragments RunHapCompass GroupFragments CorrectAlleles ReadHcOut/; use FuhaoPerl5Lib::CmdKit; use FuhaoPerl5Lib::FileKit; use FuhaoPerl5Lib::FastaKit qw/CdbFasta CdbYank IndexFasta RenameFasta RunFqTrinity RunMira4 RunCap3/; use FuhaoPerl5Lib::MiscKit qw/MaxLength/; use Storable qw/dclone/; use Data::Dumper qw/Dumper/; #no autovivification; use constant USAGE=><<EOH; SYNOPSIS: perl $0 --input my.fa [Options] Version: LUFUHAO20150603 Requirements: Programs: hapcompass.jar hc2vcf.jar, gzip, gunzip, cat, zcat, samtools, freebayes, vcf-tools, express, parallel Modiles: Scalar::Util, Cwd, Getopt::Long, FindBin, Statistics::Basic File::Copy Descriptions: Determine the insert size given pairs of seqing data by mapping them to a reference. Options: --help|-h Print this help/usage; --reference|-r <Fasta> [Msg] Sequence file in fasta; --cluster|-c <File> [Msg] Cluster file, 1 line 1 cluster, 1 cluster may have >=1 sequence ID in reference fasta; --list <ClusterLineNo1-ClusterLineNo2> [Opt] Only use cluters from line1 to line2; --bam <AABBDD.bam.list file> --vcf <AABBDD.vcf.gz file> --fpkm <FPKM configure file> --allele <Allele configure file> --numreads <file_totalreads> --taggenome <[Opt] Genome tag in AABBDD BAM, default: zg> --tagchrom <[Opt] Chromosome tag in AABBDD BAM, default: ac> --vardelimiter <[Opt] VCF genotype delimiter, default: '/'> Freebayes --freebayespath <[Opt] /path/to/freebayes if not in PATH> --freebayesparallelpath <[Opt] /path/to/freebayes-parallel if not in PATH> --freebayes_mincov <[Opt] minimum coverage, default: 3> --freebayes_minalt <[Opt] minimum alternative count, default: 3> --freebayes_parallel ###run freebayes in parallel --fastabin <[Opt] bin size for freebayes-parallel fragment, default: 200> SAMtools --tabixpath <[Opt] /path/to/tabix if not in PATH> --bgzippath <[Opt] /path/to/bgzip if not in PATH> --samtoolspath <[Opt] /path/to/samtools if not in PATH> VCFtools --vcfmergepath <[Opt] /path/to/vcf-merge if not in PATH> --vcfconcatpath <[Opt] /path/to/vcf-concat if not in PATH> --vcfsortpath <[Opt] /path/to/vcf-sort if not in PATH> --vcfqual <[Opt] minimum VCF quality, default: 20> --minmapq <[Opt] minimum mapping quality, default: 0> HapCompass --javapath <[Opt] /path/to/java if not in PATH> --javamem <[Opt] 2G> --hapcompasspath <[Opt] /path/to/hapcompass.jar> Trinity --trinitypath <[Opt] /path/to/Trinity if not in PATH> --maxinsert <[Opt] Int: default 800> --mira4path <[Opt] /path/to/mira if not in PATH>< --cap3path <[Opt] /path/to/cap3 if not in PATH> Running LOG --logcluster <[Opt] Cluster running LOG> --logfpkm <[Opt] Reference FPKM LOG> --logallele <[Opt] Allele assignment LOG> --loggeno <[Opt] Geno assignment LOG> --logcfpkm <[Opt] Cluster FPKM LOG> MISC --clean <clean cluster log> --phred <phred64|phred33> --threads <[Opt] Int, default:1> --cpus <[Opt] Int, default:1> --debug --verbose Detailed output for trouble-shooting; --version|v! Print current SCRIPT version; Example: perl $0 Author: Fu-Hao Lu Post-Doctoral Scientist in Micheal Bevan laboratory Cell and Developmental Department, John Innes Centre Norwich NR4 7UH, United Kingdom E-mail: Fu-Hao.Lu\@jic.ac.uk EOH ###HELP ends######################################################### die USAGE unless @ARGV; ###Receving parameter################################################ my ($help, $verbose, $numthreads, $debug, $ver, $cleanlog); #Global my ($reference, $file_cluster, $list); my ($file_bam_aabbdd); my ($file_vcf_aabbdd, $file_fpkm, $file_alleles); my ($geno_delimiter);###vcf format my ($bam_genome_tag, $bam_chromo_tag);###Bam my ($file_totalreads); #CDBtools my ($path_cdbfasta, $path_cdbyank); #express #my ($path_express, $express_frag_len_mean, $express_frag_len_stddev, $express_max_read_len);###express my ($minimum_fpkm, $maxinsert); #freebayes my ($path_freebayes, $freebayes_min_coverage, $freebayes_min_alternative_count, $vcfqual, $min_mapq, $freebayes_parallel, $path_freebayesparallel, $freebayes_fastabin);###freebayes #samtools my ($path_samtools, $path_tabix, $path_bgzip);###samtools #HapCompass my ($path_hapcompassjar, $path_java, $javamem);###HapCompass #vcf-tools my ($path_vcfmerge, $path_vcfconcat, $path_vcfsort);#VCFtools #Trinity my ($path_trinity, $num_cpus); #MIRA4 my $path_mira4; #CAP3 my $path_cap3; #CDHIT my ($path_cdhitest); #Bowtie2 #my ($pathbowtie2build, $pathbowtie2p); my $fq_qual_score; #LOG my ($cluster_log, $fpkm_log, $allele_log, $geno_log, $clusterfpkm);###LOG my ($totalreads_AABBDD, $totalreads_AABB, $totalreads_AA, $totalreads_DD); GetOptions( "help|h!" => \$help, "reference|r:s" => \$reference, "cluster|c:s" => \$file_cluster, "list:s" => \$list, "bam:s" => \$file_bam_aabbdd, "vcf:s" => \$file_vcf_aabbdd, "fpkm:s" => \$file_fpkm, "allele:s" => \$file_alleles, "taggenome:s" => \$bam_genome_tag, "tagchrom:s" => \$bam_chromo_tag, "numreads:s" => \$file_totalreads, "vardelimiter:s" => \$geno_delimiter, "cdbfastapath:s" => \$path_cdbfasta, "cdbyankpath:s" => \$path_cdbyank, "freebayespath:s" => \$path_freebayes, "freebayesparallelpath:s" => \$path_freebayesparallel, "tabixpath:s" => \$path_tabix, "bgzippath:s" => \$path_bgzip, "freebayes_mincov:i" => \$freebayes_min_coverage, "freebayes_minalt:i" => \$freebayes_min_alternative_count, "freebayes_parallel!" => \$freebayes_parallel, "fastabin:i" => \$freebayes_fastabin, "vcfqual:i" => \$vcfqual, "minmapq:i" => \$min_mapq, "samtoolspath:s" => \$path_samtools, "javapath:s" => \$path_java, "javamem:s" => \$javamem, "hapcompasspath:s" => \$path_hapcompassjar, "vcfmergepath:s" => \$path_vcfmerge, "vcfconcatpath:s" => \$path_vcfconcat, "vcfsortpath:s" => \$path_vcfsort, "trinitypath:s" => \$path_trinity, "mira4path:s" => \$path_mira4, "cap3path:s" => \$path_cap3, # "cdhitestpath:s" => \$path_cdhitest, "logcluster:s" => \$cluster_log, "logfpkm:s" => \$fpkm_log, "logcfpkm:s" => \$clusterfpkm, "logallele:s" => \$allele_log, "loggeno:s" => \$geno_log, "clean!" => \$cleanlog, "phred:s" => \$fq_qual_score, "maxinsert:i" => \$maxinsert, "threads|t:i" => \$numthreads, "cpus:i" => \$num_cpus, "debug|" => \$debug, "verbose!" => \$verbose, "version|v!" => \$ver) or die USAGE; ($help or $ver) and die USAGE; ### Defaults ######################################################## print "Setting up defaults\n"; ### For test ### my $RootDir=$Bin; my $cluster_start=0; my $cluster_end; ($cluster_start, $cluster_end)=split(/-/, $list); $debug=0 unless (defined $debug); $numthreads=1 unless (defined $numthreads); $num_cpus=1 unless (defined $num_cpus); $geno_delimiter=',' unless (defined $geno_delimiter); $bam_genome_tag='zg' unless (defined $bam_genome_tag); $bam_chromo_tag='zc'unless (defined $bam_chromo_tag); $fq_qual_score='phred33' unless (defined $fq_qual_score); my $cmd_success_code=1; my $cmd_failure_code=0; ### CDBtools $path_cdbfasta='cdbfasta' unless (defined $path_cdbfasta); $path_cdbyank='cdbyank' unless (defined $path_cdbyank); ###Express $minimum_fpkm=0 unless (defined $minimum_fpkm); $maxinsert=800 unless (defined $maxinsert); ###Freebayes $path_freebayes='freebayes' unless (defined $path_freebayes); $freebayes_min_coverage=3 unless (defined $freebayes_min_coverage); $freebayes_min_alternative_count=3 unless (defined $freebayes_min_alternative_count); $vcfqual=20 unless (defined $vcfqual); $min_mapq=0 unless (defined $min_mapq); $freebayes_parallel=0 unless (defined $freebayes_parallel); $path_freebayesparallel='freebayes-parallel' unless (defined $path_freebayesparallel); $freebayes_fastabin=200 unless (defined $freebayes_fastabin); #my $freebayes_additional_cmd=" --min-coverage $freebayes_min_coverage --min-alternate-count $freebayes_min_alternative_count --min-mapping-quality $min_mapq --genotype-qualities --pooled-discrete "; my $freebayes_additional_cmd=" --min-coverage $freebayes_min_coverage --min-alternate-count $freebayes_min_alternative_count --min-mapping-quality $min_mapq --pooled-discrete "; #samtools $path_samtools='samtools' unless (defined $path_samtools); $path_tabix='tabix' unless (defined $path_tabix); $path_bgzip='bgzip' unless (defined $path_bgzip); #HapCompass $path_hapcompassjar="$RootDir/utils/hapcompass/hapcompass.jar" unless (defined $path_hapcompassjar); $path_java='java' unless (defined $path_java); $javamem='2G' unless (defined $javamem and $javamem=~/^\d+G$/); #VCFtools $path_vcfmerge='vcf-merge' unless (defined $path_vcfmerge); $path_vcfconcat='vcf-concat' unless (defined $path_vcfconcat); $path_vcfsort='vcf-sort' unless (defined $path_vcfsort); #Trinity $path_trinity='Trinity' unless (defined $path_trinity); my $trinity_addcmd='--max_memory '.$javamem.' --run_as_paired --CPU '.$num_cpus.' --group_pairs_distance '.$maxinsert.' --full_cleanup --min_kmer_cov 3 --min_glue 3'; $path_mira4='mira' unless (defined $path_mira4); $path_cap3='cap3' unless (defined $path_cap3); #CDHITEST $path_cdhitest='cd-hit-est' unless (defined $path_cdhitest); my $cdhit_addcmd=' -c 1.00 -n 10 -T 0 -r 1 -d 0 -M 30000 '; #LOG $cluster_log='0.cluster.log' unless (defined $cluster_log); $fpkm_log='0.reference.fpkm.log' unless (defined $fpkm_log); $allele_log='0.allele.log' unless (defined $allele_log); $geno_log='0.geno.log' unless (defined $geno_log); $clusterfpkm='0.cluster.FPKM.log' unless (defined $clusterfpkm); $cleanlog=0 unless (defined $cleanlog); ### input and output ################################################ #Check important file inpput print "Checking input and output\n";### For test ### die "Error: undefined reference file\n" unless (defined $reference); ($reference)=AddFilePath($reference); die "Error: not-found reference file\n" unless (-s $reference); die "Please specify cluster file\n" unless (defined $file_cluster and -s $file_cluster); die "Please specify the file of bam list for AABBDD\n" unless (defined $file_bam_aabbdd and -s $file_bam_aabbdd); #die "Please specify the file of bam list for AABB\n" unless (defined $file_bam_aabb and -s $file_bam_aabb); #die "Please specify the file of bam list for AA\n" unless (defined $file_bam_aa and -s $file_bam_aa); #die "Please specify the file of bam list for DD\n" unless (defined $file_bam_dd and -s $file_bam_dd); die "Please specify the file for number of reads\n" unless (defined $file_totalreads and -s $file_totalreads); die "Please specify the file for alleles\n" unless (defined $file_alleles and -s $file_alleles); die "Please specify the file for FPKM\n" unless (defined $file_fpkm and -s $file_fpkm); #Remove last-run cluster log unlink $cluster_log if (-e $cluster_log); unlink $fpkm_log if (-e $fpkm_log); #read AABBDD bam files my $bamAABBDDfiles=' '; my $bamAABBfiles=' '; my $bamAAfiles=' '; my $bamDDfiles=' '; my $numbams=0; my @bam_AABBDD=(); if ($file_bam_aabbdd=~/\.bam$/i) { push (@bam_AABBDD, $file_bam_aabbdd); } else { close BAMAABBDD if (defined fileno(BAMAABBDD)); open (BAMAABBDD, "<$file_bam_aabbdd") || die "InputOutputError: can not open AABBDD $file_bam_aabbdd\n"; while (my $line1=<BAMAABBDD>) { chomp $line1; if (defined $line1 and $line1 =~/^\S+\.bam$/i and -s $line1) { push (@bam_AABBDD, $line1); } else { die "InputOutputError: bam $line1 in AABBDD $file_bam_aabbdd not exist or empty\n"; } } close BAMAABBDD; } die "InputOutputError: empty AABBDD bam files" if (scalar(@bam_AABBDD)<1); print "InputOutputReport: Reading AABBDD bams: ".scalar(@bam_AABBDD)."\n" if ($debug or $verbose); foreach (@bam_AABBDD) { print "---> $_\n" if ($debug or $verbose); unless (-s "$_.bai") { if (! &IndexBam($_, $path_samtools)) { die "InputOutputError: AABBDD BAM index error\n"; } } } $bamAABBDDfiles=join(',', @bam_AABBDD); $numbams=scalar(@bam_AABBDD); undef @bam_AABBDD; ###format: %expressfpkm{chr}=(abd_fpkm, ab_fpkm, a_fpkm, d_fpkm) my %expressfpkm=(); close FPKMIN if (defined fileno(FPKMIN)); unless (open(FPKMIN, "< $file_fpkm")) { die "Error: not read FPKM file\n" } while (my $line=<FPKMIN>) { chomp $line; my @fpkmarr=split(/\t/, $line); my $chrom=shift @fpkmarr; @{$expressfpkm{$chrom}}=@fpkmarr; } close FPKMIN; my $using_existing_alleles=0; ###format: %ancestralalleles{chr}{$pos}=('A' => 0/1, 'B' => 1/0, 'D' => 1/0) my %ancestralalleles=(); if (defined $file_alleles and -s $file_alleles) { $using_existing_alleles=1; close EXISTINGALLELE if (defined fileno(EXISTINGALLELE)); unless (open (EXISTINGALLELE, "< $file_alleles")) { die "Error: can not read fixed allele file\n"; } while (my $line=<EXISTINGALLELE>) { chomp $line; my @arr=split(/\t/, $line); $ancestralalleles{$arr[0]}{$arr[1]}{'A'}=$arr[2]; $ancestralalleles{$arr[0]}{$arr[1]}{'B'}='?';#$arr[3]; $ancestralalleles{$arr[0]}{$arr[1]}{'D'}=$arr[4]; } close EXISTINGALLELE; } ###input vcf if (defined $file_vcf_aabbdd) { if (! -s $file_vcf_aabbdd) { die "MainError: can not find AABBDD file: $file_vcf_aabbdd\n"; } if ($file_vcf_aabbdd=~/\.vcf$/i) { if (! &BgzipVcf($file_vcf_aabbdd, "$file_vcf_aabbdd.gz", $path_bgzip)) { die "InputOutputError: AABBDD VCF bgzip\n"; } elsif (! &IndexVcf("$file_vcf_aabbdd.gz", $path_tabix)) { die "InputOutputError: AABBDD VCF index\n"; } else { $file_vcf_aabbdd.='.gz'; } } elsif ($file_vcf_aabbdd=~/\.vcf\.gz$/i) { unless (-s "$file_vcf_aabbdd.tbi") { if (! &IndexVcf($file_vcf_aabbdd, $path_tabix)) { die "InputOutputError: AABBDD VCF index2\n"; } } } else { die "InputOutputError: unknown AABBDD VCF format\n"; } } if ($verbose) { print "InputOutputReport: VCF inputs: \n"; if (defined $file_vcf_aabbdd) {print "AABBDD VCF1: $file_vcf_aabbdd\n";} else {print "AABBDD VCF1: null\n";} } ### Number of total reads print "Reading Total number of reads\n"; my %reads_per_rg=(); close NUMREADS if (defined fileno(NUMREADS)); unless (open (NUMREADS, "<$file_totalreads")) { die "Error: can not open --numreads file\n"; } while (my $read_num_line=<NUMREADS>) { # print "REadline: $read_num_line";### For test ### chomp $read_num_line; next if ($read_num_line=~/^#/); my @read_num_arr=split(/\s+/, $read_num_line); next unless (scalar(@read_num_arr)==2); next unless (defined $read_num_arr[1] and $read_num_arr[1] =~/^\d+$/); # print "Term: $read_num_arr[0]\t TotalReads: $read_num_arr[1]\n"; ### For test ### if ($read_num_arr[0] eq 'TotalAABBDD') { $totalreads_AABBDD=$read_num_arr[1]; die "Error: wrong AABBDD read sum number\n" unless (defined $totalreads_AABBDD and $totalreads_AABBDD); } elsif ($read_num_arr[0] eq 'TotalAABB') { $totalreads_AABB=$read_num_arr[1]; die "Error: wrong AABB read sum number\n" unless (defined $totalreads_AABB and $totalreads_AABB); } elsif ($read_num_arr[0] eq 'TotalAA') { $totalreads_AA=$read_num_arr[1]; die "Error: wrong AA read sum number\n" unless (defined $totalreads_AA and $totalreads_AA); } elsif ($read_num_arr[0] eq 'TotalDD') { $totalreads_DD=$read_num_arr[1]; die "Error: wrong DD read sum number\n" unless (defined $totalreads_DD and $totalreads_DD); } else { $reads_per_rg{$read_num_arr[0]}=$read_num_arr[1]; } } close NUMREADS; my @totalreads=($totalreads_AABBDD, $totalreads_AABB, $totalreads_AA, $totalreads_DD); if (1) {### For test ### print "### SUM of reads number ###\n"; print "AABBDD: $totalreads_AABBDD\n"; print "AABB: $totalreads_AABB\n"; print "AA: $totalreads_AA\n"; print "DD: $totalreads_DD\n"; print "\n### SUM of reads group ###\n"; map {print $_."\t".$reads_per_rg{$_}."\n"} keys %reads_per_rg; print "### SUM of reads number END ###\n"; } ### Main ############################################################ my $RunDir=getcwd; #Prepare temporary folder if (! -d "$RunDir/AABBDD") { mkdir ("$RunDir/AABBDD", 0766) || die "(Main0)Error: can not create folder $RunDir/AABBDD\n"; } unlink glob "$RunDir/AABBDD/*"; if (! -d "$RunDir/fasta") { mkdir ("$RunDir/fasta", 0766) || die "(Main0)Error: can not create folder $RunDir/fasta\n"; } if (! -d "$RunDir/kmergenie") { mkdir ("$RunDir/kmergenie", 0766) || die "(Main0)Error: can not create folder $RunDir/kmergenie\n"; } #if (! -d "$RunDir/AABB") { # mkdir ("$RunDir/AABB", 0766) || die "(Main0)Error: can not create folder AABB\n"; #} #unlink glob "$RunDir/AABB/*"; #if (! -d "$RunDir/AA") { # mkdir ("$RunDir/AA", 0766) || die "(Main0)Error: can not create folder AA\n"; #} #unlink glob "$RunDir/AA/*"; #if (! -d "$RunDir/DD") { # mkdir ("$RunDir/DD", 0766) || die "(Main0)Error: can not create folder DD\n"; #} #unlink glob "$RunDir/DD/*"; #(Main1) index fasta my ($test_cdbfasta, $fasta_index)=&CdbFasta($reference, $path_cdbfasta); if ($test_cdbfasta == $cmd_failure_code ) { die "(Main1)Error: can not index fasta: $reference\n"; } print "Fasta Index: $fasta_index\n"; # Load clustered fasta id list, 1 cluster perl line, saparated by space open (CLUSTER, "<$file_cluster") || die "(Main1)Error: can not open file: $file_cluster\n"; # Output cluster succeeds or not. Format: open (CLUSTERLOG, ">$cluster_log") || die "(Main1)Error: can not write file: $cluster_log\n"; # output fpkm calculated open (REFERFPKM, ">$fpkm_log") || die "(Main1)Error: can not write file: $fpkm_log\n"; # output fpkm for each cluster open (CLUSTFPKM, ">$clusterfpkm") || die "(Main1)Error: can not write file: $clusterfpkm\n"; # output allele log open (ALLELELOG, ">$allele_log") || die "(Main1)Error: can not write file: $allele_log\n"; open (GENOLOG, ">$geno_log") || die "(Main1)Error: can not geno log: $geno_log\n"; my $cluster_num=0;###for quick find which line/cluster has problem my @cluster_seqids=();### while (my $cluster_line=<CLUSTER>) { chomp $cluster_line; @cluster_seqids=(); ###Empty this in case of abnormal duplicates @cluster_seqids=split(/\s+/, $cluster_line); $cluster_num=shift @cluster_seqids; ### Step0: control which lines to reads: --list my $stage=0; # print "(Main$stage)Step: Line control\n"; ### For test ### if ($cluster_num<$cluster_start) { next; } elsif ($cluster_num>=$cluster_start) { if (defined $cluster_end and $cluster_num>$cluster_end) { next; } } next if ($cluster_line=~/^#/); print GENOLOG "\n\n\nCluster$cluster_num: $cluster_line\n"; print "\n\n\n\n\n##### Prcessing Cluster $cluster_num ###\n$cluster_line\n"; print STDERR "\n\n\n\n\n##### Prcessing Cluster $cluster_num ###\n$cluster_line\n"; ##COMMENT: Check if empty line if (scalar(@cluster_seqids)<1) { print STDERR "(Main2)Warnings: line $cluster_num in $file_cluster ignored as empty\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tNumIDinCluster<1\n"; next; } my $fastaids=join(',', @cluster_seqids); ##COMMENT: Empty folder unless (chdir $RunDir) { print STDERR "(Main$stage)Error: can not chdir to : $RunDir\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tChDirAtBegining\n"; next; } unlink glob "$RunDir/AABBDD/*"; unlink glob "$RunDir/AABB/*"; unlink glob "$RunDir/AA/*"; unlink glob "$RunDir/DD/*"; if ($cleanlog) { my @cluster=glob "$RunDir/Clust*"; foreach my $indfolder (@cluster) { print "(Main$stage)Testing: delete PATH: $indfolder\n"; # sleep(1); unlink glob "$indfolder/*"; } } ## Stage1: extract fasta reference $stage=1; print "(Main$stage)Step: Extract AABBDD fasta\n"; ### For test ### my $clusterrefer="$RunDir/Clust$cluster_num/ref.$cluster_num.fa"; if ( ! -d "$RunDir/Clust$cluster_num") { unless (mkdir ("$RunDir/Clust$cluster_num", 0766)) { print STDERR "(Main$stage)Error: create folder $RunDir/Clust$cluster_num\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tMkdirCluster\n"; next; } } unless (-s $clusterrefer) { unless (&CdbYank($fasta_index, $clusterrefer, \@cluster_seqids, $path_cdbyank)) { print STDERR "(Main$stage)Error: failed to extract ClusterID $cluster_num: @cluster_seqids\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tCdbYank\n"; next; } } unless (-s "$clusterrefer.fai") { unless (&IndexFasta($clusterrefer, $path_samtools)) { print STDERR "(Main$stage)Error: failed to index ClusterID $cluster_num: @cluster_seqids\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tIndexFasta\n"; next; } } ###Stage2: Extract bam $stage=2; print "(Main$stage)Step: Extract AABBDD BAMs\n"; ### For test ### my $cluter_oribam="$RunDir/Clust$cluster_num/AABBDD.$cluster_num.ori.bam"; unless (&exec_cmd_return("bam_multiextract.sh -b $bamAABBDDfiles -s $fastaids -n $numbams -o $cluter_oribam")) { print STDERR "(Main$stage)Error: AABBDD BAM extraction failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tBAMExtract\n"; next; } ###Stage3: Extract VCF $stage=3; print "(Main$stage)Step: Extract AABBDD VCF\n"; ### For test ### my $cluster_orivcf="$RunDir/Clust$cluster_num/AABBDD.$cluster_num.ori.vcf.gz"; if (defined $file_vcf_aabbdd and -s $file_vcf_aabbdd) { unless (&ExtractVcf($file_vcf_aabbdd, $cluster_line, $cluster_orivcf)) { print STDERR "(Main$stage)Error: AABBDD VCF extraction failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tVcfExtractAABBDD\n"; next; } } else { print STDERR "(Main$stage)Error: NoVcfAABBDD\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tNoVcfAABBDD\n"; next; } ###Stage4: Check Point: detect polymorphism, continue if no, region and merge if yes $stage=4; my $total_sites=0; my $num_allelic_sites=0; my $num_not_allelic=0; #Format: %{$polymorphicsites}=($chr => ($posit => ++)); my $polymorphicsites={}; my ($test_loadvcf, $aabbdd_vcf_obj)=&ReadVcf($cluster_orivcf, 20); unless ($test_loadvcf) { print STDERR "(Main$stage)Error: loadvcf $cluster_orivcf failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tLoadVCF\n"; next; } foreach my $chrom (keys %{$aabbdd_vcf_obj}) { foreach my $posit (keys %{${$aabbdd_vcf_obj}{$chrom}}) { $total_sites++; if (exists ${$aabbdd_vcf_obj}{$chrom}{$posit}[2]) { my $thisgeno=${$aabbdd_vcf_obj}{$chrom}{$posit}[2]; if ($thisgeno=~/^\d+\/\d+\/\d+$/) { my @arr=split(/\//, $thisgeno); my %hash1=(); map {$hash1{$_}++} @arr; # print "(Main$stage)Test: Chr:Pos $chrom:$posit Geno: $thisgeno NumAllele: ".scalar(keys %hash1)."\n"; ### For test ### if (scalar(keys %hash1)==1) { $num_not_allelic++; } elsif (scalar(keys %hash1)>1) { map {${$polymorphicsites}{$chrom}{$posit}{$_}++} (keys %hash1); $num_allelic_sites++; } else { print STDERR "(Main$stage)Error: unknown number of genotypes\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tNumGeno\n"; next; } } else { print STDERR "(Main$stage)Error: error genotypes\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tErrorGeno\n"; next; } } else { print STDERR "(Main$stage)Error: NoGeno\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tNoGeno\n"; next; } } } if (1) { print "(Main$stage)Info: Total sites: $total_sites\n"; print "(Main$stage)Info: Allelic sites: $num_allelic_sites\n"; print "(Main$stage)Info: NotAllelic sites: $num_not_allelic\n"; } ##Stage5: Defined important hash or array here $stage=5; my $assignallele={}; # %{$polymorphismreadids}=(readid => ('gen' => ( 'A' => ++, 'B' => ++, 'D' => ++), my $polymorphismreadids={}; #Format: %{$fragments}=(readid => (chrom => (pos => (geno1 => quality, geno2 => quality))); my $fragments={}; #Format: %{$readidsum}=(readid => ('gen' => ( 'A' => ++, 'B' => ++, 'D' => ++), # 'chr' => ( '1AL' => ++, '!BL' => ++, '2DL' => ++, ...), # 'shared' => ++/0, # 'mapped' => ++/0, # 'ref' => chr => ++)); my $readsum={}; #my $test_aa_expressed=0; my $test_bb_expressed=0; my $test_dd_expressed=0; ###Stage6: Group alleles into subgenome $stage=6; print "\n(Main$stage)Step: GroupReads\n"; ### For test ### ##ReadSam my ($test_readbam, $aabbdd_bam_obj)=&ReadSam($cluter_oribam, $clusterrefer, 1); unless ($test_readbam) { print STDERR "(Main$stage)Error: Reading AABBDD BAM failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\treadsamAABBDD\n"; next; } ##GroupReads (my $test_groupreads, $fragments, $readsum)=&GroupReads($aabbdd_bam_obj, $aabbdd_vcf_obj); if ($test_groupreads) { print STDERR "(Main$stage)Error: GroupReads SUB failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tGroupReads\n"; next; } if (0) { print "(Main$stage)Test: \$readsum\n"; print Dumper $readsum; print "\n"; } if (0) { ### test $fragments ### print "(Main$stage)Test: \$fragments\n"; print Dumper $fragments;### For test ### print "\n"; } $aabbdd_bam_obj={}; ###Stage6: checkpoint $stage=6; my $fragmentfile="$RunDir/Clust$cluster_num/AABBDD.$cluster_num.fragments"; ##Format: %{$corrected_fragments}=($readid => chrom => $partstart => $pos => $allele => $qual); ##Format: %{$corrected_sites}=($chr => $pos => $allele => ++) my ($test_hc, $corrected_fragments, $corrected_sites, $vcfreferencer)=HcFragments($fragments, $fragmentfile, $readsum); unless ($test_hc) { print STDERR "(Main$stage)Error: prepare HapCompass Fragments error\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tFragments\n"; next; } print "(Main$stage)Info: Number of sites to be phased: $num_allelic_sites => "; my $corrected_num_allelic_sites=0; foreach (keys %{$corrected_sites}) { $corrected_num_allelic_sites+=scalar(keys %{${$corrected_sites}{$_}}); } # print "(Main$stage)Test: $corrected_num_allelic_sites\n"; ### for test ### print "(Main$stage)Info: Fragments cleaning: ".scalar(keys %{$fragments})." => ".scalar(keys %{$corrected_fragments})."\n"; # unless (GroupFragments($corrected_fragments)) {print STDERR "(Main$stage)Error: GroupFragments running";next;} ### For test ### # print "(Main$stage)Test: \%{\$corrected_sites}\n"; print Dumper $corrected_sites; print "\n"; $fragments={}; ##Stage7: decide ploidy here $stage=7; print "\n(Main$stage)Step: Ploidy\n"; ### For test ### my $test_run_phase=0; my $assembly_desc=''; my $ploidy=1; my %genomecount=(); my %chromcount=(); my $final_geno={}; my $totalmappedreads=0; my $total_notag=0; my $total_tagged=0; my @final_ploidy=(); my $inferred_genoploidy=''; my $inferred_chrom=''; my $genomeinfer_from_reads=0; my $unknown_genome=0; my %chrom2genome=(); my $guessgenome=''; my $num_excluded_reads=0; my $num_shared_reads=0; my ($test_aa_expressed, $test_bb_expressed, $test_dd_expressed)=(0, 0, 0); foreach my $ind_read (keys %{$readsum}) { if (exists ${$readsum}{$ind_read}{'excluded'} and ${$readsum}{$ind_read}{'excluded'}>0) { $num_excluded_reads++; ${$readsum}{$ind_read}{'shared'}=0; next; } if (exists ${$readsum}{$ind_read}{'shared'} and ${$readsum}{$ind_read}{'shared'}>0) { $num_shared_reads++; } if (exists ${${$readsum}{$ind_read}}{'gen'}) { foreach my $xgen (keys %{${${$readsum}{$ind_read}}{'gen'}}) { $genomecount{$xgen}++; if (exists ${$readsum}{$ind_read}{'ref'}) { foreach my $xref (keys %{${$readsum}{$ind_read}{'ref'}}) { $chrom2genome{$xref}{$xgen}++; } } } $total_tagged++; } else { $total_notag++; } if (exists ${${$readsum}{$ind_read}}{'chr'}) { foreach (keys %{${${$readsum}{$ind_read}}{'chr'}}) { $chromcount{$_}++; } } if (exists ${${$readsum}{$ind_read}}{'mapped'}) { $totalmappedreads++; } } unless ($totalmappedreads>0 and ($num_shared_reads+scalar(keys %{$corrected_fragments}))>10) {### minimum 10 reads print STDERR "(Main$stage)Error: Not enough reads\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tNotEnoughReads\n"; next; } if (($total_tagged/$totalmappedreads) >=0.4) {###Decide ploidy if 40% reads assigned $genomeinfer_from_reads=1; foreach (keys %genomecount) { $inferred_genoploidy.=$_ if (($genomecount{$_}/$total_tagged) >=0.1); push (@final_ploidy, $_); } print "(Main$stage)Info: Inferred geno: $inferred_genoploidy\n"; unless ($inferred_genoploidy =~/^[ABD]+$/) { print STDERR "(Main$stage)Error: unwanted \$inferred_genoploidy: $inferred_genoploidy\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tinferred_genoploidy\n"; next; } $ploidy=length($inferred_genoploidy); my $num_chr_assigned=0; map {my $gen=substr($_, 1, 1); if ($inferred_genoploidy=~/$gen/) {$num_chr_assigned++;}} (keys %chromcount); print "(Main$stage)Info: Num_InferChrom: $num_chr_assigned\n";###test### if ($num_chr_assigned>=1) { foreach (keys %chromcount) { my $gen=substr($_, 1, 1); next unless ($inferred_genoploidy=~/$gen/); if ($chromcount{$_} >= ($totalmappedreads/$num_chr_assigned)) { $inferred_chrom.="$_($chromcount{$_})"; print "(Main$stage)Info: ChromInfer: $_\t$chromcount{$_}\n"; } } print "(Main$stage)Info: Inferred geno: $inferred_chrom\n"; } } else {### Decide ploidy from diploid plants $genomeinfer_from_reads=0; ###format: %expressfpkm{chr}=(abd_fpkm, ab_fpkm, a_fpkm, d_fpkm) foreach (@cluster_seqids) { if (exists $expressfpkm{$_}) { $test_aa_expressed=1 if (defined $expressfpkm{$_}[2] and $expressfpkm{$_}[2]>$minimum_fpkm); $test_dd_expressed=1 if (defined $expressfpkm{$_}[3] and $expressfpkm{$_}[3]>$minimum_fpkm); $test_bb_expressed=1 if (exists $genomecount{'B'} and ($genomecount{'B'}/$total_tagged) >=0.05); } } if ($corrected_num_allelic_sites==0) { $ploidy=1; $test_run_phase=0; my $maxcount=0; foreach (keys %genomecount) { if ($genomecount{$_}> $maxcount) { $guessgenome=$_; $maxcount=$genomecount{$_}; } elsif ($genomecount{$_}== $maxcount) { $guessgenome.=$_; } } $inferred_genoploidy=$guessgenome; } elsif ($corrected_num_allelic_sites>0) { if ($corrected_num_allelic_sites==1) { $test_run_phase=0; $unknown_genome=1; } else { $test_run_phase=1; } $ploidy=$test_aa_expressed+$test_dd_expressed+$test_bb_expressed; $inferred_genoploidy.='A' if ($test_aa_expressed>0); $inferred_genoploidy.='B' if ($test_bb_expressed>0); $inferred_genoploidy.='D' if ($test_dd_expressed>0); $inferred_genoploidy='ABD' if ($ploidy==0 or $inferred_genoploidy eq ''); } }###PLOIDY unless ($inferred_genoploidy=~/^[ABD]+$/) { print STDERR "(Main$stage)Error: genoploidy inferring error: $inferred_genoploidy\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tinferred_genoploidy\n"; next; } unless ($ploidy>=0 and $ploidy<4) { print STDERR "(Main$stage)Error: ploidy inferring error: $ploidy\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tinferredploidy:$ploidy:$inferred_genoploidy:$genomeinfer_from_reads\n"; next; } if (1) {### print out genome assign results ### print GENOLOG "##### Genome summary #####\nTotal mapped reads: $totalmappedreads\nTagged: $total_tagged\nNotag: $total_notag\nShared reads: $num_shared_reads\nExcluded reads: $num_excluded_reads\n\n"; map {print GENOLOG "Genome: $_\tCount: $genomecount{$_}\n"} (sort (keys %genomecount)); print GENOLOG "\n"; map {print GENOLOG "Chrom: $_\tCount: $chromcount{$_}\n"} (sort (keys %chromcount)); print GENOLOG "##### Genome summary #####\n"; print GENOLOG "(Main$stage)Info: Ploidy: $ploidy\nAA: $test_aa_expressed\nBB: $test_bb_expressed\nDD: $test_dd_expressed\nPloid string: $inferred_genoploidy\nInferredFromGenome: $genomeinfer_from_reads\n"; } if (1) {### For test ### print "##### Genome summary #####\nTotal mapped reads: $totalmappedreads\nTagged: $total_tagged\nNotag: $total_notag\nShared reads: $num_shared_reads\nExcluded reads: $num_excluded_reads\n\n"; map {print "Genome: $_\tCount: $genomecount{$_}\n"} (sort (keys %genomecount)); print "\n"; map {print "Chrom: $_\tCount: $chromcount{$_}\n"} (sort (keys %chromcount)); print "##### Genome summary #####\n"; print "(Main$stage)Info: Ploidy: $ploidy\nAA: $test_aa_expressed\nBB: $test_bb_expressed\nDD: $test_dd_expressed\nPloid string: $inferred_genoploidy\nInferredFromGenome: $genomeinfer_from_reads\n"; } # if ($ploidy!=1 or $corrected_num_allelic_sites!=0 or scalar(keys %{$corrected_fragments}) != 0) { # print STDERR "(Main$stage)Error: Multiploidy\n"; # print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tMultiploidy:\n"; # next; # } ###Stage8: correct genome alleles using diploid and genome assignemnts $stage=8; print "\n(Main$stage)Step: Correct Allele\n"; ### For test ### my $comprimised=0; ##Format: %CAgenodepth=(chr => pos => allele => depth) my $alleledepth={}; if ($ploidy==1) { if ($corrected_num_allelic_sites>0) { print "(Main$stage)Info: Comprimised cluster: ploidy=1 but have $corrected_num_allelic_sites allelic sites\n"; foreach (keys %{$corrected_fragments}) { ${$readsum}{$_}{'shared'}=1; } $comprimised=1; $corrected_fragments={}; $corrected_num_allelic_sites=0; } $test_run_phase=0; } else { (my $test_CAcode, $assignallele, $alleledepth)=CorrectAlleles($inferred_genoploidy, $corrected_fragments, $readsum, \%ancestralalleles); unless ($test_CAcode) { print STDERR "(Main$stage)Error: Correct Allele\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tCorrectAllele\n"; next; } } # print "(Main$stage)Test: assignallele\n"; print Dumper $assignallele; print "\n"; ### Test asignallele ### # print "(Main$stage)Test: Depth\n"; print Dumper $alleledepth; print "\n"; ### Test depth ### ###Stage9: Fill in genotypes accroding to the corrected alleles $stage=9; print "\n(Main$stage)Step: Fillin\n"; ### For test ### my $fixedAllele_3fillin={}; ##Format: $fixedGeno_4fillin{chr}->{pos}='0/1/0'; ('A/B/D') my $fixedGeno_4fillin={}; if ($ploidy>1) { print "(Main$stage)Info: run_phasing before fillin: $test_run_phase\n"; # print "(Main$stage)Test: Genome assignment ###\n"; print Dumper $assignallele; ### for test ### (my $test_fiv, $test_run_phase, my $fixedgeno_hashindex, my $fillinAlleles_hashindex)=&FillInVariations($assignallele,$aabbdd_vcf_obj, $inferred_genoploidy, $corrected_sites, $alleledepth); ###checl Fillin $polymorphic # print "(Main$stage)Test: Genome assignment ###\n"; print Dumper $assignallele; ### for test ### if ($test_fiv==0) {###Fillin succeeds $fixedAllele_3fillin=$fillinAlleles_hashindex; $fixedGeno_4fillin=$fixedgeno_hashindex; } elsif ($test_fiv==1) { print STDERR "(Main$stage)Error: FillIn1 SUB failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tFillin1\n"; next; } elsif ($test_fiv==2) { print STDERR "(Main$stage)Error: FillIn2 SUB failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tFillin2\n"; next; } elsif ($test_fiv==3) { print STDERR "(Main$stage)Error: FillIn3 SUB failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tFillin3\n"; next; } else { print STDERR "(Main$stage)Error: FillIn SUB failed\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tFillin4\n"; next; } # print "(Main$stage)Test: ### Genome assigned ###\n"; print Dumper $assignallele; print "\n"; ### For test %{$assignallele}### # print "(Main$stage)Test: ### Genoypes Fillin ###\n"; print Dumper $fixedAllele_3fillin; print "\n"; ### For test fixedAllele_3fillin### $final_geno=$fixedAllele_3fillin; print "(Main$stage)Info: run_phasing after fillin: $test_run_phase\n"; ### For test ### } if (0) {### Test $final_geno ### foreach my $chrom (keys %{$final_geno}) { print "(Main$stage)Test: Chrom: $chrom\n"; foreach my $pos (keys %{${$assignallele}{$chrom}}) { print "(Main$stage)Test: Chrom: $chrom Pos: $pos\n"; } } } if (0) { foreach my $chrom (keys %{$aabbdd_vcf_obj}) { print "(Main$stage)Test: AlleleTesting: chromosome $chrom\n" if ($debug); ### For test ### foreach my $posit (sort {$a <=> $b } keys %{${$aabbdd_vcf_obj}{$chrom}}) { print "(Main$stage)Test: AlleleTesting: positions $posit\n" if ($debug);### For test ### next unless (exists ${$corrected_sites}{$chrom} and exists ${$corrected_sites}{$chrom}{$posit}); my $printline=$cluster_num."\t".$chrom."\t".$posit."\t".${${${$aabbdd_vcf_obj}{$chrom}}{$posit}}[2]."\t"; #%ancestralalleles $printline.="Diploid: \t"; if (exists $ancestralalleles{$chrom} and exists $ancestralalleles{$chrom}{$posit}) { $printline.=(exists $ancestralalleles{$chrom}{$posit}{'A'}) ? $ancestralalleles{$chrom}{$posit}{'A'} : 'N'; $printline.="\t"; $printline.=(exists $ancestralalleles{$chrom}{$posit}{'B'}) ? $ancestralalleles{$chrom}{$posit}{'B'} : 'N'; $printline.="\t"; $printline.=(exists $ancestralalleles{$chrom}{$posit}{'D'}) ? $ancestralalleles{$chrom}{$posit}{'D'} : 'N'; $printline.="\t"; } else { $printline.='N'."\t".'N'."\t".'N'."\t"; } #%{$assignallele} $printline.="Genome: \t"; if (exists ${$assignallele}{$chrom} and exists ${$assignallele}{$chrom}{$posit}) { $printline.=(exists ${$assignallele}{$chrom}{$posit}{'A'}) ? ${$assignallele}{$chrom}{$posit}{'A'} : 'N'; $printline.="\t"; $printline.=(exists ${$assignallele}{$chrom}{$posit}{'B'}) ? ${$assignallele}{$chrom}{$posit}{'B'} : 'N'; $printline.="\t"; $printline.=(exists ${$assignallele}{$chrom}{$posit}{'D'}) ? ${$assignallele}{$chrom}{$posit}{'D'} : 'N'; $printline.="\t"; } else { $printline.='N'."\t".'N'."\t".'N'."\t"; } #%{$fixedAllele_3fillin} $printline.="Fillin: \t"; if (exists ${$fixedAllele_3fillin}{$chrom} and exists ${$fixedAllele_3fillin}{$chrom}{$posit}) { $printline.=(exists ${$fixedAllele_3fillin}{$chrom}{$posit}{'A'}) ? ${$fixedAllele_3fillin}{$chrom}{$posit}{'A'} : 'N'; $printline.="\t"; $printline.=(exists ${$fixedAllele_3fillin}{$chrom}{$posit}{'B'}) ? ${$fixedAllele_3fillin}{$chrom}{$posit}{'B'} : 'N'; $printline.="\t"; $printline.=(exists ${$fixedAllele_3fillin}{$chrom}{$posit}{'D'}) ? ${$fixedAllele_3fillin}{$chrom}{$posit}{'D'} : 'N'; $printline.="\t"; } else { $printline.='N'."\t".'N'."\t".'N'."\t"; } #%{$final_geno} $printline.="Final: \t"; if (exists ${$final_geno}{$chrom} and exists ${$final_geno}{$chrom}{$posit}) { $printline.=(exists ${$final_geno}{$chrom}{$posit}{'A'}) ? ${$final_geno}{$chrom}{$posit}{'A'} : 'N'; $printline.="\t"; $printline.=(exists ${$final_geno}{$chrom}{$posit}{'B'}) ? ${$final_geno}{$chrom}{$posit}{'B'} : 'N'; $printline.="\t"; $printline.=(exists ${$final_geno}{$chrom}{$posit}{'D'}) ? ${$final_geno}{$chrom}{$posit}{'D'} : 'N'; $printline.="\t"; } else { $printline.='N'."\t".'N'."\t".'N'."\t"; } #%{$fixedGeno_4fillin} $printline.="Geno: \t"; if (exists ${$fixedGeno_4fillin}{$chrom}) { my $fillin_geno=(exists ${$fixedGeno_4fillin}{$chrom}{$posit}) ? ${$fixedGeno_4fillin}{$chrom}{$posit} : 'N'; $printline.=$fillin_geno."\t"; } else { $printline.='N'."\t"; } #$test_run_phase $printline.=$test_run_phase."\n"; print ALLELELOG $printline; } } } ##COMMENT: Main($stage) SNP phasing $stage=10; print "\n(Main$stage)Step: phasing\n"; ### For test ### if ($test_run_phase) { my $hapcompassvcf="$RunDir/Clust$cluster_num/AABBDD.$cluster_num.hapcompass.vcf"; my $phasedsolution="$RunDir/Clust$cluster_num/AABBDD.$cluster_num.phased"; unless (HapcompassVcf($cluster_orivcf, $hapcompassvcf, $fixedGeno_4fillin, $corrected_sites, $vcfreferencer)) { print STDERR "(Main$stage)Error: prepare HapCompass VCF error\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tHapcompassVcf\n"; next; } unless (RunHapCompass(0, $fragmentfile, $hapcompassvcf, $ploidy, "$fragmentfile.hapcompass", $phasedsolution, ' ', $path_java, $path_hapcompassjar)) { print STDERR "(Main$stage)Error: HapCompass running error\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tHapCompass\n"; next; } my $phased_geno=dclone($fixedAllele_3fillin); # print "(Main$stage)Error: phased before ReadHcOut\n"; print Dumper $phased_geno; print "\n"; ### For test ### my $excluded_chroms={}; unless (ReadHcOut($phasedsolution, $inferred_genoploidy, $phased_geno, $excluded_chroms)) { print STDERR "(Main$stage)Error: HapCompass read hapcompass error\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tHapCompassOut\n"; next; } # print "(Main$stage)Error: phased after ReadHcOut\n"; print Dumper $phased_geno; print "\n"; ### For test ### $final_geno=$phased_geno; if (scalar(keys %{$excluded_chroms}) > 0) { my @temp_excluded=keys %{$excluded_chroms}; print CLUSTERLOG $cluster_num."\t?\t1\t$stage\tExcluded: @temp_excluded\n"; foreach (@temp_excluded) { delete ${$corrected_sites}{$_} if (exists ${$corrected_sites}{$_}); foreach (keys %{$corrected_sites}) { $corrected_num_allelic_sites+=scalar(keys %{${$corrected_sites}{$_}}); } # print "(Main$stage)Test: $corrected_num_allelic_sites\n"; } foreach my $readid (keys %{$readsum}) { my $test_excluded=1; foreach my $excludchr (@temp_excluded) { unless (exists ${$readsum}{$readid}{'ref'} and exists ${$readsum}{$readid}{'ref'}{$excludchr}) { $test_excluded=0; } } if ($test_excluded==1) { ${$readsum}{$readid}{'excluded'}++; delete ${$corrected_fragments}{$readid} if (exists ${$corrected_fragments}{$readid}); } if (exists ${$corrected_fragments}{$readid}) { foreach (@temp_excluded) { if (exists ${$corrected_fragments}{$readid}{$_}) { delete ${$corrected_fragments}{$readid}{$_}; unless (scalar(keys %{${$corrected_fragments}{$readid}})>0) { delete ${$corrected_fragments}{$readid}; } } } } } } } else { print "(Main$stage)Info: no need to run HapCompass\n"; print GENOLOG "(Main$stage)Info: no need to run HapCompass\n"; } if (1) { foreach my $chrom (keys %{$aabbdd_vcf_obj}) { print "(Main$stage)Test: AlleleTesting: chromosome $chrom\n" if ($debug); ### For test ### foreach my $posit (sort {$a <=> $b } keys %{${$aabbdd_vcf_obj}{$chrom}}) { print "(Main$stage)Test: AlleleTesting: positions $posit\n" if ($debug);### For test ### # next unless (exists ${$corrected_sites}{$chrom} and exists ${$corrected_sites}{$chrom}{$posit}); my $printline=$cluster_num."\t".$chrom."\t".$posit."\t".${${${$aabbdd_vcf_obj}{$chrom}}{$posit}}[2]."\t"; #%ancestralalleles $printline.="Diploid: \t"; if (exists $ancestralalleles{$chrom} and exists ${$ancestralalleles{$chrom}}{$posit}) { $printline.=(exists $ancestralalleles{$chrom}{$posit}{'A'} and $ancestralalleles{$chrom}{$posit}{'A'}=~/^\d+$/) ? $ancestralalleles{$chrom}{$posit}{'A'} : 'N'; $printline.="\t"; $printline.=(exists $ancestralalleles{$chrom}{$posit}{'B'} and $ancestralalleles{$chrom}{$posit}{'B'}=~/^\d+$/) ? $ancestralalleles{$chrom}{$posit}{'B'} : 'N'; $printline.="\t"; $printline.=(exists $ancestralalleles{$chrom}{$posit}{'D'} and $ancestralalleles{$chrom}{$posit}{'D'}=~/^\d+$/) ? $ancestralalleles{$chrom}{$posit}{'D'} : 'N'; $printline.="\t"; } else { $printline.='N'."\t".'N'."\t".'N'."\t"; } #%{$assignallele} $printline.="Genome: \t"; if (exists ${$assignallele}{$chrom} and exists ${${$assignallele}{$chrom}}{$posit}) { $printline.=(exists ${$assignallele}{$chrom}{$posit}{'A'}) ? ${$assignallele}{$chrom}{$posit}{'A'} : 'N'; $printline.="\t"; $printline.=(exists ${$assignallele}{$chrom}{$posit}{'B'}) ? ${$assignallele}{$chrom}{$posit}{'B'} : 'N'; $printline.="\t"; $printline.=(exists ${$assignallele}{$chrom}{$posit}{'D'}) ? ${$assignallele}{$chrom}{$posit}{'D'} : 'N'; $printline.="\t"; } else { $printline.='N'."\t".'N'."\t".'N'."\t"; } #%{$fixedAllele_3fillin} $printline.="Fillin: \t"; if (exists ${$fixedAllele_3fillin}{$chrom} and exists ${${$fixedAllele_3fillin}{$chrom}}{$posit}) { $printline.=(exists ${$fixedAllele_3fillin}{$chrom}{$posit}{'A'}) ? ${$fixedAllele_3fillin}{$chrom}{$posit}{'A'} : 'N'; $printline.="\t"; $printline.=(exists ${$fixedAllele_3fillin}{$chrom}{$posit}{'B'}) ? ${$fixedAllele_3fillin}{$chrom}{$posit}{'B'} : 'N'; $printline.="\t"; $printline.=(exists ${$fixedAllele_3fillin}{$chrom}{$posit}{'D'}) ? ${$fixedAllele_3fillin}{$chrom}{$posit}{'D'} : 'N'; $printline.="\t"; } else { $printline.='N'."\t".'N'."\t".'N'."\t"; } #%{$fixedGeno_4fillin} $printline.="Geno: \t"; if (exists ${$fixedGeno_4fillin}{$chrom}) { my $fillin_geno=(exists ${$fixedGeno_4fillin}{$chrom}{$posit}) ? ${$fixedGeno_4fillin}{$chrom}{$posit} : 'N'; $printline.=$fillin_geno."\t"; } else { $printline.='N'."\t"; } #%{$final_geno} $printline.="Final: \t"; if (exists ${$final_geno}{$chrom} and exists ${$final_geno}{$chrom}{$posit}) { $printline.=(exists ${$final_geno}{$chrom}{$posit}{'A'}) ? ${$final_geno}{$chrom}{$posit}{'A'} : 'N'; $printline.="\t"; $printline.=(exists ${$final_geno}{$chrom}{$posit}{'B'}) ? ${$final_geno}{$chrom}{$posit}{'B'} : 'N'; $printline.="\t"; $printline.=(exists ${$final_geno}{$chrom}{$posit}{'D'}) ? ${$final_geno}{$chrom}{$posit}{'D'} : 'N'; $printline.="\t"; } else { $printline.='N'."\t".'N'."\t".'N'."\t"; } #$test_run_phase $printline.=$test_run_phase."\n"; print ALLELELOG $printline; } } } if (0) {### Test %{$final_geno} ### foreach my $chrom (keys %{$final_geno}) { print "(Main$stage)Test: Chrom: $chrom\n"; foreach my $pos (keys %{${$assignallele}{$chrom}}) { print "(Main$stage)Test: Chrom: $chrom Pos: $pos\n"; if (defined ${${$assignallele}{$chrom}}{$pos}){ print "NOT defined\n"; } else { print "Defined\n"; } } } } ###Stage11: Get phlymorphic readids $stage=11; print "\n(Main$stage)Step: Get allelic reads\n"; ### For test ### ##Format: %{$final_geno}=(chr => (pos => (A => allele/?, B=> allele/?, D => allele/?))) ##Format: %{$corrected_fragments}=($readid => chrom => $partstart => $pos => $allele => $qual); # %polymorphismreadids=(readid => ('gen' => ( 'A' => ++, 'B' => ++, 'D' => ++), if ($corrected_num_allelic_sites>0) { # print "(Main$stage)Test: \$corrected_fragments\n"; print Dumper $corrected_fragments; print "\n"; ### For test ### # print "(Main$stage)Test: \$final_geno\n"; print Dumper $final_geno; print "\n"; ### For test ### (my $test_GPRcode, $polymorphismreadids)=&GetPolymorphicReads($corrected_fragments, $final_geno); } if (1) { print "(Main$stage)Test: Total mapped reads: ".$totalmappedreads."\n"; print "(Main$stage)Test: Total allelic reads: ".scalar(keys %{$polymorphismreadids})."\n"; print GENOLOG "(Main$stage)Test: Total mapped reads: ".$totalmappedreads."\n"; print GENOLOG "(Main$stage)Test: Total allelic reads: ".scalar(keys %{$polymorphismreadids})."\n"; } $assignallele={}; $fixedAllele_3fillin={}; $fixedGeno_4fillin={}; $final_geno={}; ###Stage12: Bam2fastq2 $stage=12; print "\n(Main$stage)Step: bam2fastq\n"; ### For test ### my ($test_bam2fastq, $fastqfiles, $rgfpkms, $clusterfpkm)=&Bam2FastQ2($cluter_oribam, $inferred_genoploidy, $readsum, $polymorphismreadids, "$RunDir/Clust$cluster_num/reads", 1, 0, 1, $path_samtools); if (! $test_bam2fastq) { print STDERR "(Main$stage)Error: Bam2FastQ2\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tBam2FastQ2\n"; next; } ##Format: %{$rgfpkms}=(chr => ('chr' => FPKM # 'read_group' => (RG1 => ('global' => FPKM, 'A' => FPKM, 'B' => FPKM, 'D' => FPKM) # 'allelic' => ('A' => FPKM, 'B' => FPKM, 'D' => FPKM) # RG2 => ...) if (1) { # print Dumper $rgfpkms; ### For test ### foreach my $idvchrom (keys %{$rgfpkms}) { if (exists ${$rgfpkms}{$idvchrom}{'chr'}) { print REFERFPKM "Clust$cluster_num\tChr\t".${$rgfpkms}{$idvchrom}{'chr'}."\n"; } if (exists ${$rgfpkms}{$idvchrom}{'allelic'}) { foreach (sort (keys %{${$rgfpkms}{$idvchrom}{'allelic'}})) { print REFERFPKM "Clust$cluster_num\tAllelic\t$_\t".${$rgfpkms}{$idvchrom}{'allelic'}{$_}."\n"; } } if (exists ${$rgfpkms}{$idvchrom}{'read_group'}) { foreach my $ind_rg (sort (keys %{${$rgfpkms}{$idvchrom}{'read_group'}})) { print REFERFPKM "Clust$cluster_num\tReadGroup\t$ind_rg"; foreach my $indg (sort (keys %{${$rgfpkms}{$idvchrom}{'read_group'}{$ind_rg}})) { print REFERFPKM "\t$indg\t".${$rgfpkms}{$idvchrom}{'read_group'}{$ind_rg}{$indg}; } print REFERFPKM "\n"; } } } } ##Format $clusterfpkm=('genomesize' => size, # 'cluster' => FPKM # 'read_group' => (RG1 => ('global' => FPKM, 'A' => FPKM, 'B' => FPKM, 'D' => FPKM) # 'allelic' => ('A' => FPKM, 'B' => FPKM, 'D' => FPKM) # RG2 => ...) if (1) { if (exists ${$clusterfpkm}{'genomesize'}){ print CLUSTFPKM "Clust$cluster_num\tCLUST\tGenomeSize:".${$clusterfpkm}{'genomesize'}."\n"; } else { print CLUSTFPKM "Clust$cluster_num\tCLUST\tGenomeSize:N\n"; } if (exists ${$clusterfpkm}{'cluster'}){ print CLUSTFPKM "Clust$cluster_num\tClustGlobal\t".${$clusterfpkm}{'cluster'}."\n"; } else { print CLUSTFPKM "Clust$cluster_num\tClustGlobal\tN\n"; } if (exists ${$clusterfpkm}{'allelic'}) { foreach (sort (keys %{${$clusterfpkm}{'allelic'}})) { print CLUSTFPKM "Clust$cluster_num\tAllelic\t$_\t".${$clusterfpkm}{'allelic'}{$_}."\n"; } } if (exists ${$clusterfpkm}{'read_group'}) { foreach my $ind_rg (sort (keys %{${$clusterfpkm}{'read_group'}})) { print CLUSTFPKM "Clust$cluster_num\tReadGroup\t$ind_rg"; foreach my $indg (sort (keys %{${$clusterfpkm}{'read_group'}{$ind_rg}})) { print CLUSTFPKM "\t$indg\t".${$clusterfpkm}{'read_group'}{$ind_rg}{$indg}; } print CLUSTFPKM "\n"; } } } $polymorphismreadids={}; $readsum={}; ### (Main13) Trinity $stage=13; print "\n(Main$stage)Step: Trinity\n"; ### For test ### my %fasta_assembled=(); my $test_2ndassembly=0; foreach (sort keys %{$fastqfiles}) { unless (defined ${$fastqfiles}{$_} and -s ${$fastqfiles}{$_}) { print STDERR "(Main$stage)Error: Geno: $_ fastq file empty or not exists: ${$fastqfiles}{$_}\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tTrinity-$_\n"; $test_2ndassembly=1; next; } unless (RunFqTrinity(${$fastqfiles}{$_}, "$RunDir/Clust$cluster_num/Clust$cluster_num.$_.trinity.fasta", $trinity_addcmd, $path_trinity)) { print STDERR "(Main$stage)Error: Trinity-$_\n"; unless (RunMira4(${$fastqfiles}{$_}, "$RunDir/Clust$cluster_num/mira4.$_.manifest", "$RunDir/Clust$cluster_num/Clust$cluster_num.$_.MIRA4.fasta", "MIRA4", 3, $path_mira4, $numthreads)) { print STDERR "(Main$stage)Error: MIRA4-$_\n"; unless (RunCap3(${$fastqfiles}{$_}, "$RunDir/Clust$cluster_num/Clust$cluster_num.$_.cap3.fasta", $path_cap3)) { print STDERR "(Main$stage)Error: CAP3-$_\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\t2ndAssembly-$_\n"; $test_2ndassembly=1; } else { $fasta_assembled{$_}="$RunDir/Clust$cluster_num/Clust$cluster_num.$_.cap3.fasta"; } } else { $fasta_assembled{$_}="$RunDir/Clust$cluster_num/Clust$cluster_num.$_.MIRA4.fasta"; } next; } else { $fasta_assembled{$_}="$RunDir/Clust$cluster_num/Clust$cluster_num.$_.trinity.fasta"; } } if ($test_2ndassembly==1) { print STDERR "(Main$stage)Error: 2nd assembly may partially failed\n"; next; } unless (chdir $RunDir) { print STDERR "(Main$stage)Error: can not chdir to : $RunDir\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tChDirAfter2ndassembly\n"; next; } ###Stage14: rename fasta $stage=14; print "\n(Main$stage)Step: FastaRenamer\n"; ### For test ### foreach (keys %fasta_assembled) { unless (RenameFasta($fasta_assembled{$_}, "$fasta_assembled{$_}.rename.fa", "Cluster${cluster_num}_${_}_", 9, "Geno=$inferred_genoploidy Chrom=$inferred_chrom")) { print STDERR "(Main$stage)Error: FastaRenamer: $_\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tFastaRenamer\n"; next; } unless (MoveFile("$fasta_assembled{$_}.rename.fa", "$RunDir/fasta/")) { print STDERR "(Main$stage)Error: MoveFile: $_\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tMoveFile\n"; next; } } ### merge fasta =notsure ### (Main14) CD-HIT $stage=13; my %fasta_cdhit=(); foreach (keys %fasta_assembled) { unless (&CdHitEst($fasta_assembled{$_}, "$fasta_assembled{$_}.cdhit.fasta", $cdhit_addcmd, $path_cdhitest)) { print STDERR "(Main$stage)Error: cdhit: $_\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tCdHitEst\n"; next; } else { push (@fasta_cdhit, "$_.cdhit.fasta"); unlink $_ if (-e $_); } } =cut ###Stage15: Cleaning $stage=15; print "\n(Main$stage)Step: cleaning\n"; ### For test ### unless (chdir $RunDir) { print STDERR "(Main$stage)Error: can not chdir to : $RunDir\n"; print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tChDirAtLAST\n"; next; } if ($cleanlog) { # sleep(2); unlink glob "$RunDir/Clust$cluster_num/*"; # unless (rmtree("$RunDir/Clust$cluster_num")) { # print STDERR "(Main$stage)Error: DeletePATH: $RunDir/Clust$cluster_num\n"; # print CLUSTERLOG $cluster_num."\tFail\t1\t$stage\tDeletePATH\n"; # } } ### Stage16: Ending $stage=16; print CLUSTERLOG $cluster_num."\tSucceed\t0\t$stage\t0\t$genomeinfer_from_reads\t$inferred_genoploidy\t\n"; } close CLUSTER; close CLUSTERLOG; close REFERFPKM; close CLUSTFPKM; close ALLELELOG; close GENOLOG; ##################################################################### ### sub functions ### ##################################################################### ### extract batch of sequence alignment from Bams, and index ### &GetBam(bam_arr, sequence_arr, output) ### Global:$cluster_num, $path_samtools ### Dependency: ### Note: ### Return: 1=success, 0=failed, 2=BAM no alignments sub GetBam { my ($EBfiles_bam_index, $EBseq_obj, $EBoutput, $EBoutnogroup)=@_; my $EBsubinfo='SUB(GetBam)'; my $EBsam_seq=join (' ', @{$EBseq_obj}); my $EBi=0; my @EBtemp_bams=(); return 0 if (scalar(@{$EBseq_obj})<1);###return error if no sequences return 1 if (-s $EBoutput and -s "$EBoutput.bai" and -s $EBoutnogroup and -s "$EBoutnogroup.bai"); ##COMMENT: extract bam from each # print STDERR "${EBsubinfo}Info: sequence to be extracted: $EBsam_seq\n";###for test### foreach my $EBind_bam (@{$EBfiles_bam_index}) { $EBi++; my $EBbamout; if (scalar(@{$EBfiles_bam_index}) == 1) { $EBbamout="$EBoutput.multihead.bam"; } else { $EBbamout="$EBoutput.$EBi.bam"; } my $EBcmd="$path_samtools view -b -h -F 4 $EBind_bam $EBsam_seq > $EBbamout"; if (! &exec_cmd_return($EBcmd)) { print STDERR "${EBsubinfo}Error: bam extract $EBsam_seq (Cluster: $cluster_num) from $EBind_bam failed\n"; return 0; } else { push (@EBtemp_bams, "$EBoutput.$EBi.bam"); } } ##COMMENT: merge bams if (scalar(@{$EBfiles_bam_index}) > 1) { my $EBmerge_bams=join(' ', @EBtemp_bams); my $EBcmd2="$path_samtools merge $EBoutput.multihead.bam $EBmerge_bams"; if (! &exec_cmd_return($EBcmd2)) { print STDERR "${EBsubinfo}Error: bam merge (Cluster: $cluster_num) from $EBmerge_bams failed\n"; return 0; } else { if (-s "$EBoutput.multihead.bam") { map {unlink($_)} @EBtemp_bams;###delete temporary files ### For test ### } else{ print STDERR "${EBsubinfo}Error: bam merge (Cluster: $cluster_num) from $EBmerge_bams not found\n"; return 0; } } } ##COMMENT: cleanheader my $EBtest_cleanheader=&SamCleanHeader("$EBoutput.multihead.bam", "$EBoutput.withRG.bam", "$EBoutput.noRG.bam", $EBseq_obj, $path_samtools); if ($EBtest_cleanheader==0) { print STDERR "${EBsubinfo}Error: bam header clean (Cluster: $cluster_num) failed\n"; return 0; } elsif ($EBtest_cleanheader==2) { print STDERR "${EBsubinfo}Warnings: no alignments in BAM\n"; return 2;### Note this ### } else { if ( -s "$EBoutput.noRG.bam" and -s "$EBoutput.withRG.bam") { unlink ("$EBoutput.multihead.bam") if (-s "$EBoutput.multihead.bam"); if (! &SortBam("$EBoutput.withRG.bam", "$EBoutput.withRG.st.bam", $path_samtools, ' ')) { print STDERR "${EBsubinfo}Error: BAM sort running +RG error: $EBoutput.withRG.bam\n"; return 0; } unlink "$EBoutput.withRG.bam" if (-s "$EBoutput.withRG.bam"); if (! &MoveFile("$EBoutput.withRG.st.bam", $EBoutput)) { print STDERR "${EBsubinfo}Error: BAM moving: $EBoutput.withRG.bam\n"; return 0; } if (! &IndexBam("$EBoutput", $path_samtools)) { print STDERR "${EBsubinfo}Error: BAM index running +RG error: $EBoutput\n"; return 0; } if (! &SortBam("$EBoutput.noRG.bam", "$EBoutput.noRG.st.bam", $path_samtools)) { print STDERR "${EBsubinfo}Error: BAM sort running +RG error: $EBoutput.noRG.bam\n"; return 0; } unlink "$EBoutput.noRG.bam" if (-s "$EBoutput.noRG.bam"); if (! &MoveFile("$EBoutput.noRG.st.bam", $EBoutnogroup)) { print STDERR "${EBsubinfo}Error: BAM moving: $EBoutput.withRG.bam\n"; return 0; } if (! &IndexBam($EBoutnogroup, $path_samtools)) { print STDERR "${EBsubinfo}Error: BAM index running +RG error: $EBoutnogroup\n"; return 0; } } else{ print STDERR "${EBsubinfo}Error: bam headerclean output (Cluster: $cluster_num) not found\n"; return 0; } } return 1; } ### Read FPKM for cluster ### &ReadFpkm($filefpkm) ### Global: $minimum_fpkm ### Dependency: ### Note: sub ReadFpkm { my ($RFfpkmin, $RFseqids_arrindex)=@_; my $RFsubinfo='SUB(Main::ReadFpkm)'; my @RFtest_expressed=(); my $RFtotalnum=scalar(@{$RFseqids_arrindex}); my %RFseqid=(); map {$RFseqid{$_}++} @{$RFseqids_arrindex}; my ($RFfpkm1, $RFfpkm2, $RFfpkm3, $RFfpkm4)=(0, 0, 0, 0); local *RFFPKMIN; close RFFPKMIN if (defined fileno(RFFPKMIN)); unless (open(RFFPKMIN, "< $RFfpkmin")) { print STDERR "${RFsubinfo}Error: can not open FPKM input\n"; return 0; } my $RFmatchednum=0; while (my $RFline=<RFFPKMIN>) { chomp $RFline; my @RFarr=split(/\t/, $RFline); if (exists $RFseqid{$RFarr[0]}) { $RFmatchednum++; $RFfpkm1=1 if ($RFarr[1] > $minimum_fpkm); $RFfpkm2=1 if ($RFarr[2] > $minimum_fpkm); $RFfpkm3=1 if ($RFarr[3] > $minimum_fpkm); $RFfpkm4=1 if ($RFarr[4] > $minimum_fpkm); if ($RFfpkm1==1 and $RFfpkm2==1 and $RFfpkm3==1 and $RFfpkm4==1) { last; } elsif ($RFmatchednum==$RFtotalnum) { last; } } } close RFFPKMIN; @RFtest_expressed=($RFfpkm1, $RFfpkm2, $RFfpkm3, $RFfpkm4); return (1, \@RFtest_expressed); } ### Test Expressed or not ### &TestExpressed(BAMin, $total_reads) ### Global: $path_samtools, $minimum_fpkm ### Dependency: ### Note: sub TestExpressed { my ($TEbamfile, $TEtotalreads)=@_; my $TEsubinfo='SUB(TestExpressed)'; my ($TEtestcode, $TEfpkm_hashindex)=&CalcFPKM($TEbamfile, $TEtotalreads, 0, $path_samtools); if (! $TEtestcode) { print STDERR "${TEsubinfo}Error: Calculate FPKM error\n"; return 1; } my $EPexpressed=0; foreach (keys %{$TEfpkm_hashindex}) { if (exists ${$TEfpkm_hashindex}{$_} and exists ${${$TEfpkm_hashindex}{$_}}{'unknown'} and ${${$TEfpkm_hashindex}{$_}}{'unknown'}>=$minimum_fpkm) { $EPexpressed=1; last; } } return (0, $EPexpressed); } ###Extract allele based VCF ref, var, geno ###&ExtractAllele(ref, var, geno) ###Example: &ExtractAllele('AA', 'TT,GG', 0/1/1, 1/2) ###Global: ###Dependency: ###Note: sub ExtractAllele { my ($EAref, $EAvar, $EAgeno, $EAreturn_code)=@_; #Format: %EAgeno_hash=(0 => 'AA', 1 => 'TT', 2 => 'GG') my %EAgeno_hash=(); $EAgeno_hash{0}=$EAref; my @EAvar_arr=split(/$geno_delimiter/,$EAvar); for (my $EAi=0; $EAi<scalar(@EAvar_arr);$EAi++) { $EAgeno_hash{$EAi+1}=$EAvar_arr[$EAi]; } #Format: %EAgeno2_hash=(0 => count, 1 => count, ...) my %EAgeno2_hash=(); #Format: @EAgeno_arr=(0, 1, 2) my @EAgeno_arr=(); if ($EAgeno eq '.') { push (@EAgeno_arr, '?'); } elsif ($EAgeno =~m/\//) { @EAgeno_arr=split(/\//, $EAgeno); foreach (@EAgeno_arr) { if ($_=~m/^\d$/) { $EAgeno2_hash{$_}++; } else { print STDERR "SUB(ExtractAllele)Error: non number genotype\n"; } } } else { print STDERR "SUB(ExtractAllele)Error: unknown genotype\n"; } my @EAgeno2_arr=sort {$a<=>$b} keys %EAgeno2_hash; if ($EAreturn_code ==1 ) { return (\%EAgeno_hash, \@EAgeno2_arr); } elsif ($EAreturn_code ==2) { return \@EAgeno_arr; } elsif ($EAreturn_code ==3) { return (\%EAgeno2_hash, \@EAgeno_arr); } } ### Group SNPs based on read length ### &GroupReads($ReadSam_obj, AABBDD_Vcf_obj) ### Global: $debug, $verbose ### Dependancy:&ReadVariantType, $min_mapq, $bam_genome_tag, $bam_chromo_tag ### Note: sub GroupReads { my ($GRaabbdd_samobj, $GRaabbdd_vcfobj)=@_; my $GRsubinfo="SUB(GroupReads)"; #Format: %GRreadid_by_allele=(chr => (pos => (allele1 => @readIDs, allele2 => @readids))) # my %GRreadid_by_allele=(); #Format: %GRreadfragments=(readid => (chrom => (pos => (geno1 => quality, geno2 => quality))); my %GRreadfragments=(); #Format: %GRreadid2genome=(readID=> ('A' =>1, 'B' =>1, 'C'=1)) my %GRreadid2genome=(); #Format: %GRreadidsum=(readid => ('gen' => ( 'A' => ++, 'B' => ++, 'D' => ++), # 'chr' => ( '1AL' => ++, '!BL' => ++, '2DL' => ++, ...), # 'shared' => ++/0, # 'mapped' => 1/0, # 'ref' => Reference=> ++ # 'range' => (Reference => ((start, end), (start2-end2)...) # 'excluded'=> 0/++) # ) # ); my %GRreadidsum=(); #Format: %GRallele_assign=($chr => ($pos => ('A' => (allele1 =>++, allele2 =>++), # 'B' => (allele1 =>++, allele2 =>++), # 'D' => (allele1 =>++, allele2 =>++))) my %GRallele_assign=(); my $GRtotalreads_unmapped=0; my $GRtotalreads_lowqual=0; ###Retrieve all reads into share group foreach my $GRchrom (@cluster_seqids) { ###COMMENT: retrieve all alignments mapped to this reference sequence my @GRchr_alignments=$GRaabbdd_samobj->get_features_by_location(-seq_id => "$GRchrom"); foreach my $GRind_align (@GRchr_alignments) { if ($GRind_align->flag & 0x0004) {# makesure mapped $GRtotalreads_unmapped++; next; } unless ($GRind_align->qual >= $min_mapq) {#filter mapping quality $GRtotalreads_lowqual++; next; } my $GRthisreadid=$GRind_align->name; ${$GRreadidsum{$GRthisreadid}}{'mapped'}++; ${$GRreadidsum{$GRthisreadid}}{'shared'}++; $GRreadidsum{$GRthisreadid}{'ref'}{$GRchrom}++; my @GRstartend=($GRind_align->start, $GRind_align->end); unless (defined $GRstartend[0] and $GRstartend[0]=~/^\d+$/ and defined $GRstartend[1] and $GRstartend[1]=~/^\d+$/) { print STDERR "${GRsubinfo}Test: undefined (Chr: $GRchrom) range for read: $GRthisreadid\n"; } else { push (@{$GRreadidsum{$GRthisreadid}{'range'}{$GRchrom}}, \@GRstartend); } ${$GRreadidsum{$GRthisreadid}}{'excluded'}=0; # next if (exists $GRreadidsum{$GRthisreadid});###Reduce mem my $GRtag_chrom=$GRind_align->get_tag_values("$bam_chromo_tag"); while ($GRtag_chrom=~/(\d[ABDLS]{1,2})/g) { ${${$GRreadidsum{$GRthisreadid}}{'chr'}}{$1}++; } my $GRgenome_tagvalue=$GRind_align->get_tag_values("$bam_genome_tag"); if ($GRgenome_tagvalue=~m/A/i) { ${$GRreadid2genome{$GRthisreadid}}{'A'}=1; ${${$GRreadidsum{$GRthisreadid}}{'gen'}}{'A'}++; } if ($GRgenome_tagvalue=~m/B/i) { ${$GRreadid2genome{$GRthisreadid}}{'B'}=1; ${${$GRreadidsum{$GRthisreadid}}{'gen'}}{'B'}++; } if ($GRgenome_tagvalue=~m/D/i) { ${$GRreadid2genome{$GRthisreadid}}{'D'}=1; ${${$GRreadidsum{$GRthisreadid}}{'gen'}}{'D'}++; } } } ### read allele for each reads foreach my $GRchrom (keys %{$GRaabbdd_vcfobj}) { my @GRpositions=sort {$a<=>$b} (keys %{${$GRaabbdd_vcfobj}{$GRchrom}}); print "${GRsubinfo}Test: Number of variations on $GRchrom: ", scalar(@GRpositions), "\n" if ($debug or $verbose); foreach my $GRind_pos (sort {$a <=> $b} @GRpositions) { print "${GRsubinfo}Test:\t".$GRchrom, "\t", "Pos: $GRind_pos\tRef:${${${$GRaabbdd_vcfobj}{$GRchrom}}{$GRind_pos}}[0]\tVar:${${${$GRaabbdd_vcfobj}{$GRchrom}}{$GRind_pos}}[1]\tGen:${${${$GRaabbdd_vcfobj}{$GRchrom}}{$GRind_pos}}[2]", "\n" if ($debug or $verbose); # my @GRallelearr=split(/\//, ${${${$GRaabbdd_vcfobj}{$GRchrom}}{$GRind_pos}}[2]); # my %GRallelehash=(); # map {$GRallelehash{$_}++} @GRallelearr; # my $GRnumallele=scalar(keys %GRallelehash); # if ($GRnumallele<1 or $GRnumallele>3) { # print STDERR "${GRsubinfo}Error: Chr:Pos $GRchrom:$GRind_pos: Number of allele <1 or >3\n"; # return 1; # } my $GRend_pos=$GRind_pos+length(${${${$GRaabbdd_vcfobj}{$GRchrom}}{$GRind_pos}}[0])-1; my @GRchr_alignments=(); @GRchr_alignments= $GRaabbdd_samobj->get_features_by_location(-seq_id => "$GRchrom", -start => "$GRind_pos", -end => "$GRend_pos"); foreach my $GRind_align (@GRchr_alignments) { my $GRthisreadid=$GRind_align->name; next if ($GRind_align->flag & 0x0004); ${$GRreadidsum{$GRthisreadid}}{'shared'}=0;# if ($GRnumallele>1); next unless ($GRind_align->qual >= $min_mapq); my $GRstrand='U'; if ($GRind_align->flag & 0x0040) { $GRstrand=1; } elsif ($GRind_align->flag & 0x0080) { $GRstrand=2; } #$GRalelecode: this read contains which allele genotype (0(ref)/1/2/3/.) my ($GRalelecode, $GRcapture_qual)=&ReadVariantType($GRind_pos, ${${${$GRaabbdd_vcfobj}{$GRchrom}}{$GRind_pos}}[0], ${${${$GRaabbdd_vcfobj}{$GRchrom}}{$GRind_pos}}[1], ${${${$GRaabbdd_vcfobj}{$GRchrom}}{$GRind_pos}}[2], $GRind_align, 2); unless ($GRalelecode =~ /^\d+$/) { # unless ($GRalelecode =~ /^\d+$/ and exists $GRallelehash{$GRalelecode}) { $GRalelecode='N'; # $GRcapture_qual='#'; # next; } # if ($GRnumallele>1) { ###For HapCompass fragments file if (! defined $GRcapture_qual or length($GRcapture_qual) !=1) { $GRcapture_qual='I'; ### The second highest phred+33 score } elsif (ord($GRcapture_qual)<33 or ord ($GRcapture_qual) >74) { $GRcapture_qual='I'; ### The second highest phred+33 score } if (exists $GRreadfragments{$GRthisreadid} and exists $GRreadfragments{$GRthisreadid}{$GRchrom} and exists $GRreadfragments{$GRthisreadid}{$GRchrom}{$GRind_pos} and exists $GRreadfragments{$GRthisreadid}{$GRchrom}{$GRind_pos}{$GRstrand} and exists $GRreadfragments{$GRthisreadid}{$GRchrom}{$GRind_pos}{$GRstrand}{$GRalelecode}) { if (ord($GRcapture_qual) > ord($GRreadfragments{$GRthisreadid}{$GRchrom}{$GRind_pos}{$GRstrand}{$GRalelecode})) { $GRreadfragments{$GRthisreadid}{$GRchrom}{$GRind_pos}{$GRstrand}{$GRalelecode}=$GRcapture_qual; } } else { $GRreadfragments{$GRthisreadid}{$GRchrom}{$GRind_pos}{$GRstrand}{$GRalelecode}=$GRcapture_qual; } # push (@{${${$GRreadid_by_allele{$GRchrom}}{$GRind_pos}}{$GRalelecode}}, $GRthisreadid); # } # else { # $GRreadfragments{$GRthisreadid}{$GRchrom}{$GRind_pos}{$GRstrand}{$GRalelecode}=$GRcapture_qual; # } } } } #Merge parts that can overlap foreach my $GRreadid (keys %GRreadidsum) { next unless (exists $GRreadidsum{$GRreadid}{'range'}); foreach my $GRchrom (keys %{$GRreadidsum{$GRreadid}{'range'}}) { my @GRarr=@{$GRreadidsum{$GRreadid}{'range'}{$GRchrom}}; # print "${GRsubinfo}Test: range before merge\n"; ### For test ### # print Dumper \@GRarr; ### For test ### my ($GRtestmerge, $GRmergearr)=&MergeRange(\@GRarr); unless (defined $GRtestmerge and $GRtestmerge>0) { print STDERR "${GRsubinfo}Error: mergerage failed\n"; return 1; } # print "${GRsubinfo}Test: range after merge\n";### For test ### # print Dumper $GRmergearr;### For test ### my %GRmergehash=(); map {$GRmergehash{$_->[0]}=$_->[1]} @{$GRmergearr}; # print "${GRsubinfo}Test: hash after merge\n";### For test ### # print Dumper \%GRmergehash;### For test ### $GRreadidsum{$GRreadid}{'merge'}{$GRchrom}=\%GRmergehash; } } if (1) { print "${GRsubinfo}Test: total reads: ", scalar(keys %GRreadidsum), "\n"; print "${GRsubinfo}Test: total reads unmapped: $GRtotalreads_unmapped\n"; print "${GRsubinfo}Test: total reads low-quality: $GRtotalreads_lowqual\n"; print "${GRsubinfo}Test: total allelic reads: ", scalar(keys %GRreadfragments), "\n"; } return (0, \%GRreadfragments, \%GRreadidsum); } ### intersect Bioranges into intervels ### &MergeRange(\@arr) ### Global: ### Dependency: ### Note: ### Example: [ [1, 14], [2, 10], [40, 60], [30,70], [71, 90]] => [[1,14], [40, 90]] sub MergeRange { my $MRrangeori=shift; my $MRsubinfo="SUB(MergeRange)"; my %MRrangehash=(); my %MRmergehash=(); my @MRretarr=(); if (scalar(@{$MRrangeori})==0) { print STDERR $MRsubinfo, "Error: empty range\n"; return 0; } elsif (scalar(@{$MRrangeori})==1) { # print $MRsubinfo, "Info: 1 range\n"; ### For test ### return (1, $MRrangeori); } foreach my $MRindarr (@{$MRrangeori}) { my ($MRstart, $MRend)=@{$MRindarr}; unless (defined $MRstart and $MRstart=~/^\d+$/ and defined $MRend and $MRend=~/^\d+$/) { print STDERR $MRsubinfo, "Error: non number range\n"; return 0; } if (exists $MRrangehash{$MRstart}) { $MRrangehash{$MRstart}=$MRend if ($MRend> $MRrangehash{$MRstart}); } else { $MRrangehash{$MRstart}=$MRend; } } # print $MRsubinfo, "Info: merge\n"; ### For test ### my $MRtest_first=0; my ($MRmin, $MRmax); my $MRprinted=0; foreach my $MRindstart (sort {$a <=> $b} keys %MRrangehash) { $MRtest_first++; if ($MRtest_first==1) { $MRmin=$MRindstart; $MRmax=$MRrangehash{$MRindstart}; next; } else { if ($MRindstart>$MRmin and $MRindstart <=($MRmax+1)) { if ($MRmax<$MRrangehash{$MRindstart}) { $MRmax=$MRrangehash{$MRindstart}; } } else { my @MRarr2=($MRmin, $MRmax); push (@MRretarr, \@MRarr2); $MRmin=$MRindstart; $MRmax=$MRrangehash{$MRindstart}; } } if ($MRtest_first==scalar(keys %MRrangehash)) { my @MRarr3=($MRmin, $MRmax); push (@MRretarr, \@MRarr3); } } # print Dumper \@MRretarr; ### For test ### return (1, \@MRretarr); } ### FillInVariations ###&FillInVariations() ###Global: $debug ###Dependency:&ExtractAllele ###Note ### Return (0=successful, 1=ExtraAlleles, 2=InsufficientAlleles, 3=Unknown) sub FillInVariations { my ($FIVfixallele_hashindex, $FIVvcf_obj, $FIVgenoploidy, $FIVpolymorphicstes, $FIVdepth)=@_; ##Format: %{$FIVdepth}=(chr => pos => allele => depth) my $FIVsubinfo ='SUB(FillInVariations)'; ##COMMENT: Test SUB(FillInVariations) successful or not my $FIVneed_runcompass=0;###Test need to run next step compass (if there is any unfixed allele) or not (if all alleles are fixed); # %{$FIVpolymorphicstes}{chr}{$pos} ##Format: %{$FIVfixallele_hashindex}=(chr => (pos => (A => allele/?, B=> allele/?, D => allele/?))) my $FIVfillinalleles=dclone($FIVfixallele_hashindex); ##Format: ${$FIVvcf_obj}{chr}->{pos}=(ref, var, gen/gen2, ...); ##Format: $FIVfixed_geno{chr}->{pos}='0/1/0'; ('A/B/D') my %FIVfixed_geno=(); ##COMMENT: decide which subgenome to output my %FIVgenohash=(); if ($FIVgenoploidy=~/A/) { $FIVgenohash{'A'}++; # print $FIVsubinfo, "AA\n"; ### For test ### } if ($FIVgenoploidy=~/B/) { $FIVgenohash{'B'}++; # print $FIVsubinfo, "BB\n"; ### For test ### } if ($FIVgenoploidy=~/D/) { $FIVgenohash{'D'}++; # print $FIVsubinfo, "DD\n"; ### For test ### } my $FIVploidy=scalar(keys %FIVgenohash); if ($FIVploidy<2 or $FIVploidy>3) { print $FIVsubinfo, "Error: Total ploidy: $FIVploidy\n";### For test ### return 1; } # print $FIVsubinfo, "Test: Total ploidy: $FIVploidy\n"; ### For test ### ##COMMENT: Fill in unknown alleles foreach my $FIVchrom (sort keys %{$FIVpolymorphicstes}) { foreach my $FIVpos (sort keys %{${$FIVpolymorphicstes}{$FIVchrom}}) { my @FIVallelecode=keys %{${$FIVpolymorphicstes}{$FIVchrom}{$FIVpos}}; ### Get read depth after clean my %FIValleledep=(); foreach (@FIVallelecode) { unless (exists ${$FIVdepth}{$FIVchrom} and exists ${$FIVdepth}{$FIVchrom}{$FIVpos} and exists ${$FIVdepth}{$FIVchrom}{$FIVpos}{$_} and ${$FIVdepth}{$FIVchrom}{$FIVpos}{$_}>0) { print STDERR $FIVsubinfo, "Error: depth==0 at Chr:Pos:Allele $FIVchrom:$FIVpos:$_\n"; return 1; } $FIValleledep{$_}=${$FIVdepth}{$FIVchrom}{$FIVpos}{$_}; } unless (scalar(keys %FIValleledep)>1) { print STDERR $FIVsubinfo, "Error: allele <1 at Chr:Pos $FIVchrom:$FIVpos\n"; return 1; } ###rephase geno hash my @FIVvcfgeno=(); if (scalar(@FIVallelecode)==3) { @FIVvcfgeno=@FIVallelecode; } elsif (scalar(@FIVallelecode)==2) { @FIVvcfgeno=@FIVallelecode; my $FIVmaxdepth=0; my $maxcount=0; my $FIVmaxallelecoce; foreach (@FIVallelecode) { if ($FIValleledep{$_}>$FIVmaxdepth) { $FIVmaxdepth=$FIValleledep{$_}; $maxcount=1; $FIVmaxallelecoce=$_; } elsif ($FIValleledep{$_}==$FIVmaxdepth) { $maxcount++; } } if (defined $FIVmaxallelecoce and $FIVmaxallelecoce=~/^\d+$/) { push (@FIVvcfgeno, $FIVmaxallelecoce); } else { if (exists ${$FIVvcf_obj}{$FIVchrom} and exists ${$FIVvcf_obj}{$FIVchrom}{$FIVpos} and defined ${${$FIVvcf_obj}{$FIVchrom}{$FIVpos}}[2] and ${${$FIVvcf_obj}{$FIVchrom}{$FIVpos}}[2]=~/^\d+\/\d+\/\d+$/) { my @FIVvcf_thisgeno=split(/\//, ${${$FIVvcf_obj}{$FIVchrom}{$FIVpos}}[2]); unless (scalar(@FIVvcf_thisgeno)==3) { print STDERR $FIVsubinfo, "Error: genotype not triple in VCF at Chr:Pos:Geno $FIVchrom:$FIVpos:${${$FIVvcf_obj}{$FIVchrom}{$FIVpos}}[2]\n"; return 1; } my %FIVvcf_genohash=(); map {$FIVvcf_genohash{$_}++} @FIVvcf_thisgeno; foreach (keys %FIVvcf_genohash) { if ($FIVvcf_genohash{$_}>=2) { push (@FIVvcfgeno, $_); } } } else { print STDERR $FIVsubinfo, "Error: error to retrieve genotype in VCF at Chr:Pos $FIVchrom:$FIVpos\n"; return 1; } } } else { print STDERR $FIVsubinfo, "Error: unknown fillin Ploidy: $FIVploidy AlleleNum: ".scalar(@FIVallelecode)." Allele @FIVallelecode at Chr:Pos $FIVchrom:$FIVpos\n"; return 1; } unless (scalar(@FIVvcfgeno)==3) { print STDERR $FIVsubinfo, "Error: ploidy !=3 at Chr:Pos $FIVchrom:$FIVpos, @FIVvcfgeno\n"; return 1; } ###Format: %vcfgenohash=(0 => ++, 1=> ++, 2 => ++); my %FIVvcfgenhash=(); map {$FIVvcfgenhash{$_}++} @FIVvcfgeno; my $FIVnum_allele_notsure=0; my ($FIVaa_alleles,$FIVbb_alleles,$FIVdd_alleles)=('?', '?', '?'); if (exists ${$FIVfillinalleles}{$FIVchrom} and exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}) { $FIVaa_alleles=${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'A'} if (exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'A'}); $FIVbb_alleles=${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'B'} if (exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'B'}); $FIVdd_alleles=${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'D'} if (exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'D'}); } my ($FIVmissing_aa, $FIVmissing_bb, $FIVmissing_dd)=(0, 0, 0); my %FIVallele_taken=(); if (exists $FIVgenohash{'A'}) { if ($FIVaa_alleles =~/^\d+$/ and exists $FIVvcfgenhash{$FIVaa_alleles}) { $FIVvcfgenhash{$FIVaa_alleles}--; $FIVallele_taken{$FIVaa_alleles}++; } else { $FIVnum_allele_notsure++; $FIVmissing_aa=1; } } if (exists $FIVgenohash{'B'}) { if ($FIVbb_alleles =~/^\d+$/ and exists $FIVvcfgenhash{$FIVbb_alleles}) { $FIVvcfgenhash{$FIVbb_alleles}--; $FIVallele_taken{$FIVbb_alleles}++; } else { $FIVnum_allele_notsure++; $FIVmissing_bb=1; } } if (exists $FIVgenohash{'D'}) { if ($FIVdd_alleles =~/^\d+$/ and exists $FIVvcfgenhash{$FIVdd_alleles}) { $FIVvcfgenhash{$FIVdd_alleles}--; $FIVallele_taken{$FIVdd_alleles}++; } else { $FIVnum_allele_notsure++; $FIVmissing_dd=1; } } my @FIVallele_left=(); foreach (keys %FIVvcfgenhash) { push (@FIVallele_left, $_) if ($FIVvcfgenhash{$_}>0); } if (scalar(@FIVallele_left)<1 and $FIVnum_allele_notsure>0) { print STDERR $FIVsubinfo, "Error: no left allele at $FIVchrom:$FIVpos\n";###For test### return 2; } my @FIVarr_geno_fix=(); if ($FIVnum_allele_notsure==0) { push (@FIVarr_geno_fix, ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'A'}) if (exists $FIVgenohash{'A'}); push (@FIVarr_geno_fix, ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'B'}) if (exists $FIVgenohash{'B'}); push (@FIVarr_geno_fix, ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'D'}) if (exists $FIVgenohash{'D'}); } elsif ($FIVnum_allele_notsure==1) { if (scalar(@FIVallele_left)!=1) { my @FIVallele_left_new=(); foreach (@FIVallele_left) { push (@FIVallele_left_new, $_) unless (exists $FIVallele_taken{$_}); } if (scalar(@FIVallele_left_new)!=1) { print STDERR $FIVsubinfo, "Error: extra at $FIVchrom: $FIVpos\n";###For test### print "AllelesLeft: @FIVallele_left_new\nAlleleNum: $FIVnum_allele_notsure\n";###For test### return 1; } else { @FIVallele_left=@FIVallele_left_new; } } ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'A'}=shift @FIVallele_left if ($FIVmissing_aa ==1); ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'B'}=shift @FIVallele_left if ($FIVmissing_bb ==1); ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'D'}=shift @FIVallele_left if ($FIVmissing_dd ==1); push (@FIVarr_geno_fix, ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'A'}) if (exists $FIVgenohash{'A'}); push (@FIVarr_geno_fix, ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'B'}) if (exists $FIVgenohash{'B'}); push (@FIVarr_geno_fix, ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'D'}) if (exists $FIVgenohash{'D'}); } elsif ($FIVnum_allele_notsure==2) { my $uniqueallele=0; if (scalar(@FIVallele_left)==1){###Check if only one allele left $FIVallele_left[1]=$FIVallele_left[0]; $uniqueallele=1; } if (scalar(@FIVallele_left)!=2) {###check if two allele left, return error if not print STDERR $FIVsubinfo, "Error: extra at $FIVchrom: $FIVpos\n";###For test### print "AllelesLeft: @FIVallele_left\nAlleleNum: $FIVnum_allele_notsure\n";###For test### return 1; } my ($FIVallele_aa,$FIVallele_bb, $FIVallele_dd)=('?', '?', '?'); if (exists $FIVgenohash{'A'}) { if ($FIVmissing_aa ==1 and scalar(@FIVallele_left)>0) { $FIVallele_aa=shift @FIVallele_left; if ($uniqueallele) { ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'A'}=$FIVallele_aa; } else { $FIVneed_runcompass=1; } } elsif (exists ${$FIVfillinalleles}{$FIVchrom} and exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos} and exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'A'}) { $FIVallele_aa=${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'A'}; } else { print STDERR $FIVsubinfo, "Error: AA allele at $FIVchrom: $FIVpos\n";###For test### return 3; } push (@FIVarr_geno_fix, $FIVallele_aa); } if (exists $FIVgenohash{'B'}) { if ($FIVmissing_bb ==1 and scalar(@FIVallele_left)>0) { $FIVallele_bb=shift @FIVallele_left; if ($uniqueallele) { ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'B'}=$FIVallele_bb; } else { $FIVneed_runcompass=1; } } elsif (exists ${$FIVfillinalleles}{$FIVchrom} and exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos} and exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'B'}) { $FIVallele_bb=${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'B'}; } else { print STDERR $FIVsubinfo, "Error: BB allele at $FIVchrom: $FIVpos\n";###For test### return 3; } push (@FIVarr_geno_fix, $FIVallele_bb); } if (exists $FIVgenohash{'D'}) { if ($FIVmissing_dd ==1 and scalar(@FIVallele_left)>0) { $FIVallele_dd=shift @FIVallele_left; if ($uniqueallele) { ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'D'}=$FIVmissing_dd; } else { $FIVneed_runcompass=1; } } elsif (exists ${$FIVfillinalleles}{$FIVchrom} and exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos} and exists ${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'D'}) { $FIVallele_dd=${$FIVfillinalleles}{$FIVchrom}{$FIVpos}{'D'}; } else { print STDERR $FIVsubinfo, "Error: DD allele at $FIVchrom: $FIVpos\n";###For test### return 3; } push (@FIVarr_geno_fix, $FIVallele_dd); } } elsif ($FIVnum_allele_notsure==3) { @FIVarr_geno_fix=@FIVvcfgeno; $FIVneed_runcompass=1; } ${$FIVfixed_geno{$FIVchrom}}{$FIVpos}=join('/', @FIVarr_geno_fix); # print $FIVsubinfo, "Test: Fixed Alleles: ".${$FIVfixed_geno{$FIVchrom}}{$FIVpos}."\t$FIVchrom: $FIVpos\n";# if ($debug); } } return (0, $FIVneed_runcompass, \%FIVfixed_geno, $FIVfillinalleles); } ### Get polymorphic reads for each geno ### &GetPolymorphicReads($fragment_corrected, $GPRfinalgeno) ### Global: ### Dependency: ### Note: sub GetPolymorphicReads { my ($GPRcorrfrag, $GPRfinalgeno)=@_; my $GPRsubinfo='SUB(GetPolymorphicReads)'; ##Format: %GPRexcludedreads=(readid => ++); my %GPRexcludedreads=(); ##Format: %GPRcoveredsites=(chr => pos => allele => ++); my %GPRcoveredsites=(); ##Format: %GPRreadcount=('A' => ++, 'B' => ++, 'D' => ++) my %GPRreadcount=('A' => 0, 'B' => 0, 'D' => 0); ##Format: %{$GPRfinalgeno}=(chr => (pos => (A => allele/?, B=> allele/?, D => allele/?))) ##Format: %{$GPRcorrfrag}=($readid => chrom => $partstart => $pos => $allele => $qual); ##Format: %GPRpolymorphismreadids=(readid => ('gen' => ( 'A' => ++, 'B' => ++, 'D' => ++), my %GPRpolymorphismreadids=(); my $errorcode=0; READID14: {foreach my $GPRthisreadid (keys %{$GPRcorrfrag}) { my %GPRassignreads=(); my %GPRthisreadsites=(); foreach my $GPRthischrom (keys %{${$GPRcorrfrag}{$GPRthisreadid}}) { foreach my $thisstart (keys %{${$GPRcorrfrag}{$GPRthisreadid}{$GPRthischrom}}) { foreach my $GPRthispos (keys %{${$GPRcorrfrag}{$GPRthisreadid}{$GPRthischrom}{$thisstart}}) { my @GPRthisallelearr=keys %{${$GPRcorrfrag}{$GPRthisreadid}{$GPRthischrom}{$thisstart}{$GPRthispos}}; unless (scalar(@GPRthisallelearr)==1 and defined $GPRthisallelearr[0] and $GPRthisallelearr[0]=~/^\d+$/) { print STDERR $GPRsubinfo, "Error: invalid allele at: Read:Chrom:Pos:Alleles $GPRthischrom:$thisstart:$GPRthispos:@GPRthisallelearr\n"; $errorcode++; last READID14; } my $thisallelecode=shift @GPRthisallelearr; $GPRthisreadsites{$GPRthischrom}{$GPRthispos}{$thisallelecode}++; if (exists ${$GPRfinalgeno}{$GPRthischrom} and exists ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}) { if (exists ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'A'} and ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'A'}=~/^\d+$/) { if ($thisallelecode eq ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'A'}) { $GPRassignreads{'A'}{'include'}++; } else { $GPRassignreads{'A'}{'exclude'}++; } } if (exists ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'B'} and ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'B'}=~/^\d+$/) { if ($thisallelecode eq ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'B'}) { $GPRassignreads{'B'}{'include'}++; } else { $GPRassignreads{'B'}{'exclude'}++; } } if (exists ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'D'} and ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'D'}=~/^\d+$/) { if ($thisallelecode eq ${$GPRfinalgeno}{$GPRthischrom}{$GPRthispos}{'D'}) { $GPRassignreads{'D'}{'include'}++; } else { $GPRassignreads{'D'}{'exclude'}++; } } } else { print STDERR $GPRsubinfo, "Error: not existed Read:Chr:Pos $GPRthisreadid:$GPRthischrom:$GPRthispos in \%finalgeno\n"; $errorcode++; next READID14; } } } } my @GPRthisread2geno=(); foreach my $GPRgeno (keys %GPRassignreads) { unless (exists $GPRassignreads{$GPRgeno}{'include'}) { push (@GPRthisread2geno, $GPRgeno); } } if (scalar(@GPRthisread2geno)==0) { $GPRexcludedreads{$GPRthisreadid}++; } else { foreach (@GPRthisread2geno) { $GPRpolymorphismreadids{$GPRthisreadid}{'gen'}{$_}++; $GPRreadcount{$_}++; } foreach my $GPRindchr (keys %GPRthisreadsites) { foreach my $GPRindpos (keys %{$GPRthisreadsites{$GPRindchr}}) { foreach my $GPRindallele (keys %{$GPRthisreadsites{$GPRindchr}{$GPRindpos}}) { $GPRcoveredsites{$GPRindchr}{$GPRindpos}{$GPRindallele}++; } } } } }}###READID14 if ($errorcode) { print STDERR $GPRsubinfo, "Error: errorcode==1\n"; return 0; } if (0) { print $GPRsubinfo, "Test: \%GPRpolymorphismreadids\n"; print Dumper \%GPRpolymorphismreadids; print "\n"; print $GPRsubinfo, "Test: \%GPRexcludedreads\n"; print Dumper \%GPRexcludedreads; print "\n"; print $GPRsubinfo, "Test: \%GPRcoveredsites\n"; print Dumper \%GPRcoveredsites; print "\n"; } foreach (sort keys %GPRreadcount) { print $GPRsubinfo, "Info: Geno:NumReads $_ $GPRreadcount{$_}\n"; } return (1, \%GPRpolymorphismreadids) } ### convert bam files into fastq ### Bam2FastQ2 ($bamin, 'ABD', %readsum, %allelicreads, outfqprefix_path, [map_code], [MAPQ_code], [RGaware], [path_samtools]) ### Global: ### Dependency: $totalreads_AABBDD $reads_per_rg{$_} ### Note: map_code (0=all, 1=mapped, 2=unmapped) ### Note: [RGaware] 0=false; 1=true sub Bam2FastQ2 { my ($BFQbamin, $BFQgeno, $BFQreadsum, $BFQallelicreads, $BFQoutfqprefix, $BFQmapcode, $BFQmapq, $BFQrg_aware, $BFQpath_samtools)=@_; local *BAMIN; local *BAMOUT; local *BAMKEEP; local *BAMSHARE; local *BAMALLELIC; local *BAMAA;local *BAMBB; local *BAMDD; local *ALLFQ; local *SHAREOUT; local *FQOUT; #Formar: %$BFQreadsum=(readid => ('gen' => ( 'A' => ++, 'B' => ++, 'D' => ++), # 'chr' => ( '1AL' => ++, '!BL' => ++, '2DL' => ++, ...), # 'shared' => ++/0, # $chrom => ($pos => (allele => quality)) # 'reads' => (1 => (seq1=>sequence, qual1=> quality), 2=> (seq1=>sequence, qual1=> quality), U => ...) # 'excluded' => 0/++ # ) # ); my $BFQsubinfo='SUB(Bam2FastQ2)'; $BFQpath_samtools='samtools' unless (defined $BFQpath_samtools); $BFQmapcode=0 unless (defined $BFQmapcode); $BFQmapq=0 unless (defined $BFQmapq); $BFQrg_aware=0 unless (defined $BFQrg_aware); my %BFQexcludedreads=(); my $BamKit_failure=0; my $BamKit_success=1; ##Format: %returnhash=(A => "A.fastq", B => b.fastq, D => D.fastq); my %returnhash=(); ##Format: %BFQfpkms=(chr => ('chr1' => FPKM # 'read_group' => (RG1 => ('global' => FPKM, 'A' => FPKM, 'B' => FPKM, 'D' => FPKM) # 'allelic' => ('A' => FPKM, 'B' => FPKM, 'D' => FPKM) # RG2 => ...) my %BFQfpkms=(); ##Format %BFQclusterfpkm=('genomesize' => size, # 'cluster' => FPKM # 'read_group' => (RG1 => ('global' => FPKM, 'A' => FPKM, 'B' => FPKM, 'D' => FPKM) # 'allelic' => ('A' => FPKM, 'B' => FPKM, 'D' => FPKM) # RG2 => ...) #Calculate overal FPKM using estimated Cluster size my %BFQclusterfpkm=(); ##Format: %BFQreadpair=(chr => (RG1 => (readid => 1 => ('A' => 1/0, 'B' =>1/0, 'D' => 1/0, 'shared' => 1/0) # 2 => ('A' => 1/0, 'B' =>1/0, 'D' => 1/0, 'shared' => 1/0) # 'U' => ('A' => 1/0, 'B' =>1/0, 'D' => 1/0, 'shared' => 1/0) # RG2...); my %BFQreadpair=(); my %BFQgenos=(); $BFQoutfqprefix='./' unless (defined $BFQoutfqprefix); my %BFQreflen=(); my $BFQouttestbam=0; ### Output BAMs for debugging # print "${BFQsubinfo}Test: \n\tBAM: $BFQbamin\n\tGeno: $BFQgeno\n\tFqPrefix: $BFQoutfqprefix\n\tMapcode: $BFQmapcode\n\tMapQ: $BFQmapq\n\tReadGroupAware: $BFQrg_aware\n\tSAMtools: $BFQpath_samtools\n";### For test ### unless (defined $BFQbamin and -s $BFQbamin) { print STDERR "${BFQsubinfo}Error: invalid BAM input\n"; return $BamKit_failure; } unless (defined $BFQgeno and $BFQgeno =~/^[ABD]+$/) { print STDERR "${BFQsubinfo}Error: unknown geno code: $BFQgeno\n"; return $BamKit_failure; } $BFQgenos{'A'}++ if ($BFQgeno=~/A/); $BFQgenos{'B'}++ if ($BFQgeno=~/B/); $BFQgenos{'D'}++ if ($BFQgeno=~/D/); # print "${BFQsubinfo}Test: \t"; map {print "Geno: $_\t"} (keys %BFQgenos); print "\n";### For test ### close BAMIN if (defined fileno(BAMIN)); unless (open(BAMIN, "$BFQpath_samtools view -h $BFQbamin | ")) { print STDERR "${BFQsubinfo}Error: open BAM: $BFQbamin \n"; return $BamKit_failure; } close BAMOUT if (defined fileno(BAMOUT)); unless (open (BAMOUT, " | samtools view -bhS - > $BFQbamin.excluded.bam")) { print STDERR "${BFQsubinfo}Error: write BAM: $BFQbamin.excluded.bam \n"; return $BamKit_failure; } if ($BFQouttestbam) { close BAMKEEP if (defined fileno(BAMKEEP)); unless (open (BAMKEEP, " | samtools view -bhS - > $BFQbamin.included.bam")) { print STDERR "${BFQsubinfo}Error: write BAM: $BFQbamin.included.bam \n"; return $BamKit_failure; } close BAMSHARE if (defined fileno(BAMSHARE)); unless (open(BAMSHARE, " | samtools view -bhS - > $BFQbamin.shared.bam")) { print STDERR "${BFQsubinfo}Error: write BAM: $BFQbamin.shared.bam \n"; return $BamKit_failure; } close BAMALLELIC if (defined fileno(BAMALLELIC)); unless (open(BAMALLELIC, " | samtools view -bhS - > $BFQbamin.allelic.bam")) { print STDERR "${BFQsubinfo}Error: write BAM: $BFQbamin.allelic.bam \n"; return $BamKit_failure; } if (exists $BFQgenos{'A'}) { close BAMAA if (defined fileno(BAMAA)); unless (open(BAMAA, " | samtools view -bhS - > $BFQbamin.AA.bam")) { print STDERR "${BFQsubinfo}Error: write BAM: $BFQbamin.AA.bam \n"; return $BamKit_failure; } } if (exists $BFQgenos{'B'}) { close BAMBB if (defined fileno(BAMBB)); unless (open(BAMBB, " | samtools view -bhS - > $BFQbamin.BB.bam")) { print STDERR "${BFQsubinfo}Error: write BAM: $BFQbamin.BB.bam \n"; return $BamKit_failure; } } if (exists $BFQgenos{'D'}) { close BAMDD if (defined fileno(BAMDD)); unless (open(BAMDD, " | samtools view -bhS - > $BFQbamin.DD.bam")) { print STDERR "${BFQsubinfo}Error: write BAM: $BFQbamin.DD.bam \n"; return $BamKit_failure; } } } my $BFQnumline=0; while (my $BFQline1=<BAMIN>) { $BFQnumline++; chomp $BFQline1; #Get reference seq length if ($BFQline1=~/^\@/) { if ($BFQline1=~/^\@SQ\s+SN:(\S+)\s+LN:(\d+)$/) { $BFQreflen{$1}=$2; } print BAMOUT $BFQline1."\n"; if ($BFQouttestbam) { print BAMKEEP $BFQline1."\n"; print BAMSHARE $BFQline1."\n"; print BAMALLELIC $BFQline1."\n"; print BAMAA $BFQline1."\n" if (exists $BFQgenos{'A'}); print BAMBB $BFQline1."\n" if (exists $BFQgenos{'B'}); print BAMDD $BFQline1."\n" if (exists $BFQgenos{'D'}); } next; } my @BFQarr=split(/\t/, $BFQline1); #Check column number if (scalar(@BFQarr)<11) { print STDERR "${BFQsubinfo}Warnings: col<11 at line $BFQnumline (Readid: $BFQarr[0]) in BAM $BFQbamin\n"; next; } #check if exists in hash my $BFQis_shared=0; # print "${BFQsubinfo}Test: readname: $BFQarr[0]\n"; ### For test ### unless (exists ${$BFQreadsum}{$BFQarr[0]}) { print BAMOUT $BFQline1."\n"; next; } if (exists ${$BFQreadsum}{$BFQarr[0]}{'excluded'} and ${$BFQreadsum}{$BFQarr[0]}{'excluded'}>0) { print BAMOUT $BFQline1."\n"; next; } if (exists ${$BFQreadsum}{$BFQarr[0]} and exists ${${$BFQreadsum}{$BFQarr[0]}}{'shared'} and ${${$BFQreadsum}{$BFQarr[0]}}{'shared'} > 0) { $BFQis_shared=1; } my $BFQis_allelic=0; my @BFQthisread_gens=(); if (exists ${$BFQallelicreads}{$BFQarr[0]}) { $BFQis_allelic=1; my @BFQtemp_gens=(); if (exists ${${$BFQallelicreads}{$BFQarr[0]}}{'gen'}) { @BFQtemp_gens=keys %{${${$BFQallelicreads}{$BFQarr[0]}}{'gen'}}; # print "${BFQsubinfo}Test: Geno: @BFQtemp_gens Read: $BFQarr[0]\n";### For test ### } else { print STDERR "${BFQsubinfo}Warnings: $BFQarr[0] no 'gen' key in BFQallelicreads\n"; $BFQexcludedreads{$BFQarr[0]}++; print BAMOUT $BFQline1."\n"; next; } foreach (@BFQtemp_gens) { push (@BFQthisread_gens, $_) if (exists $BFQgenos{$_}); } if (scalar(@BFQthisread_gens)<1 or scalar(@BFQthisread_gens)>3) { # print STDERR "${BFQsubinfo}Warnings: no subgenome assignments for read $BFQarr[0] at Chrom: Pos $BFQarr[2]:$BFQarr[3]\n";### For test ### $BFQexcludedreads{$BFQarr[0]}++; print BAMOUT $BFQline1."\n"; next; } } if ($BFQis_shared==0 and $BFQis_allelic==0) { # print STDERR "${BFQsubinfo}Warnings: read ($BFQarr[0]) is neither shared or allelic at Chrom:Pos $BFQarr[2]:$BFQarr[3]\n"; print BAMOUT $BFQline1."\n"; $BFQexcludedreads{$BFQarr[0]}++; next; } elsif ($BFQis_shared==1 and $BFQis_allelic==1) { print STDERR "${BFQsubinfo}Warnings: read ($BFQarr[0]) is both shared and allelic at Chrom:Pos $BFQarr[2]:$BFQarr[3]\n"; print BAMOUT $BFQline1."\n"; $BFQexcludedreads{$BFQarr[0]}++; next; } elsif ($BFQis_shared==1) { if ($BFQouttestbam) { print BAMAA $BFQline1."\n" if (exists $BFQgenos{'A'}); print BAMBB $BFQline1."\n" if (exists $BFQgenos{'B'}); print BAMDD $BFQline1."\n" if (exists $BFQgenos{'D'}); } } elsif ($BFQis_allelic==1) { if ($BFQouttestbam) { if (exists ${$BFQallelicreads}{$BFQarr[0]} and exists ${$BFQallelicreads}{$BFQarr[0]}{'gen'}) { print BAMAA $BFQline1."\n" if (exists $BFQgenos{'A'} and exists ${$BFQallelicreads}{$BFQarr[0]}{'gen'}{'A'}); print BAMBB $BFQline1."\n" if (exists $BFQgenos{'B'} and exists ${$BFQallelicreads}{$BFQarr[0]}{'gen'}{'B'}); print BAMDD $BFQline1."\n" if (exists $BFQgenos{'D'} and exists ${$BFQallelicreads}{$BFQarr[0]}{'gen'}{'D'}); } } } #check if mapped if ($BFQmapcode==1) { if ($BFQarr[1] & 0x0004) { print BAMOUT $BFQline1."\n"; next; } } elsif ($BFQmapcode==2) { unless ($BFQarr[1] & 0x0004) { print BAMOUT $BFQline1."\n"; next; } } ##check if MAPQ threshold next unless (defined $BFQarr[4] and $BFQarr[4]>=$BFQmapq); ##Get readgroup info my $BFQreadgroup='undefRG'; if ($BFQrg_aware==1) { if ($BFQline1=~/\tRG:Z:(\S+)/) { $BFQreadgroup=$1; } } ##check if mapped to reverse strand my $BFQread_id=$BFQarr[0]; my $BFQreadseq=$BFQarr[9]; my $BFQreadqual=$BFQarr[10]; if ($BFQarr[1] & 0x0010) {###0x0010 = reverse strand $BFQreadseq=reverse ($BFQreadseq); $BFQreadseq=~tr/ATCGatcg/TAGCtagc/; $BFQreadqual=reverse ($BFQreadqual); } ##check if one of pair and check R1 or R2 if ($BFQarr[1] & 0x0001) { if ($BFQarr[1] & 0x0040) {###read1 if ($BFQis_shared==1) { @{${${${$BFQreadsum}{$BFQread_id}}{'reads'}}{1}}=($BFQreadseq, $BFQreadqual); ${${${${$BFQreadpair{$BFQarr[2]}}{$BFQreadgroup}}{$BFQread_id}}{1}}{'shared'}++; } elsif ($BFQis_allelic==1) { @{${${${$BFQallelicreads}{$BFQread_id}}{'reads'}}{1}}=($BFQreadseq, $BFQreadqual); foreach (@BFQthisread_gens) { ${${${${$BFQreadpair{$BFQarr[2]}}{$BFQreadgroup}}{$BFQread_id}}{1}}{$_}++; } } } elsif ($BFQarr[1] & 0x0080) {###read2 if ($BFQis_shared==1) { @{${${${$BFQreadsum}{$BFQread_id}}{'reads'}}{2}}=($BFQreadseq, $BFQreadqual); ${${${${$BFQreadpair{$BFQarr[2]}}{$BFQreadgroup}}{$BFQread_id}}{2}}{'shared'}++; } elsif ($BFQis_allelic==1) { @{${${${$BFQallelicreads}{$BFQread_id}}{'reads'}}{2}}=($BFQreadseq, $BFQreadqual); foreach (@BFQthisread_gens) { ${${${${$BFQreadpair{$BFQarr[2]}}{$BFQreadgroup}}{$BFQread_id}}{2}}{$_}++; } } } else { print STDERR "${BFQsubinfo}Warnings: unknown R1 or R2 (FLAG: $BFQarr[1]) at line $BFQnumline (Readid: $BFQarr[0]) in BAM $BFQbamin\n"; next; } } else {####sing-end if ($BFQis_shared==1) { @{${${${$BFQreadsum}{$BFQread_id}}{'reads'}}{'U'}}=($BFQreadseq, $BFQreadqual); # ${${${${$BFQreadpair{$BFQarr[2]}}{$BFQreadgroup}}{$BFQread_id}}{'U'}}{'shared'}++; ### Ignore single read for FPKM } elsif ($BFQis_allelic==1) { @{${${${$BFQallelicreads}{$BFQread_id}}{'reads'}}{'U'}}=($BFQreadseq, $BFQreadqual); # foreach (@BFQthisread_gens) { # ${${${${$BFQreadpair{$BFQarr[2]}}{$BFQreadgroup}}{$BFQread_id}}{'U'}}{$_}++; ### Ignore single read for FPKM # } } } if ($BFQouttestbam) { if ($BFQis_shared==1) { print BAMSHARE $BFQline1."\n"; } elsif ($BFQis_allelic==1) { print BAMALLELIC $BFQline1."\n"; } print BAMKEEP $BFQline1."\n"; } } close BAMIN; close BAMOUT; if ($BFQouttestbam) { close BAMKEEP; close BAMSHARE; close BAMALLELIC; close BAMAA if (defined fileno(BAMAA)); close BAMBB if (defined fileno(BAMBB)); close BAMDD if (defined fileno(BAMDD)); } print "${BFQsubinfo}Warnings: excluded reads num: ".scalar(keys %BFQexcludedreads)."\n"; ###Output fastq (shared) my $BFQshared_fastq=$BFQoutfqprefix.'.shared.fastq'; my $BFQallfastq=$BFQoutfqprefix.'.all.fastq'; unlink $BFQshared_fastq if (-e $BFQshared_fastq); my $BFQnumshared=0; close ALLFQ if (defined fileno(ALLFQ)); unless (open(ALLFQ, "> $BFQallfastq")) { print STDERR "${BFQsubinfo}Error: can not write ALL Fastq: $BFQallfastq\n"; return $BamKit_failure; } close SHAREOUT if (defined fileno(FQOUT)); unless (open (SHAREOUT, ">$BFQshared_fastq")) { print STDERR "${BFQsubinfo}Error: can not write SHARED Fastq: $BFQshared_fastq\n"; return $BamKit_failure; } foreach my $BFQreadid_shared (keys %{$BFQreadsum}) { if (exists ${${$BFQreadsum}{$BFQreadid_shared}}{'shared'} and ${${$BFQreadsum}{$BFQreadid_shared}}{'shared'}>0 and exists ${${$BFQreadsum}{$BFQreadid_shared}}{'reads'}) { $BFQnumshared++; if (exists ${${${$BFQreadsum}{$BFQreadid_shared}}{'reads'}}{1}) { my ($BFQseq, $BFQqual)=@{${${${$BFQreadsum}{$BFQreadid_shared}}{'reads'}}{1}}; print SHAREOUT '@'.$BFQreadid_shared."/1\n$BFQseq\n+\n$BFQqual\n"; print ALLFQ '@'.$BFQreadid_shared."/1\n$BFQseq\n+\n$BFQqual\n"; } if (exists ${${${$BFQreadsum}{$BFQreadid_shared}}{'reads'}}{2}) { my ($BFQseq, $BFQqual)=@{${${${$BFQreadsum}{$BFQreadid_shared}}{'reads'}}{2}}; print SHAREOUT '@'.$BFQreadid_shared."/2\n$BFQseq\n+\n$BFQqual\n"; print ALLFQ '@'.$BFQreadid_shared."/2\n$BFQseq\n+\n$BFQqual\n"; } if (exists ${${${$BFQreadsum}{$BFQreadid_shared}}{'reads'}}{'U'}) { my ($BFQseq, $BFQqual)=@{${${${$BFQreadsum}{$BFQreadid_shared}}{'reads'}}{'U'}}; print SHAREOUT '@'.$BFQreadid_shared."\n$BFQseq\n+\n$BFQqual\n"; print ALLFQ '@'.$BFQreadid_shared."\n$BFQseq\n+\n$BFQqual\n"; } } } close SHAREOUT; ###Output Allele FQ my %BFQcount_geno2reads=('A' => 0, 'B' => 0, 'D' => 0); foreach my $BFQind_gen (keys %BFQgenos) { my $BFQname=$BFQoutfqprefix.'.'.$BFQind_gen.'.fastq'; unlink $BFQname if (-e $BFQname); if (-s $BFQshared_fastq) { unless (CopyFile($BFQshared_fastq, $BFQname)) { print STDERR "${BFQsubinfo}Error: copy file failed: $BFQname\n"; } } close FQOUT if (defined fileno(FQOUT)); unless (open (FQOUT, ">>$BFQname")) { print STDERR "${BFQsubinfo}Error: can not write Fastq: $BFQname\n"; return $BamKit_failure; } foreach my $BFQreadid_allelic (keys %{$BFQallelicreads}) { next unless (exists ${$BFQallelicreads}{$BFQreadid_allelic}{'gen'} and exists ${$BFQallelicreads}{$BFQreadid_allelic}{'gen'}{$BFQind_gen} and ${$BFQallelicreads}{$BFQreadid_allelic}{'gen'}{$BFQind_gen}>0); $BFQcount_geno2reads{$BFQind_gen}++; if (exists ${${$BFQallelicreads}{$BFQreadid_allelic}}{'reads'}) { if (exists ${${${$BFQallelicreads}{$BFQreadid_allelic}}{'reads'}}{1}) { my ($BFQseq, $BFQqual)=@{${${${$BFQallelicreads}{$BFQreadid_allelic}}{'reads'}}{1}}; print FQOUT '@'.$BFQreadid_allelic."/1\n$BFQseq\n+\n$BFQqual\n"; print ALLFQ '@'.$BFQreadid_allelic."/1\n$BFQseq\n+\n$BFQqual\n"; } if (exists ${${${$BFQallelicreads}{$BFQreadid_allelic}}{'reads'}}{2}) { my ($BFQseq, $BFQqual)=@{${${${$BFQallelicreads}{$BFQreadid_allelic}}{'reads'}}{2}}; print FQOUT '@'.$BFQreadid_allelic."/2\n$BFQseq\n+\n$BFQqual\n"; print ALLFQ '@'.$BFQreadid_allelic."/2\n$BFQseq\n+\n$BFQqual\n"; } if (exists ${${${$BFQallelicreads}{$BFQreadid_allelic}}{'reads'}}{'U'}) { my ($BFQseq, $BFQqual)=@{${${${$BFQallelicreads}{$BFQreadid_allelic}}{'reads'}}{'U'}}; print FQOUT '@'.$BFQreadid_allelic."\n$BFQseq\n+\n$BFQqual\n"; print ALLFQ '@'.$BFQreadid_allelic."\n$BFQseq\n+\n$BFQqual\n"; } } } close FQOUT; if ( -s $BFQname) { $returnhash{$BFQind_gen}=$BFQname; } elsif (-e $BFQname) { $returnhash{$BFQind_gen}=0; } } close ALLFQ; foreach (sort keys %BFQcount_geno2reads) { print $BFQsubinfo, "Info: NumReads(Geno:Shared:Allelic) $_:$BFQnumshared:$BFQcount_geno2reads{$_}\n"; } ### Calculate GetGenomeSize my ($BFQtest_cmd_genomesize, $BFQgenomesize)=&GetGenomeSize($BFQallfastq); unless ($BFQtest_cmd_genomesize==1 and $BFQgenomesize=~/^\d+$/ and $BFQgenomesize>0) { print STDERR "${BFQsubinfo}Error: unknown genome size\n"; return $BamKit_failure; } print "${BFQsubinfo}Info: Estimated Cluster size: $BFQgenomesize\n"; ### Paired reads Counts ##Format: %BFQreadpair=(chr => (RG1 => (readid => 1 => ('A' => 1/0, 'B' =>1/0, 'D' => 1/0, 'shared' => 1/0) ##Format: %BFQreadcounts=(chr => ('chr' => FPKM # 'read_group' => (RG1 => ('global' => FPKM, 'A' => FPKM, 'B' => FPKM, 'D' => FPKM) # 'allelic' => ('A' => FPKM, 'B' => FPKM, 'D' => FPKM) my %BFQreadcounts=(); #Format: %BFQoveralcounts=('cluster' => FPKM # 'read_group' => (RG1 => ('global' => FPKM, 'A' => FPKM, 'B' => FPKM, 'D' => FPKM) # 'allelic' => ('A' => FPKM, 'B' => FPKM, 'D' => FPKM) my %BFQoveralcounts=(); ##Format: %BFQreadcounted=(readid => ++) #test readid if counted or not for %BFQreadcounted my %BFQreadcounted=(); foreach my $BFQchrom (keys %BFQreadpair) { foreach my $BFQrg (keys %{$BFQreadpair{$BFQchrom}}) { foreach my $BFQreadid (keys %{${$BFQreadpair{$BFQchrom}}{$BFQrg}}) { if (exists ${${${$BFQreadpair{$BFQchrom}}{$BFQrg}}{$BFQreadid}}{1} and exists ${${${$BFQreadpair{$BFQchrom}}{$BFQrg}}{$BFQreadid}}{2}) { ${$BFQreadcounts{$BFQchrom}}{'chr'}++; ${${${$BFQreadcounts{$BFQchrom}}{'read_group'}}{$BFQrg}}{'global'}++; unless (exists $BFQreadcounted{$BFQreadid}) { $BFQoveralcounts{'cluster'}++; $BFQoveralcounts{'read_group'}{$BFQrg}{'global'}++; } if (exists ${${${${$BFQreadpair{$BFQchrom}}{$BFQrg}}{$BFQreadid}}{1}}{'shared'} and ${${${${$BFQreadpair{$BFQchrom}}{$BFQrg}}{$BFQreadid}}{1}}{'shared'} >0) {###shared foreach (keys %BFQgenos) { ${${${$BFQreadcounts{$BFQchrom}}{'read_group'}}{$BFQrg}}{$_}++; ${${$BFQreadcounts{$BFQchrom}}{'allelic'}}{$_}++; unless (exists $BFQreadcounted{$BFQreadid}) { $BFQoveralcounts{'read_group'}{$BFQrg}{$_}++; $BFQoveralcounts{'allelic'}{$_}++; $BFQreadcounted{$BFQreadid}++; } } } else {##allelic foreach (keys %BFQgenos) { if (exists ${${${${$BFQreadpair{$BFQchrom}}{$BFQrg}}{$BFQreadid}}{1}}{$_} and ${${${${$BFQreadpair{$BFQchrom}}{$BFQrg}}{$BFQreadid}}{1}}{$_} >0){ ${${${$BFQreadcounts{$BFQchrom}}{'read_group'}}{$BFQrg}}{$_}++; ${${$BFQreadcounts{$BFQchrom}}{'allelic'}}{$_}++; unless (exists $BFQreadcounted{$BFQreadid}) { $BFQoveralcounts{'read_group'}{$BFQrg}{$_}++; $BFQoveralcounts{'allelic'}{$_}++; $BFQreadcounted{$BFQreadid}++; } } } } } } } } ### Calculate FPKMs for each reference sequence foreach my $BFQchrom (keys %BFQreadcounts) { if (exists ${$BFQreadcounts{$BFQchrom}}{'chr'}) { if (exists $BFQreflen{$BFQchrom} and $BFQreflen{$BFQchrom}>0) { ${$BFQfpkms{$BFQchrom}}{'chr'}=${$BFQreadcounts{$BFQchrom}}{'chr'} * 10^9 / ($BFQreflen{$BFQchrom} * $totalreads_AABBDD); } else { print STDERR "${BFQsubinfo}Error: can not get ref ($BFQchrom) length from header of BAM: $BFQbamin\n"; ${$BFQfpkms{$BFQchrom}}{'chr'}='undef'; } } foreach ('A', 'B', 'D') { if (exists ${$BFQreadcounts{$BFQchrom}}{'allelic'} and exists ${${$BFQreadcounts{$BFQchrom}}{'allelic'}}{$_}) { ${${$BFQfpkms{$BFQchrom}}{'allelic'}}{$_}= ${${$BFQreadcounts{$BFQchrom}}{'allelic'}}{$_} * 10^9 / ($BFQreflen{$BFQchrom} * $totalreads_AABBDD); } else { ${${$BFQfpkms{$BFQchrom}}{'allelic'}}{$_}=0; } } foreach my $BFQindrg (keys %reads_per_rg) { if (exists ${$BFQreadcounts{$BFQchrom}}{'read_group'} and exists ${${$BFQreadcounts{$BFQchrom}}{'read_group'}}{$BFQindrg}) { foreach ('global', 'A', 'B', 'D') { if (exists ${${${$BFQreadcounts{$BFQchrom}}{'read_group'}}{$BFQindrg}}{$_}) { ${${${$BFQfpkms{$BFQchrom}}{'read_group'}}{$BFQindrg}}{$_}=${${${$BFQreadcounts{$BFQchrom}}{'read_group'}}{$BFQindrg}}{$_} * 10^9 / ($BFQreflen{$BFQchrom} * $reads_per_rg{$BFQindrg}); } else { ${${${$BFQfpkms{$BFQchrom}}{'read_group'}}{$BFQindrg}}{$_}=0; } } } else { foreach ('global', 'A', 'B', 'D') { ${${${$BFQfpkms{$BFQchrom}}{'read_group'}}{$BFQindrg}}{$_}=0; } } } } ### Calculate overal FPKMs into %BFQclusterfpkm %BFQoveralcounts if (defined $BFQgenomesize and $BFQgenomesize>0) { $BFQclusterfpkm{'genomesize'}=$BFQgenomesize; if (exists $BFQoveralcounts{'cluster'}) { $BFQclusterfpkm{'cluster'}=$BFQoveralcounts{'cluster'} * 10^9 / ($BFQgenomesize * $totalreads_AABBDD); } else { $BFQclusterfpkm{'cluster'}=0; } foreach my $BFQindrg (keys %reads_per_rg) { if (exists $BFQoveralcounts{'read_group'} and exists $BFQoveralcounts{'read_group'}{$BFQindrg}) { foreach ('global', 'A', 'B', 'D') { if (exists $BFQoveralcounts{'read_group'}{$BFQindrg}{$_}) { $BFQclusterfpkm{'read_group'}{$BFQindrg}{$_}=$BFQoveralcounts{'read_group'}{$BFQindrg}{$_} * 10^9 / ($BFQgenomesize * $reads_per_rg{$BFQindrg}); } else { $BFQclusterfpkm{'read_group'}{$BFQindrg}{$_}=0; } } } else { foreach ('global', 'A', 'B', 'D') { $BFQclusterfpkm{'read_group'}{$BFQindrg}{$_}=0; } } } foreach ('A', 'B', 'D') { if (exists $BFQoveralcounts{'allelic'} and exists $BFQoveralcounts{'allelic'}{$_}) { $BFQclusterfpkm{'allelic'}{$_}= $BFQoveralcounts{'allelic'}{$_} * 10^9 / ($BFQgenomesize * $totalreads_AABBDD); } else { $BFQclusterfpkm{'allelic'}{$_}=0; } } } else { $BFQclusterfpkm{'genomesize'}=0; } %BFQoveralcounts=(); %BFQreadcounted=(); %BFQreadcounts=(); if (0) {###Test cluster FPKM hash %BFQclusterfpkm print "${BFQsubinfo}Test: Reference FPKM\n"; print Dumper \%BFQfpkms; print "\n"; } if (0) {###Test cluster FPKM hash %BFQclusterfpkm print "${BFQsubinfo}Test: Cluster FPKM\n"; print Dumper \%BFQclusterfpkm; print "\n"; } return ($BamKit_success, \%returnhash, \%BFQfpkms, \%BFQclusterfpkm); } ### Estimate genome size by kmergenie ### &GetGenomeSize (fastq, addcmd, path_kmergenie) ### Global: ### Dependency: ### Note: sub GetGenomeSize { my ($GGSfastq, $GGSprefix, $GGSaddcmd, $GGSpath_kmergenie)=@_; my $GGSsubinfo='SUB(GetGenomeSize)'; $GGSprefix="$RunDir/kmergenie/MyFastq" unless (defined $GGSprefix); $GGSpath_kmergenie='kmergenie' unless (defined $GGSpath_kmergenie); $GGSaddcmd= ' -l 27 -k 87 -o '.$GGSprefix.' ' unless (defined $GGSaddcmd); my $GGSgenomesize=0; local *GGSIN; my @GGoldfiles=glob "$RunDir/kmergenie/*"; foreach (@GGoldfiles){ unlink @GGoldfiles if (-e @GGoldfiles); } unless (defined $GGSfastq and -s $GGSfastq) { print STDERR "${GGSsubinfo}Error: invalid fastq input\n"; return 0; } unless (exec_cmd_return("$GGSpath_kmergenie $GGSfastq $GGSaddcmd >>kmergenie.log 2>>kmergenie.err")) { print STDERR "${GGSsubinfo}Error: invalid fastq input\n"; unlink glob("${GGSprefix}*"); return 0; } if (-s "${GGSprefix}_report.html") { close GSSIN if (defined fileno(GSSIN)); unless (open (GGSIN, "< ${GGSprefix}_report.html")) { print STDERR "${GGSsubinfo}Error: can not open kmergenie report: ${GGSprefix}_report.html\n"; unlink glob("${GGSprefix}*"); return 0; } while (my $GGSline=<GGSIN>) { if ($GGSline=~/Predicted\s+assembly\s+size:\s+(\d+)\s+bp/) { $GGSgenomesize=$1; last; } } close GSSIN; } if ($GGSgenomesize>0) { unlink glob("${GGSprefix}*"); return (1, $GGSgenomesize); } else { print STDERR "${GGSsubinfo}Error: failed kmergenie genome size\n"; unlink glob("${GGSprefix}*"); return 0; } }
37.593372
334
0.638539
73d570b5b871364c23e0f3ebda6139df3ad9b361
841
pm
Perl
auto-lib/Paws/WAFV2/ListTagsForResourceResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
164
2015-01-08T14:58:53.000Z
2022-02-20T19:16:24.000Z
auto-lib/Paws/WAFV2/ListTagsForResourceResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
348
2015-01-07T22:08:38.000Z
2022-01-27T14:34:44.000Z
auto-lib/Paws/WAFV2/ListTagsForResourceResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
87
2015-04-22T06:29:47.000Z
2021-09-29T14:45:55.000Z
package Paws::WAFV2::ListTagsForResourceResponse; use Moose; has NextMarker => (is => 'ro', isa => 'Str'); has TagInfoForResource => (is => 'ro', isa => 'Paws::WAFV2::TagInfoForResource'); has _request_id => (is => 'ro', isa => 'Str'); ### main pod documentation begin ### =head1 NAME Paws::WAFV2::ListTagsForResourceResponse =head1 ATTRIBUTES =head2 NextMarker => Str When you request a list of objects with a C<Limit> setting, if the number of objects that are still available for retrieval exceeds the limit, WAF returns a C<NextMarker> value in the response. To retrieve the next batch of objects, provide the marker from the prior call in your next request. =head2 TagInfoForResource => L<Paws::WAFV2::TagInfoForResource> The collection of tagging definitions for the resource. =head2 _request_id => Str =cut 1;
22.72973
83
0.726516
73d16e114cfcff22bcfafd0f3c7751b99da73faa
493
t
Perl
t/0.90/can/Data_Object_Code_Func_Curry_mapping.t
srchulo/do
d3c4ccecf33d1cf83d64b1c15666d0282a89e4f3
[ "Apache-2.0" ]
null
null
null
t/0.90/can/Data_Object_Code_Func_Curry_mapping.t
srchulo/do
d3c4ccecf33d1cf83d64b1c15666d0282a89e4f3
[ "Apache-2.0" ]
null
null
null
t/0.90/can/Data_Object_Code_Func_Curry_mapping.t
srchulo/do
d3c4ccecf33d1cf83d64b1c15666d0282a89e4f3
[ "Apache-2.0" ]
null
null
null
use 5.014; use strict; use warnings; use Test::More; # POD =name mapping =usage my @data = $self->mapping; =description Returns the ordered list of named function object arguments. =signature mapping() : (Str) =type method =cut # TESTING use Data::Object::Code::Func::Curry; can_ok "Data::Object::Code::Func::Curry", "mapping"; my @data; @data = Data::Object::Code::Func::Curry->mapping(); is @data, 2; is $data[0], 'arg1'; is $data[1], '@args'; ok 1 and done_testing;
10.270833
60
0.657201
73dc51da7e121b9155f8f4a6dd847b426d32dbbd
889
pm
Perl
modules/EnsEMBL/Web/ViewConfig/Location/ChromosomeImage.pm
amonida/ensembl-webcode
284a8c633fdcf72575f18c11ac0657ee0919e270
[ "Apache-2.0", "MIT" ]
null
null
null
modules/EnsEMBL/Web/ViewConfig/Location/ChromosomeImage.pm
amonida/ensembl-webcode
284a8c633fdcf72575f18c11ac0657ee0919e270
[ "Apache-2.0", "MIT" ]
null
null
null
modules/EnsEMBL/Web/ViewConfig/Location/ChromosomeImage.pm
amonida/ensembl-webcode
284a8c633fdcf72575f18c11ac0657ee0919e270
[ "Apache-2.0", "MIT" ]
null
null
null
=head1 LICENSE Copyright [1999-2014] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::ViewConfig::Location::ChromosomeImage; use strict; use base qw(EnsEMBL::Web::ViewConfig); sub init { my $self = shift; $self->add_image_config('Vmapview', 'nodas'); $self->title = 'Chromosome Image'; } 1;
27.78125
100
0.766029
ed112c4fe38c9fd5c5b9927cd16d3247d752e092
1,024
pm
Perl
lib/Google/Ads/GoogleAds/V5/Resources/TopicView.pm
PierrickVoulet/google-ads-perl
bc9fa2de22aa3e11b99dc22251d90a1723dd8cc4
[ "Apache-2.0" ]
null
null
null
lib/Google/Ads/GoogleAds/V5/Resources/TopicView.pm
PierrickVoulet/google-ads-perl
bc9fa2de22aa3e11b99dc22251d90a1723dd8cc4
[ "Apache-2.0" ]
null
null
null
lib/Google/Ads/GoogleAds/V5/Resources/TopicView.pm
PierrickVoulet/google-ads-perl
bc9fa2de22aa3e11b99dc22251d90a1723dd8cc4
[ "Apache-2.0" ]
null
null
null
# Copyright 2020, Google LLC # # 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. package Google::Ads::GoogleAds::V5::Resources::TopicView; use strict; use warnings; use base qw(Google::Ads::GoogleAds::BaseEntity); use Google::Ads::GoogleAds::Utils::GoogleAdsHelper; sub new { my ($class, $args) = @_; my $self = {resourceName => $args->{resourceName}}; # Delete the unassigned fields in this object for a more concise JSON payload remove_unassigned_fields($self, $args); bless $self, $class; return $self; } 1;
29.257143
79
0.735352
ed03680b0ecf2c72a0db083d7208f21b062202c5
322,930
pl
Perl
tools/test.pl
qiantu88/hashcat
1493bc01cfbf3fe0b7f4f639e43813f590439a4d
[ "MIT" ]
1
2018-12-28T05:42:49.000Z
2018-12-28T05:42:49.000Z
tools/test.pl
qiantu88/hashcat
1493bc01cfbf3fe0b7f4f639e43813f590439a4d
[ "MIT" ]
null
null
null
tools/test.pl
qiantu88/hashcat
1493bc01cfbf3fe0b7f4f639e43813f590439a4d
[ "MIT" ]
null
null
null
#!/usr/bin/env perl ## ## Author......: See docs/credits.txt ## License.....: MIT ## ## ## Installation script for all perl and python modules: ## ## tools/install_modules.sh ## ## ## If you want to add a new hash mode, follow the STEP comments. ## use strict; use warnings; use Authen::Passphrase::LANManager; use Authen::Passphrase::MySQL323; use Authen::Passphrase::NTHash; use Authen::Passphrase::PHPass; use Convert::EBCDIC qw (ascii2ebcdic); use Crypt::CBC; use Crypt::DES; use Crypt::Digest::RIPEMD160 qw (ripemd160_hex); use Crypt::Digest::Whirlpool qw (whirlpool_hex); use Crypt::ECB qw (encrypt); use Crypt::Eksblowfish::Bcrypt qw (bcrypt en_base64); use Crypt::GCrypt; use Crypt::Mode::CBC; use Crypt::Mode::ECB; use Crypt::MySQL qw (password41); use Crypt::OpenSSH::ChachaPoly; use Crypt::PBKDF2; use Crypt::RC4; use Crypt::Rijndael; use Crypt::ScryptKDF qw (scrypt_hash scrypt_raw scrypt_b64); use Crypt::Skip32; use Crypt::Twofish; use Crypt::UnixCrypt_XS qw (crypt_rounds fold_password base64_to_int24 block_to_base64 int24_to_base64); use Digest::MD4 qw (md4 md4_hex); use Digest::MD5 qw (md5 md5_hex); use Digest::SHA qw (sha1 sha256 sha384 sha512 sha1_hex sha224_hex sha256_hex sha384_hex sha512_hex hmac_sha1 hmac_sha256 hmac_sha512); use Digest::SHA1; use Digest::SHA3 qw (sha3_224_hex sha3_256_hex sha3_384_hex sha3_512_hex); use Digest::Keccak qw (keccak_224_hex keccak_256_hex keccak_384_hex keccak_512_hex); use Digest::HMAC qw (hmac hmac_hex); use Digest::BLAKE2 qw (blake2b_hex); use Digest::GOST qw (gost gost_hex); use Digest::HMAC_MD5 qw (hmac_md5); use Digest::CRC qw (crc32); use Digest::CMAC; use Digest::SipHash qw (siphash); use Digest::Perl::MD5; use Encode; use JSON; use MIME::Base32 qw (encode_base32 decode_base32); use MIME::Base64 qw (encode_base64 decode_base64 encode_base64url decode_base64url); use Net::DNS::RR::NSEC3; use Net::DNS::SEC; use POSIX qw (strftime ceil); use Text::Iconv; my $hashcat = "./hashcat"; my $MAX_LEN = 55; ## STEP 1: Add your hash mode to this array. # # This array contains all supported hash modes. # ## my $MODES = [ 0, 10, 11, 12, 20, 21, 22, 23, 30, 40, 50, 60, 100, 101, 110, 111, 112, 120, 121, 122, 125, 130, 131, 132, 133, 140, 141, 150, 160, 200, 300, 400, 500, 600, 900, 1000, 1100, 1300, 1400, 1410, 1411, 1420, 1430, 1440, 1441, 1450, 1460, 1500, 1600, 1700, 1710, 1711, 1720, 1730, 1740, 1722, 1731, 1750, 1760, 1800, 2100, 2400, 2410, 2500, 2600, 2611, 2612, 2711, 2811, 3000, 3100, 3200, 3710, 3711, 3300, 3500, 3610, 3720, 3800, 3910, 4010, 4110, 4210, 4300, 4400, 4500, 4520, 4521, 4522, 4600, 4700, 4800, 4900, 5100, 5300, 5400, 5500, 5600, 5700, 5800, 6000, 6100, 6300, 6400, 6500, 6600, 6700, 6800, 6900, 7000, 7100, 7200, 7300, 7400, 7500, 7700, 7701, 7800, 7801, 7900, 8000, 8100, 8200, 8300, 8400, 8500, 8600, 8700, 8900, 9100, 9200, 9300, 9400, 9500, 9600, 9700, 9800, 9900, 10000, 10100, 10200, 10300, 10400, 10500, 10600, 10700, 10800, 10900, 11000, 11100, 11200, 11300, 11400, 11500, 11600, 11700, 11750, 11760, 11800, 11850, 11860, 11900, 12000, 12001, 12100, 12200, 12300, 12400, 12600, 12700, 12800, 12900, 13000, 13100, 13200, 13300, 13400, 13500, 13600, 13800, 13900, 14000, 14100, 14400, 14700, 14800, 14900, 15000, 15100, 15200, 15300, 15400, 15500, 15600, 15700, 15900, 16000, 16100, 16200, 16300, 16400, 16500, 16600, 16700, 16800, 16900, 17300, 17400, 17500, 17600, 17700, 17800, 17900, 18000, 18100, 18200, 18300, 18400, 18500, 18600, 99999 ]; ## STEP 2a: If your hash mode does not need a salt, add it to this array. # # This array contains all unsalted hash-modes that are handled in the 'default' # branches in all three single, passthrough and verify test functions. There # still are some unsalted hash-modes which are handled differently and are not # listed here; they are caught in separate if conditions accordingly. # ## my $COMMON_UNSALTED_MODES = [ 0, 100, 101, 133, 200, 300, 600, 900, 1000, 1300, 1400, 1700, 2600, 3500, 4300, 4400, 4500, 4600, 4700, 5100, 5700, 6000, 6100, 6900, 9900, 10800, 11500, 11700, 11800, 16400, 17300, 17400, 17500, 17600, 17700, 17800, 17900, 18000, 18500, 99999 ]; ## STEP 2b: If your hash-mode has a salt without any specific syntax, ## add it to this array. Else look for STEP 2c (several spots). # # Same as above, only for salted hashes without specific salt formats. # ## my $COMMON_DEFAULT_SALTED_MODES = [ 10, 20, 23, 30, 40, 50, 60, 110, 120, 130, 140, 150, 160, 1410, 1420, 1430, 1440, 1450, 1460, 1710, 1720, 1730, 1740, 1750, 1760, 3610, 3710, 3720, 3910, 4010, 4110, 4210, 11750, 11760, 11850, 11860, 18100 ]; # Arrays for hash modes with maximum password length 15 my $LESS_FIFTEEN = [500, 1600, 1800, 3200, 6300, 7400, 10500, 10700]; # Arrays for hash modes with unusual salts my $ALLOW_LONG_SALT = [ 2500, 4520, 4521, 5500, 5600, 7100, 7200, 7300, 9400, 9500, 9600, 9700, 9800, 10400, 10500, 10600, 10700, 1100, 11000, 11200, 11300, 11400, 11600, 12600, 13500, 13800, 15000, 16900 ]; my $IS_UTF16LE = [ 30, 40, 130, 131, 132, 133, 140, 141, 1000, 1100, 1430, 1440, 1441, 1730, 1740, 1731, 5500, 5600, 8000, 9400, 9500, 9600, 9700, 9800, 11600, 13500, 13800 ]; my $LOTUS_MAGIC_TABLE = [ 0xbd, 0x56, 0xea, 0xf2, 0xa2, 0xf1, 0xac, 0x2a, 0xb0, 0x93, 0xd1, 0x9c, 0x1b, 0x33, 0xfd, 0xd0, 0x30, 0x04, 0xb6, 0xdc, 0x7d, 0xdf, 0x32, 0x4b, 0xf7, 0xcb, 0x45, 0x9b, 0x31, 0xbb, 0x21, 0x5a, 0x41, 0x9f, 0xe1, 0xd9, 0x4a, 0x4d, 0x9e, 0xda, 0xa0, 0x68, 0x2c, 0xc3, 0x27, 0x5f, 0x80, 0x36, 0x3e, 0xee, 0xfb, 0x95, 0x1a, 0xfe, 0xce, 0xa8, 0x34, 0xa9, 0x13, 0xf0, 0xa6, 0x3f, 0xd8, 0x0c, 0x78, 0x24, 0xaf, 0x23, 0x52, 0xc1, 0x67, 0x17, 0xf5, 0x66, 0x90, 0xe7, 0xe8, 0x07, 0xb8, 0x60, 0x48, 0xe6, 0x1e, 0x53, 0xf3, 0x92, 0xa4, 0x72, 0x8c, 0x08, 0x15, 0x6e, 0x86, 0x00, 0x84, 0xfa, 0xf4, 0x7f, 0x8a, 0x42, 0x19, 0xf6, 0xdb, 0xcd, 0x14, 0x8d, 0x50, 0x12, 0xba, 0x3c, 0x06, 0x4e, 0xec, 0xb3, 0x35, 0x11, 0xa1, 0x88, 0x8e, 0x2b, 0x94, 0x99, 0xb7, 0x71, 0x74, 0xd3, 0xe4, 0xbf, 0x3a, 0xde, 0x96, 0x0e, 0xbc, 0x0a, 0xed, 0x77, 0xfc, 0x37, 0x6b, 0x03, 0x79, 0x89, 0x62, 0xc6, 0xd7, 0xc0, 0xd2, 0x7c, 0x6a, 0x8b, 0x22, 0xa3, 0x5b, 0x05, 0x5d, 0x02, 0x75, 0xd5, 0x61, 0xe3, 0x18, 0x8f, 0x55, 0x51, 0xad, 0x1f, 0x0b, 0x5e, 0x85, 0xe5, 0xc2, 0x57, 0x63, 0xca, 0x3d, 0x6c, 0xb4, 0xc5, 0xcc, 0x70, 0xb2, 0x91, 0x59, 0x0d, 0x47, 0x20, 0xc8, 0x4f, 0x58, 0xe0, 0x01, 0xe2, 0x16, 0x38, 0xc4, 0x6f, 0x3b, 0x0f, 0x65, 0x46, 0xbe, 0x7e, 0x2d, 0x7b, 0x82, 0xf9, 0x40, 0xb5, 0x1d, 0x73, 0xf8, 0xeb, 0x26, 0xc7, 0x87, 0x97, 0x25, 0x54, 0xb1, 0x28, 0xaa, 0x98, 0x9d, 0xa5, 0x64, 0x6d, 0x7a, 0xd4, 0x10, 0x81, 0x44, 0xef, 0x49, 0xd6, 0xae, 0x2e, 0xdd, 0x76, 0x5c, 0x2f, 0xa7, 0x1c, 0xc9, 0x09, 0x69, 0x9a, 0x83, 0xcf, 0x29, 0x39, 0xb9, 0xe9, 0x4c, 0xff, 0x43, 0xab ]; my $PDF_PADDING = [ 0x28, 0xbf, 0x4e, 0x5e, 0x4e, 0x75, 0x8a, 0x41, 0x64, 0x00, 0x4e, 0x56, 0xff, 0xfa, 0x01, 0x08, 0x2e, 0x2e, 0x00, 0xb6, 0xd0, 0x68, 0x3e, 0x80, 0x2f, 0x0c, 0xa9, 0xfe, 0x64, 0x53, 0x69, 0x7a ]; my $CISCO_BASE64_MAPPING = { 'A', '.', 'B', '/', 'C', '0', 'D', '1', 'E', '2', 'F', '3', 'G', '4', 'H', '5', 'I', '6', 'J', '7', 'K', '8', 'L', '9', 'M', 'A', 'N', 'B', 'O', 'C', 'P', 'D', 'Q', 'E', 'R', 'F', 'S', 'G', 'T', 'H', 'U', 'I', 'V', 'J', 'W', 'K', 'X', 'L', 'Y', 'M', 'Z', 'N', 'a', 'O', 'b', 'P', 'c', 'Q', 'd', 'R', 'e', 'S', 'f', 'T', 'g', 'U', 'h', 'V', 'i', 'W', 'j', 'X', 'k', 'Y', 'l', 'Z', 'm', 'a', 'n', 'b', 'o', 'c', 'p', 'd', 'q', 'e', 'r', 'f', 's', 'g', 't', 'h', 'u', 'i', 'v', 'j', 'w', 'k', 'x', 'l', 'y', 'm', 'z', 'n', '0', 'o', '1', 'p', '2', 'q', '3', 'r', '4', 's', '5', 't', '6', 'u', '7', 'v', '8', 'w', '9', 'x', '+', 'y', '/', 'z' }; if (scalar @ARGV < 1) { usage_die (); } my $type; my $mode; my $len; $type = shift @ARGV; if ($type ne "verify") { if (scalar @ARGV > 1) { $mode = shift @ARGV; $len = shift @ARGV; } elsif (scalar @ARGV == 1) { $mode = shift @ARGV; $len = 0; } else { $len = 0; } if ($type eq "single") { single ($mode); } elsif ($type eq "passthrough") { passthrough ($mode); } else { usage_die (); } } else { if (scalar @ARGV != 4) { usage_die (); } my $mode = shift @ARGV; my $hash_file = shift @ARGV; my $in_file = shift @ARGV; my $out_file = shift @ARGV; my $db; open (IN, "<", $hash_file) or die ("$hash_file: $!\n"); # clever ? the resulting database could be huge # but we need some way to map lines in hashfile w/ cracks # maybe rli2 way would be more clever (needs sorted input) while (my $line = <IN>) { $line =~ s/[\n\r]*$//; $db->{$line} = undef; } close (IN); verify ($mode, $db, $in_file, $out_file); } # Array lookup sub is_in_array { my $value = shift; my $array = shift; return grep { $_ eq $value } @{$array}; } sub verify { my $mode = shift; my $db = shift; my $in_file = shift; my $out_file = shift; my $hash_in; my $hash_out; my $iter; my $salt; my $word; my $param; my $param2; my $param3; my $param4; my $param5; my $param6; my $param7; my $param8; my $param9; my $param10; my $param11; open (IN, "<", $in_file) or die ("$in_file: $!\n"); open (OUT, ">", $out_file) or die ("$out_file: $!\n"); my $len; my $base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; my $itoa64_1 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; my $itoa64_2 = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; while (my $line = <IN>) { chomp ($line); $line =~ s/\n$//; $line =~ s/\r$//; # remember always do "exists ($db->{$hash_in})" checks as soon as possible and don't forget it # unsalted if (is_in_array ($mode, $COMMON_UNSALTED_MODES) || $mode == 2400 || $mode == 3000 || $mode == 8600 || $mode == 16000) { my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $word = substr ($line, $index + 1); } # hash:salt elsif (is_in_array ($mode, $COMMON_DEFAULT_SALTED_MODES) || $mode == 11 || $mode == 12 || $mode == 21 || $mode == 22 || $mode == 112 || $mode == 121 || $mode == 1100 || $mode == 2410 || $mode == 2611 || $mode == 2711 || $mode == 2811 || $mode == 3100 || $mode == 3800 || $mode == 4520 || $mode == 4521 || $mode == 4522 || $mode == 4900 || $mode == 5800 || $mode == 8400 || $mode == 11000 || $mode == 12600 || $mode == 13500 || $mode == 13800 || $mode == 13900 || $mode == 14000 || $mode == 14100 || $mode == 14400 || $mode == 14900 || $mode == 15000) { # get hash my $index1 = index ($line, ":"); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); # identify lenghts of both salt and plain my $salt_plain = substr ($line, $index1 + 1); my $num_cols = () = $salt_plain =~ /:/g; my $index2; my $matched = 0; my $start = 0; $word = undef; # fuzzy foreach (my $i = 0; $i < $num_cols; $i++) { $index2 = index ($salt_plain, ":", $start); next if $index2 < 0; $start = $index2 + 1; $salt = substr ($salt_plain, 0, $index2); $word = substr ($salt_plain, $index2 + 1); # can't be true w/ wrong $hash:$salt, otherwise the # algo must have many collisions if (exists ($db->{$hash_in . ":" . $salt})) { $hash_in = $hash_in . ":" . $salt; $matched = 1; last; } } next unless ($matched); # therefore: true == exists ($db->{$hash_in} next unless (! defined ($db->{$hash_in})); } # dcc2 elsif ($mode == 2100) { # get hash my $index1 = index ($line, "\$DCC2\$"); next if $index1 != 0; # iterations my $index2 = index ($line, "#", $index1 + 1); next if $index2 < 1; $iter = substr ($line, $index1 + 6, $index2 - $index1 - 6); # get hash $index1 = index ($line, "#"); next if $index1 < 1; $hash_in = substr ($line, 0, $index1 + 1); # identify lenghts of both salt and plain my $salt_plain = substr ($line, $index2 + 1); my $num_cols = () = $salt_plain =~ /:/g; my $matched = 0; my $start = 0; my $index3 = 0; my $raw_hash; $word = undef; # fuzzy foreach (my $i = 0; $i < $num_cols; $i++) { $index2 = index ($salt_plain, ":", $start); next if $index2 < 0; $start = $index2 + 1; $index3 = rindex ($salt_plain, "#", $index2); $raw_hash = substr ($salt_plain, $index3 + 1, $index2 - $index3 - 1); $salt = substr ($salt_plain, 0, $index3); $word = substr ($salt_plain, $index2 + 1); if (exists ($db->{$hash_in . $salt . "#" .$raw_hash})) { $hash_in = $hash_in . $salt . "#" . $raw_hash; $matched = 1; last; } } next unless ($matched); # therefore: true == exists ($db->{$hash_in} next unless (! defined ($db->{$hash_in})); } # salt:hash guaranteed only : because of hex salt elsif ($mode == 7300) { # split hash and plain my $index1 = index ($line, ":"); next if $index1 < 1; $salt = substr ($line, 0, $index1); $salt = pack ("H*", $salt); my $rest = substr ($line, $index1 + 1); my $index2 = index ($rest, ":"); next if $index2 < 1; $hash_in = substr ($rest, 0, $index2); $word = substr ($rest, $index2 + 1); next unless (exists ($db->{$salt . ":" . $hash_in}) and (! defined ($db->{$hash_in}))); } # 1salthash fixed elsif ($mode == 8100) { # split hash and plain $salt = substr ($line, 1, 8); my $rest = substr ($line, 1 + 8); my $index2 = index ($rest, ":"); next if $index2 < 1; $hash_in = substr ($rest, 0, $index2); $word = substr ($rest, $index2 + 1); next unless (exists ($db->{"1" . $salt . $hash_in}) and (! defined ($db->{$hash_in}))); } # base64 and salt embedded SSHA1, salt length = total lenght - 20 elsif ($mode == 111) { # split hash and plain my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); # remove signature my $plain_base64 = substr ($hash_in, 6); # base64 decode to extract salt my $decoded = decode_base64 ($plain_base64); $salt = substr ($decoded, 20); } # base64 and salt embedded SSHA512, salt length = total length - 64 elsif ($mode == 1711) { # split hash and plain my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); # remove signature my $plain_base64 = substr ($hash_in, 9); # base64 decode to extract salt my $decoded = decode_base64 ($plain_base64); $salt = substr ($decoded, 64); } # macOS (first 8 hex chars is salt) # ArubaOS (the signature gets added in gen_hash) elsif ($mode == 122 || $mode == 1722 || $mode == 125) { my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $salt = substr ($hash_in, 0, 8); } # MSSQL (2000, 2005 AND 2012), salt after version number elsif ($mode == 131 || $mode == 132 || $mode == 1731) { my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $salt = substr ($hash_in, 6, 8); } # Sybase ASE elsif ($mode == 8000) { my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $salt = substr ($hash_in, 6, 16); } # episerver salts elsif ($mode == 141 || $mode == 1441) { my $index1 = index ($line, ":"); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $index2 = index ($line, "*", 14); #extract salt from base64 my $plain_base64 = substr ($hash_in, 14, $index2 - 14); $salt = decode_base64 ($plain_base64); } # phpass (first 8 after $P$/$H$ -- or $S$ with drupal7) elsif ($mode == 400 || $mode == 7900) { my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $salt = substr ($hash_in, 4, 8); # iterations = 2 ^ cost (where cost == $iter) $iter = index ($itoa64_1, substr ($hash_in, 3, 1)); } # $something$[rounds=iter$]salt$ (get last $, then check iter) elsif ($mode == 500 || $mode == 1600 || $mode == 1800 || $mode == 3300 || $mode == 7400) { my $index1 = index ($line, ":", 30); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $index1 = index ($hash_in, ",", 1); my $index2 = index ($hash_in, "\$", 1); if ($index1 != -1) { if ($index1 < $index2) { $index2 = $index1; } } $param = substr ($hash_in, $index2, 1); $index2++; # rounds= if available $iter = 0; if (substr ($hash_in, $index2, 7) eq "rounds=") { my $old_index = $index2; $index2 = index ($hash_in, "\$", $index2 + 1); next if $index2 < 1; $iter = substr ($hash_in, $old_index + 7, $index2 - $old_index - 7); $index2++; } # get salt my $index3 = rindex ($hash_in, "\$"); next if $index3 < 1; $salt = substr ($hash_in, $index2, $index3 - $index2); } # descrypt (salt in first 2 char) elsif ($mode == 1500) { my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $salt = substr ($hash_in, 0, 2); } # bcrypt $something$something$salt.hash elsif ($mode == 3200) { my $index1 = index ($line, ":", 33); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $index2 = index ($hash_in, "\$", 4); $iter = substr ($hash_in, 4, $index2 - 4); my $plain_base64 = substr ($hash_in, $index2 + 1, 22); # base64 mapping my $encoded = ""; for (my $i = 0; $i < length ($plain_base64); $i++) { my $char = substr ($plain_base64, $i, 1); $encoded .= substr ($base64, index ($itoa64_2, $char), 1); } $salt = decode_base64 ($encoded); } # md5 (chap) elsif ($mode == 4800) { my $index1 = index ($line, ":"); next if $index1 < 1; my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; my $index3 = index ($line, ":", $index2 + 1); next if $index3 < 1; $salt = substr ($line, $index1 + 1, $index3 - $index1 - 1); $word = substr ($line, $index3 + 1); $hash_in = substr ($line, 0, $index3); } # IKE (md5 and sha1) elsif ($mode == 5300 || $mode == 5400) { my $num_cols = () = $line =~ /:/g; next unless ($num_cols >= 9); my $index1 = -1; my $failed = 0; for (my $j = 0; $j < 9; $j++) { $index1 = index ($line, ":", $index1 + 1); if ($index1 < 1) { $failed = 1; last; } } next if ($failed); $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $index2 = rindex ($line, ":", $index1 - 1); $salt = substr ($line, 0, $index2); } # NetNTLMv1 elsif ($mode == 5500) { my $index1 = index ($line, "::"); next if $index1 < 1; my $index2 = index ($line, ":", $index1 + 2); next if $index2 < 1; $index2 = index ($line, ":", $index2 + 1); next if $index2 < 1; $salt = substr ($line, 0, $index2); $index2 = index ($line, ":", $index2 + 1); next if $index2 < 1; $salt .= substr ($line, $index2 + 1, 16); $index2 = index ($line, ":", $index2 + 1); next if $index2 < 1; $hash_in = substr ($line, 0, $index2); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $word = substr ($line, $index2 + 1); } # NetNTLMv2 elsif ($mode == 5600) { my $index1 = index ($line, "::"); next if $index1 < 1; my $index2 = index ($line, ":", $index1 + 2); next if $index2 < 1; $index2 = index ($line, ":", $index2 + 1); next if $index2 < 1; $salt = substr ($line, 0, $index2); $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; $salt .= substr ($line, $index1 + 1, $index2 - $index1 - 1); $hash_in = substr ($line, 0, $index2); # do it later on for this hash mode: # next unless ((exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))) or (exists ($db->{$mod}) and (! defined ($db->{$mod})))); $word = substr ($line, $index2 + 1); } # AIX smd5 something BRACE salt$ elsif ($mode == 6300) { my $index1 = index ($line, ":"); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $index2 = index ($hash_in, "}"); my $index3 = rindex ($hash_in, "\$"); $salt = substr ($hash_in, $index2 + 1, $index3 - $index2 - 1); } # AIX: something$salt$ (no $ at position 1) elsif ($mode == 6400 || $mode == 6500 || $mode == 6700) { my $index1 = index ($line, ":"); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $index2 = index ($hash_in, "}"); my $index3 = index ($hash_in, "\$"); my $index4 = rindex ($hash_in, "\$"); $salt = substr ($hash_in, $index3 + 1, $index4 - $index3 - 1); $iter = substr ($hash_in, $index2 + 1, $index3 - $index2 - 1); } # 1Password, agilekeychain elsif ($mode == 6600) { my $num_cols = () = $line =~ /:/g; next unless ($num_cols > 2); my $index1 = index ($line, ":"); next if $index1 < 1; $iter = substr ($line, 0, $index1); my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; $salt .= substr ($line, $index2 + 1, $index1 - $index2 - 33); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $word = substr ($line, $index1 + 1); } # 1Password, cloudkeychain elsif ($mode == 8200) { my @datas = split (":", $line); next if scalar @datas < 4; my $hash = shift @datas; $salt = shift @datas; $iter = shift @datas; my $data = shift @datas; $hash_in = $hash . ":" . $salt . ":" . $iter . ":" . $data; $salt .= $data; $word = join (":", @datas); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # lastpass (hash:iter:salt) elsif ($mode == 6800) { my $index1 = index ($line, ":", 34); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); # identify lenghts of both salt and plain my $salt_plain = substr ($line, $index1 + 1); my $num_cols = () = $salt_plain =~ /:/g; my $index2; my $matched = 0; my $start = 0; $word = undef; # fuzzy foreach (my $i = 0; $i < $num_cols; $i++) { $index2 = index ($salt_plain, ":", $start); next if $index2 < 1; $start = $index2 + 1; $salt = substr ($salt_plain, 0, $index2); $word = substr ($salt_plain, $index2 + 1); # can't be true w/ wrong $hash:$salt, otherwise the # algo must have many collisions if (exists ($db->{$hash_in . ":" . $salt})) { $hash_in = $hash_in . ":" . $salt; $matched = 1; last; } } next unless ($matched); # therefore: true == exists ($db->{$hash_in} next unless (! defined ($db->{$hash_in})); $index1 = index ($hash_in, ":"); $index2 = index ($hash_in, ":", $index1 + 1); $iter = substr ($hash_in, $index1 + 1, $index2 - $index1 - 1); $salt = substr ($hash_in, $index2 + 1); } # Fortigate elsif ($mode == 7000) { my $index1 = index ($line, ":"); next if $index1 != 47; $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next unless (substr ($hash_in, 0, 3) eq "AK1"); my $decoded = decode_base64 (substr ($hash_in, 3)); $salt = substr ($decoded, 0, 12); $salt = unpack ("H*", $salt); } # macOS 10.* : $something$iter$salt$ elsif ($mode == 7100) { my $index1 = index ($line, ":"); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $index2 = index ($hash_in, "\$", 5); next if $index2 < 1; my $index3 = index ($hash_in, "\$", $index2 + 1); $salt = substr ($hash_in, $index2 + 1, $index3 - $index2 - 1); $iter = substr ($hash_in, 4, $index2 - 4); next if (int ($iter) < 1); } # grub: something1.something2.something3.iter.salt. elsif ($mode == 7200) { my $index1 = index ($line, ":"); next if $index1 < 1; $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $index2 = index ($hash_in, ".", 19); next if $index2 < 1; my $index3 = index ($hash_in, ".", $index2 + 1); $salt = substr ($hash_in, $index2 + 1, $index3 - $index2 - 1); $iter = substr ($hash_in, 19, $index2 - 19); next if (int ($iter) < 1); } # $something1$something2$something3$something4$salt$ elsif ($mode == 7500 ) { my $index1 = index ($line, "\$", 11); next if $index1 < 1; my $index2 = index ($line, "\$", $index1 + 1); next if $index2 < 1; my $index3 = index ($line, "\$", $index2 + 1); next if $index3 < 1; $index2 = index ($line, ":", $index3 + 1); next if $index2 < 1; $hash_in = substr ($line, 0, $index2); $word = substr ($line, $index2 + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $salt = substr ($hash_in, 11, $index3 - 10); $salt .= substr ($hash_in, $index2 - 32) . "\$\$"; $salt .= substr ($hash_in, $index3 + 1, $index2 - $index3 - 32 - 1); } # $salt$$hash elsif ($mode == 7700 || $mode == 7800 || $mode == 7701 || $mode == 7801) { my $index1 = index ($line, ":"); next if $index1 < 1; my @split1 = split (":", $line); my @split2 = split ('\$', $split1[0]); next unless scalar @split2 == 2; $hash_in = $split1[0]; if (scalar @split1 > 1) { $word = $split1[1]; } else { $word = ""; } next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $salt = $split2[0]; } # DNSSEC elsif ($mode == 8300) { my @datas = split (":", $line); next if scalar @datas != 5; my $hash; my $domain; ($hash, $domain, $salt, $iter, $word) = @datas; $hash_in = $hash . ":" . $domain . ":" . $salt . ":" . $iter; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); $salt = $domain . ":" . $salt; } # RACF elsif ($mode == 8500) { my @line_elements = split (":", $line); next if scalar @line_elements < 2; # get hash and word $hash_in = shift @line_elements; $word = join (":", @line_elements); # get signature my @hash_elements = split ('\*', $hash_in); next unless ($hash_elements[0] eq '$racf$'); $salt = $hash_elements[1]; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # DOMINO 6 elsif ($mode == 8700) { # split hash and plain my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $plain_base64 = substr ($hash_in, 2, -1); ($_, $salt, $param) = domino_decode ($plain_base64); } # PHPS elsif ($mode == 2612) { next unless (substr ($line, 0, 6) eq '$PHPS$'); # get hash my $index1 = index ($line, "\$", 6); next if $index1 < 1; $salt = substr ($line, 6, $index1 - 6); $salt = pack ("H*", $salt); my $index2 = index ($line, "\:", $index1 + 1); next if $index2 < 1; $word = substr ($line, $index2 + 1); $hash_in = substr ($line, 0, $index2); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Mediawiki B type elsif ($mode == 3711) { next unless (substr ($line, 0, 3) eq '$B$'); # get hash my $index1 = index ($line, "\$", 3); next if $index1 < 1; $salt = substr ($line, 3, $index1 - 3); my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; $word = substr ($line, $index2 + 1); $hash_in = substr ($line, 0, $index2); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # scrypt elsif ($mode == 8900) { next unless (substr ($line, 0, 7) eq 'SCRYPT:'); # get hash my $index1 = index ($line, ":", 7); next if $index1 < 1; # N my $N = substr ($line, 7, $index1 - 7); my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; # r my $r = substr ($line, $index1 + 1, $index2 - $index1 - 1); $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; # p my $p = substr ($line, $index2 + 1, $index1 - $index2 - 1); $param = $N; $param2 = $r; $param3 = $p; $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; # salt $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); $salt = decode_base64 ($salt); $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; # digest $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # LOTUS 8 elsif ($mode == 9100) { # split hash and plain my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $base64_part = substr ($hash_in, 2, -1); ($_, $salt, $iter, $param) = domino_85x_decode ($base64_part); next if ($iter < 1); } # Cisco $8$ - PBKDF2-HMAC-SHA256 elsif ($mode == 9200) { next unless (substr ($line, 0, 3) eq '$8$'); # get hash my $index1 = index ($line, "\$", 3); next if $index1 != 17; my $index2 = index ($line, "\$", $index1 + 1); # salt $salt = substr ($line, 3, $index1 - 3); $index1 = index ($line, ":", $index1 + 1); next if $index1 < 1; # digest $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Cisco $9$ - scrypt elsif ($mode == 9300) { next unless (substr ($line, 0, 3) eq '$9$'); # get hash my $index1 = index ($line, "\$", 3); next if $index1 != 17; my $index2 = index ($line, "\$", $index1 + 1); # salt $salt = substr ($line, 3, $index1 - 3); $index1 = index ($line, ":", $index1 + 1); next if $index1 < 1; # digest $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Office 2007 elsif ($mode == 9400) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data == 8; next unless (shift @data eq '$office$'); next unless (shift @data eq '2007'); next unless (shift @data eq '20'); my $aes_key_size = shift @data; next unless (($aes_key_size eq '128') || ($aes_key_size eq '256')); next unless (shift @data eq '16'); next unless (length $data[0] == 32); next unless (length $data[1] == 32); next unless (length $data[2] == 40); $salt = shift @data; $param = shift @data; $param2 = $aes_key_size; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Office 2010 elsif ($mode == 9500) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data == 8; next unless (shift @data eq '$office$'); next unless (shift @data eq '2010'); next unless (shift @data eq '100000'); next unless (shift @data eq '128'); next unless (shift @data eq '16'); next unless (length $data[0] == 32); next unless (length $data[1] == 32); next unless (length $data[2] == 64); $salt = shift @data; $param = shift @data; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Office 2013 elsif ($mode == 9600) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data == 8; next unless (shift @data eq '$office$'); next unless (shift @data eq '2013'); next unless (shift @data eq '100000'); next unless (shift @data eq '256'); next unless (shift @data eq '16'); next unless (length $data[0] == 32); next unless (length $data[1] == 32); next unless (length $data[2] == 64); $salt = shift @data; $param = shift @data; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Office Old $1 $2 elsif ($mode == 9700) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data == 4; my $signature = shift @data; next unless (($signature eq '$oldoffice$0') || ($signature eq '$oldoffice$1')); next unless (length $data[0] == 32); next unless (length $data[1] == 32); next unless (length $data[2] == 32); $salt = shift @data; $param = shift @data; $param2 = substr ($signature, 11, 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Office Old $3 $4 elsif ($mode == 9800) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data == 4; my $signature = shift @data; next unless (($signature eq '$oldoffice$3') || ($signature eq '$oldoffice$4')); next unless (length $data[0] == 32); next unless (length $data[1] == 32); next unless (length $data[2] == 40); $salt = shift @data; $param = shift @data; $param2 = substr ($signature, 11, 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Django (PBKDF2-SHA256) elsif ($mode == 10000) { next unless (substr ($line, 0, 14) eq 'pbkdf2_sha256$'); # get hash my $index1 = index ($line, "\$", 14); next if $index1 < 1; my $index2 = index ($line, "\$", $index1 + 1); # iter $iter = substr ($line, 14, $index1 - 14); # salt $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); # digest $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # SipHash elsif ($mode == 10100) { my $hash; ($hash, undef, undef, $salt, $word) = split ":", $line; next unless defined $hash; next unless defined $salt; next unless defined $word; next unless (length $hash == 16); next unless (length $salt == 32); my $hash_in = sprintf ("%s:2:4:%s", $hash, $salt); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Cram MD5 elsif ($mode == 10200) { next unless (substr ($line, 0, 10) eq '$cram_md5$'); # get hash my $index1 = index ($line, "\$", 10); next if $index1 < 1; # challenge my $challengeb64 = substr ($line, 10, $index1 - 10); $salt = decode_base64 ($challengeb64); # response my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; my $responseb64 = substr ($line, $index1 + 1, $index2 - $index1 - 1); my $response = decode_base64 ($responseb64); $param = substr ($response, 0, length ($response) - 32 - 1); # -1 is for space $word = substr ($line, $index2 + 1); $hash_in = substr ($line, 0, $index2); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # SAP CODVN H (PWDSALTEDHASH) iSSHA-1 elsif ($mode == 10300) { next unless (substr ($line, 0, 10) eq '{x-issha, '); # get iterations my $index1 = index ($line, "}", 10); next if $index1 < 1; $iter = substr ($line, 10, $index1 - 10); $iter = int ($iter); # base64 substring my $base64_encoded = substr ($line, $index1 + 1); my $base64_decoded = decode_base64 ($base64_encoded); $salt = substr ($base64_decoded, 20); my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; $word = substr ($line, $index2 + 1); $hash_in = substr ($line, 0, $index2); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PDF 1.1 - 1.3 (Acrobat 2 - 4) elsif ($mode == 10400) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data == 11; next unless (shift @data eq '$pdf$1'); next unless (shift @data eq '2'); next unless (shift @data eq '40'); my $P = shift @data; next unless (shift @data eq '0'); next unless (shift @data eq '16'); my $id = shift @data; next unless (shift @data eq '32'); my $u = shift @data; next unless (shift @data eq '32'); my $o = shift @data; $salt = $id; $param = $u; $param2 = $o; $param3 = $P; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PDF 1.4 - 1.6 (Acrobat 5 - 8) elsif ($mode == 10500) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data == 11; my $V = shift @data; $V = substr ($V, 5, 1); my $R = shift @data; next unless (shift @data eq '128'); my $P = shift @data; my $enc = shift @data; next unless (shift @data eq '16'); my $id = shift @data; next unless (shift @data eq '32'); my $u = shift @data; next unless (shift @data eq '32'); my $o = shift @data; $salt = $id; $param = $u; $param2 = $o; $param3 = $P; $param4 = $V; $param5 = $R; $param6 = $enc; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PDF 1.7 Level 3 (Acrobat 9) elsif ($mode == 10600) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data >= 11; next unless (shift @data eq '$pdf$5'); next unless (shift @data eq '5'); next unless (shift @data eq '256'); next unless (shift @data eq '-1028'); next unless (shift @data eq '1'); next unless (shift @data eq '16'); my $id = shift @data; my $rest = join "*", @data; $salt = $id; $param = $rest; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PDF 1.7 Level 8 (Acrobat 10 - 11) elsif ($mode == 10700) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\*/, $hash_in; next unless scalar @data >= 11; next unless (shift @data eq '$pdf$5'); next unless (shift @data eq '6'); next unless (shift @data eq '256'); next unless (shift @data eq '-1028'); next unless (shift @data eq '1'); next unless (shift @data eq '16'); my $id = shift @data; my $rest = join "*", @data; $salt = $id; $param = $rest; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PBKDF2-HMAC-SHA256 elsif ($mode == 10900) { next unless (substr ($line, 0, 7) eq 'sha256:'); # iterations my $index1 = index ($line, ":", 7); next if $index1 < 1; $iter = substr ($line, 7, $index1 - 7); # salt my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); $salt = decode_base64 ($salt); # end of digest $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; # additional param = output len of pbkdf2 my $digest64_encoded = substr ($line, $index2 + 1, $index1 - $index2 - 1); my $digest = decode_base64 ($digest64_encoded); $param = length ($digest); # word / hash $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PostgreSQL MD5 Authentication elsif ($mode == 11100) { next unless (substr ($line, 0, 10) eq '$postgres$'); my $index1 = index ($line, "*", 10); next if $index1 < 1; # the user name $param = substr ($line, 10, $index1 - 10); # get the 4 byte salt my $index2 = index ($line, "*", $index1 + 1); next if $index2 < 1; $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); # word / hash $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # MySQL MD5 Authentication elsif ($mode == 11200) { next unless (substr ($line, 0, 9) eq '$mysqlna$'); my $index1 = index ($line, "*", 9); next if $index1 < 1; # salt $salt = substr ($line, 9, $index1 - 9); # word / hash $index1 = index ($line, ":", $index1 + 1); next if $index1 < 1; $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # WPA-EAPOL-PBKDF2 elsif ($mode == 2500) { print "ERROR: verify currently not supported for WPA-EAPOL-PBKDF2 (because of hashcat's output format)\n"; exit (1); } # Bitcoin/Litecoin wallet.dat elsif ($mode == 11300) { print "ERROR: verify currently not supported for Bitcoin/Litecoin wallet.dat because of unknown crypt data\n"; exit (1); } # SIP digest authentication (MD5) elsif ($mode == 11400) { next unless (substr ($line, 0, 6) eq '$sip$*'); # URI_server: my $index1 = index ($line, "*", 6); next if $index1 < 0; $param10 = substr ($line, 6, $index1 - 6); next if (length ($param10) > 32); # URI_client: my $index2 = index ($line, "*", $index1 + 1); next if $index2 < 0; $param11 = substr ($line, $index1 + 1, $index2 - $index1 - 1); next if (length ($param11) > 32); # user: $index1 = index ($line, "*", $index2 + 1); next if $index1 < 0; $param = substr ($line, $index2 + 1, $index1 - $index2 - 1); next if (length ($param) > 12); # realm: $index2 = index ($line, "*", $index1 + 1); next if $index2 < 0; $param2 = substr ($line, $index1 + 1, $index2 - $index1 - 1); next if (length ($param2) > 20); # method: $index1 = index ($line, "*", $index2 + 1); next if $index1 < 0; $param6 = substr ($line, $index2 + 1, $index1 - $index2 - 1); next if (length ($param6) > 24); # URI_prefix: $index2 = index ($line, "*", $index1 + 1); next if $index2 < 0; $param7 = substr ($line, $index1 + 1, $index2 - $index1 - 1); next if (length ($param7) > 10); # URI_resource: $index1 = index ($line, "*", $index2 + 1); next if $index1 < 0; $param8 = substr ($line, $index2 + 1, $index1 - $index2 - 1); next if (length ($param8) > 32); # URI_suffix: $index2 = index ($line, "*", $index1 + 1); next if $index2 < 0; $param9 = substr ($line, $index1 + 1, $index2 - $index1 - 1); next if (length ($param9) > 32); # nonce: $index1 = index ($line, "*", $index2 + 1); next if $index1 < 0; $salt = substr ($line, $index2 + 1, $index1 - $index2 - 1); next if (length ($salt) > 34); # nonce_client: $index2 = index ($line, "*", $index1 + 1); next if $index2 < 0; $param4 = substr ($line, $index1 + 1, $index2 - $index1 - 1); next if (length ($param4) > 12); # nonce_count: $index1 = index ($line, "*", $index2 + 1); next if $index1 < 0; $param3 = substr ($line, $index2 + 1, $index1 - $index2 - 1); next if (length ($param3) > 10); # qop: $index2 = index ($line, "*", $index1 + 1); next if $index2 < 0; $param5 = substr ($line, $index1 + 1, $index2 - $index1 - 1); next if (length ($param5) > 8); # directive: $index1 = index ($line, "*", $index2 + 1); next if $index1 < 0; my $directive = substr ($line, $index2 + 1, $index1 - $index2 - 1); next unless ($directive eq "MD5"); # hash_buf: $index2 = index ($line, ":", $index1 + 1); next if $index2 < 0; my $hex_digest = substr ($line, $index1 + 1, $index2 - $index1 - 1); next unless (length ($hex_digest) == 32); $word = substr ($line, $index2 + 1); $hash_in = substr ($line, 0, $index2); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # 7-Zip elsif ($mode == 11600) { next unless (substr ($line, 0, 4) eq '$7z$'); # p my $index1 = index ($line, '$', 4); next if $index1 < 0; my $p = substr ($line, 4, $index1 - 4); next unless ($p eq "0"); # num cycle power my $index2 = index ($line, '$', $index1 + 1); next if $index2 < 0; $iter = substr ($line, $index1 + 1, $index2 - $index1 - 1); # seven zip salt length $index1 = index ($line, '$', $index2 + 1); next if $index1 < 0; $param = substr ($line, $index2 + 1, $index1 - $index2 - 1); # seven zip salt $index2 = index ($line, '$', $index1 + 1); next if $index2 < 0; $param2 = substr ($line, $index1 + 1, $index2 - $index1 - 1); # salt len $index1 = index ($line, '$', $index2 + 1); next if $index1 < 0; $param3 = substr ($line, $index2 + 1, $index1 - $index2 - 1); # salt $index2 = index ($line, '$', $index1 + 1); next if $index2 < 0; $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); $salt = pack ("H*", $salt); # crc / hash $index1 = index ($line, '$', $index2 + 1); next if $index1 < 0; my $crc = substr ($line, $index2 + 1, $index1 - $index2 - 1); # ignore this crc, we don't need to pass it to gen_hash () # data len $index2 = index ($line, '$', $index1 + 1); next if $index2 < 0; $param4 = substr ($line, $index1 + 1, $index2 - $index1 - 1); # unpack size $index1 = index ($line, '$', $index2 + 1); next if $index1 < 0; $param5 = substr ($line, $index2 + 1, $index1 - $index2 - 1); # data $index2 = index ($line, ':', $index1 + 1); next if $index2 < 0; $param6 = substr ($line, $index1 + 1, $index2 - $index1 - 1); $param6 = pack ("H*", $param6); $word = substr ($line, $index2 + 1); $hash_in = substr ($line, 0, $index2); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PBKDF2-HMAC-MD5 elsif ($mode == 11900) { next unless (substr ($line, 0, 4) eq 'md5:'); # iterations my $index1 = index ($line, ":", 4); next if $index1 < 1; $iter = substr ($line, 4, $index1 - 4); # salt my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); $salt = decode_base64 ($salt); # end of digest $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; # additional param = output len of pbkdf2 my $digest64_encoded = substr ($line, $index2 + 1, $index1 - $index2 - 1); my $digest = decode_base64 ($digest64_encoded); $param = length ($digest); # word / hash $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PBKDF2-HMAC-SHA1 elsif ($mode == 12000) { next unless (substr ($line, 0, 5) eq 'sha1:'); # iterations my $index1 = index ($line, ":", 5); next if $index1 < 1; $iter = substr ($line, 5, $index1 - 5); # salt my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); $salt = decode_base64 ($salt); # end of digest $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; # additional param = output len of pbkdf2 my $digest64_encoded = substr ($line, $index2 + 1, $index1 - $index2 - 1); my $digest = decode_base64 ($digest64_encoded); $param = length ($digest); # word / hash $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # PBKDF2-HMAC-SHA512 elsif ($mode == 12100) { next unless (substr ($line, 0, 7) eq 'sha512:'); # iterations my $index1 = index ($line, ":", 7); next if $index1 < 1; $iter = substr ($line, 7, $index1 - 7); # salt my $index2 = index ($line, ":", $index1 + 1); next if $index2 < 1; $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); $salt = decode_base64 ($salt); # end of digest $index1 = index ($line, ":", $index2 + 1); next if $index1 < 1; # additional param = output len of pbkdf2 my $digest64_encoded = substr ($line, $index2 + 1, $index1 - $index2 - 1); my $digest = decode_base64 ($digest64_encoded); $param = length ($digest); # word / hash $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # ecryptfs elsif ($mode == 12200) { next unless (substr ($line, 0, 12) eq '$ecryptfs$0$'); # check if default salt $param = 1; $param = 0 if (substr ($line, 12, 2) eq '1$'); # salt $salt = ""; my $index1 = 12; if ($param == 0) # we need to extract the salt { $index1 = index ($line, '$', $index1); next if $index1 < 1; my $index2 = index ($line, '$', $index1 + 1); next if $index2 < 1; $salt = substr ($line, $index1 + 1, $index2 - $index1 - 1); $index1 = $index2; } $index1 = index ($line, ':', $index1 + 1); next if $index1 < 1; # word / hash $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Oracle T: Type (Oracle 12+) elsif ($mode == 12300) { my $index1 = index ($line, ':'); next if ($index1 != 160); # salt $salt = substr ($line, 128, 32); # word / hash $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # BSDi Crypt, Extended DES elsif ($mode == 12400) { next unless (substr ($line, 0, 1) eq '_'); my $index1 = index ($line, ':', 20); next if ($index1 != 20); # iter $iter = substr ($line, 1, 4); $iter = base64_to_int24 ($iter); # salt $salt = substr ($line, 5, 4); # word / hash $word = substr ($line, $index1 + 1); $hash_in = substr ($line, 0, $index1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Blockchain, My Wallet elsif ($mode == 12700) { my $index1 = index ($line, ':'); next if ($index1 < 0); $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); my (undef, $signature, $data_len, $data_buf) = split '\$', $hash_in; next unless ($signature eq "blockchain"); next unless (($data_len * 2) == length $data_buf); $salt = substr ($data_buf, 0, 32); $param = substr ($data_buf, 32); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 12800) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split /\,/, $hash_in; next unless scalar @data == 4; next unless (shift @data eq 'v1;PPH1_MD4'); $salt = shift @data; $iter = shift @data; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 12900) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; next unless length $hash_in == 160; $param = substr ($hash_in, 0, 64); $salt = substr ($hash_in, 128, 32); $iter = 4096; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 13000) { my $hash_line; ($hash_line, $word) = split ":", $line; next unless defined $hash_line; next unless defined $word; my @data = split ('\$', $hash_line); next unless scalar @data == 8; shift @data; my $signature = shift @data; my $salt_len = shift @data; my $salt_buf = shift @data; my $iterations = shift @data; my $iv = shift @data; my $pswcheck_len = shift @data; my $pswcheck = shift @data; next unless ($signature eq "rar5"); next unless ($salt_len == 16); next unless ($pswcheck_len == 8); $salt = $salt_buf; $iter = $iterations; $hash_in = $pswcheck; $param = $iv; next unless (exists ($db->{$hash_line}) and (! defined ($db->{$hash_line}))); } elsif ($mode == 13100) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\$', $hash_in); next unless scalar @data == 8; shift @data; my $signature = shift @data; my $algorithm = shift @data; my $user = shift @data; $user = substr ($user, 1); my $realm = shift @data; my $spn = shift @data; $spn = substr ($spn, 0, length ($spn) - 1); my $checksum = shift @data; my $edata2 = shift @data; next unless ($signature eq "krb5tgs"); next unless (length ($checksum) == 32); next unless (length ($edata2) >= 64); $salt = $user . '$' . $realm . '$' . $spn . '$'; $param = $checksum; $param2 = $edata2; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 13200) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\*', $hash_in); next unless scalar @data == 5; my $signature = shift @data; my $version = shift @data; my $iteration = shift @data; my $mysalt = shift @data; my $digest = shift @data; next unless ($signature eq '$axcrypt$'); next unless (length ($mysalt) == 32); next unless (length ($digest) == 48); $salt = $iteration . '*' . $mysalt; $param = $digest; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 13300) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\$', $hash_in); next unless scalar @data == 3; shift @data; my $signature = shift @data; my $digest = shift @data; $param = length ($digest); next unless ($signature eq 'axcrypt_sha1'); next unless (($param == 32) || ($param == 40)); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 13400) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\*', $hash_in); next unless (scalar @data == 9 || scalar @data == 11 || scalar @data == 12 || scalar @data == 14); my $signature = shift @data; next unless ($signature eq '$keepass$'); my $version = shift @data; next unless ($version == 1 || $version == 2); my $iteration = shift @data; my $algorithm = shift @data; my $final_random_seed = shift @data; if ($version == 1) { next unless (length ($final_random_seed) == 32); } elsif ($version == 2) { next unless (length ($final_random_seed) == 64); } my $transf_random_seed = shift @data; next unless (length ($transf_random_seed) == 64); my $enc_iv = shift @data; next unless (length ($enc_iv) == 32); if ($version == 1) { my $contents_hash = shift @data; next unless (length ($contents_hash) == 64); my $inline_flags = shift @data; next unless ($inline_flags == 1); my $contents_len = shift @data; my $contents = shift @data; next unless (length ($contents) == $contents_len * 2); } elsif ($version == 2) { my $expected_bytes = shift @data; next unless (length ($expected_bytes) == 64); my $contents_hash = shift @data; next unless (length ($contents_hash) == 64); } if (scalar @data == 12 || scalar @data == 14) { my $inline_flags = shift @data; next unless ($inline_flags == 1); my $keyfile_len = shift @data; next unless ($keyfile_len == 64); my $keyfile = shift @data; next unless (length ($keyfile) == $keyfile_len); } $salt = substr ($hash_in, length ("*keepass*") + 1); $param = 1; # distinguish between encrypting vs decrypting next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 13600) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\*', $hash_in); next unless scalar @data == 10; my $tag_start = shift @data; my $type = shift @data; my $mode = shift @data; my $magic = shift @data; my $salt = shift @data; my $verify_bytes = shift @data; my $length = shift @data; my $data = shift @data; my $auth = shift @data; my $tag_end = shift @data; next unless ($tag_start eq '$zip2$'); next unless ($tag_end eq '$/zip2$'); $param = $type; $param2 = $mode; $param3 = $magic; $param4 = $salt; $param5 = $length; $param6 = $data; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # itunes backup 9/10 elsif (($mode == 14700) || ($mode == 14800)) { ($hash_in, $word) = split ":", $line; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); my $index1 = index ($hash_in, '*'); next unless ($index1 == 15); # signature my $signature = substr ($hash_in, 0, $index1); next unless ($signature eq '$itunes_backup$'); my $index2 = index ($hash_in, '*', $index1 + 1); next unless ($index2 >= 0); # version my $version = substr ($hash_in, $index1 + 1, $index2 - $index1 - 1); if ($mode == 14700) { next unless ($version eq "9"); } else { next unless ($version eq "10"); } $index1 = index ($hash_in, '*', $index2 + 1); next unless ($index1 >= 0); # wpky my $wpky = substr ($hash_in, $index2 + 1, $index1 - $index2 - 1); next unless (length ($wpky) == 80); $wpky = pack ("H*", $wpky); $param = $wpky; $index2 = index ($hash_in, '*', $index1 + 1); next unless ($index2 >= 0); # iterations $iter = substr ($hash_in, $index1 + 1, $index2 - $index1 - 1); $iter = int ($iter); next unless ($iter > 0); $index1 = index ($hash_in, '*', $index2 + 1); next unless ($index1 >= 0); # salt $salt = substr ($hash_in, $index2 + 1, $index1 - $index2 - 1); next unless (length ($salt) == 40); # dpic and dpsl if ($mode == 14700) { $index2 = index ($hash_in, '**', $index1 + 1); next unless ($index2 != $index1 + 1); } else { $index2 = index ($hash_in, '*', $index1 + 1); next unless ($index2 >= 0); # dpic my $dpic = substr ($hash_in, $index1 + 1, $index2 - $index1 - 1); $dpic = int ($dpic); next unless ($dpic > 0); $param2 = $dpic; # dpsl my $dpsl = substr ($hash_in, $index2 + 1); next unless (length ($dpsl) == 40); $dpsl = pack ("H*", $dpsl); $param3 = $dpsl; } } # base64 and salt embedded SSHA256, salt length = total length - 32 elsif ($mode == 1411) { # split hash and plain my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); # remove signature my $plain_base64 = substr ($hash_in, 9); # base64 decode to extract salt my $decoded = decode_base64 ($plain_base64); $salt = substr ($decoded, 32); } # Atlassian (PBKDF2-HMAC-SHA1) elsif ($mode == 12001) { my $index = index ($line, ":"); next if $index < 1; $hash_in = substr ($line, 0, $index); $word = substr ($line, $index + 1); next unless (substr ($hash_in, 0, 9) eq '{PKCS5S2}'); # base64 buf my $base64_buf = substr ($hash_in, 9); my $base64_buf_decoded = decode_base64 ($base64_buf); next if (length ($base64_buf_decoded) != (16 + 32)); $salt = substr ($base64_buf_decoded, 0, 16); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 15100) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\$', $hash_in); next unless scalar @data == 5; shift @data; my $signature = shift @data; next unless ($signature eq 'sha1'); $iter = shift @data; $salt = shift @data; $param = shift @data; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 15200) { my $index1 = index ($line, ':'); next if ($index1 < 0); $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); my (undef, $signature, $version, $iter_count, $data_len, $data_buf) = split '\$', $hash_in; next unless ($signature eq "blockchain"); next unless ($version eq "v2"); next unless (($data_len * 2) == length $data_buf); $iter = $iter_count; $salt = substr ($data_buf, 0, 32); $param = substr ($data_buf, 32); next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 15300 || $mode == 15900) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @tmp_data = split ('\$', $hash_in); my $signature = $tmp_data[1]; next unless ($signature eq 'DPAPImk'); my @data = split ('\*', $tmp_data[2]); next unless (scalar @data == 9); my $version = shift @data; next unless ($version == 1 || $version == 2); my $context = shift @data; my $SID = shift @data; my $cipher_algorithm = shift @data; my $hash_algorithm = shift @data; my $iteration = shift @data; my $iv = shift @data; my $cipher_len = shift @data; my $cipher = shift @data; next unless (length ($cipher) == $cipher_len); if ($version == 1) { next unless ($cipher_len == 208); } elsif ($version == 2) { next unless ($cipher_len == 288); } $salt = substr ($hash_in, length ('$DPAPImk$')); $param = $cipher; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # chacha elsif ($mode == 15400) { my $index1 = index ($line, ':'); next if ($index1 < 0); $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next if (length ($hash_in) < 11); next unless (substr ($hash_in, 0, 11) eq "\$chacha20\$\*"); my @data = split ('\*', $hash_in); next unless (scalar (@data) == 6); $param = $data[1]; # counter $param2 = $data[2]; # offset $param3 = $data[3]; # iv next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # jksprivk elsif ($mode == 15500) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\*', $hash_in); next unless scalar @data == 7; my $signature = shift @data; next unless ($signature eq '$jksprivk$'); my $checksum = shift @data; my $iv = shift @data; my $enc_key = shift @data; my $DER1 = shift @data; my $DER2 = shift @data; my $alias = shift @data; $param = $iv; $param2 = $enc_key; $param3 = $alias; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Ethereum - PBKDF2 elsif ($mode == 15600) { my $index1 = index ($line, ':'); next if ($index1 < 0); $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next if (length ($hash_in) < 12); next unless (substr ($hash_in, 0, 12) eq "\$ethereum\$p\*"); my @data = split ('\*', $hash_in); next unless (scalar (@data) == 5); $iter = $data[1]; $salt = pack ("H*", $data[2]); $param = pack ("H*", $data[3]); # ciphertext next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Ethereum - Scrypt elsif ($mode == 15700) { my $index1 = index ($line, ':'); next if ($index1 < 0); $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next if (length ($hash_in) < 12); next unless (substr ($hash_in, 0, 12) eq "\$ethereum\$s\*"); my @data = split ('\*', $hash_in); next unless (scalar (@data) == 7); $param = $data[1]; # scrypt_N $param2 = $data[2]; # scrypt_r $param3 = $data[3]; # scrypt_p $salt = pack ("H*", $data[4]); $param4 = pack ("H*", $data[5]); # ciphertext next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # tacacs-plus elsif ($mode == 16100) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\$', $hash_in); next unless scalar @data == 6; shift @data; my $signature = shift @data; next unless ($signature eq "tacacs-plus"); my $auth_version = shift @data; next unless ($auth_version eq "0"); my $session_id = shift @data; my $encrypted_data = shift @data; my $sequence = shift @data; $param = $session_id; $param2 = $encrypted_data; $param3 = $sequence; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # apple secure notes elsif ($mode == 16200) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\*', $hash_in); next unless scalar @data == 5; my $signature = shift @data; next unless ($signature eq '$ASN$'); my ($Z_PK, $ZCRYPTOITERATIONCOUNT, $ZCRYPTOSALT, $ZCRYPTOWRAPPEDKEY) = @data; $salt = $ZCRYPTOSALT; $iter = $ZCRYPTOITERATIONCOUNT; $param = $Z_PK; $param2 = $ZCRYPTOWRAPPEDKEY; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Ethereum Pre-Sale - PBKDF2 elsif ($mode == 16300) { my $index1 = index ($line, ':'); next if ($index1 < 0); $hash_in = substr ($line, 0, $index1); $word = substr ($line, $index1 + 1); next if (length ($hash_in) < 12); next unless (substr ($hash_in, 0, 12) eq "\$ethereum\$w\*"); my @data = split ('\*', $hash_in); next unless (scalar (@data) == 4); $param = pack ("H*", $data[1]); # encseed $salt = $data[2]; # ethaddr $param2 = pack ("H*", $data[3]); # bpk (the iv + keccak digest) next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # JWT elsif ($mode == 16500) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split (/\./, $hash_in); next unless scalar @data == 3; my ($header, $payload, $signature) = @data; $salt = $header . "." . $payload; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Electrum Wallet (Salt-Type 1-3) elsif ($mode == 16600) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split (/\*/, $hash_in); next unless scalar @data == 3; my ($mode, $iv, $encrypted) = @data; my (undef, $signature, $salt_type) = split ('\$', $mode); next unless ($signature eq "electrum"); $param = $salt_type; $param2 = $iv; $param3 = $encrypted; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # FileVault 2 elsif ($mode == 16700) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\$', $hash_in); next unless scalar @data == 7; shift @data; my $signature = shift @data; next unless ($signature eq 'fvde'); my $Z_PK = shift @data; next unless ($Z_PK eq '1'); my $salt_length = shift @data; next unless ($salt_length eq '16'); my ($ZCRYPTOSALT, $ZCRYPTOITERATIONCOUNT, $ZCRYPTOWRAPPEDKEY) = @data; $salt = $ZCRYPTOSALT; $iter = $ZCRYPTOITERATIONCOUNT; $param = $Z_PK; $param2 = $ZCRYPTOWRAPPEDKEY; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # WPA-PMKID-PMKDF2 elsif ($mode == 16800) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split (/\*/, $hash_in); next unless scalar @data == 4; my ($pmkid, $macap, $macsta, $essid) = @data; $param = $macap; $param2 = $macsta; $param3 = $essid; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # Ansible Vault elsif ($mode == 16900) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\*', $hash_in); next unless scalar @data == 5; my ($signature_tmp, $cipher, $salt, $ciphertext, $hmac) = @data; my ($signature, undef) = split ('\$', $signature_tmp); next unless ($signature eq "ansible"); $param = $ciphertext; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 18200) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\$', $hash_in); next unless scalar @data == 8; shift @data; my $signature = shift @data; my $algorithm = shift @data; my $user_principal_name = shift @data; my $checksum = shift @data; my $edata2 = shift @data; next unless ($signature eq "krb5asrep"); next unless (length ($checksum) == 32); next unless (length ($edata2) >= 64); $salt = $user_principal_name; $param = $checksum; $param2 = $edata2; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } # FileVault 2 elsif ($mode == 18300) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; my @data = split ('\$', $hash_in); next unless scalar @data == 7; shift @data; my $signature = shift @data; next unless ($signature eq 'fvde'); my $Z_PK = shift @data; next unless ($Z_PK eq '2'); my $salt_length = shift @data; next unless ($salt_length eq '16'); my ($ZCRYPTOSALT, $ZCRYPTOITERATIONCOUNT, $ZCRYPTOWRAPPEDKEY) = @data; $salt = $ZCRYPTOSALT; $iter = $ZCRYPTOITERATIONCOUNT; $param = $Z_PK; $param2 = $ZCRYPTOWRAPPEDKEY; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 18400) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; # tokenize my @data = split ('\*', $hash_in); next unless scalar @data == 12; my $signature = shift @data; my $cipher_type = shift @data; my $cs_type = shift @data; $iter = shift @data; my $cs_len = shift @data; my $cs = shift @data; my $iv_len = shift @data; my $iv = shift @data; my $salt_len = shift @data; $salt = shift @data; my $unused = shift @data; my $ciphertext = shift @data; # validate next unless ($signature eq '$odf$'); next unless ($cipher_type eq '1'); next unless ($cs_type eq '1'); next unless ($cs_len eq '32'); next unless ($iv_len eq '16'); next unless ($salt_len eq '16'); next unless ($unused eq '0'); next unless defined $ciphertext; # decrypt my $b_iv = pack ("H*", $iv); my $b_salt = pack ("H*", $salt); my $b_ciphertext = pack ("H*", $ciphertext); my $kdf = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => $iter, output_len => 32 ); my $pass_hash = sha256 ($word); my $derived_key = $kdf->PBKDF2 ($b_salt, $pass_hash); my $cbc = Crypt::Mode::CBC->new ('AES', 0); my $b_plaintext = $cbc->decrypt ($b_ciphertext, $derived_key, $b_iv); my $plaintext = unpack ("H*", $b_plaintext); $param = $iv; $param2 = $plaintext; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } elsif ($mode == 18600) { ($hash_in, $word) = split ":", $line; next unless defined $hash_in; next unless defined $word; # tokenize my @data = split ('\*', $hash_in); next unless scalar @data == 12; my $signature = shift @data; my $cipher_type = shift @data; my $cs_type = shift @data; $iter = shift @data; my $cs_len = shift @data; my $cs = shift @data; my $iv_len = shift @data; my $iv = shift @data; my $salt_len = shift @data; $salt = shift @data; my $unused = shift @data; my $ciphertext = shift @data; # validate next unless ($signature eq '$odf$'); next unless ($cipher_type eq '0'); next unless ($cs_type eq '0'); next unless ($cs_len eq '16'); next unless ($iv_len eq '8'); next unless ($salt_len eq '16'); next unless ($unused eq '0'); next unless defined $ciphertext; # decrypt my $b_iv = pack ("H*", $iv); my $b_salt = pack ("H*", $salt); my $b_ciphertext = pack ("H*", $ciphertext); my $kdf = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => $iter, output_len => 16 ); my $pass_hash = sha1 ($word); my $derived_key = $kdf->PBKDF2 ($b_salt, $pass_hash); my $cfb = Crypt::GCrypt->new( type => 'cipher', algorithm => 'blowfish', mode => 'cfb' ); $cfb->start ('decrypting'); $cfb->setkey ($derived_key); $cfb->setiv ($b_iv); my $b_plaintext = $cfb->decrypt ($b_ciphertext); $cfb->finish (); my $plaintext = unpack ("H*", $b_plaintext); $param = $iv; $param2 = $plaintext; next unless (exists ($db->{$hash_in}) and (! defined ($db->{$hash_in}))); } ## STEP 2c: Add your custom hash parser branch here else { print "ERROR: hash mode is not supported\n"; exit (1); } if ($word =~ m/^\$HEX\[[0-9a-fA-F]*\]$/) { $word = pack ("H*", substr ($word, 5, -1)); } # finally generate the hash # special case: if ($mode == 6800) { # check both variations $hash_out = gen_hash ($mode, $word, $salt, $iter, 1); $len = length $hash_out; # == length $alternative if (substr ($line, 0, $len) ne $hash_out) { my $alternative = gen_hash ($mode, $word, $salt, $iter, 2); return unless (substr ($line, 0, $len) eq $alternative); } } elsif ($mode == 8700) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 8900) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param, $param2, $param3); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 9100) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 3300) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 5100) { # check 3 variants (start, middle, end) my $idx = 0; $hash_out = gen_hash ($mode, $word, $salt, $iter, $idx++); $len = length $hash_out; # == length $alternative if (substr ($line, 0, $len) ne $hash_out) { my $alternative = gen_hash ($mode, $word, $salt, $iter, $idx++); if (substr ($line, 0, $len) ne $alternative) { my $alternative = gen_hash ($mode, $word, $salt, $iter, $idx++); return unless (substr ($line, 0, $len) eq $alternative); } } } elsif ($mode == 9400) { $hash_out = gen_hash ($mode, $word, $salt, 50000, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 9500) { $hash_out = gen_hash ($mode, $word, $salt, 100000, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 9600) { $hash_out = gen_hash ($mode, $word, $salt, 100000, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 9700) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 9800) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 10200) { $hash_out = gen_hash ($mode, $word, $salt, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 10400) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param, $param2, $param3); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 10500) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param, $param2, $param3, $param4, $param5, $param6); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 10600) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 10700) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 10900) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 11100) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 11400) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2, $param3, $param4, $param5, $param6, $param7, $param8, $param9, $param10, $param11); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 11600) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2, $param3, $param4, $param5, $param6); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 11900) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 12000) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 12100) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 12200) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 12700) { # this is very special, we can't call gen_hash () because the param part is not always the same # we only know that it should contain the letters "guid" at the beginning of the decryted string my $pbkdf2 = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => 10, output_len => 32 ); my $salt_bin = pack ("H*", $salt); my $key = $pbkdf2->PBKDF2 ($salt_bin, $word); my $cipher = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $salt_bin, literal_key => 1, header => "none", keysize => 32 }); my $param_bin = pack ("H*", $param); my $decrypted = $cipher->decrypt ($param_bin); my $decrypted_part = substr ($decrypted, 1, 16); return unless ($decrypted_part =~ /"guid"/); $hash_out = $hash_in; } elsif ($mode == 12900) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 13000) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 13100) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 13200) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 13300) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 13400) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 13600) { $hash_out = gen_hash ($mode, $word, undef, undef, $param, $param2, $param3, $param4, $param5, $param6); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 14700) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 14800) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2, $param3); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 15100) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 15200) { # this is very special, we can't call gen_hash () because the param part is not always the same # we only know that it should contain the letters "guid" at the beginning of the decryted string my $pbkdf2 = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => 5000, output_len => 32 ); my $salt_bin = pack ("H*", $salt); my $key = $pbkdf2->PBKDF2 ($salt_bin, $word); my $cipher = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $salt_bin, literal_key => 1, header => "none", keysize => 32 }); my $param_bin = pack ("H*", $param); my $decrypted = $cipher->decrypt ($param_bin); my $decrypted_part = substr ($decrypted, 1, 16); return unless ($decrypted_part =~ /"guid"/); $hash_out = $hash_in; } elsif ($mode == 15300 || $mode == 15900) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 15400) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param, $param2, $param3); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 15500) { $hash_out = gen_hash ($mode, $word, undef, undef, $param, $param2, $param3); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 15600) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 15700) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param, $param2, $param3, $param4); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 16100) { $hash_out = gen_hash ($mode, $word, undef, 0, $param, $param2, $param3); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 16200) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 16300) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 16600) { $hash_out = gen_hash ($mode, $word, undef, 0, $param, $param2, $param3); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 16700) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 16800) { $hash_out = gen_hash ($mode, $word, undef, 0, $param, $param2, $param3); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 16900) { $hash_out = gen_hash ($mode, $word, $salt, 0, $param); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 18200) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 18300) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 18400) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } elsif ($mode == 18600) { $hash_out = gen_hash ($mode, $word, $salt, $iter, $param, $param2); $len = length $hash_out; return unless (substr ($line, 0, $len) eq $hash_out); } ## STEP 2c: Add your custom gen_hash call here else { $hash_out = gen_hash ($mode, $word, $salt, $iter); $len = length $hash_out; # special cases: if ($mode == 400) { # allow $P$ and $H$ for -m 400 next unless (substr ($line, 3, $len - 3) eq substr ($hash_out, 3)); } elsif ($mode == 5600) { # hashcat outputs the user name always upper-case, we need next unless (substr ($line, 0, $len) eq $hash_out); my $found = 0; my $hash_out_lower = lc ($hash_out); for my $key (keys %{$db}) { if (lc ($key) eq $hash_out_lower) { $found = 1; last; } } next unless $found; } else { next unless (substr ($line, 0, $len) eq $hash_out); } } # do not forget "exists ($db->$hash_out)" should be done above! $db->{$hash_out} = $word; print OUT $line . "\n"; } close (IN); close (OUT); } sub passthrough { my $mode = shift || 0; while (my $word_buf = <>) { chomp ($word_buf); next if length ($word_buf) > 256; ## ## gen salt ## my @salt_arr; for (my $i = 0; $i < 256; $i++) { my $c = get_random_chr (0x30, 0x39); push (@salt_arr, $c); } my $salt_buf = join ("", @salt_arr); ## ## gen hash ## my $tmp_hash; # unsalted if (is_in_array ($mode, $COMMON_UNSALTED_MODES) || $mode == 2400 || $mode == 13300) { $tmp_hash = gen_hash ($mode, $word_buf, ""); } elsif (is_in_array ($mode, $COMMON_DEFAULT_SALTED_MODES) || $mode == 1411 || $mode == 1711 || $mode == 3711 || $mode == 3800 || $mode == 4900 || $mode == 8900 || $mode == 10000 || $mode == 10200 || $mode == 10900 || $mode == 11900 || $mode == 12000 || $mode == 12100) { my $salt_len = get_random_num (1, 15); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 11 || $mode == 12) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 21) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 2)); } elsif ($mode == 22) { my $salt_len = get_random_num (1, 11); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 111 || $mode == 122 || $mode == 131 || $mode == 132 || $mode == 400 || $mode == 500 || $mode == 1600 || $mode == 1722 || $mode == 1731 || $mode == 1800 || $mode == 6300 || $mode == 7900 || $mode == 8100 || $mode == 11100) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 8)); } elsif ($mode == 112) { next if length ($word_buf) > 30; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 20)); } elsif ($mode == 121) { my $salt_len = get_random_num (1, 9); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 125) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 8)); } elsif ($mode == 141 || $mode == 1441) { my $salt_len = get_random_num (1, 15); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 1100) { my $salt_len = get_random_num (1, 19); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 1500) { next if length ($word_buf) > 8; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 2)); } elsif ($mode == 2100) { next if length ($word_buf) > 13; my $salt_len = get_random_num (1, 19); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 2410) { my $salt_len = get_random_num (1, 4); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 2500) { next if length ($word_buf) < 8; my $salt_len = get_random_num (0, 32); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 2611) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 3)); } elsif ($mode == 2612) { my $salt_len = get_random_num (1, 22); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 2711) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 30)); } elsif ($mode == 2811) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 5)); } elsif ($mode == 3000) { next if length ($word_buf) > 7; $tmp_hash = gen_hash ($mode, $word_buf, ""); } elsif ($mode == 3100) { next if length ($word_buf) > 30; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 10)); } elsif ($mode == 3200 || $mode == 5800 || $mode == 6400 || $mode == 6500 || $mode == 6700 || $mode == 7400 || $mode == 3300 || $mode == 8000 || $mode == 9100 || $mode == 12001 || $mode == 12200 || $mode == 15600) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 16)); } elsif ($mode == 3800 || $mode == 4900) { my $salt_len = get_random_num (1, 11); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 4520) { my $salt_len = get_random_num (1, 50); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 4521 || $mode == 15700) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 4522) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 12)); } elsif ($mode == 4800) { $salt_buf = get_random_md5chap_salt (substr ($salt_buf, 0, 16)); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 5300 || $mode == 5400) { $salt_buf = get_random_ike_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 5500) { my $user_len = get_random_num (0, 15); my $domain_len = get_random_num (0, 15); $salt_buf = get_random_netntlmv1_salt ($user_len, $domain_len); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 5600) { my $user_len = get_random_num (0, 15); my $domain_len = get_random_num (0, 15); $salt_buf = get_random_netntlmv2_salt ($user_len, $domain_len); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 6600) { $salt_buf = get_random_agilekeychain_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 6800) { my $email_len = get_random_num (1, 15); my $email = ""; for (my $i = 0; $i < $email_len; $i++) { $email .= get_random_chr (0x61, 0x7a); } $email .= '@trash-mail.com'; $tmp_hash = gen_hash ($mode, $word_buf, $email); } elsif ($mode == 7000) { next if length ($word_buf) > 19; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 24)); } elsif ($mode == 7100) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 64)); } elsif ($mode == 7200) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 128)); } elsif ($mode == 7300) { my $salt_len = get_random_num (32, 256); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 7500) { $salt_buf = get_random_kerberos5_salt (substr ($salt_buf, 0, 16)); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 7700 || $mode == 7701) { next if length ($word_buf) > 8; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 12)); } elsif ($mode == 7800 || $mode == 7801) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 12)); } elsif ($mode == 8200) { $salt_buf = get_random_cloudkeychain_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 8300) { $salt_buf = get_random_dnssec_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 8400 || $mode == 11200 || $mode == 16300) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 40)); } elsif ($mode == 8500) { next if length ($word_buf) > 8; my $salt_len = get_random_num (1, 9); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 8600) { next if length ($word_buf) > 16; $tmp_hash = gen_hash ($mode, $word_buf, ""); } elsif ($mode == 8700) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 5)); } elsif ($mode == 9200 || $mode == 9300) { my $salt_len = 14; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 9400 || $mode == 9500 || $mode == 9600) { next if length ($word_buf) > 19; my $salt_len = 32; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 9700 || $mode == 9800) { next if length ($word_buf) > 15; my $salt_len = 32; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 10100) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 10300) { my $salt_len = get_random_num (4, 15); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 10400) { next if length ($word_buf) > 31; my $salt_len = 32; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 10500) { next if length ($word_buf) > 15; my $salt_len = 32; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 10600) { next if length ($word_buf) > 31; my $salt_len = 32; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 10700) { next if length ($word_buf) > 15; my $salt_len = 32; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 11000) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 56)); } elsif ($mode == 11300) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 16)); } elsif ($mode == 11400) { next if length ($word_buf) > 24; my $salt_len = get_random_num (1, 15); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 11600) { my $salt_len = get_random_num (0, 16); $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, $salt_len)); } elsif ($mode == 12300) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 12400) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 4)); } elsif ($mode == 12600 || $mode == 15000) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 64)); } elsif ($mode == 12700) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 12800) { next if length ($word_buf) > 24; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 20)); } elsif ($mode == 12900) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 13000) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 13100) { $salt_buf = get_random_kerberos5_tgs_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 13200) { $salt_buf = get_random_axcrypt_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 13400) { $salt_buf = get_random_keepass_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 13500) { $salt_buf = get_pstoken_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 13600) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 13800) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 256)); } elsif ($mode == 13900) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 9)); } elsif ($mode == 14000) { next if length ($word_buf) != 8; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 16)); } elsif ($mode == 14100) { next if length ($word_buf) != 24; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 16)); } elsif ($mode == 14400) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 20)); } elsif (($mode == 14700) || ($mode == 14800)) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 40)); } elsif ($mode == 14900) { next if length ($word_buf) != 10; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 8)); } elsif ($mode == 15100) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 8)); } elsif ($mode == 15200) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 15300 || $mode == 15900) { my $version = 2; if ($mode == 15300) { $version = 1; } $salt_buf = get_random_dpapimk_salt ($version); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 15400) { next if length ($word_buf) != 32; $tmp_hash = gen_hash ($mode, $word_buf, ""); } elsif ($mode == 15500) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 40)); } elsif ($mode == 16000) { next if length ($word_buf) > 8; $tmp_hash = gen_hash ($mode, $word_buf, ""); } elsif ($mode == 16100) { $tmp_hash = gen_hash ($mode, $word_buf, undef); } elsif ($mode == 16200) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 16500) { $salt_buf = get_random_jwt_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 16600) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 16700) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 16800) { next if length ($word_buf) < 8; $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 16900) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 64)); } elsif ($mode == 18200) { $salt_buf = get_random_kerberos5_as_rep_salt (); $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); } elsif ($mode == 18300) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 18400) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } elsif ($mode == 18600) { $tmp_hash = gen_hash ($mode, $word_buf, substr ($salt_buf, 0, 32)); } ## STEP 2c: Add your custom salt branch here else { print "ERROR: Unsupported hash type\n"; exit (1); } print $tmp_hash, "\n"; } } sub single { my $mode = shift; if (defined $mode) { @{$MODES} = ($mode); } for (my $j = 0; $j < scalar @{$MODES}; $j++) { my $mode = $MODES->[$j]; if (is_in_array ($mode, $COMMON_UNSALTED_MODES) || $mode == 5300 || $mode == 5400 || $mode == 6600 || $mode == 8200 || $mode == 8300 || $mode == 13300) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 0); } else { rnd ($mode, $i, 0); } } } elsif (is_in_array ($mode, $COMMON_DEFAULT_SALTED_MODES) || $mode == 121 || $mode == 1411 || $mode == 1711 || $mode == 3711 || $mode == 8900 || $mode == 10000 || $mode == 10200 || $mode == 10900 || $mode == 11900 || $mode == 12000 || $mode == 12100 || $mode == 16500) { my $salt_len = get_random_num (1, 15); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 11 || $mode == 12) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 21 || $mode == 22) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 2); } else { rnd ($mode, $i, 2); } } } elsif ($mode == 111 || $mode == 122 || $mode == 125 || $mode == 131 || $mode == 132 || $mode == 400 || $mode == 500 || $mode == 1600 || $mode == 1722 || $mode == 1731 || $mode == 6300 || $mode == 7900 || $mode == 8100 || $mode == 11100) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 8); } else { rnd ($mode, $i, 8); } } } elsif ($mode == 112) { for (my $i = 1; $i < 31; $i++) { if ($len != 0) { rnd ($mode, $len, 20); } else { rnd ($mode, $i, 20); } } } elsif ($mode == 141 || $mode == 3300 || $mode == 1441 || $mode == 1800 || $mode == 3200 || $mode == 4800 || $mode == 6400 || $mode == 6500 || $mode == 6700 || $mode == 7400 || $mode == 8000 || $mode == 9100 || $mode == 12001 || $mode == 12200 || $mode == 15600) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 1100) { my $salt_len = get_random_num (1, 19); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 1500) { for (my $i = 1; $i < 9; $i++) { if ($len != 0) { rnd ($mode, $len, 2); } else { rnd ($mode, $i, 2); } } } elsif ($mode == 2100) { my $salt_len = get_random_num (1, 19); for (my $i = 1; $i < 13; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 2400) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 0); } else { rnd ($mode, $i, 0); } } } elsif ($mode == 2410) { my $salt_len = get_random_num (3, 4); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 2500) { my $salt_len = get_random_num (0, 32); for (my $i = 8; $i < 16; $i++) { if ($len != 0) { if ($len < 8) { $len += 7; } rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 2611) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 3); } else { rnd ($mode, $i, 3); } } } elsif ($mode == 2612) { my $salt_len = get_random_num (1, 22); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 2711) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 30); } else { rnd ($mode, $i, 30); } } } elsif ($mode == 2811) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 5); } else { rnd ($mode, $i, 5); } } } elsif ($mode == 3000) { for (my $i = 1; $i < 8; $i++) { if ($len != 0) { rnd ($mode, $len, 0); } else { rnd ($mode, $i, 0); } } } elsif ($mode == 3100) { for (my $i = 1; $i < 31; $i++) { if ($len != 0) { rnd ($mode, $len, 10); } else { rnd ($mode, $i, 10); } } } elsif ($mode == 3800 || $mode == 4900) { my $salt_len = get_random_num (1, 11); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 4520) { my $salt_len = get_random_num (1, 50); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 4521 || $mode == 15700) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 4522) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 12); } else { rnd ($mode, $i, 12); } } } elsif ($mode == 5500 || $mode == 5600) { my $salt_len; for (my $i = 1; $i < 27; $i++) { $salt_len = get_random_num (1, 15); if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 5800) { for (my $i = 1; $i < 14; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 6800) { my $salt_len = get_random_num (8, 25); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 7000) { for (my $i = 1; $i < 19; $i++) { if ($len != 0) { rnd ($mode, $len, 24); } else { rnd ($mode, $i, 24); } } } elsif ($mode == 7100) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 64); } else { rnd ($mode, $i, 64); } } } elsif ($mode == 7200) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 128); } else { rnd ($mode, $i, 128); } } } elsif ($mode == 7300) { my $salt_len = get_random_num (32, 255); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 7500) { for (my $i = 1; $i < 27; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 7700 || $mode == 7701) { my $salt_len = get_random_num (1, 12); for (my $i = 1; $i < 9; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 7800 || $mode == 7801) { my $salt_len = get_random_num (1, 12); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 8400 || $mode == 11200 || $mode == 14700 || $mode == 14800 || $mode == 16300) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 40); } else { rnd ($mode, $i, 40); } } } elsif ($mode == 8500) { my $salt_len = get_random_num (1, 8); for (my $i = 1; $i < 9; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 8600) { for (my $i = 1; $i < 17; $i++) { if ($len != 0) { rnd ($mode, $len, 0); } else { rnd ($mode, $i, 0); } } } elsif ($mode == 8700) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 5); } else { rnd ($mode, $i, 5); } } } elsif ($mode == 9200 || $mode == 9300) { my $salt_len = 14; for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 9400 || $mode == 9500 || $mode == 9600) { my $salt_len = 32; for (my $i = 1; $i < 20; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 9700 || $mode == 9800) { my $salt_len = 32; for (my $i = 1; $i < 16; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 10100) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 10300) { my $salt_len = get_random_num (4, 15); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 10400 || $mode == 10600) { my $salt_len = 32; for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 10500 || $mode == 10700) { my $salt_len = 32; for (my $i = 1; $i < 16; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 11000) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 56); } else { rnd ($mode, $i, 56); } } } elsif ($mode == 11300) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 11400) { for (my $i = 1; $i < 24; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 11600) { my $salt_len = get_random_num (0, 16); for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 12300) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 12400) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 4); } else { rnd ($mode, $i, 4); } } } elsif ($mode == 12600 || $mode == 15000) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 64); } else { rnd ($mode, $i, 64); } } } elsif ($mode == 12700) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 12800) { for (my $i = 1; $i < 25; $i++) { if ($len != 0) { rnd ($mode, $len, 20); } else { rnd ($mode, $i, 20); } } } elsif ($mode == 12900) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 13000) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 13100) { for (my $i = 1; $i < 27; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 13200) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 13400) { for (my $i = 1; $i < 16; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 13500) { for (my $i = 1; $i < 16; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 13600) { for (my $i = 1; $i < 16; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 13800) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 256); } else { rnd ($mode, $i, 256); } } } elsif ($mode == 13900) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 9); } else { rnd ($mode, $i, 9); } } } elsif ($mode == 14000) { rnd ($mode, 8, 16); } elsif ($mode == 14100) { rnd ($mode, 24, 16); } elsif ($mode == 14400) { for (my $i = 1; $i < 24; $i++) { if ($len != 0) { rnd ($mode, $len, 20); } else { rnd ($mode, $i, 20); } } } elsif ($mode == 14900) { rnd ($mode, 10, 8); } elsif ($mode == 15100) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 8); } else { rnd ($mode, $i, 8); } } } elsif ($mode == 15200) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 15300 || $mode == 15900) { for (my $i = 1; $i < 16; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 15400) { rnd ($mode, 32, 0); } elsif ($mode == 15500) { for (my $i = 1; $i < 16; $i++) { if ($len != 0) { rnd ($mode, $len, 40); } else { rnd ($mode, $i, 40); } } } elsif ($mode == 16000) { for (my $i = 1; $i < 9; $i++) { if ($len != 0) { rnd ($mode, $len, 0); } else { rnd ($mode, $i, 0); } } } elsif ($mode == 16100) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 0); } else { rnd ($mode, $i, 0); } } } elsif ($mode == 16200) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 16600) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 16700) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 16800) { my $salt_len = get_random_num (0, 32); for (my $i = 8; $i < 16; $i++) { if ($len != 0) { if ($len < 8) { $len += 7; } rnd ($mode, $len, $salt_len); } else { rnd ($mode, $i, $salt_len); } } } elsif ($mode == 16900) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 64); } else { rnd ($mode, $i, 64); } } } elsif ($mode == 18200) { for (my $i = 1; $i < 27; $i++) { if ($len != 0) { rnd ($mode, $len, 16); } else { rnd ($mode, $i, 16); } } } elsif ($mode == 18300) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 18400) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } elsif ($mode == 18600) { for (my $i = 1; $i < 32; $i++) { if ($len != 0) { rnd ($mode, $len, 32); } else { rnd ($mode, $i, 32); } } } ## STEP 2c: Add your custom salt branch here } } exit; ## STEP 3: Implement hash generation for your hash mode here. # # For an example of how to use python, see mode 11700. # For an example of how to use PHP, see mode 11900. # # Don't forget to add the modules you depend on to the # installation script. # ## sub gen_hash { my $mode = shift; my $word_buf = shift; my $salt_buf = shift; my $iter = shift; my $additional_param = shift; my $additional_param2 = shift; my $additional_param3 = shift; my $additional_param4 = shift; my $additional_param5 = shift; my $additional_param6 = shift; my $additional_param7 = shift; my $additional_param8 = shift; my $additional_param9 = shift; my $additional_param10 = shift; my $additional_param11 = shift; ## ## gen hash ## my $tmp_hash; my $hash_buf; if ($mode == 0) { $hash_buf = md5_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 10) { $hash_buf = md5_hex ($word_buf . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 11) { $hash_buf = md5_hex ($word_buf . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 12) { $hash_buf = md5_hex ($word_buf . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 20) { $hash_buf = md5_hex ($salt_buf . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 21) { $hash_buf = md5_hex ($salt_buf . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 22) { my $itoa64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; my $salt_suffix = "Administration Tools"; my $pass = sprintf ("%s:%s:%s", $salt_buf, $salt_suffix, $word_buf); $hash_buf = md5 ($pass); my $res = ""; for (my $pos = 0; $pos < 16; $pos += 2) { my $octet1 = ord (substr ($hash_buf, $pos + 0, 1)); my $octet2 = ord (substr ($hash_buf, $pos + 1, 1)); my $num = ($octet1 <<8 & 0xff00) | ($octet2 & 0xff); my $idx1 = $num >> 12 & 0x0f; my $idx2 = $num >> 6 & 0x3f; my $idx3 = $num & 0x3f; $res = $res . substr ($itoa64, $idx1, 1) . substr ($itoa64, $idx2, 1) . substr ($itoa64, $idx3, 1); } my $obfuscate_str = "nrcstn"; my @obfuscate_pos = (0, 6, 12, 17, 23, 29); foreach my $pos (keys @obfuscate_pos) { my $idx = $obfuscate_pos[$pos]; my $before = substr ($res, 0, $idx); my $char = substr ($obfuscate_str, $pos, 1); my $after = substr ($res, $idx); $res = sprintf ("%s%s%s", $before, $char, $after); } $tmp_hash = sprintf ("%s:%s", $res, $salt_buf); } elsif ($mode == 23) { $hash_buf = md5_hex ($salt_buf . "\nskyper\n" . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 30) { $hash_buf = md5_hex (encode ("UTF-16LE", $word_buf) . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 40) { $hash_buf = md5_hex ($salt_buf . encode ("UTF-16LE", $word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 50) { $hash_buf = hmac_hex ($salt_buf, $word_buf, \&md5, 64); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 60) { $hash_buf = hmac_hex ($word_buf, $salt_buf, \&md5, 64); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 100) { $hash_buf = sha1_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 101) { $hash_buf = sha1 ($word_buf); my $base64_buf = encode_base64 ($hash_buf, ""); $tmp_hash = sprintf ("{SHA}%s", $base64_buf); } elsif ($mode == 110) { $hash_buf = sha1_hex ($word_buf . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 111) { $hash_buf = sha1 ($word_buf . $salt_buf); my $base64_buf = encode_base64 ($hash_buf . $salt_buf, ""); $tmp_hash = sprintf ("{SSHA}%s", $base64_buf); } elsif ($mode == 112) { my $salt_buf_bin = pack ("H*", $salt_buf); $hash_buf = sha1_hex ($word_buf . $salt_buf_bin); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 120) { $hash_buf = sha1_hex ($salt_buf . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 121) { $hash_buf = sha1_hex (lc ($salt_buf) . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 122) { my $salt_buf_bin = pack ("H*", $salt_buf); $hash_buf = sha1_hex ($salt_buf_bin . $word_buf); $tmp_hash = sprintf ("%s%s", $salt_buf, $hash_buf); } elsif ($mode == 125) { my $signature = "01"; my $salt_buf_bin = pack ("H*", $salt_buf . $signature); $hash_buf = sha1_hex ($salt_buf_bin . $word_buf); $tmp_hash = sprintf ("%s%s%s", $salt_buf, $signature, $hash_buf); } elsif ($mode == 130) { $hash_buf = sha1_hex (encode ("UTF-16LE", $word_buf) . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 131) { my $salt_buf_bin = pack ("H*", $salt_buf); $hash_buf = sha1_hex (encode ("UTF-16LE", uc ($word_buf)) . $salt_buf_bin); $tmp_hash = sprintf ("0x0100%s%s%s", $salt_buf, "0" x 40, $hash_buf); } elsif ($mode == 132) { my $salt_buf_bin = pack ("H*", $salt_buf); $hash_buf = sha1_hex (encode ("UTF-16LE", $word_buf) . $salt_buf_bin); $tmp_hash = sprintf ("0x0100%s%s", $salt_buf, $hash_buf); } elsif ($mode == 133) { $hash_buf = sha1 (encode ("UTF-16LE", $word_buf)); $hash_buf = encode_base64 ($hash_buf, ""); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 140) { $hash_buf = sha1_hex ($salt_buf . encode ("UTF-16LE", $word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 141) { $hash_buf = sha1 ($salt_buf . encode ("UTF-16LE", $word_buf)); my $base64_salt_buf = encode_base64 ($salt_buf, ""); my $base64_hash_buf = encode_base64 ($hash_buf, ""); $base64_hash_buf = substr ($base64_hash_buf, 0, 27); $tmp_hash = sprintf ("\$episerver\$*0*%s*%s", $base64_salt_buf, $base64_hash_buf); } elsif ($mode == 150) { $hash_buf = hmac_hex ($salt_buf, $word_buf, \&sha1, 64); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 160) { $hash_buf = hmac_hex ($word_buf, $salt_buf, \&sha1, 64); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 200) { my $ppr = Authen::Passphrase::MySQL323->new (passphrase => $word_buf); $hash_buf = $ppr->hash_hex; $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 300) { $hash_buf = substr (password41 ($word_buf), 1); $hash_buf = lc ($hash_buf); # useful for 'not matched' check only $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 400) { my $cost = 11; if (length ($iter)) { $cost = $iter; } my $ppr = Authen::Passphrase::PHPass->new ( cost => $cost, salt => $salt_buf, passphrase => $word_buf, ); $hash_buf = $ppr->as_rfc2307; $tmp_hash = sprintf ("%s", substr ($hash_buf, 7)); } elsif ($mode == 500) { my $iterations = 1000; if (defined ($iter)) { if ($iter > 0) { $iterations = int ($iter); } } $hash_buf = md5_crypt ('$1$', $iterations, $word_buf, $salt_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 600) { $hash_buf = lc blake2b_hex ($word_buf); $tmp_hash = sprintf ("\$BLAKE2\$" . $hash_buf); } elsif ($mode == 900) { $hash_buf = md4_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 1000) { $hash_buf = md4_hex (encode ("UTF-16LE", $word_buf)); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 1100) { $hash_buf = md4_hex (md4 (encode ("UTF-16LE", $word_buf)) . encode ("UTF-16LE", lc ($salt_buf))); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1300) { $hash_buf = sha224_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 1400) { $hash_buf = sha256_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 1410) { $hash_buf = sha256_hex ($word_buf . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1411) { $hash_buf = sha256_hex ($word_buf . $salt_buf); my $base64_buf = encode_base64 (pack ("H*", $hash_buf) . $salt_buf, ""); $tmp_hash = sprintf ("{SSHA256}%s", $base64_buf); } elsif ($mode == 1420) { $hash_buf = sha256_hex ($salt_buf . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1430) { $hash_buf = sha256_hex (encode ("UTF-16LE", $word_buf) . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1440) { $hash_buf = sha256_hex ($salt_buf . encode ("UTF-16LE", $word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1441) { $hash_buf = sha256 ($salt_buf . encode ("UTF-16LE", $word_buf)); my $base64_salt_buf = encode_base64 ($salt_buf, ""); my $base64_hash_buf = encode_base64 ($hash_buf, ""); $base64_hash_buf = substr ($base64_hash_buf, 0, 43); $tmp_hash = sprintf ("\$episerver\$*1*%s*%s", $base64_salt_buf, $base64_hash_buf); } elsif ($mode == 1450) { $hash_buf = hmac_hex ($salt_buf, $word_buf, \&sha256, 64); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1460) { $hash_buf = hmac_hex ($word_buf, $salt_buf, \&sha256, 64); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1500) { $hash_buf = crypt ($word_buf, $salt_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 1600) { my $iterations = 1000; if (defined ($iter)) { if ($iter > 0) { $iterations = int ($iter); } } $hash_buf = md5_crypt ('$apr1$', $iterations, $word_buf, $salt_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 1700) { $hash_buf = sha512_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 1710 || $mode == 15000) { $hash_buf = sha512_hex ($word_buf . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1711) { $hash_buf = sha512_hex ($word_buf . $salt_buf); my $base64_buf = encode_base64 (pack ("H*", $hash_buf) . $salt_buf, ""); $tmp_hash = sprintf ("{SSHA512}%s", $base64_buf); } elsif ($mode == 1720) { $hash_buf = sha512_hex ($salt_buf . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1730) { $hash_buf = sha512_hex (encode ("UTF-16LE", $word_buf) . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1740) { $hash_buf = sha512_hex ($salt_buf . encode ("UTF-16LE", $word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1722) { my $salt_buf_bin = pack ("H*", $salt_buf); $hash_buf = sha512_hex ($salt_buf_bin . $word_buf); $tmp_hash = sprintf ("%s%s", $salt_buf, $hash_buf); } elsif ($mode == 1731) { my $salt_buf_bin = pack ("H*", $salt_buf); $hash_buf = sha512_hex (encode ("UTF-16LE", $word_buf) . $salt_buf_bin); $tmp_hash = sprintf ("0x0200%s%s", $salt_buf, $hash_buf); } elsif ($mode == 1750) { $hash_buf = hmac_hex ($salt_buf, $word_buf, \&sha512, 128); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1760) { $hash_buf = hmac_hex ($word_buf, $salt_buf, \&sha512, 128); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 1800) { my $iterations = 5000; if (defined ($iter)) { if ($iter > 0) { $iterations = int ($iter); } } $hash_buf = sha512_crypt ($iterations, $word_buf, $salt_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 2100) { my $iterations = 10240; if (length ($iter)) { $iterations = int ($iter); } my $salt = encode ("UTF-16LE", lc ($salt_buf)); my $pbkdf2 = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => $iterations, output_len => 16, salt_len => length ($salt), ); $hash_buf = unpack ("H*", $pbkdf2->PBKDF2 ($salt, md4 (md4 (encode ("UTF-16LE", $word_buf)) . $salt))); $tmp_hash = sprintf ("\$DCC2\$%i#%s#%s", $iterations, $salt_buf, $hash_buf); } elsif ($mode == 2400) { my $word_len = length ($word_buf); my $pad_len = ceil ($word_len / 16) * 16; my $hash_buf = Digest::MD5::md5 ($word_buf . "\0" x ($pad_len - $word_len)); $tmp_hash = sprintf ("%s", pseudo_base64 ($hash_buf)); } elsif ($mode == 2410) { my $word_salt_buf = $word_buf . $salt_buf; my $word_salt_len = length ($word_salt_buf); my $pad_len = ceil ($word_salt_len / 16) * 16; my $hash_buf = Digest::MD5::md5 ($word_buf . $salt_buf . "\0" x ($pad_len - $word_salt_len)); $tmp_hash = sprintf ("%s:%s", pseudo_base64 ($hash_buf), $salt_buf); } elsif ($mode == 2500) { my ($bssid, $stmac, $snonce, $anonce, $eapol, $keyver, $eapol_len, $essid_len); if (! defined ($additional_param)) { # random stuff $bssid = randbytes (6); $stmac = randbytes (6); $snonce = randbytes (32); $anonce = randbytes (32); $keyver = get_random_num (1, 4); # 1, 2 or 3 # eapol: # should be "validly" generated, but in theory could be anything for us also: # $eapol = "\x00" x 121; # works too, but let's generate it correctly $eapol = gen_random_wpa_eapol ($keyver, $snonce); } else { $bssid = $additional_param; $stmac = $additional_param2; $snonce = $additional_param3; $anonce = $additional_param4; $keyver = $additional_param5; $eapol = $additional_param6; } $eapol_len = length ($eapol); # constants my $iterations = 4096; # # START # # generate the Pairwise Master Key (PMK) my $pbkdf2 = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => $iterations, output_len => 32, ); my $pmk = $pbkdf2->PBKDF2 ($salt_buf, $word_buf); # Pairwise Transient Key (PTK) transformation my $ptk = wpa_prf_512 ($keyver, $pmk, $stmac, $bssid, $snonce, $anonce); # generate the Message Integrity Code (MIC) my $mic = ""; if ($keyver == 1) # WPA1 => MD5 { $mic = hmac ($eapol, $ptk, \&md5); } elsif ($keyver == 2) # WPA2 => SHA1 { $mic = hmac ($eapol, $ptk, \&sha1); } elsif ($keyver == 3) # WPA2 => SHA256 + AES-CMAC { my $omac1 = Digest::CMAC->new ($ptk, 'Crypt::Rijndael'); $omac1->add ($eapol); $mic = $omac1->digest; } $mic = substr ($mic, 0, 16); # # format the binary output # my $HCCAPX_VERSION = 4; # signature $hash_buf = "HCPX"; # format version $hash_buf .= pack ("L<", $HCCAPX_VERSION); # authenticated $hash_buf .= pack ("C", 0); # essid length $essid_len = length ($salt_buf); $hash_buf .= pack ("C", $essid_len); # essid (NULL-padded up to the first 32 bytes) $hash_buf .= $salt_buf; $hash_buf .= "\x00" x (32 - $essid_len); # key version $hash_buf .= pack ("C", $keyver); # key mic $hash_buf .= $mic; # access point MAC $hash_buf .= $bssid; # access point nonce $hash_buf .= $snonce; # client MAC $hash_buf .= $stmac; # client nonce $hash_buf .= $anonce; # eapol length $hash_buf .= pack ("S<", $eapol_len); # eapol $hash_buf .= $eapol; $hash_buf .= "\x00" x (256 - $eapol_len); # base64 encode the output $tmp_hash = encode_base64 ($hash_buf, ""); } elsif ($mode == 2600) { $hash_buf = md5_hex (md5_hex ($word_buf)); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 2611) { $hash_buf = md5_hex (md5_hex ($word_buf) . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 2612) { my $salt_buf_hex = unpack ("H*", $salt_buf); $hash_buf = md5_hex (md5_hex ($word_buf) . $salt_buf); $tmp_hash = sprintf ("\$PHPS\$%s\$%s", $salt_buf_hex, $hash_buf); } elsif ($mode == 2711) { $hash_buf = md5_hex (md5_hex ($word_buf) . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 2811) { $hash_buf = md5_hex (md5_hex ($salt_buf) . md5_hex ($word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 3000) { my $ppr = Authen::Passphrase::LANManager->new ("passphrase" => $word_buf); $hash_buf = $ppr->hash_hex; $tmp_hash = sprintf ("%s", substr ($hash_buf, 0, 16)); } elsif ($mode == 3100) { $hash_buf = oracle_hash ($salt_buf, $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 3200) { my $cost = "05"; if (length ($iter)) { $cost = $iter; } $tmp_hash = bcrypt ($word_buf, sprintf ('$2a$%s$%s$', $cost, en_base64 ($salt_buf))); } elsif ($mode == 3300) { my $iterations = 904; if (length ($iter)) { $iterations = int ($iter); } my $variant = "\$"; if (defined ($additional_param)) { $variant = $additional_param; } my $prefix = sprintf ("\$md5%srounds=%i\$%s", $variant, $iterations, $salt_buf); $iterations += 4096; $hash_buf = sun_md5 ($word_buf, $prefix, $iterations); $tmp_hash = sprintf ("%s\$%s", $prefix, $hash_buf); } elsif ($mode == 3500) { $hash_buf = md5_hex (md5_hex (md5_hex ($word_buf))); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 3610) { $hash_buf = md5_hex (md5_hex ($salt_buf) . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 3710) { $hash_buf = md5_hex ($salt_buf . md5_hex ($word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 3711) { $hash_buf = md5_hex ($salt_buf . "-" . md5_hex ($word_buf)); $tmp_hash = sprintf ("\$B\$%s\$%s", $salt_buf, $hash_buf); } elsif ($mode == 3720) { $hash_buf = md5_hex ($word_buf . md5_hex ($salt_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 3800) { $hash_buf = md5_hex ($salt_buf . $word_buf . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 3910) { $hash_buf = md5_hex (md5_hex ($word_buf) . md5_hex ($salt_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 4010) { $hash_buf = md5_hex ($salt_buf . md5_hex ($salt_buf . $word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 4110) { $hash_buf = md5_hex ($salt_buf . md5_hex ($word_buf . $salt_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 4210) { $hash_buf = md5_hex ($salt_buf . "\x00" . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 4300) { $hash_buf = md5_hex (uc (md5_hex ($word_buf))); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 4400) { $hash_buf = md5_hex (sha1_hex ($word_buf)); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 4500) { $hash_buf = sha1_hex (sha1_hex ($word_buf)); $tmp_hash = sprintf ("%s", $hash_buf); } elsif (($mode == 4520) || ($mode == 4521) || ($mode == 4522)) { $hash_buf = sha1_hex ($salt_buf . sha1_hex ($word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 4600) { $hash_buf = sha1_hex (sha1_hex (sha1_hex ($word_buf))); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 4700) { $hash_buf = sha1_hex (md5_hex ($word_buf)); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 4800) { my $index = rindex ($salt_buf, ":"); my $salt = substr ($salt_buf, 0, $index); my $salt_bin = pack ("H*", $salt); my $chap_sign = substr ($salt_buf, $index + 1); my $chap_sign_bin = pack ("H*", $chap_sign); $hash_buf = md5_hex ($chap_sign_bin . $word_buf . $salt_bin); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 4900) { $hash_buf = sha1_hex ($salt_buf . $word_buf . $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 5100) { my $pos; if (! defined ($additional_param)) { $pos = 0; } else { $pos = $additional_param * 8 unless ($additional_param > 2); } $hash_buf = md5_hex ($word_buf); $tmp_hash = sprintf ("%s", substr ($hash_buf, $pos, 16)); } elsif ($mode == 5300) { my @salt_arr = split (":", $salt_buf); my $msg_buf = pack ("H*", $salt_arr[0] . $salt_arr[1] . $salt_arr[2] . $salt_arr[3] . $salt_arr[4] . $salt_arr[5]); my $nr_buf = pack ("H*", $salt_arr[6] . $salt_arr[7]); my $hash_buf = hmac ($nr_buf , $word_buf, \&md5, 64); $hash_buf = hmac_hex ($msg_buf, $hash_buf, \&md5, 64); $tmp_hash = sprintf ("%s:%s", $salt_buf, $hash_buf); } elsif ($mode == 5400) { my @salt_arr = split (":", $salt_buf); my $msg_buf = pack ("H*", $salt_arr[0] . $salt_arr[1] . $salt_arr[2] . $salt_arr[3] . $salt_arr[4] . $salt_arr[5]); my $nr_buf = pack ("H*", $salt_arr[6] . $salt_arr[7]); my $hash_buf = hmac ($nr_buf , $word_buf, \&sha1, 64); $hash_buf = hmac_hex ($msg_buf, $hash_buf, \&sha1, 64); $tmp_hash = sprintf ("%s:%s", $salt_buf, $hash_buf); } elsif ($mode == 5500) { my $index1 = index ($salt_buf, "::"); my $user = substr ($salt_buf, 0, $index1); my $index2 = index ($salt_buf, ":", $index1 + 2); my $domain = substr ($salt_buf, $index1 + 2, $index2 - $index1 - 2); my $len = length (substr ($salt_buf, $index2 + 1)); my $c_challenge_hex; if ($len > 32) { $c_challenge_hex = substr ($salt_buf, $index2 + 1, 48); $index2 += 32; } else { $c_challenge_hex = substr ($salt_buf, $index2 + 1, 16); $c_challenge_hex .= 00 x 32; } my $c_challenge = pack ("H*", substr ($c_challenge_hex, 0, 16)); my $s_challenge_hex = substr ($salt_buf, $index2 + 17, 16); my $s_challenge = pack ("H*", $s_challenge_hex); my $challenge = substr (md5 ($s_challenge . $c_challenge), 0, 8); my $ntresp; my $nthash = Authen::Passphrase::NTHash->new (passphrase => $word_buf)->hash . "\x00" x 5; $ntresp .= Crypt::ECB::encrypt (setup_des_key (substr ($nthash, 0, 7)), "DES", $challenge, "none"); $ntresp .= Crypt::ECB::encrypt (setup_des_key (substr ($nthash, 7, 7)), "DES", $challenge, "none"); $ntresp .= Crypt::ECB::encrypt (setup_des_key (substr ($nthash, 14, 7)), "DES", $challenge, "none"); $tmp_hash = sprintf ("%s::%s:%s:%s:%s", $user, $domain, $c_challenge_hex, unpack ("H*", $ntresp), $s_challenge_hex); } elsif ($mode == 5600) { my $index1 = index ($salt_buf, "::"); my $user = substr ($salt_buf, 0, $index1); my $index2 = index ($salt_buf, ":", $index1 + 2); my $domain = substr ($salt_buf, $index1 + 2, $index2 - $index1 - 2); my $s_challenge_hex = substr ($salt_buf, $index2 + 1, 16); my $s_challenge = pack ("H*", $s_challenge_hex); my $temp_hex = substr ($salt_buf, $index2 + 17); my $temp = pack ("H*", $temp_hex); my $nthash = Authen::Passphrase::NTHash->new (passphrase => $word_buf)->hash; my $identity = Encode::encode ("UTF-16LE", uc ($user) . $domain); $hash_buf = hmac_hex ($s_challenge . $temp, hmac ($identity, $nthash, \&md5, 64), \&md5, 64); $tmp_hash = sprintf ("%s::%s:%s:%s:%s", $user, $domain, $s_challenge_hex, $hash_buf, $temp_hex); } elsif ($mode == 5700) { $hash_buf = sha256 ($word_buf); my $base64_buf = encode_base64 ($hash_buf, ""); $tmp_hash = ""; for (my $i = 0; $i < 43; $i++) { $tmp_hash .= $CISCO_BASE64_MAPPING->{substr ($base64_buf, $i, 1)}; } } elsif ($mode == 5800) { $hash_buf = androidpin_hash ($word_buf, $salt_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 6000) { $hash_buf = ripemd160_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 6100) { $hash_buf = whirlpool_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 6300) { my $iterations = 1000; # hard coded by the AIX format $hash_buf = md5_crypt ('', $iterations, $word_buf, $salt_buf); $tmp_hash = sprintf ("{smd5}%s", $hash_buf); } elsif ($mode == 6400) { my $iterations = 64; if (length ($iter)) { $iterations = 1 << int ($iter); } $hash_buf = aix_ssha256_pbkdf2 ($word_buf, $salt_buf, $iterations); $tmp_hash = sprintf ("{ssha256}%02i\$%s\$%s", log ($iterations) / log (2), $salt_buf, $hash_buf); } elsif ($mode == 6500) { my $iterations = 64; if (length ($iter)) { $iterations = 1 << int ($iter); } $hash_buf = aix_ssha512_pbkdf2 ($word_buf, $salt_buf, $iterations); $tmp_hash = sprintf ("{ssha512}%02i\$%s\$%s", log ($iterations) / log (2), $salt_buf, $hash_buf); } elsif ($mode == 6600) { my $iterations = 1000; if (length ($iter)) { $iterations = int ($iter); } my $salt_hex = substr ($salt_buf, 0, 16); my $salt = pack ("H*", $salt_hex); my $prefix = substr ($salt_buf, 16, 2016); my $iv_hex = substr ($salt_buf, 2032); my $iv = pack ("H*", $iv_hex); my $data = pack ("H*", "10101010101010101010101010101010"); my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, output_len => 16 ); my $key = $pbkdf2->PBKDF2 ($salt, $word_buf); my $cipher = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $iv, literal_key => 1, header => "none", keysize => 16 }); my $encrypted = unpack ("H*", $cipher->encrypt ($data)); $hash_buf = substr ($encrypted, 0, 32); $tmp_hash = sprintf ("%i:%s:%s%s%s", $iterations, $salt_hex, $prefix, $iv_hex, $hash_buf); } elsif ($mode == 6700) { my $iterations = 64; if (length ($iter)) { $iterations = 1 << int ($iter); } $hash_buf = aix_ssha1_pbkdf2 ($word_buf, $salt_buf, $iterations); $tmp_hash = sprintf ("{ssha1}%02i\$%s\$%s", log ($iterations) / log (2), $salt_buf, $hash_buf); } elsif ($mode == 6800) { my $variant = $additional_param; if (! defined ($variant)) { $variant = int (rand (2)); } my $iterations = 500; if (length ($iter)) { $iterations = int ($iter); } my $iv = "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, output_len => 32 ); my $key = $pbkdf2->PBKDF2 ($salt_buf, $word_buf); my $cipher = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $iv, literal_key => 1, header => "none", keysize => 32 }); if ($variant == 1) { my $encrypt = $cipher->encrypt (substr ($salt_buf, 0, 16)); $hash_buf = substr (unpack ("H*", $encrypt), 0, 32); } else { my $verifier = "lastpass rocks\x02\x02"; $hash_buf = unpack ("H*", substr ($cipher->encrypt ($verifier), 0, 16)); } $tmp_hash = sprintf ("%s:%i:%s", $hash_buf, $iterations, $salt_buf); } elsif ($mode == 6900) { $hash_buf = gost_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 7000) { my $FORTIGATE_SIGNATURE = "AK1"; my $FORTIGATE_MAGIC = pack ("H*", "a388ba2e424cb04a537930c13107cc3fa1329029a9815b70"); my $salt_bin = pack ("H*", $salt_buf); my $hash = sha1 ($salt_bin . $word_buf . $FORTIGATE_MAGIC); $hash = encode_base64 ($salt_bin . $hash, ""); $tmp_hash = sprintf ("%s%s", $FORTIGATE_SIGNATURE, $hash); } elsif ($mode == 7100) { my $iterations = 1024; if (length ($iter)) { $iterations = int ($iter); } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 512), iterations => $iterations ); $hash_buf = unpack ("H*", $pbkdf2->PBKDF2 (pack ("H*", $salt_buf), $word_buf)); $tmp_hash = sprintf ("\$ml\$%i\$%s\$%0128s", $iterations, $salt_buf, $hash_buf); } elsif ($mode == 7200) { my $iterations = 1024; if (length ($iter)) { $iterations = int ($iter); } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 512), iterations => $iterations ); $hash_buf = unpack ("H*", $pbkdf2->PBKDF2 (pack ("H*", $salt_buf), $word_buf)); $tmp_hash = sprintf ("grub.pbkdf2.sha512.%i.%s.%0128s", $iterations, $salt_buf, $hash_buf); } elsif ($mode == 7300) { $hash_buf = hmac_hex ($salt_buf, $word_buf, \&sha1); $tmp_hash = sprintf ("%s:%s", unpack ("H*", $salt_buf), $hash_buf); } elsif ($mode == 7400) { my $iterations = 5000; if (defined ($iter)) { if ($iter > 0) { $iterations = int ($iter); } } $hash_buf = sha256_crypt ($iterations, $word_buf, $salt_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 7500) { my @salt_arr = split ("\\\$", $salt_buf); my $user = $salt_arr[0]; my $realm = $salt_arr[1]; my $salt = $salt_arr[2]; my $hmac_salt = $salt_arr[3]; my $hmac_salt_bin = pack ("H*", $hmac_salt); my $clear_data = $salt_arr[4]; my $k = md4 (encode ("UTF-16LE", $word_buf)); my $k1 = hmac_md5 ("\x01\x00\x00\x00", $k); my $k3 = hmac_md5 ($hmac_salt_bin, $k1); if (length ($clear_data) > 1) { my $clear_data_bin = pack ("H*", $clear_data); $hash_buf = RC4 ($k3, $clear_data_bin); } else { my $hash = $salt_arr[5]; my $hash_bin = pack ("H*", $hash); my $clear_data = RC4 ($k3, $hash_bin); my $timestamp = substr ($clear_data, 14, 14); my $is_numeric = 1; if ($timestamp !~ /^[[:digit:]]{14}$/) { $is_numeric = 0; } if (! $is_numeric) { $hash_buf = "\x00" x 36; if ($hash_buf eq $hash_bin) { $hash_buf = "\x01" x 36; } } else { $hash_buf = $hash_bin; } } $tmp_hash = sprintf ("\$krb5pa\$23\$%s\$%s\$%s\$%s%s", $user, $realm, $salt, unpack ("H*", $hash_buf), $hmac_salt); } elsif ($mode == 7700 || $mode == 7701) { $word_buf = uc $word_buf; $salt_buf = uc $salt_buf; my $word_buf_t = sapb_transcode ($word_buf); my $salt_buf_t = sapb_transcode ($salt_buf); my $digest1 = md5 ($word_buf_t . $salt_buf_t); my $data = sapb_waldorf ($digest1, $word_buf_t, $salt_buf_t); my $digest2 = md5 ($data); my ($a, $b, $c, $d) = unpack ("N4", $digest2); $a ^= $c; $b ^= $d; if ($mode == 7700) { $tmp_hash = sprintf ("%s\$%08X%08X", $salt_buf, $a, $b); } else { $tmp_hash = sprintf ("%s\$%08X%08X", $salt_buf, $a, 0); } } elsif ($mode == 7800 || $mode == 7801) { my $theMagicArray_s = "\x91\xac\x51\x14\x9f\x67\x54\x43\x24\xe7\x3b\xe0\x28\x74\x7b\xc2" . "\x86\x33\x13\xeb\x5a\x4f\xcb\x5c\x08\x0a\x73\x37\x0e\x5d\x1c\x2f" . "\x33\x8f\xe6\xe5\xf8\x9b\xae\xdd\x16\xf2\x4b\x8d\x2c\xe1\xd4\xdc" . "\xb0\xcb\xdf\x9d\xd4\x70\x6d\x17\xf9\x4d\x42\x3f\x9b\x1b\x11\x94" . "\x9f\x5b\xc1\x9b\x06\x05\x9d\x03\x9d\x5e\x13\x8a\x1e\x9a\x6a\xe8" . "\xd9\x7c\x14\x17\x58\xc7\x2a\xf6\xa1\x99\x63\x0a\xd7\xfd\x70\xc3" . "\xf6\x5e\x74\x13\x03\xc9\x0b\x04\x26\x98\xf7\x26\x8a\x92\x93\x25" . "\xb0\xa2\x0d\x23\xed\x63\x79\x6d\x13\x32\xfa\x3c\x35\x02\x9a\xa3" . "\xb3\xdd\x8e\x0a\x24\xbf\x51\xc3\x7c\xcd\x55\x9f\x37\xaf\x94\x4c" . "\x29\x08\x52\x82\xb2\x3b\x4e\x37\x9f\x17\x07\x91\x11\x3b\xfd\xcd"; $salt_buf = uc $salt_buf; my $digest = sha1 ($word_buf . $salt_buf); my ($a, $b, $c, $d, $e) = unpack ("I*", $digest); my $lengthMagicArray = 0x20; my $offsetMagicArray = 0; $lengthMagicArray += (($a >> 0) & 0xff) % 6; $lengthMagicArray += (($a >> 8) & 0xff) % 6; $lengthMagicArray += (($a >> 16) & 0xff) % 6; $lengthMagicArray += (($a >> 24) & 0xff) % 6; $lengthMagicArray += (($b >> 0) & 0xff) % 6; $lengthMagicArray += (($b >> 8) & 0xff) % 6; $lengthMagicArray += (($b >> 16) & 0xff) % 6; $lengthMagicArray += (($b >> 24) & 0xff) % 6; $lengthMagicArray += (($c >> 0) & 0xff) % 6; $lengthMagicArray += (($c >> 8) & 0xff) % 6; $offsetMagicArray += (($c >> 16) & 0xff) % 8; $offsetMagicArray += (($c >> 24) & 0xff) % 8; $offsetMagicArray += (($d >> 0) & 0xff) % 8; $offsetMagicArray += (($d >> 8) & 0xff) % 8; $offsetMagicArray += (($d >> 16) & 0xff) % 8; $offsetMagicArray += (($d >> 24) & 0xff) % 8; $offsetMagicArray += (($e >> 0) & 0xff) % 8; $offsetMagicArray += (($e >> 8) & 0xff) % 8; $offsetMagicArray += (($e >> 16) & 0xff) % 8; $offsetMagicArray += (($e >> 24) & 0xff) % 8; my $hash_buf = sha1_hex ($word_buf . substr ($theMagicArray_s, $offsetMagicArray, $lengthMagicArray) . $salt_buf); if ($mode == 7800) { $tmp_hash = sprintf ("%s\$%s", $salt_buf, uc $hash_buf); } else { $tmp_hash = sprintf("%s\$%.20s%020X", $salt_buf, uc $hash_buf, 0); } } elsif ($mode == 7900) { my $cost = 14; if (length ($iter)) { $cost = $iter; } my $phpass_it = 1 << $cost; $hash_buf = sha512 ($salt_buf . $word_buf); for (my $i = 0; $i < $phpass_it; $i++) { $hash_buf = sha512 ($hash_buf . $word_buf); } my $base64_buf = substr (Authen::Passphrase::PHPass::_en_base64 ($hash_buf), 0, 43); my $base64_digits = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; my $cost_str = substr ($base64_digits , $cost, 1); $tmp_hash = sprintf ('$S$%s%s%s', $cost_str, $salt_buf, $base64_buf); } elsif ($mode == 8000) { my $salt_buf_bin = pack ("H*", $salt_buf); my $word_buf_utf = encode ("UTF-16BE", $word_buf); $hash_buf = sha256_hex ($word_buf_utf . "\x00" x (510 - (length ($word_buf) * 2)) . $salt_buf_bin); $tmp_hash = sprintf ("0xc007%s%s", $salt_buf, $hash_buf); } elsif ($mode == 8100) { $hash_buf = sha1_hex ($salt_buf . $word_buf . "\x00"); $tmp_hash = sprintf ("1%s%s", $salt_buf, $hash_buf); } elsif ($mode == 8200) { my $iterations = 40000; if (defined ($iter)) { $iterations = $iter; } my $salt_hex = substr ($salt_buf, 0, 32); my $salt = pack ("H*", $salt_hex); my $data_hex = substr ($salt_buf, 32); my $data = pack ("H*", $data_hex); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 512), iterations => int $iterations ); my $key = $pbkdf2->PBKDF2 ($salt, $word_buf); $hash_buf = hmac_hex ($data, substr ($key, 32, 32), \&sha256, 64); $tmp_hash = sprintf ("%s:%s:%d:%s", $hash_buf, $salt_hex, $iterations, $data_hex); } elsif ($mode == 8300) { my ($domain, $salt_hex) = split (":", $salt_buf); my $hashalg = Net::DNS::SEC->digtype ("SHA1"); my $salt = pack ("H*", $salt_hex); my $iterations = 1; if (defined ($iter)) { $iterations = $iter; } my $name = lc ($word_buf . $domain); my $hash_buf = Net::DNS::RR::NSEC3::name2hash ($hashalg, $name, $iterations, $salt); $tmp_hash = sprintf ("%s:%s:%s:%d", $hash_buf, $domain, $salt_hex, $iterations); } elsif ($mode == 8400 || $mode == 13900) { $hash_buf = sha1_hex ($salt_buf . sha1_hex ($salt_buf . sha1_hex ($word_buf))); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 8500) { $hash_buf = racf_hash (uc $salt_buf, $word_buf); $tmp_hash = sprintf ('$racf$*%s*%s', uc $salt_buf, uc $hash_buf); } elsif ($mode == 8600) { my @saved_key = map { ord $_; } split "", $word_buf; my $len = scalar @saved_key; my @state = domino_big_md (\@saved_key, $len); $tmp_hash = sprintf ('%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x', $state[ 0], $state[ 1], $state[ 2], $state[ 3], $state[ 4], $state[ 5], $state[ 6], $state[ 7], $state[ 8], $state[ 9], $state[10], $state[11], $state[12], $state[13], $state[14], $state[15], ); } elsif ($mode == 8700) { my $domino_char = undef; if (defined ($additional_param)) { $domino_char = $additional_param; } my @saved_key = map { ord $_; } split "", $word_buf; my $len = scalar @saved_key; my @state = domino_big_md (\@saved_key, $len); my $str = "(" . unpack ("H*", join ("", (map { chr $_; } @state))) . ")"; @saved_key = map { ord $_; } split "", $salt_buf . uc $str; @state = domino_big_md (\@saved_key, 34); $hash_buf = join ("", (map { chr $_; } @state)); $tmp_hash = sprintf ('(G%s)', domino_encode ($salt_buf . $hash_buf, $domino_char)); } elsif ($mode == 8900) { my $N = 1024; my $r = 1; my $p = 1; if (defined ($additional_param)) { $N = $additional_param; $r = $additional_param2; $p = $additional_param3; } $hash_buf = scrypt_hash ($word_buf, $salt_buf, $N, $r, $p, 32); $tmp_hash = sprintf ('%s', $hash_buf); } elsif ($mode == 9100) { my $iterations = 5000; if (defined ($iter)) { $iterations = $iter; } my $domino_char = undef; # domino 5 hash - SEC_pwddigest_V1 - -m 8600 my @saved_key = map { ord $_; } split "", $word_buf; my $len = scalar @saved_key; my @state = domino_big_md (\@saved_key, $len); # domino 6 hash - SEC_pwddigest_V2 - -m 8700 my $salt_part = substr ($salt_buf, 0, 5); my $str = "(" . unpack ("H*", join ("", (map { chr $_; } @state))) . ")"; @saved_key = map { ord $_; } split "", $salt_part . uc $str; @state = domino_big_md (\@saved_key, 34); $hash_buf = join ("", (map { chr $_; } @state)); $tmp_hash = sprintf ('(G%s)', domino_encode ($salt_part . $hash_buf, $domino_char)); # domino 8(.5.x) hash - SEC_pwddigest_V3 - -m 9100 my $pbkdf2 = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => $iterations, output_len => 8, salt_len => 16, ); my $chars = "02"; if (defined ($additional_param)) { $chars = $additional_param; } my $digest_new = $pbkdf2->PBKDF2 ($salt_buf, $tmp_hash); for (my $i = length ($iterations); $i < 10; $i++) { $iterations = "0" . $iterations; } $tmp_hash = sprintf ('(H%s)', domino_85x_encode ($salt_buf . $iterations . $chars . $digest_new, $domino_char)); } elsif ($mode == 9200) { my $iterations = 20000; my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations ); $hash_buf = encode_base64 ($pbkdf2->PBKDF2 ($salt_buf, $word_buf), ""); $tmp_hash = ""; for (my $i = 0; $i < 43; $i++) { $tmp_hash .= $CISCO_BASE64_MAPPING->{substr ($hash_buf, $i, 1)}; } $tmp_hash = sprintf ("\$8\$%s\$%s", $salt_buf, $tmp_hash); } elsif ($mode == 9300) { my $N = 16384; my $r = 1; my $p = 1; $hash_buf = scrypt_b64 ($word_buf, $salt_buf, $N, $r, $p, 32); $tmp_hash = ""; for (my $i = 0; $i < 43; $i++) { $tmp_hash .= $CISCO_BASE64_MAPPING->{substr ($hash_buf, $i, 1)}; } $tmp_hash = sprintf ('$9$%s$%s', $salt_buf, $tmp_hash); } elsif ($mode == 9400) { my $iterations = 50000; if (length ($iter)) { $iterations = int ($iter); } my $aes_key_size = 128; # or 256 if (defined ($additional_param2)) { $aes_key_size = $additional_param2; } $salt_buf = pack ("H*", $salt_buf); my $tmp = sha1 ($salt_buf . encode ("UTF-16LE", $word_buf)); for (my $i = 0; $i < $iterations; $i++) { my $num32 = pack ("L", $i); $tmp = sha1 ($num32 . $tmp); } my $zero32 = pack ("L", 0x00); my $derivation_array1 = pack ("C", 0x36) x 64; my $derivation_array2 = pack ("C", 0x5C) x 64; $tmp = sha1 ($tmp . $zero32); my $tmp2 = sha1 ($derivation_array1 ^ $tmp); my $tmp3 = sha1 ($derivation_array2 ^ $tmp); my $key = substr ($tmp2 . $tmp3, 0, $aes_key_size / 8); my $m = Crypt::Mode::ECB->new ('AES', 0); my $encdata; if (defined $additional_param) { $encdata = $m->decrypt (pack ("H*", $additional_param), $key); } else { $encdata = "A" x 16; ## can be anything } my $data1_buf = $encdata; my $data2_buf = sha1 (substr ($data1_buf, 0, 16)); $data1_buf = substr ($data1_buf . ("\x00" x 16), 0, 16); $data2_buf = substr ($data2_buf . ("\x00" x 16), 0, 32); my $encrypted1 = unpack ("H*", $m->encrypt ($data1_buf, $key)); my $encrypted2 = unpack ("H*", $m->encrypt ($data2_buf, $key)); $encrypted1 = substr ($encrypted1, 0, 32); $encrypted2 = substr ($encrypted2, 0, 40); $tmp_hash = sprintf ("\$office\$*%d*%d*%d*%d*%s*%s*%s", 2007, 20, $aes_key_size, 16, unpack ("H*", $salt_buf), $encrypted1, $encrypted2); } elsif ($mode == 9500) { my $iterations = 100000; if (length ($iter)) { $iterations = int ($iter); } $salt_buf = pack ("H*", $salt_buf); my $tmp = sha1 ($salt_buf . encode ("UTF-16LE", $word_buf)); for (my $i = 0; $i < $iterations; $i++) { my $num32 = pack ("L", $i); $tmp = sha1 ($num32 . $tmp); } my $encryptedVerifierHashInputBlockKey = "\xfe\xa7\xd2\x76\x3b\x4b\x9e\x79"; my $encryptedVerifierHashValueBlockKey = "\xd7\xaa\x0f\x6d\x30\x61\x34\x4e"; my $final1 = sha1 ($tmp . $encryptedVerifierHashInputBlockKey); my $final2 = sha1 ($tmp . $encryptedVerifierHashValueBlockKey); my $key1 = substr ($final1, 0, 16); my $key2 = substr ($final2, 0, 16); my $cipher1 = Crypt::CBC->new ({ key => $key1, cipher => "Crypt::Rijndael", iv => $salt_buf, literal_key => 1, header => "none", keysize => 16, padding => "null", }); my $cipher2 = Crypt::CBC->new ({ key => $key2, cipher => "Crypt::Rijndael", iv => $salt_buf, literal_key => 1, header => "none", keysize => 16, padding => "null", }); my $encdata; if (defined $additional_param) { $encdata = $cipher1->decrypt (pack ("H*", $additional_param)); } else { $encdata = "A" x 16; ## can be anything } my $data1_buf = $encdata; my $data2_buf = sha1 (substr ($data1_buf, 0, 16)); my $encrypted1 = unpack ("H*", $cipher1->encrypt ($data1_buf)); my $encrypted2 = unpack ("H*", $cipher2->encrypt ($data2_buf)); $encrypted2 = substr ($encrypted2, 0, 64); $tmp_hash = sprintf ("\$office\$*%d*%d*%d*%d*%s*%s*%s", 2010, 100000, 128, 16, unpack ("H*", $salt_buf), $encrypted1, $encrypted2); } elsif ($mode == 9600) { my $iterations = 100000; if (length ($iter)) { $iterations = int ($iter); } $salt_buf = pack ("H*", $salt_buf); my $tmp = sha512 ($salt_buf . encode ("UTF-16LE", $word_buf)); for (my $i = 0; $i < $iterations; $i++) { my $num32 = pack ("L", $i); $tmp = sha512 ($num32 . $tmp); } my $encryptedVerifierHashInputBlockKey = "\xfe\xa7\xd2\x76\x3b\x4b\x9e\x79"; my $encryptedVerifierHashValueBlockKey = "\xd7\xaa\x0f\x6d\x30\x61\x34\x4e"; my $final1 = sha512 ($tmp . $encryptedVerifierHashInputBlockKey); my $final2 = sha512 ($tmp . $encryptedVerifierHashValueBlockKey); my $key1 = substr ($final1, 0, 32); my $key2 = substr ($final2, 0, 32); my $cipher1 = Crypt::CBC->new ({ key => $key1, cipher => "Crypt::Rijndael", iv => $salt_buf, literal_key => 1, header => "none", keysize => 32, padding => "null", }); my $cipher2 = Crypt::CBC->new ({ key => $key2, cipher => "Crypt::Rijndael", iv => $salt_buf, literal_key => 1, header => "none", keysize => 32, padding => "null", }); my $encdata; if (defined $additional_param) { $encdata = $cipher1->decrypt (pack ("H*", $additional_param)); } else { $encdata = "A" x 16; ## can be anything } my $data1_buf = $encdata; my $data2_buf = sha512 (substr ($data1_buf, 0, 16)); my $encrypted1 = unpack ("H*", $cipher1->encrypt ($data1_buf)); my $encrypted2 = unpack ("H*", $cipher2->encrypt ($data2_buf)); $encrypted2 = substr ($encrypted2, 0, 64); $tmp_hash = sprintf ("\$office\$*%d*%d*%d*%d*%s*%s*%s", 2013, 100000, 256, 16, unpack ("H*", $salt_buf), $encrypted1, $encrypted2); } elsif ($mode == 9700) { $salt_buf = pack ("H*", $salt_buf); my $tmp = md5 (encode ("UTF-16LE", $word_buf)); $tmp = substr ($tmp, 0, 5); my $data; for (my $i = 0; $i < 16; $i++) { $data .= $tmp; $data .= $salt_buf; } $tmp = md5 ($data); $tmp = substr ($tmp, 0, 5); my $version; if (defined $additional_param2) { $version = $additional_param2; } else { $version = (unpack ("L", $tmp) & 1) ? 0 : 1; } my $rc4_key = md5 ($tmp . "\x00\x00\x00\x00"); my $m = Crypt::RC4->new (substr ($rc4_key, 0, 16)); my $encdata; if (defined $additional_param) { $encdata = $m->RC4 (pack ("H*", $additional_param)); } else { $encdata = "A" x 16; ## can be anything } my $data1_buf = $encdata; my $data2_buf = md5 (substr ($data1_buf, 0, 16)); $m = Crypt::RC4->new (substr ($rc4_key, 0, 16)); my $encrypted1 = $m->RC4 ($data1_buf); my $encrypted2 = $m->RC4 ($data2_buf); $tmp_hash = sprintf ("\$oldoffice\$%d*%s*%s*%s", $version, unpack ("H*", $salt_buf), unpack ("H*", $encrypted1), unpack ("H*", $encrypted2)); } elsif ($mode == 9800) { $salt_buf = pack ("H*", $salt_buf); my $tmp = sha1 ($salt_buf. encode ("UTF-16LE", $word_buf)); my $version; if (defined $additional_param2) { $version = $additional_param2; } else { $version = (unpack ("L", $tmp) & 1) ? 3 : 4; } my $rc4_key = sha1 ($tmp . "\x00\x00\x00\x00"); if ($version == 3) { $rc4_key = substr ($rc4_key, 0, 5) . "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; } my $m = Crypt::RC4->new (substr ($rc4_key, 0, 16)); my $encdata; if (defined $additional_param) { $encdata = $m->RC4 (pack ("H*", $additional_param)); } else { $encdata = "A" x 16; ## can be anything } my $data1_buf = $encdata; my $data2_buf = sha1 (substr ($data1_buf, 0, 16)); $m = Crypt::RC4->new (substr ($rc4_key, 0, 16)); my $encrypted1 = $m->RC4 ($data1_buf); my $encrypted2 = $m->RC4 ($data2_buf); $tmp_hash = sprintf ("\$oldoffice\$%d*%s*%s*%s", $version, unpack ("H*", $salt_buf), unpack ("H*", $encrypted1), unpack ("H*", $encrypted2)); } elsif ($mode == 9900) { $tmp_hash = sprintf ("%s", md5_hex ($word_buf . "\0" x (100 - length ($word_buf)))); } elsif ($mode == 10000) { my $iterations = 10000; if (length ($iter)) { $iterations = int ($iter); } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations ); $hash_buf = encode_base64 ($pbkdf2->PBKDF2 ($salt_buf, $word_buf), ""); $tmp_hash = sprintf ("pbkdf2_sha256\$%i\$%s\$%s", $iterations, $salt_buf, $hash_buf); } elsif ($mode == 10100) { my $seed = pack ("H*", $salt_buf); my ($hi, $lo) = siphash ($word_buf, $seed); my $hi_s = sprintf ("%08x", $hi); my $lo_s = sprintf ("%08x", $lo); $hi_s =~ s/^(..)(..)(..)(..)$/$4$3$2$1/; $lo_s =~ s/^(..)(..)(..)(..)$/$4$3$2$1/; $tmp_hash = sprintf ("%s%s:2:4:%s", $hi_s, $lo_s, $salt_buf); } elsif ($mode == 10200) { my $challengeb64 = encode_base64 ($salt_buf, ""); my $username; if (defined $additional_param) { $username = $additional_param; } else { $username = "user"; } $hash_buf = hmac_hex ($salt_buf, $word_buf, \&md5); my $responseb64 = encode_base64 ($username . " " . $hash_buf, ""); $tmp_hash = sprintf ('$cram_md5$%s$%s', $challengeb64, $responseb64); } elsif ($mode == 10300) { my $iterations = 1024; if (length ($iter)) { $iterations = int ($iter); } my $hash_buf = $salt_buf; for (my $pos = 0; $pos < $iterations; $pos++) { $hash_buf = sha1 ($word_buf . $hash_buf); } $hash_buf = encode_base64 ($hash_buf . $salt_buf, ""); $tmp_hash = sprintf ("{x-issha, %i}%s", $iterations, $hash_buf); } elsif ($mode == 10400) { my $id = $salt_buf; my $u = $additional_param; my $o = $additional_param2; my $P = $additional_param3; if (defined $u == 0) { $u = "0" x 64; } if (defined $o == 0) { $o = "0" x 64; } if (defined $P == 0) { $P = -1; } my $padding; for (my $i = 0; $i < 32; $i++) { $padding .= pack ("C", $PDF_PADDING->[$i]); } my $res = pdf_compute_encryption_key ($word_buf, $padding, $id, $u, $o, $P, 1, 2, 0); my $m = Crypt::RC4->new (substr ($res, 0, 5)); $u = $m->RC4 ($padding); $tmp_hash = sprintf ('$pdf$%d*%d*40*%d*%d*16*%s*32*%s*32*%s', 1, 2, $P, 0, $id, unpack ("H*", $u), $o); } elsif ($mode == 10500) { my $id = $salt_buf; my $u = $additional_param; my $o = $additional_param2; my $P = $additional_param3; my $V = $additional_param4; my $R = $additional_param5; my $enc = $additional_param6; if (defined $u == 0) { $u = "0" x 64; } my $u_save = $u; if (defined $o == 0) { $o = "0" x 64; } if (defined $R == 0) { $R = get_random_num (3, 5); } if (defined $V == 0) { $V = ($R == 3) ? 2 : 4; } if (defined $P == 0) { $P = ($R == 3) ? -4 : -1028; } if (defined $enc == 0) { $enc = ($R == 3) ? 1 : get_random_num (0, 2); } my $padding; for (my $i = 0; $i < 32; $i++) { $padding .= pack ("C", $PDF_PADDING->[$i]); } my $res = pdf_compute_encryption_key ($word_buf, $padding, $id, $u, $o, $P, $V, $R, $enc); my $digest = md5 ($padding . pack ("H*", $id)); my $m = Crypt::RC4->new ($res); $u = $m->RC4 ($digest); my @ress = split "", $res; for (my $x = 1; $x <= 19; $x++) { my @xor; for (my $i = 0; $i < 16; $i++) { $xor[$i] = chr (ord ($ress[$i]) ^ $x); } my $s = join ("", @xor); my $m2 = Crypt::RC4->new ($s); $u = $m2->RC4 ($u); } $u .= substr (pack ("H*", $u_save), 16, 16); $tmp_hash = sprintf ('$pdf$%d*%d*128*%d*%d*16*%s*32*%s*32*%s', $V, $R, $P, $enc, $id, unpack ("H*", $u), $o); } elsif ($mode == 10600) { my $id = $salt_buf; my $rest = $additional_param; if (defined $id == 0) { $id = "0" x 32; } if (defined $rest == 0) { $rest = "127*"; $rest .= "0" x 64; $rest .= $id; $rest .= "0" x 158; $rest .= "*127*00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*32*0000000000000000000000000000000000000000000000000000000000000000*32*0000000000000000000000000000000000000000000000000000000000000000"; } my @data = split /\*/, $rest; my $u = pack ("H*", $data[1]); my $h = sha256 ($word_buf . substr ($u, 32, 8)); $data[1] = unpack ("H*", $h . substr ($u, 32)); $rest = join ("*", @data); $tmp_hash = sprintf ('$pdf$5*5*256*-1028*1*16*%s*%s', $id, $rest); } elsif ($mode == 10700) { my $id = $salt_buf; my $rest = $additional_param; if (defined $id == 0) { $id = "0" x 32; } if (defined $rest == 0) { $rest = "127*"; $rest .= "0" x 64; $rest .= $id; $rest .= "0" x 158; $rest .= "*127*00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*32*0000000000000000000000000000000000000000000000000000000000000000*32*0000000000000000000000000000000000000000000000000000000000000000"; } my @datax = split /\*/, $rest; my $u = pack ("H*", $datax[1]); my $block = sha256 ($word_buf . substr ($u, 32, 8)); my $block_size = 32; my $data = 0x00 x 64; my $data_len = 1; my $data63 = 0; for (my $i = 0; $i < 64 || $i < $data63 + 32; $i++) { $data = $word_buf . $block; $data_len = length ($data); for (my $k = 1; $k < 64; $k++) { $data .= $word_buf . $block; } my $aes = Crypt::CBC->new ({ key => substr ($block, 0, 16), cipher => "Crypt::Rijndael", iv => substr ($block, 16, 16), literal_key => 1, header => "none", keysize => 16, padding => "null", }); my $data = $aes->encrypt ($data); my $sum = 0; for (my $j = 0; $j < 16; $j++) { $sum += ord (substr ($data, $j, 1)); } $block_size = 32 + ($sum % 3) * 16; if ($block_size == 32) { $block = sha256 (substr ($data, 0, $data_len * 64)); } elsif ($block_size == 48) { $block = sha384 (substr ($data, 0, $data_len * 64)); } elsif ($block_size == 64) { $block = sha512 (substr ($data, 0, $data_len * 64)); } $data63 = ord (substr ($data, $data_len * 64 - 1, 1)); } $datax[1] = unpack ("H*", substr ($block, 0, 32) . substr ($u, 32)); $rest = join ("*", @datax); $tmp_hash = sprintf ('$pdf$5*6*256*-1028*1*16*%s*%s', $id, $rest); } elsif ($mode == 10800) { $hash_buf = sha384_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 10900) { my $iterations = 1000; if (length ($iter)) { $iterations = int ($iter); } my $out_len = 24; if (defined $additional_param) { $out_len = $additional_param; } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations, output_len => $out_len ); $hash_buf = encode_base64 ($pbkdf2->PBKDF2 ($salt_buf, $word_buf), ""); my $base64_salt_buf = encode_base64 ($salt_buf, ""); $tmp_hash = sprintf ("sha256:%i:%s:%s", $iterations, $base64_salt_buf, $hash_buf); } elsif ($mode == 16900) { my $iterations = 10000; my $salt_hex = substr ($salt_buf, 0, 64); my $salt = pack ("H*", $salt_hex); my $ciphertext = randbytes(32); if (defined $additional_param) { my $ciphertext_hex = $additional_param; $ciphertext = pack ("H*", $ciphertext_hex); } # actually 80 but the last 16 bytes are the IV which we don't need my $out_len = 64; my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations, output_len => $out_len ); my $derived_key = $pbkdf2->PBKDF2 ($salt, $word_buf); $hash_buf = hmac_hex ($ciphertext, substr ($derived_key, 32, 32), \&sha256); $tmp_hash = sprintf ('$ansible$0*0*%s*%s*%s', unpack ("H*", $salt), unpack ("H*", $ciphertext), $hash_buf); } elsif ($mode == 11000) { $hash_buf = md5_hex ($salt_buf . $word_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 11100) { my $user = "postgres"; if (defined $additional_param) { $user = $additional_param; } $hash_buf = md5_hex (md5_hex ($word_buf . $user) . pack ("H*", $salt_buf)); $tmp_hash = sprintf ("\$postgres\$%s*%s*%s", $user, $salt_buf, $hash_buf); } elsif ($mode == 11200) { my $sha1_pass = sha1 ($word_buf); my $double_sha1 = sha1 ($sha1_pass); my $xor_part1 = $sha1_pass; my $xor_part2 = sha1 (pack ("H*", $salt_buf) . $double_sha1); my $hash_buf = ""; for (my $i = 0; $i < 20; $i++) { my $first_byte = substr ($xor_part1, $i, 1); my $second_byte = substr ($xor_part2, $i, 1); my $xor_result = $first_byte ^ $second_byte; $hash_buf .= unpack ("H*", $xor_result); } $tmp_hash = sprintf ("\$mysqlna\$%s*%s", $salt_buf, $hash_buf); } elsif ($mode == 11300) { my $ckey_buf = get_random_string (96); if (length ($additional_param)) { $ckey_buf = $additional_param; } my $public_key_buf = get_random_string (66); if (length ($additional_param2)) { $public_key_buf = $additional_param2; } my $salt_iter = get_random_num (150000, 250000); if (length ($iter)) { $salt_iter = int ($iter); } my $hash_buf = sha512 ($word_buf . pack ("H*", $salt_buf)); for (my $i = 1; $i < $salt_iter; $i++) { $hash_buf = sha512 ($hash_buf); } my $data = get_random_string (32); my $aes = Crypt::CBC->new ({ key => substr ($hash_buf, 0, 32), cipher => "Crypt::Rijndael", iv => substr ($hash_buf, 32, 16), literal_key => 1, header => "none", keysize => 32, padding => "standard", }); my $cry_master_buf = (unpack ("H*", $aes->encrypt ($data))); $tmp_hash = sprintf ('$bitcoin$%d$%s$%d$%s$%d$%d$%s$%d$%s', length ($cry_master_buf), $cry_master_buf, length ($salt_buf), $salt_buf, $salt_iter, length ($ckey_buf), $ckey_buf, length ($public_key_buf), $public_key_buf); } elsif ($mode == 11400) { my ($directive, $URI_server, $URI_client, $user, $realm, $nonce, $nonce_count, $nonce_client, $qop, $method, $URI, $URI_prefix, $URI_resource, $URI_suffix); $directive = "MD5"; # only directive currently supported if (defined ($additional_param)) { $user = $additional_param; $realm = $additional_param2; $nonce = $salt_buf; $nonce_count = $additional_param3; $nonce_client = $additional_param4; $qop = $additional_param5; $method = $additional_param6; $URI_prefix = $additional_param7; $URI_resource = $additional_param8; $URI_suffix = $additional_param9; # not needed information $URI_server = $additional_param10; $URI_client = $additional_param11; } else { $user = get_random_string (get_random_num (0, 12 + 1)); # special limit: (user_len + 1 + realm_len + 1 + word_buf_len) < 56 my $realm_max_len = 55 - length ($user) - 1 - length ($word_buf) - 1; if ($realm_max_len < 1) # should never happen { $realm_max_len = 1; } $realm_max_len = min (20, $realm_max_len); $realm = get_random_string (get_random_num (0, $realm_max_len + 1)); $nonce = $salt_buf; if (get_random_num (0, 1 + 1) == 1) { $qop = "auth"; $nonce_count = get_random_string (get_random_num (0, 10 + 1)); $nonce_client = get_random_string (get_random_num (0, 12 + 1)); } else { $qop = ""; $nonce_count = ""; $nonce_client = ""; } $method = get_random_string (get_random_num (0, 24 + 1)); $URI_prefix = get_random_string (get_random_num (0, 10 + 1)); $URI_resource = get_random_string (get_random_num (1, 32 + 1)); $URI_suffix = get_random_string (get_random_num (0, 32 + 1)); # not needed information $URI_server = get_random_string (get_random_num (0, 32 + 1)); $URI_client = $URI_resource; # simplification } # start $URI = ""; if (length ($URI_prefix) > 0) { $URI = $URI_prefix . ":"; } $URI .= $URI_resource; if (length ($URI_suffix) > 0) { $URI .= ":" . $URI_suffix; } my $HA2 = md5_hex ($method . ":" . $URI); my $HA1 = md5_hex ($user . ":" . $realm . ":" . $word_buf); my $tmp_buf; if (($qop eq "auth") || ($qop eq "auth-int")) { $tmp_buf = $nonce . ":" . $nonce_count . ":" . $nonce_client . ":" . $qop; } else { $tmp_buf = $nonce; } my $hash_buf = md5_hex ($HA1 . ":" . $tmp_buf . ":" . $HA2); $tmp_hash = sprintf ("\$sip\$*%s*%s*%s*%s*%s*%s*%s*%s*%s*%s*%s*%s*%s*%s", $URI_server, $URI_resource, $user, $realm, $method, $URI_prefix, $URI_resource, $URI_suffix, $nonce, $nonce_client, $nonce_count, $qop, $directive, $hash_buf); } elsif ($mode == 11500) { $hash_buf = crc32 ($word_buf); $tmp_hash = sprintf ("%08x:00000000", $hash_buf); } elsif ($mode == 11600) { my ($p, $num_cycle_power, $seven_zip_salt_len, $seven_zip_salt_buf, $salt_len, $data_len, $unpack_size, $data_buf); $p = 0; # is fixed my $validation_only = 0; $validation_only = 1 if (defined ($additional_param)); if ($validation_only == 1) { $num_cycle_power = int ($iter); $seven_zip_salt_len = $additional_param; $seven_zip_salt_buf = $additional_param2; $salt_len = $additional_param3; # $salt_buf set in parser # $hash_buf (resulting crc) $data_len = $additional_param4; $unpack_size = $additional_param5; $data_buf = $additional_param6; } else { $num_cycle_power = 14; # by default it is 19 $seven_zip_salt_len = 0; $seven_zip_salt_buf = ""; $salt_len = length ($salt_buf); # $salt_buf set automatically # $hash_buf (resulting crc) # $data_len will be set when encrypting $unpack_size = get_random_num (1, 32 + 1); $data_buf = get_random_string ($unpack_size); } # # 2 ^ NumCyclesPower "iterations" of SHA256 (only one final SHA256) # $word_buf = encode ("UTF-16LE", $word_buf); my $rounds = 1 << $num_cycle_power; my $pass_buf = ""; for (my $i = 0; $i < $rounds; $i++) { my $num_buf = ""; $num_buf .= pack ("V", $i); $num_buf .= "\x00" x 4; # this would be better but only works on 64-bit systems: # $num_buf = pack ("q", $i); $pass_buf .= sprintf ("%s%s", $word_buf, $num_buf); } my $key = sha256 ($pass_buf); # the salt_buf is our IV for AES CBC # pad the salt_buf my $salt_buf_len = length ($salt_buf); my $salt_padding_len = 0; if ($salt_buf_len < 16) { $salt_padding_len = 16 - $salt_buf_len; } $salt_buf .= "\x00" x $salt_padding_len; my $aes = Crypt::CBC->new ({ cipher => "Crypt::Rijndael", key => $key, keysize => 32, literal_key => 1, iv => $salt_buf, header => "none", }); if ($validation_only == 1) { # decrypt my $decrypted_data = $aes->decrypt ($data_buf); $decrypted_data = substr ($decrypted_data, 0, $unpack_size); $hash_buf = crc32 ($decrypted_data); } else { # encrypt $hash_buf = crc32 ($data_buf); $data_buf = $aes->encrypt ($data_buf); $data_len = length ($data_buf); } $tmp_hash = sprintf ("\$7z\$%i\$%i\$%i\$%s\$%i\$%08s\$%u\$%u\$%u\$%s", $p, $num_cycle_power, $seven_zip_salt_len, $seven_zip_salt_buf, $salt_len, unpack ("H*", $salt_buf), $hash_buf, $data_len, $unpack_size, unpack ("H*", $data_buf)); } elsif ($mode == 11700) { # PyGOST outputs digests in little-endian order, while the kernels # expect them in big-endian; hence the digest[::-1] mirroring. # Using sys.stdout.write instead of print to disable \n character. my $python_code = <<"END_CODE"; import binascii import sys from pygost import gost34112012256 digest = gost34112012256.new(b"$word_buf").digest() sys.stdout.write(binascii.hexlify(digest[::-1])) END_CODE $tmp_hash = `python2 -c '$python_code'`; } elsif ($mode == 11750) { my $python_code = <<"END_CODE"; import binascii import hmac import sys from pygost import gost34112012256 key = b"$word_buf" msg = b"$salt_buf" digest = hmac.new(key, msg, gost34112012256).digest() sys.stdout.write(binascii.hexlify(digest[::-1])) END_CODE $hash_buf = `python2 -c '$python_code'`; $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 11760) { my $python_code = <<"END_CODE"; import binascii import hmac import sys from pygost import gost34112012256 key = b"$salt_buf" msg = b"$word_buf" digest = hmac.new(key, msg, gost34112012256).digest() sys.stdout.write(binascii.hexlify(digest[::-1])) END_CODE $hash_buf = `python2 -c '$python_code'`; $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 11800) { my $python_code = <<"END_CODE"; import binascii import sys from pygost import gost34112012512 digest = gost34112012512.new(b"$word_buf").digest() sys.stdout.write(binascii.hexlify(digest[::-1])) END_CODE $tmp_hash = `python2 -c '$python_code'`; } elsif ($mode == 11850) { my $python_code = <<"END_CODE"; import binascii import hmac import sys from pygost import gost34112012512 key = b"$word_buf" msg = b"$salt_buf" digest = hmac.new(key, msg, gost34112012512).digest() sys.stdout.write(binascii.hexlify(digest[::-1])) END_CODE $hash_buf = `python2 -c '$python_code'`; $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 11860) { my $python_code = <<"END_CODE"; import binascii import hmac import sys from pygost import gost34112012512 key = b"$salt_buf" msg = b"$word_buf" digest = hmac.new(key, msg, gost34112012512).digest() sys.stdout.write(binascii.hexlify(digest[::-1])) END_CODE $hash_buf = `python2 -c '$python_code'`; $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 11900) { my $iterations = 1000; if (length ($iter)) { $iterations = int ($iter); } my $out_len = 32; if (defined $additional_param) { $out_len = $additional_param; } # # call PHP here - WTF # # sanitize $word_buf and $salt_buf: my $word_buf_base64 = encode_base64 ($word_buf, ""); my $salt_buf_base64 = encode_base64 ($salt_buf, ""); # sanitize lenghs $out_len = int ($out_len); # output is in hex encoding, otherwise it could be screwed (but shouldn't) my $php_code = <<'END_CODE'; function pbkdf2 ($algorithm, $password, $salt, $count, $key_length, $raw_output = false) { $algorithm = strtolower ($algorithm); if (! in_array ($algorithm, hash_algos (), true)) { trigger_error ("PBKDF2 ERROR: Invalid hash algorithm.", E_USER_ERROR); } if ($count <= 0 || $key_length <= 0) { trigger_error ("PBKDF2 ERROR: Invalid parameters.", E_USER_ERROR); } if (function_exists ("hash_pbkdf2")) { if (!$raw_output) { $key_length = $key_length * 2; } return hash_pbkdf2 ($algorithm, $password, $salt, $count, $key_length, $raw_output); } $hash_length = strlen (hash ($algorithm, "", true)); $block_count = ceil ($key_length / $hash_length); $output = ""; for ($i = 1; $i <= $block_count; $i++) { $last = $salt . pack ("N", $i); $last = $xorsum = hash_hmac ($algorithm, $last, $password, true); for ($j = 1; $j < $count; $j++) { $xorsum ^= ($last = hash_hmac ($algorithm, $last, $password, true)); } $output .= $xorsum; } if ($raw_output) { return substr ($output, 0, $key_length); } else { return bin2hex (substr ($output, 0, $key_length)); } } print pbkdf2 ("md5", base64_decode ("$word_buf_base64"), base64_decode ("$salt_buf_base64"), $iterations, $out_len, False); END_CODE # replace with these command line arguments $php_code =~ s/\$word_buf_base64/$word_buf_base64/; $php_code =~ s/\$salt_buf_base64/$salt_buf_base64/; $php_code =~ s/\$iterations/$iterations/; $php_code =~ s/\$out_len/$out_len/; my $php_output = `php -r '$php_code'`; $hash_buf = pack ("H*", $php_output); $hash_buf = encode_base64 ($hash_buf, ""); my $base64_salt_buf = encode_base64 ($salt_buf, ""); $tmp_hash = sprintf ("md5:%i:%s:%s", $iterations, $base64_salt_buf, $hash_buf); } elsif ($mode == 12000) { my $iterations = 1000; if (length ($iter)) { $iterations = int ($iter); } my $out_len = 16; if (defined $additional_param) { $out_len = $additional_param; } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'), iterations => $iterations, output_len => $out_len ); $hash_buf = encode_base64 ($pbkdf2->PBKDF2 ($salt_buf, $word_buf), ""); my $base64_salt_buf = encode_base64 ($salt_buf, ""); $tmp_hash = sprintf ("sha1:%i:%s:%s", $iterations, $base64_salt_buf, $hash_buf); } elsif ($mode == 12001) { my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'), iterations => 10000, output_len => 32 ); my $base64_buf = encode_base64 ($salt_buf . $pbkdf2->PBKDF2 ($salt_buf, $word_buf), ""); $tmp_hash = sprintf ("{PKCS5S2}%s", $base64_buf); } elsif ($mode == 12100) { my $iterations = 1000; if (length ($iter)) { $iterations = int ($iter); } my $out_len = 16; if (defined $additional_param) { $out_len = $additional_param; } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 512), iterations => $iterations, output_len => $out_len ); $hash_buf = encode_base64 ($pbkdf2->PBKDF2 ($salt_buf, $word_buf), ""); my $base64_salt_buf = encode_base64 ($salt_buf, ""); $tmp_hash = sprintf ("sha512:%i:%s:%s", $iterations, $base64_salt_buf, $hash_buf); } elsif ($mode == 12200) { my $iterations = 65536; my $default_salt = 0; if (defined $additional_param) { $default_salt = int ($additional_param); } if ($default_salt == 1) { $salt_buf = "0011223344556677"; } $hash_buf = sha512 (pack ("H*", $salt_buf) . $word_buf); for (my $i = 0; $i < $iterations; $i++) { $hash_buf = sha512 ($hash_buf); } $hash_buf = unpack ("H*", $hash_buf); $hash_buf = substr ($hash_buf, 0, 16); if ($default_salt == 0) { $tmp_hash = sprintf ("\$ecryptfs\$0\$1\$%s\$%s", $salt_buf, $hash_buf); } else { $tmp_hash = sprintf ("\$ecryptfs\$0\$%s", $hash_buf); } } elsif ($mode == 12300) { my $iterations = 4096; my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 512); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, output_len => 64 ); my $salt_bin = pack ("H*", $salt_buf); my $key = $pbkdf2->PBKDF2 ($salt_bin. "AUTH_PBKDF2_SPEEDY_KEY", $word_buf); $hash_buf = sha512_hex ($key . $salt_bin); $tmp_hash = sprintf ("%s%s", uc ($hash_buf), uc ($salt_buf)); } elsif ($mode == 12400) { my $iterations; if (length ($iter)) { $iterations = int ($iter); } else { $iterations = get_random_num (1, 5001 + 1); } my $key_value = fold_password ($word_buf); my $data = "\x00\x00\x00\x00\x00\x00\x00\x00"; my $salt_value = base64_to_int24 ($salt_buf); $hash_buf = crypt_rounds ($key_value, $iterations, $salt_value, $data); $tmp_hash = sprintf ("_%s%s%s", int24_to_base64 ($iterations), $salt_buf, block_to_base64 ($hash_buf)); } elsif ($mode == 12600) { $hash_buf = sha1_hex ($word_buf); $hash_buf = sha256_hex ($salt_buf . uc $hash_buf); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 12700) { my $iterations = 10; my $data = qq|{ "guid" : "00000000-0000-0000-0000-000000000000", "sharedKey" : "00000000-0000-0000-0000-000000000000", "options" : {"pbkdf2_iterations":10,"fee_policy":0,"html5_notifications":false,"logout_time":600000,"tx_display":0,"always_keep_local_backup":false}|; my $salt_buf_bin = pack ("H*", $salt_buf); my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, output_len => 32 ); my $key = $pbkdf2->PBKDF2 ($salt_buf_bin, $word_buf); my $cipher = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $salt_buf_bin, literal_key => 1, header => "none", keysize => 32 }); my $encrypted = unpack ("H*", $cipher->encrypt ($data)); $tmp_hash = sprintf ("\$blockchain\$%s\$%s", length ($salt_buf . $encrypted) / 2, $salt_buf . $encrypted); } elsif ($mode == 12800) { my $iterations = 100; if (length ($iter)) { $iterations = int ($iter); } my $nt = md4_hex (encode ("UTF-16LE", $word_buf)); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations, output_len => 32 ); my $salt_buf_bin = pack ("H*", $salt_buf); my $hash = $pbkdf2->PBKDF2 ($salt_buf_bin, uc (encode ("UTF-16LE", $nt))); $tmp_hash = sprintf ("v1;PPH1_MD4,%s,%d,%s", $salt_buf, $iterations, unpack ("H*", $hash)); } elsif ($mode == 12900) { my $iterations = 4096; if (length ($iter)) { $iterations = int ($iter); } my $salt2 = $salt_buf . $salt_buf; if (defined $additional_param) { $salt2 = $additional_param; } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations, output_len => 32 ); my $salt_buf_bin = pack ("H*", $salt_buf); my $hash = $pbkdf2->PBKDF2 ($salt_buf_bin, $word_buf); my $salt2_bin = pack ("H*", $salt2); my $hash_hmac = hmac_hex ($salt2_bin, $hash, \&sha256, 64); $tmp_hash = sprintf ("%s%s%s", $salt2, $hash_hmac, $salt_buf); } elsif ($mode == 13000) { my $iterations = 15; if (length ($iter)) { $iterations = int ($iter); } my $iv = "0" x 32; if (defined $additional_param) { $iv = $additional_param; } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => (1 << $iterations) + 32, output_len => 32 ); my $salt_buf_bin = pack ("H*", $salt_buf); my $hash = $pbkdf2->PBKDF2 ($salt_buf_bin, $word_buf); my $hash_final = substr ($hash, 0, 8) ^ substr ($hash, 8, 8) ^ substr ($hash, 16, 8) ^ substr ($hash, 24, 8); $tmp_hash = sprintf ('$rar5$16$%s$%d$%s$8$%s', $salt_buf, $iterations, $iv, unpack ("H*", $hash_final)); } elsif ($mode == 13100) { my @salt_arr = split ('\$', $salt_buf); my $user = $salt_arr[0]; my $realm = $salt_arr[1]; my $spn = $salt_arr[2]; my $k = md4 (encode ("UTF-16LE", $word_buf)); my $k1 = hmac_md5 ("\x02\x00\x00\x00", $k); my $cleartext_ticket = '6381b03081ada00703050050a00000a11b3019a003020117a1'. '12041058e0d77776e8b8e03991f2966939222aa2171b154d594b5242544553542e434f4e5'. '44f534f2e434f4da3133011a003020102a10a30081b067472616e6365a40b3009a0030201'. '01a1020400a511180f32303136303231353134343735305aa611180f32303136303231353'. '134343735305aa711180f32303136303231363030343735305aa811180f32303136303232'. '323134343735305a'; my $checksum = ""; if (defined $additional_param) { $checksum = pack ("H*", $additional_param); } else { my $nonce = $salt_arr[3]; $cleartext_ticket = $nonce . $cleartext_ticket; $checksum = hmac_md5 (pack ("H*", $cleartext_ticket), $k1); } my $k3 = hmac_md5 ($checksum, $k1); my $edata2 = ""; if (defined $additional_param2) { $edata2 = $additional_param2; my $cipher_decrypt = Crypt::RC4->new ($k3); my $ticket_decrypt = unpack ("H*", $cipher_decrypt->RC4 (pack ("H*", $edata2))); my $check_correct = ((substr ($ticket_decrypt, 16, 4) eq "6381" && substr ($ticket_decrypt, 22, 2) eq "30") || (substr ($ticket_decrypt, 16, 4) eq "6382")) && ((substr ($ticket_decrypt, 32, 6) eq "030500") || (substr ($ticket_decrypt, 32, 8) eq "050307A0")); if ($check_correct == 1) { $cleartext_ticket = $ticket_decrypt; } else # validation failed { # fake/wrong ticket (otherwise if we just decrypt/encrypt we end up with false positives all the time) $cleartext_ticket = "0" x (length ($cleartext_ticket) + 16); } } my $cipher = Crypt::RC4->new ($k3); $edata2 = $cipher->RC4 (pack ("H*", $cleartext_ticket)); $tmp_hash = sprintf ('$krb5tgs$23$*%s$%s$%s*$%s$%s', $user, $realm, $spn, unpack ("H*", $checksum), unpack ("H*", $edata2)); } elsif ($mode == 13200) { my @salt_arr = split ('\*', $salt_buf); my $iteration = $salt_arr[0]; my $mysalt = $salt_arr[1]; $mysalt = pack ("H*", $mysalt); my $iv = "a6a6a6a6a6a6a6a6"; my $KEK = sha1 ($word_buf); $KEK = substr ($KEK ^ $mysalt, 0, 16); my $aes = Crypt::Mode::ECB->new ('AES'); my $B; my $A; my @R = (); if (defined $additional_param) { $additional_param = pack ("H*", $additional_param); $A = substr ($additional_param, 0, 8); $B = 0x00 x 8; $R[1] = substr ($additional_param, 8, 8); $R[2] = substr ($additional_param, 16, 8); for (my $j = $iteration - 1; $j >= 0; $j--) { $A = substr ($A, 0, 8) ^ pack ("l", (2 * $j + 2)); $B = $R[2]; $A = $aes->decrypt ($A . $B . "\x00" x 16, $KEK); $R[2] = substr ($A, 8, 16); $A = substr ($A, 0, 8) ^ pack ("l", (2 * $j + 1)); $B = $R[1]; $A = $aes->decrypt ($A . $B . "\x00" x 16, $KEK); $R[1] = substr ($A, 8, 16); } # check if valid if (index ($A, "\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6") != 0) { # fake wrong @R and $A values @R = ('', "\x00" x 8, "\x00" x 8); $A = "\x00" x 16; } } else { my $DEK = randbytes (16); @R = ('', substr (pack ("H*", $DEK), 0, 8), substr (pack ("H*", $DEK), 8, 16)); $A = pack ("H*", $iv); } for (my $j = 0; $j < $iteration; $j++) { $B = $aes->encrypt ($A . $R[1], $KEK); $A = substr ($B, 0, 8) ^ pack ("q", (2 * $j + 1)); $R[1] = substr ($B, 8, 16); $B = $aes->encrypt ($A . $R[2], $KEK); $A = substr ($B, 0, 8) ^ pack ("q", (2 * $j + 2)); $R[2] = substr ($B, 8, 16); } my $wrapped_key = unpack ("H*", $A . substr ($R[1], 0 ,8) . substr ($R[2], 0 ,8)); $mysalt = unpack ("H*", $mysalt); $tmp_hash = sprintf ('$axcrypt$*1*%s*%s*%s', $iteration, $mysalt, $wrapped_key); } elsif ($mode == 13300) { my $length = 32; if ($additional_param) { $length = $additional_param; } $hash_buf = sha1_hex ($word_buf); $tmp_hash = sprintf ('$axcrypt_sha1$%s', substr ($hash_buf, 0, $length)); } elsif ($mode == 13400) { my @salt_arr = split ('\*', $salt_buf); my $version = $salt_arr[0]; my $iteration = $salt_arr[1]; my $algorithm = $salt_arr[2]; my $final_random_seed = $salt_arr[3]; my $transf_random_seed = $salt_arr[4]; my $enc_iv = $salt_arr[5]; my $contents_hash; # specific to version 1 my $inline_flag; my $contents_len; my $contents; # specific to version 2 my $expected_bytes; # specific to keyfile handling my $inline_keyfile_flag; my $keyfile_len; my $keyfile_content; my $keyfile_attributes = ""; $final_random_seed = pack ("H*", $final_random_seed); $transf_random_seed = pack ("H*", $transf_random_seed); $enc_iv = pack ("H*", $enc_iv); my $intermediate_hash = sha256 ($word_buf); if ($version == 1) { $contents_hash = $salt_arr[6]; $contents_hash = pack ("H*", $contents_hash); $inline_flag = $salt_arr[7]; $contents_len = $salt_arr[8]; $contents = $salt_arr[9]; $contents = pack ("H*", $contents); # keyfile handling if (scalar @salt_arr == 13) { $inline_keyfile_flag = $salt_arr[10]; $keyfile_len = $salt_arr[11]; $keyfile_content = $salt_arr[12]; $keyfile_attributes = $keyfile_attributes . "*" . $inline_keyfile_flag . "*" . $keyfile_len . "*" . $keyfile_content; $intermediate_hash = $intermediate_hash . pack ("H*", $keyfile_content); $intermediate_hash = sha256 ($intermediate_hash); } } elsif ($version == 2) { # keyfile handling if (scalar @salt_arr == 11) { $inline_keyfile_flag = $salt_arr[8]; $keyfile_len = $salt_arr[9]; $keyfile_content = $salt_arr[10]; $intermediate_hash = $intermediate_hash . pack ("H*", $keyfile_content); $keyfile_attributes = $keyfile_attributes . "*" . $inline_keyfile_flag . "*" . $keyfile_len . "*" . $keyfile_content; } $intermediate_hash = sha256 ($intermediate_hash); } my $aes = Crypt::Mode::ECB->new ('AES', 1); for (my $j = 0; $j < $iteration; $j++) { $intermediate_hash = $aes->encrypt ($intermediate_hash, $transf_random_seed); $intermediate_hash = substr ($intermediate_hash, 0, 32); } $intermediate_hash = sha256 ($intermediate_hash); my $final_key = sha256 ($final_random_seed . $intermediate_hash); my $final_algorithm; if ($version == 1 && $algorithm == 1) { $final_algorithm = "Crypt::Twofish"; } else { $final_algorithm = "Crypt::Rijndael"; } my $cipher = Crypt::CBC->new ({ key => $final_key, cipher => $final_algorithm, iv => $enc_iv, literal_key => 1, header => "none", keysize => 32 }); if ($version == 1) { if (defined $additional_param) { # if we try to verify the crack, we need to decrypt the contents instead of only encrypting it: $contents = $cipher->decrypt ($contents); # and check the output my $contents_hash_old = $contents_hash; $contents_hash = sha256 ($contents); if ($contents_hash_old ne $contents_hash) { # fake content $contents = "\x00" x length ($contents); } } else { $contents_hash = sha256 ($contents); } $contents = $cipher->encrypt ($contents); $tmp_hash = sprintf ('$keepass$*%d*%d*%d*%s*%s*%s*%s*%d*%d*%s%s', $version, $iteration, $algorithm, unpack ("H*", $final_random_seed), unpack ("H*", $transf_random_seed), unpack ("H*", $enc_iv), unpack ("H*", $contents_hash), $inline_flag, $contents_len, unpack ("H*", $contents), $keyfile_attributes); } if ($version == 2) { $expected_bytes = $salt_arr[6]; $contents_hash = $salt_arr[7]; $contents_hash = pack ("H*", $contents_hash); $expected_bytes = $cipher->decrypt ($contents_hash); $tmp_hash = sprintf ('$keepass$*%d*%d*%d*%s*%s*%s*%s*%s%s', $version, $iteration, $algorithm, unpack ("H*", $final_random_seed), unpack ("H*", $transf_random_seed), unpack ("H*", $enc_iv), unpack ("H*", $expected_bytes), unpack ("H*", $contents_hash), $keyfile_attributes); } } elsif ($mode == 13500) { $hash_buf = sha1_hex (pack ("H*", $salt_buf) . encode ("UTF-16LE", $word_buf)); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 13600) { my $iterations = 1000; my $type = 0; if (defined $additional_param) { $type = $additional_param; } my $mode = 1 + int rand (3); if (defined $additional_param2) { $mode = $additional_param2; } my $magic = 0; if (defined $additional_param3) { $magic = $additional_param3; } if (defined $additional_param4) { $salt_buf = $additional_param4; } $salt_buf = substr ($salt_buf, 0, 8 + ($mode * 8)); my $compress_length = 0; if (defined $additional_param5) { $compress_length = $additional_param5; } my $data = ""; if (defined $additional_param6) { $data = $additional_param6; } my $key_len = (8 * ($mode & 3) + 8) * 2; my $out_len = $key_len + 2; my $salt_buf_bin = pack ("H*", $salt_buf); my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, output_len => $out_len ); my $key = $pbkdf2->PBKDF2_hex ($salt_buf_bin, $word_buf); my $verify_bytes = substr ($key, -4); $verify_bytes =~ s/^0+//; #lol $key = substr ($key, $key_len, $key_len); my $key_bin = pack ("H*", $key); my $auth = hmac_hex ($data, $key_bin, \&sha1, 64); $tmp_hash = sprintf ('$zip2$*%u*%u*%u*%s*%s*%u*%s*%s*$/zip2$', $type, $mode, $magic, $salt_buf, $verify_bytes, $compress_length, $data, substr ($auth, 0, 20)); } elsif ($mode == 13800) { my $word_buf_utf16le = encode ("UTF-16LE", $word_buf); my $salt_buf_bin = pack ("H*", $salt_buf); $hash_buf = sha256_hex ($word_buf_utf16le . $salt_buf_bin); $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 14000) { my $salt_buf_bin = pack ("H*", $salt_buf); my $cipher = new Crypt::DES $word_buf; my $hash_buf = $cipher->encrypt ($salt_buf_bin); $tmp_hash = sprintf ("%s:%s", unpack ("H*", $hash_buf), $salt_buf); } elsif ($mode == 14100) { my $word_buf1 = substr ($word_buf, 0, 8); my $word_buf2 = substr ($word_buf, 8, 8); my $word_buf3 = substr ($word_buf, 16, 8); my $salt_buf_bin = pack ("H*", $salt_buf); my $cipher1 = new Crypt::DES $word_buf1; my $hash_buf1 = $cipher1->encrypt ($salt_buf_bin); my $cipher2 = new Crypt::DES $word_buf2; my $hash_buf2 = $cipher2->decrypt ($hash_buf1); my $cipher3 = new Crypt::DES $word_buf3; my $hash_buf3 = $cipher3->encrypt ($hash_buf2); $tmp_hash = sprintf ("%s:%s", unpack ("H*", $hash_buf3), $salt_buf); } elsif ($mode == 14400) { my $begin = "--" . $salt_buf . "--"; my $end = "--" . $word_buf . "----"; my $hash_buf = sha1_hex ($begin . $end); for (my $round = 1; $round < 10; $round++) { $hash_buf = sha1_hex ($begin . $hash_buf . $end); } $tmp_hash = sprintf ("%s:%s", $hash_buf, $salt_buf); } elsif ($mode == 14700) { my $iterations = 10000; if (length ($iter)) { $iterations = int ($iter); } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'), iterations => $iterations, output_len => 32 ); $salt_buf = pack ("H*", $salt_buf); my $key = $pbkdf2->PBKDF2 ($salt_buf, $word_buf); my $ITUNES_BACKUP_KEY = 12008468691120727718; my $WPKY = "\x00" x 40; if (defined $additional_param) { my ($A, $R) = itunes_aes_unwrap ($key, $additional_param); if ($A == $ITUNES_BACKUP_KEY) { $WPKY = itunes_aes_wrap ($key, $A, $R); } } else { my $max_number = 18446744073709551615; # 0xffffffffffffffff my @R; for (my $i = 0; $i < 4; $i++) { $R[$i] = get_random_num (0, $max_number); } $WPKY = itunes_aes_wrap ($key, $ITUNES_BACKUP_KEY, \@R); } $tmp_hash = sprintf ("\$itunes_backup\$*9*%s*%i*%s**", unpack ("H*", $WPKY), $iterations, unpack ("H*", $salt_buf)); } elsif ($mode == 14800) { my $iterations = 10000; if (length ($iter)) { $iterations = int ($iter); } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'), iterations => $iterations, output_len => 32 ); $salt_buf = pack ("H*", $salt_buf); my $ITUNES_BACKUP_KEY = 12008468691120727718; my $DPIC; my $DPSL; if (defined $additional_param) { $DPIC = $additional_param2; $DPSL = $additional_param3; } else { #$DPIC = 10000000; it's too much for the tests $DPIC = 1000; $DPSL = randbytes (20); } my $WPKY = "\x00" x 40; my $pbkdf2x = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2'), iterations => $DPIC, output_len => 32 ); my $key_dpsl = $pbkdf2x->PBKDF2 ($DPSL, $word_buf); my $key = $pbkdf2->PBKDF2 ($salt_buf, $key_dpsl); if (defined $additional_param) { my ($A, $R) = itunes_aes_unwrap ($key, $additional_param); if ($A == $ITUNES_BACKUP_KEY) { $WPKY = itunes_aes_wrap ($key, $A, $R); } } else { my $max_number = 18446744073709551615; # 0xffffffffffffffff my @R; for (my $i = 0; $i < 4; $i++) { $R[$i] = get_random_num (0, $max_number); } $WPKY = itunes_aes_wrap ($key, $ITUNES_BACKUP_KEY, \@R); } $tmp_hash = sprintf ("\$itunes_backup\$*10*%s*%i*%s*%i*%s", unpack ("H*", $WPKY), $iterations, unpack ("H*", $salt_buf), $DPIC, unpack ("H*", $DPSL)); } elsif ($mode == 14900) { my $salt_bin = pack ("H*", $salt_buf); my $skip32 = Crypt::Skip32->new ($word_buf); my $hash = $skip32->encrypt ($salt_bin); $tmp_hash = sprintf ("%08x:%s", unpack ("N*", $hash), $salt_buf); } elsif ($mode == 15100) { my $iterations = 20000; if (defined ($iter)) { $iterations = $iter; } my $pbkdf1_salt_buf = sprintf ('%s$sha1$%u', $salt_buf, $iterations); my $tmp = hmac ($pbkdf1_salt_buf, $word_buf, \&sha1, 64); for (my $r = 1; $r < $iterations; $r++) { $tmp = hmac ($tmp, $word_buf, \&sha1, 64); } my $hash_buf = ""; $hash_buf .= to64 ((int (ord (substr ($tmp, 0, 1))) << 16) | (int (ord (substr ($tmp, 1, 1))) << 8) | (int (ord (substr ($tmp, 2, 1)))), 4); $hash_buf .= to64 ((int (ord (substr ($tmp, 3, 1))) << 16) | (int (ord (substr ($tmp, 4, 1))) << 8) | (int (ord (substr ($tmp, 5, 1)))), 4); $hash_buf .= to64 ((int (ord (substr ($tmp, 6, 1))) << 16) | (int (ord (substr ($tmp, 7, 1))) << 8) | (int (ord (substr ($tmp, 8, 1)))), 4); $hash_buf .= to64 ((int (ord (substr ($tmp, 9, 1))) << 16) | (int (ord (substr ($tmp, 10, 1))) << 8) | (int (ord (substr ($tmp, 11, 1)))), 4); $hash_buf .= to64 ((int (ord (substr ($tmp, 12, 1))) << 16) | (int (ord (substr ($tmp, 13, 1))) << 8) | (int (ord (substr ($tmp, 14, 1)))), 4); $hash_buf .= to64 ((int (ord (substr ($tmp, 15, 1))) << 16) | (int (ord (substr ($tmp, 16, 1))) << 8) | (int (ord (substr ($tmp, 17, 1)))), 4); $hash_buf .= to64 ((int (ord (substr ($tmp, 18, 1))) << 16) | (int (ord (substr ($tmp, 19, 1))) << 8) | 0 , 4); ## super hackish, but we have no other choice, as this byte is kind of a random byte added to the digest when the hash was created if (defined $additional_param) { $hash_buf = substr ($hash_buf, 0, 24) . substr ($additional_param, 24, 4); } $tmp_hash = sprintf ("\$sha1\$%d\$%s\$%s", $iterations, $salt_buf, $hash_buf); } elsif ($mode == 15200) { my $iterations = 5000; if (defined ($iter)) { $iterations = $iter; } my $data = qq|{ "guid" : "00000000-0000-0000-0000-000000000000", "sharedKey" : "00000000-0000-0000-0000-000000000000", "options" : {"pbkdf2_iterations":$iterations,"fee_policy":0,"html5_notifications":false,"logout_time":600000,"tx_display":0,"always_keep_local_backup":false}|; my $salt_buf_bin = pack ("H*", $salt_buf); my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, output_len => 32 ); my $key = $pbkdf2->PBKDF2 ($salt_buf_bin, $word_buf); my $cipher = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $salt_buf_bin, literal_key => 1, header => "none", keysize => 32 }); my $encrypted = unpack ("H*", $cipher->encrypt ($data)); $tmp_hash = sprintf ("\$blockchain\$v2\$%d\$%s\$%s", $iterations, length ($salt_buf . $encrypted) / 2, $salt_buf . $encrypted); } elsif ($mode == 15300 || $mode == 15900) { my @salt_arr = split ('\*', $salt_buf); my $version = $salt_arr[0]; my $context = $salt_arr[1]; my $SID = $salt_arr[2]; my $cipher_algorithm = $salt_arr[3]; my $hash_algorithm = $salt_arr[4]; my $iterations = $salt_arr[5]; my $salt = pack ("H*", $salt_arr[6]); my $cipher_len = $salt_arr[7]; my $cipher; # intermediate values my $user_hash; my $user_derivationKey; my $encKey; my $expected_hmac; my $cleartext; if ($context == 1) { $user_hash = sha1 (encode ("UTF-16LE", $word_buf)); } elsif ($context == 2) { $user_hash = md4 (encode ("UTF-16LE", $word_buf)); } $user_derivationKey = hmac_sha1 (encode ("UTF-16LE", $SID . "\x00"), $user_hash); my $hmacSalt = randbytes (16); my $last_key = randbytes (64); if ($version == 1) { $encKey = hmac_sha1 ($hmacSalt, $user_derivationKey); $expected_hmac = hmac_sha1 ($last_key, $encKey); # need padding because keyLen is 24 and hashLen 20 $expected_hmac = $expected_hmac . randbytes (4); } elsif ($version == 2) { $encKey = hmac_sha512 ($hmacSalt, $user_derivationKey); $expected_hmac = hmac_sha512 ($last_key, $encKey); } $cleartext = $hmacSalt . $expected_hmac . $last_key; my $derived_key; my $key; my $iv; my $pbkdf2; if ($version == 1) { $derived_key = dpapi_pbkdf2 ($user_derivationKey, $salt, $iterations, 32, \&hmac_sha1); } elsif ($version == 2) { $derived_key = dpapi_pbkdf2 ($user_derivationKey, $salt, $iterations, 48, \&hmac_sha512); } if (defined $additional_param) { $cipher = pack ("H*", $additional_param); my $computed_hmac = ""; if ($version == 1) { $key = substr ($derived_key, 0, 24); $iv = substr ($derived_key, 24, 8); my $p1 = Crypt::ECB->new ({ key => substr ($key, 0, 8), cipher => "DES", literal_key => 1, header => "none", keysize => 8, padding => "null", }); my $p2 = Crypt::ECB->new ({ key => substr ($key, 8, 8), cipher => "DES", literal_key => 1, header => "none", keysize => 8, padding => "null", }); my $p3 = Crypt::ECB->new ({ key => substr ($key, 16, 8), cipher => "DES", literal_key => 1, header => "none", keysize => 8, padding => "null", }); # let's compute a 3DES-EDE-CBC decryption my $out1; my $out2; my $out3; my $expected_cleartext = ""; # size of cipherlen is 104 bytes for (my $k = 0; $k < 13; $k++) { $out1 = $p3->decrypt (substr ($cipher, $k * 8, 8)); $out2 = $p2->encrypt ($out1); $out3 = $p1->decrypt ($out2); $expected_cleartext .= substr ($out3, 0, 8) ^ $iv; $iv = substr ($cipher, $k * 8, 8); } $last_key = substr ($expected_cleartext, length ($expected_cleartext) - 64, 64); $hmacSalt = substr ($expected_cleartext, 0, 16); $expected_hmac = substr ($expected_cleartext, 16, 20); $encKey = hmac_sha1 ($hmacSalt, $user_derivationKey); $computed_hmac = hmac_sha1 ($last_key, $encKey); $cleartext = $expected_cleartext; if (unpack ("H*", $expected_hmac) ne unpack ("H*", $computed_hmac)) { $cleartext = "0" x 104; } } elsif ($version == 2) { $key = substr ($derived_key, 0, 32); $iv = substr ($derived_key, 32, 16); my $aes = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $iv, literal_key => 1, header => "none", keysize => 32, padding => "null", }); my $expected_cleartext = $aes->decrypt ($cipher); $last_key = substr ($expected_cleartext, length ($expected_cleartext) - 64, 64); $hmacSalt = substr ($expected_cleartext, 0, 16); $expected_hmac = substr ($expected_cleartext, 16, 64); $encKey = hmac_sha512 ($hmacSalt, $user_derivationKey); $computed_hmac = hmac_sha512 ($last_key, $encKey); $cleartext = $expected_cleartext; if (unpack ("H*", $expected_hmac) ne unpack ("H*", $computed_hmac)) { $cleartext = "0" x 144; } } } if ($version == 1) { $key = substr ($derived_key, 0, 24); $iv = substr ($derived_key, 24, 8); my $p1 = Crypt::ECB->new ({ key => substr ($key, 0, 8), cipher => "DES", literal_key => 1, header => "none", keysize => 8, padding => "null", }); my $p2 = Crypt::ECB->new ({ key => substr ($key, 8, 8), cipher => "DES", literal_key => 1, header => "none", keysize => 8, padding => "null", }); my $p3 = Crypt::ECB->new ({ key => substr ($key, 16, 8), cipher => "DES", literal_key => 1, header => "none", keysize => 8, padding => "null", }); # let's compute a 3DES-EDE-CBC encryption # compute first block my $out1 = $p1->encrypt (substr ($cleartext, 0, 8) ^ $iv); my $out2 = $p2->decrypt ($out1); my $out3 = $p3->encrypt ($out2); $cipher = substr ($out3, 0, 8); # size of cipherlen is 104 bytes for (my $k = 1; $k < 13; $k++) { $iv = $out3; $out1 = $p1->encrypt (substr ($cleartext, $k * 8, 8) ^ $iv); $out2 = $p2->decrypt ($out1); $out3 = $p3->encrypt ($out2); $cipher .= substr ($out3, 0, 8); } } else { $key = substr ($derived_key, 0, 32); $iv = substr ($derived_key, 32, 16); my $aes = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $iv, literal_key => 1, header => "none", keysize => 32, padding => "null", }); $cipher = $aes->encrypt ($cleartext); } $tmp_hash = sprintf ('$DPAPImk$%d*%d*%s*%s*%s*%d*%s*%d*%s', $version, $context, $SID, $cipher_algorithm, $hash_algorithm, $iterations, unpack ("H*", $salt), $cipher_len, unpack ("H*", $cipher)); } elsif ($mode == 15400) { my $counter; my $offset; my $iv; if (defined $additional_param) { $counter = $additional_param; $offset = $additional_param2; $iv = $additional_param3; } else { $counter = "0400000000000003"; $offset = int (rand (63)); $iv = "0200000000000001"; } my $plaintext = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz0a2b4c6d8e"; my $eight_byte_iv = pack ("H*", $iv); my $eight_byte_counter = pack ("H*", $counter); my $pad_len = 32 - length ($word_buf); my $key = $word_buf . "\0" x $pad_len; my $cipher = Crypt::OpenSSH::ChachaPoly->new ($key); $cipher->ivsetup ($eight_byte_iv, $eight_byte_counter); my $enc = $cipher->encrypt ($plaintext); my $enc_offset = substr ($enc, $offset, 8); $hash_buf = $enc_offset; $tmp_hash = sprintf ("\$chacha20\$\*%s\*%d\*%s\*%s\*%s", $counter, $offset, $iv, unpack ("H*", substr ($plaintext, $offset, 8)), unpack ("H*", $enc_offset)); } elsif ($mode == 15500) { my $iv = pack ("H*", $salt_buf); if (length $additional_param) { $iv = pack ("H*", $additional_param); } my $enc_key = randbytes (get_random_num (1, 1500)); if (length $additional_param2) { $enc_key = pack ("H*", $additional_param2); } my $alias = "test"; if (length $additional_param3) { $alias = $additional_param3; } my $word_buf_utf16be = encode ("UTF-16BE", $word_buf); my $hash_buf = sha1 ($word_buf_utf16be . $iv); my $DER1 = substr ($hash_buf, 0, 1); my $DER2 = substr ($hash_buf, 6, 14); my @enc_key_data = split "", $enc_key; my $enc_key_data_length = scalar @enc_key_data; my @key_data = (); for (my $i = 0; $i < scalar $enc_key_data_length; $i += 20) { my @hash_buf_data = split "", $hash_buf; for (my $j = 0; $j < 20; $j++) { last if (($i + $j) >= $enc_key_data_length); $key_data[$i + $j] = $enc_key_data[$i + $j] ^ $hash_buf_data[$j]; } $hash_buf = sha1 ($word_buf_utf16be . $hash_buf); } my $key = join "", @key_data; $hash_buf = sha1 ($word_buf_utf16be . $key); $tmp_hash = sprintf ("\$jksprivk\$*%s*%s*%s*%s*%s*%s", uc unpack ("H*", $hash_buf), uc unpack ("H*", $iv), uc unpack ("H*", $enc_key), uc unpack ("H*", $DER1), uc unpack ("H*", $DER2), $alias); } elsif ($mode == 15600) { my $iterations; my $ciphertext; if (defined $additional_param) { $iterations = $iter; $ciphertext = $additional_param; } else { $iterations = 1024; # 262144 originally $ciphertext = randbytes (32); } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations, out_len => 32 ); my $derived_key = $pbkdf2->PBKDF2 ($salt_buf, $word_buf); my $derived_key_cropped = substr ($derived_key, 16, 16); $hash_buf = keccak_256_hex ($derived_key_cropped . $ciphertext); $tmp_hash = sprintf ("\$ethereum\$p*%i*%s*%s*%s", $iterations, unpack ("H*", $salt_buf), unpack ("H*", $ciphertext), $hash_buf); } elsif ($mode == 15700) { my $scrypt_N; my $scrypt_r; my $scrypt_p; my $ciphertext; if (defined $additional_param) { $scrypt_N = $additional_param; $scrypt_r = $additional_param2; $scrypt_p = $additional_param3; $ciphertext = $additional_param4; } else { $scrypt_N = 1024; # 262144 originally $scrypt_r = 1; # 8 originally $scrypt_p = 1; $ciphertext = randbytes (32); } my $derived_key = scrypt_raw ($word_buf, $salt_buf, $scrypt_N, $scrypt_r, $scrypt_p, 32); my $derived_key_cropped = substr ($derived_key, 16, 16); $hash_buf = keccak_256_hex ($derived_key_cropped . $ciphertext); $tmp_hash = sprintf ("\$ethereum\$s*%i*%i*%i*%s*%s*%s", $scrypt_N, $scrypt_r, $scrypt_p, unpack ("H*", $salt_buf), unpack ("H*", $ciphertext), $hash_buf); } elsif ($mode == 16000) { my $converter = Text::Iconv->new ("utf-8", "shift-jis"); $word_buf = $converter->convert ($word_buf); $salt_buf = substr ($word_buf . '..', 1, 2); $salt_buf =~ s/[^\.-z]/\./go; $salt_buf =~ tr/:;<=>?@[\\]^_`/A-Ga-f/; $hash_buf = crypt ($word_buf, $salt_buf); $hash_buf = substr ($hash_buf, -10); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 16100) { my $session_id; my $encrypted_data; my $sequence; if (defined $additional_param) { $session_id = pack ("H*", $additional_param); } else { $session_id = pack ("H*", randbytes (8)); } if (defined $additional_param2) { $encrypted_data = pack ("H*", $additional_param2); } if (defined $additional_param3) { $sequence = pack ("H*", $additional_param3); } else { $sequence = pack ("H*", "c006"); } my $key = md5 ($session_id . $word_buf . $sequence); if (defined $encrypted_data) { ## verify case my $encrypted_data_len = length $encrypted_data; my $plain_data = substr ($encrypted_data, 0, 6) ^ substr ($key, 0, 6); my ($status, $flags, $server_msg_len, $data_len) = unpack ("CCnn", $plain_data); if ((($status >= 0x01 && $status <= 0x07) || $status == 0x21) && ($flags == 0x01 || $flags == 0x00) && (6 + $server_msg_len + $data_len == $encrypted_data_len)) { ## ok } else { $encrypted_data = ""; # some invalid data } } else { my $plain_data = "\x01\x00\x00\x00\x00\x00"; my $plain_data_len = length $plain_data; my $shortest = ($plain_data_len > 16) ? 16 : $plain_data_len; $encrypted_data = substr ($plain_data, 0, $shortest) ^ substr ($key, 0, $shortest); } $tmp_hash = sprintf ('$tacacs-plus$0$%s$%s$%s', unpack ("H*", $session_id), unpack ("H*", $encrypted_data), unpack ("H*", $sequence)); } elsif ($mode == 16200) { my $salt_bin = pack ("H*", $salt_buf); my $iterations = 20000; if (defined ($iter)) { $iterations = $iter; } my $Z_PK = 1; if (defined $additional_param) { $Z_PK = $additional_param; } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations, output_len => 16, ); my $KEK = $pbkdf2->PBKDF2 ($salt_bin, $word_buf); my $aes = Crypt::Mode::ECB->new ('AES', 0); my $blob_bin; my $A; my $B; my $P1; my $P2; if (defined $additional_param2) { $blob_bin = pack ("H*", $additional_param2); $A = substr ($blob_bin, 0, 8); $P1 = substr ($blob_bin, 8, 8); $P2 = substr ($blob_bin, 16, 8); for (my $j = 5; $j >= 0; $j--) { # N = 2 $B = $A; $B ^= pack ("Q>", (2 * $j + 2)); $B .= $P2; $B = $aes->decrypt ($B, $KEK); $A = substr ($B, 0, 8); $P2 = substr ($B, 8, 8); # N = 1 $B = $A; $B ^= pack ("Q>", (2 * $j + 1)); $B .= $P1; $B = $aes->decrypt ($B, $KEK); $A = substr ($B, 0, 8); $P1 = substr ($B, 8, 8); } if ($A eq "\xa6" x 8) { for (my $j = 0; $j <= 5; $j++) { # N = 1 $B = $A; $B .= $P1; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (2 * $j + 1)); $P1 = substr ($B, 8, 8); # N = 2 $B = $A; $B .= $P2; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (2 * $j + 2)); $P2 = substr ($B, 8, 8); } $blob_bin = $A . $P1 . $P2; } else { $blob_bin = "\xff" x 24; } } else { $A = "\xa6" x 8; $P1 = "\xff" x 8; $P2 = "\xff" x 8; for (my $j = 0; $j <= 5; $j++) { # N = 1 $B = $A; $B .= $P1; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (2 * $j + 1)); $P1 = substr ($B, 8, 8); # N = 2 $B = $A; $B .= $P2; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (2 * $j + 2)); $P2 = substr ($B, 8, 8); } $blob_bin = $A . $P1 . $P2; } $tmp_hash = sprintf ('$ASN$*%d*%d*%s*%s', $Z_PK, $iterations, unpack ("H*", $salt_bin), unpack ("H*", $blob_bin)); } elsif ($mode == 16300) { my $ethaddr = $salt_buf; my $iv = ""; my $seed = ""; my $encseed = ""; # setup pbkdf2 params: my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => 2000, output_len => 16 ); my $key = $pbkdf2->PBKDF2 ($word_buf, $word_buf); if (defined $additional_param) { $iv = substr ($additional_param, 0, 16); $encseed = substr ($additional_param, 16); # AES-128-CBC decrypt: my $aes_cbc = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $iv, literal_key => 1, header => "none", keysize => 16 }); $seed = $aes_cbc->decrypt ($encseed); } else { $iv = randbytes (16); $seed = randbytes (592); # AES-128-CBC encrypt: my $aes_cbc = Crypt::CBC->new ({ key => $key, cipher => "Crypt::Rijndael", iv => $iv, literal_key => 1, header => "none", keysize => 16 }); $encseed = $aes_cbc->encrypt ($seed); } $hash_buf = keccak_256_hex ($seed . "\x02"); $tmp_hash = sprintf ("\$ethereum\$w*%s*%s*%s", unpack ("H*", $iv . $encseed), $ethaddr, substr ($hash_buf, 0, 32)); } elsif ($mode == 16400) { my $md5 = Digest::Perl::MD5->new; my $length = length($word_buf); $md5->{_data} = $word_buf ^ ("\x5c" x $length); $md5->{_data} .= "\x5c" x (64 - $length); $md5->add(); $hash_buf = unpack("H*", pack('V4', @{$md5->{_state}})); $tmp_hash = sprintf ("{CRAM-MD5}%s00000000000000000000000000000000", $hash_buf); } elsif ($mode == 16500) { my ($header_base64) = split (/\./, $salt_buf); my $header_jwt = decode_base64url ($header_base64); my $header = decode_json ($header_jwt); my $alg = $header->{"alg"}; if ($alg eq "HS256") { $hash_buf = hmac ($salt_buf, $word_buf, \&sha256, 64); } elsif ($alg eq "HS384") { $hash_buf = hmac ($salt_buf, $word_buf, \&sha384, 128); } elsif ($alg eq "HS512") { $hash_buf = hmac ($salt_buf, $word_buf, \&sha512, 128); } else { die "not supported hash\n"; } $tmp_hash = sprintf ("%s.%s", $salt_buf, encode_base64url ($hash_buf, "")); } elsif ($mode == 16600) { my $key_bin = sha256 (sha256 ($word_buf)); my $salt_type; if (defined $additional_param) { $salt_type = $additional_param; if ($salt_type ne "1") { die "currently only salt_type 1 supported\n"; } } else { $salt_type = 1; } my $iv; if (defined $additional_param2) { $iv = $additional_param2; } else { $iv = substr ($salt_buf, 0, 32); } my $iv_bin = pack ("H*", $iv); my $cipher = Crypt::CBC->new ({ key => $key_bin, cipher => "Crypt::Rijndael", iv => $iv_bin, literal_key => 1, header => "none", keysize => 32, padding => "null", }); my $plain_bin; if (defined $additional_param3) { my $encrypted_bin = pack ("H*", $additional_param3); my $test = $cipher->decrypt ($encrypted_bin); if ($test =~ /^[0-9a-f]+$/) { $plain_bin = $test; } else { $plain_bin = "\xff" x 16; } } else { my $plain = "30313233343536373839616263646566"; $plain_bin = pack ("H*", $plain); } my $encrypted_bin = $cipher->encrypt ($plain_bin); my $encrypted = unpack ("H*", $encrypted_bin); $tmp_hash = sprintf ("\$electrum\$%d*%s*%s", $salt_type, $iv, $encrypted); } elsif ($mode == 16700) { my $salt_bin = pack ("H*", $salt_buf); my $iterations = 20000; if (defined ($iter)) { $iterations = $iter; } my $Z_PK = 1; if (defined $additional_param) { $Z_PK = $additional_param; } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations, output_len => 16, ); my $KEK = $pbkdf2->PBKDF2 ($salt_bin, $word_buf); my $aes = Crypt::Mode::ECB->new ('AES', 0); my $blob_bin; my $A; my $B; my $P1; my $P2; if (defined $additional_param2) { $blob_bin = pack ("H*", $additional_param2); $A = substr ($blob_bin, 0, 8); $P1 = substr ($blob_bin, 8, 8); $P2 = substr ($blob_bin, 16, 8); for (my $j = 5; $j >= 0; $j--) { # N = 2 $B = $A; $B ^= pack ("Q>", (2 * $j + 2)); $B .= $P2; $B = $aes->decrypt ($B, $KEK); $A = substr ($B, 0, 8); $P2 = substr ($B, 8, 8); # N = 1 $B = $A; $B ^= pack ("Q>", (2 * $j + 1)); $B .= $P1; $B = $aes->decrypt ($B, $KEK); $A = substr ($B, 0, 8); $P1 = substr ($B, 8, 8); } if ($A eq "\xa6" x 8) { for (my $j = 0; $j <= 5; $j++) { # N = 1 $B = $A; $B .= $P1; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (2 * $j + 1)); $P1 = substr ($B, 8, 8); # N = 2 $B = $A; $B .= $P2; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (2 * $j + 2)); $P2 = substr ($B, 8, 8); } $blob_bin = $A . $P1 . $P2; } else { $blob_bin = "\xff" x 24; } } else { $A = "\xa6" x 8; $P1 = "\xff" x 8; $P2 = "\xff" x 8; for (my $j = 0; $j <= 5; $j++) { # N = 1 $B = $A; $B .= $P1; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (2 * $j + 1)); $P1 = substr ($B, 8, 8); # N = 2 $B = $A; $B .= $P2; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (2 * $j + 2)); $P2 = substr ($B, 8, 8); } $blob_bin = $A . $P1 . $P2; } $tmp_hash = sprintf ('$fvde$%d$%d$%s$%d$%s', $Z_PK, length ($salt_bin), unpack ("H*", $salt_bin), $iterations, unpack ("H*", $blob_bin)); } elsif ($mode == 16800) { my $macap; my $macsta; my $essid; if (!defined ($additional_param)) { $macap = unpack ("H*", randbytes (6)); } else { $macap = $additional_param; } if (!defined ($additional_param2)) { $macsta = unpack ("H*", randbytes (6)); } else { $macsta = $additional_param2; } if (!defined ($additional_param3)) { $essid = unpack ("H*", randbytes (get_random_num (8, 32) & 0x1e)); } else { $essid = $additional_param3; } # generate the Pairwise Master Key (PMK) my $iterations = 4096; my $pbkdf2 = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => $iterations, output_len => 32, ); my $essid_bin = pack ("H*", $essid); my $pmk = $pbkdf2->PBKDF2 ($essid_bin, $word_buf); my $macap_bin = pack ("H*", $macap); my $macsta_bin = pack ("H*", $macsta); my $data = "PMK Name" . $macap_bin . $macsta_bin; my $pmkid = hmac_hex ($data, $pmk, \&sha1); $tmp_hash = sprintf ("%s*%s*%s*%s", substr ($pmkid, 0, 32), $macap, $macsta, $essid); } elsif ($mode == 17300) { $hash_buf = sha3_224_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 17400) { $hash_buf = sha3_256_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 17500) { $hash_buf = sha3_384_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 17600) { $hash_buf = sha3_512_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 17700) { $hash_buf = keccak_224_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 17800) { $hash_buf = keccak_256_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 17900) { $hash_buf = keccak_384_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 18000) { $hash_buf = keccak_512_hex ($word_buf); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 18100) { my $paddedTime = sprintf ("%016x", int (int ($salt_buf) / 30)); my $data = pack ('H*', $paddedTime); my $key = $word_buf; $hash_buf = hmac_hex ($data, $key, \&sha1, 64); my $offset = hex (substr ($hash_buf, -8)) & 0xf; $offset *= 2; my $token = hex (substr ($hash_buf, $offset, 8)); $token &= 0x7fffffff; $token %= 1000000; ## token must be leading zero padded, and salt leading zero stripped $tmp_hash = sprintf ("%06d:%d", $token, int ($salt_buf)); } elsif ($mode == 18200) { my @salt_arr = split (':', $salt_buf); my $user_principal_name = $salt_arr[0]; my $k = md4 (encode ("UTF-16LE", $word_buf)); my $k1 = hmac_md5 ("\x08\x00\x00\x00", $k); my $cleartext_ticket = '7981df3081dca01b3019a003020117a112041071e026814da2' . '3f129f0e67a01b73f79aa11c301a3018a003020100a111180f32303138313033303039353' . '831365aa206020460fdc6caa311180f32303337303931343032343830355aa40703050050' . 'c10000a511180f32303138313033303039353831365aa611180f323031383130333030393' . '53831365aa711180f32303138313033303139353831365aa811180f323031383130333131' . '30303433385aa90d1b0b545952454c4c2e434f5250aa20301ea003020101a11730151b066' . 'b72627467741b0b545952454c4c2e434f5250'; my $checksum = ""; if (defined $additional_param) { $checksum = pack ("H*", $additional_param); } else { my $nonce = $salt_arr[1]; $cleartext_ticket = $nonce . $cleartext_ticket; $checksum = hmac_md5 (pack ("H*", $cleartext_ticket), $k1); } my $k3 = hmac_md5 ($checksum, $k1); my $edata2 = ""; if (defined $additional_param2) { $edata2 = $additional_param2; my $cipher_decrypt = Crypt::RC4->new ($k3); my $ticket_decrypt = unpack ("H*", $cipher_decrypt->RC4 (pack ("H*", $edata2))); my $check_correct = ((substr ($ticket_decrypt, 16, 4) eq "7981" && substr ($ticket_decrypt, 22, 2) eq "30")) || ((substr ($ticket_decrypt, 16, 2) eq "79") && (substr ($ticket_decrypt, 20, 2) eq "30")) || ((substr ($ticket_decrypt, 16, 4) eq "7982") && (substr ($ticket_decrypt, 24, 2) eq "30")); if ($check_correct == 1) { $cleartext_ticket = $ticket_decrypt; } else # validation failed { # fake/wrong ticket (otherwise if we just decrypt/encrypt we end up with false positives all the time) $cleartext_ticket = "0" x (length ($cleartext_ticket) + 16); } } my $cipher = Crypt::RC4->new ($k3); $edata2 = $cipher->RC4 (pack ("H*", $cleartext_ticket)); $tmp_hash = sprintf ('$krb5asrep$23$%s:%s$%s', $user_principal_name, unpack ("H*", $checksum), unpack ("H*", $edata2)); } elsif ($mode == 18300) { my $salt_bin = pack ("H*", $salt_buf); my $iterations = 20000; if (defined ($iter)) { $iterations = $iter; } my $Z_PK = 2; if (defined $additional_param) { $Z_PK = $additional_param; } my $pbkdf2 = Crypt::PBKDF2->new ( hasher => Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256), iterations => $iterations, output_len => 32, ); my $KEK = $pbkdf2->PBKDF2 ($salt_bin, $word_buf); my $aes = Crypt::Mode::ECB->new ('AES', 0); my $blob_bin; my $A; my $B; my $P1; my $P2; my $P3; my $P4; if (defined $additional_param2) { $blob_bin = pack ("H*", $additional_param2); $A = substr ($blob_bin, 0, 8); $P1 = substr ($blob_bin, 8, 8); $P2 = substr ($blob_bin, 16, 8); $P3 = substr ($blob_bin, 24, 8); $P4 = substr ($blob_bin, 32, 8); for (my $j = 5; $j >= 0; $j--) { # N = 4 $B = $A; $B ^= pack ("Q>", (4 * $j + 4)); $B .= $P4; $B = $aes->decrypt ($B, $KEK); $A = substr ($B, 0, 8); $P4 = substr ($B, 8, 8); # N = 3 $B = $A; $B ^= pack ("Q>", (4 * $j + 3)); $B .= $P3; $B = $aes->decrypt ($B, $KEK); $A = substr ($B, 0, 8); $P3 = substr ($B, 8, 8); # N = 2 $B = $A; $B ^= pack ("Q>", (4 * $j + 2)); $B .= $P2; $B = $aes->decrypt ($B, $KEK); $A = substr ($B, 0, 8); $P2 = substr ($B, 8, 8); # N = 1 $B = $A; $B ^= pack ("Q>", (4 * $j + 1)); $B .= $P1; $B = $aes->decrypt ($B, $KEK); $A = substr ($B, 0, 8); $P1 = substr ($B, 8, 8); } if ($A eq "\xa6" x 8) { for (my $j = 0; $j <= 5; $j++) { # N = 1 $B = $A; $B .= $P1; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (4 * $j + 1)); $P1 = substr ($B, 8, 8); # N = 2 $B = $A; $B .= $P2; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (4 * $j + 2)); $P2 = substr ($B, 8, 8); # N = 3 $B = $A; $B .= $P3; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (4 * $j + 3)); $P3 = substr ($B, 8, 8); # N = 4 $B = $A; $B .= $P4; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (4 * $j + 4)); $P4 = substr ($B, 8, 8); } $blob_bin = $A . $P1 . $P2 . $P3 . $P4; } else { $blob_bin = "\xff" x 40; } } else { $A = "\xa6" x 8; $P1 = "\xff" x 8; $P2 = "\xff" x 8; $P3 = "\xff" x 8; $P4 = "\xff" x 8; for (my $j = 0; $j <= 5; $j++) { # N = 1 $B = $A; $B .= $P1; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (4 * $j + 1)); $P1 = substr ($B, 8, 8); # N = 2 $B = $A; $B .= $P2; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (4 * $j + 2)); $P2 = substr ($B, 8, 8); # N = 3 $B = $A; $B .= $P3; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (4 * $j + 3)); $P3 = substr ($B, 8, 8); # N = 4 $B = $A; $B .= $P4; $B = $aes->encrypt ($B, $KEK); $A = substr ($B, 0, 8); $A ^= pack ("Q>", (4 * $j + 4)); $P4 = substr ($B, 8, 8); } $blob_bin = $A . $P1 . $P2 . $P3 . $P4; } $tmp_hash = sprintf ('$fvde$%d$%d$%s$%d$%s', $Z_PK, length ($salt_bin), unpack ("H*", $salt_bin), $iterations, unpack ("H*", $blob_bin)); } elsif ($mode == 18400) { # defaults for single mode my $iterations = 100000; my $iv = "aa" x 16; my $plaintext = "bb" x 1024; # parameters for verify mode if (defined $iter) { $iterations = $iter; } if (defined $additional_param) { $iv = $additional_param; } if (defined $additional_param2) { $plaintext = $additional_param2; } # binary buffers my $b_iv = pack ("H*", $iv); my $b_salt = pack ("H*", $salt_buf); my $b_plaintext = pack ("H*", $plaintext); my $kdf = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => $iterations, output_len => 32 ); my $checksum = sha256_hex ($b_plaintext); my $pass_hash = sha256 ($word_buf); my $derived_key = $kdf->PBKDF2 ($b_salt, $pass_hash); my $cbc = Crypt::Mode::CBC->new ('AES', 0); my $b_ciphertext = $cbc->encrypt ($b_plaintext, $derived_key, $b_iv); my $ciphertext = unpack ("H*", $b_ciphertext); $tmp_hash = '$odf$'."*1*1*$iterations*32*$checksum*16*$iv*16*$salt_buf*0*$ciphertext"; } elsif ($mode == 18500) { $hash_buf = sha1_hex (md5_hex (md5_hex ($word_buf))); $tmp_hash = sprintf ("%s", $hash_buf); } elsif ($mode == 18600) { # defaults for single mode my $iterations = 1024; my $iv = "aa" x 8; my $plaintext = "bb" x 1024; # parameters for verify mode if (defined $iter) { $iterations = $iter; } if (defined $additional_param) { $iv = $additional_param; } if (defined $additional_param2) { $plaintext = $additional_param2; } # binary buffers my $b_iv = pack ("H*", $iv); my $b_salt = pack ("H*", $salt_buf); my $b_plaintext = pack ("H*", $plaintext); my $kdf = Crypt::PBKDF2->new ( hash_class => 'HMACSHA1', iterations => $iterations, output_len => 16 ); my $checksum = sha1_hex ($b_plaintext); my $pass_hash = sha1 ($word_buf); my $derived_key = $kdf->PBKDF2 ($b_salt, $pass_hash); my $cfb = Crypt::GCrypt->new( type => 'cipher', algorithm => 'blowfish', mode => 'cfb', ); $cfb->start ('encrypting'); $cfb->setkey ($derived_key); $cfb->setiv ($b_iv); my $b_ciphertext = $cfb->encrypt ($b_plaintext); $cfb->finish (); my $ciphertext = unpack ("H*", $b_ciphertext); $tmp_hash = '$odf$'."*0*0*$iterations*16*$checksum*8*$iv*16*$salt_buf*0*$ciphertext"; } elsif ($mode == 99999) { $tmp_hash = sprintf ("%s", $word_buf); } return ($tmp_hash); } #Thanks to Jochen Hoenicke <hoenicke@gmail.com> # (one of the authors of Palm Keyring) # for these next two subs. sub dpapi_pbkdf2 { my ($password, $salt, $iter, $keylen, $prf) = @_; my ($k, $t, $u, $ui, $i); $t = ""; for ($k = 1; length ($t) < $keylen; $k++) { $u = $ui = &$prf ($salt.pack ('N', $k), $password); for ($i = 1; $i < $iter; $i++) { # modification to fit Microsoft # weird pbkdf2 implementation... $ui = &$prf ($u, $password); $u ^= $ui; } $t .= $u; } return substr ($t, 0, $keylen); } ## STEP 4: Add custom traits here (optional). sub rnd { my $mode = shift; my $word_len = shift; my $salt_len = shift; my $max = $MAX_LEN; if ($mode == 2410) { $salt_len = min ($salt_len, 4); } if (is_in_array ($mode, $IS_UTF16LE)) { if (is_in_array ($mode, $ALLOW_LONG_SALT)) { $word_len = min ($word_len, int ($max / 2)); } else { $word_len = min ($word_len, int ($max / 2) - $salt_len); } } elsif (is_in_array ($mode, $LESS_FIFTEEN)) { $word_len = min ($word_len, 15); } else { if (! is_in_array ($mode, $ALLOW_LONG_SALT)) { $word_len = min ($word_len, $max - $salt_len); } } if ($word_len < 1) { $word_len = 1; } ## ## gen salt ## my $salt_buf; if ($mode == 4800) { my @salt_arr; for (my $i = 0; $i < $salt_len; $i++) { my $c = get_random_chr (0x30, 0x39); push (@salt_arr, $c); } $salt_buf = join ("", @salt_arr); $salt_buf = get_random_md5chap_salt ($salt_buf); } elsif ($mode == 5300 || $mode == 5400) { $salt_buf = get_random_ike_salt (); } elsif ($mode == 5500) { $salt_buf = get_random_netntlmv1_salt ($salt_len, $salt_len); } elsif ($mode == 5600) { $salt_buf = get_random_netntlmv2_salt ($salt_len, $salt_len); } elsif ($mode == 6600) { $salt_buf = get_random_agilekeychain_salt (); } elsif ($mode == 8200) { $salt_buf = get_random_cloudkeychain_salt (); } elsif ($mode == 8300) { $salt_buf = get_random_dnssec_salt (); } elsif ($mode == 13100) { $salt_buf = get_random_kerberos5_tgs_salt (); } elsif ($mode == 13200) { $salt_buf = get_random_axcrypt_salt (); } elsif ($mode == 13400) { $salt_buf = get_random_keepass_salt (); } elsif ($mode == 13500) { $salt_buf = get_pstoken_salt (); } elsif ($mode == 15300 || $mode == 15900) { my $version = 2; if ($mode == 15300) { $version = 1; } $salt_buf = get_random_dpapimk_salt ($version); } elsif ($mode == 16500) { $salt_buf = get_random_jwt_salt (); } elsif ($mode == 18200) { $salt_buf = get_random_kerberos5_as_rep_salt (); } else { my @salt_arr; for (my $i = 0; $i < $salt_len; $i++) { my $c = get_random_chr (0x30, 0x39); push (@salt_arr, $c); } $salt_buf = join ("", @salt_arr); if ($mode == 7500) { $salt_buf = get_random_kerberos5_salt ($salt_buf); } } ## ## gen plain ## my @word_arr; for (my $i = 0; $i < $word_len; $i++) { my $c = get_random_chr (0x30, 0x39); if (($mode == 14000) || ($mode == 14100)) { $c &= 0xfe; } push (@word_arr, $c); } my $word_buf = join ("", @word_arr); ## ## gen hash ## my $tmp_hash = gen_hash ($mode, $word_buf, $salt_buf); ## ## run ## my @cmd = ( $hashcat, "-a 0 -m", $mode, $tmp_hash ); print sprintf ("echo -n %-20s | %s \${OPTS} %s %4d '%s'\n", $word_buf, @cmd); } ## ## subs ## sub min { $_[$_[0] > $_[1]]; } sub get_random_string { my $len = shift; my @arr; for (my $i = 0; $i < $len; $i++) { my $c = get_random_chr (0x30, 0x39); push (@arr, $c); } my $buf = join ("", @arr); return $buf; } sub get_random_num { my $min = shift; my $max = shift; return int ((rand ($max - $min)) + $min); } sub get_random_chr { return chr get_random_num (@_); } sub domino_decode { my $str = shift; my $decoded = ""; for (my $i = 0; $i < length ($str); $i += 4) { my $num = domino_base64_decode (substr ($str, $i, 4), 4); $decoded .= chr (($num >> 16) & 0xff) . chr (($num >> 8) & 0xff) . chr ($num & 0xff); } my $salt; my $digest; my $char; $salt = substr ($decoded, 0, 5); my $byte10 = (ord (substr ($salt, 3, 1)) - 4); if ($byte10 < 0) { $byte10 = 256 + $byte10; } substr ($salt, 3, 1) = chr ($byte10); $digest = substr ($decoded, 5, 9); $char = substr ($str, 18, 1); return ($digest, $salt, $char); } sub domino_85x_decode { my $str = shift; my $decoded = ""; for (my $i = 0; $i < length ($str); $i += 4) { my $num = domino_base64_decode (substr ($str, $i, 4), 4); $decoded .= chr (($num >> 16) & 0xff) . chr (($num >> 8) & 0xff) . chr ($num & 0xff); } my $digest; my $salt; my $iterations = -1; my $chars; $salt = substr ($decoded, 0, 16); # longer than -m 8700 (5 vs 16 <- new) my $byte10 = (ord (substr ($salt, 3, 1)) - 4); if ($byte10 < 0) { $byte10 = 256 + $byte10; } substr ($salt, 3, 1) = chr ($byte10); $iterations = substr ($decoded, 16, 10); if ($iterations =~ /^?d*$/) { # continue $iterations = $iterations + 0; # hack: make sure it is an int now (atoi ()) $chars = substr ($decoded, 26, 2); # in my example it is "02" $digest = substr ($decoded, 28, 8); # only of length of 8 vs 20 SHA1 bytes } return ($digest, $salt, $iterations, $chars); } sub domino_base64_decode { my $v = shift; my $n = shift; my $itoa64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"; my $ret = 0; my $i = 1; while ($i <= $n) { my $idx = (index ($itoa64, substr ($v, $n - $i, 1))) & 0x3f; $ret += ($idx << (6 * ($i - 1))); $i = $i + 1; } return $ret } sub domino_encode { my $final = shift; my $char = shift; my $byte10 = (ord (substr ($final, 3, 1)) + 4); if ($byte10 > 255) { $byte10 = $byte10 - 256; } substr ($final, 3, 1) = chr ($byte10); my $passwd = ""; $passwd .= domino_base64_encode ((int (ord (substr ($final, 0, 1))) << 16) | (int (ord (substr ($final, 1, 1))) << 8) | (int (ord (substr ($final, 2, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 3, 1))) << 16) | (int (ord (substr ($final, 4, 1))) << 8) | (int (ord (substr ($final, 5, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 6, 1))) << 16) | (int (ord (substr ($final, 7, 1))) << 8) | (int (ord (substr ($final, 8, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 9, 1))) << 16) | (int (ord (substr ($final, 10, 1))) << 8) | (int (ord (substr ($final, 11, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 12, 1))) << 16) | (int (ord (substr ($final, 13, 1))) << 8) | (int (ord (substr ($final, 14, 1)))), 4); if (defined ($char)) { substr ($passwd, 18, 1) = $char; } substr ($passwd, 19, 1) = ""; return $passwd; } sub domino_85x_encode { my $final = shift; my $char = shift; my $byte10 = (ord (substr ($final, 3, 1)) + 4); if ($byte10 > 255) { $byte10 = $byte10 - 256; } substr ($final, 3, 1) = chr ($byte10); my $passwd = ""; $passwd .= domino_base64_encode ((int (ord (substr ($final, 0, 1))) << 16) | (int (ord (substr ($final, 1, 1))) << 8) | (int (ord (substr ($final, 2, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 3, 1))) << 16) | (int (ord (substr ($final, 4, 1))) << 8) | (int (ord (substr ($final, 5, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 6, 1))) << 16) | (int (ord (substr ($final, 7, 1))) << 8) | (int (ord (substr ($final, 8, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 9, 1))) << 16) | (int (ord (substr ($final, 10, 1))) << 8) | (int (ord (substr ($final, 11, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 12, 1))) << 16) | (int (ord (substr ($final, 13, 1))) << 8) | (int (ord (substr ($final, 14, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 15, 1))) << 16) | (int (ord (substr ($final, 16, 1))) << 8) | (int (ord (substr ($final, 17, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 18, 1))) << 16) | (int (ord (substr ($final, 19, 1))) << 8) | (int (ord (substr ($final, 20, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 21, 1))) << 16) | (int (ord (substr ($final, 22, 1))) << 8) | (int (ord (substr ($final, 23, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 24, 1))) << 16) | (int (ord (substr ($final, 25, 1))) << 8) | (int (ord (substr ($final, 26, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 27, 1))) << 16) | (int (ord (substr ($final, 28, 1))) << 8) | (int (ord (substr ($final, 29, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 30, 1))) << 16) | (int (ord (substr ($final, 31, 1))) << 8) | (int (ord (substr ($final, 32, 1)))), 4); $passwd .= domino_base64_encode ((int (ord (substr ($final, 33, 1))) << 16) | (int (ord (substr ($final, 34, 1))) << 8) | (int (ord (substr ($final, 35, 1)))), 4); if (defined ($char)) { substr ($passwd, 18, 1) = $char; } return $passwd; } sub domino_base64_encode { my $v = shift; my $n = shift; my $itoa64 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"; my $ret = ""; while (($n - 1) >= 0) { $n = $n - 1; $ret = substr ($itoa64, $v & 0x3f, 1) . $ret; $v = $v >> 6; } return $ret } sub pseudo_base64 { my $itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; my $md5 = shift; my $s64 = ""; for my $i (0..3) { my $v = unpack "V", substr ($md5, $i*4, 4); for (1..4) { $s64 .= substr ($itoa64, $v & 0x3f, 1); $v >>= 6; } } return $s64; } sub racf_hash { my ($username, $password) = @_; $username = substr ($username . " " x 8, 0, 8); $password = substr ($password . " " x 8, 0, 8); my $username_ebc = ascii2ebcdic ($username); my $password_ebc = ascii2ebcdic ($password); my @pw = split ("", $password_ebc); for (my $i = 0; $i < 8; $i++) { $pw[$i] = unpack ("C", $pw[$i]); $pw[$i] ^= 0x55; $pw[$i] <<= 1; $pw[$i] = pack ("C", $pw[$i] & 0xff); } my $key = join ("", @pw); my $cipher = new Crypt::DES $key; my $ciphertext = $cipher->encrypt ($username_ebc); my $ct = unpack ("H16", $ciphertext); return $ct; } sub oracle_hash { my ($username, $password) = @_; my $userpass = pack ('n*', unpack ('C*', uc ($username.$password))); $userpass .= pack ('C', 0) while (length ($userpass) % 8); my $key = pack ('H*', "0123456789ABCDEF"); my $iv = pack ('H*', "0000000000000000"); my $c = new Crypt::CBC ( -literal_key => 1, -cipher => "DES", -key => $key, -iv => $iv, -header => "none" ); my $key2 = substr ($c->encrypt ($userpass), length ($userpass)-8, 8); my $c2 = new Crypt::CBC ( -literal_key => 1, -cipher => "DES", -key => $key2, -iv => $iv, -header => "none" ); my $hash = substr ($c2->encrypt ($userpass), length ($userpass)-8, 8); return uc (unpack ('H*', $hash)); } sub androidpin_hash { my $word_buf = shift; my $salt_buf = shift; my $w = sprintf ("%d%s%s", 0, $word_buf, $salt_buf); my $digest = sha1 ($w); for (my $i = 1; $i < 1024; $i++) { $w = $digest . sprintf ("%d%s%s", $i, $word_buf, $salt_buf); $digest = sha1 ($w); } my ($A, $B, $C, $D, $E) = unpack ("N5", $digest); return sprintf ("%08x%08x%08x%08x%08x", $A, $B, $C, $D, $E); } sub to64 { my $v = shift; my $n = shift; my $itoa64 = "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; my $ret = ""; while (($n - 1) >= 0) { $n = $n - 1; $ret .= substr ($itoa64, $v & 0x3f, 1); $v = $v >> 6; } return $ret } sub md5_crypt { my $magic = shift; my $iter = shift; my $pass = shift; my $salt = shift; my $hash = ""; # hash to be returned by this function my $final = md5 ($pass . $salt . $pass); $salt = substr ($salt, 0, 8); my $tmp = $pass . $magic . $salt; my $pass_len = length ($pass); my $i; for ($i = $pass_len; $i > 0; $i -= 16) { my $len = 16; if ($i < $len) { $len = $i; } $tmp .= substr ($final, 0, $len); } $i = $pass_len; while ($i > 0) { if ($i & 1) { $tmp .= chr (0); } else { $tmp .= substr ($pass, 0, 1); } $i >>= 1; } $final = md5 ($tmp); for ($i = 0; $i < $iter; $i++) { $tmp = ""; if ($i & 1) { $tmp .= $pass; } else { $tmp .= $final; } if ($i % 3) { $tmp .= $salt; } if ($i % 7) { $tmp .= $pass; } if ($i & 1) { $tmp .= $final; } else { $tmp .= $pass; } $final = md5 ($tmp); } # done # now format the output sting ("hash") my $hash_buf; $hash = to64 ((ord (substr ($final, 0, 1)) << 16) | (ord (substr ($final, 6, 1)) << 8) | (ord (substr ($final, 12, 1))), 4); $hash .= to64 ((ord (substr ($final, 1, 1)) << 16) | (ord (substr ($final, 7, 1)) << 8) | (ord (substr ($final, 13, 1))), 4); $hash .= to64 ((ord (substr ($final, 2, 1)) << 16) | (ord (substr ($final, 8, 1)) << 8) | (ord (substr ($final, 14, 1))), 4); $hash .= to64 ((ord (substr ($final, 3, 1)) << 16) | (ord (substr ($final, 9, 1)) << 8) | (ord (substr ($final, 15, 1))), 4); $hash .= to64 ((ord (substr ($final, 4, 1)) << 16) | (ord (substr ($final, 10, 1)) << 8) | (ord (substr ($final, 5, 1))), 4); $hash .= to64 (ord (substr ($final, 11, 1)), 2); if ($iter == 1000) # default { $hash_buf = sprintf ("%s%s\$%s", $magic , $salt , $hash); } else { $hash_buf = sprintf ("%srounds=%i\$%s\$%s", $magic, $iter, $salt , $hash); } return $hash_buf; } sub sha512_crypt { my $iter = shift; my $pass = shift; my $salt = shift; my $hash = ""; # hash to be returned by this function my $final = sha512 ($pass . $salt . $pass); $salt = substr ($salt, 0, 16); my $tmp = $pass . $salt; my $pass_len = length ($pass); my $salt_len = length ($salt); my $i; for ($i = $pass_len; $i > 0; $i -= 16) { my $len = 16; if ($i < $len) { $len = $i; } $tmp .= substr ($final, 0, $len); } $i = $pass_len; while ($i > 0) { if ($i & 1) { $tmp .= $final; } else { $tmp .= $pass; } $i >>= 1; } $final = sha512 ($tmp); # p_bytes my $p_bytes = ""; for ($i = 0; $i < $pass_len; $i++) { $p_bytes .= $pass; } $p_bytes = sha512 ($p_bytes); $p_bytes = substr ($p_bytes, 0, $pass_len); # s_bytes my $final_first_byte = ord (substr ($final, 0, 1)); my $s_bytes = ""; for ($i = 0; $i < (16 + $final_first_byte); $i++) { $s_bytes .= $salt; } $s_bytes = sha512 ($s_bytes); $s_bytes = substr ($s_bytes, 0, $salt_len); for ($i = 0; $i < $iter; $i++) { $tmp = ""; if ($i & 1) { $tmp .= $p_bytes; } else { $tmp .= $final; } if ($i % 3) { $tmp .= $s_bytes; } if ($i % 7) { $tmp .= $p_bytes; } if ($i & 1) { $tmp .= $final; } else { $tmp .= $p_bytes; } $final = sha512 ($tmp); } # done # now format the output string ("hash") my $hash_buf; $hash .= to64 ((ord (substr ($final, 0, 1)) << 16) | (ord (substr ($final, 21, 1)) << 8) | (ord (substr ($final, 42, 1))), 4); $hash .= to64 ((ord (substr ($final, 22, 1)) << 16) | (ord (substr ($final, 43, 1)) << 8) | (ord (substr ($final, 1, 1))), 4); $hash .= to64 ((ord (substr ($final, 44, 1)) << 16) | (ord (substr ($final, 2, 1)) << 8) | (ord (substr ($final, 23, 1))), 4); $hash .= to64 ((ord (substr ($final, 3, 1)) << 16) | (ord (substr ($final, 24, 1)) << 8) | (ord (substr ($final, 45, 1))), 4); $hash .= to64 ((ord (substr ($final, 25, 1)) << 16) | (ord (substr ($final, 46, 1)) << 8) | (ord (substr ($final, 4, 1))), 4); $hash .= to64 ((ord (substr ($final, 47, 1)) << 16) | (ord (substr ($final, 5, 1)) << 8) | (ord (substr ($final, 26, 1))), 4); $hash .= to64 ((ord (substr ($final, 6, 1)) << 16) | (ord (substr ($final, 27, 1)) << 8) | (ord (substr ($final, 48, 1))), 4); $hash .= to64 ((ord (substr ($final, 28, 1)) << 16) | (ord (substr ($final, 49, 1)) << 8) | (ord (substr ($final, 7, 1))), 4); $hash .= to64 ((ord (substr ($final, 50, 1)) << 16) | (ord (substr ($final, 8, 1)) << 8) | (ord (substr ($final, 29, 1))), 4); $hash .= to64 ((ord (substr ($final, 9, 1)) << 16) | (ord (substr ($final, 30, 1)) << 8) | (ord (substr ($final, 51, 1))), 4); $hash .= to64 ((ord (substr ($final, 31, 1)) << 16) | (ord (substr ($final, 52, 1)) << 8) | (ord (substr ($final, 10, 1))), 4); $hash .= to64 ((ord (substr ($final, 53, 1)) << 16) | (ord (substr ($final, 11, 1)) << 8) | (ord (substr ($final, 32, 1))), 4); $hash .= to64 ((ord (substr ($final, 12, 1)) << 16) | (ord (substr ($final, 33, 1)) << 8) | (ord (substr ($final, 54, 1))), 4); $hash .= to64 ((ord (substr ($final, 34, 1)) << 16) | (ord (substr ($final, 55, 1)) << 8) | (ord (substr ($final, 13, 1))), 4); $hash .= to64 ((ord (substr ($final, 56, 1)) << 16) | (ord (substr ($final, 14, 1)) << 8) | (ord (substr ($final, 35, 1))), 4); $hash .= to64 ((ord (substr ($final, 15, 1)) << 16) | (ord (substr ($final, 36, 1)) << 8) | (ord (substr ($final, 57, 1))), 4); $hash .= to64 ((ord (substr ($final, 37, 1)) << 16) | (ord (substr ($final, 58, 1)) << 8) | (ord (substr ($final, 16, 1))), 4); $hash .= to64 ((ord (substr ($final, 59, 1)) << 16) | (ord (substr ($final, 17, 1)) << 8) | (ord (substr ($final, 38, 1))), 4); $hash .= to64 ((ord (substr ($final, 18, 1)) << 16) | (ord (substr ($final, 39, 1)) << 8) | (ord (substr ($final, 60, 1))), 4); $hash .= to64 ((ord (substr ($final, 40, 1)) << 16) | (ord (substr ($final, 61, 1)) << 8) | (ord (substr ($final, 19, 1))), 4); $hash .= to64 ((ord (substr ($final, 62, 1)) << 16) | (ord (substr ($final, 20, 1)) << 8) | (ord (substr ($final, 41, 1))), 4); $hash .= to64 (ord (substr ($final, 63, 1)), 2); my $magic = '$6$'; if ($iter == 5000) # default { $hash_buf = sprintf ("%s%s\$%s", $magic, $salt , $hash); } else { $hash_buf = sprintf ("%srounds=%i\$%s\$%s", $magic, $iter, $salt , $hash); } return $hash_buf; } sub sha256_crypt { my $iter = shift; my $pass = shift; my $salt = shift; my $hash = ""; # hash to be returned by this function my $final = sha256 ($pass . $salt . $pass); $salt = substr ($salt, 0, 16); my $tmp = $pass . $salt; my $pass_len = length ($pass); my $salt_len = length ($salt); my $i; for ($i = $pass_len; $i > 0; $i -= 16) { my $len = 16; if ($i < $len) { $len = $i; } $tmp .= substr ($final, 0, $len); } $i = $pass_len; while ($i > 0) { if ($i & 1) { $tmp .= $final; } else { $tmp .= $pass; } $i >>= 1; } $final = sha256 ($tmp); # p_bytes my $p_bytes = ""; for ($i = 0; $i < $pass_len; $i++) { $p_bytes .= $pass; } $p_bytes = sha256 ($p_bytes); $p_bytes = substr ($p_bytes, 0, $pass_len); # s_bytes my $final_first_byte = ord (substr ($final, 0, 1)); my $s_bytes = ""; for ($i = 0; $i < (16 + $final_first_byte); $i++) { $s_bytes .= $salt; } $s_bytes = sha256 ($s_bytes); $s_bytes = substr ($s_bytes, 0, $salt_len); for ($i = 0; $i < $iter; $i++) { $tmp = ""; if ($i & 1) { $tmp .= $p_bytes; } else { $tmp .= $final; } if ($i % 3) { $tmp .= $s_bytes; } if ($i % 7) { $tmp .= $p_bytes; } if ($i & 1) { $tmp .= $final; } else { $tmp .= $p_bytes; } $final = sha256 ($tmp); } # done # now format the output string ("hash") my $hash_buf; $hash .= to64 ((ord (substr ($final, 0, 1)) << 16) | (ord (substr ($final, 10, 1)) << 8) | (ord (substr ($final, 20, 1))), 4); $hash .= to64 ((ord (substr ($final, 21, 1)) << 16) | (ord (substr ($final, 1, 1)) << 8) | (ord (substr ($final, 11, 1))), 4); $hash .= to64 ((ord (substr ($final, 12, 1)) << 16) | (ord (substr ($final, 22, 1)) << 8) | (ord (substr ($final, 2, 1))), 4); $hash .= to64 ((ord (substr ($final, 3, 1)) << 16) | (ord (substr ($final, 13, 1)) << 8) | (ord (substr ($final, 23, 1))), 4); $hash .= to64 ((ord (substr ($final, 24, 1)) << 16) | (ord (substr ($final, 4, 1)) << 8) | (ord (substr ($final, 14, 1))), 4); $hash .= to64 ((ord (substr ($final, 15, 1)) << 16) | (ord (substr ($final, 25, 1)) << 8) | (ord (substr ($final, 5, 1))), 4); $hash .= to64 ((ord (substr ($final, 6, 1)) << 16) | (ord (substr ($final, 16, 1)) << 8) | (ord (substr ($final, 26, 1))), 4); $hash .= to64 ((ord (substr ($final, 27, 1)) << 16) | (ord (substr ($final, 7, 1)) << 8) | (ord (substr ($final, 17, 1))), 4); $hash .= to64 ((ord (substr ($final, 18, 1)) << 16) | (ord (substr ($final, 28, 1)) << 8) | (ord (substr ($final, 8, 1))), 4); $hash .= to64 ((ord (substr ($final, 9, 1)) << 16) | (ord (substr ($final, 19, 1)) << 8) | (ord (substr ($final, 29, 1))), 4); $hash .= to64 ((ord (substr ($final, 31, 1)) << 8) | (ord (substr ($final, 30, 1))), 3); my $magic = '$5$'; if ($iter == 5000) # default { $hash_buf = sprintf ("%s%s\$%s", $magic, $salt , $hash); } else { $hash_buf = sprintf ("%srounds=%i\$%s\$%s", $magic, $iter, $salt , $hash); } return $hash_buf; } sub aix_ssha256_pbkdf2 { my $word_buf = shift; my $salt_buf = shift; my $iterations = shift; my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 256); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, output_len => 32 ); my $hash_buf = $pbkdf2->PBKDF2 ($salt_buf, $word_buf); my $tmp_hash = ""; $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 0, 1))) << 16) | (int (ord (substr ($hash_buf, 1, 1))) << 8) | (int (ord (substr ($hash_buf, 2, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 3, 1))) << 16) | (int (ord (substr ($hash_buf, 4, 1))) << 8) | (int (ord (substr ($hash_buf, 5, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 6, 1))) << 16) | (int (ord (substr ($hash_buf, 7, 1))) << 8) | (int (ord (substr ($hash_buf, 8, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 9, 1))) << 16) | (int (ord (substr ($hash_buf, 10, 1))) << 8) | (int (ord (substr ($hash_buf, 11, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 12, 1))) << 16) | (int (ord (substr ($hash_buf, 13, 1))) << 8) | (int (ord (substr ($hash_buf, 14, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 15, 1))) << 16) | (int (ord (substr ($hash_buf, 16, 1))) << 8) | (int (ord (substr ($hash_buf, 17, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 18, 1))) << 16) | (int (ord (substr ($hash_buf, 19, 1))) << 8) | (int (ord (substr ($hash_buf, 20, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 21, 1))) << 16) | (int (ord (substr ($hash_buf, 22, 1))) << 8) | (int (ord (substr ($hash_buf, 23, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 24, 1))) << 16) | (int (ord (substr ($hash_buf, 25, 1))) << 8) | (int (ord (substr ($hash_buf, 26, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 27, 1))) << 16) | (int (ord (substr ($hash_buf, 28, 1))) << 8) | (int (ord (substr ($hash_buf, 29, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 30, 1))) << 16) | (int (ord (substr ($hash_buf, 31, 1))) << 8) , 3); return $tmp_hash; } sub aix_ssha512_pbkdf2 { my $word_buf = shift; my $salt_buf = shift; my $iterations = shift; my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA2', 512); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, ); my $hash_buf = $pbkdf2->PBKDF2 ($salt_buf, $word_buf); my $tmp_hash = ""; $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 0, 1))) << 16) | (int (ord (substr ($hash_buf, 1, 1))) << 8) | (int (ord (substr ($hash_buf, 2, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 3, 1))) << 16) | (int (ord (substr ($hash_buf, 4, 1))) << 8) | (int (ord (substr ($hash_buf, 5, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 6, 1))) << 16) | (int (ord (substr ($hash_buf, 7, 1))) << 8) | (int (ord (substr ($hash_buf, 8, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 9, 1))) << 16) | (int (ord (substr ($hash_buf, 10, 1))) << 8) | (int (ord (substr ($hash_buf, 11, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 12, 1))) << 16) | (int (ord (substr ($hash_buf, 13, 1))) << 8) | (int (ord (substr ($hash_buf, 14, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 15, 1))) << 16) | (int (ord (substr ($hash_buf, 16, 1))) << 8) | (int (ord (substr ($hash_buf, 17, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 18, 1))) << 16) | (int (ord (substr ($hash_buf, 19, 1))) << 8) | (int (ord (substr ($hash_buf, 20, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 21, 1))) << 16) | (int (ord (substr ($hash_buf, 22, 1))) << 8) | (int (ord (substr ($hash_buf, 23, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 24, 1))) << 16) | (int (ord (substr ($hash_buf, 25, 1))) << 8) | (int (ord (substr ($hash_buf, 26, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 27, 1))) << 16) | (int (ord (substr ($hash_buf, 28, 1))) << 8) | (int (ord (substr ($hash_buf, 29, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 30, 1))) << 16) | (int (ord (substr ($hash_buf, 31, 1))) << 8) | (int (ord (substr ($hash_buf, 32, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 33, 1))) << 16) | (int (ord (substr ($hash_buf, 34, 1))) << 8) | (int (ord (substr ($hash_buf, 35, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 36, 1))) << 16) | (int (ord (substr ($hash_buf, 37, 1))) << 8) | (int (ord (substr ($hash_buf, 38, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 39, 1))) << 16) | (int (ord (substr ($hash_buf, 40, 1))) << 8) | (int (ord (substr ($hash_buf, 41, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 42, 1))) << 16) | (int (ord (substr ($hash_buf, 43, 1))) << 8) | (int (ord (substr ($hash_buf, 44, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 45, 1))) << 16) | (int (ord (substr ($hash_buf, 46, 1))) << 8) | (int (ord (substr ($hash_buf, 47, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 48, 1))) << 16) | (int (ord (substr ($hash_buf, 49, 1))) << 8) | (int (ord (substr ($hash_buf, 50, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 51, 1))) << 16) | (int (ord (substr ($hash_buf, 52, 1))) << 8) | (int (ord (substr ($hash_buf, 53, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 54, 1))) << 16) | (int (ord (substr ($hash_buf, 55, 1))) << 8) | (int (ord (substr ($hash_buf, 56, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 57, 1))) << 16) | (int (ord (substr ($hash_buf, 58, 1))) << 8) | (int (ord (substr ($hash_buf, 59, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 60, 1))) << 16) | (int (ord (substr ($hash_buf, 61, 1))) << 8) | (int (ord (substr ($hash_buf, 62, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 63, 1))) << 16) , 2); return $tmp_hash; } sub aix_ssha1_pbkdf2 { my $word_buf = shift; my $salt_buf = shift; my $iterations = shift; my $hasher = Crypt::PBKDF2->hasher_from_algorithm ('HMACSHA1'); my $pbkdf2 = Crypt::PBKDF2->new ( hasher => $hasher, iterations => $iterations, ); my $hash_buf = $pbkdf2->PBKDF2 ($salt_buf, $word_buf); my $tmp_hash = ""; $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 0, 1))) << 16) | (int (ord (substr ($hash_buf, 1, 1))) << 8) | (int (ord (substr ($hash_buf, 2, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 3, 1))) << 16) | (int (ord (substr ($hash_buf, 4, 1))) << 8) | (int (ord (substr ($hash_buf, 5, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 6, 1))) << 16) | (int (ord (substr ($hash_buf, 7, 1))) << 8) | (int (ord (substr ($hash_buf, 8, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 9, 1))) << 16) | (int (ord (substr ($hash_buf, 10, 1))) << 8) | (int (ord (substr ($hash_buf, 11, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 12, 1))) << 16) | (int (ord (substr ($hash_buf, 13, 1))) << 8) | (int (ord (substr ($hash_buf, 14, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 15, 1))) << 16) | (int (ord (substr ($hash_buf, 16, 1))) << 8) | (int (ord (substr ($hash_buf, 17, 1)))), 4); $tmp_hash .= to64 ((int (ord (substr ($hash_buf, 18, 1))) << 16) | (int (ord (substr ($hash_buf, 19, 1))) << 8) , 3); return $tmp_hash; } sub sapb_transcode { my $data_s = shift; my @data = split "", $data_s; my $transTable_s = "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\x3f\x40\x41\x50\x43\x44\x45\x4b\x47\x48\x4d\x4e\x54\x51\x53\x46" . "\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x56\x55\x5c\x49\x5d\x4a" . "\x42\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" . "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x58\x5b\x59\xff\x52" . "\x4c\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f" . "\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x57\x5e\x5a\x4f\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff" . "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"; my @transTable = unpack ("C256", $transTable_s); my @out; for (my $i = 0; $i < scalar @data; $i++) { $out[$i] = $transTable[int (ord ($data[$i]))]; } return pack ("C*", @out); } sub sapb_waldorf { my $digest_s = shift; my $w_s = shift; my $s_s = shift; my @w = unpack "C*", $w_s; my @s = unpack "C*", $s_s; my $bcodeTable_s = "\x14\x77\xf3\xd4\xbb\x71\x23\xd0\x03\xff\x47\x93\x55\xaa\x66\x91" . "\xf2\x88\x6b\x99\xbf\xcb\x32\x1a\x19\xd9\xa7\x82\x22\x49\xa2\x51" . "\xe2\xb7\x33\x71\x8b\x9f\x5d\x01\x44\x70\xae\x11\xef\x28\xf0\x0d"; my @bcodeTable = unpack ("C48", $bcodeTable_s); my @abcd = unpack ("C16", $digest_s); my $sum20 = ($abcd[0] & 3) + ($abcd[1] & 3) + ($abcd[2] & 3) + ($abcd[3] & 3) + ($abcd[5] & 3); $sum20 |= 0x20; my @out; for (my $i2 = 0; $i2 < $sum20; $i2++) { $out[$i2] = 0; } for (my $i1 = 0, my $i2 = 0, my $i3 = 0; $i2 < $sum20; $i2++, $i2++) { if ($i1 < length $w_s) { if ($abcd[15 - $i1] & 1) { $out[$i2] = $bcodeTable[48 - 1 - $i1]; $i2++; } $out[$i2] = $w[$i1]; $i1++; $i2++; } if ($i3 < length $s_s) { $out[$i2] = $s[$i3]; $i2++; $i3++; } $out[$i2] = $bcodeTable[$i2 - $i1 - $i3]; } return substr (pack ("C*", @out), 0, $sum20); } sub setup_des_key { my @key_56 = split (//, shift); my $key = ""; $key = $key_56[0]; $key .= chr (((ord ($key_56[0]) << 7) | (ord ($key_56[1]) >> 1)) & 255); $key .= chr (((ord ($key_56[1]) << 6) | (ord ($key_56[2]) >> 2)) & 255); $key .= chr (((ord ($key_56[2]) << 5) | (ord ($key_56[3]) >> 3)) & 255); $key .= chr (((ord ($key_56[3]) << 4) | (ord ($key_56[4]) >> 4)) & 255); $key .= chr (((ord ($key_56[4]) << 3) | (ord ($key_56[5]) >> 5)) & 255); $key .= chr (((ord ($key_56[5]) << 2) | (ord ($key_56[6]) >> 6)) & 255); $key .= chr (( ord ($key_56[6]) << 1) & 255); return $key; } sub randbytes { my $len = shift; my @arr; for (my $i = 0; $i < $len; $i++) { my $c = get_random_chr (0, 255); push (@arr, $c); } return join ("", @arr); } sub get_random_netntlmv1_salt { my $len_user = shift; my $len_domain = shift; my $char; my $type; my $user = ""; for (my $i = 0; $i < $len_user; $i++) { $type = get_random_num (1, 3); if ($type == 1) { $char = get_random_chr (0x30, 0x39); } elsif ($type == 2) { $char = get_random_chr (0x41, 0x5A); } else { $char = get_random_chr (0x61, 0x7A); } $user .= $char; } my $domain = ""; for (my $i = 0; $i < $len_domain; $i++) { $type = get_random_num (1, 3); if ($type == 1) { $char = get_random_chr (0x30, 0x39); } elsif ($type == 2) { $char = get_random_chr (0x41, 0x5A); } else { $char = get_random_chr (0x61, 0x7A); } $domain .= $char; } my $c_challenge = randbytes (8); my $s_challenge = randbytes (8); my $salt_buf = $user . "::" . $domain . ":" . unpack ("H*", $c_challenge) . unpack ("H*", $s_challenge); return $salt_buf; } sub get_random_netntlmv2_salt { my $len_user = shift; my $len_domain = shift; my $char; my $type; my $user = ""; if ($len_user + $len_domain > 27) { if ($len_user > $len_domain) { $len_user = 27 - $len_domain; } else { $len_domain = 27 - $len_user; } } for (my $i = 0; $i < $len_user; $i++) { $type = get_random_num (1, 3); if ($type == 1) { $char = get_random_chr (0x30, 0x39); } elsif ($type == 2) { $char = get_random_chr (0x41, 0x5A); } else { $char = get_random_chr (0x61, 0x7A); } $user .= $char; } my $domain = ""; for (my $i = 0; $i < $len_domain; $i++) { $type = get_random_num (1, 3); if ($type == 1) { $char = get_random_chr (0x30, 0x39); } elsif ($type == 2) { $char = get_random_chr (0x41, 0x5A); } else { $char = get_random_chr (0x61, 0x7A); } $domain .= $char; } my $c_challenge = randbytes (8); my $s_challenge = randbytes (8); my $temp = "\x01\x01" . "\x00" x 6 . randbytes (8) . $c_challenge . "\x00" x 4 . randbytes (20 * rand () + 1) . "\x00"; my $salt_buf = $user . "::" . $domain . ":" . unpack ("H*", $s_challenge) . unpack ("H*", $temp); return $salt_buf; } sub get_random_ike_salt { my $nr_buf = ""; for (my $i = 0; $i < 40; $i++) { $nr_buf .= get_random_chr (0, 0xff); } my $msg_buf = ""; for (my $i = 0; $i < 440; $i++) { $msg_buf .= get_random_chr (0, 0xff); } my $nr_buf_hex = unpack ("H*", $nr_buf); my $msg_buf_hex = unpack ("H*", $msg_buf); my $salt_buf = sprintf ("%s:%s:%s:%s:%s:%s:%s:%s", substr ($msg_buf_hex, 0, 256), substr ($msg_buf_hex, 256, 256), substr ($msg_buf_hex, 512, 16), substr ($msg_buf_hex, 528, 16), substr ($msg_buf_hex, 544, 320), substr ($msg_buf_hex, 864, 16), substr ($nr_buf_hex, 0, 40), substr ($nr_buf_hex, 40, 40)); return $salt_buf; } sub get_random_agilekeychain_salt { my $salt_buf = ""; for (my $i = 0; $i < 8; $i++) { $salt_buf .= get_random_chr (0x0, 0xff); } my $iv = ""; for (my $i = 0; $i < 16; $i++) { $iv .= get_random_chr (0x0, 0xff); } my $prefix = "\x00" x 1008; my $ret = unpack ("H*", $salt_buf . $prefix . $iv); return $ret; } sub get_random_cloudkeychain_salt { my $salt_buf = ""; for (my $i = 0; $i < 16; $i++) { $salt_buf .= get_random_chr (0x0, 0xff); } for (my $i = 0; $i < 304; $i++) { $salt_buf .= get_random_chr (0x0, 0xff); } my $ret = unpack ("H*", $salt_buf); return $ret; } sub get_random_kerberos5_salt { my $custom_salt = shift; my $clear_data = randbytes (14) . strftime ("%Y%m%d%H%M%S", localtime) . randbytes (8); my $user = "user"; my $realm = "realm"; my $salt = "salt"; my $salt_buf = $user . "\$" . $realm . "\$" . $salt . "\$" . unpack ("H*", $custom_salt) . "\$" . unpack ("H*", $clear_data) . "\$"; return $salt_buf; } sub get_random_kerberos5_tgs_salt { my $nonce = randbytes (8); my $user = "user"; my $realm = "realm"; my $spn = "test/spn"; my $salt_buf = $user . "\$" . $realm . "\$" . $spn . "\$" . unpack ("H*", $nonce); return $salt_buf; } sub get_random_kerberos5_as_rep_salt { my $nonce = randbytes (8); my $user_principal_name = "user\@domain.com"; my $salt_buf = $user_principal_name . ":" . unpack ("H*", $nonce); return $salt_buf; } sub get_random_axcrypt_salt { my $mysalt = randbytes (16); $mysalt = unpack ("H*", $mysalt); my $iteration = get_random_num (6, 100000); my $salt_buf = $iteration . '*' . $mysalt; return $salt_buf; } sub get_random_keepass_salt { my $version = get_random_num (1, 3); my $algorithm; my $iteration; my $final_random_seed; if ($version == 1) { $algorithm = get_random_num (0, 2); $iteration = get_random_num (50000, 100000); $final_random_seed = randbytes (16); $final_random_seed = unpack ("H*", $final_random_seed); } elsif ($version == 2) { $algorithm = 0; $iteration = get_random_num (6000, 100000); $final_random_seed = randbytes (32); $final_random_seed = unpack ("H*", $final_random_seed); } my $transf_random_seed = randbytes (32); $transf_random_seed = unpack ("H*", $transf_random_seed); my $enc_iv = randbytes (16); $enc_iv = unpack ("H*", $enc_iv); my $contents_hash = randbytes (32); $contents_hash = unpack ("H*", $contents_hash); my $inline_flag = 1; my $contents_len = get_random_num (128, 500); my $contents = randbytes ($contents_len); $contents_len += 16 - $contents_len % 16; $contents = unpack ("H*", $contents); my $salt_buf; my $is_keyfile = get_random_num (0, 2); my $keyfile_attributes = ""; if ($is_keyfile == 1) { $keyfile_attributes = $keyfile_attributes . "1*64*" . unpack ("H*", randbytes (32)); } if ($version == 1) { $salt_buf = $version . '*' . $iteration . '*' . $algorithm . '*' . $final_random_seed . '*' . $transf_random_seed . '*' . $enc_iv . '*' . $contents_hash . '*' . $inline_flag . '*' . $contents_len . '*' . $contents . '*' . $keyfile_attributes; } elsif ($version == 2) { $contents = randbytes (32); $contents = unpack ("H*", $contents); $salt_buf = $version . '*' . $iteration . '*' . $algorithm . '*' . $final_random_seed . '*' . $transf_random_seed . '*' . $enc_iv . '*' . $contents_hash . '*' . $contents . '*' . $keyfile_attributes; } return $salt_buf; } sub get_pstoken_salt { my $pstoken_length = get_random_num (16, 256); ## not a valid pstoken but a better test ## because of random length my $pstoken_const = randbytes ($pstoken_length); return unpack ("H*", $pstoken_const); } sub get_random_md5chap_salt { my $salt_buf = shift; my $salt = unpack ("H*", $salt_buf); $salt .= ":"; $salt .= unpack ("H*", randbytes (1)); return $salt; } sub get_random_dnssec_salt { my $salt_buf = ""; $salt_buf .= "."; for (my $i = 0; $i < 8; $i++) { $salt_buf .= get_random_chr (0x61, 0x7a); } $salt_buf .= ".net"; $salt_buf .= ":"; for (my $i = 0; $i < 8; $i++) { $salt_buf .= get_random_chr (0x30, 0x39); } return $salt_buf; } sub get_random_dpapimk_salt { my $salt_buf = ""; my $version = shift; my $context = get_random_num (1, 3); my $cipher_algo = ""; my $hash_algo = ""; my $iterations; my $SID = sprintf ('S-15-21-%d-%d-%d-%d', get_random_num (400000000,490000000), get_random_num (400000000,490000000), get_random_num (400000000,490000000), get_random_num (1000,1999)); my $cipher_len = 0; if ($version == 1) { $iterations = get_random_num (4000, 24000); $cipher_algo = "des3"; $hash_algo = "sha1"; $cipher_len = 208; } elsif ($version == 2) { $iterations = get_random_num (8000, 17000); $cipher_algo = "aes256"; $hash_algo = "sha512"; $cipher_len = 288; } my $iv = randbytes (16); $iv = unpack ("H*", $iv); $salt_buf = $version . '*' . $context . '*' . $SID . '*' . $cipher_algo . '*' . $hash_algo . '*' . $iterations . '*' . $iv . '*' . $cipher_len . '*'; return $salt_buf; } sub get_random_jwt_salt { my @hashes = ( "HS256", #"HS384", #this is support in hashcat, but commented out here to prevent mixed hash output files in single mode #"HS512", #this is support in hashcat, but commented out here to prevent mixed hash output files in single mode #"RS256", #not supported by hashcat #"RS384", #"RS512", #"PS256", #"PS384", #"PS512", #"ES256", #"ES384", #"ES512", ); my $rnd = get_random_num (0, scalar @hashes); my $hash = $hashes[$rnd]; my $header = { "alg" => $hash }; my $random_key = get_random_num (1, 100000000); my $random_val = get_random_num (1, 100000000); my $payload = { $random_key => $random_val }; my $header_json = encode_json ($header); my $payload_json = encode_json ($payload); my $header_base64 = encode_base64url ($header_json, ""); my $payload_base64 = encode_base64url ($payload_json, ""); return $header_base64 . "." . $payload_base64; } sub md5bit { my $digest = shift; my $bit = shift; $bit %= 128; my $byte_off = int ($bit / 8); my $bit_off = int ($bit % 8); my $char = substr ($digest, $byte_off, 1); my $num = ord ($char); return (($num & (1 << $bit_off)) ? 1 : 0); } sub sun_md5 { my $pw = shift; my $salt = shift; my $iter = shift; my $constant_phrase = "To be, or not to be,--that is the question:--\n" . "Whether 'tis nobler in the mind to suffer\n" . "The slings and arrows of outrageous fortune\n" . "Or to take arms against a sea of troubles,\n" . "And by opposing end them?--To die,--to sleep,--\n" . "No more; and by a sleep to say we end\n" . "The heartache, and the thousand natural shocks\n" . "That flesh is heir to,--'tis a consummation\n" . "Devoutly to be wish'd. To die,--to sleep;--\n" . "To sleep! perchance to dream:--ay, there's the rub;\n" . "For in that sleep of death what dreams may come,\n" . "When we have shuffled off this mortal coil,\n" . "Must give us pause: there's the respect\n" . "That makes calamity of so long life;\n" . "For who would bear the whips and scorns of time,\n" . "The oppressor's wrong, the proud man's contumely,\n" . "The pangs of despis'd love, the law's delay,\n" . "The insolence of office, and the spurns\n" . "That patient merit of the unworthy takes,\n" . "When he himself might his quietus make\n" . "With a bare bodkin? who would these fardels bear,\n" . "To grunt and sweat under a weary life,\n" . "But that the dread of something after death,--\n" . "The undiscover'd country, from whose bourn\n" . "No traveller returns,--puzzles the will,\n" . "And makes us rather bear those ills we have\n" . "Than fly to others that we know not of?\n" . "Thus conscience does make cowards of us all;\n" . "And thus the native hue of resolution\n" . "Is sicklied o'er with the pale cast of thought;\n" . "And enterprises of great pith and moment,\n" . "With this regard, their currents turn awry,\n" . "And lose the name of action.--Soft you now!\n" . "The fair Ophelia!--Nymph, in thy orisons\n" . "Be all my sins remember'd.\n\x00"; my $constant_len = length ($constant_phrase); my $hash_buf = md5 ($pw . $salt); my $W; my $to_hash; for (my $round = 0; $round < $iter; $round++) { my $shift_a = md5bit ($hash_buf, $round + 0); my $shift_b = md5bit ($hash_buf, $round + 64); my @shift_4; my @shift_7; for (my $k = 0; $k < 16; $k++) { my $s7shift = ord (substr ($hash_buf, $k, 1)) % 8; my $l = ($k + 3) % 16; my $num = ord (substr ($hash_buf, $l, 1)); $shift_4[$k] = $num % 5; $shift_7[$k] = ($num >> $s7shift) & 1; } my @indirect_4; for (my $k = 0; $k < 16; $k++) { $indirect_4[$k] = (ord (substr ($hash_buf, $k, 1)) >> $shift_4[$k]) & 0xf; } my @indirect_7; for (my $k = 0; $k < 16; $k++) { $indirect_7[$k] = (ord (substr ($hash_buf, $indirect_4[$k], 1)) >> $shift_7[$k]) & 0x7f; } my $indirect_a = 0; my $indirect_b = 0; for (my $k = 0; $k < 8; $k++) { $indirect_a |= md5bit ($hash_buf, $indirect_7[$k + 0]) << $k; $indirect_b |= md5bit ($hash_buf, $indirect_7[$k + 8]) << $k; } $indirect_a = ($indirect_a >> $shift_a) & 0x7f; $indirect_b = ($indirect_b >> $shift_b) & 0x7f; my $bit_a = md5bit ($hash_buf, $indirect_a); my $bit_b = md5bit ($hash_buf, $indirect_b); $W = $hash_buf; my $pos = 16; my $total = $pos; $to_hash = ""; if ($bit_a ^ $bit_b) { substr ($W, 16, 48) = substr ($constant_phrase, 0, 48); $total += 48; $to_hash .= substr ($W, 0, 64); my $constant_off; for ($constant_off = 48; $constant_off < $constant_len - 64; $constant_off += 64) { substr ($W, 0, 64) = substr ($constant_phrase, $constant_off, 64); $total += 64; $to_hash .= substr ($W, 0, 64); } $pos = $constant_len - $constant_off; $total += $pos; substr ($W, 0, $pos) = substr ($constant_phrase, $constant_off, $pos); } my $a_len = 0; my @a_buf; $a_buf[0] = 0; $a_buf[1] = 0; $a_buf[2] = 0; $a_buf[3] = 0; my $tmp = $round; do { my $round_div = int ($tmp / 10); my $round_mod = int ($tmp % 10); $tmp = $round_div; $a_buf[int ($a_len / 4)] = (($round_mod + 0x30) | ($a_buf[int ($a_len / 4)] << 8)); $a_len++; } while ($tmp); my $tmp_str = ""; my $g; for ($g = 0; $g < $a_len; $g++) { my $remainder = $a_buf[$g]; my $factor = 7; my $started = 1; my $sub; while ($remainder > 0) { $sub = $remainder >> (8 * $factor); if ($started != 1 || $sub > 0) { $started = 0; $tmp_str = chr ($sub) . $tmp_str; $remainder -= ($sub << (8 * $factor)); } $factor--; } } substr ($W, $pos, $a_len) = $tmp_str; $pos += $a_len; $total += $a_len; $to_hash .= substr ($W, 0, $pos); $to_hash = substr ($to_hash, 0, $total); $hash_buf = md5 ($to_hash); } my $passwd = ""; $passwd .= to64 ((int (ord (substr ($hash_buf, 0, 1))) << 16) | (int (ord (substr ($hash_buf, 6, 1))) << 8) | (int (ord (substr ($hash_buf, 12, 1)))), 4); $passwd .= to64 ((int (ord (substr ($hash_buf, 1, 1))) << 16) | (int (ord (substr ($hash_buf, 7, 1))) << 8) | (int (ord (substr ($hash_buf, 13, 1)))), 4); $passwd .= to64 ((int (ord (substr ($hash_buf, 2, 1))) << 16) | (int (ord (substr ($hash_buf, 8, 1))) << 8) | (int (ord (substr ($hash_buf, 14, 1)))), 4); $passwd .= to64 ((int (ord (substr ($hash_buf, 3, 1))) << 16) | (int (ord (substr ($hash_buf, 9, 1))) << 8) | (int (ord (substr ($hash_buf, 15, 1)))), 4); $passwd .= to64 ((int (ord (substr ($hash_buf, 4, 1))) << 16) | (int (ord (substr ($hash_buf, 10, 1))) << 8) | (int (ord (substr ($hash_buf, 5, 1)))), 4); $passwd .= to64 ((int (ord (substr ($hash_buf, 11, 1)))), 2); return $passwd; } sub usage_die { die ("usage: $0 single|passthrough| [mode] [len]\n" . " or\n" . " $0 verify [mode] [hashfile] [cracks] [outfile]\n"); } sub pad16 { my $block_ref = shift; my $offset = shift; my $value = 16 - $offset; for (my $i = $offset; $i < 16; $i++) { push @{$block_ref}, $value; } } sub lotus_mix { my $in_ref = shift; my $p = 0; for (my $i = 0; $i < 18; $i++) { for (my $j = 0; $j < 48; $j++) { $p = ($p + 48 - $j) & 0xff; my $c = $LOTUS_MAGIC_TABLE->[$p]; $p = $in_ref->[$j] ^ $c; $in_ref->[$j] = $p; } } } sub lotus_transform_password { my $in_ref = shift; my $out_ref = shift; my $t = $out_ref->[15]; for (my $i = 0; $i < 16; $i++) { $t ^= $in_ref->[$i]; my $c = $LOTUS_MAGIC_TABLE->[$t]; $out_ref->[$i] ^= $c; $t = $out_ref->[$i]; } } sub mdtransform_norecalc { my $state_ref = shift; my $block_ref = shift; my @x; push (@x, @{$state_ref}); push (@x, @{$block_ref}); for (my $i = 0; $i < 16; $i++) { push (@x, $x[0 + $i] ^ $x[16 + $i]); } lotus_mix (\@x); for (my $i = 0; $i < 16; $i++) { $state_ref->[$i] = $x[$i]; } } sub mdtransform { my $state_ref = shift; my $checksum_ref = shift; my $block_ref = shift; mdtransform_norecalc ($state_ref, $block_ref); lotus_transform_password ($block_ref, $checksum_ref); } sub domino_big_md { my $saved_key_ref = shift; my $size = shift; @{$saved_key_ref} = splice (@{$saved_key_ref}, 0, $size); my @state = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); my @checksum; my $curpos; for ($curpos = 0; $curpos + 16 < $size; $curpos += 16) { my @block = splice (@{$saved_key_ref}, 0, 16); mdtransform (\@state, \@checksum, \@block); } my $left = $size - $curpos; my @block = splice (@{$saved_key_ref}, 0, 16); pad16 (\@block, $left); mdtransform (\@state, \@checksum, \@block); mdtransform_norecalc (\@state, \@checksum); return @state; } sub pdf_compute_encryption_key { my $word_buf = shift; my $padding = shift; my $id = shift; my $u = shift; my $o = shift; my $P = shift; my $V = shift; my $R = shift; my $enc = shift; ## start my $data; $data .= $word_buf; $data .= substr ($padding, 0, 32 - length $word_buf); $data .= pack ("H*", $o); $data .= pack ("I", $P); $data .= pack ("H*", $id); if ($R >= 4) { if (!$enc) { $data .= pack ("I", -1); } } my $res = md5 ($data); if ($R >= 3) { for (my $i = 0; $i < 50; $i++) { $res = md5 ($res); } } return $res; } sub gen_random_wpa_eapol { my $keyver = shift; my $snonce = shift; my $ret = ""; # version my $version = 1; # 802.1X-2001 $ret .= pack ("C*", $version); my $type = 3; # means that this EAPOL frame is used to transfer key information $ret .= pack ("C*", $type); my $length; # length of remaining data if ($keyver == 1) { $length = 119; } else { $length = 117; } $ret .= pack ("n*", $length); my $descriptor_type; if ($keyver == 1) { $descriptor_type = 254; # EAPOL WPA key } else { $descriptor_type = 1; # EAPOL RSN key } $ret .= pack ("C*", $descriptor_type); # key_info is a bit vector: # generated from these 13 bits: encrypted key data, request, error, secure, key mic, key ack, install, key index (2), key type, key descriptor (3) my $key_info = 0; $key_info |= 1 << 8; # set key MIC $key_info |= 1 << 3; # set if it is a pairwise key if ($keyver == 1) { $key_info |= 1 << 0; # RC4 Cipher, HMAC-MD5 MIC } else { $key_info |= 1 << 1; # AES Cipher, HMAC-SHA1 MIC } $ret .= pack ("n*", $key_info); my $key_length; if ($keyver == 1) { $key_length = 32; } else { $key_length = 0; } $ret .= pack ("n*", $key_length); my $replay_counter = 1; $ret .= pack ("Q>*", $replay_counter); $ret .= $snonce; my $key_iv = "\x00" x 16; $ret .= $key_iv; my $key_rsc = "\x00" x 8; $ret .= $key_rsc; my $key_id = "\x00" x 8; $ret .= $key_id; my $key_mic = "\x00" x 16; $ret .= $key_mic; my $key_data_len; if ($keyver == 1) { $key_data_len = 24; # length of the key_data (== WPA info) } else { $key_data_len = 22; # length of the key_data (== RSN info) } $ret .= pack ("n*", $key_data_len); my $key_data = ""; if ($keyver == 1) { # wpa info my $wpa_info = ""; my $vendor_specific_data = ""; my $tag_number = 221; # means it is a vendor specific tag $vendor_specific_data .= pack ("C*", $tag_number); my $tag_len = 22; # length of the remaining "tag data" $vendor_specific_data .= pack ("C*", $tag_len); my $vendor_specific_oui = pack ("H*", "0050f2"); # microsoft $vendor_specific_data .= $vendor_specific_oui; my $vendor_specific_oui_type = 1; # WPA Information Element $vendor_specific_data .= pack ("C*", $vendor_specific_oui_type); my $vendor_specific_wpa_version = 1; $vendor_specific_data .= pack ("v*", $vendor_specific_wpa_version); # multicast my $vendor_specific_multicast_oui = pack ("H*", "0050f2"); $vendor_specific_data .= $vendor_specific_multicast_oui; my $vendor_specific_multicast_type = 2; # TKIP $vendor_specific_data .= pack ("C*", $vendor_specific_multicast_type); # unicast my $vendor_specific_unicast_count = 1; $vendor_specific_data .= pack ("v*", $vendor_specific_unicast_count); my $vendor_specific_unicast_oui = pack ("H*", "0050f2"); $vendor_specific_data .= $vendor_specific_unicast_oui; my $vendor_specific_unicast_type = 2; # TKIP $vendor_specific_data .= pack ("C*", $vendor_specific_unicast_type); # Auth Key Management (AKM) my $auth_key_management_count = 1; $vendor_specific_data .= pack ("v*", $auth_key_management_count); my $auth_key_management_oui = pack ("H*", "0050f2"); $vendor_specific_data .= $auth_key_management_oui; my $auth_key_management_type = 2; # Pre-Shared Key (PSK) $vendor_specific_data .= pack ("C*", $auth_key_management_type); $wpa_info = $vendor_specific_data; $key_data = $wpa_info; } else { # rsn info my $rsn_info = ""; my $tag_number = 48; # RSN info $rsn_info .= pack ("C*", $tag_number); my $tag_len = 20; # length of the remaining "tag_data" $rsn_info .= pack ("C*", $tag_len); my $rsn_version = 1; $rsn_info .= pack ("v*", $rsn_version); # group cipher suite my $group_cipher_suite_oui = pack ("H*", "000fac"); # Ieee8021 $rsn_info .= $group_cipher_suite_oui; my $group_cipher_suite_type = 4; # AES (CCM) $rsn_info .= pack ("C*", $group_cipher_suite_type); # pairwise cipher suite my $pairwise_cipher_suite_count = 1; $rsn_info .= pack ("v*", $pairwise_cipher_suite_count); my $pairwise_cipher_suite_oui = pack ("H*", "000fac"); # Ieee8021 $rsn_info .= $pairwise_cipher_suite_oui; my $pairwise_cipher_suite_type = 4; # AES (CCM) $rsn_info .= pack ("C*", $pairwise_cipher_suite_type); # Auth Key Management (AKM) my $auth_key_management_count = 1; $rsn_info .= pack ("v*", $auth_key_management_count); my $auth_key_management_oui = pack ("H*", "000fac"); # Ieee8021 $rsn_info .= $auth_key_management_oui; my $auth_key_management_type = 2; # Pre-Shared Key (PSK) $rsn_info .= pack ("C*", $auth_key_management_type); # RSN Capabilities # bit vector of these 9 bits: peerkey enabled, management frame protection (MFP) capable, MFP required, # RSN GTKSA Capabilities (2), RSN PTKSA Capabilities (2), no pairwise Capabilities, Pre-Auth Capabilities my $rsn_capabilities = pack ("H*", "0000"); $rsn_info .= $rsn_capabilities; $key_data = $rsn_info; } $ret .= $key_data; return $ret; } sub wpa_prf_512 { my $keyver = shift; my $pmk = shift; my $stmac = shift; my $bssid = shift; my $snonce = shift; my $anonce = shift; my $data = "Pairwise key expansion"; if (($keyver == 1) || ($keyver == 2)) { $data .= "\x00"; } # # Min(AA, SPA) || Max(AA, SPA) # # compare if greater: Min()/Max() on the MACs (6 bytes) if (memcmp ($stmac, $bssid, 6) < 0) { $data .= $stmac; $data .= $bssid; } else { $data .= $bssid; $data .= $stmac; } # # Min(ANonce,SNonce) || Max(ANonce,SNonce) # # compare if greater: Min()/Max() on the nonces (32 bytes) if (memcmp ($snonce, $anonce, 32) < 0) { $data .= $snonce; $data .= $anonce; } else { $data .= $anonce; $data .= $snonce; } my $prf_buf; if (($keyver == 1) || ($keyver == 2)) { $data .= "\x00"; $prf_buf = hmac ($data, $pmk, \&sha1); } else { my $data3 = "\x01\x00" . $data . "\x80\x01"; $prf_buf = hmac ($data3, $pmk, \&sha256); } $prf_buf = substr ($prf_buf, 0, 16); return $prf_buf; } sub itunes_aes_wrap { my $key = shift; my $A = shift; my $R_l = shift; my $k = scalar (@$R_l); my $n = $k + 1; my @R; for (my $i = 0; $i < $n; $i++) { $R[$i] = @$R_l[$i]; } # AES mode ECB my $m = Crypt::Mode::ECB->new ('AES', 0); # main wrap loop my ($i, $j, $a); for ($j = 0; $j <= 5; $j++) { for ($i = 1, $a = 0; $i <= $k; $i++, $a++) { my $input; $input = pack ("Q>", $A); $input .= pack ("Q>", $R[$a]); my $t = $m->encrypt ($input, $key); $A = unpack ("Q>", substr ($t, 0, 8)); $A ^= $k * $j + $i; $R[$a] = unpack ("Q>", substr ($t, 8, 8)); } } my $WPKY = pack ("Q>", $A); for (my $i = 0; $i < $k; $i++) { $WPKY .= pack ("Q>", $R[$i]); } return $WPKY; } sub itunes_aes_unwrap { my $key = shift; my $WPKY = shift; my @B; for (my $i = 0; $i < length ($WPKY) / 8; $i++) { $B[$i] = unpack ("Q>", substr ($WPKY, $i * 8, 8)); } my $n = scalar (@B); my $k = $n - 1; my @R; for (my $i = 0; $i < $k; $i++) { $R[$i] = $B[$i + 1]; } # AES mode ECB my $m = Crypt::Mode::ECB->new ('AES', 0); # main unwrap loop my $A = $B[0]; my ($i, $j, $a); for ($j = 5; $j >= 0; $j--) { for ($i = $k, $a = $k - 1; $i > 0; $i--, $a--) { my $input; $input = pack ("Q>", $A ^ ($k * $j + $i)); $input .= pack ("Q>", $R[$a]); my $t = $m->decrypt ($input, $key); $A = unpack ("Q>", substr ($t, 0, 8)); $R[$a] = unpack ("Q>", substr ($t, 8, 8)); } } return ($A, \@R); } sub memcmp { my $str1 = shift; my $str2 = shift; my $len = shift; my $len_str1 = length ($str1); my $len_str2 = length ($str2); if (($len > $len_str1) || ($len > $len_str2)) { print "ERROR: memcmp () lengths wrong"; exit (1); } for (my $i = 0; $i < $len; $i++) { my $c_1 = ord (substr ($str1, $i, 1)); my $c_2 = ord (substr ($str2, $i, 1)); return -1 if ($c_1 < $c_2); return 1 if ($c_1 > $c_2); } return 0; }
23.986481
413
0.500914
ed18eb946cb9b19949c8687e2aeb0cce655bd9e9
3,218
t
Perl
perl/src/lib/Module/Build/t/add_property.t
nokibsarkar/sl4a
d3c17dca978cbeee545e12ea240a9dbf2a6999e9
[ "Apache-2.0" ]
2,293
2015-01-02T12:46:10.000Z
2022-03-29T09:45:43.000Z
perl/src/lib/Module/Build/t/add_property.t
nokibsarkar/sl4a
d3c17dca978cbeee545e12ea240a9dbf2a6999e9
[ "Apache-2.0" ]
315
2015-05-31T11:55:46.000Z
2022-01-12T08:36:37.000Z
perl/src/lib/Module/Build/t/add_property.t
nokibsarkar/sl4a
d3c17dca978cbeee545e12ea240a9dbf2a6999e9
[ "Apache-2.0" ]
1,033
2015-01-04T07:48:40.000Z
2022-03-24T09:34:37.000Z
#!/usr/bin/perl -w use strict; use lib $ENV{PERL_CORE} ? '../lib/Module/Build/t/lib' : 't/lib'; use MBTest tests => 29; #use MBTest 'no_plan'; use DistGen; BEGIN { use_ok 'Module::Build' or die; } ensure_blib 'Module::Build'; my $tmp = MBTest->tmpdir; my $dist = DistGen->new( dir => $tmp ); $dist->regen; $dist->chdir_in; ADDPROP: { package My::Build::Prop; use base 'Module::Build'; __PACKAGE__->add_property( 'foo' ); __PACKAGE__->add_property( 'bar', 'howdy' ); __PACKAGE__->add_property( 'baz', default => 'howdy' ); __PACKAGE__->add_property( 'code', default => sub { 'yay' } ); __PACKAGE__->add_property( 'check', default => sub { 'howdy' }, check => sub { return 1 if $_ eq 'howdy'; shift->property_error(qq{"$_" is invalid}); return 0; }, ); __PACKAGE__->add_property( 'hash', default => { foo => 1 }, check => sub { return 1 if !defined $_ or exists $_->{foo}; shift->property_error(qq{hash is invalid}); return 0; }, ); } ok my $build = My::Build::Prop->new( 'module_name' => 'Simple', quiet => 1, ), 'Create new build object'; is $build->foo, undef, 'Property "foo" should be undef'; ok $build->foo(42), 'Set "foo"'; is $build->foo, 42, 'Now "foo" should have new value'; is $build->bar, 'howdy', 'Property "bar" should be its default'; ok $build->bar('yo'), 'Set "bar"'; is $build->bar, 'yo', 'Now "bar" should have new value'; is $build->check, 'howdy', 'Property "check" should be its default'; eval { $build->check('yo') }; ok my $err = $@, 'Should get an error for an invalid value'; like $err, qr/^ERROR: "yo" is invalid/, 'It should be the correct error'; is $build->code, 'yay', 'Property "code" should have its code value'; is_deeply $build->hash, { foo => 1 }, 'Property "hash" should be default'; is $build->hash('foo'), 1, 'Should be able to get key in hash'; ok $build->hash( bar => 3 ), 'Add a key to the hash prop'; is_deeply $build->hash, { foo => 1, bar => 3 }, 'New key should be in hash'; eval { $build->hash({ bar => 3 }) }; ok $err = $@, 'Should get exception for assigning invalid hash'; like $err, qr/^ERROR: hash is invalid/, 'It should be the correct error'; eval { $build->hash( []) }; ok $err = $@, 'Should get exception for assigning an array for a hash'; like $err, qr/^Unexpected arguments for property 'hash'/, 'It should be the proper error'; is $build->hash(undef), undef, 'Should be able to set hash to undef'; # Check core properties. is $build->installdirs, 'site', 'Property "installdirs" should be default'; ok $build->installdirs('core'), 'Set "installdirst" to "core"'; is $build->installdirs, 'core', 'Now "installdirs" should be "core"'; eval { $build->installdirs('perl') }; ok $err = $@, 'Should have caught exception setting "installdirs" to "perl"'; like $err, qr/^ERROR: Perhaps you meant installdirs to be "core" rather than "perl"\?/, 'And it should suggest "core" in the error message'; eval { $build->installdirs('foo') }; ok $err = $@, 'Should catch exception for invalid "installdirs" value'; like $err, qr/ERROR: installdirs must be one of "core", "site", or "vendor"/, 'And it should suggest the proper values in the error message';
34.234043
87
0.638906
73f7aa12d22ffe0559d03a267a3c8d0ae22cbd47
1,514
pl
Perl
script/packed-type.pl
mknob/p5-opcua-open62541
394891b5d18384c50a65f5bd6067c9665bad051a
[ "Artistic-1.0" ]
2
2020-02-11T11:08:10.000Z
2021-07-29T08:19:09.000Z
script/packed-type.pl
mknob/p5-opcua-open62541
394891b5d18384c50a65f5bd6067c9665bad051a
[ "Artistic-1.0" ]
5
2020-02-13T12:06:51.000Z
2021-08-09T18:19:00.000Z
script/packed-type.pl
mknob/p5-opcua-open62541
394891b5d18384c50a65f5bd6067c9665bad051a
[ "Artistic-1.0" ]
3
2020-02-12T15:34:48.000Z
2020-02-25T13:11:47.000Z
#!/usr/bin/perl # Generate function tables to pack and unpack based on type index. use strict; use warnings; open(my $in, '<', "Open62541-packed.xsh") or die "Open 'Open62541-packed.xsh' for reading failed: $!"; my @types = map { m{^static UA_(\w+) XS_unpack_UA_\w+} } <$in> or die "No types found"; local $\ = "\n"; open(my $out, '>', "Open62541-packed-type.xsh") or die "Open 'Open62541-packed-type.xsh' for writing failed: $!"; print $out "/* begin generated by $0 */\n"; foreach my $type (sort @types) { my $index = uc($type); print $out <<"EOF"; #ifdef UA_TYPES_$index static void pack_UA_$type(SV *sv, void *p) { UA_$type *data = p; XS_pack_UA_$type(sv, *data); } static void unpack_UA_$type(SV *sv, void *p) { UA_$type *data = p; *data = XS_unpack_UA_$type(sv); } #endif EOF } print $out "typedef void (*packed_UA)(SV *, void *);\n"; print $out "static packed_UA pack_UA_table[UA_TYPES_COUNT] = {"; foreach my $type (@types) { my $index = "UA_TYPES_". uc($type); print $out "#ifdef $index"; print $out " [$index] = pack_UA_$type,"; print $out "#endif"; } print $out "};\n"; print $out "static packed_UA unpack_UA_table[UA_TYPES_COUNT] = {"; foreach my $type (@types) { my $index = "UA_TYPES_". uc($type); print $out "#ifdef $index"; print $out " [$index] = unpack_UA_$type,"; print $out "#endif"; } print $out "};\n"; print $out "/* end generated by $0 */"; close($out) or die "Close 'Open62541-packed-type.xsh' after writing failed: $!";
25.233333
72
0.628137
73ffa4f763ccb0b9f0f3e0ce19d0ab9470a8c305
8,071
pm
Perl
original/sources/3D_Dock/scripts/PDB_Types.pm
albertsgrc/ftdock-opt
3361d1f18bf529958b78231fdcf139b1c1c1f232
[ "MIT" ]
null
null
null
original/sources/3D_Dock/scripts/PDB_Types.pm
albertsgrc/ftdock-opt
3361d1f18bf529958b78231fdcf139b1c1c1f232
[ "MIT" ]
null
null
null
original/sources/3D_Dock/scripts/PDB_Types.pm
albertsgrc/ftdock-opt
3361d1f18bf529958b78231fdcf139b1c1c1f232
[ "MIT" ]
null
null
null
# PDB utilities and data about legal names etc # Copyright (C) 1997-2000 Gidon Moont # # Biomolecular Modelling Laboratory # Imperial Cancer Research Fund # 44 Lincoln's Inn Fields # London WC2A 3PX # # +44 (0)20 7269 3348 # http://www.bmm.icnet.uk/ # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. package PDB_Types ; ############# select STDOUT ; $| = 1 ; ############# # # List of legal possible residue / base names @legal_res_names = ( 'ALA', 'ARG', 'ASN', 'ASP', 'CYS', # twenty standard amino acids 'GLN', 'GLU', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', ' A', ' C', ' G', ' T', ' U' # common nucleic acids ) ; ############# # # List of corresponding numerical codes for each residue %numerical_codes = ( 'ALA' => ' 1' , 'ARG' => ' 2' , 'ASN' => ' 3' , 'ASP' => ' 4' , 'CYS' => ' 5' , 'GLN' => ' 6' , 'GLU' => ' 7' , 'GLY' => ' 8' , 'HIS' => ' 9' , 'ILE' => '10' , 'LEU' => '11' , 'LYS' => '12' , 'MET' => '13' , 'PHE' => '14' , 'PRO' => '15' , 'SER' => '16' , 'THR' => '17' , 'TRP' => '18' , 'TYR' => '19' , 'VAL' => '20' , 'ASX' => '21' , 'GLX' => '22' , 'XXX' => ' 0' , ' A' => '41' , ' C' => '42' , ' G' => '43' , ' T' => '44' , ' U' => '45' , ) ; ############# # # List of corresponding one letter codes for each residue %one_letter_codes = ( 'ALA' => 'A' , 'ARG' => 'R' , 'ASN' => 'N' , 'ASP' => 'D' , 'CYS' => 'C' , 'GLN' => 'Q' , 'GLU' => 'E' , 'GLY' => 'G' , 'HIS' => 'H' , 'ILE' => 'I' , 'LEU' => 'L' , 'LYS' => 'K' , 'MET' => 'M' , 'PHE' => 'F' , 'PRO' => 'P' , 'SER' => 'S' , 'THR' => 'T' , 'TRP' => 'W' , 'TYR' => 'Y' , 'VAL' => 'V' , 'ASX' => 'B' , 'GLX' => 'Z' , 'XXX' => 'X' , ' A' => 'a' , ' C' => 'c' , ' G' => 'g' , ' T' => 't' , ' U' => 'u' , ) ; ############# # # List of number of (non-hydrogen) atoms expected per residue %atoms_per_residue = ( 'ALA' => ' 5' , 'ARG' => '11' , 'ASN' => ' 8' , 'ASP' => ' 8' , 'CYS' => ' 6' , 'GLN' => ' 9' , 'GLU' => ' 9' , 'GLY' => ' 4' , 'HIS' => '10' , 'ILE' => ' 8' , 'LEU' => ' 8' , 'LYS' => ' 9' , 'MET' => ' 8' , 'PHE' => '11' , 'PRO' => ' 7' , 'SER' => ' 6' , 'THR' => ' 7' , 'TRP' => '14' , 'TYR' => '12' , 'VAL' => ' 7' , 'xxx' => ' 0' , # for first test in each file 'XXX' => '50' , # for those residues I have no information on # these are patently dumby values for now... ' A' => '99' , ' C' => '99' , ' G' => '99' , ' T' => '99' , ' U' => '99' , ) ; ############# # # List of legal possible atom names @legal_atom_names = ( ' N ', ' CA ', ' C ', ' O ', # amino acid backbone ' CB ', # amino acid carbons ' CD ', ' CD1', ' CD2', ' CE ', ' CE1', ' CE2', ' CE3', ' CG ', ' CG1', ' CG2', ' CH2', ' CZ ', ' CZ2', ' CZ3', ' OD ', ' OD1', ' OD2', # amino acid oxygens ' OE1', ' OE2', ' OG ', ' OG1', ' OG2', ' OH ', ' ND1', ' ND2', # amino acid nitrogens ' NE ', ' NE1', ' NE2', ' NH1', ' NH2', ' NZ ', ' SD ', ' SG ', # amino acid sulphurs ' P ', ' O1P', ' O2P', # DNA backbone ' C1*', ' C2*', ' C3*', ' C4*', ' C5*', ' O2*', ' O3*', ' O4*', ' O5*', ' C1\'', ' C2\'', ' C3\'', ' C4\'', ' C5\'', # other version - may be wrong - but its used ' O2\'', ' O3\'', ' O4\'', ' O5\'', ' N1 ', ' N2 ', ' N3 ', ' N4 ', ' N5 ', # base nitrogens ' N6 ', ' N7 ', ' N8 ', ' N9 ', ' C2 ', ' C4 ', ' C5 ', ' C5M', # base carbons ' C6 ', ' C7 ', ' C8 ', ' O2 ', ' O4 ', ' O6 ' # base oxygens ) ; ############# # # List of corresponding numerical codes for each atom on a given residue # # taken from "Novel Knowledge-based Mean Force Potential at Atomic Level" # - Melo and Feytmans - JMB (1997) 256 , 207--222 # # not used at the moment to assign, but to check legality of atom type # for residue type @atom_type_key = ( # dud to cope with arrays starting at zero { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , } , # dud to cope with arrays starting at zero { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 6 , } , # alanine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 8 , ' CD ' => 37 , ' NE ' => 36 , ' CZ ' => 21 , ' NH1' => 22 , ' NH2' => 22 , } , # arginine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 33 , ' OD1' => 34 , ' ND2' => 18 , } , # asparagine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 27 , ' OD1' => 28 , ' OD2' => 28 , } , # aspartic acid { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 29 , ' SG ' => 19 , } , # cystine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 8 , ' CD ' => 33 , ' OE1' => 34 , ' NE2' => 18 , } , # glutamine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 8 , ' CD ' => 27 , ' OE1' => 28 , ' OE2' => 28 , } , # glutamic acid { ' N ' => 3 , ' CA ' => 2 , ' C ' => 4 , ' O ' => 5 , } , # glycine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 23 , ' CD2' => 24 , ' NE2' => 25 , ' CE1' => 26 , ' ND1' => 38 , } , # histidine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 7 , ' CG1' => 8 , ' CD1' => 6 , ' CG2' => 6 , } , # isoleucine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 7 , ' CD1' => 6 , ' CD2' => 6 , } , # leucine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 8 , ' CD ' => 8 , ' CE ' => 35 , ' NZ ' => 20 , } , # lysine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 29 , ' SD ' => 9 , ' CE ' => 30 , } , # methionine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 11 , ' CD1' => 12 , ' CD2' => 12 , ' CE1' => 12 , ' CE2' => 12 , ' CZ ' => 12 , } , # phenylalanine { ' N ' => 10 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 8 , ' CD ' => 32 , } , # proline { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 15 , ' OG ' => 16 , } , # serine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 17 , ' OG1' => 16 , ' CG2' => 6 , } , # threonine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 13 , ' CD1' => 24 , ' NE1' => 39 , ' CD2' => 11 , ' CE2' => 14 , ' CE3' => 12 , ' CZ2' => 12 , ' CZ3' => 12 , ' CH2' => 12 , } , # tryptophan { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 8 , ' CG ' => 11 , ' CD1' => 12 , ' CD2' => 12 , ' CE1' => 12 , ' CE2' => 12 , ' CZ ' => 31 , ' OH ' => 40 , } , # tyrosine { ' N ' => 3 , ' CA ' => 1 , ' C ' => 4 , ' O ' => 5 , ' CB ' => 7 , ' CG1' => 6 , ' CG2' => 6 , } , # valine ) ;
22.864023
90
0.361417
ed1d2415e58e6a0b8f28d969a1a0dee4fb6be91f
1,247
t
Perl
src/npcs/birchwell/birchwell.t
evan-erdos/if-template
049c83cb714786ba41f2b268b23fe55c3fba119a
[ "MIT" ]
null
null
null
src/npcs/birchwell/birchwell.t
evan-erdos/if-template
049c83cb714786ba41f2b268b23fe55c3fba119a
[ "MIT" ]
null
null
null
src/npcs/birchwell/birchwell.t
evan-erdos/if-template
049c83cb714786ba41f2b268b23fe55c3fba119a
[ "MIT" ]
null
null
null
#include <adv3.h> #include <en_us.h> #include "macros.h" birchwell : Person 'professor/cameron birchwell/prof/professor' 'Professor Birchwell' @observatory_atrium """ He looks thinner than he did the last time you saw him. He's scribbling away madly at his desk. """ { isProperName = true; properName = 'Professor Cameron T. Birchwell'; isHim = true; globalParamName = 'birchwell'; initSpecialDesc { isInInitState = null; """ As you enter, you notice Professor Birchwell, sitting alone at a desk. <br> You stand quietly in the doorway, he hasn't noticed you yet. """; } specialDesc { birchwell_list.doScript(); } } birchwell_list : ShuffledEventList, RandomFiringScript [''' The professor gets up from his desk, and begins to pace around. ''',''' The professor stares up towards the stars, lost in thought. ''',''' He looks back at the telescope. ''',''' He sits down at his desk, and begins to write. '''][''' The professor continues scrawling away. ''',''' The professor leans up from his work for a moment, but then continues writing. '''] eventPercent = 80; birchwell_init : PreinitObject { execute() { birchwell.setKnowsAbout(soviet_troops); } }
22.267857
78
0.676824
ed09bdfc9bf45558f61dbfcbd187ec6b609c4317
418
t
Perl
t/04_utf8.t
wu-lee/p5-cgi-emulate-psgi
ff7906d763e23eec161c24c70052891903693eea
[ "Artistic-1.0" ]
6
2015-02-28T08:34:43.000Z
2021-03-24T16:34:16.000Z
t/04_utf8.t
wu-lee/p5-cgi-emulate-psgi
ff7906d763e23eec161c24c70052891903693eea
[ "Artistic-1.0" ]
4
2016-02-16T15:14:46.000Z
2017-05-04T22:07:25.000Z
t/04_utf8.t
wu-lee/p5-cgi-emulate-psgi
ff7906d763e23eec161c24c70052891903693eea
[ "Artistic-1.0" ]
4
2015-07-21T15:08:35.000Z
2018-01-14T06:39:21.000Z
use strict; use warnings; use CGI; use CGI::Emulate::PSGI; use Test::More; my $app = CGI::Emulate::PSGI->handler( sub { binmode STDOUT, ":utf8"; print "Content-Type: text/html\r\n\r\n"; print chr(4242); }, ); my $res = $app->({ REQUEST_METHOD => 'GET', 'psgi.input' => \*STDIN, 'psgi.errors' => \*STDERR }); is $res->[0], 200; is_deeply $res->[2], [ "\xe1\x82\x92" ]; done_testing;
19.904762
98
0.569378
ed01f90bc83cd1c85ec36fddfc64637b9f58ef0d
1,903
pl
Perl
scripts/examples/species_buildSpeciesTree.pl
MatBarba/ensembl-compara
e7b0ac16adca6849934b15bc37e58603be3690ff
[ "Apache-2.0" ]
null
null
null
scripts/examples/species_buildSpeciesTree.pl
MatBarba/ensembl-compara
e7b0ac16adca6849934b15bc37e58603be3690ff
[ "Apache-2.0" ]
null
null
null
scripts/examples/species_buildSpeciesTree.pl
MatBarba/ensembl-compara
e7b0ac16adca6849934b15bc37e58603be3690ff
[ "Apache-2.0" ]
null
null
null
#!/usr/bin/env perl # Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute # Copyright [2016-2018] EMBL-European Bioinformatics Institute # # 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. use strict; use warnings; use Bio::EnsEMBL::Registry; use Bio::EnsEMBL::Compara::Utils::SpeciesTree; # # This script creates a species tree for a given list of species using # the NCBITaxon facilities of the Compara database # my $reg = 'Bio::EnsEMBL::Registry'; $reg->load_registry_from_db( -host=>'ensembldb.ensembl.org', -user=>'anonymous', ); my $taxonDBA = $reg->get_adaptor("Multi", "compara", "NCBITaxon"); my @list_of_species = ("Homo sapiens","Mus musculus","Drosophila melanogaster","Caenorhabditis elegans"); my @taxon_ids = (); foreach my $species_name (@list_of_species) { my $taxon = $taxonDBA->fetch_node_by_name($species_name); unless ($taxon) { warn "Cannot find '$species_name' in the NCBI taxonomy tables\n"; next; } push @taxon_ids, $taxon->dbID; } my $root = Bio::EnsEMBL::Compara::Utils::SpeciesTree->create_species_tree( -COMPARA_DBA => $reg->get_DBAdaptor("Multi", "compara"), -SPECIES_SET => undef, -NO_PREVIOUS => 1, -RETURN_NCBI_TREE => 1, -EXTRATAXON_SEQUENCED => \@taxon_ids, ); print "MRCA is ", $root->name, "\t", $root->taxon_id, "\n"; $root->print_tree(10);
30.206349
105
0.709932
73fb02dee5bc58c862ea4e3d602f0c39c7d73fd2
844
pm
Perl
covid19/modules/EnsEMBL/Web/Document/Page/Dynamic.pm
TamaraNaboulsi/public-plugins
e37154f3c96987ed77de95302405952339bed154
[ "Apache-2.0" ]
null
null
null
covid19/modules/EnsEMBL/Web/Document/Page/Dynamic.pm
TamaraNaboulsi/public-plugins
e37154f3c96987ed77de95302405952339bed154
[ "Apache-2.0" ]
null
null
null
covid19/modules/EnsEMBL/Web/Document/Page/Dynamic.pm
TamaraNaboulsi/public-plugins
e37154f3c96987ed77de95302405952339bed154
[ "Apache-2.0" ]
null
null
null
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::Document::Page::Dynamic; use strict; sub modify_elements { $_[0]->remove_body_element('search_box'); } 1;
29.103448
100
0.78673
73fbefa82b38da7435e8f0f5a94db9782ee84556
1,120
t
Perl
t/Faker_Plugin_CompanyNameSuffix.t
alnewkirk/Faker
ea2ff475aaf7fc81c782b014f836a77aaee77d45
[ "Apache-2.0" ]
4
2021-02-08T09:41:51.000Z
2022-01-21T20:00:42.000Z
t/Faker_Plugin_CompanyNameSuffix.t
iamalnewkirk/faker
ea2ff475aaf7fc81c782b014f836a77aaee77d45
[ "Apache-2.0" ]
12
2020-03-14T02:11:30.000Z
2020-05-12T00:40:29.000Z
t/Faker_Plugin_CompanyNameSuffix.t
alnewkirk/Faker
ea2ff475aaf7fc81c782b014f836a77aaee77d45
[ "Apache-2.0" ]
null
null
null
use 5.014; use strict; use warnings; use routines; use Test::Auto; use Test::More; =name Faker::Plugin::CompanyNameSuffix =cut =abstract Company Name Suffix Plugin for Faker =cut =includes method: execute =cut =libraries Types::Standard =cut =synopsis package main; use Faker; use Faker::Plugin::CompanyNameSuffix; my $f = Faker->new; my $p = Faker::Plugin::CompanyNameSuffix->new(faker => $f); my $plugin = $p; =cut =inherits Data::Object::Plugin =cut =attributes faker: ro, req, ConsumerOf["Faker::Maker"] =cut =description This package provides methods for generating fake company name suffix data. =cut =method execute The execute method returns a random fake company name suffix. =signature execute execute() : Str =example-1 execute # given: synopsis $p->execute; =cut package main; my $test = testauto(__FILE__); my $subs = $test->standard; $subs->synopsis(fun($tryable) { ok my $result = $tryable->result; $result }); $subs->example(-1, 'execute', 'method', fun($tryable) { ok my $result = $tryable->result; $result }); ok 1 and done_testing;
11.089109
75
0.685714
ed1a9698a9e3cfe14e9b17b77a808747b73cd074
2,009
pm
Perl
lib/EPPlication/Step/DateCheck.pm
nic-at/EPPlication
cd5205f3bf45430859dcfc671da18819b487dff4
[ "Artistic-2.0" ]
1
2018-12-05T20:08:27.000Z
2018-12-05T20:08:27.000Z
lib/EPPlication/Step/DateCheck.pm
nic-at/EPPlication
cd5205f3bf45430859dcfc671da18819b487dff4
[ "Artistic-2.0" ]
null
null
null
lib/EPPlication/Step/DateCheck.pm
nic-at/EPPlication
cd5205f3bf45430859dcfc671da18819b487dff4
[ "Artistic-2.0" ]
1
2018-10-08T07:16:32.000Z
2018-10-08T07:16:32.000Z
package EPPlication::Step::DateCheck; use Moose; use EPPlication::Role::Step::Parameters; with 'EPPlication::Role::Step::Base', Parameters(parameter_list => [qw/ duration date_got date_expected /]), 'EPPlication::Role::Step::Util::DateTime', ; sub process { my ($self) = @_; my $date_got_str = $self->process_tt_value( 'date_got', $self->date_got ); my $date_expected_str = $self->process_tt_value( 'date_expected', $self->date_expected ); my $duration_str = $self->process_tt_value( 'duration', $self->duration ); $self->add_detail("$date_expected_str +/- $duration_str"); my $date_got = $self->parse_datetime($date_got_str); my $date_expected = $self->parse_datetime($date_expected_str); my $duration = $self->parse_duration($duration_str); my $date_lower_boundary = $date_expected->clone->subtract_duration($duration); my $date_upper_boundary = $date_expected->clone->add_duration($duration); if ( $date_got < $date_lower_boundary ) { die "date_got exceeds lower boundary.\n" . "Expected: " . $self->date_to_str($date_expected) . "\n" . "Got: " . $self->date_to_str($date_got) . "\n" . "Lower: " . $self->date_to_str($date_lower_boundary) . "\n" . "Upper: " . $self->date_to_str($date_upper_boundary) . "\n" . "Duration: $duration_str\n"; } elsif ( $date_got > $date_upper_boundary ) { die "date_got exceeds upper boundary.\n" . "Expected: " . $self->date_to_str($date_expected) . "\n" . "Got: " . $self->date_to_str($date_got) . "\n" . "Lower: " . $self->date_to_str($date_lower_boundary) . "\n" . "Upper: " . $self->date_to_str($date_upper_boundary) . "\n" . "Duration: $duration_str\n"; } $self->status('success'); return $self->result; } __PACKAGE__->meta->make_immutable; 1;
33.483333
93
0.59333
73e52e8a99fc19a5a5d3191e5dd0eaa7af4f3c51
2,177
pm
Perl
auto-lib/Paws/SageMaker/MonitoringBaselineConfig.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
164
2015-01-08T14:58:53.000Z
2022-02-20T19:16:24.000Z
auto-lib/Paws/SageMaker/MonitoringBaselineConfig.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
348
2015-01-07T22:08:38.000Z
2022-01-27T14:34:44.000Z
auto-lib/Paws/SageMaker/MonitoringBaselineConfig.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
87
2015-04-22T06:29:47.000Z
2021-09-29T14:45:55.000Z
# Generated by default/object.tt package Paws::SageMaker::MonitoringBaselineConfig; use Moose; has BaseliningJobName => (is => 'ro', isa => 'Str'); has ConstraintsResource => (is => 'ro', isa => 'Paws::SageMaker::MonitoringConstraintsResource'); has StatisticsResource => (is => 'ro', isa => 'Paws::SageMaker::MonitoringStatisticsResource'); 1; ### main pod documentation begin ### =head1 NAME Paws::SageMaker::MonitoringBaselineConfig =head1 USAGE This class represents one of two things: =head3 Arguments in a call to a service Use the attributes of this class as arguments to methods. You shouldn't make instances of this class. Each attribute should be used as a named argument in the calls that expect this type of object. As an example, if Att1 is expected to be a Paws::SageMaker::MonitoringBaselineConfig object: $service_obj->Method(Att1 => { BaseliningJobName => $value, ..., StatisticsResource => $value }); =head3 Results returned from an API call Use accessors for each attribute. If Att1 is expected to be an Paws::SageMaker::MonitoringBaselineConfig object: $result = $service_obj->Method(...); $result->Att1->BaseliningJobName =head1 DESCRIPTION Configuration for monitoring constraints and monitoring statistics. These baseline resources are compared against the results of the current job from the series of jobs scheduled to collect data periodically. =head1 ATTRIBUTES =head2 BaseliningJobName => Str The name of the job that performs baselining for the monitoring job. =head2 ConstraintsResource => L<Paws::SageMaker::MonitoringConstraintsResource> The baseline constraint file in Amazon S3 that the current monitoring job should validated against. =head2 StatisticsResource => L<Paws::SageMaker::MonitoringStatisticsResource> The baseline statistics file in Amazon S3 that the current monitoring job should be validated against. =head1 SEE ALSO This class forms part of L<Paws>, describing an object used in L<Paws::SageMaker> =head1 BUGS and CONTRIBUTIONS The source code is located here: L<https://github.com/pplu/aws-sdk-perl> Please report bugs to: L<https://github.com/pplu/aws-sdk-perl/issues> =cut
28.644737
112
0.768489
ed117422d5d8c544f864960cef54ffe7855482e6
10,022
pl
Perl
openkore-master/plugins/macro/macro.pl
phuchduong/ro_restart_bot
41da6e1def82d05341433961ca0f071ad4424b60
[ "Apache-2.0" ]
null
null
null
openkore-master/plugins/macro/macro.pl
phuchduong/ro_restart_bot
41da6e1def82d05341433961ca0f071ad4424b60
[ "Apache-2.0" ]
null
null
null
openkore-master/plugins/macro/macro.pl
phuchduong/ro_restart_bot
41da6e1def82d05341433961ca0f071ad4424b60
[ "Apache-2.0" ]
null
null
null
# macro by Arachno # # $Id: macro.pl r6744 2009-06-28 20:05:00Z ezza $ # # This source code is licensed under the # GNU General Public License, Version 2. # See http://www.gnu.org/licenses/gpl.html package macro; my $Version = "2.0.3-svn"; my ($rev) = q$Revision: 6744 $ =~ /(\d+)/; our $plugin_folder = $Plugins::current_plugin_folder; use strict; use Plugins; use Settings; use Globals; use Utils; use Misc; use Log qw(message error warning); use Translation qw/T TF/; use lib $Plugins::current_plugin_folder; use Macro::Data; use Macro::Script; use Macro::Parser qw(parseMacroFile); use Macro::Automacro qw(automacroCheck consoleCheckWrapper releaseAM); use Macro::Utilities qw(callMacro); ######### # startup Plugins::register('macro', 'allows usage of macros', \&Unload, \&Reload); my $hooks = Plugins::addHooks( ['configModify', \&onconfigModify, undef], ['start3', \&onstart3, undef], ['mainLoop_pre', \&callMacro, undef] ); my $chooks = Commands::register( ['macro', "Macro plugin", \&commandHandler] ); my $autohooks; my $loghook; my $cfID; my $macro_file; # onconfigModify sub onconfigModify { my (undef, $args) = @_; if ($args->{key} eq 'macro_file') { Settings::removeFile($cfID); $cfID = Settings::addControlFile($args->{val}, loader => [ \&parseAndHook, \%macro]); Settings::loadByHandle($cfID); } } # onstart3 sub onstart3 { &checkConfig; $cfID = Settings::addControlFile($macro_file,loader => [\&parseAndHook,\%macro], mustExist => 0); Settings::loadByHandle($cfID); if ( $interface->isa ('Interface::Wx') && $interface->{viewMenu} && $interface->can ('addMenu') && $interface->can ('openWindow') ) { $interface->addMenu ($interface->{viewMenu}, T('Macro debugger'), sub { $interface->openWindow (T('Macro'), 'Macro::Wx::Debugger', 1); }, T('Interactive debugger for macro plugin')); } } # onReload sub Reload { message "macro plugin reloading, ", 'success'; &cleanup; &onstart3 } # onUnload sub Unload { message "macro plugin unloading, ", 'success'; &cleanup; Plugins::delHooks($hooks); Commands::unregister($chooks); } sub cleanup { message "cleaning up\n", 'success'; Settings::removeFile($cfID) if defined $cfID; Log::delHook($loghook); foreach (@{$autohooks}) {Plugins::delHook($_)} undef $autohooks; undef $queue; undef %macro; undef %automacro; undef %varStack } # onFile(Re)load sub parseAndHook { my $file = shift; if (parseMacroFile($file, 0)) { Plugins::callHook ('macro/parseAndHook'); &hookOnDemand; return 1 } error "error loading $file.\n"; return 0 } # only adds hooks that are needed sub hookOnDemand { foreach (@{$autohooks}) {Plugins::delHook($_)} undef $autohooks; Log::delHook($loghook) if defined $loghook; my %load = ('AI_pre' => 1); my $hookToLog; foreach my $a (keys %automacro) { next if $automacro{$a}->{disabled}; if (defined $automacro{$a}->{spell}) { if (!defined $load{'is_casting'}) {$load{'is_casting'} = 1} if (!defined $load{'packet_skilluse'}) {$load{'packet_skilluse'} = 1} } if (defined $automacro{$a}->{areaSpell} && !defined $load{'packet_areaSpell'}) {$load{'packet_areaSpell'} = 1} if (defined $automacro{$a}->{pm} && !defined $load{'packet_privMsg'}) {$load{'packet_privMsg'} = 1} if (defined $automacro{$a}->{pubm} && !defined $load{'packet_pubMsg'}) {$load{'packet_pubMsg'} = 1} if (defined $automacro{$a}->{system} && !defined $load{'packet_sysMsg'}) {$load{'packet_sysMsg'} = 1;} if (defined $automacro{$a}->{party} && !defined $load{'packet_partyMsg'}) {$load{'packet_partyMsg'} = 1} if (defined $automacro{$a}->{guild} && !defined $load{'packet_guildMsg'}) {$load{'packet_guildMsg'} = 1} if (defined $automacro{$a}->{mapchange} && !defined $load{'packet_mapChange'}) {$load{'packet_mapChange'} = 1} if (defined $automacro{$a}->{hook} && !defined $load{$automacro{$a}->{hook}}) {$load{$automacro{$a}->{hook}} = 1} if (defined $automacro{$a}->{console} && !defined $hookToLog) {$hookToLog = 1} if (defined $automacro{$a}->{playerguild} && !defined $load{'player'}) {$load{'player'} = 1} if (defined $automacro{$a}->{playerguild} && !defined $load{'charNameUpdate'}) {$load{'charNameUpdate'} = 1} } foreach my $l (keys %load) { message "[macro] hooking to $l\n"; push(@{$autohooks}, Plugins::addHook($l, \&automacroCheck)) } if ($hookToLog) { message "[macro] hooking to log\n"; $loghook = Log::addHook(\&consoleCheckWrapper) } } # checks macro configuration sub checkConfig { $timeout{macro_delay}{timeout} = 1 unless defined $timeout{macro_delay}; $macro_file = (defined $::config{macro_file})?$::config{macro_file}:"macros.txt"; if (!defined $::config{macro_orphans} || $::config{macro_orphans} !~ /^(?:terminate|reregister(?:_safe)?)$/) { warning "[macro] orphans: using method 'terminate'\n"; configModify('macro_orphans', 'terminate') } return 1 } # macro command handler sub commandHandler { ### no parameter given if (!defined $_[1]) { message "usage: macro [MACRO|list|stop|set|version|reset] [automacro]\n", "list"; message "macro MACRO: run macro MACRO\n". "macro list: list available macros\n". "macro status: shows current status\n". "macro stop: stop current macro\n". "macro pause: interrupt current macro\n". "macro resume: resume interrupted macro\n". "macro version: print macro plugin version\n". "macro reset [automacro]: resets run-once status for all or given automacro(s)\n"; return } my ($arg, @params) = split(/\s+/, $_[1]); ### parameter: list if ($arg eq 'list') { message(sprintf("The following macros are available:\n%smacros%s\n","-"x10,"-"x9), "list"); foreach my $m (keys %macro) {message "$m\n" unless $m =~ /^tempMacro/} message(sprintf("%sautomacros%s\n", "-"x8, "-"x7), "list"); foreach my $a (sort { ($automacro{$a}->{priority} or 0) <=> ($automacro{$b}->{priority} or 0) } keys %automacro) {message "$a\n"} message(sprintf("%sPerl Sub%s\n", "-"x9, "-"x8), "list"); foreach my $s (@perl_name) {message "$s\n"} message(sprintf("%s\n","-"x25), "list"); ### parameter: status } elsif ($arg eq 'status') { if (defined $queue) { message(sprintf("macro %s\n", $queue->name), "list"); message(sprintf("status: %s\n", $queue->registered?"running":"waiting")); my %tmp = $queue->timeout; message(sprintf("delay: %ds\n", $tmp{timeout})); message(sprintf("line: %d\n", $queue->line)); message(sprintf("override AI: %s\n", $queue->overrideAI?"yes":"no")); message(sprintf("paused: %s\n", $onHold?"yes":"no")); message(sprintf("finished: %s\n", $queue->finished?"yes":"no")); } else { message "There's no macro currently running.\n" } ### parameter: stop } elsif ($arg eq 'stop') { undef $queue; message "macro queue cleared.\n" ### parameter: pause } elsif ($arg eq 'pause') { if (defined $queue) { $onHold = 1; message "macro ".$queue->name." paused.\n" } else { warning "There's no macro currently running.\n" } ### parameter: resume } elsif ($arg eq 'resume') { if (defined $queue) { $onHold = 0; message "macro ".$queue->name." resumed.\n" } else { warning "There's no macro currently running.\n" } ### parameter: reset } elsif ($arg eq 'reset') { if (!defined $params[0]) { foreach my $am (keys %automacro) {undef $automacro{$am}->{disabled}} message "automacro runonce list cleared.\n"; return } for my $reset (@params) { my $ret = releaseAM($reset); if ($ret == 1) {message "automacro $reset reenabled.\n"} elsif ($ret == 0) {warning "automacro $reset wasn't disabled.\n"} else {error "automacro $reset not found.\n"} } ### parameter: version } elsif ($arg eq 'version') { message "macro plugin version $Version\n", "list"; message "macro.pl ". $rev."\n"; message "Macro::Automacro ".$Macro::Automacro::rev."\n"; message "Macro::Script ".$Macro::Script::rev."\n"; message "Macro::Parser ".$Macro::Parser::rev."\n"; message "Macro::Utilities ".$Macro::Utilities::rev."\n"; message "Macro::Data ".$Macro::Data::rev."\n" ### debug } elsif ($arg eq 'varstack') { message "Varstack List\n", "menu"; foreach my $v (keys %varStack) { message "\$varStack{$v} = [".$varStack{$v}."]\n", "menu" } ### parameter: probably a macro } else { if (defined $queue) { warning "a macro is already running. Wait until the macro has finished or call 'macro stop'\n"; return } my ($repeat, $oAI, $exclusive, $mdelay, $orphan) = (1, 0, 0, undef, undef); my $cparms; for (my $idx = 0; $idx <= @params; $idx++) { if ($params[$idx] eq '-repeat') {$repeat += $params[++$idx]} if ($params[$idx] eq '-overrideAI') {$oAI = 1} if ($params[$idx] eq '-exclusive') {$exclusive = 1} if ($params[$idx] eq '-macro_delay') {$mdelay = $params[++$idx]} if ($params[$idx] eq '-orphan') {$orphan = $params[++$idx]} if ($params[$idx] =~ /^--/) {$cparms = substr(join(' ', map { "$_" } @params[$idx..($#params)]), 2); last} } delete $varStack{$_} for grep /^\.param\d+$/, keys %varStack; if ($cparms) { #parse macro parameters my @new_params = $cparms =~ /"[^"]+"|\S+/g; foreach my $p (1..@new_params) { $varStack{".param".$p} = $new_params[$p-1]; $varStack{".param".$p} = substr($varStack{".param".$p}, 1, -1) if ($varStack{".param".$p} =~ /^".*"$/); # remove quotes } } $queue = new Macro::Script($arg, $repeat); if (!defined $queue) {error "macro $arg not found or error in queue\n"} else { $onHold = 0; if ($oAI) {$queue->overrideAI(1)} if ($exclusive) {$queue->interruptible(0)} if (defined $mdelay) {$queue->setMacro_delay($mdelay)} if (defined $orphan) {$queue->orphan($orphan)} } } } 1; __END__ =head1 NAME macro.pl - plugin for openkore 2.0.0 and later =head1 AVAILABILITY Get the latest release from L<http://www.openkore.com/wiki/index.php/Macro_plugin> or from SVN: C<svn co https://openkore.svn.sourceforge.net/svnroot/openkore/macro/trunk/> =head1 AUTHOR Arachno <arachnophobia at users dot sf dot net> =cut
32.538961
123
0.637597
ed0541e5ece806ffa4414ae23d7d84536d6dae67
352
pm
Perl
assets/PortableGit/usr/share/perl5/vendor_perl/Authen/SASL/EXTERNAL.pm
ther3tyle/git-it-electron
d808d9ce9f95ffebe39911e57907d72f4653ff6e
[ "BSD-2-Clause" ]
4,499
2015-05-08T04:02:28.000Z
2022-03-31T20:07:15.000Z
assets/PortableGit/usr/share/perl5/vendor_perl/Authen/SASL/EXTERNAL.pm
enterstudio/git-it-electron
b101d208e9a393e16fc4368e205275e5dfc6f63e
[ "BSD-2-Clause" ]
261
2015-05-09T03:09:24.000Z
2022-03-25T18:35:53.000Z
assets/PortableGit/usr/share/perl5/vendor_perl/Authen/SASL/EXTERNAL.pm
enterstudio/git-it-electron
b101d208e9a393e16fc4368e205275e5dfc6f63e
[ "BSD-2-Clause" ]
1,318
2015-05-09T02:16:45.000Z
2022-03-28T11:10:01.000Z
# Copyright (c) 2002 Graham Barr <gbarr@pobox.com>. All rights reserved. # This program is free software; you can redistribute it and/or # modify it under the same terms as Perl itself. package Authen::SASL::EXTERNAL; use strict; use vars qw($VERSION); $VERSION = "2.14"; sub new { shift; Authen::SASL->new(@_, mechanism => 'EXTERNAL'); } 1;
18.526316
72
0.693182
73d0684471eba34f627feb805516fd2ab06bce3f
6,755
pm
Perl
core/standards/mathml/reftests/perl/xdotool/xwd/RT.pm
frivoal/presto-testo
cdeca5092fb8227f327169a772b42fca854d355e
[ "BSD-3-Clause" ]
null
null
null
core/standards/mathml/reftests/perl/xdotool/xwd/RT.pm
frivoal/presto-testo
cdeca5092fb8227f327169a772b42fca854d355e
[ "BSD-3-Clause" ]
null
null
null
core/standards/mathml/reftests/perl/xdotool/xwd/RT.pm
frivoal/presto-testo
cdeca5092fb8227f327169a772b42fca854d355e
[ "BSD-3-Clause" ]
null
null
null
#!/usr/bin/perl package RT; use strict; use warnings; my @winIDs; my @reference; my @fail; my @skip; my @button; my @buttonX; my @buttonY; my @buttonZ; my @knownUI; my @mismatch; my $rowSize; my $colSize; my $pass = 0; my $pageOffset = 40; sub GrabWindow {my $winName = shift; my $winID = `xdotool search --limit 1 --name '$winName'`; if($winID) {system("xdotool windowraise $winID"); system("xdotool windowfocus $winID");} unshift(@winIDs,$winID); if($winName =~ /LinGogi desktop UI/) {unshift(@knownUI,1); unshift(@buttonX,90); unshift(@buttonY,10); unshift(@buttonZ,1); unshift(@button,'215,215,213');} elsif($winName =~ /LinGogi phone UI/) {unshift(@knownUI,1); unshift(@buttonX,-13); unshift(@buttonY,25); unshift(@buttonZ,4); unshift(@button,'0,0,0,0,0,0,0,0,0,0,0,0');} else {unshift(@knownUI,0);} } sub LoadPage {if(Alive()) {my $tc = shift; system("xdotool key F8"); system("xdotool type $tc"); system("xdotool key Return"); print "Loading page ".$tc."\n";} } sub SwitchWindows {if(Alive()) {system("xdotool key alt+Tab"); @winIDs = reverse(@winIDs); @button = reverse(@button); @buttonX = reverse(@buttonX); @buttonY = reverse(@buttonY); @buttonZ = reverse(@buttonZ); @knownUI = reverse(@knownUI);} } sub WaitSeconds {select(undef, undef, undef, shift);} sub Alive {if(`xdotool getactivewindow` ne $winIDs[0]) {Quit("Testing interrupted since target window lost focus.\n");} return 1;} sub Gogi() {return 'LinGogi';} sub Desktop() {return 'LinGogi desktop UI \(X11\/SW\)';} sub TV() {return 'LinGogi desktop UI \(X11\/VEMU2D\)';} sub SmartPhone() {return 'LinGogi phone UI';} sub SaveReference {@reference = (); my $wait = 3; until($wait == 0) {$wait = $wait - 1; WaitSeconds(0.5); my $result = SaveBitmapRows(); if($result eq 'loading' or $result eq 'invalid screenshot') {if($wait == 0) {print "Timeout.\n"; return "timeout";} elsif($result eq 'loading') {print "Waiting for page to load.\n";} else {print "Waiting for screenshot.\n";} } else {return $result;} } } sub MatchesReference {my $wait = 3; until($wait == 0) {$wait = $wait - 1; WaitSeconds(0.5); my $result = CompareBitmapRows(); if($result eq 'loading' or $result eq 'invalid screenshot') {if($wait == 0) {print "Timeout.\n"; return "timeout";} elsif($result eq 'loading') {print "Waiting for page to load.\n";} else {print "Waiting for screenshot.\n";} } else {if($result eq 'line mismatch') {print LineNumbers();} elsif($result eq 'width mismatch') {print "Bitmap width does not match reference\n";} elsif($result eq 'height mismatch') {print "Bitmap height does not match reference\n";} return $result;} } } sub LineNumbers {my ($lines,$range) = ("The following lines mismatch: $mismatch[0]",0); for(my $i = 1; $i != int(@mismatch); $i++) {if($mismatch[$i]-$mismatch[$i-1]>1) {if($range == 1) {$lines = "$lines-$mismatch[$i-1], $mismatch[$i]"; $range = 0;} else {$lines = "$lines, $mismatch[$i]";} } else {if($i == int(@mismatch)-1) {$lines = "$lines-$mismatch[$i]";} $range = 1;} } return "$lines\n";} sub SaveBitmapRows {if(Alive()) {open(TC,"xwd -nobdrs -silent -id $winIDs[0]|") or Quit("Can't load xwd data.\n"); read(TC,my $data, 100); my @h = unpack('N'.100, $data); if(@h) {($rowSize,$colSize) = ($h[12],$h[5]); read(TC, $data, $h[0] - 100 + 12*$h[19]); if($knownUI[0] == 1) {if($buttonX[0] < 0) {$buttonX[0] = $rowSize+$buttonX[0]} read(TC, $data, $buttonY[0]*$rowSize + $buttonX[0]*$h[11]/8); read(TC,$data,$buttonZ[0]*$h[11]/8); if($button[0] ne join(',',unpack("C*",$data))) {print join(',',unpack("C*",$data))."\n"; close TC; return 'loading';} read(TC,$data,($pageOffset - $buttonY[0])*$rowSize - ($buttonX[0] + $buttonZ[0])*$h[11]/8);} else {read(TC,$data,$pageOffset*$rowSize);} for(my $y=$pageOffset; $y < $colSize; $y++) {read(TC, $data, $rowSize); push(@reference,$data);} close TC; return 'done';} close TC; return 'invalid screenshot';} close TC; return 'no screenshot';} sub CompareBitmapRows {if(Alive()) {open(TC,"xwd -nobdrs -silent -id $winIDs[0]|") or Quit("Can't load xwd data.\n"); read(TC,my $data, 100); @mismatch = (); my @h = unpack('N'.100, $data); if(@h) {if($rowSize != $h[12]) {close TC; return 'width mismatch';} if($colSize != $h[5]) {close TC; return 'height mismatch';} read(TC, $data, $h[0] - 100 + 12*$h[19]); if($knownUI[0] == 1) {if($buttonX[0] < 0) {$buttonX[0] = $rowSize+$buttonX[0]} read(TC, $data, $buttonY[0]*$rowSize + $buttonX[0]*$h[11]/8); read(TC,$data,$buttonZ[0]*$h[11]/8); if($button[0] ne join(',',unpack("C*",$data))) {close TC; return 'loading';} read(TC,$data,($pageOffset - $buttonY[0])*$rowSize - ($buttonX[0] + $buttonZ[0])*$h[11]/8);} else {read(TC,$data,$pageOffset*$rowSize);} for(my $y=$pageOffset; $y < $colSize; $y++) {read(TC, $data, $rowSize); if($data ne $reference[$y-$pageOffset]) {push(@mismatch,$y);} } close TC; if(@mismatch) {return 'line mismatch';} else {return 'match';} } close TC; return 'invalid screenshot';} close TC; return 'no screenshot';} sub Quit {Results(); die(shift);} sub Result {my ($result,$title) = @_; if($result == 1) {print "PASS\n"; $pass++;} elsif($result == 0) {print "FAIL\n"; push(@fail,$title);} else {push(@skip,$title);} } sub Results {my $tests = $pass + int(@fail); print "$pass tests out of $tests passed.\n"; if(@fail) {if(int(@fail) > 1) {print "The following ".int(@fail)." tests failed:\n"; print join("\n",@fail); print "\n";} else {print "The following test failed:\n$fail[0]\n";} } if(@skip) {if(int(@skip) > 1) {print "The following ".int(@skip)." tests skipped:\n"; print join("\n",@skip); print "\n";} else {print "The following test skipped:\n$skip[0]\n";} } my $testTime = time - $^T; if($testTime > 60) {my $testMin = int($testTime/60); my $testSec = $testTime%60; if($testSec == 0) {print "Testing took $testMin minutes."} else {print "Testing took $testMin minutes and $testSec seconds."} } else {print "Testing took $testTime seconds."} if($tests > 1) {my $averageTime = int($testTime*100/$tests)/100; print " $averageTime seconds per test.\n";} else {print "\n";} } 1;
26.699605
97
0.569356
73eea38b0d7ee43135d10abfc1fad5f4da2aa64d
747
t
Perl
t/percents.t
ronsavage/Text-Balanced-Marpa
7715b489b2663880e88fec076ae4a9de5d56a217
[ "Artistic-1.0" ]
1
2015-12-09T13:11:28.000Z
2015-12-09T13:11:28.000Z
t/percents.t
ronsavage/Text-Balanced-Marpa
7715b489b2663880e88fec076ae4a9de5d56a217
[ "Artistic-1.0" ]
null
null
null
t/percents.t
ronsavage/Text-Balanced-Marpa
7715b489b2663880e88fec076ae4a9de5d56a217
[ "Artistic-1.0" ]
null
null
null
#!/usr/bin/env perl use strict; use warnings; use Test::More; use Text::Balanced::Marpa ':constants'; # ----------- my($count) = 0; my($parser) = Text::Balanced::Marpa -> new ( open => ['[%'], close => ['%]'], options => nesting_is_fatal, ); my(@text) = ( q||, q|a|, q|[% a %]|, q|a {b [% c %] d} e|, q|a [% b [% c %] d %] e|, # nesting_is_fatal triggers an error here. ); my($result); for my $text (@text) { $count++; $result = $parser -> parse(text => \$text); if ($count == 5) { ok($result == 1, "Deliberate error. Failed to parse: $text"); } else { ok($result == 0, "Parsed: $text"); } #diag join("\n", @{$parser -> tree -> tree2string}); } print "# Internal test count: $count\n"; done_testing($count);
14.647059
69
0.531459
ed144b4107dc064de397ebe16d8d17376bbc849f
322
al
Perl
vendor/git-for-windows/usr/lib/perl5/vendor_perl/auto/Net/SSLeay/get_https4.al
azure-hu/cmder-env
9d0f6a2a73bec2a44008755849207ecbb69925c4
[ "MIT" ]
16
2020-09-20T22:32:54.000Z
2021-04-02T17:14:25.000Z
usr/lib/perl5/vendor_perl/auto/Net/SSLeay/get_https4.al
Felipe-Souza-Pereira-Lima/didactic-funicular
88d902f879b6ad976a1b418e93f8bd2a11ba6cd8
[ "MIT" ]
98
2017-11-02T19:00:44.000Z
2022-03-22T16:15:39.000Z
usr/lib/perl5/vendor_perl/auto/Net/SSLeay/get_https4.al
Felipe-Souza-Pereira-Lima/didactic-funicular
88d902f879b6ad976a1b418e93f8bd2a11ba6cd8
[ "MIT" ]
9
2017-10-24T21:53:36.000Z
2021-11-23T07:36:59.000Z
# NOTE: Derived from blib/lib/Net/SSLeay.pm. # Changes made here will be lost when autosplit is run again. # See AutoSplit.pm. package Net::SSLeay; #line 1440 "blib/lib/Net/SSLeay.pm (autosplit into blib/lib/auto/Net/SSLeay/get_https4.al)" sub get_https4 { do_httpx4(GET => 1, @_) } # end of Net::SSLeay::get_https4 1;
32.2
91
0.726708
73fb7261d628a84d25bbf1491e38d8afc71597b1
2,729
pm
Perl
lib/App/Yath/Options/Workspace.pm
JRaspass/Test2-Harness
2fb581d3ddb77cebe20255cfef4d31c9604034f0
[ "Artistic-1.0" ]
null
null
null
lib/App/Yath/Options/Workspace.pm
JRaspass/Test2-Harness
2fb581d3ddb77cebe20255cfef4d31c9604034f0
[ "Artistic-1.0" ]
null
null
null
lib/App/Yath/Options/Workspace.pm
JRaspass/Test2-Harness
2fb581d3ddb77cebe20255cfef4d31c9604034f0
[ "Artistic-1.0" ]
null
null
null
package App::Yath::Options::Workspace; use strict; use warnings; our $VERSION = '1.000048'; use File::Spec(); use File::Path qw/remove_tree/; use File::Temp qw/tempdir/; use Test2::Harness::Util qw/clean_path chmod_tmp/; use App::Yath::Options; option_group {prefix => 'workspace', category => "Workspace Options"} => sub { option tmp_dir => ( type => 's', short => 't', alt => ['tmpdir'], description => 'Use a specific temp directory (Default: use system temp dir)', env_vars => [qw/T2_HARNESS_TEMP_DIR YATH_TEMP_DIR TMPDIR TEMPDIR TMP_DIR TEMP_DIR/], default => sub { File::Spec->tmpdir }, ); option workdir => ( type => 's', short => 'w', description => 'Set the work directory (Default: new temp directory)', env_vars => [qw/T2_WORKDIR YATH_WORKDIR/], clear_env_vars => 1, normalize => \&clean_path, ); option clear => ( short => 'C', description => 'Clear the work directory if it is not already empty', ); post sub { my %params = @_; my $settings = $params{settings}; if (my $workdir = $settings->workspace->workdir) { if (-d $workdir) { remove_tree($workdir, {safe => 1, keep_root => 1}) if $settings->workspace->clear; } else { mkdir($workdir) or die "Could not create workdir: $!"; chmod_tmp($workdir); } return; } my $project = $settings->harness->project; my $template = join '-' => ( "yath", $$, "XXXXXX"); my $tmpdir = tempdir( $template, DIR => $settings->workspace->tmp_dir, CLEANUP => !($settings->debug->keep_dirs || $params{command}->always_keep_dir), ); chmod_tmp($tmpdir); $settings->workspace->field(workdir => $tmpdir); }; }; 1; =pod =encoding UTF-8 =head1 NAME App::Yath::Options::Workspace - Options for specifying the yath work dir. =head1 DESCRIPTION Options regarding the yath working directory. =head1 PROVIDED OPTIONS POD IS AUTO-GENERATED =head1 SOURCE The source code repository for Test2-Harness can be found at F<http://github.com/Test-More/Test2-Harness/>. =head1 MAINTAINERS =over 4 =item Chad Granum E<lt>exodist@cpan.orgE<gt> =back =head1 AUTHORS =over 4 =item Chad Granum E<lt>exodist@cpan.orgE<gt> =back =head1 COPYRIGHT Copyright 2020 Chad Granum E<lt>exodist7@gmail.comE<gt>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F<http://dev.perl.org/licenses/> =cut
23.525862
98
0.589593
73d27f807baa09cf647bd17427e40a8ab4dba04a
8,176
pl
Perl
www/scripts/contrib/dbgen/dbgen.pl
OpenAai/php-syslog-ng
490a2bf59b354988f40099ee70fcf692c52308a5
[ "Apache-2.0" ]
10
2016-05-05T03:40:30.000Z
2021-11-05T20:11:27.000Z
www/scripts/contrib/dbgen/dbgen.pl
OpenAai/php-syslog-ng
490a2bf59b354988f40099ee70fcf692c52308a5
[ "Apache-2.0" ]
1
2018-12-21T11:57:25.000Z
2018-12-21T11:57:25.000Z
www/scripts/contrib/dbgen/dbgen.pl
OpenAai/php-syslog-ng
490a2bf59b354988f40099ee70fcf692c52308a5
[ "Apache-2.0" ]
7
2017-12-25T14:05:52.000Z
2021-02-08T14:38:32.000Z
#!/usr/bin/perl # # dbgen.pl # # Developed by Clayton Dukes <cdukes@cdukes.com> # Copyright (c) 2006 # Licensed under terms of GNU General Public License. # All rights reserved. # # Changelog: # 2006-04-14 - created # # $Platon$ $| = 1; # Note - requires: # Digest::SHA1 # and # Net-Mysql use Net::MySQL; use POSIX qw(strftime); use File::Basename; use strict; my $sleeptime = (1 + rand(5)); # Set sleep time as random or as an integer #my $sleeptime = ".0001"; # Use this to just blast a whole bunch into the database # Change below to match your config path (use full path if you run this from cron) my $ngconfig = "/var/www/html/config/config.php"; open( CONFIG, $ngconfig ) or die "Can't open $ngconfig : $!"; my @config = <CONFIG>; close( CONFIG ); my($table,$dbadmin,$dbpw,$dbname,$dbhost,$dbport,$DEBUG); foreach my $var (@config) { next unless $var =~ /^define/; # read only def's $table = $1 if ($var =~ /'DEFAULTLOGTABLE', '(\w+)'/); $dbadmin = $1 if ($var =~ /'DBADMIN', '(\w+)'/); $dbpw = $1 if ($var =~ /'DBADMINPW', '(\w+)'/); $dbname = $1 if ($var =~ /'DBNAME', '(\w+)'/); $dbhost = $1 if ($var =~ /'DBHOST', '(\w+)'/); $dbport = $1 if ($var =~ /'DBPORT', '(\w+)'/); $DEBUG = $1 if ($var =~ /'DEBUG', '(\w+)'/); } if ( ! $table ) { print "Error: Unable to read config variables from $ngconfig\n"; exit; } if ($DEBUG > 0) { print "Table: $table\n"; print "Adminuser: $dbadmin\n"; print "PW: $dbpw\n"; print "DB: $dbname\n"; print "DB Host: $dbhost\n"; print "DB Port: $dbport\n"; #exit; } ### our fake stuff our %myevents = ( 'pagp' => [ '%AAA-3-ACCT_IOMEM_LOW: Line protocol on Interface FastEthernet0/5, changed state to up', '%AAA-3-IPILLEGALMSG: Line protocol on Interface FastEthernet0/7, changed state to up', '%FWSM-5-111008: User \'\'2g456\'\' executed the \'\'exit\'\' command', '%AAAA-3-ACCTFORKFAIL:Configured from console by vty0 (192.168.4.35)', '%AAAA-3-BADSTATE:Attempted to connect to RSHELL from 10.15.10.121', '%AAA-3-BADHDL:Authentication failure for SNMP req from host 10.6.1.36', ], 'mls' => [ '%AAAA-4-NOSERVER: IP Multilayer switching is enabled', '%C4K_HWACLMAN-4-CAMAUDIT: Netflow Data Export disabled', '%FWSM-5-111008: User \'\'2g456\'\' executed the \'\'exit\'\' command', '%NCDP-5-UNABLETOREACHCL: Duplicate address 10.10.2.2 on Vlan20', '%NEVADA-0-BADADD: Duplicate address 10.10.7.2 on Vlan70', ], 'sys' => [ '%FABRIC-5-FABRIC_MODULE_ACTIVE: Module 1 is online', '%FABRIC-5-FABRIC_MODULE_ACTIVE: Module 3 is online', '%FWSM-5-111008: User \'\'2g456\'\' executed the \'\'exit\'\' command', '%C6KENV-2-FANUPGREQ: Fan 1 had a rotation error reported.', '%C6KENV-2-FANUPGREQ: Fan 1 had earlier reported a rotation error. It is ok now', '%LINK-3-BADENCAP: FastEthernet0/11 link down/up 5 times per min', '%LINK-3-BADENCAP: FastEthernet0/12 link down/up 5 times per min', '%LINK-3-BADENCAP: FastEthernet0/15 link down/up 5 times per min', ] ); our %mynames = ( 'sys' => [ '%AAA-1-AAA_SESSION_LIMIT_REJECT:', '%AAA-2-AAAMULTILINKERROR:', '%AAA-2-AAA_NVRAM_UPGRADE_FAILURE', '%AAA-2-AAA_PROGRAM_EXIT:', '%AAA-2-FORKFAIL:', '%AAA-3-AAA_NVRAMFAILURE:', '%AAA-3-ACCT_IOMEM_LOW:', '%AAA-3-ACCT_LOW_MEM_TRASH:', '%AAA-3-ACCT_LOW_MEM_UID_FAIL:', '%AAA-3-ATTRFORMATERR:', '%AAAA-3-BADLIST:', '%AAAA-3-BADREG:', '%AAAA-3-BADSTATE:', '%AAAA-3-BADSTR:', '%AAAA-3-DLRFORKFAIL:', '%AAAA-3-DROPACCTFULLQ:', '%AAAA-3-DROPACCTLOWMEM:', '%AAAA-3-DROPACCTSNDFAIL:', '%AAAA-3-ILLEGALNAME:', '%AAAA-3-ILLSGNAME:', '%AAAA-3-INTERNAL_ERROR:', '%APBR-4-PRTR_ARP_IPV6_ERR:', '%APBR-4-PRTR_ARP_IP_BAD:', '%APBR-4-PRTR_ARP_PROT_BAD:', '%APBR-4-PRTR_DHCP_XID_EXP:', ], 'mls' => [ '%AAAA-3-INVALIDLIST:', '%ACLMGR-2-NOVLB:', '%ACLMGR-2-NOVMR:', '%ACLMGR-3-ACLTCAMFULL:', '%ACLMGR-3-AUGMENTFAIL:', '%ACLMGR-3-IECPORTLABELERROR:', '%ACLMGR-3-INSERTFAIL:', '%APBR-4-DNS_CON_FAILED:', '%APBR-4-EAP_AUTH_FAILED:', '%APBR-4-EAP_SRV_VRF_FAILED:', '%APBR-4-EAP_TOUT:', '%APBR-4-FWDTBL_GIVE_FAILED:', '%APBR-4-FWDTBL_TAKE_FAILED:', '%APBR-4-FWDTBL_UNKNW_HOST:', '%APBR-4-LOSS_ETHERNET_ACTION:', '%APBR-4-MACAUTH_CON_FAIL:', '%APBR-4-MACAUTH_DENY:', '%APBR-4-MACAUTH_NORESP:', '%APBR-4-NET_ADMSTAT_SET_FAILED:', '%APBR-4-PRO80211_MNGPKT_RCV_ERR1', '%APBR-4-PRO80211_MNGPKT_RCV_ERR2', '%APBR-4-PRO80211_MNGPKT_TRNC:', '%APBR-4-PRO80211_PKTALLOC_ERR:', '%APBR-4-PRO80211_PKTBSS_ERR:', '%APBR-4-PRO80211_RCV_INV_CTRL:', '%APBR-4-PRO80211_RCV_INV_PORT:', '%APBR-4-PRO80211_RCV_TRNC_CTRL:', '%APBR-4-PRO80211_SND_ERROR:', '%APBR-4-PRTR_ADDR_ERR:', '%APBR-4-PRTR_ARP_FMT_BAD:', '%MLS-5-MLSENABLED:', '%MLS-5-NDEDISABLED:', ], 'pagp' => [ '%ACLMGR-3-INTTABLE:', '%ACLMGR-3-MAXRECURSION:', '%APBR-0-SYS_REBOOT_CFG_RESETALL:', '%APBR-0-SYS_REBOOT_CFG_RSTR:', '%APBR-0-SYS_REBOOT_EBUF:', '%APBR-0-SYS_REBOOT_FWDTSIZE:', '%APBR-0-SYS_REBOOT_FW_UPD:', '%APBR-0-SYS_REBOOT_HW_ADDR:', '%APBR-1-RCV_PCKT_ALERT:', '%APBR-4-BKP_INF_PTR_ERR:', '%APBR-4-BKR_KEY1_BADSIZE:', '%APBR-4-BKR_KEY1_NORADIOCTRL:', '%APBR-4-BKR_KEY1_NORADIOINF:', '%APBR-4-BKR_KEY1_NOT_INIT:', '%APBR-4-BKR_MANY_RADIOS:', '%APBR-4-BKR_NOT_INIT:', '%APBR-4-BKR_VLAN_DISABLED:', '%APBR-4-BKR_VLAN_NOT_INIT:', '%APBR-4-BRLP_SADDR_PKT:', '%APBR-4-DDP_RCV_PKT_ERR:', ] ); our @facilities = ("kern", "user", "mail", "daemon", "auth", "syslog", "lpr", "news", "uucp", "cron", "authpriv", "ftp", "local0", "local1", "local2", "local3", "local4", "local5", "local6"); our @priorities = ("debug", "info", "notice", "warning", "err", "crit", "alert", "emerg"); my $c = 0; our @devicelist; until ($c > 50) { # cdukes - 2-28-08: Modified sections below to generate fewer random hostnames, it was a bit overkill :-) #my @devs = ("router","switch","server","firewall"); my @devs = ("router","switch","server","fw","css","www","ftp","sun","linux","as400","6509","2811","1701","2911"); my @chars = ( 'a' .. 'z', 'A' .. 'Z', 0 .. 9 ); #my @nums = ( '0' .. '9'); my @nums = ( '0' .. '6'); my $num = join '', map $nums[ rand @nums ], 0 .. 0; my $string1 = join '', map $devs[ rand @devs ], 1 ; my $string2 = join '', map $chars[ rand @chars ], 1 .. 3; #push(@devicelist, "$string1-$num-$string2"); push(@devicelist, "$string1-$num"); $c++; } if ($DEBUG > 0) { my $DEBUG = "true"; print "DEBUG: $DEBUG\n"; } else { my $DEBUG = ""; print "Debug off, showing only inserted data...\n"; } my $mysql = Net::MySQL->new( debug => "$DEBUG", # enable debug unixsocket => "$dbport", # Default use UNIX socket hostname => "$dbhost", database => "$dbname", user => "$dbadmin", password => "$dbpw", ); ### main ### my $i = 0; my $total = 1500; # Set Loopcount #while (1) # runs in a continuous loop until ($i > $total) { my @evtypes = ('sys', 'mls', 'pagp'); foreach my $eventtype (@evtypes) { my $index = rand @priorities; my $pri = $priorities[$index]; my $index = rand @priorities; my $lvl = $priorities[$index]; my $index = rand @facilities; my $fac = $facilities[$index]; my $index = rand @devicelist; my $devlist = $devicelist[$index]; my $curr_fakeevent = get_rand_event ($eventtype); my $YMDHMS = strftime "%Y-%m-%d %H:%M:%S", localtime; my $HOST = "$devlist"; my $FACILITY = "$fac"; my $PRIORITY = "$pri"; my $LEVEL = "$lvl"; my $TAG = "Tag"; my $PRG = "DBGen"; my $MSG = "$curr_fakeevent"; $mysql->query(qq{ INSERT INTO $table (host, facility, priority, level, tag, fo, program, msg) VALUES ( '$HOST', '$FACILITY', '$PRIORITY', '$LEVEL', '$TAG', '$YMDHMS', '$PRG', '$PRG: $MSG' ) }); print "\n\nHost: $HOST\nFacility: $FACILITY\nPriority: $PRIORITY\nLevel: $LEVEL\nTag: $TAG\nYMDHMS: $YMDHMS\nProgram: $PRG\nMessage: $PRG: $MSG \n"; printf "Affected row: %d\n", $mysql->get_affected_rows_length; sleep $sleeptime; } print "Loopcount: $i of $total"; $i++; } ### our subs ### sub get_rand_event { my $evttype = shift; $evttype = "sys" if ((!defined($evttype)) or ($evttype eq "")); my @namesarr = @{$mynames{$evttype}}; my @msgarr = @{$myevents{$evttype}}; return ( $namesarr[rand($#namesarr+1)], $msgarr[rand($#msgarr+1)] ); } # vim: ts=4 # vim600: fdm=marker fdl=0 fdc=3
30.169742
191
0.632216
ed0cf895c373164f07a3bf6bf450c718feb1f0a1
12,984
pm
Perl
modules/Bio/EnsEMBL/DBSQL/SimpleFeatureAdaptor.pm
duartemolha/ensembl
378db18977278a066bd54b41e7afcf1db05d7db3
[ "Apache-2.0" ]
null
null
null
modules/Bio/EnsEMBL/DBSQL/SimpleFeatureAdaptor.pm
duartemolha/ensembl
378db18977278a066bd54b41e7afcf1db05d7db3
[ "Apache-2.0" ]
null
null
null
modules/Bio/EnsEMBL/DBSQL/SimpleFeatureAdaptor.pm
duartemolha/ensembl
378db18977278a066bd54b41e7afcf1db05d7db3
[ "Apache-2.0" ]
null
null
null
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2019] EMBL-European Bioinformatics Institute 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. =cut =head1 CONTACT Please email comments or questions to the public Ensembl developers list at <http://lists.ensembl.org/mailman/listinfo/dev>. Questions may also be sent to the Ensembl help desk at <http://www.ensembl.org/Help/Contact>. =cut =head1 NAME Bio::EnsEMBL::DBSQL::SimpleFeatureAdaptor =head1 SYNOPSIS my $registry = 'Bio::EnsEMBL::Registry'; $registry-> load_registry_from_db( ... my $sfa = $registry->get_adaptor('homo sapiens', 'core', 'SimpleFeature'); print ref($sfa), "\n"; my $sf_aref = $sfa->fetch_all; print scalar @$sf_aref, "\n"; =head1 DESCRIPTION Simple Feature Adaptor - database access for simple features =head1 METHODS =cut package Bio::EnsEMBL::DBSQL::SimpleFeatureAdaptor; use vars qw(@ISA); use strict; use Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor; use Bio::EnsEMBL::SimpleFeature; use Bio::EnsEMBL::Utils::Exception qw(throw warning); @ISA = qw(Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor); =head2 store Arg [1] : list of Bio::EnsEMBL::SimpleFeatures @sf the simple features to store in the database Example : $simple_feature_adaptor->store(@simple_feats); Description: Stores a list of simple feature objects in the database Returntype : none Exceptions : thrown if @sf is not defined, if any of the features do not have an attached slice. or if any elements of @sf are not Bio::EnsEMBL::SimpleFeatures Caller : general Status : Stable =cut sub store{ my ($self,@sf) = @_; if( scalar(@sf) == 0 ) { throw("Must call store with list of SimpleFeatures"); } my $sth = $self->prepare ("INSERT INTO simple_feature (seq_region_id, seq_region_start, " . "seq_region_end, seq_region_strand, " . "display_label, analysis_id, score) " . "VALUES (?,?,?,?,?,?,?)"); my $db = $self->db(); my $analysis_adaptor = $db->get_AnalysisAdaptor(); FEATURE: foreach my $sf ( @sf ) { if( !ref $sf || !$sf->isa("Bio::EnsEMBL::SimpleFeature") ) { throw("SimpleFeature must be an Ensembl SimpleFeature, " . "not a [".ref($sf)."]"); } if($sf->is_stored($db)) { warning("SimpleFeature [".$sf->dbID."] is already stored" . " in this database."); next FEATURE; } if(!defined($sf->analysis)) { throw("An analysis must be attached to the features to be stored."); } #store the analysis if it has not been stored yet if(!$sf->analysis->is_stored($db)) { $analysis_adaptor->store($sf->analysis()); } my $original = $sf; my $seq_region_id; ($sf, $seq_region_id) = $self->_pre_store($sf); $sth->bind_param(1,$seq_region_id,SQL_INTEGER); $sth->bind_param(2,$sf->start,SQL_INTEGER); $sth->bind_param(3,$sf->end,SQL_INTEGER); $sth->bind_param(4,$sf->strand,SQL_TINYINT); $sth->bind_param(5,$sf->display_label,SQL_VARCHAR); $sth->bind_param(6,$sf->analysis->dbID,SQL_INTEGER); $sth->bind_param(7,$sf->score,SQL_DOUBLE); $sth->execute(); $original->dbID($self->last_insert_id('simple_feature_id', undef, 'simple_feature')); $original->adaptor($self); } } =head2 _tables Arg [1] : none Example : none Description: PROTECTED implementation of superclass abstract method returns the names, aliases of the tables to use for queries Returntype : list of listrefs of strings Exceptions : none Caller : internal Status : Stable =cut sub _tables { my $self = shift; return ['simple_feature', 'sf']; } =head2 _columns Arg [1] : none Example : none Description: PROTECTED implementation of superclass abstract method returns a list of columns to use for queries Returntype : list of strings Exceptions : none Caller : internal Status : Stable =cut sub _columns { my $self = shift; return qw( sf.simple_feature_id sf.seq_region_id sf.seq_region_start sf.seq_region_end sf.seq_region_strand sf.display_label sf.analysis_id sf.score ); } =head2 _objs_from_sth Arg [1] : hash reference $hashref Example : none Description: PROTECTED implementation of superclass abstract method. creates SimpleFeatures from an executed DBI statement handle. Returntype : list reference to Bio::EnsEMBL::SimpleFeature objects Exceptions : none Caller : internal Status : Stable =cut sub _objs_from_sth { my ($self, $sth, $mapper, $dest_slice) = @_; # # This code is ugly because an attempt has been made to remove as many # function calls as possible for speed purposes. Thus many caches and # a fair bit of gymnastics is used. # my $sa = $self->db()->get_SliceAdaptor(); my $aa = $self->db()->get_AnalysisAdaptor(); my @features; my %analysis_hash; my %slice_hash; my %sr_name_hash; my %sr_cs_hash; my( $simple_feature_id, $seq_region_id, $seq_region_start, $seq_region_end, $seq_region_strand, $display_label, $analysis_id, $score); $sth->bind_columns(\( $simple_feature_id, $seq_region_id, $seq_region_start, $seq_region_end, $seq_region_strand, $display_label, $analysis_id, $score)); my $dest_slice_start; my $dest_slice_end; my $dest_slice_strand; my $dest_slice_length; my $dest_slice_cs; my $dest_slice_sr_name; my $dest_slice_sr_id; my $asma; if ($dest_slice) { $dest_slice_start = $dest_slice->start(); $dest_slice_end = $dest_slice->end(); $dest_slice_strand = $dest_slice->strand(); $dest_slice_length = $dest_slice->length(); $dest_slice_cs = $dest_slice->coord_system(); $dest_slice_sr_name = $dest_slice->seq_region_name(); $dest_slice_sr_id = $dest_slice->get_seq_region_id(); $asma = $self->db->get_AssemblyMapperAdaptor(); } FEATURE: while($sth->fetch()) { #get the analysis object my $analysis = $analysis_hash{$analysis_id} ||= $aa->fetch_by_dbID($analysis_id); $analysis_hash{$analysis_id} = $analysis; #need to get the internal_seq_region, if present $seq_region_id = $self->get_seq_region_id_internal($seq_region_id); my $slice = $slice_hash{"ID:".$seq_region_id}; if (!$slice) { $slice = $sa->fetch_by_seq_region_id($seq_region_id); $slice_hash{"ID:".$seq_region_id} = $slice; $sr_name_hash{$seq_region_id} = $slice->seq_region_name(); $sr_cs_hash{$seq_region_id} = $slice->coord_system(); } #obtain a mapper if none was defined, but a dest_seq_region was if(!$mapper && $dest_slice && !$dest_slice_cs->equals($slice->coord_system)) { $mapper = $asma->fetch_by_CoordSystems($dest_slice_cs, $slice->coord_system); } my $sr_name = $sr_name_hash{$seq_region_id}; my $sr_cs = $sr_cs_hash{$seq_region_id}; # # remap the feature coordinates to another coord system # if a mapper was provided # if ($mapper) { if (defined $dest_slice && $mapper->isa('Bio::EnsEMBL::ChainedAssemblyMapper') ) { ($seq_region_id, $seq_region_start, $seq_region_end, $seq_region_strand) = $mapper->map($sr_name, $seq_region_start, $seq_region_end, $seq_region_strand, $sr_cs, 1, $dest_slice); } else { ($seq_region_id, $seq_region_start, $seq_region_end, $seq_region_strand) = $mapper->fastmap($sr_name, $seq_region_start, $seq_region_end, $seq_region_strand, $sr_cs); } #skip features that map to gaps or coord system boundaries next FEATURE if (!defined($seq_region_id)); #get a slice in the coord system we just mapped to $slice = $slice_hash{"ID:".$seq_region_id} ||= $sa->fetch_by_seq_region_id($seq_region_id); } # # If a destination slice was provided convert the coords. # if (defined($dest_slice)) { my $seq_region_len = $dest_slice->seq_region_length(); if ( $dest_slice_strand == 1 ) { $seq_region_start = $seq_region_start - $dest_slice_start + 1; $seq_region_end = $seq_region_end - $dest_slice_start + 1; if ( $dest_slice->is_circular ) { # Handle circular chromosomes. if ( $seq_region_start > $seq_region_end ) { # Looking at a feature overlapping the chromosome origin. if ( $seq_region_end > $dest_slice_start ) { # Looking at the region in the beginning of the chromosome $seq_region_start -= $seq_region_len; } if ( $seq_region_end < 0 ) { $seq_region_end += $seq_region_len; } } else { if ($dest_slice_start > $dest_slice_end && $seq_region_end < 0) { # Looking at the region overlapping the chromosome # origin and a feature which is at the beginning of the # chromosome. $seq_region_start += $seq_region_len; $seq_region_end += $seq_region_len; } } } } else { my $start = $dest_slice_end - $seq_region_end + 1; my $end = $dest_slice_end - $seq_region_start + 1; if ($dest_slice->is_circular()) { if ($dest_slice_start > $dest_slice_end) { # slice spans origin or replication if ($seq_region_start >= $dest_slice_start) { $end += $seq_region_len; $start += $seq_region_len if $seq_region_end > $dest_slice_start; } elsif ($seq_region_start <= $dest_slice_end) { # do nothing } elsif ($seq_region_end >= $dest_slice_start) { $start += $seq_region_len; $end += $seq_region_len; } elsif ($seq_region_end <= $dest_slice_end) { $end += $seq_region_len if $end < 0; } elsif ($seq_region_start > $seq_region_end) { $end += $seq_region_len; } } else { if ($seq_region_start <= $dest_slice_end and $seq_region_end >= $dest_slice_start) { # do nothing } elsif ($seq_region_start > $seq_region_end) { if ($seq_region_start <= $dest_slice_end) { $start -= $seq_region_len; } elsif ($seq_region_end >= $dest_slice_start) { $end += $seq_region_len; } } } } $seq_region_start = $start; $seq_region_end = $end; $seq_region_strand *= -1; } ## end else [ if ( $dest_slice_strand...)] # Throw away features off the end of the requested slice or on # different seq_region. if ($seq_region_end < 1 || $seq_region_start > $dest_slice_length || ($dest_slice_sr_id != $seq_region_id)) { next FEATURE; } $slice = $dest_slice; } push( @features, $self->_create_feature_fast( 'Bio::EnsEMBL::SimpleFeature', { 'start' => $seq_region_start, 'end' => $seq_region_end, 'strand' => $seq_region_strand, 'slice' => $slice, 'analysis' => $analysis, 'adaptor' => $self, 'dbID' => $simple_feature_id, 'display_label' => $display_label, 'score' => $score } ) ); } return \@features; } =head2 list_dbIDs Arg [1] : none Example : @feature_ids = @{$simple_feature_adaptor->list_dbIDs()}; Description: Gets an array of internal ids for all simple features in the current db Arg[1] : <optional> int. not 0 for the ids to be sorted by the seq_region. Returntype : list of ints Exceptions : none Caller : ? Status : Stable =cut sub list_dbIDs { my ($self, $ordered) = @_; return $self->_list_dbIDs("simple_feature", undef, $ordered); } 1;
30.550588
112
0.608518
ed202ee1276268ac09ab61a19355671282dbfb8c
2,956
pl
Perl
solve.pl
StefanSchroeder/Jewelbot
57f83804f286ebd43263f8ea163639c2adf418c7
[ "Artistic-2.0" ]
1
2017-03-20T12:01:47.000Z
2017-03-20T12:01:47.000Z
solve.pl
StefanSchroeder/Jewelbot
57f83804f286ebd43263f8ea163639c2adf418c7
[ "Artistic-2.0" ]
null
null
null
solve.pl
StefanSchroeder/Jewelbot
57f83804f286ebd43263f8ea163639c2adf418c7
[ "Artistic-2.0" ]
null
null
null
# This script is part of Jewel-Bot. It solves a puzzle # of NxN letters to find two tiles to swap to get three symbols # in a row. # Author: Stefan Schroeder # #-1 4 3 #0 5 x o o x 1 #1 6 2 # -2-1 0 1 2 3 j # # 7 # o x o # 8 use strict; my $IN; my @a; # Store initial puzzle. warn "# Now reading puzzle from $ARGV[0]\n"; open($IN, "<", $ARGV[0]) or die("FATAL: Cannot open file.\n"); while ( <$IN> ) { chomp; last unless $_; push @a, [ split ]; } close($IN); # store result in extra array. my @r = @a; my $size = scalar @a; my $solution_cnt = 0; my @solutions = (); warn "# Puzzle-Size=$size\n"; foreach( examine_puzzle(\@a) ) { my($b, $a) = split(",", $_); push @solutions, "$b,$a"; } my @a_t = transpose(@a); foreach( examine_puzzle(\@a_t) ) { my($a, $b) = split(",", $_); push @solutions, "$b,$a"; } $solution_cnt and print_solution($solution_cnt) and exit; print "NO SOLUTION"; exit; ################################################## sub print_solution { my $index = shift; my $pick = int(rand($index)); print "$solutions[$pick*2] $solutions[$pick*2+1]\n"; } ################################################## # examine_puzzle check each of the 8 different solutions if any of them # is a hit. sub examine_puzzle { my $a_ref = shift; my @collect = (); foreach my $j ( 0 .. $size-1 ) { foreach my $i ( 0 .. $size-1 ) { push @collect, tryn($a_ref, $i,$j, $i,$j+1, $i ,$j+3, $i,$j+2); # 1 push @collect, tryn($a_ref, $i,$j, $i,$j+1, $i+1,$j+2, $i,$j+2); # 2 push @collect, tryn($a_ref, $i,$j, $i,$j+1, $i-1,$j+2, $i,$j+2); # 3 push @collect, tryn($a_ref, $i,$j, $i,$j+1, $i-1,$j-1, $i,$j-1); # 4 push @collect, tryn($a_ref, $i,$j, $i,$j+1, $i+1,$j-1, $i,$j-1); # 6 push @collect, tryn($a_ref, $i,$j, $i,$j+1, $i, $j-2, $i,$j-1); # 5 push @collect, tryn($a_ref, $i,$j, $i,$j+2, $i+1,$j+1, $i,$j+1); # 7 push @collect, tryn($a_ref, $i,$j, $i,$j+2, $i-1,$j+1, $i,$j+1); # 8 } } return(@collect); } ################################################## sub transpose { my @in = @_; my @out = (); foreach my $j ( 0 .. $size-1 ) { foreach my $i ( 0 .. $size-1 ) { $out[$i][$j] = $in[$j][$i]; } } return(@out); } ################################################## sub tryn { my $a_ref = shift; my ($y1, $x1, $y2, $x2, $y3, $x3, $y4, $x4) = @_; grep {return if $_ < 0} @_; my @a = @$a_ref; if (( $a[$y1][$x1] eq $a[$y2][$x2]) and ( $a[$y1][$x1] eq $a[$y3][$x3])) { warn "## There is a pair ($x1,$y1 - $x2,$y2) and a swapper at ($x3,$y3) target is ($x4,$y4)\n"; $solution_cnt++; return("$x3,$y3", "$x4,$y4"); } return; } ################################################## # for debugging only sub dump_puzzle { my @puzzle = @_; foreach my $i ( 0.. $size-1 ) { foreach my $j ( 0.. $size-1 ) { print STDERR "$puzzle[$i][$j] "; } print STDERR "\n"; } } ##################################################
20.671329
97
0.468877
ed138960feb7be595339951cab4267f19ec71c9e
72
pl
Perl
refactor/tests/ex18.pl
edisonm/pl-tests
4cde1228a13a2862bfda15862790a9c9043dc431
[ "BSD-2-Clause" ]
13
2015-04-10T13:39:12.000Z
2022-01-19T15:06:05.000Z
refactor/tests/ex18.pl
edisonm/pl-tests
4cde1228a13a2862bfda15862790a9c9043dc431
[ "BSD-2-Clause" ]
1
2020-07-20T13:11:14.000Z
2020-07-20T13:11:14.000Z
tests/ex18.pl
edisonm/refactor
88749a139418040df5e80a4c1382241302941bf8
[ "BSD-2-Clause" ]
1
2019-04-11T00:40:08.000Z
2019-04-11T00:40:08.000Z
:- module(ex18, [ex18/1]). ex18(C) :- C=M : H, p(M:H). p(_C).
9
26
0.402778
ed1fd0ad3da03d067bb61d03264a483248902214
1,228
al
Perl
lib/auto/Net/SSLeay/new_x_ctx.al
ajhodges/zap2xml-lambda
5af6b65ca0cb3205aba321a1b586bc2ddf135860
[ "MIT" ]
null
null
null
lib/auto/Net/SSLeay/new_x_ctx.al
ajhodges/zap2xml-lambda
5af6b65ca0cb3205aba321a1b586bc2ddf135860
[ "MIT" ]
null
null
null
lib/auto/Net/SSLeay/new_x_ctx.al
ajhodges/zap2xml-lambda
5af6b65ca0cb3205aba321a1b586bc2ddf135860
[ "MIT" ]
null
null
null
# NOTE: Derived from blib/lib/Net/SSLeay.pm. # Changes made here will be lost when autosplit is run again. # See AutoSplit.pm. package Net::SSLeay; #line 933 "blib/lib/Net/SSLeay.pm (autosplit into blib/lib/auto/Net/SSLeay/new_x_ctx.al)" sub new_x_ctx { if ($ssl_version == 2) { unless (exists &Net::SSLeay::CTX_v2_new) { warn "ssl_version has been set to 2, but this version of OpenSSL has been compiled without SSLv2 support"; return undef; } $ctx = CTX_v2_new(); } elsif ($ssl_version == 3) { $ctx = CTX_v3_new(); } elsif ($ssl_version == 10) { $ctx = CTX_tlsv1_new(); } elsif ($ssl_version == 11) { unless (exists &Net::SSLeay::CTX_tlsv1_1_new) { warn "ssl_version has been set to 11, but this version of OpenSSL has been compiled without TLSv1.1 support"; return undef; } $ctx = CTX_tlsv1_1_new; } elsif ($ssl_version == 12) { unless (exists &Net::SSLeay::CTX_tlsv1_2_new) { warn "ssl_version has been set to 12, but this version of OpenSSL has been compiled without TLSv1.2 support"; return undef; } $ctx = CTX_tlsv1_2_new; } else { $ctx = CTX_new(); } return $ctx; } # end of Net::SSLeay::new_x_ctx 1;
33.189189
114
0.649023
73d65c5f460c4266147af895a37a8a9b18accbc7
605
pl
Perl
external/win_perl/lib/unicore/lib/Dep/Y.pl
phixion/l0phtcrack
48ee2f711134e178dbedbd925640f6b3b663fbb5
[ "Apache-2.0", "MIT" ]
2
2021-10-20T00:25:39.000Z
2021-11-08T12:52:42.000Z
external/win_perl/lib/unicore/lib/Dep/Y.pl
Brute-f0rce/l0phtcrack
25f681c07828e5e68e0dd788d84cc13c154aed3d
[ "Apache-2.0", "MIT" ]
null
null
null
external/win_perl/lib/unicore/lib/Dep/Y.pl
Brute-f0rce/l0phtcrack
25f681c07828e5e68e0dd788d84cc13c154aed3d
[ "Apache-2.0", "MIT" ]
1
2022-03-14T06:41:16.000Z
2022-03-14T06:41:16.000Z
# !!!!!!! DO NOT EDIT THIS FILE !!!!!!! # This file is machine-generated by ..\lib\unicore\mktables from the Unicode # database, Version 9.0.0. Any changes made here will be lost! # !!!!!!! INTERNAL PERL USE ONLY !!!!!!! # This file is for internal use by core Perl only. The format and even the # name or existence of this file are subject to change without notice. Don't # use it directly. Use Unicode::UCD to access the Unicode character data # base. return <<'END'; V16 329 330 1651 1652 3959 3960 3961 3962 6051 6053 8298 8304 9001 9003 917505 917506 END
19.516129
78
0.66281
ed149b350c595fe2828019aa517e44b0b1bc65b2
11,294
pm
Perl
cloud/aws/ebs/mode/volumeio.pm
gourk/centreon-plugins
d1fe91cfe0e89bdcb8737f267657d24b44d9b8d3
[ "Apache-2.0" ]
null
null
null
cloud/aws/ebs/mode/volumeio.pm
gourk/centreon-plugins
d1fe91cfe0e89bdcb8737f267657d24b44d9b8d3
[ "Apache-2.0" ]
null
null
null
cloud/aws/ebs/mode/volumeio.pm
gourk/centreon-plugins
d1fe91cfe0e89bdcb8737f267657d24b44d9b8d3
[ "Apache-2.0" ]
null
null
null
# # Copyright 2020 Centreon (http://www.centreon.com/) # # Centreon is a full-fledged industry-strength solution that meets # the needs in IT infrastructure and application monitoring for # service performance. # # 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. # package cloud::aws::ebs::mode::volumeio; use base qw(centreon::plugins::templates::counter); use strict; use warnings; my %metrics_mapping = ( 'VolumeReadBytes' => { 'output' => 'Volume Read Bytes', 'label' => 'volume-read-bytes', 'nlabel' => { 'absolute' => 'ebs.volume.bytes.read.bytes', 'per_second' => 'ebs.volume.bytes.read.bytespersecond' }, 'unit' => 'B' }, 'VolumeWriteBytes' => { 'output' => 'Volume Write Bytes', 'label' => 'volume-write-bytes', 'nlabel' => { 'absolute' => 'ebs.volume.bytes.write.bytes', 'per_second' => 'ebs.volume.bytes.write.bytespersecond' }, 'unit' => 'B' } ); sub custom_metric_calc { my ($self, %options) = @_; $self->{result_values}->{timeframe} = $options{new_datas}->{$self->{instance} . '_timeframe'}; $self->{result_values}->{value} = $options{new_datas}->{$self->{instance} . '_' . $options{extra_options}->{metric}}; $self->{result_values}->{value_per_sec} = $self->{result_values}->{value} / $self->{result_values}->{timeframe}; $self->{result_values}->{metric} = $options{extra_options}->{metric}; return 0; } sub custom_metric_threshold { my ($self, %options) = @_; my $exit = $self->{perfdata}->threshold_check( value => defined($self->{instance_mode}->{option_results}->{per_sec}) ? $self->{result_values}->{value_per_sec} : $self->{result_values}->{value}, threshold => [ { label => 'critical-' . $metrics_mapping{$self->{result_values}->{metric}}->{label} , exit_litteral => 'critical' }, { label => 'warning-' . $metrics_mapping{$self->{result_values}->{metric}}->{label}, exit_litteral => 'warning' } ] ); return $exit; } sub custom_metric_perfdata { my ($self, %options) = @_; $self->{output}->perfdata_add( instances => $self->{instance}, label => $metrics_mapping{$self->{result_values}->{metric}}->{label}, nlabel => defined($self->{instance_mode}->{option_results}->{per_sec}) ? $metrics_mapping{$self->{result_values}->{metric}}->{nlabel}->{per_second} : $metrics_mapping{$self->{result_values}->{metric}}->{nlabel}->{absolute}, unit => defined($self->{instance_mode}->{option_results}->{per_sec}) ? $metrics_mapping{$self->{result_values}->{metric}}->{unit} . '/s' : $metrics_mapping{$self->{result_values}->{metric}}->{unit}, value => sprintf("%.2f", defined($self->{instance_mode}->{option_results}->{per_sec}) ? $self->{result_values}->{value_per_sec} : $self->{result_values}->{value}), warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $metrics_mapping{$self->{result_values}->{metric}}->{label}), critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $metrics_mapping{$self->{result_values}->{metric}}->{label}), ); } sub custom_metric_output { my ($self, %options) = @_; my $msg = ""; if (defined($self->{instance_mode}->{option_results}->{per_sec})) { my ($value, $unit) = ($metrics_mapping{$self->{result_values}->{metric}}->{unit} eq 'B') ? $self->{perfdata}->change_bytes(value => $self->{result_values}->{value_per_sec}) : ($self->{result_values}->{value_per_sec}, $metrics_mapping{$self->{result_values}->{metric}}->{unit}); $msg = sprintf("%s: %.2f %s", $metrics_mapping{$self->{result_values}->{metric}}->{output}, $value, $unit . '/s'); } else { my ($value, $unit) = ($metrics_mapping{$self->{result_values}->{metric}}->{unit} eq 'B') ? $self->{perfdata}->change_bytes(value => $self->{result_values}->{value}) : ($self->{result_values}->{value}, $metrics_mapping{$self->{result_values}->{metric}}->{unit}); $msg = sprintf("%s: %.2f %s", $metrics_mapping{$self->{result_values}->{metric}}->{output}, $value, $unit); } return $msg; } sub prefix_metric_output { my ($self, %options) = @_; return "'" . $options{instance_value}->{display} . "' "; } sub prefix_statistics_output { my ($self, %options) = @_; return "Statistic '" . $options{instance_value}->{display} . "' Metrics "; } sub long_output { my ($self, %options) = @_; return "AWS EBS Volume'" . $options{instance_value}->{display} . "' "; } sub set_counters { my ($self, %options) = @_; $self->{maps_counters_type} = [ { name => 'metrics', type => 3, cb_prefix_output => 'prefix_metric_output', cb_long_output => 'long_output', message_multiple => 'All EBS metrics are ok', indent_long_output => ' ', group => [ { name => 'statistics', display_long => 1, cb_prefix_output => 'prefix_statistics_output', message_multiple => 'All metrics are ok', type => 1, skipped_code => { -10 => 1 } }, ] } ]; foreach my $metric (keys %metrics_mapping) { my $entry = { label => $metrics_mapping{$metric}->{label}, set => { key_values => [ { name => $metric }, { name => 'timeframe' }, { name => 'display' } ], closure_custom_calc => $self->can('custom_metric_calc'), closure_custom_calc_extra_options => { metric => $metric }, closure_custom_output => $self->can('custom_metric_output'), closure_custom_perfdata => $self->can('custom_metric_perfdata'), closure_custom_threshold_check => $self->can('custom_metric_threshold') } }; push @{$self->{maps_counters}->{statistics}}, $entry; } } sub new { my ($class, %options) = @_; my $self = $class->SUPER::new(package => __PACKAGE__, %options, force_new_perfdata => 1); bless $self, $class; $options{options}->add_options(arguments => { 'volume-id:s@' => { name => 'volume_id' }, 'per-sec' => { name => 'per_sec' }, 'filter-metric:s' => { name => 'filter_metric' } }); return $self; } sub check_options { my ($self, %options) = @_; $self->SUPER::check_options(%options); if (!defined($self->{option_results}->{volume_id}) || $self->{option_results}->{volume_id} eq '') { $self->{output}->add_option_msg(short_msg => "Need to specify --volumeid option."); $self->{output}->option_exit(); }; foreach my $instance (@{$self->{option_results}->{volume_id}}) { if ($instance ne '') { push @{$self->{aws_instance}}, $instance; }; } $self->{aws_timeframe} = defined($self->{option_results}->{timeframe}) ? $self->{option_results}->{timeframe} : 600; $self->{aws_period} = defined($self->{option_results}->{period}) ? $self->{option_results}->{period} : 60; $self->{aws_statistics} = ['Average']; if (defined($self->{option_results}->{statistic})) { $self->{aws_statistics} = []; foreach my $stat (@{$self->{option_results}->{statistic}}) { if ($stat ne '') { push @{$self->{aws_statistics}}, ucfirst(lc($stat)); } } }; foreach my $metric (keys %metrics_mapping) { next if (defined($self->{option_results}->{filter_metric}) && $self->{option_results}->{filter_metric} ne '' && $metric !~ /$self->{option_results}->{filter_metric}/); push @{$self->{aws_metrics}}, $metric; }; } sub manage_selection { my ($self, %options) = @_; my %metric_results; foreach my $instance (@{$self->{aws_instance}}) { $metric_results{$instance} = $options{custom}->cloudwatch_get_metrics( region => $self->{option_results}->{region}, namespace => 'AWS/EBS', dimensions => [ { Name => 'VolumeId', Value => $instance } ], metrics => $self->{aws_metrics}, statistics => $self->{aws_statistics}, timeframe => $self->{aws_timeframe}, period => $self->{aws_period}, ); foreach my $metric (@{$self->{aws_metrics}}) { foreach my $statistic (@{$self->{aws_statistics}}) { next if (!defined($metric_results{$instance}->{$metric}->{lc($statistic)}) && !defined($self->{option_results}->{zeroed})); $self->{metrics}->{$instance}->{display} = $instance; $self->{metrics}->{$instance}->{statistics}->{lc($statistic)}->{display} = $statistic; $self->{metrics}->{$instance}->{statistics}->{lc($statistic)}->{timeframe} = $self->{aws_timeframe}; $self->{metrics}->{$instance}->{statistics}->{lc($statistic)}->{$metric} = defined($metric_results{$instance}->{$metric}->{lc($statistic)}) ? $metric_results{$instance}->{$metric}->{lc($statistic)} : 0; } } } if (scalar(keys %{$self->{metrics}}) <= 0) { $self->{output}->add_option_msg(short_msg => 'No metrics. Check your options or use --zeroed option to set 0 on undefined values'); $self->{output}->option_exit(); } } 1; __END__ =head1 MODE Check Amazon Elastic Block Store volumes IO usage. Example: perl centreon_plugins.pl --plugin=cloud::aws::ebs::plugin --custommode=awscli --mode=volumeio --region='eu-west-1' --volumeid='vol-1234abcd' --warning-write-bytes='100000' --critical-write-bytes='200000' --warning --verbose See 'https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using_cloudwatch_ebs.html' for more information. =over 8 =item B<--volumeid> Set the VolumeId (Required). =item B<--filter-metric> Filter on a specific metric. Can be: VolumeReadBytes, VolumeWriteBytes =item B<--warning-$metric$> Warning thresholds ($metric$ can be: 'volume-read-bytes', 'volume-write-bytes'). =item B<--critical-$metric$> Critical thresholds ($metric$ can be: 'volume-read-bytes', 'volume-write-bytes'). =item B<--per-sec> Change the data to be unit/sec. =back =cut
40.049645
161
0.567558
73d1b2e63e308c0e02a3ed48f3dba4644239c44e
73,382
pl
Perl
crypto/aes/asm/bsaes-x86_64.pl
BPLSNico/openssl
f8f686ec1cda6a077ec9d5c2ab540cf202059279
[ "OpenSSL" ]
null
null
null
crypto/aes/asm/bsaes-x86_64.pl
BPLSNico/openssl
f8f686ec1cda6a077ec9d5c2ab540cf202059279
[ "OpenSSL" ]
null
null
null
crypto/aes/asm/bsaes-x86_64.pl
BPLSNico/openssl
f8f686ec1cda6a077ec9d5c2ab540cf202059279
[ "OpenSSL" ]
null
null
null
#! /usr/bin/env perl # Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved. # # Licensed under the OpenSSL license (the "License"). You may not use # this file except in compliance with the License. You can obtain a copy # in the file LICENSE in the source distribution or at # https://www.openssl.org/source/license.html ################################################################### ### AES-128 [originally in CTR mode] ### ### bitsliced implementation for Intel Core 2 processors ### ### requires support of SSE extensions up to SSSE3 ### ### Author: Emilia Käsper and Peter Schwabe ### ### Date: 2009-03-19 ### ### Public domain ### ### ### ### See http://homes.esat.kuleuven.be/~ekasper/#software for ### ### further information. ### ################################################################### # # September 2011. # # Started as transliteration to "perlasm" the original code has # undergone following changes: # # - code was made position-independent; # - rounds were folded into a loop resulting in >5x size reduction # from 12.5KB to 2.2KB; # - above was possibile thanks to mixcolumns() modification that # allowed to feed its output back to aesenc[last], this was # achieved at cost of two additional inter-registers moves; # - some instruction reordering and interleaving; # - this module doesn't implement key setup subroutine, instead it # relies on conversion of "conventional" key schedule as returned # by AES_set_encrypt_key (see discussion below); # - first and last round keys are treated differently, which allowed # to skip one shiftrows(), reduce bit-sliced key schedule and # speed-up conversion by 22%; # - support for 192- and 256-bit keys was added; # # Resulting performance in CPU cycles spent to encrypt one byte out # of 4096-byte buffer with 128-bit key is: # # Emilia's this(*) difference # # Core 2 9.30 8.69 +7% # Nehalem(**) 7.63 6.88 +11% # Atom 17.1 16.4 +4% # Silvermont - 12.9 # # (*) Comparison is not completely fair, because "this" is ECB, # i.e. no extra processing such as counter values calculation # and xor-ing input as in Emilia's CTR implementation is # performed. However, the CTR calculations stand for not more # than 1% of total time, so comparison is *rather* fair. # # (**) Results were collected on Westmere, which is considered to # be equivalent to Nehalem for this code. # # As for key schedule conversion subroutine. Interface to OpenSSL # relies on per-invocation on-the-fly conversion. This naturally # has impact on performance, especially for short inputs. Conversion # time in CPU cycles and its ratio to CPU cycles spent in 8x block # function is: # # conversion conversion/8x block # Core 2 240 0.22 # Nehalem 180 0.20 # Atom 430 0.20 # # The ratio values mean that 128-byte blocks will be processed # 16-18% slower, 256-byte blocks - 9-10%, 384-byte blocks - 6-7%, # etc. Then keep in mind that input sizes not divisible by 128 are # *effectively* slower, especially shortest ones, e.g. consecutive # 144-byte blocks are processed 44% slower than one would expect, # 272 - 29%, 400 - 22%, etc. Yet, despite all these "shortcomings" # it's still faster than ["hyper-threading-safe" code path in] # aes-x86_64.pl on all lengths above 64 bytes... # # October 2011. # # Add decryption procedure. Performance in CPU cycles spent to decrypt # one byte out of 4096-byte buffer with 128-bit key is: # # Core 2 9.98 # Nehalem 7.80 # Atom 17.9 # Silvermont 14.0 # # November 2011. # # Add bsaes_xts_[en|de]crypt. Less-than-80-bytes-block performance is # suboptimal, but XTS is meant to be used with larger blocks... # # <appro@openssl.org> $flavour = shift; $output = shift; if ($flavour =~ /\./) { $output = $flavour; undef $flavour; } $win64=0; $win64=1 if ($flavour =~ /[nm]asm|mingw64/ || $output =~ /\.asm$/); $0 =~ m/(.*[\/\\])[^\/\\]+$/; $dir=$1; ( $xlate="${dir}x86_64-xlate.pl" and -f $xlate ) or ( $xlate="${dir}../../perlasm/x86_64-xlate.pl" and -f $xlate) or die "can't locate x86_64-xlate.pl"; open OUT,"| \"$^X\" $xlate $flavour $output"; *STDOUT=*OUT; my ($inp,$out,$len,$key,$ivp)=("%rdi","%rsi","%rdx","%rcx"); my @XMM=map("%xmm$_",(15,0..14)); # best on Atom, +10% over (0..15) my $ecb=0; # suppress unreferenced ECB subroutines, spare some space... { my ($key,$rounds,$const)=("%rax","%r10d","%r11"); sub Sbox { # input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb # output in lsb > [b0, b1, b4, b6, b3, b7, b2, b5] < msb my @b=@_[0..7]; my @t=@_[8..11]; my @s=@_[12..15]; &InBasisChange (@b); &Inv_GF256 (@b[6,5,0,3,7,1,4,2],@t,@s); &OutBasisChange (@b[7,1,4,2,6,5,0,3]); } sub InBasisChange { # input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb # output in lsb > [b6, b5, b0, b3, b7, b1, b4, b2] < msb my @b=@_[0..7]; $code.=<<___; pxor @b[6], @b[5] pxor @b[1], @b[2] pxor @b[0], @b[3] pxor @b[2], @b[6] pxor @b[0], @b[5] pxor @b[3], @b[6] pxor @b[7], @b[3] pxor @b[5], @b[7] pxor @b[4], @b[3] pxor @b[5], @b[4] pxor @b[1], @b[3] pxor @b[7], @b[2] pxor @b[5], @b[1] ___ } sub OutBasisChange { # input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb # output in lsb > [b6, b1, b2, b4, b7, b0, b3, b5] < msb my @b=@_[0..7]; $code.=<<___; pxor @b[6], @b[0] pxor @b[4], @b[1] pxor @b[0], @b[2] pxor @b[6], @b[4] pxor @b[1], @b[6] pxor @b[5], @b[1] pxor @b[3], @b[5] pxor @b[7], @b[3] pxor @b[5], @b[7] pxor @b[5], @b[2] pxor @b[7], @b[4] ___ } sub InvSbox { # input in lsb > [b0, b1, b2, b3, b4, b5, b6, b7] < msb # output in lsb > [b0, b1, b6, b4, b2, b7, b3, b5] < msb my @b=@_[0..7]; my @t=@_[8..11]; my @s=@_[12..15]; &InvInBasisChange (@b); &Inv_GF256 (@b[5,1,2,6,3,7,0,4],@t,@s); &InvOutBasisChange (@b[3,7,0,4,5,1,2,6]); } sub InvInBasisChange { # OutBasisChange in reverse my @b=@_[5,1,2,6,3,7,0,4]; $code.=<<___ pxor @b[7], @b[4] pxor @b[5], @b[7] pxor @b[5], @b[2] pxor @b[7], @b[3] pxor @b[3], @b[5] pxor @b[5], @b[1] pxor @b[1], @b[6] pxor @b[0], @b[2] pxor @b[6], @b[4] pxor @b[6], @b[0] pxor @b[4], @b[1] ___ } sub InvOutBasisChange { # InBasisChange in reverse my @b=@_[2,5,7,3,6,1,0,4]; $code.=<<___; pxor @b[5], @b[1] pxor @b[7], @b[2] pxor @b[1], @b[3] pxor @b[5], @b[4] pxor @b[5], @b[7] pxor @b[4], @b[3] pxor @b[0], @b[5] pxor @b[7], @b[3] pxor @b[2], @b[6] pxor @b[1], @b[2] pxor @b[3], @b[6] pxor @b[0], @b[3] pxor @b[6], @b[5] ___ } sub Mul_GF4 { #;************************************************************* #;* Mul_GF4: Input x0-x1,y0-y1 Output x0-x1 Temp t0 (8) * #;************************************************************* my ($x0,$x1,$y0,$y1,$t0)=@_; $code.=<<___; movdqa $y0, $t0 pxor $y1, $t0 pand $x0, $t0 pxor $x1, $x0 pand $y0, $x1 pand $y1, $x0 pxor $x1, $x0 pxor $t0, $x1 ___ } sub Mul_GF4_N { # not used, see next subroutine # multiply and scale by N my ($x0,$x1,$y0,$y1,$t0)=@_; $code.=<<___; movdqa $y0, $t0 pxor $y1, $t0 pand $x0, $t0 pxor $x1, $x0 pand $y0, $x1 pand $y1, $x0 pxor $x0, $x1 pxor $t0, $x0 ___ } sub Mul_GF4_N_GF4 { # interleaved Mul_GF4_N and Mul_GF4 my ($x0,$x1,$y0,$y1,$t0, $x2,$x3,$y2,$y3,$t1)=@_; $code.=<<___; movdqa $y0, $t0 movdqa $y2, $t1 pxor $y1, $t0 pxor $y3, $t1 pand $x0, $t0 pand $x2, $t1 pxor $x1, $x0 pxor $x3, $x2 pand $y0, $x1 pand $y2, $x3 pand $y1, $x0 pand $y3, $x2 pxor $x0, $x1 pxor $x3, $x2 pxor $t0, $x0 pxor $t1, $x3 ___ } sub Mul_GF16_2 { my @x=@_[0..7]; my @y=@_[8..11]; my @t=@_[12..15]; $code.=<<___; movdqa @x[0], @t[0] movdqa @x[1], @t[1] ___ &Mul_GF4 (@x[0], @x[1], @y[0], @y[1], @t[2]); $code.=<<___; pxor @x[2], @t[0] pxor @x[3], @t[1] pxor @y[2], @y[0] pxor @y[3], @y[1] ___ Mul_GF4_N_GF4 (@t[0], @t[1], @y[0], @y[1], @t[3], @x[2], @x[3], @y[2], @y[3], @t[2]); $code.=<<___; pxor @t[0], @x[0] pxor @t[0], @x[2] pxor @t[1], @x[1] pxor @t[1], @x[3] movdqa @x[4], @t[0] movdqa @x[5], @t[1] pxor @x[6], @t[0] pxor @x[7], @t[1] ___ &Mul_GF4_N_GF4 (@t[0], @t[1], @y[0], @y[1], @t[3], @x[6], @x[7], @y[2], @y[3], @t[2]); $code.=<<___; pxor @y[2], @y[0] pxor @y[3], @y[1] ___ &Mul_GF4 (@x[4], @x[5], @y[0], @y[1], @t[3]); $code.=<<___; pxor @t[0], @x[4] pxor @t[0], @x[6] pxor @t[1], @x[5] pxor @t[1], @x[7] ___ } sub Inv_GF256 { #;******************************************************************** #;* Inv_GF256: Input x0-x7 Output x0-x7 Temp t0-t3,s0-s3 (144) * #;******************************************************************** my @x=@_[0..7]; my @t=@_[8..11]; my @s=@_[12..15]; # direct optimizations from hardware $code.=<<___; movdqa @x[4], @t[3] movdqa @x[5], @t[2] movdqa @x[1], @t[1] movdqa @x[7], @s[1] movdqa @x[0], @s[0] pxor @x[6], @t[3] pxor @x[7], @t[2] pxor @x[3], @t[1] movdqa @t[3], @s[2] pxor @x[6], @s[1] movdqa @t[2], @t[0] pxor @x[2], @s[0] movdqa @t[3], @s[3] por @t[1], @t[2] por @s[0], @t[3] pxor @t[0], @s[3] pand @s[0], @s[2] pxor @t[1], @s[0] pand @t[1], @t[0] pand @s[0], @s[3] movdqa @x[3], @s[0] pxor @x[2], @s[0] pand @s[0], @s[1] pxor @s[1], @t[3] pxor @s[1], @t[2] movdqa @x[4], @s[1] movdqa @x[1], @s[0] pxor @x[5], @s[1] pxor @x[0], @s[0] movdqa @s[1], @t[1] pand @s[0], @s[1] por @s[0], @t[1] pxor @s[1], @t[0] pxor @s[3], @t[3] pxor @s[2], @t[2] pxor @s[3], @t[1] movdqa @x[7], @s[0] pxor @s[2], @t[0] movdqa @x[6], @s[1] pxor @s[2], @t[1] movdqa @x[5], @s[2] pand @x[3], @s[0] movdqa @x[4], @s[3] pand @x[2], @s[1] pand @x[1], @s[2] por @x[0], @s[3] pxor @s[0], @t[3] pxor @s[1], @t[2] pxor @s[2], @t[1] pxor @s[3], @t[0] #Inv_GF16 \t0, \t1, \t2, \t3, \s0, \s1, \s2, \s3 # new smaller inversion movdqa @t[3], @s[0] pand @t[1], @t[3] pxor @t[2], @s[0] movdqa @t[0], @s[2] movdqa @s[0], @s[3] pxor @t[3], @s[2] pand @s[2], @s[3] movdqa @t[1], @s[1] pxor @t[2], @s[3] pxor @t[0], @s[1] pxor @t[2], @t[3] pand @t[3], @s[1] movdqa @s[2], @t[2] pxor @t[0], @s[1] pxor @s[1], @t[2] pxor @s[1], @t[1] pand @t[0], @t[2] pxor @t[2], @s[2] pxor @t[2], @t[1] pand @s[3], @s[2] pxor @s[0], @s[2] ___ # output in s3, s2, s1, t1 # Mul_GF16_2 \x0, \x1, \x2, \x3, \x4, \x5, \x6, \x7, \t2, \t3, \t0, \t1, \s0, \s1, \s2, \s3 # Mul_GF16_2 \x0, \x1, \x2, \x3, \x4, \x5, \x6, \x7, \s3, \s2, \s1, \t1, \s0, \t0, \t2, \t3 &Mul_GF16_2(@x,@s[3,2,1],@t[1],@s[0],@t[0,2,3]); ### output msb > [x3,x2,x1,x0,x7,x6,x5,x4] < lsb } # AES linear components sub ShiftRows { my @x=@_[0..7]; my $mask=pop; $code.=<<___; pxor 0x00($key),@x[0] pxor 0x10($key),@x[1] pxor 0x20($key),@x[2] pxor 0x30($key),@x[3] pshufb $mask,@x[0] pshufb $mask,@x[1] pxor 0x40($key),@x[4] pxor 0x50($key),@x[5] pshufb $mask,@x[2] pshufb $mask,@x[3] pxor 0x60($key),@x[6] pxor 0x70($key),@x[7] pshufb $mask,@x[4] pshufb $mask,@x[5] pshufb $mask,@x[6] pshufb $mask,@x[7] lea 0x80($key),$key ___ } sub MixColumns { # modified to emit output in order suitable for feeding back to aesenc[last] my @x=@_[0..7]; my @t=@_[8..15]; my $inv=@_[16]; # optional $code.=<<___; pshufd \$0x93, @x[0], @t[0] # x0 <<< 32 pshufd \$0x93, @x[1], @t[1] pxor @t[0], @x[0] # x0 ^ (x0 <<< 32) pshufd \$0x93, @x[2], @t[2] pxor @t[1], @x[1] pshufd \$0x93, @x[3], @t[3] pxor @t[2], @x[2] pshufd \$0x93, @x[4], @t[4] pxor @t[3], @x[3] pshufd \$0x93, @x[5], @t[5] pxor @t[4], @x[4] pshufd \$0x93, @x[6], @t[6] pxor @t[5], @x[5] pshufd \$0x93, @x[7], @t[7] pxor @t[6], @x[6] pxor @t[7], @x[7] pxor @x[0], @t[1] pxor @x[7], @t[0] pxor @x[7], @t[1] pshufd \$0x4E, @x[0], @x[0] # (x0 ^ (x0 <<< 32)) <<< 64) pxor @x[1], @t[2] pshufd \$0x4E, @x[1], @x[1] pxor @x[4], @t[5] pxor @t[0], @x[0] pxor @x[5], @t[6] pxor @t[1], @x[1] pxor @x[3], @t[4] pshufd \$0x4E, @x[4], @t[0] pxor @x[6], @t[7] pshufd \$0x4E, @x[5], @t[1] pxor @x[2], @t[3] pshufd \$0x4E, @x[3], @x[4] pxor @x[7], @t[3] pshufd \$0x4E, @x[7], @x[5] pxor @x[7], @t[4] pshufd \$0x4E, @x[6], @x[3] pxor @t[4], @t[0] pshufd \$0x4E, @x[2], @x[6] pxor @t[5], @t[1] ___ $code.=<<___ if (!$inv); pxor @t[3], @x[4] pxor @t[7], @x[5] pxor @t[6], @x[3] movdqa @t[0], @x[2] pxor @t[2], @x[6] movdqa @t[1], @x[7] ___ $code.=<<___ if ($inv); pxor @x[4], @t[3] pxor @t[7], @x[5] pxor @x[3], @t[6] movdqa @t[0], @x[3] pxor @t[2], @x[6] movdqa @t[6], @x[2] movdqa @t[1], @x[7] movdqa @x[6], @x[4] movdqa @t[3], @x[6] ___ } sub InvMixColumns_orig { my @x=@_[0..7]; my @t=@_[8..15]; $code.=<<___; # multiplication by 0x0e pshufd \$0x93, @x[7], @t[7] movdqa @x[2], @t[2] pxor @x[5], @x[7] # 7 5 pxor @x[5], @x[2] # 2 5 pshufd \$0x93, @x[0], @t[0] movdqa @x[5], @t[5] pxor @x[0], @x[5] # 5 0 [1] pxor @x[1], @x[0] # 0 1 pshufd \$0x93, @x[1], @t[1] pxor @x[2], @x[1] # 1 25 pxor @x[6], @x[0] # 01 6 [2] pxor @x[3], @x[1] # 125 3 [4] pshufd \$0x93, @x[3], @t[3] pxor @x[0], @x[2] # 25 016 [3] pxor @x[7], @x[3] # 3 75 pxor @x[6], @x[7] # 75 6 [0] pshufd \$0x93, @x[6], @t[6] movdqa @x[4], @t[4] pxor @x[4], @x[6] # 6 4 pxor @x[3], @x[4] # 4 375 [6] pxor @x[7], @x[3] # 375 756=36 pxor @t[5], @x[6] # 64 5 [7] pxor @t[2], @x[3] # 36 2 pxor @t[4], @x[3] # 362 4 [5] pshufd \$0x93, @t[5], @t[5] ___ my @y = @x[7,5,0,2,1,3,4,6]; $code.=<<___; # multiplication by 0x0b pxor @y[0], @y[1] pxor @t[0], @y[0] pxor @t[1], @y[1] pshufd \$0x93, @t[2], @t[2] pxor @t[5], @y[0] pxor @t[6], @y[1] pxor @t[7], @y[0] pshufd \$0x93, @t[4], @t[4] pxor @t[6], @t[7] # clobber t[7] pxor @y[0], @y[1] pxor @t[0], @y[3] pshufd \$0x93, @t[0], @t[0] pxor @t[1], @y[2] pxor @t[1], @y[4] pxor @t[2], @y[2] pshufd \$0x93, @t[1], @t[1] pxor @t[2], @y[3] pxor @t[2], @y[5] pxor @t[7], @y[2] pshufd \$0x93, @t[2], @t[2] pxor @t[3], @y[3] pxor @t[3], @y[6] pxor @t[3], @y[4] pshufd \$0x93, @t[3], @t[3] pxor @t[4], @y[7] pxor @t[4], @y[5] pxor @t[7], @y[7] pxor @t[5], @y[3] pxor @t[4], @y[4] pxor @t[5], @t[7] # clobber t[7] even more pxor @t[7], @y[5] pshufd \$0x93, @t[4], @t[4] pxor @t[7], @y[6] pxor @t[7], @y[4] pxor @t[5], @t[7] pshufd \$0x93, @t[5], @t[5] pxor @t[6], @t[7] # restore t[7] # multiplication by 0x0d pxor @y[7], @y[4] pxor @t[4], @y[7] pshufd \$0x93, @t[6], @t[6] pxor @t[0], @y[2] pxor @t[5], @y[7] pxor @t[2], @y[2] pshufd \$0x93, @t[7], @t[7] pxor @y[1], @y[3] pxor @t[1], @y[1] pxor @t[0], @y[0] pxor @t[0], @y[3] pxor @t[5], @y[1] pxor @t[5], @y[0] pxor @t[7], @y[1] pshufd \$0x93, @t[0], @t[0] pxor @t[6], @y[0] pxor @y[1], @y[3] pxor @t[1], @y[4] pshufd \$0x93, @t[1], @t[1] pxor @t[7], @y[7] pxor @t[2], @y[4] pxor @t[2], @y[5] pshufd \$0x93, @t[2], @t[2] pxor @t[6], @y[2] pxor @t[3], @t[6] # clobber t[6] pxor @y[7], @y[4] pxor @t[6], @y[3] pxor @t[6], @y[6] pxor @t[5], @y[5] pxor @t[4], @y[6] pshufd \$0x93, @t[4], @t[4] pxor @t[6], @y[5] pxor @t[7], @y[6] pxor @t[3], @t[6] # restore t[6] pshufd \$0x93, @t[5], @t[5] pshufd \$0x93, @t[6], @t[6] pshufd \$0x93, @t[7], @t[7] pshufd \$0x93, @t[3], @t[3] # multiplication by 0x09 pxor @y[1], @y[4] pxor @y[1], @t[1] # t[1]=y[1] pxor @t[5], @t[0] # clobber t[0] pxor @t[5], @t[1] pxor @t[0], @y[3] pxor @y[0], @t[0] # t[0]=y[0] pxor @t[6], @t[1] pxor @t[7], @t[6] # clobber t[6] pxor @t[1], @y[4] pxor @t[4], @y[7] pxor @y[4], @t[4] # t[4]=y[4] pxor @t[3], @y[6] pxor @y[3], @t[3] # t[3]=y[3] pxor @t[2], @y[5] pxor @y[2], @t[2] # t[2]=y[2] pxor @t[7], @t[3] pxor @y[5], @t[5] # t[5]=y[5] pxor @t[6], @t[2] pxor @t[6], @t[5] pxor @y[6], @t[6] # t[6]=y[6] pxor @y[7], @t[7] # t[7]=y[7] movdqa @t[0],@XMM[0] movdqa @t[1],@XMM[1] movdqa @t[2],@XMM[2] movdqa @t[3],@XMM[3] movdqa @t[4],@XMM[4] movdqa @t[5],@XMM[5] movdqa @t[6],@XMM[6] movdqa @t[7],@XMM[7] ___ } sub InvMixColumns { my @x=@_[0..7]; my @t=@_[8..15]; # Thanks to Jussi Kivilinna for providing pointer to # # | 0e 0b 0d 09 | | 02 03 01 01 | | 05 00 04 00 | # | 09 0e 0b 0d | = | 01 02 03 01 | x | 00 05 00 04 | # | 0d 09 0e 0b | | 01 01 02 03 | | 04 00 05 00 | # | 0b 0d 09 0e | | 03 01 01 02 | | 00 04 00 05 | $code.=<<___; # multiplication by 0x05-0x00-0x04-0x00 pshufd \$0x4E, @x[0], @t[0] pshufd \$0x4E, @x[6], @t[6] pxor @x[0], @t[0] pshufd \$0x4E, @x[7], @t[7] pxor @x[6], @t[6] pshufd \$0x4E, @x[1], @t[1] pxor @x[7], @t[7] pshufd \$0x4E, @x[2], @t[2] pxor @x[1], @t[1] pshufd \$0x4E, @x[3], @t[3] pxor @x[2], @t[2] pxor @t[6], @x[0] pxor @t[6], @x[1] pshufd \$0x4E, @x[4], @t[4] pxor @x[3], @t[3] pxor @t[0], @x[2] pxor @t[1], @x[3] pshufd \$0x4E, @x[5], @t[5] pxor @x[4], @t[4] pxor @t[7], @x[1] pxor @t[2], @x[4] pxor @x[5], @t[5] pxor @t[7], @x[2] pxor @t[6], @x[3] pxor @t[6], @x[4] pxor @t[3], @x[5] pxor @t[4], @x[6] pxor @t[7], @x[4] pxor @t[7], @x[5] pxor @t[5], @x[7] ___ &MixColumns (@x,@t,1); # flipped 2<->3 and 4<->6 } sub aesenc { # not used my @b=@_[0..7]; my @t=@_[8..15]; $code.=<<___; movdqa 0x30($const),@t[0] # .LSR ___ &ShiftRows (@b,@t[0]); &Sbox (@b,@t); &MixColumns (@b[0,1,4,6,3,7,2,5],@t); } sub aesenclast { # not used my @b=@_[0..7]; my @t=@_[8..15]; $code.=<<___; movdqa 0x40($const),@t[0] # .LSRM0 ___ &ShiftRows (@b,@t[0]); &Sbox (@b,@t); $code.=<<___ pxor 0x00($key),@b[0] pxor 0x10($key),@b[1] pxor 0x20($key),@b[4] pxor 0x30($key),@b[6] pxor 0x40($key),@b[3] pxor 0x50($key),@b[7] pxor 0x60($key),@b[2] pxor 0x70($key),@b[5] ___ } sub swapmove { my ($a,$b,$n,$mask,$t)=@_; $code.=<<___; movdqa $b,$t psrlq \$$n,$b pxor $a,$b pand $mask,$b pxor $b,$a psllq \$$n,$b pxor $t,$b ___ } sub swapmove2x { my ($a0,$b0,$a1,$b1,$n,$mask,$t0,$t1)=@_; $code.=<<___; movdqa $b0,$t0 psrlq \$$n,$b0 movdqa $b1,$t1 psrlq \$$n,$b1 pxor $a0,$b0 pxor $a1,$b1 pand $mask,$b0 pand $mask,$b1 pxor $b0,$a0 psllq \$$n,$b0 pxor $b1,$a1 psllq \$$n,$b1 pxor $t0,$b0 pxor $t1,$b1 ___ } sub bitslice { my @x=reverse(@_[0..7]); my ($t0,$t1,$t2,$t3)=@_[8..11]; $code.=<<___; movdqa 0x00($const),$t0 # .LBS0 movdqa 0x10($const),$t1 # .LBS1 ___ &swapmove2x(@x[0,1,2,3],1,$t0,$t2,$t3); &swapmove2x(@x[4,5,6,7],1,$t0,$t2,$t3); $code.=<<___; movdqa 0x20($const),$t0 # .LBS2 ___ &swapmove2x(@x[0,2,1,3],2,$t1,$t2,$t3); &swapmove2x(@x[4,6,5,7],2,$t1,$t2,$t3); &swapmove2x(@x[0,4,1,5],4,$t0,$t2,$t3); &swapmove2x(@x[2,6,3,7],4,$t0,$t2,$t3); } $code.=<<___; .text .extern asm_AES_encrypt .extern asm_AES_decrypt .type _bsaes_encrypt8,\@abi-omnipotent .align 64 _bsaes_encrypt8: lea .LBS0(%rip), $const # constants table movdqa ($key), @XMM[9] # round 0 key lea 0x10($key), $key movdqa 0x50($const), @XMM[8] # .LM0SR pxor @XMM[9], @XMM[0] # xor with round0 key pxor @XMM[9], @XMM[1] pxor @XMM[9], @XMM[2] pxor @XMM[9], @XMM[3] pshufb @XMM[8], @XMM[0] pshufb @XMM[8], @XMM[1] pxor @XMM[9], @XMM[4] pxor @XMM[9], @XMM[5] pshufb @XMM[8], @XMM[2] pshufb @XMM[8], @XMM[3] pxor @XMM[9], @XMM[6] pxor @XMM[9], @XMM[7] pshufb @XMM[8], @XMM[4] pshufb @XMM[8], @XMM[5] pshufb @XMM[8], @XMM[6] pshufb @XMM[8], @XMM[7] _bsaes_encrypt8_bitslice: ___ &bitslice (@XMM[0..7, 8..11]); $code.=<<___; dec $rounds jmp .Lenc_sbox .align 16 .Lenc_loop: ___ &ShiftRows (@XMM[0..7, 8]); $code.=".Lenc_sbox:\n"; &Sbox (@XMM[0..7, 8..15]); $code.=<<___; dec $rounds jl .Lenc_done ___ &MixColumns (@XMM[0,1,4,6,3,7,2,5, 8..15]); $code.=<<___; movdqa 0x30($const), @XMM[8] # .LSR jnz .Lenc_loop movdqa 0x40($const), @XMM[8] # .LSRM0 jmp .Lenc_loop .align 16 .Lenc_done: ___ # output in lsb > [t0, t1, t4, t6, t3, t7, t2, t5] < msb &bitslice (@XMM[0,1,4,6,3,7,2,5, 8..11]); $code.=<<___; movdqa ($key), @XMM[8] # last round key pxor @XMM[8], @XMM[4] pxor @XMM[8], @XMM[6] pxor @XMM[8], @XMM[3] pxor @XMM[8], @XMM[7] pxor @XMM[8], @XMM[2] pxor @XMM[8], @XMM[5] pxor @XMM[8], @XMM[0] pxor @XMM[8], @XMM[1] ret .size _bsaes_encrypt8,.-_bsaes_encrypt8 .type _bsaes_decrypt8,\@abi-omnipotent .align 64 _bsaes_decrypt8: lea .LBS0(%rip), $const # constants table movdqa ($key), @XMM[9] # round 0 key lea 0x10($key), $key movdqa -0x30($const), @XMM[8] # .LM0ISR pxor @XMM[9], @XMM[0] # xor with round0 key pxor @XMM[9], @XMM[1] pxor @XMM[9], @XMM[2] pxor @XMM[9], @XMM[3] pshufb @XMM[8], @XMM[0] pshufb @XMM[8], @XMM[1] pxor @XMM[9], @XMM[4] pxor @XMM[9], @XMM[5] pshufb @XMM[8], @XMM[2] pshufb @XMM[8], @XMM[3] pxor @XMM[9], @XMM[6] pxor @XMM[9], @XMM[7] pshufb @XMM[8], @XMM[4] pshufb @XMM[8], @XMM[5] pshufb @XMM[8], @XMM[6] pshufb @XMM[8], @XMM[7] ___ &bitslice (@XMM[0..7, 8..11]); $code.=<<___; dec $rounds jmp .Ldec_sbox .align 16 .Ldec_loop: ___ &ShiftRows (@XMM[0..7, 8]); $code.=".Ldec_sbox:\n"; &InvSbox (@XMM[0..7, 8..15]); $code.=<<___; dec $rounds jl .Ldec_done ___ &InvMixColumns (@XMM[0,1,6,4,2,7,3,5, 8..15]); $code.=<<___; movdqa -0x10($const), @XMM[8] # .LISR jnz .Ldec_loop movdqa -0x20($const), @XMM[8] # .LISRM0 jmp .Ldec_loop .align 16 .Ldec_done: ___ &bitslice (@XMM[0,1,6,4,2,7,3,5, 8..11]); $code.=<<___; movdqa ($key), @XMM[8] # last round key pxor @XMM[8], @XMM[6] pxor @XMM[8], @XMM[4] pxor @XMM[8], @XMM[2] pxor @XMM[8], @XMM[7] pxor @XMM[8], @XMM[3] pxor @XMM[8], @XMM[5] pxor @XMM[8], @XMM[0] pxor @XMM[8], @XMM[1] ret .size _bsaes_decrypt8,.-_bsaes_decrypt8 ___ } { my ($out,$inp,$rounds,$const)=("%rax","%rcx","%r10d","%r11"); sub bitslice_key { my @x=reverse(@_[0..7]); my ($bs0,$bs1,$bs2,$t2,$t3)=@_[8..12]; &swapmove (@x[0,1],1,$bs0,$t2,$t3); $code.=<<___; #&swapmove(@x[2,3],1,$t0,$t2,$t3); movdqa @x[0], @x[2] movdqa @x[1], @x[3] ___ #&swapmove2x(@x[4,5,6,7],1,$t0,$t2,$t3); &swapmove2x (@x[0,2,1,3],2,$bs1,$t2,$t3); $code.=<<___; #&swapmove2x(@x[4,6,5,7],2,$t1,$t2,$t3); movdqa @x[0], @x[4] movdqa @x[2], @x[6] movdqa @x[1], @x[5] movdqa @x[3], @x[7] ___ &swapmove2x (@x[0,4,1,5],4,$bs2,$t2,$t3); &swapmove2x (@x[2,6,3,7],4,$bs2,$t2,$t3); } $code.=<<___; .type _bsaes_key_convert,\@abi-omnipotent .align 16 _bsaes_key_convert: lea .Lmasks(%rip), $const movdqu ($inp), %xmm7 # load round 0 key lea 0x10($inp), $inp movdqa 0x00($const), %xmm0 # 0x01... movdqa 0x10($const), %xmm1 # 0x02... movdqa 0x20($const), %xmm2 # 0x04... movdqa 0x30($const), %xmm3 # 0x08... movdqa 0x40($const), %xmm4 # .LM0 pcmpeqd %xmm5, %xmm5 # .LNOT movdqu ($inp), %xmm6 # load round 1 key movdqa %xmm7, ($out) # save round 0 key lea 0x10($out), $out dec $rounds jmp .Lkey_loop .align 16 .Lkey_loop: pshufb %xmm4, %xmm6 # .LM0 movdqa %xmm0, %xmm8 movdqa %xmm1, %xmm9 pand %xmm6, %xmm8 pand %xmm6, %xmm9 movdqa %xmm2, %xmm10 pcmpeqb %xmm0, %xmm8 psllq \$4, %xmm0 # 0x10... movdqa %xmm3, %xmm11 pcmpeqb %xmm1, %xmm9 psllq \$4, %xmm1 # 0x20... pand %xmm6, %xmm10 pand %xmm6, %xmm11 movdqa %xmm0, %xmm12 pcmpeqb %xmm2, %xmm10 psllq \$4, %xmm2 # 0x40... movdqa %xmm1, %xmm13 pcmpeqb %xmm3, %xmm11 psllq \$4, %xmm3 # 0x80... movdqa %xmm2, %xmm14 movdqa %xmm3, %xmm15 pxor %xmm5, %xmm8 # "pnot" pxor %xmm5, %xmm9 pand %xmm6, %xmm12 pand %xmm6, %xmm13 movdqa %xmm8, 0x00($out) # write bit-sliced round key pcmpeqb %xmm0, %xmm12 psrlq \$4, %xmm0 # 0x01... movdqa %xmm9, 0x10($out) pcmpeqb %xmm1, %xmm13 psrlq \$4, %xmm1 # 0x02... lea 0x10($inp), $inp pand %xmm6, %xmm14 pand %xmm6, %xmm15 movdqa %xmm10, 0x20($out) pcmpeqb %xmm2, %xmm14 psrlq \$4, %xmm2 # 0x04... movdqa %xmm11, 0x30($out) pcmpeqb %xmm3, %xmm15 psrlq \$4, %xmm3 # 0x08... movdqu ($inp), %xmm6 # load next round key pxor %xmm5, %xmm13 # "pnot" pxor %xmm5, %xmm14 movdqa %xmm12, 0x40($out) movdqa %xmm13, 0x50($out) movdqa %xmm14, 0x60($out) movdqa %xmm15, 0x70($out) lea 0x80($out),$out dec $rounds jnz .Lkey_loop movdqa 0x50($const), %xmm7 # .L63 #movdqa %xmm6, ($out) # don't save last round key ret .size _bsaes_key_convert,.-_bsaes_key_convert ___ } if (0 && !$win64) { # following four functions are unsupported interface # used for benchmarking... $code.=<<___; .globl bsaes_enc_key_convert .type bsaes_enc_key_convert,\@function,2 .align 16 bsaes_enc_key_convert: mov 240($inp),%r10d # pass rounds mov $inp,%rcx # pass key mov $out,%rax # pass key schedule call _bsaes_key_convert pxor %xmm6,%xmm7 # fix up last round key movdqa %xmm7,(%rax) # save last round key ret .size bsaes_enc_key_convert,.-bsaes_enc_key_convert .globl bsaes_encrypt_128 .type bsaes_encrypt_128,\@function,4 .align 16 bsaes_encrypt_128: .Lenc128_loop: movdqu 0x00($inp), @XMM[0] # load input movdqu 0x10($inp), @XMM[1] movdqu 0x20($inp), @XMM[2] movdqu 0x30($inp), @XMM[3] movdqu 0x40($inp), @XMM[4] movdqu 0x50($inp), @XMM[5] movdqu 0x60($inp), @XMM[6] movdqu 0x70($inp), @XMM[7] mov $key, %rax # pass the $key lea 0x80($inp), $inp mov \$10,%r10d call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[4], 0x20($out) movdqu @XMM[6], 0x30($out) movdqu @XMM[3], 0x40($out) movdqu @XMM[7], 0x50($out) movdqu @XMM[2], 0x60($out) movdqu @XMM[5], 0x70($out) lea 0x80($out), $out sub \$0x80,$len ja .Lenc128_loop ret .size bsaes_encrypt_128,.-bsaes_encrypt_128 .globl bsaes_dec_key_convert .type bsaes_dec_key_convert,\@function,2 .align 16 bsaes_dec_key_convert: mov 240($inp),%r10d # pass rounds mov $inp,%rcx # pass key mov $out,%rax # pass key schedule call _bsaes_key_convert pxor ($out),%xmm7 # fix up round 0 key movdqa %xmm6,(%rax) # save last round key movdqa %xmm7,($out) ret .size bsaes_dec_key_convert,.-bsaes_dec_key_convert .globl bsaes_decrypt_128 .type bsaes_decrypt_128,\@function,4 .align 16 bsaes_decrypt_128: .Ldec128_loop: movdqu 0x00($inp), @XMM[0] # load input movdqu 0x10($inp), @XMM[1] movdqu 0x20($inp), @XMM[2] movdqu 0x30($inp), @XMM[3] movdqu 0x40($inp), @XMM[4] movdqu 0x50($inp), @XMM[5] movdqu 0x60($inp), @XMM[6] movdqu 0x70($inp), @XMM[7] mov $key, %rax # pass the $key lea 0x80($inp), $inp mov \$10,%r10d call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) movdqu @XMM[7], 0x50($out) movdqu @XMM[3], 0x60($out) movdqu @XMM[5], 0x70($out) lea 0x80($out), $out sub \$0x80,$len ja .Ldec128_loop ret .size bsaes_decrypt_128,.-bsaes_decrypt_128 ___ } { ###################################################################### # # OpenSSL interface # my ($arg1,$arg2,$arg3,$arg4,$arg5,$arg6)=$win64 ? ("%rcx","%rdx","%r8","%r9","%r10","%r11d") : ("%rdi","%rsi","%rdx","%rcx","%r8","%r9d"); my ($inp,$out,$len,$key)=("%r12","%r13","%r14","%r15"); if ($ecb) { $code.=<<___; .globl bsaes_ecb_encrypt_blocks .type bsaes_ecb_encrypt_blocks,\@abi-omnipotent .align 16 bsaes_ecb_encrypt_blocks: mov %rsp, %rax .Lecb_enc_prologue: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 lea -0x48(%rsp),%rsp ___ $code.=<<___ if ($win64); lea -0xa0(%rsp), %rsp movaps %xmm6, 0x40(%rsp) movaps %xmm7, 0x50(%rsp) movaps %xmm8, 0x60(%rsp) movaps %xmm9, 0x70(%rsp) movaps %xmm10, 0x80(%rsp) movaps %xmm11, 0x90(%rsp) movaps %xmm12, 0xa0(%rsp) movaps %xmm13, 0xb0(%rsp) movaps %xmm14, 0xc0(%rsp) movaps %xmm15, 0xd0(%rsp) .Lecb_enc_body: ___ $code.=<<___; mov %rsp,%rbp # backup %rsp mov 240($arg4),%eax # rounds mov $arg1,$inp # backup arguments mov $arg2,$out mov $arg3,$len mov $arg4,$key cmp \$8,$arg3 jb .Lecb_enc_short mov %eax,%ebx # backup rounds shl \$7,%rax # 128 bytes per inner round key sub \$`128-32`,%rax # size of bit-sliced key schedule sub %rax,%rsp mov %rsp,%rax # pass key schedule mov $key,%rcx # pass key mov %ebx,%r10d # pass rounds call _bsaes_key_convert pxor %xmm6,%xmm7 # fix up last round key movdqa %xmm7,(%rax) # save last round key sub \$8,$len .Lecb_enc_loop: movdqu 0x00($inp), @XMM[0] # load input movdqu 0x10($inp), @XMM[1] movdqu 0x20($inp), @XMM[2] movdqu 0x30($inp), @XMM[3] movdqu 0x40($inp), @XMM[4] movdqu 0x50($inp), @XMM[5] mov %rsp, %rax # pass key schedule movdqu 0x60($inp), @XMM[6] mov %ebx,%r10d # pass rounds movdqu 0x70($inp), @XMM[7] lea 0x80($inp), $inp call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[4], 0x20($out) movdqu @XMM[6], 0x30($out) movdqu @XMM[3], 0x40($out) movdqu @XMM[7], 0x50($out) movdqu @XMM[2], 0x60($out) movdqu @XMM[5], 0x70($out) lea 0x80($out), $out sub \$8,$len jnc .Lecb_enc_loop add \$8,$len jz .Lecb_enc_done movdqu 0x00($inp), @XMM[0] # load input mov %rsp, %rax # pass key schedule mov %ebx,%r10d # pass rounds cmp \$2,$len jb .Lecb_enc_one movdqu 0x10($inp), @XMM[1] je .Lecb_enc_two movdqu 0x20($inp), @XMM[2] cmp \$4,$len jb .Lecb_enc_three movdqu 0x30($inp), @XMM[3] je .Lecb_enc_four movdqu 0x40($inp), @XMM[4] cmp \$6,$len jb .Lecb_enc_five movdqu 0x50($inp), @XMM[5] je .Lecb_enc_six movdqu 0x60($inp), @XMM[6] call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[4], 0x20($out) movdqu @XMM[6], 0x30($out) movdqu @XMM[3], 0x40($out) movdqu @XMM[7], 0x50($out) movdqu @XMM[2], 0x60($out) jmp .Lecb_enc_done .align 16 .Lecb_enc_six: call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[4], 0x20($out) movdqu @XMM[6], 0x30($out) movdqu @XMM[3], 0x40($out) movdqu @XMM[7], 0x50($out) jmp .Lecb_enc_done .align 16 .Lecb_enc_five: call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[4], 0x20($out) movdqu @XMM[6], 0x30($out) movdqu @XMM[3], 0x40($out) jmp .Lecb_enc_done .align 16 .Lecb_enc_four: call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[4], 0x20($out) movdqu @XMM[6], 0x30($out) jmp .Lecb_enc_done .align 16 .Lecb_enc_three: call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[4], 0x20($out) jmp .Lecb_enc_done .align 16 .Lecb_enc_two: call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) jmp .Lecb_enc_done .align 16 .Lecb_enc_one: call _bsaes_encrypt8 movdqu @XMM[0], 0x00($out) # write output jmp .Lecb_enc_done .align 16 .Lecb_enc_short: lea ($inp), $arg1 lea ($out), $arg2 lea ($key), $arg3 call asm_AES_encrypt lea 16($inp), $inp lea 16($out), $out dec $len jnz .Lecb_enc_short .Lecb_enc_done: lea (%rsp),%rax pxor %xmm0, %xmm0 .Lecb_enc_bzero: # wipe key schedule [if any] movdqa %xmm0, 0x00(%rax) movdqa %xmm0, 0x10(%rax) lea 0x20(%rax), %rax cmp %rax, %rbp jb .Lecb_enc_bzero lea (%rbp),%rsp # restore %rsp ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 movaps 0x50(%rbp), %xmm7 movaps 0x60(%rbp), %xmm8 movaps 0x70(%rbp), %xmm9 movaps 0x80(%rbp), %xmm10 movaps 0x90(%rbp), %xmm11 movaps 0xa0(%rbp), %xmm12 movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 lea 0xa0(%rbp), %rsp ___ $code.=<<___; mov 0x48(%rsp), %r15 mov 0x50(%rsp), %r14 mov 0x58(%rsp), %r13 mov 0x60(%rsp), %r12 mov 0x68(%rsp), %rbx mov 0x70(%rsp), %rax lea 0x78(%rsp), %rsp mov %rax, %rbp .Lecb_enc_epilogue: ret .size bsaes_ecb_encrypt_blocks,.-bsaes_ecb_encrypt_blocks .globl bsaes_ecb_decrypt_blocks .type bsaes_ecb_decrypt_blocks,\@abi-omnipotent .align 16 bsaes_ecb_decrypt_blocks: mov %rsp, %rax .Lecb_dec_prologue: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 lea -0x48(%rsp),%rsp ___ $code.=<<___ if ($win64); lea -0xa0(%rsp), %rsp movaps %xmm6, 0x40(%rsp) movaps %xmm7, 0x50(%rsp) movaps %xmm8, 0x60(%rsp) movaps %xmm9, 0x70(%rsp) movaps %xmm10, 0x80(%rsp) movaps %xmm11, 0x90(%rsp) movaps %xmm12, 0xa0(%rsp) movaps %xmm13, 0xb0(%rsp) movaps %xmm14, 0xc0(%rsp) movaps %xmm15, 0xd0(%rsp) .Lecb_dec_body: ___ $code.=<<___; mov %rsp,%rbp # backup %rsp mov 240($arg4),%eax # rounds mov $arg1,$inp # backup arguments mov $arg2,$out mov $arg3,$len mov $arg4,$key cmp \$8,$arg3 jb .Lecb_dec_short mov %eax,%ebx # backup rounds shl \$7,%rax # 128 bytes per inner round key sub \$`128-32`,%rax # size of bit-sliced key schedule sub %rax,%rsp mov %rsp,%rax # pass key schedule mov $key,%rcx # pass key mov %ebx,%r10d # pass rounds call _bsaes_key_convert pxor (%rsp),%xmm7 # fix up 0 round key movdqa %xmm6,(%rax) # save last round key movdqa %xmm7,(%rsp) sub \$8,$len .Lecb_dec_loop: movdqu 0x00($inp), @XMM[0] # load input movdqu 0x10($inp), @XMM[1] movdqu 0x20($inp), @XMM[2] movdqu 0x30($inp), @XMM[3] movdqu 0x40($inp), @XMM[4] movdqu 0x50($inp), @XMM[5] mov %rsp, %rax # pass key schedule movdqu 0x60($inp), @XMM[6] mov %ebx,%r10d # pass rounds movdqu 0x70($inp), @XMM[7] lea 0x80($inp), $inp call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) movdqu @XMM[7], 0x50($out) movdqu @XMM[3], 0x60($out) movdqu @XMM[5], 0x70($out) lea 0x80($out), $out sub \$8,$len jnc .Lecb_dec_loop add \$8,$len jz .Lecb_dec_done movdqu 0x00($inp), @XMM[0] # load input mov %rsp, %rax # pass key schedule mov %ebx,%r10d # pass rounds cmp \$2,$len jb .Lecb_dec_one movdqu 0x10($inp), @XMM[1] je .Lecb_dec_two movdqu 0x20($inp), @XMM[2] cmp \$4,$len jb .Lecb_dec_three movdqu 0x30($inp), @XMM[3] je .Lecb_dec_four movdqu 0x40($inp), @XMM[4] cmp \$6,$len jb .Lecb_dec_five movdqu 0x50($inp), @XMM[5] je .Lecb_dec_six movdqu 0x60($inp), @XMM[6] call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) movdqu @XMM[7], 0x50($out) movdqu @XMM[3], 0x60($out) jmp .Lecb_dec_done .align 16 .Lecb_dec_six: call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) movdqu @XMM[7], 0x50($out) jmp .Lecb_dec_done .align 16 .Lecb_dec_five: call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) jmp .Lecb_dec_done .align 16 .Lecb_dec_four: call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) jmp .Lecb_dec_done .align 16 .Lecb_dec_three: call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) jmp .Lecb_dec_done .align 16 .Lecb_dec_two: call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) jmp .Lecb_dec_done .align 16 .Lecb_dec_one: call _bsaes_decrypt8 movdqu @XMM[0], 0x00($out) # write output jmp .Lecb_dec_done .align 16 .Lecb_dec_short: lea ($inp), $arg1 lea ($out), $arg2 lea ($key), $arg3 call asm_AES_decrypt lea 16($inp), $inp lea 16($out), $out dec $len jnz .Lecb_dec_short .Lecb_dec_done: lea (%rsp),%rax pxor %xmm0, %xmm0 .Lecb_dec_bzero: # wipe key schedule [if any] movdqa %xmm0, 0x00(%rax) movdqa %xmm0, 0x10(%rax) lea 0x20(%rax), %rax cmp %rax, %rbp jb .Lecb_dec_bzero lea (%rbp),%rsp # restore %rsp ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 movaps 0x50(%rbp), %xmm7 movaps 0x60(%rbp), %xmm8 movaps 0x70(%rbp), %xmm9 movaps 0x80(%rbp), %xmm10 movaps 0x90(%rbp), %xmm11 movaps 0xa0(%rbp), %xmm12 movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 lea 0xa0(%rbp), %rsp ___ $code.=<<___; mov 0x48(%rsp), %r15 mov 0x50(%rsp), %r14 mov 0x58(%rsp), %r13 mov 0x60(%rsp), %r12 mov 0x68(%rsp), %rbx mov 0x70(%rsp), %rax lea 0x78(%rsp), %rsp mov %rax, %rbp .Lecb_dec_epilogue: ret .size bsaes_ecb_decrypt_blocks,.-bsaes_ecb_decrypt_blocks ___ } $code.=<<___; .extern asm_AES_cbc_encrypt .globl bsaes_cbc_encrypt .type bsaes_cbc_encrypt,\@abi-omnipotent .align 16 bsaes_cbc_encrypt: ___ $code.=<<___ if ($win64); mov 48(%rsp),$arg6 # pull direction flag ___ $code.=<<___; cmp \$0,$arg6 jne asm_AES_cbc_encrypt cmp \$128,$arg3 jb asm_AES_cbc_encrypt mov %rsp, %rax .Lcbc_dec_prologue: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 lea -0x48(%rsp), %rsp ___ $code.=<<___ if ($win64); mov 0xa0(%rsp),$arg5 # pull ivp lea -0xa0(%rsp), %rsp movaps %xmm6, 0x40(%rsp) movaps %xmm7, 0x50(%rsp) movaps %xmm8, 0x60(%rsp) movaps %xmm9, 0x70(%rsp) movaps %xmm10, 0x80(%rsp) movaps %xmm11, 0x90(%rsp) movaps %xmm12, 0xa0(%rsp) movaps %xmm13, 0xb0(%rsp) movaps %xmm14, 0xc0(%rsp) movaps %xmm15, 0xd0(%rsp) .Lcbc_dec_body: ___ $code.=<<___; mov %rsp, %rbp # backup %rsp mov 240($arg4), %eax # rounds mov $arg1, $inp # backup arguments mov $arg2, $out mov $arg3, $len mov $arg4, $key mov $arg5, %rbx shr \$4, $len # bytes to blocks mov %eax, %edx # rounds shl \$7, %rax # 128 bytes per inner round key sub \$`128-32`, %rax # size of bit-sliced key schedule sub %rax, %rsp mov %rsp, %rax # pass key schedule mov $key, %rcx # pass key mov %edx, %r10d # pass rounds call _bsaes_key_convert pxor (%rsp),%xmm7 # fix up 0 round key movdqa %xmm6,(%rax) # save last round key movdqa %xmm7,(%rsp) movdqu (%rbx), @XMM[15] # load IV sub \$8,$len .Lcbc_dec_loop: movdqu 0x00($inp), @XMM[0] # load input movdqu 0x10($inp), @XMM[1] movdqu 0x20($inp), @XMM[2] movdqu 0x30($inp), @XMM[3] movdqu 0x40($inp), @XMM[4] movdqu 0x50($inp), @XMM[5] mov %rsp, %rax # pass key schedule movdqu 0x60($inp), @XMM[6] mov %edx,%r10d # pass rounds movdqu 0x70($inp), @XMM[7] movdqa @XMM[15], 0x20(%rbp) # put aside IV call _bsaes_decrypt8 pxor 0x20(%rbp), @XMM[0] # ^= IV movdqu 0x00($inp), @XMM[8] # re-load input movdqu 0x10($inp), @XMM[9] pxor @XMM[8], @XMM[1] movdqu 0x20($inp), @XMM[10] pxor @XMM[9], @XMM[6] movdqu 0x30($inp), @XMM[11] pxor @XMM[10], @XMM[4] movdqu 0x40($inp), @XMM[12] pxor @XMM[11], @XMM[2] movdqu 0x50($inp), @XMM[13] pxor @XMM[12], @XMM[7] movdqu 0x60($inp), @XMM[14] pxor @XMM[13], @XMM[3] movdqu 0x70($inp), @XMM[15] # IV pxor @XMM[14], @XMM[5] movdqu @XMM[0], 0x00($out) # write output lea 0x80($inp), $inp movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) movdqu @XMM[7], 0x50($out) movdqu @XMM[3], 0x60($out) movdqu @XMM[5], 0x70($out) lea 0x80($out), $out sub \$8,$len jnc .Lcbc_dec_loop add \$8,$len jz .Lcbc_dec_done movdqu 0x00($inp), @XMM[0] # load input mov %rsp, %rax # pass key schedule mov %edx, %r10d # pass rounds cmp \$2,$len jb .Lcbc_dec_one movdqu 0x10($inp), @XMM[1] je .Lcbc_dec_two movdqu 0x20($inp), @XMM[2] cmp \$4,$len jb .Lcbc_dec_three movdqu 0x30($inp), @XMM[3] je .Lcbc_dec_four movdqu 0x40($inp), @XMM[4] cmp \$6,$len jb .Lcbc_dec_five movdqu 0x50($inp), @XMM[5] je .Lcbc_dec_six movdqu 0x60($inp), @XMM[6] movdqa @XMM[15], 0x20(%rbp) # put aside IV call _bsaes_decrypt8 pxor 0x20(%rbp), @XMM[0] # ^= IV movdqu 0x00($inp), @XMM[8] # re-load input movdqu 0x10($inp), @XMM[9] pxor @XMM[8], @XMM[1] movdqu 0x20($inp), @XMM[10] pxor @XMM[9], @XMM[6] movdqu 0x30($inp), @XMM[11] pxor @XMM[10], @XMM[4] movdqu 0x40($inp), @XMM[12] pxor @XMM[11], @XMM[2] movdqu 0x50($inp), @XMM[13] pxor @XMM[12], @XMM[7] movdqu 0x60($inp), @XMM[15] # IV pxor @XMM[13], @XMM[3] movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) movdqu @XMM[7], 0x50($out) movdqu @XMM[3], 0x60($out) jmp .Lcbc_dec_done .align 16 .Lcbc_dec_six: movdqa @XMM[15], 0x20(%rbp) # put aside IV call _bsaes_decrypt8 pxor 0x20(%rbp), @XMM[0] # ^= IV movdqu 0x00($inp), @XMM[8] # re-load input movdqu 0x10($inp), @XMM[9] pxor @XMM[8], @XMM[1] movdqu 0x20($inp), @XMM[10] pxor @XMM[9], @XMM[6] movdqu 0x30($inp), @XMM[11] pxor @XMM[10], @XMM[4] movdqu 0x40($inp), @XMM[12] pxor @XMM[11], @XMM[2] movdqu 0x50($inp), @XMM[15] # IV pxor @XMM[12], @XMM[7] movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) movdqu @XMM[7], 0x50($out) jmp .Lcbc_dec_done .align 16 .Lcbc_dec_five: movdqa @XMM[15], 0x20(%rbp) # put aside IV call _bsaes_decrypt8 pxor 0x20(%rbp), @XMM[0] # ^= IV movdqu 0x00($inp), @XMM[8] # re-load input movdqu 0x10($inp), @XMM[9] pxor @XMM[8], @XMM[1] movdqu 0x20($inp), @XMM[10] pxor @XMM[9], @XMM[6] movdqu 0x30($inp), @XMM[11] pxor @XMM[10], @XMM[4] movdqu 0x40($inp), @XMM[15] # IV pxor @XMM[11], @XMM[2] movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) jmp .Lcbc_dec_done .align 16 .Lcbc_dec_four: movdqa @XMM[15], 0x20(%rbp) # put aside IV call _bsaes_decrypt8 pxor 0x20(%rbp), @XMM[0] # ^= IV movdqu 0x00($inp), @XMM[8] # re-load input movdqu 0x10($inp), @XMM[9] pxor @XMM[8], @XMM[1] movdqu 0x20($inp), @XMM[10] pxor @XMM[9], @XMM[6] movdqu 0x30($inp), @XMM[15] # IV pxor @XMM[10], @XMM[4] movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) jmp .Lcbc_dec_done .align 16 .Lcbc_dec_three: movdqa @XMM[15], 0x20(%rbp) # put aside IV call _bsaes_decrypt8 pxor 0x20(%rbp), @XMM[0] # ^= IV movdqu 0x00($inp), @XMM[8] # re-load input movdqu 0x10($inp), @XMM[9] pxor @XMM[8], @XMM[1] movdqu 0x20($inp), @XMM[15] # IV pxor @XMM[9], @XMM[6] movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) jmp .Lcbc_dec_done .align 16 .Lcbc_dec_two: movdqa @XMM[15], 0x20(%rbp) # put aside IV call _bsaes_decrypt8 pxor 0x20(%rbp), @XMM[0] # ^= IV movdqu 0x00($inp), @XMM[8] # re-load input movdqu 0x10($inp), @XMM[15] # IV pxor @XMM[8], @XMM[1] movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) jmp .Lcbc_dec_done .align 16 .Lcbc_dec_one: lea ($inp), $arg1 lea 0x20(%rbp), $arg2 # buffer output lea ($key), $arg3 call asm_AES_decrypt # doesn't touch %xmm pxor 0x20(%rbp), @XMM[15] # ^= IV movdqu @XMM[15], ($out) # write output movdqa @XMM[0], @XMM[15] # IV .Lcbc_dec_done: movdqu @XMM[15], (%rbx) # return IV lea (%rsp), %rax pxor %xmm0, %xmm0 .Lcbc_dec_bzero: # wipe key schedule [if any] movdqa %xmm0, 0x00(%rax) movdqa %xmm0, 0x10(%rax) lea 0x20(%rax), %rax cmp %rax, %rbp ja .Lcbc_dec_bzero lea (%rbp),%rsp # restore %rsp ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 movaps 0x50(%rbp), %xmm7 movaps 0x60(%rbp), %xmm8 movaps 0x70(%rbp), %xmm9 movaps 0x80(%rbp), %xmm10 movaps 0x90(%rbp), %xmm11 movaps 0xa0(%rbp), %xmm12 movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 lea 0xa0(%rbp), %rsp ___ $code.=<<___; mov 0x48(%rsp), %r15 mov 0x50(%rsp), %r14 mov 0x58(%rsp), %r13 mov 0x60(%rsp), %r12 mov 0x68(%rsp), %rbx mov 0x70(%rsp), %rax lea 0x78(%rsp), %rsp mov %rax, %rbp .Lcbc_dec_epilogue: ret .size bsaes_cbc_encrypt,.-bsaes_cbc_encrypt .globl bsaes_ctr32_encrypt_blocks .type bsaes_ctr32_encrypt_blocks,\@abi-omnipotent .align 16 bsaes_ctr32_encrypt_blocks: mov %rsp, %rax .Lctr_enc_prologue: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 lea -0x48(%rsp), %rsp ___ $code.=<<___ if ($win64); mov 0xa0(%rsp),$arg5 # pull ivp lea -0xa0(%rsp), %rsp movaps %xmm6, 0x40(%rsp) movaps %xmm7, 0x50(%rsp) movaps %xmm8, 0x60(%rsp) movaps %xmm9, 0x70(%rsp) movaps %xmm10, 0x80(%rsp) movaps %xmm11, 0x90(%rsp) movaps %xmm12, 0xa0(%rsp) movaps %xmm13, 0xb0(%rsp) movaps %xmm14, 0xc0(%rsp) movaps %xmm15, 0xd0(%rsp) .Lctr_enc_body: ___ $code.=<<___; mov %rsp, %rbp # backup %rsp movdqu ($arg5), %xmm0 # load counter mov 240($arg4), %eax # rounds mov $arg1, $inp # backup arguments mov $arg2, $out mov $arg3, $len mov $arg4, $key movdqa %xmm0, 0x20(%rbp) # copy counter cmp \$8, $arg3 jb .Lctr_enc_short mov %eax, %ebx # rounds shl \$7, %rax # 128 bytes per inner round key sub \$`128-32`, %rax # size of bit-sliced key schedule sub %rax, %rsp mov %rsp, %rax # pass key schedule mov $key, %rcx # pass key mov %ebx, %r10d # pass rounds call _bsaes_key_convert pxor %xmm6,%xmm7 # fix up last round key movdqa %xmm7,(%rax) # save last round key movdqa (%rsp), @XMM[9] # load round0 key lea .LADD1(%rip), %r11 movdqa 0x20(%rbp), @XMM[0] # counter copy movdqa -0x20(%r11), @XMM[8] # .LSWPUP pshufb @XMM[8], @XMM[9] # byte swap upper part pshufb @XMM[8], @XMM[0] movdqa @XMM[9], (%rsp) # save adjusted round0 key jmp .Lctr_enc_loop .align 16 .Lctr_enc_loop: movdqa @XMM[0], 0x20(%rbp) # save counter movdqa @XMM[0], @XMM[1] # prepare 8 counter values movdqa @XMM[0], @XMM[2] paddd 0x00(%r11), @XMM[1] # .LADD1 movdqa @XMM[0], @XMM[3] paddd 0x10(%r11), @XMM[2] # .LADD2 movdqa @XMM[0], @XMM[4] paddd 0x20(%r11), @XMM[3] # .LADD3 movdqa @XMM[0], @XMM[5] paddd 0x30(%r11), @XMM[4] # .LADD4 movdqa @XMM[0], @XMM[6] paddd 0x40(%r11), @XMM[5] # .LADD5 movdqa @XMM[0], @XMM[7] paddd 0x50(%r11), @XMM[6] # .LADD6 paddd 0x60(%r11), @XMM[7] # .LADD7 # Borrow prologue from _bsaes_encrypt8 to use the opportunity # to flip byte order in 32-bit counter movdqa (%rsp), @XMM[9] # round 0 key lea 0x10(%rsp), %rax # pass key schedule movdqa -0x10(%r11), @XMM[8] # .LSWPUPM0SR pxor @XMM[9], @XMM[0] # xor with round0 key pxor @XMM[9], @XMM[1] pxor @XMM[9], @XMM[2] pxor @XMM[9], @XMM[3] pshufb @XMM[8], @XMM[0] pshufb @XMM[8], @XMM[1] pxor @XMM[9], @XMM[4] pxor @XMM[9], @XMM[5] pshufb @XMM[8], @XMM[2] pshufb @XMM[8], @XMM[3] pxor @XMM[9], @XMM[6] pxor @XMM[9], @XMM[7] pshufb @XMM[8], @XMM[4] pshufb @XMM[8], @XMM[5] pshufb @XMM[8], @XMM[6] pshufb @XMM[8], @XMM[7] lea .LBS0(%rip), %r11 # constants table mov %ebx,%r10d # pass rounds call _bsaes_encrypt8_bitslice sub \$8,$len jc .Lctr_enc_loop_done movdqu 0x00($inp), @XMM[8] # load input movdqu 0x10($inp), @XMM[9] movdqu 0x20($inp), @XMM[10] movdqu 0x30($inp), @XMM[11] movdqu 0x40($inp), @XMM[12] movdqu 0x50($inp), @XMM[13] movdqu 0x60($inp), @XMM[14] movdqu 0x70($inp), @XMM[15] lea 0x80($inp),$inp pxor @XMM[0], @XMM[8] movdqa 0x20(%rbp), @XMM[0] # load counter pxor @XMM[9], @XMM[1] movdqu @XMM[8], 0x00($out) # write output pxor @XMM[10], @XMM[4] movdqu @XMM[1], 0x10($out) pxor @XMM[11], @XMM[6] movdqu @XMM[4], 0x20($out) pxor @XMM[12], @XMM[3] movdqu @XMM[6], 0x30($out) pxor @XMM[13], @XMM[7] movdqu @XMM[3], 0x40($out) pxor @XMM[14], @XMM[2] movdqu @XMM[7], 0x50($out) pxor @XMM[15], @XMM[5] movdqu @XMM[2], 0x60($out) lea .LADD1(%rip), %r11 movdqu @XMM[5], 0x70($out) lea 0x80($out), $out paddd 0x70(%r11), @XMM[0] # .LADD8 jnz .Lctr_enc_loop jmp .Lctr_enc_done .align 16 .Lctr_enc_loop_done: add \$8, $len movdqu 0x00($inp), @XMM[8] # load input pxor @XMM[8], @XMM[0] movdqu @XMM[0], 0x00($out) # write output cmp \$2,$len jb .Lctr_enc_done movdqu 0x10($inp), @XMM[9] pxor @XMM[9], @XMM[1] movdqu @XMM[1], 0x10($out) je .Lctr_enc_done movdqu 0x20($inp), @XMM[10] pxor @XMM[10], @XMM[4] movdqu @XMM[4], 0x20($out) cmp \$4,$len jb .Lctr_enc_done movdqu 0x30($inp), @XMM[11] pxor @XMM[11], @XMM[6] movdqu @XMM[6], 0x30($out) je .Lctr_enc_done movdqu 0x40($inp), @XMM[12] pxor @XMM[12], @XMM[3] movdqu @XMM[3], 0x40($out) cmp \$6,$len jb .Lctr_enc_done movdqu 0x50($inp), @XMM[13] pxor @XMM[13], @XMM[7] movdqu @XMM[7], 0x50($out) je .Lctr_enc_done movdqu 0x60($inp), @XMM[14] pxor @XMM[14], @XMM[2] movdqu @XMM[2], 0x60($out) jmp .Lctr_enc_done .align 16 .Lctr_enc_short: lea 0x20(%rbp), $arg1 lea 0x30(%rbp), $arg2 lea ($key), $arg3 call asm_AES_encrypt movdqu ($inp), @XMM[1] lea 16($inp), $inp mov 0x2c(%rbp), %eax # load 32-bit counter bswap %eax pxor 0x30(%rbp), @XMM[1] inc %eax # increment movdqu @XMM[1], ($out) bswap %eax lea 16($out), $out mov %eax, 0x2c(%rsp) # save 32-bit counter dec $len jnz .Lctr_enc_short .Lctr_enc_done: lea (%rsp), %rax pxor %xmm0, %xmm0 .Lctr_enc_bzero: # wipe key schedule [if any] movdqa %xmm0, 0x00(%rax) movdqa %xmm0, 0x10(%rax) lea 0x20(%rax), %rax cmp %rax, %rbp ja .Lctr_enc_bzero lea (%rbp),%rsp # restore %rsp ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 movaps 0x50(%rbp), %xmm7 movaps 0x60(%rbp), %xmm8 movaps 0x70(%rbp), %xmm9 movaps 0x80(%rbp), %xmm10 movaps 0x90(%rbp), %xmm11 movaps 0xa0(%rbp), %xmm12 movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 lea 0xa0(%rbp), %rsp ___ $code.=<<___; mov 0x48(%rsp), %r15 mov 0x50(%rsp), %r14 mov 0x58(%rsp), %r13 mov 0x60(%rsp), %r12 mov 0x68(%rsp), %rbx mov 0x70(%rsp), %rax lea 0x78(%rsp), %rsp mov %rax, %rbp .Lctr_enc_epilogue: ret .size bsaes_ctr32_encrypt_blocks,.-bsaes_ctr32_encrypt_blocks ___ ###################################################################### # void bsaes_xts_[en|de]crypt(const char *inp,char *out,size_t len, # const AES_KEY *key1, const AES_KEY *key2, # const unsigned char iv[16]); # my ($twmask,$twres,$twtmp)=@XMM[13..15]; $arg6=~s/d$//; $code.=<<___; .globl bsaes_xts_encrypt .type bsaes_xts_encrypt,\@abi-omnipotent .align 16 bsaes_xts_encrypt: mov %rsp, %rax .Lxts_enc_prologue: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 lea -0x48(%rsp), %rsp ___ $code.=<<___ if ($win64); mov 0xa0(%rsp),$arg5 # pull key2 mov 0xa8(%rsp),$arg6 # pull ivp lea -0xa0(%rsp), %rsp movaps %xmm6, 0x40(%rsp) movaps %xmm7, 0x50(%rsp) movaps %xmm8, 0x60(%rsp) movaps %xmm9, 0x70(%rsp) movaps %xmm10, 0x80(%rsp) movaps %xmm11, 0x90(%rsp) movaps %xmm12, 0xa0(%rsp) movaps %xmm13, 0xb0(%rsp) movaps %xmm14, 0xc0(%rsp) movaps %xmm15, 0xd0(%rsp) .Lxts_enc_body: ___ $code.=<<___; mov %rsp, %rbp # backup %rsp mov $arg1, $inp # backup arguments mov $arg2, $out mov $arg3, $len mov $arg4, $key lea ($arg6), $arg1 lea 0x20(%rbp), $arg2 lea ($arg5), $arg3 call asm_AES_encrypt # generate initial tweak mov 240($key), %eax # rounds mov $len, %rbx # backup $len mov %eax, %edx # rounds shl \$7, %rax # 128 bytes per inner round key sub \$`128-32`, %rax # size of bit-sliced key schedule sub %rax, %rsp mov %rsp, %rax # pass key schedule mov $key, %rcx # pass key mov %edx, %r10d # pass rounds call _bsaes_key_convert pxor %xmm6, %xmm7 # fix up last round key movdqa %xmm7, (%rax) # save last round key and \$-16, $len sub \$0x80, %rsp # place for tweak[8] movdqa 0x20(%rbp), @XMM[7] # initial tweak pxor $twtmp, $twtmp movdqa .Lxts_magic(%rip), $twmask pcmpgtd @XMM[7], $twtmp # broadcast upper bits sub \$0x80, $len jc .Lxts_enc_short jmp .Lxts_enc_loop .align 16 .Lxts_enc_loop: ___ for ($i=0;$i<7;$i++) { $code.=<<___; pshufd \$0x13, $twtmp, $twres pxor $twtmp, $twtmp movdqa @XMM[7], @XMM[$i] movdqa @XMM[7], `0x10*$i`(%rsp)# save tweak[$i] paddq @XMM[7], @XMM[7] # psllq 1,$tweak pand $twmask, $twres # isolate carry and residue pcmpgtd @XMM[7], $twtmp # broadcast upper bits pxor $twres, @XMM[7] ___ $code.=<<___ if ($i>=1); movdqu `0x10*($i-1)`($inp), @XMM[8+$i-1] ___ $code.=<<___ if ($i>=2); pxor @XMM[8+$i-2], @XMM[$i-2]# input[] ^ tweak[] ___ } $code.=<<___; movdqu 0x60($inp), @XMM[8+6] pxor @XMM[8+5], @XMM[5] movdqu 0x70($inp), @XMM[8+7] lea 0x80($inp), $inp movdqa @XMM[7], 0x70(%rsp) pxor @XMM[8+6], @XMM[6] lea 0x80(%rsp), %rax # pass key schedule pxor @XMM[8+7], @XMM[7] mov %edx, %r10d # pass rounds call _bsaes_encrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[4] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[6] movdqu @XMM[4], 0x20($out) pxor 0x40(%rsp), @XMM[3] movdqu @XMM[6], 0x30($out) pxor 0x50(%rsp), @XMM[7] movdqu @XMM[3], 0x40($out) pxor 0x60(%rsp), @XMM[2] movdqu @XMM[7], 0x50($out) pxor 0x70(%rsp), @XMM[5] movdqu @XMM[2], 0x60($out) movdqu @XMM[5], 0x70($out) lea 0x80($out), $out movdqa 0x70(%rsp), @XMM[7] # prepare next iteration tweak pxor $twtmp, $twtmp movdqa .Lxts_magic(%rip), $twmask pcmpgtd @XMM[7], $twtmp pshufd \$0x13, $twtmp, $twres pxor $twtmp, $twtmp paddq @XMM[7], @XMM[7] # psllq 1,$tweak pand $twmask, $twres # isolate carry and residue pcmpgtd @XMM[7], $twtmp # broadcast upper bits pxor $twres, @XMM[7] sub \$0x80,$len jnc .Lxts_enc_loop .Lxts_enc_short: add \$0x80, $len jz .Lxts_enc_done ___ for ($i=0;$i<7;$i++) { $code.=<<___; pshufd \$0x13, $twtmp, $twres pxor $twtmp, $twtmp movdqa @XMM[7], @XMM[$i] movdqa @XMM[7], `0x10*$i`(%rsp)# save tweak[$i] paddq @XMM[7], @XMM[7] # psllq 1,$tweak pand $twmask, $twres # isolate carry and residue pcmpgtd @XMM[7], $twtmp # broadcast upper bits pxor $twres, @XMM[7] ___ $code.=<<___ if ($i>=1); movdqu `0x10*($i-1)`($inp), @XMM[8+$i-1] cmp \$`0x10*$i`,$len je .Lxts_enc_$i ___ $code.=<<___ if ($i>=2); pxor @XMM[8+$i-2], @XMM[$i-2]# input[] ^ tweak[] ___ } $code.=<<___; movdqu 0x60($inp), @XMM[8+6] pxor @XMM[8+5], @XMM[5] movdqa @XMM[7], 0x70(%rsp) lea 0x70($inp), $inp pxor @XMM[8+6], @XMM[6] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_encrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[4] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[6] movdqu @XMM[4], 0x20($out) pxor 0x40(%rsp), @XMM[3] movdqu @XMM[6], 0x30($out) pxor 0x50(%rsp), @XMM[7] movdqu @XMM[3], 0x40($out) pxor 0x60(%rsp), @XMM[2] movdqu @XMM[7], 0x50($out) movdqu @XMM[2], 0x60($out) lea 0x70($out), $out movdqa 0x70(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_enc_done .align 16 .Lxts_enc_6: pxor @XMM[8+4], @XMM[4] lea 0x60($inp), $inp pxor @XMM[8+5], @XMM[5] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_encrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[4] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[6] movdqu @XMM[4], 0x20($out) pxor 0x40(%rsp), @XMM[3] movdqu @XMM[6], 0x30($out) pxor 0x50(%rsp), @XMM[7] movdqu @XMM[3], 0x40($out) movdqu @XMM[7], 0x50($out) lea 0x60($out), $out movdqa 0x60(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_enc_done .align 16 .Lxts_enc_5: pxor @XMM[8+3], @XMM[3] lea 0x50($inp), $inp pxor @XMM[8+4], @XMM[4] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_encrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[4] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[6] movdqu @XMM[4], 0x20($out) pxor 0x40(%rsp), @XMM[3] movdqu @XMM[6], 0x30($out) movdqu @XMM[3], 0x40($out) lea 0x50($out), $out movdqa 0x50(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_enc_done .align 16 .Lxts_enc_4: pxor @XMM[8+2], @XMM[2] lea 0x40($inp), $inp pxor @XMM[8+3], @XMM[3] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_encrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[4] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[6] movdqu @XMM[4], 0x20($out) movdqu @XMM[6], 0x30($out) lea 0x40($out), $out movdqa 0x40(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_enc_done .align 16 .Lxts_enc_3: pxor @XMM[8+1], @XMM[1] lea 0x30($inp), $inp pxor @XMM[8+2], @XMM[2] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_encrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[4] movdqu @XMM[1], 0x10($out) movdqu @XMM[4], 0x20($out) lea 0x30($out), $out movdqa 0x30(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_enc_done .align 16 .Lxts_enc_2: pxor @XMM[8+0], @XMM[0] lea 0x20($inp), $inp pxor @XMM[8+1], @XMM[1] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_encrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) lea 0x20($out), $out movdqa 0x20(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_enc_done .align 16 .Lxts_enc_1: pxor @XMM[0], @XMM[8] lea 0x10($inp), $inp movdqa @XMM[8], 0x20(%rbp) lea 0x20(%rbp), $arg1 lea 0x20(%rbp), $arg2 lea ($key), $arg3 call asm_AES_encrypt # doesn't touch %xmm pxor 0x20(%rbp), @XMM[0] # ^= tweak[] #pxor @XMM[8], @XMM[0] #lea 0x80(%rsp), %rax # pass key schedule #mov %edx, %r10d # pass rounds #call _bsaes_encrypt8 #pxor 0x00(%rsp), @XMM[0] # ^= tweak[] movdqu @XMM[0], 0x00($out) # write output lea 0x10($out), $out movdqa 0x10(%rsp), @XMM[7] # next iteration tweak .Lxts_enc_done: and \$15, %ebx jz .Lxts_enc_ret mov $out, %rdx .Lxts_enc_steal: movzb ($inp), %eax movzb -16(%rdx), %ecx lea 1($inp), $inp mov %al, -16(%rdx) mov %cl, 0(%rdx) lea 1(%rdx), %rdx sub \$1,%ebx jnz .Lxts_enc_steal movdqu -16($out), @XMM[0] lea 0x20(%rbp), $arg1 pxor @XMM[7], @XMM[0] lea 0x20(%rbp), $arg2 movdqa @XMM[0], 0x20(%rbp) lea ($key), $arg3 call asm_AES_encrypt # doesn't touch %xmm pxor 0x20(%rbp), @XMM[7] movdqu @XMM[7], -16($out) .Lxts_enc_ret: lea (%rsp), %rax pxor %xmm0, %xmm0 .Lxts_enc_bzero: # wipe key schedule [if any] movdqa %xmm0, 0x00(%rax) movdqa %xmm0, 0x10(%rax) lea 0x20(%rax), %rax cmp %rax, %rbp ja .Lxts_enc_bzero lea (%rbp),%rsp # restore %rsp ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 movaps 0x50(%rbp), %xmm7 movaps 0x60(%rbp), %xmm8 movaps 0x70(%rbp), %xmm9 movaps 0x80(%rbp), %xmm10 movaps 0x90(%rbp), %xmm11 movaps 0xa0(%rbp), %xmm12 movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 lea 0xa0(%rbp), %rsp ___ $code.=<<___; mov 0x48(%rsp), %r15 mov 0x50(%rsp), %r14 mov 0x58(%rsp), %r13 mov 0x60(%rsp), %r12 mov 0x68(%rsp), %rbx mov 0x70(%rsp), %rax lea 0x78(%rsp), %rsp mov %rax, %rbp .Lxts_enc_epilogue: ret .size bsaes_xts_encrypt,.-bsaes_xts_encrypt .globl bsaes_xts_decrypt .type bsaes_xts_decrypt,\@abi-omnipotent .align 16 bsaes_xts_decrypt: mov %rsp, %rax .Lxts_dec_prologue: push %rbp push %rbx push %r12 push %r13 push %r14 push %r15 lea -0x48(%rsp), %rsp ___ $code.=<<___ if ($win64); mov 0xa0(%rsp),$arg5 # pull key2 mov 0xa8(%rsp),$arg6 # pull ivp lea -0xa0(%rsp), %rsp movaps %xmm6, 0x40(%rsp) movaps %xmm7, 0x50(%rsp) movaps %xmm8, 0x60(%rsp) movaps %xmm9, 0x70(%rsp) movaps %xmm10, 0x80(%rsp) movaps %xmm11, 0x90(%rsp) movaps %xmm12, 0xa0(%rsp) movaps %xmm13, 0xb0(%rsp) movaps %xmm14, 0xc0(%rsp) movaps %xmm15, 0xd0(%rsp) .Lxts_dec_body: ___ $code.=<<___; mov %rsp, %rbp # backup %rsp mov $arg1, $inp # backup arguments mov $arg2, $out mov $arg3, $len mov $arg4, $key lea ($arg6), $arg1 lea 0x20(%rbp), $arg2 lea ($arg5), $arg3 call asm_AES_encrypt # generate initial tweak mov 240($key), %eax # rounds mov $len, %rbx # backup $len mov %eax, %edx # rounds shl \$7, %rax # 128 bytes per inner round key sub \$`128-32`, %rax # size of bit-sliced key schedule sub %rax, %rsp mov %rsp, %rax # pass key schedule mov $key, %rcx # pass key mov %edx, %r10d # pass rounds call _bsaes_key_convert pxor (%rsp), %xmm7 # fix up round 0 key movdqa %xmm6, (%rax) # save last round key movdqa %xmm7, (%rsp) xor %eax, %eax # if ($len%16) len-=16; and \$-16, $len test \$15, %ebx setnz %al shl \$4, %rax sub %rax, $len sub \$0x80, %rsp # place for tweak[8] movdqa 0x20(%rbp), @XMM[7] # initial tweak pxor $twtmp, $twtmp movdqa .Lxts_magic(%rip), $twmask pcmpgtd @XMM[7], $twtmp # broadcast upper bits sub \$0x80, $len jc .Lxts_dec_short jmp .Lxts_dec_loop .align 16 .Lxts_dec_loop: ___ for ($i=0;$i<7;$i++) { $code.=<<___; pshufd \$0x13, $twtmp, $twres pxor $twtmp, $twtmp movdqa @XMM[7], @XMM[$i] movdqa @XMM[7], `0x10*$i`(%rsp)# save tweak[$i] paddq @XMM[7], @XMM[7] # psllq 1,$tweak pand $twmask, $twres # isolate carry and residue pcmpgtd @XMM[7], $twtmp # broadcast upper bits pxor $twres, @XMM[7] ___ $code.=<<___ if ($i>=1); movdqu `0x10*($i-1)`($inp), @XMM[8+$i-1] ___ $code.=<<___ if ($i>=2); pxor @XMM[8+$i-2], @XMM[$i-2]# input[] ^ tweak[] ___ } $code.=<<___; movdqu 0x60($inp), @XMM[8+6] pxor @XMM[8+5], @XMM[5] movdqu 0x70($inp), @XMM[8+7] lea 0x80($inp), $inp movdqa @XMM[7], 0x70(%rsp) pxor @XMM[8+6], @XMM[6] lea 0x80(%rsp), %rax # pass key schedule pxor @XMM[8+7], @XMM[7] mov %edx, %r10d # pass rounds call _bsaes_decrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[6] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[4] movdqu @XMM[6], 0x20($out) pxor 0x40(%rsp), @XMM[2] movdqu @XMM[4], 0x30($out) pxor 0x50(%rsp), @XMM[7] movdqu @XMM[2], 0x40($out) pxor 0x60(%rsp), @XMM[3] movdqu @XMM[7], 0x50($out) pxor 0x70(%rsp), @XMM[5] movdqu @XMM[3], 0x60($out) movdqu @XMM[5], 0x70($out) lea 0x80($out), $out movdqa 0x70(%rsp), @XMM[7] # prepare next iteration tweak pxor $twtmp, $twtmp movdqa .Lxts_magic(%rip), $twmask pcmpgtd @XMM[7], $twtmp pshufd \$0x13, $twtmp, $twres pxor $twtmp, $twtmp paddq @XMM[7], @XMM[7] # psllq 1,$tweak pand $twmask, $twres # isolate carry and residue pcmpgtd @XMM[7], $twtmp # broadcast upper bits pxor $twres, @XMM[7] sub \$0x80,$len jnc .Lxts_dec_loop .Lxts_dec_short: add \$0x80, $len jz .Lxts_dec_done ___ for ($i=0;$i<7;$i++) { $code.=<<___; pshufd \$0x13, $twtmp, $twres pxor $twtmp, $twtmp movdqa @XMM[7], @XMM[$i] movdqa @XMM[7], `0x10*$i`(%rsp)# save tweak[$i] paddq @XMM[7], @XMM[7] # psllq 1,$tweak pand $twmask, $twres # isolate carry and residue pcmpgtd @XMM[7], $twtmp # broadcast upper bits pxor $twres, @XMM[7] ___ $code.=<<___ if ($i>=1); movdqu `0x10*($i-1)`($inp), @XMM[8+$i-1] cmp \$`0x10*$i`,$len je .Lxts_dec_$i ___ $code.=<<___ if ($i>=2); pxor @XMM[8+$i-2], @XMM[$i-2]# input[] ^ tweak[] ___ } $code.=<<___; movdqu 0x60($inp), @XMM[8+6] pxor @XMM[8+5], @XMM[5] movdqa @XMM[7], 0x70(%rsp) lea 0x70($inp), $inp pxor @XMM[8+6], @XMM[6] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_decrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[6] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[4] movdqu @XMM[6], 0x20($out) pxor 0x40(%rsp), @XMM[2] movdqu @XMM[4], 0x30($out) pxor 0x50(%rsp), @XMM[7] movdqu @XMM[2], 0x40($out) pxor 0x60(%rsp), @XMM[3] movdqu @XMM[7], 0x50($out) movdqu @XMM[3], 0x60($out) lea 0x70($out), $out movdqa 0x70(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_dec_done .align 16 .Lxts_dec_6: pxor @XMM[8+4], @XMM[4] lea 0x60($inp), $inp pxor @XMM[8+5], @XMM[5] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_decrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[6] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[4] movdqu @XMM[6], 0x20($out) pxor 0x40(%rsp), @XMM[2] movdqu @XMM[4], 0x30($out) pxor 0x50(%rsp), @XMM[7] movdqu @XMM[2], 0x40($out) movdqu @XMM[7], 0x50($out) lea 0x60($out), $out movdqa 0x60(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_dec_done .align 16 .Lxts_dec_5: pxor @XMM[8+3], @XMM[3] lea 0x50($inp), $inp pxor @XMM[8+4], @XMM[4] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_decrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[6] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[4] movdqu @XMM[6], 0x20($out) pxor 0x40(%rsp), @XMM[2] movdqu @XMM[4], 0x30($out) movdqu @XMM[2], 0x40($out) lea 0x50($out), $out movdqa 0x50(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_dec_done .align 16 .Lxts_dec_4: pxor @XMM[8+2], @XMM[2] lea 0x40($inp), $inp pxor @XMM[8+3], @XMM[3] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_decrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[6] movdqu @XMM[1], 0x10($out) pxor 0x30(%rsp), @XMM[4] movdqu @XMM[6], 0x20($out) movdqu @XMM[4], 0x30($out) lea 0x40($out), $out movdqa 0x40(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_dec_done .align 16 .Lxts_dec_3: pxor @XMM[8+1], @XMM[1] lea 0x30($inp), $inp pxor @XMM[8+2], @XMM[2] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_decrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output pxor 0x20(%rsp), @XMM[6] movdqu @XMM[1], 0x10($out) movdqu @XMM[6], 0x20($out) lea 0x30($out), $out movdqa 0x30(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_dec_done .align 16 .Lxts_dec_2: pxor @XMM[8+0], @XMM[0] lea 0x20($inp), $inp pxor @XMM[8+1], @XMM[1] lea 0x80(%rsp), %rax # pass key schedule mov %edx, %r10d # pass rounds call _bsaes_decrypt8 pxor 0x00(%rsp), @XMM[0] # ^= tweak[] pxor 0x10(%rsp), @XMM[1] movdqu @XMM[0], 0x00($out) # write output movdqu @XMM[1], 0x10($out) lea 0x20($out), $out movdqa 0x20(%rsp), @XMM[7] # next iteration tweak jmp .Lxts_dec_done .align 16 .Lxts_dec_1: pxor @XMM[0], @XMM[8] lea 0x10($inp), $inp movdqa @XMM[8], 0x20(%rbp) lea 0x20(%rbp), $arg1 lea 0x20(%rbp), $arg2 lea ($key), $arg3 call asm_AES_decrypt # doesn't touch %xmm pxor 0x20(%rbp), @XMM[0] # ^= tweak[] #pxor @XMM[8], @XMM[0] #lea 0x80(%rsp), %rax # pass key schedule #mov %edx, %r10d # pass rounds #call _bsaes_decrypt8 #pxor 0x00(%rsp), @XMM[0] # ^= tweak[] movdqu @XMM[0], 0x00($out) # write output lea 0x10($out), $out movdqa 0x10(%rsp), @XMM[7] # next iteration tweak .Lxts_dec_done: and \$15, %ebx jz .Lxts_dec_ret pxor $twtmp, $twtmp movdqa .Lxts_magic(%rip), $twmask pcmpgtd @XMM[7], $twtmp pshufd \$0x13, $twtmp, $twres movdqa @XMM[7], @XMM[6] paddq @XMM[7], @XMM[7] # psllq 1,$tweak pand $twmask, $twres # isolate carry and residue movdqu ($inp), @XMM[0] pxor $twres, @XMM[7] lea 0x20(%rbp), $arg1 pxor @XMM[7], @XMM[0] lea 0x20(%rbp), $arg2 movdqa @XMM[0], 0x20(%rbp) lea ($key), $arg3 call asm_AES_decrypt # doesn't touch %xmm pxor 0x20(%rbp), @XMM[7] mov $out, %rdx movdqu @XMM[7], ($out) .Lxts_dec_steal: movzb 16($inp), %eax movzb (%rdx), %ecx lea 1($inp), $inp mov %al, (%rdx) mov %cl, 16(%rdx) lea 1(%rdx), %rdx sub \$1,%ebx jnz .Lxts_dec_steal movdqu ($out), @XMM[0] lea 0x20(%rbp), $arg1 pxor @XMM[6], @XMM[0] lea 0x20(%rbp), $arg2 movdqa @XMM[0], 0x20(%rbp) lea ($key), $arg3 call asm_AES_decrypt # doesn't touch %xmm pxor 0x20(%rbp), @XMM[6] movdqu @XMM[6], ($out) .Lxts_dec_ret: lea (%rsp), %rax pxor %xmm0, %xmm0 .Lxts_dec_bzero: # wipe key schedule [if any] movdqa %xmm0, 0x00(%rax) movdqa %xmm0, 0x10(%rax) lea 0x20(%rax), %rax cmp %rax, %rbp ja .Lxts_dec_bzero lea (%rbp),%rsp # restore %rsp ___ $code.=<<___ if ($win64); movaps 0x40(%rbp), %xmm6 movaps 0x50(%rbp), %xmm7 movaps 0x60(%rbp), %xmm8 movaps 0x70(%rbp), %xmm9 movaps 0x80(%rbp), %xmm10 movaps 0x90(%rbp), %xmm11 movaps 0xa0(%rbp), %xmm12 movaps 0xb0(%rbp), %xmm13 movaps 0xc0(%rbp), %xmm14 movaps 0xd0(%rbp), %xmm15 lea 0xa0(%rbp), %rsp ___ $code.=<<___; mov 0x48(%rsp), %r15 mov 0x50(%rsp), %r14 mov 0x58(%rsp), %r13 mov 0x60(%rsp), %r12 mov 0x68(%rsp), %rbx mov 0x70(%rsp), %rax lea 0x78(%rsp), %rsp mov %rax, %rbp .Lxts_dec_epilogue: ret .size bsaes_xts_decrypt,.-bsaes_xts_decrypt ___ } $code.=<<___; .type _bsaes_const,\@object .align 64 _bsaes_const: .LM0ISR: # InvShiftRows constants .quad 0x0a0e0206070b0f03, 0x0004080c0d010509 .LISRM0: .quad 0x01040b0e0205080f, 0x0306090c00070a0d .LISR: .quad 0x0504070602010003, 0x0f0e0d0c080b0a09 .LBS0: # bit-slice constants .quad 0x5555555555555555, 0x5555555555555555 .LBS1: .quad 0x3333333333333333, 0x3333333333333333 .LBS2: .quad 0x0f0f0f0f0f0f0f0f, 0x0f0f0f0f0f0f0f0f .LSR: # shiftrows constants .quad 0x0504070600030201, 0x0f0e0d0c0a09080b .LSRM0: .quad 0x0304090e00050a0f, 0x01060b0c0207080d .LM0SR: .quad 0x0a0e02060f03070b, 0x0004080c05090d01 .LSWPUP: # byte-swap upper dword .quad 0x0706050403020100, 0x0c0d0e0f0b0a0908 .LSWPUPM0SR: .quad 0x0a0d02060c03070b, 0x0004080f05090e01 .LADD1: # counter increment constants .quad 0x0000000000000000, 0x0000000100000000 .LADD2: .quad 0x0000000000000000, 0x0000000200000000 .LADD3: .quad 0x0000000000000000, 0x0000000300000000 .LADD4: .quad 0x0000000000000000, 0x0000000400000000 .LADD5: .quad 0x0000000000000000, 0x0000000500000000 .LADD6: .quad 0x0000000000000000, 0x0000000600000000 .LADD7: .quad 0x0000000000000000, 0x0000000700000000 .LADD8: .quad 0x0000000000000000, 0x0000000800000000 .Lxts_magic: .long 0x87,0,1,0 .Lmasks: .quad 0x0101010101010101, 0x0101010101010101 .quad 0x0202020202020202, 0x0202020202020202 .quad 0x0404040404040404, 0x0404040404040404 .quad 0x0808080808080808, 0x0808080808080808 .LM0: .quad 0x02060a0e03070b0f, 0x0004080c0105090d .L63: .quad 0x6363636363636363, 0x6363636363636363 .asciz "Bit-sliced AES for x86_64/SSSE3, Emilia Käsper, Peter Schwabe, Andy Polyakov" .align 64 .size _bsaes_const,.-_bsaes_const ___ # EXCEPTION_DISPOSITION handler (EXCEPTION_RECORD *rec,ULONG64 frame, # CONTEXT *context,DISPATCHER_CONTEXT *disp) if ($win64) { $rec="%rcx"; $frame="%rdx"; $context="%r8"; $disp="%r9"; $code.=<<___; .extern __imp_RtlVirtualUnwind .type se_handler,\@abi-omnipotent .align 16 se_handler: push %rsi push %rdi push %rbx push %rbp push %r12 push %r13 push %r14 push %r15 pushfq sub \$64,%rsp mov 120($context),%rax # pull context->Rax mov 248($context),%rbx # pull context->Rip mov 8($disp),%rsi # disp->ImageBase mov 56($disp),%r11 # disp->HandlerData mov 0(%r11),%r10d # HandlerData[0] lea (%rsi,%r10),%r10 # prologue label cmp %r10,%rbx # context->Rip<prologue label jb .Lin_prologue mov 152($context),%rax # pull context->Rsp mov 4(%r11),%r10d # HandlerData[1] lea (%rsi,%r10),%r10 # epilogue label cmp %r10,%rbx # context->Rip>=epilogue label jae .Lin_prologue mov 160($context),%rax # pull context->Rbp lea 0x40(%rax),%rsi # %xmm save area lea 512($context),%rdi # &context.Xmm6 mov \$20,%ecx # 10*sizeof(%xmm0)/sizeof(%rax) .long 0xa548f3fc # cld; rep movsq lea 0xa0(%rax),%rax # adjust stack pointer mov 0x70(%rax),%rbp mov 0x68(%rax),%rbx mov 0x60(%rax),%r12 mov 0x58(%rax),%r13 mov 0x50(%rax),%r14 mov 0x48(%rax),%r15 lea 0x78(%rax),%rax # adjust stack pointer mov %rbx,144($context) # restore context->Rbx mov %rbp,160($context) # restore context->Rbp mov %r12,216($context) # restore context->R12 mov %r13,224($context) # restore context->R13 mov %r14,232($context) # restore context->R14 mov %r15,240($context) # restore context->R15 .Lin_prologue: mov %rax,152($context) # restore context->Rsp mov 40($disp),%rdi # disp->ContextRecord mov $context,%rsi # context mov \$`1232/8`,%ecx # sizeof(CONTEXT) .long 0xa548f3fc # cld; rep movsq mov $disp,%rsi xor %rcx,%rcx # arg1, UNW_FLAG_NHANDLER mov 8(%rsi),%rdx # arg2, disp->ImageBase mov 0(%rsi),%r8 # arg3, disp->ControlPc mov 16(%rsi),%r9 # arg4, disp->FunctionEntry mov 40(%rsi),%r10 # disp->ContextRecord lea 56(%rsi),%r11 # &disp->HandlerData lea 24(%rsi),%r12 # &disp->EstablisherFrame mov %r10,32(%rsp) # arg5 mov %r11,40(%rsp) # arg6 mov %r12,48(%rsp) # arg7 mov %rcx,56(%rsp) # arg8, (NULL) call *__imp_RtlVirtualUnwind(%rip) mov \$1,%eax # ExceptionContinueSearch add \$64,%rsp popfq pop %r15 pop %r14 pop %r13 pop %r12 pop %rbp pop %rbx pop %rdi pop %rsi ret .size se_handler,.-se_handler .section .pdata .align 4 ___ $code.=<<___ if ($ecb); .rva .Lecb_enc_prologue .rva .Lecb_enc_epilogue .rva .Lecb_enc_info .rva .Lecb_dec_prologue .rva .Lecb_dec_epilogue .rva .Lecb_dec_info ___ $code.=<<___; .rva .Lcbc_dec_prologue .rva .Lcbc_dec_epilogue .rva .Lcbc_dec_info .rva .Lctr_enc_prologue .rva .Lctr_enc_epilogue .rva .Lctr_enc_info .rva .Lxts_enc_prologue .rva .Lxts_enc_epilogue .rva .Lxts_enc_info .rva .Lxts_dec_prologue .rva .Lxts_dec_epilogue .rva .Lxts_dec_info .section .xdata .align 8 ___ $code.=<<___ if ($ecb); .Lecb_enc_info: .byte 9,0,0,0 .rva se_handler .rva .Lecb_enc_body,.Lecb_enc_epilogue # HandlerData[] .Lecb_dec_info: .byte 9,0,0,0 .rva se_handler .rva .Lecb_dec_body,.Lecb_dec_epilogue # HandlerData[] ___ $code.=<<___; .Lcbc_dec_info: .byte 9,0,0,0 .rva se_handler .rva .Lcbc_dec_body,.Lcbc_dec_epilogue # HandlerData[] .Lctr_enc_info: .byte 9,0,0,0 .rva se_handler .rva .Lctr_enc_body,.Lctr_enc_epilogue # HandlerData[] .Lxts_enc_info: .byte 9,0,0,0 .rva se_handler .rva .Lxts_enc_body,.Lxts_enc_epilogue # HandlerData[] .Lxts_dec_info: .byte 9,0,0,0 .rva se_handler .rva .Lxts_dec_body,.Lxts_dec_epilogue # HandlerData[] ___ } $code =~ s/\`([^\`]*)\`/eval($1)/gem; print $code; close STDOUT;
23.595498
92
0.609768
73fae85a44fb37795f8f1a856a0460d0814247e1
24,822
pm
Perl
lib/Zonemaster/Engine/Test/Basic.pm
repperille/zonemaster-engine
6654726ec2b3777fb10c46c95a548aa9ec68d645
[ "CC-BY-4.0" ]
null
null
null
lib/Zonemaster/Engine/Test/Basic.pm
repperille/zonemaster-engine
6654726ec2b3777fb10c46c95a548aa9ec68d645
[ "CC-BY-4.0" ]
null
null
null
lib/Zonemaster/Engine/Test/Basic.pm
repperille/zonemaster-engine
6654726ec2b3777fb10c46c95a548aa9ec68d645
[ "CC-BY-4.0" ]
null
null
null
package Zonemaster::Engine::Test::Basic; use 5.014002; use strict; use warnings; use version; our $VERSION = version->declare("v1.0.17"); use Zonemaster::Engine; use Carp; use List::MoreUtils qw[any none]; use Locale::TextDomain qw[Zonemaster-Engine]; use Readonly; use Zonemaster::Engine::Profile; use Zonemaster::Engine::Constants qw[:ip :name]; use Zonemaster::Engine::Test::Address; use Zonemaster::Engine::Test::Syntax; use Zonemaster::Engine::TestMethods; use Zonemaster::Engine::Util; ### ### Entry Points ### sub all { my ( $class, $zone ) = @_; my @results; push @results, $class->basic00( $zone ); if ( none { $_->tag eq q{DOMAIN_NAME_LABEL_TOO_LONG} or $_->tag eq q{DOMAIN_NAME_ZERO_LENGTH_LABEL} or $_->tag eq q{DOMAIN_NAME_TOO_LONG} } @results ) { push @results, $class->basic01( $zone ); push @results, $class->basic04( $zone ); push @results, $class->basic02( $zone ); # Perform BASIC3 if BASIC2 failed if ( none { $_->tag eq q{HAS_NAMESERVERS} } @results ) { push @results, $class->basic03( $zone ) if Zonemaster::Engine::Util::should_run_test( q{basic03} ); } else { push @results, info( HAS_NAMESERVER_NO_WWW_A_TEST => { zname => $zone->name, } ); } } ## end if ( none { $_->tag eq...}) return @results; } ## end sub all sub can_continue { my ( $class, @results ) = @_; my %tag = map { $_->tag => 1 } @results; if ( not $tag{NO_GLUE_PREVENTS_NAMESERVER_TESTS} and $tag{HAS_NAMESERVERS} ) { return 1; } else { return; } } ### ### Metadata Exposure ### sub metadata { my ( $class ) = @_; return { basic00 => [ qw( DOMAIN_NAME_LABEL_TOO_LONG DOMAIN_NAME_ZERO_LENGTH_LABEL DOMAIN_NAME_TOO_LONG TEST_CASE_END TEST_CASE_START ) ], basic01 => [ qw( NO_PARENT HAS_PARENT TEST_CASE_END TEST_CASE_START ) ], basic02 => [ qw( NO_GLUE_PREVENTS_NAMESERVER_TESTS NS_FAILED NS_NO_RESPONSE HAS_NAMESERVERS IPV4_DISABLED IPV6_DISABLED IPV4_ENABLED IPV6_ENABLED TEST_CASE_END TEST_CASE_START ) ], basic03 => [ qw( A_QUERY_NO_RESPONSES HAS_A_RECORDS IPV4_DISABLED IPV4_ENABLED IPV6_DISABLED IPV6_ENABLED NO_A_RECORDS TEST_CASE_END TEST_CASE_START ) ], basic04 => [ qw( B04_MISSING_NS_RECORD B04_MISSING_SOA_RECORD B04_NO_RESPONSE B04_NO_RESPONSE_NS_QUERY B04_NO_RESPONSE_SOA_QUERY B04_NS_RECORD_NOT_AA B04_RESPONSE_TCP_NOT_UDP B04_SOA_RECORD_NOT_AA B04_UNEXPECTED_RCODE_NS_QUERY B04_UNEXPECTED_RCODE_SOA_QUERY B04_WRONG_NS_RECORD B04_WRONG_SOA_RECORD IPV4_DISABLED IPV4_ENABLED IPV6_DISABLED IPV6_ENABLED TEST_CASE_END TEST_CASE_START ) ], }; } ## end sub metadata Readonly my %TAG_DESCRIPTIONS => ( A_QUERY_NO_RESPONSES => sub { __x # BASIC:A_QUERY_NO_RESPONSES 'Nameservers did not respond to A query.'; }, B04_MISSING_NS_RECORD => sub { __x # BASIC:B04_MISSING_NS_RECORD 'Nameserver {ns} reponds to a NS query with no NS records in the answer section.', @_; }, B04_MISSING_SOA_RECORD => sub { __x # BASIC:B04_MISSING_SOA_RECORD 'Nameserver {ns} reponds to a SOA query with no SOA records in the answer section.', @_; }, B04_NO_RESPONSE => sub { __x # BASIC:B04_NO_RESPONSE 'Nameserver {ns} does not respond over neither UDP nor TCP.', @_; }, B04_NO_RESPONSE_NS_QUERY => sub { __x # BASIC:B04_NO_RESPONSE_NS_QUERY 'Nameserver {ns} does not respond to NS queries.', @_; }, B04_NO_RESPONSE_SOA_QUERY => sub { __x # BASIC:B04_NO_RESPONSE_SOA_QUERY 'Nameserver {ns} does not respond to SOA queries.', @_; }, B04_NS_RECORD_NOT_AA => sub { __x # BASIC:B04_NS_RECORD_NOT_AA 'Nameserver {ns} does not give an authoritative response on an NS query.', @_; }, B04_RESPONSE_TCP_NOT_UDP => sub { __x # BASIC:B04_RESPONSE_TCP_NOT_UDP 'Nameserver {ns} does not respond over UDP.', @_; }, B04_SOA_RECORD_NOT_AA => sub { __x # BASIC:B04_SOA_RECORD_NOT_AA 'Nameserver {ns} does not give an authoritative response on an SOA query.', @_; }, B04_UNEXPECTED_RCODE_NS_QUERY => sub { __x # BASIC:B04_UNEXPECTED_RCODE_NS_QUERY 'Nameserver {ns} responds with an unexpected RCODE ({rcode}) on an NS query.', @_; }, B04_UNEXPECTED_RCODE_SOA_QUERY => sub { __x # BASIC:B04_UNEXPECTED_RCODE_SOA_QUERY 'Nameserver {ns} responds with an unexpected RCODE ({rcode}) on an SOA query.', @_; }, B04_WRONG_NS_RECORD => sub { __x # BASIC:B04_WRONG_NS_RECORD 'Nameserver {ns} responds with a wrong owner name ({owner} instead of {name}) on NS queries.', @_; }, B04_WRONG_SOA_RECORD => sub { __x # BASIC:B04_WRONG_SOA_RECORD 'Nameserver {ns} responds with a wrong owner name ({owner} instead of {name}) on SOA queries.', @_; }, DOMAIN_NAME_LABEL_TOO_LONG => sub { __x # BASIC:DOMAIN_NAME_LABEL_TOO_LONG 'Domain name ({domain}) has a label ({dlabel}) too long ({dlength}/{max}).', @_; }, DOMAIN_NAME_TOO_LONG => sub { __x # BASIC:DOMAIN_NAME_TOO_LONG 'Domain name is too long ({fqdnlength}/{max}).', @_; }, DOMAIN_NAME_ZERO_LENGTH_LABEL => sub { __x # BASIC:DOMAIN_NAME_ZERO_LENGTH_LABEL 'Domain name ({domain}) has a zero-length label.', @_; }, HAS_A_RECORDS => sub { __x # BASIC:HAS_A_RECORDS 'Nameserver {ns} returned "A" record(s) for {domain}.', @_; }, HAS_NAMESERVER_NO_WWW_A_TEST => sub { __x # BASIC:HAS_NAMESERVER_NO_WWW_A_TEST 'Functional nameserver found. "A" query for www.{zname} test skipped.', @_; }, HAS_NAMESERVERS => sub { __x # BASIC:HAS_NAMESERVERS 'Nameserver {ns} listed these servers as glue: {nsnlist}.', @_; }, HAS_PARENT => sub { __x # BASIC:HAS_PARENT 'Parent domain \'{pname}\' was found for the tested domain.', @_; }, IPV4_DISABLED => sub { __x # BASIC:IPV4_DISABLED 'IPv4 is disabled, not sending "{rrtype}" query to {ns}.', @_; }, IPV4_ENABLED => sub { __x # BASIC:IPV4_ENABLED 'IPv4 is enabled, can send "{rrtype}" query to {ns}.', @_; }, IPV6_DISABLED => sub { __x # BASIC:IPV6_DISABLED 'IPv6 is disabled, not sending "{rrtype}" query to {ns}.', @_; }, IPV6_ENABLED => sub { __x # BASIC:IPV6_ENABLED 'IPv6 is enabled, can send "{rrtype}" query to {ns}.', @_; }, NO_A_RECORDS => sub { __x # BASIC:NO_A_RECORDS 'Nameserver {ns} did not return "A" record(s) for {domain}.', @_; }, NO_GLUE_PREVENTS_NAMESERVER_TESTS => sub { __x # BASIC:NO_GLUE_PREVENTS_NAMESERVER_TESTS 'No NS records for tested zone from parent. NS tests skipped.', @_; }, NO_PARENT => sub { __x # BASIC:NO_PARENT 'No parent domain could be found for the domain under test.', @_; }, NS_FAILED => sub { __x # BASIC:NS_FAILED 'Nameserver {ns} did not return NS records. RCODE was {rcode}.', @_; }, NS_NO_RESPONSE => sub { __x # BASIC:NS_NO_RESPONSE 'Nameserver {ns} did not respond to NS query.', @_; }, TEST_CASE_END => sub { __x # BASIC:TEST_CASE_END 'TEST_CASE_END {testcase}.', @_; }, TEST_CASE_START => sub { __x # BASIC:TEST_CASE_START 'TEST_CASE_START {testcase}.', @_; }, ); sub tag_descriptions { return \%TAG_DESCRIPTIONS; } sub version { return "$Zonemaster::Engine::Test::Basic::VERSION"; } ### ### Tests ### sub basic00 { my ( $class, $zone ) = @_; push my @results, info( TEST_CASE_START => { testcase => (split /::/, (caller(0))[3])[-1] } ); my $name = name( $zone ); foreach my $local_label ( @{ $name->labels } ) { if ( length $local_label > $LABEL_MAX_LENGTH ) { push @results, info( q{DOMAIN_NAME_LABEL_TOO_LONG} => { domain => "$name", dlabel => $local_label, dlength => length( $local_label ), max => $LABEL_MAX_LENGTH, } ); } elsif ( length $local_label == 0 ) { push @results, info( q{DOMAIN_NAME_ZERO_LENGTH_LABEL} => { domain => "$name", } ); } } ## end foreach my $local_label ( @...) my $fqdn = $name->fqdn; if ( length( $fqdn ) > $FQDN_MAX_LENGTH ) { push @results, info( q{DOMAIN_NAME_TOO_LONG} => { fqdn => $fqdn, fqdnlength => length( $fqdn ), max => $FQDN_MAX_LENGTH, } ); } return ( @results, info( TEST_CASE_END => { testcase => (split /::/, (caller(0))[3])[-1] } ) ); } ## end sub basic00 sub basic01 { my ( $class, $zone ) = @_; push my @results, info( TEST_CASE_START => { testcase => (split /::/, (caller(0))[3])[-1] } ); my $parent = $zone->parent; if ( not $parent ) { push @results, info( NO_PARENT => { zone => $zone->name->string, } ); } else { push @results, info( HAS_PARENT => { zone => $zone->name->string, pname => $parent->name->string, } ); } return ( @results, info( TEST_CASE_END => { testcase => (split /::/, (caller(0))[3])[-1] } ) ); } ## end sub basic01 sub basic02 { my ( $class, $zone ) = @_; push my @results, info( TEST_CASE_START => { testcase => (split /::/, (caller(0))[3])[-1] } ); my $query_type = q{NS}; my @ns = @{ Zonemaster::Engine::TestMethods->method4( $zone ) }; if ( not scalar @ns ) { push @results, info( NO_GLUE_PREVENTS_NAMESERVER_TESTS => {} ); } foreach my $ns ( @ns ) { if ( not Zonemaster::Engine::Profile->effective->get(q{net.ipv4}) and $ns->address->version == $IP_VERSION_4 ) { push @results, info( IPV4_DISABLED => { ns => $ns->string, rrtype => $query_type, } ); next; } elsif ( Zonemaster::Engine::Profile->effective->get(q{net.ipv4}) and $ns->address->version == $IP_VERSION_4 ) { push @results, info( IPV4_ENABLED => { ns => $ns->string, rrtype => $query_type, } ); } if ( not Zonemaster::Engine::Profile->effective->get(q{net.ipv6}) and $ns->address->version == $IP_VERSION_6 ) { push @results, info( IPV6_DISABLED => { ns => $ns->string, rrtype => $query_type, } ); next; } elsif ( Zonemaster::Engine::Profile->effective->get(q{net.ipv6}) and $ns->address->version == $IP_VERSION_6 ) { push @results, info( IPV6_ENABLED => { ns => $ns->string, rrtype => $query_type, } ); } my $p = $ns->query( $zone->name, $query_type ); if ( $p ) { if ( $p->has_rrs_of_type_for_name( $query_type, $zone->name ) ) { push @results, info( HAS_NAMESERVERS => { nsnlist => join( q{,}, sort map { $_->nsdname } $p->get_records_for_name( $query_type, $zone->name ) ), ns => $ns->string, } ); } else { push @results, info( NS_FAILED => { ns => $ns->string, rcode => $p->rcode, } ); } } ## end if ( $p ) else { push @results, info( NS_NO_RESPONSE => { ns => $ns->string } ); } } ## end foreach my $ns ( @{ Zonemaster::Engine::TestMethods...}) return ( @results, info( TEST_CASE_END => { testcase => (split /::/, (caller(0))[3])[-1] } ) ); } ## end sub basic02 sub basic03 { my ( $class, $zone ) = @_; push my @results, info( TEST_CASE_START => { testcase => (split /::/, (caller(0))[3])[-1] } ); my $query_type = q{A}; my $name = q{www.} . $zone->name; my $response_nb = 0; foreach my $ns ( @{ Zonemaster::Engine::TestMethods->method4( $zone ) } ) { if ( not Zonemaster::Engine::Profile->effective->get(q{net.ipv4}) and $ns->address->version == $IP_VERSION_4 ) { push @results, info( IPV4_DISABLED => { ns => $ns->string, rrtype => $query_type, } ); next; } elsif ( Zonemaster::Engine::Profile->effective->get(q{net.ipv4}) and $ns->address->version == $IP_VERSION_4 ) { push @results, info( IPV4_ENABLED => { ns => $ns->string, rrtype => $query_type, } ); } if ( not Zonemaster::Engine::Profile->effective->get(q{net.ipv6}) and $ns->address->version == $IP_VERSION_6 ) { push @results, info( IPV6_DISABLED => { ns => $ns->string, rrtype => $query_type, } ); next; } elsif ( Zonemaster::Engine::Profile->effective->get(q{net.ipv6}) and $ns->address->version == $IP_VERSION_6 ) { push @results, info( IPV6_ENABLED => { ns => $ns->string, rrtype => $query_type, } ); } my $p = $ns->query( $name, $query_type ); next if not $p; $response_nb++; if ( $p->has_rrs_of_type_for_name( $query_type, $name ) ) { push @results, info( HAS_A_RECORDS => { ns => $ns->string, domain => $name, } ); } else { push @results, info( NO_A_RECORDS => { ns => $ns->string, domain => $name, } ); } } ## end foreach my $ns ( @{ Zonemaster::Engine::TestMethods...}) if ( scalar( @{ Zonemaster::Engine::TestMethods->method4( $zone ) } ) and not $response_nb ) { push @results, info( A_QUERY_NO_RESPONSES => {} ); } return ( @results, info( TEST_CASE_END => { testcase => (split /::/, (caller(0))[3])[-1] } ) ); } ## end sub basic03 sub basic04 { my ( $class, $zone ) = @_; push my @results, info( TEST_CASE_START => { testcase => (split /::/, (caller(0))[3])[-1] } ); my $name = name( $zone ); my @query_types = qw{SOA NS}; my @ns = @{ Zonemaster::Engine::TestMethods->method4and5( $zone ) }; foreach my $ns ( @ns ) { if ( not Zonemaster::Engine::Profile->effective->get(q{net.ipv4}) and $ns->address->version == $IP_VERSION_4 ) { push @results, map { info( IPV4_DISABLED => { ns => $ns->string, rrtype => $_, } ) } @query_types; next; } elsif ( Zonemaster::Engine::Profile->effective->get(q{net.ipv4}) and $ns->address->version == $IP_VERSION_4 ) { push @results, map { info( IPV4_ENABLED => { ns => $ns->string, rrtype => $_, } ) } @query_types; } if ( not Zonemaster::Engine::Profile->effective->get(q{net.ipv6}) and $ns->address->version == $IP_VERSION_6 ) { push @results, map { info( IPV6_DISABLED => { ns => $ns->string, rrtype => $_, } ) } @query_types; next; } elsif ( Zonemaster::Engine::Profile->effective->get(q{net.ipv6}) and $ns->address->version == $IP_VERSION_6 ) { push @results, map { info( IPV6_ENABLED => { ns => $ns->string, rrtype => $_, } ) } @query_types; } my $p_soa_udp = $ns->query( $name, q{SOA}, { usevc => 0 } ); my $p_ns_udp = $ns->query( $name, q{NS}, { usevc => 0 } ); if ( not $p_soa_udp and not $p_ns_udp ) { my $p_soa_tcp = $ns->query( $name, q{SOA}, { usevc => 1 } ); if ( not $p_soa_tcp ) { push @results, info( B04_NO_RESPONSE => { ns => $ns->string } ); } else { push @results, info( B04_RESPONSE_TCP_NOT_UDP => { ns => $ns->string } ); } } else { if ( not $p_soa_udp ) { push @results, info( B04_NO_RESPONSE_SOA_QUERY => { ns => $ns->string } ); } else { if ( $p_soa_udp->rcode ne q{NOERROR} ) { push @results, info( B04_UNEXPECTED_RCODE_SOA_QUERY => { ns => $ns->string, rcode => $p_soa_udp->rcode } ); } else { my ( $soa ) = $p_soa_udp->get_records( q{SOA}, q{answer} ); if ( not $soa ) { push @results, info( B04_MISSING_SOA_RECORD => { ns => $ns->string } ); } else { if ( lc($soa->owner) ne lc($name->fqdn) ) { push @results, info( B04_WRONG_SOA_RECORD => { ns => $ns->string, owner => lc($soa->owner), name => lc($name->fqdn) } ); } elsif ( not $p_soa_udp->aa ) { push @results, info( B04_SOA_RECORD_NOT_AA => { ns => $ns->string } ); } } } } if ( not $p_ns_udp ) { push @results, info( B04_NO_RESPONSE_NS_QUERY => { ns => $ns->string } ); } else { if ( $p_ns_udp->rcode ne q{NOERROR} ) { push @results, info( B04_UNEXPECTED_RCODE_NS_QUERY => { ns => $ns->string, rcode => $p_ns_udp->rcode } ); } else { my ( $ns ) = $p_ns_udp->get_records( q{NS}, q{answer} ); if ( not $ns ) { push @results, info( B04_MISSING_NS_RECORD => { ns => $ns->string } ); } else { if ( lc($ns->owner) ne lc($name->fqdn) ) { push @results, info( B04_WRONG_NS_RECORD => { ns => $ns->string, owner => lc($ns->owner), name => lc($name->fqdn) } ); } elsif ( not $p_ns_udp->aa ) { push @results, info( B04_NS_RECORD_NOT_AA => { ns => $ns->string } ); } } } } } } return ( @results, info( TEST_CASE_END => { testcase => (split /::/, (caller(0))[3])[-1] } ) ); } ## end sub basic04 1; =head1 NAME Zonemaster::Engine::Test::Basic - module implementing test for very basic domain functionality =head1 SYNOPSIS my @results = Zonemaster::Engine::Test::Basic->all($zone); =head1 METHODS =over =item all($zone) Runs between one and three tests, depending on the zone. If L<basic01> passes, L<basic02> is run. If L<basic02> fails, L<basic03> is run. =item metadata() Returns a reference to a hash, the keys of which are the names of all test methods in the module, and the corresponding values are references to lists with all the tags that the method can use in log entries. =item tag_descriptions() Returns a refernce to a hash with translation functions. Used by the builtin translation system. =item version() Returns a version string for the module. =item can_continue(@results) Looks at the provided log entries and returns true if they indicate that further testing of the relevant zone is possible. =back =head1 TESTS =over =item basic00 Checks if the domain name to be tested is valid. Not all syntax tests are done here, it "just" checks domain name total length and labels length. In case of failure, all other tests are aborted. =item basic01 Checks that we can find a parent zone for the zone we're testing. If we can't, no further testing is done. =item basic02 Checks that the nameservers for the parent zone returns NS records for the tested zone, and that at least one of the nameservers thus pointed out responds sensibly to an NS query for the tested zone. =item basic03 Checks if at least one of the nameservers pointed out by the parent zone gives a useful response when sent an A query for the C<www> label in the tested zone (that is, if we're testing C<example.org> this test will as for A records for C<www.example.org>). This test is only run if the L<basic02> test has I<failed>. =item basic04 Query all nameservers pointed out by the parent zone or found in delegation for NS and/or SOA records. Previously done in several test cases, these tests should be done only here. =back =cut
31.945946
145
0.459955
73d5a450fb3174ac905ac55b2aa6e096acbea1a4
25,606
pm
Perl
tools/modules/EnsEMBL/Web/Object/Blast.pm
CristiGuijarro/public-plugins
060930ad6b4b47784e53c2fd9b6cd38e635f1d76
[ "Apache-2.0" ]
null
null
null
tools/modules/EnsEMBL/Web/Object/Blast.pm
CristiGuijarro/public-plugins
060930ad6b4b47784e53c2fd9b6cd38e635f1d76
[ "Apache-2.0" ]
null
null
null
tools/modules/EnsEMBL/Web/Object/Blast.pm
CristiGuijarro/public-plugins
060930ad6b4b47784e53c2fd9b6cd38e635f1d76
[ "Apache-2.0" ]
null
null
null
=head1 LICENSE Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute Copyright [2016-2018] EMBL-European Bioinformatics Institute 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. =cut package EnsEMBL::Web::Object::Blast; ## The aim is to create an object which can be updated to ## use a different queuing mechanism, without any need to ## change the user interface. Where possible, therefore, ## public methods should accept the same arguments and ## return the same values use strict; use warnings; use EnsEMBL::Web::Utils::FileHandler qw(file_get_contents); use EnsEMBL::Web::BlastConstants qw(CONFIGURATION_FIELDS); use parent qw(EnsEMBL::Web::Object::Tools); sub get_blast_form_options { ## Gets the list of options for dropdown fields in the blast input form my $self = shift; # return if already cached return $self->{'_form_options'} if $self->{'_form_options'}; my $hub = $self->hub; my $sd = $self->species_defs; my @species = $self->valid_species; my $blast_types = $sd->multi_val('ENSEMBL_BLAST_TYPES'); # hashref with keys as BLAT, NCBIBLAST etc my $query_types = $sd->multi_val('ENSEMBL_BLAST_QUERY_TYPES'); # hashref with keys dna, peptide my $db_types = $sd->multi_val('ENSEMBL_BLAST_DB_TYPES'); # hashref with keys dna, peptide my $blast_configs = $sd->multi_val('ENSEMBL_BLAST_CONFIGS'); # hashref with valid combinations of query_type, db_type, sources, search_type (and program for the search_type) my $sources = $sd->multi_val('ENSEMBL_BLAST_DATASOURCES'); # hashref with keys as blast type and value as a hashref of data sources type and label my $sources_ordered = $sd->multi_val('ENSEMBL_BLAST_DATASOURCES_ORDER'); # hashref with keys as blast type and value as a ordered array if data sources type my $restrictions = $sd->multi_val('ENSEMBL_BLAST_RESTRICTIONS'); # hashref with keys as blast type and value as a arrayref of data sources by value my $search_types = [ map { $_->{'search_type'} } @$blast_configs ]; # NCBIBLAST_BLASTN, NCBIBLAST_BLASTP, BLAT_BLAT etc my $options = {}; # Options for different dropdown fields my $missing_sources = {}; # List of missing source files per species my $blat_availability = {}; # List all species that has blat available my $invalid_comb = {}; # Species, query types and db types options $options->{'species'} = [ sort { $a->{'caption'} cmp $b->{'caption'} } map { 'value' => $_, 'caption' => $sd->species_label($_, 1) }, @species ]; $options->{'query_type'} = [ map { 'value' => $_, 'caption' => $query_types->{$_} }, sort keys %$query_types ]; $options->{'db_type'} = [ map { 'value' => $_, 'caption' => $db_types->{$_} }, sort keys %$db_types ]; # Search type options and restrictions to the search type foreach my $search_type (@$search_types) { my ($blast_type, $search_method) = $self->parse_search_type($search_type); push @{$options->{'search_type'}}, { 'value' => $search_type, 'caption' => $search_method }; if ($restrictions->{$search_type}) { for (@{$restrictions->{$search_type}}) { push @{$invalid_comb->{$search_type}}, { 'value' => $_, 'caption' => $sources->{$_} }; } } } # DB Source options foreach my $source_type (@$sources_ordered) { for (@$blast_configs) { if (grep { $source_type eq $_ } @{$_->{'sources'}}) { push @{$options->{'source'}{$_->{'db_type'}}}, { 'value' => $source_type, 'caption' => $sources->{$source_type} }; last; } } } # Find the missing source files for (@species) { my $available_sources = $sd->get_available_blast_datasources($_); if (my @missing = grep !$available_sources->{$_}, keys %$sources) { $missing_sources->{$_} = \@missing; } my $blat_available = $sd->get_config($_, 'BLAT_DATASOURCES'); if (keys %$blat_available) { $blat_availability->{$_} = 1; } } #Reset the blat list if blat is disabled undef %$blat_availability if (!$sd->ENSEMBL_BLAT_ENABLED); return $self->{'_form_options'} = { 'options' => $options, 'missing_sources' => $missing_sources, 'combinations' => $blast_configs, 'restrictions' => $invalid_comb, 'blat_availability' => $blat_availability }; } sub get_edit_jobs_data { ## Abstract method implementation my $self = shift; my $hub = $self->hub; my $jobs = $self->get_requested_job || $self->get_requested_ticket; $jobs = $jobs ? ref($jobs) =~ /Ticket/ ? $jobs->job : [ $jobs ] : []; my @jobs_data; if (@$jobs) { my %config_fields = map { @{$_->{'fields'}} } values %{{ @{CONFIGURATION_FIELDS()} }}; for (@$jobs) { my $job_data = $_->job_data->raw; delete $job_data->{$_} for qw(source_file output_file); if ($job_data->{configs} && $job_data->{configs}->{gap_dna}) { my $new_gap_dna_key = "gap_dna" . '__' . $job_data->{configs}->{score}; $job_data->{configs}->{$new_gap_dna_key} = $job_data->{configs}->{gap_dna}; delete $job_data->{configs}->{gap_dna}; } $job_data->{'species'} = $_->species; $job_data->{'sequence'} = $self->get_input_sequence_for_job($_); for (keys %{$job_data->{'configs'}}) { $job_data->{'configs'}{$_} = { reverse %{$config_fields{$_}{'commandline_values'}} }->{ $job_data->{'configs'}{$_} } if exists $config_fields{$_}{'commandline_values'}; } push @jobs_data, $job_data; } } return \@jobs_data; } sub get_input_sequence_for_job { ## Gets input sequence of a job from input file ## @param Job rose object ## @return Copy of hashref saved at $job->job_data->{'seuqnece'}, but with two extra keys 'display_id', 'sequence', but one removed key 'input_file' my ($self, $job) = @_; my $sequence = $job->job_data->raw->{'sequence'}; my @fasta_lines = file_get_contents(sprintf("%s/%s", $job->job_dir, delete $sequence->{'input_file'}), sub { chomp; $_; }); $sequence->{'display_id'} = $fasta_lines[0] =~ s/^>// ? shift @fasta_lines : ''; $sequence->{'sequence'} = join("", @fasta_lines); return $sequence; } sub get_param_value_caption { ## Gets the display caption for a value for a given param type ## @param Param type string (query_type, db_type, source or search_type) ## @param Value ## @return String caption, if param value is valid, undef otherwise my ($self, $param_name, $param_value) = @_; my $hub = $self->hub; my $sd = $hub->species_defs; if ($param_name eq 'search_type') { my $blast_types = $sd->multi_val('ENSEMBL_BLAST_TYPES'); for (@{$sd->multi_val('ENSEMBL_BLAST_CONFIGS')}) { if ($param_value eq $_->{'search_type'}) { my ($blast_type, $search_method) = $self->parse_search_type($param_value); return $search_method eq $blast_types->{$blast_type} ? $search_method : sprintf('%s (%s)', $search_method, $blast_types->{$blast_type}); } } } else { my %param_type_map = qw(query_type ENSEMBL_BLAST_QUERY_TYPES db_type ENSEMBL_BLAST_DB_TYPES source ENSEMBL_BLAST_DATASOURCES); if (my $sd_key = $param_type_map{$param_name}) { my $param_details = $sd->multi_val($sd_key); return $param_details->{$param_value} if exists $param_details->{$param_value}; } } } sub parse_search_type { ## Parses the search type value to get blast type and actual search method name ## @param Search type string ## @param (optional) required key (blast_type or search_method) ## @return List of blast_type and search_method values if required key not specified, individual key value otherwise my ($self, $search_type, $required_key) = @_; my @search_type = split /_/, $search_type; if ($required_key) { return $search_type[0] if $required_key eq 'blast_type'; return $search_type[1] if $required_key eq 'search_method'; } return @search_type } sub get_target_object { ## Gets the target genomic object according to the target Id of the blast result's hit ## @param Blast result hit ## @param DB Source type ## @return PredictionTranscript/Transcript/Translation object my ($self, $hit, $source) = @_; my $target_id = $hit->{'tid'}; my $species = $hit->{'species'}; my $feature_type = $source =~ /abinitio/i ? 'PredictionTranscript' : $source =~ /cdna|ncrna/i ? 'Transcript' : 'Translation'; my $adaptor = $self->hub->get_adaptor("get_${feature_type}Adaptor", 'core', $species); return $adaptor->fetch_by_stable_id($target_id); } sub map_result_hits_to_karyotype { ## Maps all the hit as a feature on the karyotype view ## In case some hits are on a patch, it gets the actual chromosome name to draw that hit on the karyotype ## @param Job object my ($self, $job) = @_; my $hub = $self->hub; my $species = $job->species; my $results = $job->result; my %all_chr = map { $_ => 1 } @{$hub->species_defs->get_config($species, 'ENSEMBL_CHROMOSOMES') || []}; my %alt_chr; my @features; for (@$results) { my $hit_id = $_->result_id; my $hit = $_->result_data; my $feature = { 'region' => $hit->{'gid'}, 'start' => $hit->{'gstart'}, 'end' => $hit->{'gend'}, 'p_value' => 1 + $hit->{'pident'} / 100, 'strand' => $hit->{'gori'}, 'href' => { 'species' => $species, 'type' => 'ZMenu', 'action' => 'Tools', 'function' => 'Blast', 'tl' => $self->create_url_param, 'hit' => $hit_id }, 'html_id' => "hsp_$hit_id" }; if (!$all_chr{$hit->{'gid'}}) { # if it's a patch region, get the actual chromosome name if (!exists $alt_chr{$hit->{'gid'}}) { my $slice = $hub->get_adaptor('get_SliceAdaptor')->fetch_by_region('toplevel', $hit->{'gid'}, $hit->{'gstart'}, $hit->{'gend'}); my ($alt) = @{$hub->get_adaptor('get_AssemblyExceptionFeatureAdaptor')->fetch_all_by_Slice($slice)}; my $alt_slice; if ($alt) { $alt_slice = $alt->alternate_slice; } $alt_chr{$hit->{'gid'}} = $alt_slice ? $alt_slice->seq_region_name : undef; } next unless $alt_chr{$hit->{'gid'}}; $feature->{'actual_region'} = $hit->{'gid'}; $feature->{'region'} = $alt_chr{$hit->{'gid'}}; } push @features, $feature; } return \@features; } sub get_all_hits { ## Gets all the result hits (hashrefs) for the given job, and adds result_id and tl (url param) to the individual hit ## @param Job object ## @param Optional sort subroutine to sort the hits (defaults to sorting by result id) ## @return Arrayref of hits hashref my ($self, $job, $sort) = @_; $sort ||= sub { $a->{'result_id'} <=> $b->{'result_id'} }; $job->load('with' => 'result'); return [ sort $sort map { my $result_id = $_->result_id; my $result_data = $_->result_data->raw; $result_data->{'result_id'} = $result_id; $result_data->{'tl'} = $self->create_url_param({'job_id' => $job->job_id, 'result_id' => $result_id}); $result_data } @{$job->result} ]; } sub get_all_hits_in_slice_region { ## Gets all the result hits for the given job in the given slice region ## @param Job object ## @param Slice object ## @param Sort subroutine as accepted by get_all_hits ## @return Array of hits hashrefs my ($self, $job, $slice, $sort) = @_; my $s_name = $slice->seq_region_name; my $s_start = $slice->start; my $s_end = $slice->end; return [ grep { my $gid = $_->{'gid'}; my $vtid = $_->{'v_tid'} || ''; my $gstart = $_->{'gstart'}; my $gend = $_->{'gend'}; ($s_name eq $vtid || $s_name eq $gid) && ( $gstart >= $s_start && $gend <= $s_end || $gstart < $s_start && $gend <= $s_end && $gend > $s_start || $gstart >= $s_start && $gstart <= $s_end && $gend > $s_end || $gstart < $s_start && $gend > $s_end && $gstart < $s_end ) } @{$self->get_all_hits($job, $sort)} ]; } sub get_result_urls { ## Gets url links for the result hit ## @param Job object ## @param Result object ## @return Hashref of keys as link types and values as hashrefs as accepted by hub->url (or arrayref of such hashrefs in case of genes) my ($self, $job, $result) = @_; my $species = $job->species; my $job_data = $job->job_data; my $source = $job_data->{'source'}; my $hit = $result->result_data; my $url_param = $self->create_url_param({'job_id' => $job->job_id, 'result_id' => $result->result_id}); my $urls = {}; # Target url (only for sources other than genmoic seq) if ($source !~ /latestgp/i) { my $target = $self->get_target_object($hit, $source); $target = $target->transcript if $target->isa('Bio::EnsEMBL::Translation'); my $param = $target->isa('Bio::EnsEMBL::PredictionTranscript') ? 'pt' : 't'; $urls->{'target'} = { 'species' => $species, 'type' => 'Transcript', 'action' => $source =~/cdna|ncrna/i ? 'Summary' : 'ProteinSummary', $param => $hit->{'tid'}, 'tl' => $url_param }; } # Genes url $urls->{'gene'} = []; for (@{$self->get_genes_for_hit($job, $result)}) { my $label = $_->display_xref; push @{$urls->{'gene'}}, { 'species' => $species, 'type' => 'Gene', 'action' => 'Summary', 'g' => $_->stable_id, 'tl' => $url_param, 'label' => $label ? $label->display_id : $_->stable_id }; } # Location url my $start = $hit->{'gstart'} < $hit->{'gend'} ? $hit->{'gstart'} : $hit->{'gend'}; my $end = $hit->{'gstart'} > $hit->{'gend'} ? $hit->{'gstart'} : $hit->{'gend'}; my $length = $end - $start; # add 5% padding on both sides $start = int($start - $length * 0.05); $start = 1 if $start < 1; $end = int($end + $length * 0.05); $urls->{'location'} = { '__clear' => 1, 'species' => $species, 'type' => 'Location', 'action' => 'View', 'r' => sprintf('%s:%s-%s', $hit->{'gid'}, $start, $end), 'tl' => $url_param }; # Alignment url $urls->{'alignment'} = { 'species' => $species, 'type' => 'Tools', 'action' => 'Blast', 'function' => $self->get_alignment_component_name_for_job($job), 'tl' => $url_param }; # Query sequence url $urls->{'query_sequence'} = { 'species' => $species, 'type' => 'Tools', 'action' => 'Blast', 'function' => 'QuerySeq', 'tl' => $url_param }; # Genomic sequence url $urls->{'genomic_sequence'} = { 'species' => $species, 'type' => 'Tools', 'action' => 'Blast', 'function' => 'GenomicSeq', 'tl' => $url_param }; return $urls; } sub get_genes_for_hit { ## Returns the gene objects linked to a blast hit ## @param Job object ## @param Blast result object my ($self, $job, $result) = @_; my $hit = $result->result_data; my @genes; if ($hit->{'genes'}) { if (@{$hit->{'genes'}}) { my $adaptor = $self->hub->get_adaptor("get_GeneAdaptor", 'core', $job->species); @genes = map { $adaptor->fetch_by_stable_id($_) } @{$hit->{'genes'}}; } } else { my $source = $job->job_data->{'source'}; if ($source =~ /latestgp/i) { @genes = @{$self->get_hit_genomic_slice($hit)->get_all_Genes}; } else { my $target = $self->get_target_object($hit, $source); $target = $target->transcript if $target->isa('Bio::EnsEMBL::Translation'); push @genes, $target->get_Gene || () unless $target->isa('Bio::EnsEMBL::PredictionTranscript'); } # cache it in the db $hit->{'genes'} = [ map $_->stable_id, @genes ]; $result->save; } return \@genes; } sub get_alignment_component_name_for_job { ## Returns 'Alignment' or 'AlignmentProtein' depending upon job object my ($self, $job) = @_; return $job->job_data->{'db_type'} eq 'peptide' || $job->job_data->{'query_type'} eq 'peptide' ? 'AlignmentProtein' : 'Alignment'; } sub handle_download { ## Method reached by url ensembl.org/Download/Blast/ my ($self, $r) = @_; my $job = $self->get_requested_job; # TODO redirect to job not found page if !$job my $result_file = sprintf '%s/%s', $job->job_dir, $job->job_data->{'output_file'}; # TODO - result file is missing, or temporarily not available if !-e $result_file my $content = file_get_contents($result_file, sub { s/\R/\r\n/r }); $r->headers_out->add('Content-Type' => 'text/plain'); $r->headers_out->add('Content-Length' => length $content); $r->headers_out->add('Content-Disposition' => sprintf 'attachment; filename=%s.blast.txt', $self->create_url_param); print $content; } sub get_hit_genomic_slice { ## Gets the genomic slice according to the coordinates returned in the blast results ## @param Result hit ## @return Bio::EnsEMBL::Slice object my ($self, $hit, $flank5, $flank3) = @_; my $start = $hit->{'gstart'} < $hit->{'gend'} ? $hit->{'gstart'} : $hit->{'gend'}; my $end = $hit->{'gstart'} > $hit->{'gend'} ? $hit->{'gstart'} : $hit->{'gend'}; my $coords = $hit->{'gid'}.':'.$start.'-'.$end.':'.$hit->{'gori'}; my $slice = $self->hub->get_adaptor('get_SliceAdaptor', 'core', $hit->{'species'})->fetch_by_toplevel_location($coords); return $flank5 || $flank3 ? $slice->expand($flank5, $flank3) : $slice; } sub map_btop_to_genomic_coords { ## Maps the btop format returned by NCBI BLAST to genomic alignment ## @param Hit object ## @param Job object (needed to cache the mapped genomic aligment for future use) my ($self, $hit, $job) = @_; my $source = $hit->{'source'}; my $galn = ''; # don't need to map for other dbs if ($source !~/cdna|pep/i) { return $hit->{'gori'} == $hit->{'qori'} ? $hit->{'aln'} : $self->_reverse_btop($hit->{'aln'}); } # find the alignment and cache it in the db in case not already saved unless ($galn = $hit->{'galn'}) { my $btop = $hit->{'aln'} =~ s/^\s|\s$//gr; my $coords = $hit->{'g_coords'}; my $target_object = $self->get_target_object($hit, $source); my $mapping_type = $source =~/pep/i ? 'pep2genomic' : 'cdna2genomic'; my $gap_start = $coords->[0]->end; my $gap_count = scalar @$coords; my $processed_gaps = 0; # reverse btop string if necessary so always dealing with + strand genomic coords my $object_strand = $target_object->isa('Bio::EnsEMBL::Translation') ? $target_object->start_Exon->strand : $target_object->strand; my $rev_flag = $object_strand ne $hit->{'tori'}; $btop = $self->_reverse_btop($btop) if $rev_flag; # account for btop strings that do not start with a match; $btop = "0$btop" if $btop !~/^\d+/ ; $btop =~s/(\d+)/:$1:/g; $btop =~s/^:|:$//g; my @btop_features = split (/:/, $btop); my $genomic_start = $hit->{'gstart'}; my $genomic_end = $hit->{'gend'}; my $genomic_offset = $genomic_start; my $target_offset = !$rev_flag ? $hit->{'tstart'} : $hit->{'tend'}; while (my ($num_matches, $diff_string) = splice @btop_features, 0, 2) { next unless $diff_string; my $diff_length = (length $diff_string) / 2; my $temp = $diff_string; my @diffs = split //, $temp; # Account for bases inserted in query relative to target my $insert_in_query = 0; while (my ($query_base, $target_base) = splice @diffs, 0, 2) { $insert_in_query++ if $target_base eq '-' && $query_base ne '-'; } my ($difference_start, $difference_end); if ($rev_flag) { $difference_end = $target_offset - $num_matches; $difference_start = $difference_end - $diff_length + $insert_in_query + 1; $target_offset = $difference_start - 1; } else { $difference_start = $target_offset + $num_matches; $difference_end = $difference_start + $diff_length - $insert_in_query - 1; $target_offset = $difference_end + 1; } my @mapped_coords = sort { $a->start <=> $b->start } grep { ! $_->isa('Bio::EnsEMBL::Mapper::Gap') } $target_object->$mapping_type($difference_start, $difference_end); my $mapped_start = $mapped_coords[0]->start; my $mapped_end = $mapped_coords[-1]->end; # Check that mapping occurs before the next gap if ($mapped_start < $gap_start && $mapped_end <= $gap_start) { $galn .= $num_matches; $galn .= $diff_string; $genomic_offset = $mapped_end + 1; } elsif ($mapped_start > $gap_start) { # process any gaps in mapped genomic coords first while ($mapped_start > $gap_start) { my $matches_before_gap = $gap_start - $genomic_offset + 1; my $gap_end = $coords->[$processed_gaps + 1]->start -1; my $gap_length = ($gap_end - $gap_start); my $gap_string = '--' x $gap_length; $genomic_offset = $gap_end + 1; $galn .= $matches_before_gap; $galn .= $gap_string; $processed_gaps++; $gap_start = $coords->[$processed_gaps]->end || $genomic_end; } # Add difference info my $matches_after_gap = $mapped_start - $genomic_offset; $galn .= $matches_after_gap; $galn .= $diff_string; $genomic_offset = $mapped_end + 1; } elsif ($mapped_start < $gap_start && $mapped_end > $gap_start) { # Difference in btop string spans a gap in the genomic coords my $diff_matches_before_gap = $gap_start - $mapped_start; my $diff_index = $diff_matches_before_gap * 2 - 1; my $diff_before_gap = join '', @diffs[0..$diff_index]; $diff_index++; $galn .= $num_matches; $galn .= $diff_before_gap; while ($mapped_end > $gap_start) { my $gap_end = $coords->[$processed_gaps + 1]->start - 1; my $gap_length = ($gap_end - $gap_start); my $gap_string = '--' x $gap_length; $processed_gaps++; $gap_start = $coords->[$processed_gaps]->end || $genomic_end; my $match_number = $gap_start - $gap_end; my $diff_end = $diff_index + ( $match_number * 2 ) - 1; my $diff_after_gap = join '', @diffs[$diff_index..$diff_end]; $galn .= $gap_string; $galn .= $diff_after_gap; $diff_index = $diff_end + 1; } my $diff_after_gap = join '', @diffs[$diff_index..-1]; $galn .= $diff_after_gap; $genomic_offset = $mapped_end + 1; } else { warn "Object::Blast::map_btop_to_genomic_coords: mapping case not caught! $mapped_start $mapped_end $gap_start"; } } # Add in any gaps from mapping to genomic coords that occur after last btop feature while ($gap_count > $processed_gaps + 1) { my $num_matches = $gap_start - $genomic_offset + 1; my $gap_end = $coords->[$processed_gaps + 1]->start - 1; my $gap_length = ($gap_end - $gap_start); my $gap_string = '--' x $gap_length; $galn .= $num_matches; $galn .= $gap_string; $genomic_offset = $gap_end + 1; $gap_start = $coords->[$processed_gaps + 1]->end; $processed_gaps++; } my $btop_end = $genomic_end - $genomic_offset + 1; $galn .= $btop_end; $self->_compress_galn(\$galn); # Write back to database so we only have to do this once if ($job && (my $result_id = $hit->{'result_id'})) { my ($result) = grep { $result_id eq $_->result_id} @{$job->result}; $result->result_data->{'galn'} = $galn; $result->save; } } $self->_decompress_galn(\$galn); return $galn && $source =~ /latest/i && $hit->{'gori'} ne '1' ? $self->_reverse_btop($galn) : $galn; } sub _reverse_btop { ## @private my ($self, $incoming_btop) = @_; $incoming_btop = uc $incoming_btop =~ s/(\d+)/:$1:/rg =~ s/^:|:$//rg; $incoming_btop .= ':0' if $incoming_btop !~ /\d+$/; return join '', reverse split ':', $incoming_btop; } sub _compress_galn { ## @private ## Compresses the galn string by replacing repeating hyphens with the count enclosed in brackets my ($self, $galn_ref) = @_; my @offsets; while ($$galn_ref =~ /([\-]{4,})/g) { # ignore less then 4 hiphens push @offsets, [ $-[1], length $1 ]; } for (reverse @offsets) { substr $$galn_ref, $_->[0], $_->[1], "($_->[1])"; } } sub _decompress_galn { ## @private ## Decompresses the galn string by replacing the counts of hyphens enclosed in brackets with actual number of hyphens my ($self, $galn_ref) = @_; my @offsets; while ($$galn_ref =~ /(\((\d+)\))/g) { push @offsets, [ $-[1], length $1, $2 ]; } for (reverse @offsets) { substr $$galn_ref, $_->[0], $_->[1], '-' x $_->[2]; } } 1;
36.166667
188
0.596188
73e708de18714fff748530538048e6c949bf64dd
1,495
t
Perl
t/response.t
tsirkin/Apache-ASP
effd5958f145d217e531969d35167c97a11b0ba6
[ "Artistic-1.0-Perl" ]
1
2016-05-09T11:50:20.000Z
2016-05-09T11:50:20.000Z
t/response.t
tsirkin/Apache-ASP
effd5958f145d217e531969d35167c97a11b0ba6
[ "Artistic-1.0-Perl" ]
null
null
null
t/response.t
tsirkin/Apache-ASP
effd5958f145d217e531969d35167c97a11b0ba6
[ "Artistic-1.0-Perl" ]
null
null
null
use Apache::ASP::CGI; &Apache::ASP::CGI::do_self(NoState => 1); __END__ <% use lib '.'; use T; $t =T->new(); # IsClientConnected Tests $t->eok($Response->{IsClientConnected}, "\$Response->{IsClientConnected}"); $t->eok($Response->IsClientConnected, "\$Response->IsClientConnected"); $Server->{asp}{r}->connection->aborted(1); $Response->Flush; # updates {IsClientConnected} $t->eok(! $Response->{IsClientConnected}, "\$Response->{IsClientConnected} after aborted/Flush()"); $t->eok(! $Response->IsClientConnected, "\$Response->IsClientConnected after aborted"); # AddHeader() member setting my $date = &Apache::ASP::Date::time2str($time); $Response->AddHeader('expires', $date); $t->eok($Response->{ExpiresAbsolute} eq $date, "\$Response->AddHeader('Expires', ...) did not set ExpiresAbsolute member"); $Response->AddHeader('Content-type', 'text/plain'); $t->eok($Response->{ContentType} eq 'text/plain', "\$Response->AddHeader('Content-Type', ...) did not set ContentType member"); $Response->AddHeader('Cache-Control', 'no-cache'); $t->eok($Response->{CacheControl} eq 'no-cache', "\$Response->AddHeader('Cache-Control', ...) did not set CacheControl member"); # reset $Server->{asp}{r}->connection->aborted(0); $Response->{IsClientConnected} = 1; $t->eok($Response->IsClientConnected, "\$Response->IsClientConnected after reset"); $t->{t} += 3; $t->done; $Response->Write(""); %> ok ok <% print "ok\n"; # $Response->AppendToLog("logging ok"); # $Response->Debug("logging ok"); %>
33.977273
128
0.682274
73f6149b5fc6c71a7a39d90bc7c56cf5185ea62b
2,872
t
Perl
t/Devices.t
kcaran/Selenium-UserAgent
b5d652737ba0a56ef5df8c05019e17ae095b31dd
[ "X11", "MIT" ]
null
null
null
t/Devices.t
kcaran/Selenium-UserAgent
b5d652737ba0a56ef5df8c05019e17ae095b31dd
[ "X11", "MIT" ]
null
null
null
t/Devices.t
kcaran/Selenium-UserAgent
b5d652737ba0a56ef5df8c05019e17ae095b31dd
[ "X11", "MIT" ]
null
null
null
use JSON; use LWP::UserAgent; use Selenium::UserAgent; use Test::Spec; my $ua = LWP::UserAgent->new; my $devices_url = 'https://code.cdn.mozilla.net/devices/devices.json'; my $res = $ua->get($devices_url); plan skip_all => 'Cannot get device source document' unless $res->code == 200; my $devices = decode_json($res->content); describe 'Device information' => sub { my $expected_phones = [ @{ $devices->{phones} }, @{ $devices->{tablets} }]; my $expected_tablets = $devices->{tablets}; my $phones = { # iphone4 => 'Apple iPhone 4', iphone5 => 'iPhone 5/SE', iphone6 => 'iPhone 6/7/8', iphone6plus => 'iPhone 6/7/8 Plus', iphone_x => 'iPhone X/XS', iphone_xr => 'iPhone XR', iphone_xs_max => 'iPhone XS Max', # galaxy_s3 => 'Samsung Galaxy S3', # galaxy_s4 => 'Samsung Galaxy S4', galaxy_s5 => 'Galaxy S5', galaxy_note3 => 'Galaxy Note 3', # nexus4 => 'Google Nexus 4', }; my $actual = get_actual_phones(); describe 'phones' => sub { foreach my $name (keys %$phones) { my $converted_name = $phones->{$name}; my @details = grep { $_->{name} eq $converted_name } @$expected_phones; my $expected = $details[0]; it 'should match width for ' . $name => sub { is($actual->{$name}->{portrait}->{width}, $expected->{width}); }; it 'should match height for ' . $name => sub { is($actual->{$name}->{portrait}->{height}, $expected->{height}); }; it 'should match pixel ratio for ' . $name => sub { is($actual->{$name}->{pixel_ratio}, $expected->{pixelRatio}); }; } }; describe 'tablets' => sub { my $tablets = { ipad => 'iPad', ipad_mini => 'iPad Mini', ipad_pro_10_5 => 'iPad Pro (10.5-inch)', ipad_pro_12_9 => 'iPad Pro (12.9-inch)', nexus10 => 'Nexus 10' }; foreach my $name (keys %$tablets) { my $converted_name = $tablets->{$name}; my @details = grep { $_->{name} eq $converted_name } @$expected_tablets; my $expected = $details[0]; it 'should match width for ' . $name => sub { is($actual->{$name}->{portrait}->{width}, $expected->{width}); }; it 'should match height for ' . $name => sub { is($actual->{$name}->{portrait}->{height}, $expected->{height}); }; it 'should match pixel ratio for ' . $name => sub { is($actual->{$name}->{pixel_ratio}, $expected->{pixelRatio}); }; } }; }; sub get_actual_phones { return Selenium::UserAgent->new( agent => 'iphone', browserName => 'chrome' )->_specs; } runtests;
30.88172
84
0.517758
73f138b98054ddeca810c93621215e55b18157ac
3,845
pm
Perl
dependencies/lib/perl/BLATer.pm
jordan-rash/CICERO
040f4280a3a891c477613cb268715632b0301e74
[ "Apache-2.0" ]
19
2020-05-29T12:14:42.000Z
2022-03-17T13:40:58.000Z
dependencies/lib/perl/BLATer.pm
jordan-rash/CICERO
040f4280a3a891c477613cb268715632b0301e74
[ "Apache-2.0" ]
44
2020-02-03T16:49:35.000Z
2022-03-08T15:46:55.000Z
dependencies/lib/perl/BLATer.pm
jordan-rash/CICERO
040f4280a3a891c477613cb268715632b0301e74
[ "Apache-2.0" ]
13
2020-05-29T12:06:15.000Z
2022-02-24T22:11:27.000Z
package BLATer; # BLAT wrapper use strict; use Carp qw(confess); use Bio::SearchIO; use Configurable; use Exporter; use TemporaryFileWrangler; use WorkingFile; @BLATer::ISA = qw(Configurable Exporter); @BLATer::EXPORT_OK = qw(); use MethodMaker qw( tfw tempfile_base null_mode verbose minScore stepSize tileSize ); my $VERBOSE = 0; sub new { my ($type, %options) = @_; my $self = {}; bless $self, $type; my $tfw = new TemporaryFileWrangler(); # $tfw->verbose(1); $self->tempfile_base($tfw->get_tempfile("-glob" => 1)); $self->tfw($tfw); $self->configure(%options); return $self; } sub blat { my ($self, %options) = @_; my $parser; if ($self->null_mode) { $parser = Bio::SearchIO->new(); # not sure this will fly } else { my $db_fa = $self->fa_setup(($options{"-database"} || die "-database"), "database"); my $query_fa = $self->fa_setup(($options{"-query"} || die "-query"), "query"); my $outfile = $self->get_tempfile("-append" => ".blat"); printf STDERR "db=%s query=%s out=%s\n", $db_fa, $query_fa, $outfile if $VERBOSE; if ($ENV{DEBUG_BLAT_DB_FASTA}) { foreach my $ref (["query", $query_fa], ["db", $db_fa]) { my ($label, $file) = @{$ref}; printf STDERR "%s FASTA:\n", $label; open(DEBUGTMP, $file) || die; while(<DEBUGTMP>) { print STDERR $_; } } } my @cmd = "blat"; push @cmd, sprintf "-minScore=%d", $self->minScore if $self->minScore(); push @cmd, sprintf "-stepSize=%d", $self->stepSize if $self->stepSize(); push @cmd, sprintf "-tileSize=%d", $self->tileSize if $self->tileSize(); push @cmd, "-out=pslx"; if ($options{"-protein"}) { push @cmd, "-t=prot"; push @cmd, "-q=prot"; } push @cmd, $db_fa; push @cmd, $query_fa; push @cmd, $outfile; push @cmd, "> /dev/null" unless $VERBOSE; my $cmd = join " ", @cmd; printf STDERR "running %s\n", $cmd if $VERBOSE; system($cmd); die sprintf "error running %s, exit %d", $cmd, $? if $?; die "where is outfile $outfile" unless -f $outfile; if ($self->verbose) { printf STDERR "BLAT output:\n"; open(BLATTMP, $outfile) || die; while (<BLATTMP>) { print STDERR $_; } close BLATTMP; } $parser = Bio::SearchIO->new(-file => $outfile, -format => 'psl'); # no specific pslx parser?? } return $parser; } sub fa_setup { my ($self, $thing, $tag) = @_; my $fa_file; die unless $tag; if (ref $thing) { # hash of sequences $fa_file = $self->get_tempfile("-append" => sprintf ".%s.fa", $tag); write_fasta_set("-file" => $fa_file, "-reads" => $thing); } else { if (-f $thing) { # pre-built filename $fa_file = $thing; } else { # single sequence string $fa_file = $self->get_tempfile("-append" => sprintf ".%s.fa", $tag); my %reads; $reads{query} = $thing; write_fasta_set("-file" => $fa_file, "-reads" => \%reads); } } return $fa_file; } sub write_fasta_set { # hack: should probably figure out how to do w/SeqIO but this is so simple... my (%options) = @_; my $file = $options{"-file"} || die; my $reads = $options{"-reads"} || die; my $wf = new WorkingFile($file); my $fh = $wf->output_filehandle(); foreach my $id (sort keys %{$reads}) { my $sequence = $reads->{$id}; # QUESTION: mask *? how does blat deal with these? printf $fh ">%s\n%s\n", $id, $sequence; } $wf->finish(); } sub get_tempfile { my ($self, %options) = @_; my $append = $options{"-append"} || die "-append"; my $base = $self->tempfile_base() || die; return $base . $append; # glob mode will clean up these varieties } 1; # LRF support: # _______________ ______________________________ _______________ # \____/ \____/
23.734568
88
0.575813
73eff7adf068e59064cc0abeb34bd114bf88e342
780
pm
Perl
auto-lib/Paws/WorkLink/ListWebsiteAuthorizationProvidersResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
164
2015-01-08T14:58:53.000Z
2022-02-20T19:16:24.000Z
auto-lib/Paws/WorkLink/ListWebsiteAuthorizationProvidersResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
348
2015-01-07T22:08:38.000Z
2022-01-27T14:34:44.000Z
auto-lib/Paws/WorkLink/ListWebsiteAuthorizationProvidersResponse.pm
0leksii/aws-sdk-perl
b2132fe3c79a06fd15b6137e8a0eb628de722e0f
[ "Apache-2.0" ]
87
2015-04-22T06:29:47.000Z
2021-09-29T14:45:55.000Z
package Paws::WorkLink::ListWebsiteAuthorizationProvidersResponse; use Moose; has NextToken => (is => 'ro', isa => 'Str'); has WebsiteAuthorizationProviders => (is => 'ro', isa => 'ArrayRef[Paws::WorkLink::WebsiteAuthorizationProviderSummary]'); has _request_id => (is => 'ro', isa => 'Str'); 1; ### main pod documentation begin ### =head1 NAME Paws::WorkLink::ListWebsiteAuthorizationProvidersResponse =head1 ATTRIBUTES =head2 NextToken => Str The pagination token to use to retrieve the next page of results for this operation. If this value is null, it retrieves the first page. =head2 WebsiteAuthorizationProviders => ArrayRef[L<Paws::WorkLink::WebsiteAuthorizationProviderSummary>] The website authorization providers. =head2 _request_id => Str =cut
22.285714
124
0.744872
73d22b60c6f6b5d0786d5b0bf2178a9ea8c2ac94
5,826
al
Perl
Modules/System/Translation/src/TranslationImplementation.Codeunit.al
deerware/ALAppExtensions
9cfed2a7a54b733501aa0d26ea28a790b9badd06
[ "MIT" ]
null
null
null
Modules/System/Translation/src/TranslationImplementation.Codeunit.al
deerware/ALAppExtensions
9cfed2a7a54b733501aa0d26ea28a790b9badd06
[ "MIT" ]
null
null
null
Modules/System/Translation/src/TranslationImplementation.Codeunit.al
deerware/ALAppExtensions
9cfed2a7a54b733501aa0d26ea28a790b9badd06
[ "MIT" ]
null
null
null
// ------------------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // ------------------------------------------------------------------------------------------------ codeunit 3712 "Translation Implementation" { Access = Internal; Permissions = tabledata Translation = rimd; var NoRecordIdErr: Label 'The variant passed is not a record.'; CannotTranslateTempRecErr: Label 'Translations cannot be added or retrieved for temporary records.'; NotAValidRecordForTranslationErr: Label 'Translations cannot be added for the record on table %1.', Comment = '%1 - Table number'; procedure Any(): Boolean var Translation: Record Translation; begin exit(not Translation.IsEmpty()); end; procedure Get(RecVariant: Variant; FieldId: Integer; LanguageId: Integer; FallbackToWindows: Boolean): Text var Translation: Record Translation; SystemId: Guid; TableNo: Integer; begin GetSystemIdFromVariant(RecVariant, SystemId, TableNo); if Translation.Get(LanguageId, SystemId, FieldId) then exit(Translation.Value); if FallbackToWindows then if Translation.Get(WindowsLanguage(), SystemId, FieldId) then exit(Translation.Value); exit(''); end; procedure Get(RecVariant: Variant; FieldId: Integer; LanguageId: Integer): Text begin exit(Get(RecVariant, FieldId, LanguageId, false)); end; procedure Set(RecVariant: Variant; FieldId: Integer; Value: Text[2048]) begin Set(RecVariant, FieldId, GlobalLanguage(), Value); end; procedure Set(RecVariant: Variant; FieldId: Integer; LanguageId: Integer; Value: Text[2048]) var Translation: Record Translation; SystemId: Guid; TableNo: Integer; Exists: Boolean; begin GetSystemIdFromVariant(RecVariant, SystemId, TableNo); Exists := Translation.Get(LanguageId, SystemId, FieldId); if Exists then begin if Translation.Value <> Value then begin Translation.Value := Value; Translation.Modify(true); end; end else begin Translation.Init(); Translation."Language ID" := LanguageId; Translation."System ID" := SystemId; Translation."Table ID" := TableNo; Translation."Field ID" := FieldId; Translation.Value := Value; Translation.Insert(true); end; end; procedure Delete(RecVariant: Variant) var Translation: Record Translation; begin DeleteTranslations(RecVariant, Translation); end; procedure Delete(RecVariant: Variant; FieldId: Integer) var Translation: Record Translation; begin Translation.SetRange("Field ID", FieldId); DeleteTranslations(RecVariant, Translation); end; local procedure DeleteTranslations(RecVariant: Variant; var TranslationWithFilters: Record Translation) var RecordRef: RecordRef; begin GetRecordRefFromVariant(RecVariant, RecordRef); TranslationWithFilters.SetRange("System ID", GetSystemIdFromRecordRef(RecordRef)); TranslationWithFilters.DeleteAll(true); end; procedure Show(RecVariant: Variant; FieldId: Integer) var Translation: Record Translation; TranslationPage: Page Translation; SystemID: Guid; TableNo: Integer; begin GetSystemIdFromVariant(RecVariant, SystemID, TableNo); Translation.SetRange("System ID", SystemID); Translation.SetRange("Field ID", FieldId); TranslationPage.SetTableId(TableNo); TranslationPage.SetCaption(GetRecordIdCaptionFromVariant(RecVariant)); TranslationPage.SetTableView(Translation); TranslationPage.Run(); end; procedure ShowForAllRecords(TableId: Integer; FieldId: Integer) var Translation: Record Translation; begin Translation.SetRange("Table ID", TableId); Translation.SetRange("Field ID", FieldId); PAGE.Run(PAGE::Translation, Translation); end; local procedure GetRecordIdCaptionFromVariant(RecVariant: Variant): Text var RecordRef: RecordRef; RecordId: RecordId; begin GetRecordRefFromVariant(RecVariant, RecordRef); RecordId := RecordRef.RecordId(); exit(Format(RecordId)); end; local procedure GetSystemIdFromVariant(RecVariant: Variant; var SystemId: Guid; var TableNo: Integer) var RecordRef: RecordRef; begin GetRecordRefFromVariant(RecVariant, RecordRef); SystemId := GetSystemIdFromRecordRef(RecordRef); TableNo := RecordRef.Number(); end; local procedure GetSystemIdFromRecordRef(RecordRef: RecordRef) SystemId: Guid begin Evaluate(SystemId, Format(RecordRef.Field(RecordRef.SystemIdNo()).Value())); // TODO: Uptake new method to directly get SystemID from record ref as soon as it is available end; local procedure GetRecordRefFromVariant(RecVariant: Variant; var RecordRef: RecordRef) begin if RecVariant.IsRecord() then begin RecordRef.GetTable(RecVariant); if RecordRef.IsTemporary() then Error(CannotTranslateTempRecErr); if RecordRef.Number() = 0 then Error(NotAValidRecordForTranslationErr, 0); exit; end; if RecVariant.IsRecordRef() then begin RecordRef := RecVariant; exit; end; Error(NoRecordIdErr); end; }
34.473373
179
0.637487
73d0d4bb1e0db3206d604dc2136002cfff3b2057
3,941
pm
Perl
Mojoqq/perl/vendor/lib/Mojo/Home.pm
ghuan/Mojo-webqq-for-windows
ad44014da4578f99aa3efad0b55f0fc3bc3af322
[ "Unlicense" ]
null
null
null
Mojoqq/perl/vendor/lib/Mojo/Home.pm
ghuan/Mojo-webqq-for-windows
ad44014da4578f99aa3efad0b55f0fc3bc3af322
[ "Unlicense" ]
3
2016-09-22T07:23:29.000Z
2017-02-01T01:39:44.000Z
Mojoqq/perl/vendor/lib/Mojo/Home.pm
ghuan/Mojo-webqq-for-windows
ad44014da4578f99aa3efad0b55f0fc3bc3af322
[ "Unlicense" ]
10
2016-09-13T02:10:40.000Z
2021-07-11T23:11:01.000Z
package Mojo::Home; use Mojo::Base -base; use overload bool => sub {1}, '""' => sub { shift->to_string }, fallback => 1; use Cwd 'abs_path'; use File::Basename 'dirname'; use File::Spec::Functions qw(abs2rel catdir catfile splitdir); use FindBin; use Mojo::Util qw(class_to_path files); has parts => sub { [] }; sub detect { my ($self, $class) = @_; # Environment variable return $self->parts([splitdir abs_path $ENV{MOJO_HOME}]) if $ENV{MOJO_HOME}; # Try to find home from lib directory if ($class && (my $path = $INC{my $file = class_to_path $class})) { $path =~ s/\Q$file\E$//; my @home = splitdir $path; # Remove "lib" and "blib" pop @home while @home && ($home[-1] =~ /^b?lib$/ || !length $home[-1]); # Turn into absolute path return $self->parts([splitdir abs_path catdir(@home) || '.']); } # FindBin fallback return $self->parts([split '/', $FindBin::Bin]); } sub lib_dir { my $path = catdir @{shift->parts}, 'lib'; return -d $path ? $path : undef; } sub list_files { my ($self, $dir, $options) = (shift, shift // '', shift); $dir = catdir @{$self->parts}, split('/', $dir); return [map { join '/', splitdir abs2rel($_, $dir) } files $dir, $options]; } sub mojo_lib_dir { catdir dirname(__FILE__), '..' } sub new { @_ > 1 ? shift->SUPER::new->parse(@_) : shift->SUPER::new } sub parse { shift->parts([splitdir shift]) } sub rel_dir { catdir @{shift->parts}, split('/', shift) } sub rel_file { catfile @{shift->parts}, split('/', shift) } sub to_string { catdir @{shift->parts} } 1; =encoding utf8 =head1 NAME Mojo::Home - Home sweet home =head1 SYNOPSIS use Mojo::Home; # Find and manage the project root directory my $home = Mojo::Home->new; $home->detect; say $home->lib_dir; say $home->rel_file('templates/layouts/default.html.ep'); say "$home"; =head1 DESCRIPTION L<Mojo::Home> is a container for home directories. =head1 ATTRIBUTES L<Mojo::Home> implements the following attributes. =head2 parts my $parts = $home->parts; $home = $home->parts(['home', 'sri', 'myapp']); Home directory parts. =head1 METHODS L<Mojo::Home> inherits all methods from L<Mojo::Base> and implements the following new ones. =head2 detect $home = $home->detect; $home = $home->detect('My::App'); Detect home directory from the value of the C<MOJO_HOME> environment variable or application class. =head2 lib_dir my $path = $home->lib_dir; Path to C<lib> directory of application. =head2 list_files my $files = $home->list_files; my $files = $home->list_files('foo/bar'); my $files = $home->list_files('foo/bar', {hidden => 1}); Portably list all files recursively in directory relative to the home directory. # List layouts say $home->rel_file($_) for @{$home->list_files('templates/layouts')}; These options are currently available: =over 2 =item hidden hidden => 1 Include hidden files and directories. =back =head2 mojo_lib_dir my $path = $home->mojo_lib_dir; Path to C<lib> directory in which L<Mojolicious> is installed. =head2 new my $home = Mojo::Home->new; my $home = Mojo::Home->new('/home/sri/my_app'); Construct a new L<Mojo::Home> object and L</"parse"> home directory if necessary. =head2 parse $home = $home->parse('/home/sri/my_app'); Parse home directory. =head2 rel_dir my $path = $home->rel_dir('foo/bar'); Portably generate an absolute path for a directory relative to the home directory. =head2 rel_file my $path = $home->rel_file('foo/bar.html'); Portably generate an absolute path for a file relative to the home directory. =head2 to_string my $str = $home->to_string; Home directory. =head1 OPERATORS L<Mojo::Home> overloads the following operators. =head2 bool my $bool = !!$home; Always true. =head2 stringify my $str = "$home"; Alias for L</"to_string">. =head1 SEE ALSO L<Mojolicious>, L<Mojolicious::Guides>, L<http://mojolicious.org>. =cut
20.419689
80
0.662015
73d911f68e2d377f354cbf48b2e8adecbc5a7b6f
1,438
pm
Perl
perl/lib/IO/Compress/Adapter/Identity.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
4
2018-04-20T07:27:13.000Z
2021-12-21T05:19:24.000Z
perl/lib/IO/Compress/Adapter/Identity.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
4
2021-03-10T19:10:00.000Z
2021-05-11T14:58:19.000Z
perl/lib/IO/Compress/Adapter/Identity.pm
mnikolop/Thesis_project_CyberDoc
9a37fdd5a31de24cb902ee31ef19eb992faa1665
[ "Apache-2.0" ]
1
2019-11-12T02:29:26.000Z
2019-11-12T02:29:26.000Z
package IO::Compress::Adapter::Identity ; use strict; use warnings; use bytes; use IO::Compress::Base::Common 2.060 qw(:Status); our ($VERSION); $VERSION = '2.060'; sub mkCompObject { my $level = shift ; my $strategy = shift ; return bless { 'CompSize' => 0, 'UnCompSize' => 0, 'Error' => '', 'ErrorNo' => 0, } ; } sub compr { my $self = shift ; if (defined ${ $_[0] } && length ${ $_[0] }) { $self->{CompSize} += length ${ $_[0] } ; $self->{UnCompSize} = $self->{CompSize} ; if ( ref $_[1] ) { ${ $_[1] } .= ${ $_[0] } } else { $_[1] .= ${ $_[0] } } } return STATUS_OK ; } sub flush { my $self = shift ; return STATUS_OK; } sub close { my $self = shift ; return STATUS_OK; } sub reset { my $self = shift ; $self->{CompSize} = 0; $self->{UnCompSize} = 0; return STATUS_OK; } sub deflateParams { my $self = shift ; return STATUS_OK; } #sub total_out #{ # my $self = shift ; # return $self->{UnCompSize} ; #} # #sub total_in #{ # my $self = shift ; # return $self->{UnCompSize} ; #} sub compressedBytes { my $self = shift ; return $self->{UnCompSize} ; } sub uncompressedBytes { my $self = shift ; return $self->{UnCompSize} ; } 1; __END__
14.098039
50
0.476356
73d10e7a547437f48726b95edc4252e087a8af63
2,356
t
Perl
t/selection.t
manwar/perl-tcl-ptk
744bafb4928390bbbb5861466d8c16bb01cef120
[ "Artistic-1.0-Perl" ]
3
2018-10-06T07:53:53.000Z
2021-02-20T17:56:41.000Z
t/selection.t
manwar/perl-tcl-ptk
744bafb4928390bbbb5861466d8c16bb01cef120
[ "Artistic-1.0-Perl" ]
22
2018-09-16T02:48:35.000Z
2021-12-13T11:14:46.000Z
t/selection.t
manwar/perl-tcl-ptk
744bafb4928390bbbb5861466d8c16bb01cef120
[ "Artistic-1.0-Perl" ]
3
2018-08-26T15:29:05.000Z
2019-10-28T15:35:15.000Z
use warnings; use strict; use Tcl::pTk; #use Tk; use Test; plan tests => 9; $| = 1; # Pipes Hot my $top = MainWindow->new; #$top->option('add','*Text.background'=>'white'); my $t = $top->Scrolled('Text',"-relief" => "raised", "-bd" => "2", "-setgrid" => "true"); $t->pack(-expand => 1, "-fill" => "both"); my $text = "This window is a text widget. It displays one or more lines of text and allows you to edit the text."; $t->insert("0.0",$text); #$top->after(1000,sub{$top->destroy}); $t->selectAll(); my $sel = $t->SelectionGet; ok($sel, $text."\n", "Unexpected text returned from SelectionGet"); #print "SelectAll = '$sel'\n"; $t->tagRemove('sel','1.0','end'); $t->tagAdd('sel','1.0','1.10'); $sel = $t->SelectionGet(); #print "SelectPartial = '$sel'\n"; ok($sel, "This windo", "Unexpected partial selection"); $t->SelectionClear(); $sel = eval{ $t->SelectionGet();}; $sel ||= ''; ok($sel, '', "Unexpected text after SelectionClear"); #print "SelectClear = '$sel'\n"; $t->tagRemove('sel','1.0','end'); $t->tagAdd('sel','1.0','1.10'); my $owner = $t->SelectionOwner(); #print "selection owner = '$owner' ref = ".ref($owner)."\n"; ok(ref($owner), 'Tcl::pTk::Text', "Unexpected object type for SelectionOwner"); # Test the clipboard $t->tagRemove('sel','1.0','end'); $t->tagAdd('sel','1.0','1.10'); my $val = $t->clipboardCopy; ok($val, "This windo", "Unexpected results of clipboardCopy"); #print "clip = $val\n"; my $get = $t->clipboardGet(); ok($val, "This windo", "Unexpected results of clipboardGet"); #print "clip = $get\n"; ###### SelectionHanldle Test ##### $t->SelectionOwn( -selection => 'CLIPBOARD'); # Make sure $t owns the selection # Setup SelectionHandle Callback $t->SelectionHandle( -selection => 'CLIPBOARD', #$t->interp->call('selection', 'handle', -selection => 'CLIPBOARD', $t, sub{ my @args = @_; #print "selection handle args ".join(", ", @args)."\n"; ok($args[0], 0, "1st SelectionHandle Arg is zero"); ok($args[1] =~ /^\d+$/, 1, "2nd SelectionHandle Arg is number"); return "Selection Handle Return"; } ); $sel = $t->SelectionGet(-selection => 'CLIPBOARD'); ok( $sel, "Selection Handle Return", "Selection Returns the right value"); #MainLoop;
25.89011
80
0.581494
ed20f480d4efdac2984e1c2eca9b1902ebbe9a99
2,966
pl
Perl
postgis/build/postgis-2.5.4/utils/svn_repo_revision.pl
khannaekta/geospatial
d5c5c38640ae0cefada63787dbd29a373f995a21
[ "OLDAP-2.5", "OLDAP-2.4", "OLDAP-2.6" ]
23
2017-07-09T15:19:17.000Z
2022-03-05T07:26:49.000Z
postgis/build/postgis-2.5.4/utils/svn_repo_revision.pl
khannaekta/geospatial
d5c5c38640ae0cefada63787dbd29a373f995a21
[ "OLDAP-2.5", "OLDAP-2.4", "OLDAP-2.6" ]
12
2017-11-27T17:28:09.000Z
2022-01-21T17:01:07.000Z
postgis/build/postgis-2.5.4/utils/svn_repo_revision.pl
khannaekta/geospatial
d5c5c38640ae0cefada63787dbd29a373f995a21
[ "OLDAP-2.5", "OLDAP-2.4", "OLDAP-2.6" ]
22
2017-07-13T17:59:21.000Z
2022-02-23T18:58:03.000Z
#!/usr/bin/perl $ENV{"LC_ALL"} = "C"; use warnings; use strict; my $top_srcdir = "."; my $rev_file = $top_srcdir.'/postgis_svn_revision.h'; my $target = 'local'; $target = $ARGV[0] if $ARGV[0]; # Read the svn revision number my $svn_rev = &read_rev($target); # Write it &write_defn($svn_rev); sub read_rev { my $target = shift; #print STDERR "Target: $target\n"; my $svn_info; if ( $target eq "local" ) { if ( -d $top_srcdir."/.svn" ) { #print STDERR "There's a ". $top_srcdir."/.svn dir\n"; $svn_info = &read_rev_svn($target); } elsif ( -e $top_srcdir."/.git" ) { #print STDERR "There's a ". $top_srcdir."/.git dir\n"; $svn_info = &read_rev_git(); } else { print STDERR "Can't fetch local revision (neither .svn nor .git found)\n"; $svn_info = 0; } } else { $svn_info = &read_rev_svn($target); } return $svn_info; } sub read_rev_git { # TODO: test on old systems, I think I saw some `which` # implementations returning "nothing found" or something # like that, making the later if ( ! $svn_exe ) always false # my $git_exe = `which git`; if ( ! $git_exe ) { print STDERR "Can't fetch SVN revision: no git executable found\n"; return 0; } chop($git_exe); my $cmd = "\"${git_exe}\" log --grep=git-svn -1 | grep git-svn | cut -d@ -f2 | cut -d' ' -f1"; #print STDERR "cmd: ${cmd}\n"; my $rev = `$cmd`; if ( ! $rev ) { print STDERR "Can't fetch SVN revision from git log\n"; $rev = 0; } else { chop($rev); } return $rev; } sub read_rev_svn { my $target = shift; # TODO: test on old systems, I think I saw some `which` # implementations returning "nothing found" or something # like that, making the later if ( ! $svn_exe ) always false # my $svn_exe = `which svn`; if ( ! $svn_exe ) { print STDERR "Can't fetch SVN revision: no svn executable found\n"; return 0; } chop($svn_exe); my $svn_info; if ( $target eq "local" ) { $svn_info = `"${svn_exe}" info`; } else { $svn_info = `"${svn_exe}" info $target`; } my $rev; if ( $svn_info =~ /Last Changed Rev: (\d+)/ ) { $rev = $1; } else { print STDERR "Can't fetch SVN revision: no 'Loast Changed Rev' in `svn info` output\n"; $rev = 0; } return $rev; } sub write_defn { my $rev = shift; my $oldrev = 0; # Do not override the file if new detected # revision isn't zero nor different from the existing one if ( -f $rev_file ) { open(IN, "<$rev_file"); my $oldrevline = <IN>; if ( $oldrevline =~ /POSTGIS_SVN_REVISION (.*)/ ) { $oldrev = $1; } close(IN); if ( $rev == 0 or $rev == $oldrev ) { print STDERR "Not updating existing rev file at $oldrev\n"; return; } } my $string = "#define POSTGIS_SVN_REVISION $rev\n"; open(OUT,">$rev_file"); print OUT $string; close(OUT); print STDERR "Wrote rev file at $rev\n"; }
22.134328
96
0.581254
73f96a9ee88d23414b3b3df12124505acb75c420
7,414
pm
Perl
lib/Google/Ads/AdWords/v201809/BudgetOrderService/BudgetOrderServiceInterfacePort.pm
googleads/googleads-perl-lib
69e66d7e46fbd8ad901581b108ea6c14212701cf
[ "Apache-2.0" ]
4
2015-04-23T01:59:40.000Z
2021-10-12T23:14:36.000Z
lib/Google/Ads/AdWords/v201809/BudgetOrderService/BudgetOrderServiceInterfacePort.pm
googleads/googleads-perl-lib
69e66d7e46fbd8ad901581b108ea6c14212701cf
[ "Apache-2.0" ]
23
2015-02-19T17:03:58.000Z
2019-07-01T10:15:46.000Z
lib/Google/Ads/AdWords/v201809/BudgetOrderService/BudgetOrderServiceInterfacePort.pm
googleads/googleads-perl-lib
69e66d7e46fbd8ad901581b108ea6c14212701cf
[ "Apache-2.0" ]
10
2015-08-03T07:51:58.000Z
2020-09-26T16:17:46.000Z
package Google::Ads::AdWords::v201809::BudgetOrderService::BudgetOrderServiceInterfacePort; use strict; use warnings; use Class::Std::Fast::Storable; use Scalar::Util qw(blessed); use base qw(SOAP::WSDL::Client::Base); # only load if it hasn't been loaded before require Google::Ads::AdWords::v201809::TypeMaps::BudgetOrderService if not Google::Ads::AdWords::v201809::TypeMaps::BudgetOrderService->can('get_class'); sub START { $_[0]->set_proxy('https://adwords.google.com/api/adwords/billing/v201809/BudgetOrderService') if not $_[2]->{proxy}; $_[0]->set_class_resolver('Google::Ads::AdWords::v201809::TypeMaps::BudgetOrderService') if not $_[2]->{class_resolver}; $_[0]->set_prefix($_[2]->{use_prefix}) if exists $_[2]->{use_prefix}; } sub get { my ($self, $body, $header) = @_; die "get must be called as object method (\$self is <$self>)" if not blessed($self); return $self->SUPER::call({ operation => 'get', soap_action => '', style => 'document', body => { 'use' => 'literal', namespace => 'http://schemas.xmlsoap.org/wsdl/soap/', encodingStyle => '', parts => [qw( Google::Ads::AdWords::v201809::BudgetOrderService::get )], }, header => { 'use' => 'literal', namespace => 'http://schemas.xmlsoap.org/wsdl/soap/', encodingStyle => '', parts => [qw( Google::Ads::AdWords::v201809::BudgetOrderService::RequestHeader )], }, headerfault => { } }, $body, $header); } sub getBillingAccounts { my ($self, $body, $header) = @_; die "getBillingAccounts must be called as object method (\$self is <$self>)" if not blessed($self); return $self->SUPER::call({ operation => 'getBillingAccounts', soap_action => '', style => 'document', body => { 'use' => 'literal', namespace => 'http://schemas.xmlsoap.org/wsdl/soap/', encodingStyle => '', parts => [qw( Google::Ads::AdWords::v201809::BudgetOrderService::getBillingAccounts )], }, header => { 'use' => 'literal', namespace => 'http://schemas.xmlsoap.org/wsdl/soap/', encodingStyle => '', parts => [qw( Google::Ads::AdWords::v201809::BudgetOrderService::RequestHeader )], }, headerfault => { } }, $body, $header); } sub mutate { my ($self, $body, $header) = @_; die "mutate must be called as object method (\$self is <$self>)" if not blessed($self); return $self->SUPER::call({ operation => 'mutate', soap_action => '', style => 'document', body => { 'use' => 'literal', namespace => 'http://schemas.xmlsoap.org/wsdl/soap/', encodingStyle => '', parts => [qw( Google::Ads::AdWords::v201809::BudgetOrderService::mutate )], }, header => { 'use' => 'literal', namespace => 'http://schemas.xmlsoap.org/wsdl/soap/', encodingStyle => '', parts => [qw( Google::Ads::AdWords::v201809::BudgetOrderService::RequestHeader )], }, headerfault => { } }, $body, $header); } 1; __END__ =pod =head1 NAME Google::Ads::AdWords::v201809::BudgetOrderService::BudgetOrderServiceInterfacePort - SOAP Interface for the BudgetOrderService Web Service =head1 SYNOPSIS use Google::Ads::AdWords::v201809::BudgetOrderService::BudgetOrderServiceInterfacePort; my $interface = Google::Ads::AdWords::v201809::BudgetOrderService::BudgetOrderServiceInterfacePort->new(); my $response; $response = $interface->get(); $response = $interface->getBillingAccounts(); $response = $interface->mutate(); =head1 DESCRIPTION SOAP Interface for the BudgetOrderService web service located at https://adwords.google.com/api/adwords/billing/v201809/BudgetOrderService. =head1 SERVICE BudgetOrderService =head2 Port BudgetOrderServiceInterfacePort =head1 METHODS =head2 General methods =head3 new Constructor. All arguments are forwarded to L<SOAP::WSDL::Client|SOAP::WSDL::Client>. =head2 SOAP Service methods Method synopsis is displayed with hash refs as parameters. The commented class names in the method's parameters denote that objects of the corresponding class can be passed instead of the marked hash ref. You may pass any combination of objects, hash and list refs to these methods, as long as you meet the structure. List items (i.e. multiple occurences) are not displayed in the synopsis. You may generally pass a list ref of hash refs (or objects) instead of a hash ref - this may result in invalid XML if used improperly, though. Note that SOAP::WSDL always expects list references at maximum depth position. XML attributes are not displayed in this synopsis and cannot be set using hash refs. See the respective class' documentation for additional information. =head3 get Gets a list of {@link BudgetOrder}s using the generic selector. @param serviceSelector specifies which BudgetOrder to return. @return A {@link BudgetOrderPage} of BudgetOrders of the client customer. All BudgetOrder fields are returned. Stats are not yet supported. @throws ApiException Returns a L<Google::Ads::AdWords::v201809::BudgetOrderService::getResponse|Google::Ads::AdWords::v201809::BudgetOrderService::getResponse> object. $response = $interface->get( { serviceSelector => $a_reference_to, # see Google::Ads::AdWords::v201809::Selector },, ); =head3 getBillingAccounts Returns all the open/active BillingAccounts associated with the current manager. @return A list of {@link BillingAccount}s. @throws ApiException Returns a L<Google::Ads::AdWords::v201809::BudgetOrderService::getBillingAccountsResponse|Google::Ads::AdWords::v201809::BudgetOrderService::getBillingAccountsResponse> object. $response = $interface->getBillingAccounts( { },, ); =head3 mutate Adds, updates, or removes budget orders. Supported operations are: <p><code>ADD</code>: Adds a {@link BudgetOrder} to the billing account specified by the billing account ID.</p> <p><code>SET</code>: Sets the start/end date and amount of the {@link BudgetOrder}.</p> <p><code>REMOVE</code>: Cancels the {@link BudgetOrder} (status change).</p> <p class="warning"><b>Warning:</b> The <code>BudgetOrderService</code> is limited to one operation per mutate request. Any attempt to make more than one operation will result in an <code>ApiException</code>.</p> <p class="note"><b>Note:</b> This action is available only on a whitelist basis.</p> @param operations A list of operations, <b>however currently we only support one operation per mutate call</b>. @return BudgetOrders affected by the mutate operation. @throws ApiException Returns a L<Google::Ads::AdWords::v201809::BudgetOrderService::mutateResponse|Google::Ads::AdWords::v201809::BudgetOrderService::mutateResponse> object. $response = $interface->mutate( { operations => $a_reference_to, # see Google::Ads::AdWords::v201809::BudgetOrderOperation },, ); =head1 AUTHOR Generated by SOAP::WSDL on Thu Sep 20 11:05:33 2018 =cut
33.547511
829
0.654707
ed0348d0be20fc1553c2f0317f9b9dd7fa4ba2ff
2,018
pm
Perl
lib/Test2/Harness/UI/Queries.pm
adamgsg/Test2-Harness-UI
4fefbad962172be0f199c2410f99322c8b71ec3f
[ "Artistic-1.0", "MIT" ]
null
null
null
lib/Test2/Harness/UI/Queries.pm
adamgsg/Test2-Harness-UI
4fefbad962172be0f199c2410f99322c8b71ec3f
[ "Artistic-1.0", "MIT" ]
null
null
null
lib/Test2/Harness/UI/Queries.pm
adamgsg/Test2-Harness-UI
4fefbad962172be0f199c2410f99322c8b71ec3f
[ "Artistic-1.0", "MIT" ]
null
null
null
package Test2::Harness::UI::Queries; use strict; use warnings; our $VERSION = '0.000084'; use Carp qw/croak/; use Test2::Harness::UI::Util::HashBase qw/-config/; sub init { my $self = shift; croak "'config' is a required attribute" unless $self->{+CONFIG}; } sub projects { my $self = shift; my $dbh = $self->{+CONFIG}->connect; my $sth = $dbh->prepare('SELECT name FROM projects ORDER BY name ASC'); $sth->execute() or die $sth->errstr; my $rows = $sth->fetchall_arrayref; return [map { $_->[0] } @$rows]; } sub versions { $_[0]->_from_project(version => $_[1]) } sub categories { $_[0]->_from_project(category => $_[1]) } sub tiers { $_[0]->_from_project(tier => $_[1]) } sub builds { $_[0]->_from_project(build => $_[1]) } sub _from_project { my $self = shift; my ($field, $project_name) = @_; croak "project_name is required" unless defined $project_name; my $dbh = $self->{+CONFIG}->connect; my $schema = $self->{+CONFIG}->schema; my $project = $schema->resultset('Project')->find({name => $project_name}) or return []; my $sth = $dbh->prepare("SELECT distinct($field) FROM runs WHERE project_id = ? ORDER BY $field ASC"); $sth->execute($project->project_id) or die $sth->errstr; my $rows = $sth->fetchall_arrayref; return [map { $_->[0] } @$rows]; } 1; __END__ =pod =encoding UTF-8 =head1 NAME Test2::Harness::UI::Queries =head1 DESCRIPTION =head1 SYNOPSIS TODO =head1 SOURCE The source code repository for Test2-Harness-UI can be found at F<http://github.com/Test-More/Test2-Harness-UI/>. =head1 MAINTAINERS =over 4 =item Chad Granum E<lt>exodist@cpan.orgE<gt> =back =head1 AUTHORS =over 4 =item Chad Granum E<lt>exodist@cpan.orgE<gt> =back =head1 COPYRIGHT Copyright 2019 Chad Granum E<lt>exodist7@gmail.comE<gt>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See F<http://dev.perl.org/licenses/> =cut
19.980198
106
0.647175
73e3dbe789169ffaf7554e7444be673984401296
28,415
t
Perl
t/unit.t
gryphonshafer/Bible-Reference
954585b92a35009dd6bc4ce28b09891f4c3ac6fc
[ "ClArtistic" ]
1
2018-02-21T16:43:29.000Z
2018-02-21T16:43:29.000Z
t/unit.t
gryphonshafer/Bible-Reference
954585b92a35009dd6bc4ce28b09891f4c3ac6fc
[ "ClArtistic" ]
1
2017-08-17T10:24:27.000Z
2017-08-17T14:06:40.000Z
t/unit.t
gryphonshafer/Bible-Reference
954585b92a35009dd6bc4ce28b09891f4c3ac6fc
[ "ClArtistic" ]
1
2017-08-17T10:19:13.000Z
2017-08-17T10:19:13.000Z
use Test2::V0; use Bible::Reference; my $obj; ok( lives { $obj = Bible::Reference->new }, 'new' ) or note $@; isa_ok( $obj, 'Bible::Reference' ); my $test_data = [ undef, 0, '', 'Text with no Reference 3:16 data included', 'Text Samuel 3:15 said in 1 Samuel 4:16 that 2 Samuel 3-5 was as clear as 1 Peter in full', 'Text Pet text II Pet text II Pet 3:15 text 2pt 3-4 text ' . '2 Peter 3:15-17, 18, 20-22, 2 Peter 5:1 text', 'The book of rev. The verse of rEv. 3:15. The book of Rev.', 'Books of Revel, Gal, and Roma exist', 'Verses Mark 12:4 and Mark 12:3-5 and Mark 12:4-7, 13:1-2 and Genesis 4:1 and Genesis 1:2 exist', 'Mark 3:15-17, Ps 117, 3 John, Mark 3:6, 20-23, Mark 4-5', 'A = Matthew 1:18-25, 2-12, 14-22, 28-26 = A', 'B = Romans, James = B', 'C = Acts 1-20 = C', 'D = Galatians, Ephesians, Philippians, Colossians = D', 'E = Luke 1-3:23, 9-11, 13-19, 21-24 = E', 'F = 1 Corinthians, 2 Corinthians = F', 'G = John = G', 'H = Hebrews, 1 Peter, 2 Peter = H', ]; attributes_and_classes(); bible_type(); in_and_clear(); require_settings(); books(); expand_ranges(); as_array(); as_hash(); as_verses(); as_runs(); as_chapters(); as_books(); refs(); as_text(); set_bible_data(); done_testing; sub attributes_and_classes { can_ok( $obj, $_ ) for ( qw( acronyms sorting require_verse_match require_book_ucfirst minimum_book_length add_detail bible new expand_ranges in clear books as_array as_hash as_verses as_runs as_chapters as_books refs as_text set_bible_data ) ); } sub bible_type { is( $obj->bible, 'Protestant', 'default bible() set ok'); is( $obj->bible('c'), 'Catholic', 'can set "Catholic" with bible("c")' ); is( $obj->bible, 'Catholic', 'bible type set to "Catholic"'); is( $obj->bible('ogh'), 'Orthodox', 'can set "Orthodox" with bible("ogh")' ); is( $obj->bible, 'Orthodox', 'bible type set to "Orthodox"'); like( dies { $obj->bible('barf') }, qr/^Could not determine a valid Bible type from input/, 'fails to set bible("barf")', ); } sub in_and_clear { ok( lives { $obj->clear }, 'clear lives', ) or note $@; is( $obj->_data, [], 'in() is empty' ); ok( lives { $obj->in('Text with I Pet 3:16 and Rom 12:13-14,17 references in it.') }, 'in("text") lives', ) or note $@; is( $obj->_data, [ [ 'Text with ', [ '1 Peter', [ [ 3, [16] ] ] ], ' and ', [ 'Romans', [ [ 12, [ 13, 14, 17 ] ] ] ], ' references in it.', ], ], 'in() is set correctly' ); ok( lives { $obj->in('Text with Roms 12:16, 13:14-15 in it.') }, 'in("text 2") lives', ) or note $@; is( $obj->_data, [ [ 'Text with ', [ '1 Peter', [ [ 3, [16] ] ] ], ' and ', [ 'Romans', [ [ 12, [ 13, 14, 17 ] ] ] ], ' references in it.', ], [ 'Text with ', [ 'Romans', [ [ 12, [16] ], [ 13, [ 14, 15 ] ], ], ], ' in it.' ], ], 'in() is set correctly' ); ok( lives { $obj->in( 'Even more text with Jam 1:5 in it.', 'And one last bit of text with 1 Cor 12:8-12 in it.', ); }, 'in( "text 3", "text 4" ) lives', ) or note $@; is( $obj->_data, [ [ 'Text with ', [ '1 Peter', [ [ 3, [16] ] ] ], ' and ', [ 'Romans', [ [ 12, [ 13, 14, 17 ] ] ] ], ' references in it.', ], [ 'Text with ', [ 'Romans', [ [ 12, [16] ], [ 13, [ 14, 15 ] ], ], ], ' in it.' ], [ 'Even more text with ', [ 'James', [ [ 1, [5] ] ] ], ' in it.' ], [ 'And one last bit of text with ', [ '1 Corinthians', [ [ 12, [ 8, 9, 10, 11, 12 ] ] ] ], ' in it.' ], ], 'in() is set correctly' ); ok( lives { $obj->clear }, 'clear lives', ) or note $@; is( $obj->_data, [], '_data is empty' ); } sub require_settings { $obj->clear->require_book_ucfirst(1); is( $obj->in('header romans 12:13 footer')->_data, [ ['header romans 12:13 footer'], ], '"romans 12:13" and require_book_ucfirst(0)' ); $obj->clear->require_book_ucfirst(0); is( $obj->in('header romans 12:13 footer')->_data, [ [ 'header ', [ 'Romans', [[ 12, [13]]]], ' footer' ], ], '"romans 12:13" and require_book_ucfirst(1)' ); $obj->clear->require_verse_match(1); is( $obj->in('header romans 12 footer')->_data, [ ['header romans 12 footer'], ], '"romans 12" and require_verse_match(1)' ); $obj->clear->require_verse_match(0); is( $obj->in('header romans 12 footer')->_data, [ [ 'header ', [ 'Romans', [[12]]], ' footer' ], ], '"romans 12" and require_verse_match(0)' ); } sub books { my @books; $obj->bible('Protestant'); ok( lives { @books = $obj->books }, 'books lives', ) or note $@; is( scalar @books, 66, 'Protestant book count' ); is( $books[0], 'Genesis', 'Protestant Genesis location' ); is( $books[1], 'Exodus', 'Protestant Exodus location' ); is( $books[-1], 'Revelation', 'Protestant Revelation location' ); $obj->bible('Catholic'); @books = $obj->books; is( scalar @books, 73, 'Catholic book count' ); is( $books[0], 'Genesis', 'Catholic Genesis location' ); is( $books[1], 'Exodus', 'Catholic Exodus location' ); is( $books[-1], 'Revelation', 'Catholic Revelation location' ); $obj->bible('Orthodox'); @books = $obj->books; is( scalar @books, 78, 'Orthodox book count' ); is( $books[0], 'Genesis', 'Orthodox Genesis location' ); is( $books[1], 'Exodus', 'Orthodox Exodus location' ); is( $books[-1], 'Revelation', 'Orthodox Revelation location' ); $obj->bible('Vulgate'); @books = $obj->books; is( scalar @books, 73, 'Vulgate book count' ); is( $books[0], 'Genesis', 'Vulgate Genesis location' ); is( $books[1], 'Exodus', 'Vulgate Exodus location' ); is( $books[-1], 'Revelation', 'Vulgate Revelation location' ); } sub expand_ranges { $obj->bible('Protestant'); is( $obj->expand_ranges( 'Mark', '3-3', 1 ), '3', 'C: "3-3" = consider as "3"' ); is( $obj->expand_ranges( 'Mark', '3-5', 1 ), '3,4,5', 'D: "3-5" = consider as a simple range' ); is( $obj->expand_ranges( 'Mark', '5-3', 1 ), '5,4,3', 'E: "5-3" = consider as a simple reversed range' ); is( $obj->expand_ranges( 'Mark', '1:3-7', 1 ), '1:3,4,5,6,7', 'F: "1:3-7" = consider 3-7 as verses' ); is( $obj->expand_ranges( 'Mark', '1:43-3', 1 ), '1:43,44,45;2;3', 'G: "1:43-3" = consider 3 a chapter' ); is( $obj->expand_ranges( 'Mark', '1:3-3', 1 ), '1:' . join( ',', 3 .. 45 ) . ';2;3', 'H: "1:3-3" = consider the second 3 a chapter', ); is( $obj->expand_ranges( 'Mark', '3:2-3', 1 ), '3:2,3', 'I: "3:2-3" = consider 2-3 as verses' ); is( $obj->expand_ranges( 'Mark', '3:3-2', 1 ), '3:3,2', 'J: "3:3-2" = consider 3-2 as verses' ); is( $obj->expand_ranges( 'Mark', '3-5:2', 1 ), '3;4;5:1,2', 'K: "3-5:2" = 3-4 are full chapters; plus 5:1-5:2', ); is( $obj->expand_ranges( 'Mark', '3-3:2', 1 ), '3:1,2', 'L: "3-3:2" = interpretted as "3:1-2"' ); is( $obj->expand_ranges( 'Mark', '3:4-4:7', 1 ), '3:' . join( ',', 4 .. 35 ) . ';4:1,2,3,4,5,6,7', 'M: "3:4-4:7" becomes "3:4-*;4:1-7"', ); is( $obj->expand_ranges( 'Mark', '4:7-3:4', 1 ), '4:7,6,5,4,3,2,1;3:' . join( ',', reverse 4 .. 35 ), 'N: "4:7-3:4" becomes reverse of "3:4-*;4:1-7"', ); is( $obj->expand_ranges( 'Mark', '3:4-5:2', 1 ), '3:' . join( ',', 4 .. 35 ) . ';4;5:1,2', 'O: "3:4-5:2" becomes "3:4-*;4;5:1-2"', ); is( $obj->expand_ranges( 'Mark', '5:2-3:4', 1 ), '5:2,1;4;3:' . join( ',', reverse 4 .. 35 ), 'P: "5:2-3:4" becomes reverse of "3:4-*;4;5:2-*"', ); is( $obj->expand_ranges( 'Mark', '5-3:4', 1 ), '5:1;4;3:' . join( ',', reverse 4 .. 35 ), 'A: "5-3:4" = translated to "5:1-3:4"', ); is( $obj->expand_ranges( 'Mark', '3:4-3:7', 1 ), '3:4,5,6,7', 'B: "3:4-3:7" = translated to "3:4-7"', ); is( $obj->expand_ranges( 'Mark', '3:37-3:4', 1 ), '3:' . join( ',', reverse 4 .. 37 ), 'Q: "3:37-3:4" is the reverse of 3:4-3:37', ); is( $obj->expand_ranges( 'Mark', '4:37-9', 1 ), '4:37,38,39,40,41;5;6;7;8;9', '4:37-9', ); is( $obj->expand_ranges( 'Mark', '3:23-27,4:37-9,6', 1 ), '3:23,24,25,26,27,4:37,38,39,40,41;5;6;7;8;9,6', '3:23-27,4:37-9,6', ); is( $obj->expand_ranges( 'Mark', '4:37-5:9', 1 ), '4:37,38,39,40,41;5:1,2,3,4,5,6,7,8,9', '4:37-5:9', ); is( $obj->expand_ranges( 'Mark', '3:23-27,4:37-5:9,6', 1 ), '3:23,24,25,26,27,4:37,38,39,40,41;5:1,2,3,4,5,6,7,8,9,6', '3:23-27,4:37-5:9,6', ); } sub as_array { $obj->clear->acronyms(0); $obj->in(@$test_data); my $refs; ok( lives { $refs = $obj->as_array }, 'as_array lives' ) or note $@; is( $refs, [ [ 'Genesis', [ [ 1, [ 2 ] ], [ 4, [ 1 ] ] ] ], [ '1 Samuel', [ [ 4, [ 16 ] ] ] ], [ '2 Samuel', [ [ 3 ], [ 4 ], [ 5 ] ] ], [ 'Psalm', [ [ 117 ] ] ], [ 'Matthew', [ [ 1, [ 18, 19, 20, 21, 22, 23, 24, 25 ] ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 10 ], [ 11 ], [ 12 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 20 ], [ 21 ], [ 22 ], [ 26 ], [ 27 ], [ 28 ] ] ], [ 'Mark', [ [ 3, [ 6, 15, 16, 17, 20, 21, 22, 23 ] ], [ 4 ], [ 5 ], [ 12, [ 3, 4, 5, 6, 7 ] ], [ 13, [ 1, 2 ] ] ] ], [ 'Luke', [ [ 1 ], [ 2 ], [ 3, [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ] ], [ 9 ], [ 10 ], [ 11 ], [ 13 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 21 ], [ 22 ], [ 23 ], [ 24 ] ] ], [ 'John' ], [ 'Acts', [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 10 ], [ 11 ], [ 12 ], [ 13 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 20 ] ] ], [ 'Romans' ], [ '1 Corinthians' ], [ '2 Corinthians' ], [ 'Galatians' ], [ 'Ephesians' ], [ 'Philippians' ], [ 'Colossians' ], [ 'Hebrews' ], [ 'James' ], [ '1 Peter' ], [ '2 Peter', [ [ 3, [ 15, 16, 17, 18, 20, 21, 22 ] ], [ 4 ], [ 5, [ 1 ] ] ] ], [ '3 John' ], [ 'Revelation', [ [ 3, [ 15 ] ] ] ] ], 'as_array data normal', ); $obj->acronyms(1); $refs = $obj->as_array; is( $refs, [ [ 'Ge', [ [ 1, [ 2 ] ], [ 4, [ 1 ] ] ] ], [ '1Sa', [ [ 4, [ 16 ] ] ] ], [ '2Sa', [ [ 3 ], [ 4 ], [ 5 ] ] ], [ 'Ps', [ [ 117 ] ] ], [ 'Mt', [ [ 1, [ 18, 19, 20, 21, 22, 23, 24, 25 ] ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 10 ], [ 11 ], [ 12 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 20 ], [ 21 ], [ 22 ], [ 26 ], [ 27 ], [ 28 ] ] ], [ 'Mk', [ [ 3, [ 6, 15, 16, 17, 20, 21, 22, 23 ] ], [ 4 ], [ 5 ], [ 12, [ 3, 4, 5, 6, 7 ] ], [ 13, [ 1, 2 ] ] ] ], [ 'Lk', [ [ 1 ], [ 2 ], [ 3, [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ] ], [ 9 ], [ 10 ], [ 11 ], [ 13 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 21 ], [ 22 ], [ 23 ], [ 24 ] ] ], [ 'Joh' ], [ 'Ac', [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 10 ], [ 11 ], [ 12 ], [ 13 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 20 ] ] ], [ 'Ro' ], [ '1Co' ], [ '2Co' ], [ 'Ga' ], [ 'Ep' ], [ 'Php' ], [ 'Cl' ], [ 'He' ], [ 'Jam' ], [ '1Pt' ], [ '2Pt', [ [ 3, [ 15, 16, 17, 18, 20, 21, 22 ] ], [ 4 ], [ 5, [ 1 ] ] ] ], [ '3Jn' ], [ 'Rv', [ [ 3, [ 15 ] ] ] ] ], 'as_array data acronyms', ); $obj->acronyms(0); $obj->sorting(0); $refs = $obj->as_array; is( $refs, [ [ '1 Samuel', [ [ 4, [ 16 ] ] ] ], [ '2 Samuel', [ [ 3 ], [ 4 ], [ 5 ] ] ], [ '1 Peter' ], [ '2 Peter' ], [ '2 Peter', [ [ 3, [ 15 ] ] ] ], [ '2 Peter', [ [ 3 ], [ 4 ] ] ], [ '2 Peter', [ [ 3, [ 15, 16, 17, 18, 20, 21, 22 ] ] ] ], [ '2 Peter', [ [ 5, [ 1 ] ] ] ], [ 'Revelation' ], [ 'Revelation', [ [ 3, [ 15 ] ] ] ], [ 'Revelation' ], [ 'Revelation' ], [ 'Galatians' ], [ 'Romans' ], [ 'Mark', [ [ 12, [ 4 ] ] ] ], [ 'Mark', [ [ 12, [ 3, 4, 5 ] ] ] ], [ 'Mark', [ [ 12, [ 4, 5, 6, 7 ] ], [ 13, [ 1, 2 ] ] ] ], [ 'Genesis', [ [ 4, [ 1 ] ] ] ], [ 'Genesis', [ [ 1, [ 2 ] ] ] ], [ 'Mark', [ [ 3, [ 15, 16, 17 ] ] ] ], [ 'Psalm', [ [ 117 ] ] ], [ '3 John' ], [ 'Mark', [ [ 3, [ 6, 20, 21, 22, 23 ] ] ] ], [ 'Mark', [ [ 4 ], [ 5 ] ] ], [ 'Matthew', [ [ 1, [ 18, 19, 20, 21, 22, 23, 24, 25 ] ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 10 ], [ 11 ], [ 12 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 20 ], [ 21 ], [ 22 ], [ 28 ], [ 27 ], [ 26 ] ] ], [ 'Romans' ], [ 'James' ], [ 'Acts', [ [ 1 ], [ 2 ], [ 3 ], [ 4 ], [ 5 ], [ 6 ], [ 7 ], [ 8 ], [ 9 ], [ 10 ], [ 11 ], [ 12 ], [ 13 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 20 ] ] ], [ 'Galatians' ], [ 'Ephesians' ], [ 'Philippians' ], [ 'Colossians' ], [ 'Luke', [ [ 1 ], [ 2 ], [ 3, [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ] ], [ 9 ], [ 10 ], [ 11 ], [ 13 ], [ 14 ], [ 15 ], [ 16 ], [ 17 ], [ 18 ], [ 19 ], [ 21 ], [ 22 ], [ 23 ], [ 24 ] ] ], [ '1 Corinthians' ], [ '2 Corinthians' ], [ 'John' ], [ 'Hebrews' ], [ '1 Peter' ], [ '2 Peter' ] ], 'as_array data no sorting', ); $obj->sorting(1); $obj->add_detail(1); $refs = $obj->as_array; is( $refs->[20], [ '3 John', [ [ '1', [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 ] ] ] ], 'as_array data add detail', ); $obj->add_detail(0); } sub as_hash { $obj->clear->acronyms(0); $obj->in(@$test_data); my $refs; ok( lives { $refs = $obj->as_hash }, 'as_hash lives' ) or note $@; is( $refs, { 'Philippians' => {}, '1 Corinthians' => {}, '1 Peter' => {}, 'Genesis' => { 1 => [ 2 ], 4 => [ 1 ] }, 'Matthew' => { 21 => [], 28 => [], 10 => [], 7 => [], 3 => [], 5 => [], 8 => [], 1 => [ 18, 19, 20, 21, 22, 23, 24, 25 ], 16 => [], 17 => [], 12 => [], 6 => [], 15 => [], 11 => [], 18 => [], 20 => [], 27 => [], 22 => [], 14 => [], 19 => [], 4 => [], 2 => [], 9 => [], 26 => [] }, '2 Corinthians' => {}, 'James' => {}, 'Romans' => {}, '2 Peter' => { 3 => [ 15, 16, 17, 18, 20, 21, 22 ], 5 => [ 1 ], 4 => [] }, 'Colossians' => {}, 'John' => {}, '1 Samuel' => { 4 => [ 16 ] }, 'Acts' => { 7 => [], 20 => [], 18 => [], 11 => [], 5 => [], 3 => [], 10 => [], 15 => [], 9 => [], 12 => [], 2 => [], 17 => [], 6 => [], 1 => [], 14 => [], 8 => [], 4 => [], 19 => [], 16 => [], 13 => [] }, 'Luke' => { 19 => [], 13 => [], 16 => [], 22 => [], 14 => [], 1 => [], 23 => [], 2 => [], 24 => [], 9 => [], 17 => [], 15 => [], 10 => [], 21 => [], 3 => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ], 11 => [], 18 => [] }, '3 John' => {}, 'Galatians' => {}, 'Psalm' => { 117 => [] }, 'Ephesians' => {}, '2 Samuel' => { 5 => [], 3 => [], 4 => [] }, 'Revelation' => { 3 => [ 15 ] }, 'Mark' => { 12 => [ 3, 4, 5, 6, 7 ], 4 => [], 5 => [], 3 => [ 6, 15, 16, 17, 20, 21, 22, 23 ], 13 => [ 1, 2 ] }, 'Hebrews' => {} }, 'as_hash data', ); } sub as_verses { $obj->clear->acronyms(0); $obj->in(@$test_data); my $refs; ok( lives { $refs = $obj->as_verses }, 'as_verses lives' ) or note $@; is( $refs, [ 'Genesis 1:2', 'Genesis 4:1', '1 Samuel 4:16', '2 Samuel 3', '2 Samuel 4', '2 Samuel 5', 'Psalm 117', 'Matthew 1:18', 'Matthew 1:19', 'Matthew 1:20', 'Matthew 1:21', 'Matthew 1:22', 'Matthew 1:23', 'Matthew 1:24', 'Matthew 1:25', 'Matthew 2', 'Matthew 3', 'Matthew 4', 'Matthew 5', 'Matthew 6', 'Matthew 7', 'Matthew 8', 'Matthew 9', 'Matthew 10', 'Matthew 11', 'Matthew 12', 'Matthew 14', 'Matthew 15', 'Matthew 16', 'Matthew 17', 'Matthew 18', 'Matthew 19', 'Matthew 20', 'Matthew 21', 'Matthew 22', 'Matthew 26', 'Matthew 27', 'Matthew 28', 'Mark 3:6', 'Mark 3:15', 'Mark 3:16', 'Mark 3:17', 'Mark 3:20', 'Mark 3:21', 'Mark 3:22', 'Mark 3:23', 'Mark 4', 'Mark 5', 'Mark 12:3', 'Mark 12:4', 'Mark 12:5', 'Mark 12:6', 'Mark 12:7', 'Mark 13:1', 'Mark 13:2', 'Luke 1', 'Luke 2', 'Luke 3:1', 'Luke 3:2', 'Luke 3:3', 'Luke 3:4', 'Luke 3:5', 'Luke 3:6', 'Luke 3:7', 'Luke 3:8', 'Luke 3:9', 'Luke 3:10', 'Luke 3:11', 'Luke 3:12', 'Luke 3:13', 'Luke 3:14', 'Luke 3:15', 'Luke 3:16', 'Luke 3:17', 'Luke 3:18', 'Luke 3:19', 'Luke 3:20', 'Luke 3:21', 'Luke 3:22', 'Luke 3:23', 'Luke 9', 'Luke 10', 'Luke 11', 'Luke 13', 'Luke 14', 'Luke 15', 'Luke 16', 'Luke 17', 'Luke 18', 'Luke 19', 'Luke 21', 'Luke 22', 'Luke 23', 'Luke 24', 'John', 'Acts 1', 'Acts 2', 'Acts 3', 'Acts 4', 'Acts 5', 'Acts 6', 'Acts 7', 'Acts 8', 'Acts 9', 'Acts 10', 'Acts 11', 'Acts 12', 'Acts 13', 'Acts 14', 'Acts 15', 'Acts 16', 'Acts 17', 'Acts 18', 'Acts 19', 'Acts 20', 'Romans', '1 Corinthians', '2 Corinthians', 'Galatians', 'Ephesians', 'Philippians', 'Colossians', 'Hebrews', 'James', '1 Peter', '2 Peter 3:15', '2 Peter 3:16', '2 Peter 3:17', '2 Peter 3:18', '2 Peter 3:20', '2 Peter 3:21', '2 Peter 3:22', '2 Peter 4', '2 Peter 5:1', '3 John', 'Revelation 3:15' ], 'as_verses data', ); } sub as_runs { $obj->clear->acronyms(0); $obj->in(@$test_data); my $refs; ok( lives { $refs = $obj->as_runs }, 'as_runs lives' ) or note $@; is( $refs, [ 'Genesis 1:2', 'Genesis 4:1', '1 Samuel 4:16', '2 Samuel 3', '2 Samuel 4', '2 Samuel 5', 'Psalm 117', 'Matthew 1:18-25', 'Matthew 2', 'Matthew 3', 'Matthew 4', 'Matthew 5', 'Matthew 6', 'Matthew 7', 'Matthew 8', 'Matthew 9', 'Matthew 10', 'Matthew 11', 'Matthew 12', 'Matthew 14', 'Matthew 15', 'Matthew 16', 'Matthew 17', 'Matthew 18', 'Matthew 19', 'Matthew 20', 'Matthew 21', 'Matthew 22', 'Matthew 26', 'Matthew 27', 'Matthew 28', 'Mark 3:6', 'Mark 3:15-17', 'Mark 3:20-23', 'Mark 4', 'Mark 5', 'Mark 12:3-7', 'Mark 13:1-2', 'Luke 1', 'Luke 2', 'Luke 3:1-23', 'Luke 9', 'Luke 10', 'Luke 11', 'Luke 13', 'Luke 14', 'Luke 15', 'Luke 16', 'Luke 17', 'Luke 18', 'Luke 19', 'Luke 21', 'Luke 22', 'Luke 23', 'Luke 24', 'John', 'Acts 1', 'Acts 2', 'Acts 3', 'Acts 4', 'Acts 5', 'Acts 6', 'Acts 7', 'Acts 8', 'Acts 9', 'Acts 10', 'Acts 11', 'Acts 12', 'Acts 13', 'Acts 14', 'Acts 15', 'Acts 16', 'Acts 17', 'Acts 18', 'Acts 19', 'Acts 20', 'Romans', '1 Corinthians', '2 Corinthians', 'Galatians', 'Ephesians', 'Philippians', 'Colossians', 'Hebrews', 'James', '1 Peter', '2 Peter 3:15-18', '2 Peter 3:20-22', '2 Peter 4', '2 Peter 5:1', '3 John', 'Revelation 3:15' ], 'as_runs data', ); } sub as_chapters { $obj->clear->acronyms(0); $obj->in(@$test_data); my $refs; ok( lives { $refs = $obj->as_chapters }, 'as_chapters lives' ) or note $@; is( $refs, [ 'Genesis 1:2', 'Genesis 4:1', '1 Samuel 4:16', '2 Samuel 3', '2 Samuel 4', '2 Samuel 5', 'Psalm 117', 'Matthew 1:18-25', 'Matthew 2', 'Matthew 3', 'Matthew 4', 'Matthew 5', 'Matthew 6', 'Matthew 7', 'Matthew 8', 'Matthew 9', 'Matthew 10', 'Matthew 11', 'Matthew 12', 'Matthew 14', 'Matthew 15', 'Matthew 16', 'Matthew 17', 'Matthew 18', 'Matthew 19', 'Matthew 20', 'Matthew 21', 'Matthew 22', 'Matthew 26', 'Matthew 27', 'Matthew 28', 'Mark 3:6, 15-17, 20-23', 'Mark 4', 'Mark 5', 'Mark 12:3-7', 'Mark 13:1-2', 'Luke 1', 'Luke 2', 'Luke 3:1-23', 'Luke 9', 'Luke 10', 'Luke 11', 'Luke 13', 'Luke 14', 'Luke 15', 'Luke 16', 'Luke 17', 'Luke 18', 'Luke 19', 'Luke 21', 'Luke 22', 'Luke 23', 'Luke 24', 'John', 'Acts 1', 'Acts 2', 'Acts 3', 'Acts 4', 'Acts 5', 'Acts 6', 'Acts 7', 'Acts 8', 'Acts 9', 'Acts 10', 'Acts 11', 'Acts 12', 'Acts 13', 'Acts 14', 'Acts 15', 'Acts 16', 'Acts 17', 'Acts 18', 'Acts 19', 'Acts 20', 'Romans', '1 Corinthians', '2 Corinthians', 'Galatians', 'Ephesians', 'Philippians', 'Colossians', 'Hebrews', 'James', '1 Peter', '2 Peter 3:15-18, 20-22', '2 Peter 4', '2 Peter 5:1', '3 John', 'Revelation 3:15' ], 'as_chapters data', ); } sub as_books { $obj->clear->acronyms(0); $obj->in(@$test_data); my $refs; ok( lives { $refs = $obj->as_books }, 'as_books lives' ) or note $@; is( $refs, [ 'Genesis 1:2; 4:1', '1 Samuel 4:16', '2 Samuel 3-5', 'Psalm 117', 'Matthew 1:18-25; 2-12; 14-22; 26-28', 'Mark 3:6, 15-17, 20-23; 4-5; 12:3-7; 13:1-2', 'Luke 1-2; 3:1-23; 9-11; 13-19; 21-24', 'John', 'Acts 1-20', 'Romans', '1 Corinthians', '2 Corinthians', 'Galatians', 'Ephesians', 'Philippians', 'Colossians', 'Hebrews', 'James', '1 Peter', '2 Peter 3:15-18, 20-22; 4; 5:1', '3 John', 'Revelation 3:15' ], 'as_books data', ); } sub refs { $obj->clear->acronyms(0); $obj->in(@$test_data); my $refs; ok( lives { $refs = $obj->refs }, 'refs lives' ) or note $@; is( $refs, 'Genesis 1:2; 4:1; 1 Samuel 4:16; 2 Samuel 3-5; Psalm 117; ' . 'Matthew 1:18-25; 2-12; 14-22; 26-28; Mark 3:6, 15-17, 20-23; 4-5; 12:3-7; 13:1-2; ' . 'Luke 1-2; 3:1-23; 9-11; 13-19; 21-24; John; Acts 1-20; Romans; 1 Corinthians; 2 Corinthians; ' . 'Galatians; Ephesians; Philippians; Colossians; Hebrews; James; 1 Peter; ' . '2 Peter 3:15-18, 20-22; 4; 5:1; 3 John; Revelation 3:15', 'refs data', ); } sub as_text { $obj->clear->acronyms(0); $obj->in(@$test_data); my $refs; ok( lives { $refs = $obj->as_text }, 'as_text lives' ) or note $@; is( $refs, [ '', '0', '', 'Text with no Reference 3:16 data included', 'Text Samuel 3:15 said in 1 Samuel 4:16 that 2 Samuel 3-5 was as clear as 1 Peter in full', 'Text Pet text 2 Peter text 2 Peter 3:15 text 2 Peter 3-4 text ' . '2 Peter 3:15-18, 20-22, 2 Peter 5:1 text', 'The book of Revelation. The verse of Revelation 3:15. The book of Revelation.', 'Books of Revelation, Galatians, and Romans exist', 'Verses Mark 12:4 and Mark 12:3-5 and Mark 12:4-7; 13:1-2 and Genesis 4:1 and Genesis 1:2 exist', 'Mark 3:15-17, Psalm 117, 3 John, Mark 3:6, 20-23, Mark 4-5', 'A = Matthew 1:18-25; 2-12; 14-22; 26-28 = A', 'B = Romans, James = B', 'C = Acts 1-20 = C', 'D = Galatians, Ephesians, Philippians, Colossians = D', 'E = Luke 1-2; 3:1-23; 9-11; 13-19; 21-24 = E', 'F = 1 Corinthians, 2 Corinthians = F', 'G = John = G', 'H = Hebrews, 1 Peter, 2 Peter = H' ], 'as_text data', ); } sub set_bible_data { like( dies { $obj->set_bible_data }, qr/^First argument/, 'set_bible_data()' ); like( dies { $obj->set_bible_data('Special') }, qr/^Second argument/, 'set_bible_data()' ); like( dies { $obj->set_bible_data( 'Special' => [ [ 'Genesis', 'Ge' ], [ \'Genesis', \'Ge' ], ] ) }, qr/^Second argument/, 'set_bible_data()' ); ok( lives { $obj->set_bible_data( 'Special' => [ [ 'Genesis', 'Ge' ], [ 'Exodus', 'Ex' ], [ 'Leviticus', 'Lv' ], [ 'Numbers', 'Nu' ], [ 'Deuteronomy', 'Dt' ], [ 'Joshua', 'Jsh' ], [ 'Judges', 'Jdg' ], [ 'Ruth', 'Ru' ], [ '1 Samuel', '1Sa' ], [ '2 Samuel', '2Sa' ], [ '1 Kings', '1Ki' ], [ '2 Kings', '2Ki' ], [ '1 Chronicles', '1Ch' ], [ '2 Chronicles', '2Ch' ], [ 'Ezra', 'Ezr' ], [ 'Nehemiah', 'Ne' ], [ 'Esther', 'Est' ], [ 'Job', 'Jb' ], [ 'Psalms', 'Ps' ], [ 'Proverbs', 'Pr' ], [ 'Ecclesiastes', 'Ec' ], [ 'Song of Solomon', 'SS' ], [ 'Isaiah', 'Is' ], [ 'Jeremiah', 'Jr' ], [ 'Lamentations', 'Lm' ], [ 'Ezekiel', 'Ezk' ], [ 'Daniel', 'Da' ], [ 'Hosea', 'Ho' ], [ 'Joel', 'Jl' ], [ 'Amos', 'Am' ], [ 'Obadiah', 'Ob' ], [ 'Jonah', 'Jnh' ], [ 'Micah', 'Mi' ], [ 'Nahum', 'Na' ], [ 'Habakkuk', 'Hab' ], [ 'Zephaniah', 'Zp' ], [ 'Haggai', 'Hg' ], [ 'Zechariah', 'Zec' ], [ 'Malachi', 'Ml' ], ], ) }, '"Special" Bible data set' ) or note $@; is( $obj->bible, 'Special', '"Special" Bible is set' ); my @books; ok( lives { @books = $obj->books }, 'books lives', ) or note $@; is( scalar @books, 39, 'Special book count' ); is( $books[0], 'Genesis', 'Special Genesis location' ); is( $books[1], 'Exodus', 'Special Exodus location' ); is( $books[-1], 'Malachi', 'Special Revelation location' ); }
37.339028
110
0.398522
ed005998fdd710073c67f64c0f25157bae5193cc
79,721
pm
Perl
MT_systems/squoia/conll2xml_desr.pm
dan-zeman/squoia
096868f96bd4c19b45b1d69251321c85c71c6c3b
[ "Apache-2.0" ]
9
2016-04-27T16:48:58.000Z
2021-01-17T21:55:55.000Z
MT_systems/squoia/conll2xml_desr.pm
dan-zeman/squoia
096868f96bd4c19b45b1d69251321c85c71c6c3b
[ "Apache-2.0" ]
null
null
null
MT_systems/squoia/conll2xml_desr.pm
dan-zeman/squoia
096868f96bd4c19b45b1d69251321c85c71c6c3b
[ "Apache-2.0" ]
6
2016-03-29T22:26:50.000Z
2021-01-17T21:56:21.000Z
#!/usr/bin/perl package squoia::conll2xml_desr; use strict; use utf8; #use XML::LibXML; #binmode STDIN, ':utf8'; #binmode STDOUT, ':utf8'; #binmode (STDERR); use File::Spec::Functions qw(rel2abs); use File::Basename; my %mapCliticToEaglesTag = ( 'la' => 'PP3FSA00', 'las' => 'PP3FPA00', 'lo' => 'PP3MSA00', 'los' => 'PP3MPA00', 'le' => 'PP3CSD00', 'les' => 'PP3CPD00', 'me' => 'PP1CS000', # PP1CS000? 'te' => 'PP2CS000', # PP2CS000? 'se' => 'PP3CN000', # PP3CN000? could be le|les => se or refl se ...or passive|impersonal se ...? 'nos' => 'PP1CP000', # PP1CP000? 'os' => 'PP2CP000' # PP2CP000? ); my %mapCliticFormToLemma = ( 'la' => 'lo', 'las' => 'lo', 'lo' => 'lo', 'los' => 'lo', 'le' => 'le', 'les' => 'le', 'me' => 'me', 'te' => 'te', 'se' => 'se', 'nos' => 'nos', 'os' => 'os' ); # read conll file and create xml (still flat) my $scount=1; #sentence ord my %docHash; my %conllHash; # hash to store each sentence as conll, in case second analysis is needed my $dom = XML::LibXML->createDocument ('1.0', 'UTF-8'); my $root = $dom->createElementNS( "", "corpus" ); $dom->setDocumentElement( $root ); my $sentence; # actual sentence # necessary to differentiate between opening and closing quotes, tagger doesn't do that my $openQuot=1; my $openBar=1; my $verbose = ''; sub main{ my $InputLines = $_[0]; binmode($InputLines, ':utf8'); my $desrPort2 = $_[1]; # port where desr_server with model2 runs $verbose = $_[2]; print STDERR "#VERBOSE ". (caller(0))[3]."\n" if $verbose; while(<$InputLines>) { my $line = $_; # print $line; # if($line =~ /ó|í|á/){print "matched line is: ".$line; # my $encoding_name = Encode::Detect::Detector::detect($line); # print "encoding is: ".$encoding_name."\n"; # } # else{print "not matched line is: ".$line;} #skip empty line if($line =~ /^\s*$/) { $scount++; undef $sentence; } # word with analysis else { #create a new sentence node if(!$sentence) { $sentence = XML::LibXML::Element->new( 'SENTENCE' ); $sentence->setAttribute( 'ord', $scount ); $root->appendChild($sentence); } # create a new word node and attach it to sentence my $wordNode = XML::LibXML::Element->new( 'NODE' ); $sentence->appendChild($wordNode); my ($id, $word, $lem, $cpos, $pos, $info, $head, $rel, $phead, $prel) = split (/\t|\s/, $line); # print "line: $id, $word, $lem, $cpos, $pos, $info, $head, $rel, $phead, $prel\n"; # special case with estar (needs to be vm for desr and form instead of lemma -> set lemma back to 'estar') if(($pos =~ /vm|va/ || $pos eq 'va') && $lem =~ /^est/ && $lem !~ /r$/) { $lem =~ s/^est[^_]+/estar/; #$lem = "estar"; } # quotes, opening -> fea, closing -> fet if($pos eq 'Fe') { # for some reason, apostrophes are not encoded by libxml -> leads to crash! # -> replace them with quotes.. $word = '"'; $lem = '"'; if($openQuot){ $pos = 'Fea'; $openQuot=0;} else{ $pos = 'Fet'; $openQuot=1;} } # hyphen, opening -> fga, closing -> fgt if($pos eq 'Fg') { if($openQuot){ $pos = 'Fga'; $openBar=0;} else{ $pos = 'Fgt'; $openBar=1;} } my $eaglesTag = &toEaglesTag($pos, $info); # if verb (gerund,infinitve or imperative form) has clitic(s) then make new node(s) if($eaglesTag =~ /^V.[GNM]/ and $word =~ /(me|te|nos|os|se|[^l](la|las|lo|los|le|les))$/ and $word !~ /parte|frente|adelante|base|menos$/ and $word !~ /_/) { #print STDERR "clitics in verb $lem: $word\n" if $verbose; my $clstr = splitCliticsFromVerb($word,$eaglesTag,$lem); if ($clstr !~ /^$/){ # some imperative forms may end on "me|te|se|la|le" and not contain any clitic &createAppendCliticNodes($sentence,$scount,$id,$clstr); } } if($eaglesTag =~ /^NP/){ $pos="np"; } # set rel of 'y' and 'o' to coord if($lem eq 'y' || $lem eq 'o'){ $rel = 'coord'; } # Numbers: FreeLing uses their form as lemma (may be uppercased) -> change lem to lowercase for numbers! if($pos eq 'Z'){ # HACK!!! TODO check why FL tags it as a number Z and DeSR parses it as a circunstancial complement cc... if ($word eq 'un' and $lem eq 'un' and $rel eq 'cc'){ $lem = 'uno'; $rel = 'spec'; $pos = 'di'; $cpos = 'd'; $head = "". int($id)+1 . ""; $eaglesTag = 'DI0MS0'; } $lem = lc($lem); } # often: 'se fue' -> fue tagged as 'ser', VSIS3S0 -> change to VMIS3S0, set lemma to 'ir' if($eaglesTag =~ /VSIS[123][SP]0/ && $lem eq 'ser'){ my $precedingWord = $docHash{$scount.":".($id-1)}; #print STDERR "preceding of fue: ".$precedingWord->getAttribute('lem')."\n" if $verbose; if($precedingWord && $precedingWord->getAttribute('lem') eq 'se'){ $eaglesTag =~ s/^VS/VM/ ; #print STDERR "new tag: $eaglesTag\n" if $verbose; $lem = 'ir'; } } # # if 'hay' tagged as VA -> changed to VM! # if($eaglesTag eq 'VAIP3S0' && $word =~ /^[Hh]ay$/){ # $eaglesTag = 'VMIP3S0' ; # print STDERR "new tag for hay: $eaglesTag\n" if $verbose; # } # freeling error for reirse, two lemmas, reír/reir -> change to reír if($lem =~ /\/reir/){ $lem = 'reír'; } $wordNode->setAttribute( 'ord', $id ); $wordNode->setAttribute( 'form', $word ); $wordNode->setAttribute( 'lem', $lem ); $wordNode->setAttribute( 'pos', $pos ); $wordNode->setAttribute( 'cpos', $cpos ); $wordNode->setAttribute( 'head', $head ); $wordNode->setAttribute( 'rel', $rel ); $wordNode->setAttribute( 'mi', $eaglesTag ); # print "$eaglesTag\n"; # store node in hash, key sentenceId:wordId, in order to resolve dependencies my $key = "$scount:$id"; $docHash{$key}= $wordNode; $conllHash{$scount} = $conllHash{$scount}.$line; } } # my $docstring = $dom->toString(3); # #print STDERR $docstring; # print STDERR "------------------------------------------------\n"; # foreach my $n ($dom->getElementsByTagName('NODE')){ # if($n->getAttribute('form') =~ /ó|í|á/){ # print STDERR "matched: ".$n->getAttribute('form')."\n"; # my $encoding_name = Encode::Detect::Detector::detect(utf8::decode($n->getAttribute('form'))); # print "encoding: ".$encoding_name."\n"; # print STDOUT "node: ".$dom->toString()."\n";} # else{ # print STDERR "not matched: ".$n->getAttribute('form')."\n"; # } # } # print STDERR "------------------------------------------------\n"; ## adjust dependencies (word level), my @sentences = $dom->getElementsByTagName('SENTENCE'); #foreach my $sentence ( $dom->getElementsByTagName('SENTENCE')) my $model2 =0; for(my $i = 0; $i < scalar(@sentences); $i++) { if($model2 == 1) { my $sentence = @sentences[$i]; my $sentenceId = $sentence->getAttribute('ord'); print STDERR "model2 in sentence: $sentenceId\n" if $verbose; #print STDERR "1:".$sentence->toString."\n" if $verbose; my @nodes = $sentence->getElementsByTagName('NODE'); foreach my $node (@nodes) { my $head = $node->getAttribute('head'); if ($head ne '0') { my $headKey = "$sentenceId:$head"; my $word = $node->getAttribute('form'); #print "$word= $headKey\n"; my $parent = $docHash{$headKey}; $parent->appendChild($node); } } $model2=0; } else { my $sentence = @sentences[$i]; my $sentenceId = $sentence->getAttribute('ord'); #print STDERR "adjusting dependencies in sentence: ".$sentence->getAttribute('ord')."\n" if $verbose; #print STDERR "2: ".$sentence->toString."\n" if $verbose; my @nodes = $sentence->getElementsByTagName('NODE'); foreach my $node (@nodes) { #print STDERR $node->getAttribute('ord')."\n" if $verbose; my $head = $node->getAttribute('head'); if ($head ne '0') { my $headKey = "$sentenceId:$head"; #print STDERR "Head key: $headKey\n" if $verbose; my $word = $node->getAttribute('form'); #print "$word= $headKey\n"; my $parent = $docHash{$headKey}; eval { $parent->appendChild($node); } or do { &model2($sentence,$desrPort2); print STDERR "loop detected in sentence: ".$sentence->getAttribute('ord')."\n" if $verbose; $model2 = 1; $i--; last; } } # if this is the head, check if it's a good head (should not be a funcion word!), and if not, # check if there are >3 words in this sentence (otherwise it might be a title) else { my $pos = $node->getAttribute('pos'); if($pos =~ /d.|s.|p[^I]|c.|n.|r.|F./ && scalar(@nodes) > 4) { &model2($sentence,$desrPort2); $model2 = 1; $i--; last; } } } } } #my $docstring = $dom->toString(3); #print STDERR $docstring if $verbose; #print STDERR "------------------------------------------------\n" if $verbose; #print STDERR "------------------------------------------------\n" if $verbose; # insert chunks foreach my $sentence ( $dom->getElementsByTagName('SENTENCE')) { my $sentenceId = $sentence->getAttribute('ord'); #print STDERR "insert chunks in sentence: $sentenceId\n" if $verbose; #my $chunkCount = 1; my $parent; my @nodes = $sentence->getElementsByTagName('NODE'); my $nonewChunk = 0; for(my $i=0; $i<scalar(@nodes); $i++) { #print "\n ord chunk: $chunkCount\n"; #my $docstring = $dom->toString(3); my $node = @nodes[$i]; my $head = $node->getAttribute('head'); my $headKey = "$sentenceId:$head"; my $word = $node->getAttribute('form'); if ($head ne '0') { #print "$word= $headKey\n"; $parent = $docHash{$headKey}; # in case no parent found, assume parent is sentence (this shouldn't happen) if(!$parent) { $parent = $sentence; } } #if head of sentence, parent is sentence node else { $parent = $sentence; } #my $docstring = $dom->toString(3); #print STDERR $docstring; ####print STDERR $node->toString; #print STDERR "\n---------------------------------\n"; #print STDERR $node->getAttribute('lem'); #print STDERR "\n---------------------------------\n"; # #if this is a main verb or auxiliary used as main verb # (as auxiliary rel=v, auxilaries don't get their own chunk, they should live inside the main verbs' chunk) # if this is a finite verb with rel=v, check if its a finite verb and head is non-finite # -> avoid having two finite verbs in one chunk! if ($node->exists('self::NODE[starts-with(@mi,"V")] and not(self::NODE[@rel="v"])') ) { my $verbchunk = XML::LibXML::Element->new( 'CHUNK' ); #if this node is parent of a coordination if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]')) { $verbchunk->setAttribute('type', 'coor-v'); } # no coordination else { $verbchunk->setAttribute('type', 'grup-verb'); } # if this is the main verb in the chunk labeled as VA, change pos to VM if($node->getAttribute('pos') eq 'va' && !$node->exists('child::NODE[@pos="vm"]')) { my $eaglesTag = $node->getAttribute('mi'); substr($eaglesTag, 1, 1) = "M"; $node->setAttribute('mi',$eaglesTag); $node->setAttribute('pos', 'vm'); print STDERR "changed mi of ".$node->{'form'}." to $eaglesTag\n" if $verbose; } # if relative clause with preposition preceding relative pronoun-> desr makes wrong analysis: #(la mujer a quien dejaron): #<corpus> # <SENTENCE ord="1"> # <CHUNK type="grup-verb" si="top"> # <NODE ord="5" form="dejaron" lem="dejar" pos="vm" cpos="v" rel="sentence" mi="VMIS3P0"/> # <CHUNK type="sn" si="suj"> # <NODE ord="2" form="mujer" lem="mujer" pos="nc" cpos="n" rel="cd-a" mi="NCFS000"> # <NODE ord="1" form="la" lem="el" pos="da" cpos="d" head="2" rel="spec" mi="DA0FS0"/> # </NODE> # </CHUNK> # <CHUNK type="grup-sp" si="cd"> # <NODE ord="3" form="a" lem="a" pos="sp" cpos="s" rel="cd" mi="SPS00"> # <NODE ord="4" form="quien" lem="quien" pos="pr" cpos="p" head="3" rel="sn" mi="PR00S000"/> # </NODE> # </CHUNK> # </CHUNK> # </SENTENCE> #</corpus> #my $docstring = $dom->toString(3); #print STDERR $docstring; #print STDERR $node->getAttribute('lem'); #print STDERR "\n---------------------------------\n"; # find rel-prn within PP my $relprn = ${$node->findnodes('NODE[@pos="sp"]/NODE[starts-with(@mi,"PR")]')}[-1]; my $subj = ${$node->findnodes('../descendant::*[(@rel="suj" or @rel="cd-a") and @cpos="n"][1]')}[0]; # find subj within rel-clause with cual, see below # my $relcual = ${$node->findnodes('child::NODE[@lem="cual"]')}[-1]; # my $cualsubj = ${$node->findnodes('child::*[(@rel="suj" or @rel="cd-a") and @cpos="n"][1]')}[0]; # in case we have to insert a subject chunk my $snchunk; my $clitic2; my $clitic; my $LO; my $QUE; #check if subj should be the head of the rel-clause (head preceeds rel-prn) if($relprn && $subj && ( $relprn->getAttribute('ord') > $subj->getAttribute('ord') )) { $node->setAttribute('head', $subj->getAttribute('ord')); $head = $subj->getAttribute('ord'); $node->setAttribute('rel', 'S'); $parent->appendChild($subj); $subj->appendChild($node); if($parent->nodeName() eq 'SENTENCE') { $subj->setAttribute('si', 'top'); $subj->setAttribute('head', '0'); } else { if($parent->nodeName() eq 'NODE') { $subj->setAttribute('head', $parent->getAttribute('ord')); } else { $subj->setAttribute('head', $parent->getAttribute('ord')); } } $parent=$subj; } # La mujer la cual baila se fue. # <SENTENCE ord="1"> # <CHUNK type="grup-verb" si="top" idref="7"> # <NODE ord="7" form="fue" lem="ir" pos="vm" cpos="v" rel="sentence" mi="VMIS3S0"> # <NODE ord="5" form="baila" lem="bailar" pos="vm" cpos="v" head="7" rel="suj" mi="VMIP3S0"> # <NODE ord="2" form="mujer" lem="mujer" pos="nc" cpos="n" head="5" rel="suj" mi="NCFS000"> # <NODE ord="1" form="La" lem="el" pos="da" cpos="d" head="2" rel="spec" mi="DA0FS0"/> # </NODE> # <NODE ord="4" form="cual" lem="cual" pos="pr" cpos="p" head="5" rel="cc" mi="PR00S000"> # <NODE ord="3" form="la" lem="el" pos="da" cpos="d" head="4" rel="d" mi="DA0FS0"/> # </NODE> # <NODE ord="6" form="se" lem="se" pos="pp" cpos="p" head="5" rel="suj" mi="PP30C000"/> # </NODE> # <NODE ord="8" form="." lem="." pos="Fp" cpos="F" head="7" rel="f" mi="FP"/> # </NODE> # </CHUNK> # </SENTENCE> # elsif($relcual && $cualsubj && ( $relcual->getAttribute('ord') > $cualsubj->getAttribute('ord') )) # { # print STDERR "cualsubj:".$cualsubj->toString."\n" if $verbose; # $node->setAttribute('head', $cualsubj->getAttribute('ord')); # $head = $cualsubj->getAttribute('ord'); # $node->setAttribute('rel', 'S'); # $parent->appendChild($cualsubj); # $cualsubj->appendChild($node); # # if($parent->nodeName() eq 'SENTENCE') # { # $cualsubj->setAttribute('si', 'top'); # $cualsubj->setAttribute('head', '0'); # } # else # { # if($parent->nodeName() eq 'NODE') # { # $cualsubj->setAttribute('head', $parent->getAttribute('ord')); # } # else # { # $cualsubj->setAttribute('head', $parent->getAttribute('idref')); # } # } # $parent=$cualsubj; # } # Vi al hombre a quien dejaron. -> 'a quien dejaron'->grup-sp, cc/sp, depends on verb (only if simple np/pp, with complex nps/pps not a problem) # attach this relative-clause to preceeding noun # <SENTENCE ord="1"> # <CHUNK type="grup-verb" si="top"> # <NODE ord="1" form="Vi" lem="ver" pos="vm" cpos="v" rel="sentence" mi="VMIS1S0"/> # <CHUNK type="grup-sp" si="cd"> # <NODE ord="2" form="al" lem="al" pos="sp" cpos="s" rel="cd" mi="SPCMS"/> # <CHUNK type="sn" si="sn"> # <NODE ord="3" form="hombre" lem="hombre" pos="nc" cpos="n" rel="sn" mi="NCMS000"/> # </CHUNK> # </CHUNK> # <CHUNK type="grup-sp" si="cc"> # <NODE ord="4" form="a" lem="a" pos="sp" cpos="s" rel="cc" mi="SPS00"/> # <CHUNK type="grup-verb" si="S"> # <NODE ord="6" form="dejaron" lem="dejar" pos="vm" cpos="v" rel="S" mi="VMIS3P0"> # <NODE ord="5" form="quien" lem="quien" pos="pr" cpos="p" head="6" rel="suj" mi="PR00S000"/> # </NODE> # </CHUNK> # </CHUNK> # <CHUNK type="F-term" si="term"> # <NODE ord="7" form="." lem="." pos="Fp" cpos="F" mi="FP"/> # </CHUNK> # </CHUNK> # </SENTENCE> elsif($node->exists('child::NODE[@pos="pr"]') && ( ($parent->getAttribute('type') eq 'grup-sp') || ($parent->getAttribute('pos') eq 'sp') ) ) { # if rel-pron is set to 'suj'-> correct that, if there's a preceding preposition, this can't be subject $relprn = @{$node->findnodes('child::NODE[@pos="pr"]')}[-1]; my $prep = @{$parent->findnodes('descendant-or-self::NODE[@pos="sp"]')}[-1]; if($relprn && $prep && $relprn->getAttribute('rel') eq 'suj') { if($prep->getAttribute('lem') eq 'a' ||$prep->getAttribute('lem') eq 'al') { $relprn->setAttribute('rel', 'cd/ci'); } else { $relprn->setAttribute('rel', 'cc'); } } my $headOfRelPP = $parent->parentNode(); if($headOfRelPP && $headOfRelPP->nodeName() ne 'SENTENCE' && $headOfRelPP->exists('self::*[@type="grup-verb" or @cpos="v"]')) { my $nominalHead = @{$parent->findnodes('preceding-sibling::CHUNK[@type="grup-sp" or @type="sn"]/descendant-or-self::CHUNK[@type="sn"]')}[-1]; # if there is a candidate for the nominal head of this rel clause, attach it there if($nominalHead) { $nominalHead->appendChild($parent); $parent->setAttribute('head', $nominalHead->getAttribute('ord')); } } } # problem re-clauses with 'ART+cual': # <SENTENCE ord="1"> # <CHUNK type="grup-verb" si="top"> # <NODE ord="6" form="fue" lem="ir" pos="vm" cpos="v" rel="sentence" mi="VMIS3S0"> # <NODE ord="5" form="se" lem="se" pos="pp" cpos="p" head="6" rel="ci" mi="PP30C000"/> # </NODE> # <CHUNK type="sn" si="suj"> # <NODE ord="2" form="mujer" lem="mujer" pos="nc" cpos="n" rel="suj" mi="NCFS000"> # <NODE ord="1" form="la" lem="el" pos="da" cpos="d" head="2" rel="spec" mi="DA0FS0"/> # <NODE ord="4" form="cual" lem="cual" pos="pr" cpos="p" head="2" rel="sn" mi="PR00S000"> # <NODE ord="3" form="la" lem="el" pos="da" cpos="d" head="4" rel="spec" mi="DA0FS0"/> # </NODE> # </NODE> # </CHUNK> # </CHUNK> # </SENTENCE> elsif($subj && $node->exists('child::*[(@si="suj" and @type="sn")or (@rel="suj" and @cpos="n")]/descendant::NODE[@lem="cual"]') ) { my $subjnoun = @{$node->findnodes('child::*[(@si="suj" and @type="sn") or (@rel="suj" and @cpos="n")][1]')}[-1]; #print STDERR "subjnoun: ".$subjnoun->toString if $verbose; my $cual = @{$subjnoun->findnodes('child::NODE[@lem="cual"][1]')}[-1]; if($cual && $subjnoun) { # attach cual to verb instead of subject noun, set rel=suj $cual->setAttribute('head', $node->getAttribute('ord')); $cual->setAttribute('rel', 'suj'); $node->appendChild($cual); # attach node(verb) to head noun and set rel=S $node->setAttribute('head', $subjnoun->getAttribute('ord')); $head = $subjnoun->getAttribute('ord'); $node->setAttribute('rel', 'S'); $parent->appendChild($subjnoun); $subjnoun->appendChild($node); if($parent->nodeName() eq 'SENTENCE') { $subj->setAttribute('si', 'top'); $subj->setAttribute('head', '0'); } else { if($parent->nodeName() eq 'NODE') { $subj->setAttribute('head', $parent->getAttribute('ord')); } else { $subj->setAttribute('head', $parent->getAttribute('ord')); } } $parent=$subjnoun; } } # TODO ist das wirklich sinnvoll? # if analyzed as relative clause but no rel-prn & head noun not part of prep.phrase # -> head noun is part of sentence, if no other subject & congruent, insert as subject, # this seems to happen particularly with clitic object ( los pobladores LA llaman sirena..etc) elsif($node->getAttribute('rel') =~ /S|sn/ && $node->exists('parent::NODE/parent::CHUNK[@type="sn"]/NODE[@cpos="n"]') && !$node->exists('ancestor::CHUNK[@type="grup-sp"]') && !$node->exists('descendant::NODE[@pos="pr"]') && !&hasRealSubj($node) && $node->exists('child::NODE[@lem="lo" or @lem="le"]')) { my $headnoun = &getHeadNoun($node); if($headnoun && &isCongruent($headnoun, $node)) { print STDERR "suj inserted in sentence: $sentenceId\n" if $verbose; #parent node = noun, parent of that = sn-chunk # new head of this verb will be the head of this sn-chunk $snchunk = $headnoun->parentNode; my $newhead = $snchunk->parentNode; if($snchunk && $newhead) { $newhead->appendChild($verbchunk); #insert after node, see below #$verbchunk->appendChild($snchunk); $snchunk->setAttribute('head', $node->getAttribute('ord')); $node->setAttribute('head', $newhead->getAttribute('ord')); $parent = $newhead; $snchunk->setAttribute('si', 'suj-a'); $headnoun->setAttribute('rel', 'suj-a'); } } } # Problem with clitic pronouns la sirena SE LO comerá, SE LO diré cuando llegue)-> head se--concat--lo--concat--verb # edit: same problem with 'me lo, te la, etc', -> adapted regex, note that $clitic2 contains also 'me,te,no,vos,os' now elsif($node->getAttribute('rel') eq 'CONCAT' && $node->exists('parent::NODE[@pos="pp" and (@lem="lo" or @lem="le" or @lem="te" or @lem="me" or @lem="nos" or @lem="vos" or @lem="os")]')) { #print STDERR "abzweigung erwischt\n" if $verbose; $clitic = $node->parentNode(); $clitic2 = @{$clitic->parentNode()->findnodes('parent::CHUNK[@type="sn"]/NODE[@lem="se" or @lem="te" or @lem="me" or @lem="nos" or @lem="vos" or @lem="os"][1]')}[0]; # if 'se lo' if($clitic && $clitic2) { #attach verb to current head of 'se' and 'la'/'lo' (se and lo/la already in sn-chunks!) $parent = $clitic2->parentNode->parentNode; #print STDERR "parent of se : ".$parent->toString() if $verbose; $node->setAttribute('head', $parent->getAttribute('ord')); # add 'se' and 'lo/la' to verb with their chunks # should be attached AFTER verb, else sequence gets mixed up # $verbchunk->appendChild($clitic2->parentNode); # $verbchunk->appendChild($clitic->parentNode); $clitic2->setAttribute('head', $node->getAttribute('ord')); $clitic->setAttribute('head', $node->getAttribute('ord')); #$clitic2->parentNode->setAttribute('ord', $node->getAttribute('ord')); #$clitic->parentNode->setAttribute('ord', $node->getAttribute('ord')); $clitic2->parentNode->setAttribute('si', 'ci'); $clitic2->setAttribute('rel', 'ci'); $clitic->setAttribute('rel', 'cd'); $clitic->parentNode->setAttribute('si', 'cd'); print STDERR "changed verb clitics in sentence $sentenceId\n" if $verbose; } # if only one clitc ('Cuando vine, le dije./Cuando vine, la vi.') elsif ($clitic && !$clitic2) { $parent = $clitic->parentNode->parentNode; $node->setAttribute('head', $parent->getAttribute('ord')); $clitic->setAttribute('head', $node->getAttribute('ord')); #$clitic->parentNode->setAttribute('ord', $node->getAttribute('ord')); print STDERR "changed CONCAT in verb clitics in sentence $sentenceId\n" if $verbose; if($clitic->getAttribute('lem') eq 'lo') { $clitic->setAttribute('rel', 'cd'); $clitic->parentNode->setAttribute('si', 'cd'); } elsif($clitic->getAttribute('lem') eq 'le') { $clitic->setAttribute('rel', 'ci'); $clitic->parentNode->setAttribute('si', 'ci'); } else { $clitic->setAttribute('rel', 'cd-a'); $clitic->parentNode->setAttribute('si', 'cd-a'); } } } # lo que elsif($node->exists('parent::NODE[@lem="que"]/parent::NODE[@form="lo" or @form="Lo" or @form="los" or @form="Los"]') ) { # que $QUE = $node->parentNode; if($QUE) { $QUE->setAttribute('rel', 'cd-a'); # lo $LO = $QUE->parentNode; if($LO) { $LO->setAttribute('rel', 'spec'); $parent = $LO->parentNode; $node->setAttribute('rel', 'S'); } } } # # if this is an infinitive with 'que' and head is 'tener' -> insert this verb into head chunk, as head of tener! # # too complicated, let classifier handle this! # elsif($node->exists('child::NODE[@lem="que"]') && $parent->exists('child::NODE[@lem="tener"]') ) # { # my $tener = @{$parent->findnodes('child::NODE[@lem="tener"]')}[0]; # if($tener) # { # parent->appendChild($node); # $node->appendChild($tener); # $nonewChunk=1; # } # } # if this verb is labeled as 'suj', but is local person -> change label to 'S' elsif($node->getAttribute('rel') eq 'suj' && $node->getAttribute('mi') =~ /1|2/ ) { $node->setAttribute('rel','S'); } # if this is a gerund labeled as 'suj' with no verbal child node -> change label to 'cc' elsif($node->getAttribute('rel') eq 'suj' && $node->getAttribute('mi') =~ /^VMG/ && !$node->exists('child::NODE[@lem="estar"]')) { $node->setAttribute('rel','gerundi'); } #if this verb chunk is labeled as 'cd' but main verb has no 'que' and this is not an infinitive: change label to 'S' elsif($node->getAttribute('rel') eq 'cd' && $node->getAttribute('mi') !~ /^V[MAS]N/ && !$parent->exists('descendant::NODE[@lem="que"]' )) { $node->setAttribute('rel','S'); } # relative clauses: if head of verbchunk is a nominal chunk + verbchunk has descendant = relative pronoun -> set si="S" if($node->exists('parent::NODE[@cpos="n"]') && $node->exists('child::NODE[@pos="pr"]')) { $verbchunk->setAttribute('si', 'S'); } else { $verbchunk->setAttribute('si', $node->getAttribute('rel')); } $verbchunk->setAttribute('ord', $node->getAttribute('ord')); #$node->removeAttribute('rel'); $node->removeAttribute('head'); $verbchunk->appendChild($node); if($snchunk) { $verbchunk->appendChild($snchunk); } elsif($clitic2 && $clitic) { $verbchunk->appendChild($clitic2->parentNode); $verbchunk->appendChild($clitic->parentNode); } elsif($clitic && !$clitic2) { $verbchunk->appendChild($clitic->parentNode); } elsif($LO && $QUE) { $verbchunk->appendChild($QUE); #print STDERR $LO->toString if $verbose; $verbchunk->appendChild($LO); } eval{$parent->appendChild($verbchunk);}; warn "could not attach verbchunk".$node->getAttribute('ord')."to head in sentence: $sentenceId" if $@; # the key in hash should point now to the chunk instead of the node my $ord = $node->getAttribute('ord'); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $verbchunk; } # if this is a noun, a personal or a demonstrative pronoun, or a number, make a nominal chunk (sn) # change 13.04.2015: put PT (interrogative non-attributive pronouns) in their own chunk, so they can be moved independently of the verb elsif ($node->exists('self::NODE[@cpos="n" or @pos="pp" or @pos="pd" or @pos="pi" or @pos="Z" or @pos="pt"]')) { my $nounchunk = XML::LibXML::Element->new( 'CHUNK' ); #if this node is parent of a coordination if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]')) { $nounchunk->setAttribute('type', 'coor-n'); # if coordinated prsprn -> mostly wrong-> correct if($node->getAttribute('pos') eq 'pp') { &correctCoord($node, $sentenceId); } } # no coordination else { $nounchunk->setAttribute('type', 'sn'); } #print STDERR "node: ".$node->getAttribute('lem')." ,parent: ".$parent->toString."\n" if $verbose; # if this is suj -> check if congruent with finite verb, check also if parent is a verbchunk if($node->getAttribute('rel') eq 'suj' && $parent->exists('self::*[@type="grup-verb" or @cpos="v"]') && &isCongruent($node, $parent) == 0) { $node->setAttribute('rel', 'cd-a'); } # if this is 'lo/la' and pp-> change to cd if($node->getAttribute('lem') eq 'lo') { $node->setAttribute('rel', 'cd'); } # if this is 'le' and pp-> change to ci elsif($node->getAttribute('lem') eq 'le') { $node->setAttribute('rel', 'ci'); } # if this is tú/yo/ etc and congruent with verb -> this is the subject #if($node->getAttribute('lem') =~ /^yo|tú|él|ellos|nosotros|vosotros/ && $parent->exists('self::*[@type="grup-verb" or @cpos="v"]') && &isCongruent($node,$parent) ==1 ) # problem: STDIN is set to :utf8, libxml doesn't like that, can't match tú/él directly if($node->getAttribute('mi') =~ /PP2CSN0.|PP3.S000/ && $parent->exists('self::*[@type="grup-verb" or @cpos="v"]') && &isCongruent($node,$parent)) { $node->setAttribute('rel', 'suj-a'); } elsif($node->getAttribute('lem') =~ /^yo|ellos|nosotros|vosotros/ && $parent->exists('self::*[@type="grup-verb" or @cpos="v"]') && &isCongruent($node,$parent) ) { $node->setAttribute('rel', 'suj-a'); } $nounchunk->setAttribute('si', $node->getAttribute('rel')); $nounchunk->setAttribute('ord', $node->getAttribute('ord')); #$node->removeAttribute('rel'); $node->removeAttribute('head'); $nounchunk->appendChild($node); $parent = &attachNewChunkUnderChunk($nounchunk,$parent,$sentence); # $parent->appendChild($nounchunk); # the key in hash should point now to the chunk instead of the node my $ord = $node->getAttribute('ord'); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $nounchunk; #check if there are already child chunks attached (corrected rel. clauses), if so, attach them to noun chunk for my $chunkchild ($node->getElementsByTagName('CHUNK')) { $nounchunk->appendChild($chunkchild); } } # if this is a preposition, make a prepositional chunk (grup-sp) elsif ($node->exists('self::NODE[starts-with(@mi,"SP")]')) { #print STDERR "parent of prep: \n".$parent->toString."\n" if $verbose; # if head is an infinitive (para hacer, voy a hacer, de hacer etc)-> don't create a chunk, preposition just hangs below verb # check if preposition precedes infinitive, otherwise make a chunk if($parent->exists('self::CHUNK/NODE[@mi="VMN0000" or @mi="VSN0000"]') && $parent->getAttribute('ord')> $node->getAttribute('ord')) { } else { my $ppchunk = XML::LibXML::Element->new( 'CHUNK' ); #if this node is parent of a coordination if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]')) { $ppchunk->setAttribute('type', 'coor-sp'); } # no coordination else { $ppchunk->setAttribute('type', 'grup-sp'); } $ppchunk->setAttribute('si', $node->getAttribute('rel')); $ppchunk->setAttribute('ord', $node->getAttribute('ord')); #$node->removeAttribute('rel'); $node->removeAttribute('head'); $ppchunk->appendChild($node); $parent->appendChild($ppchunk); # the key in hash should point now to the chunk instead of the node my $ord = $node->getAttribute('ord'); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $ppchunk; } } # if this is an adjective, make an adjective chunk (sa) elsif ($node->exists('self::NODE[starts-with(@mi,"A")]')) { my $sachunk = XML::LibXML::Element->new( 'CHUNK' ); #if this node is parent of a coordination if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]')) { $sachunk->setAttribute('type', 'coor-sa'); } # no coordination else { $sachunk->setAttribute('type', 'sa'); } $sachunk->setAttribute('si', $node->getAttribute('rel')); $sachunk->setAttribute('ord', $node->getAttribute('ord')); #$node->removeAttribute('rel'); $node->removeAttribute('head'); $sachunk->appendChild($node); $parent = &attachNewChunkUnderChunk($sachunk,$parent,$sentence); #$parent->appendChild($sachunk); # the key in hash should point now to the chunk instead of the node my $ord = $node->getAttribute('ord'); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $sachunk; } # if this is an adverb, make an adverb chunk (sadv) elsif ($node->exists('self::NODE[starts-with(@mi,"R")]')) { my $sadvchunk = XML::LibXML::Element->new( 'CHUNK' ); #if this node is parent of a coordination if ($node->exists('child::NODE[@lem="ni" or @rel="coord"]')) { $sadvchunk->setAttribute('type', 'coor-sadv'); } # no coordination else { $sadvchunk->setAttribute('type', 'sadv'); } $sadvchunk->setAttribute('si', $node->getAttribute('rel')); $sadvchunk->setAttribute('ord', $node->getAttribute('ord')); #$node->removeAttribute('rel'); $node->removeAttribute('head'); $sadvchunk->appendChild($node); $parent = &attachNewChunkUnderChunk($sadvchunk,$parent,$sentence); #if ($parent->nodeName eq 'NODE') { # print STDERR "adverb chunk" . $sadvchunk->toString(). " within NODE ". $parent->toString() ." has to be appended to a higher CHUNK\n" if $verbose; # $parent = @{$parent->findnodes('ancestor::CHUNK[1]')}[0]; #} #$parent->appendChild($sadvchunk); # the key in hash should point now to the chunk instead of the node my $ord = $node->getAttribute('ord'); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $sadvchunk; } # if this is a subordination (CS), check if attached to correct verb (gets often attached to main clause instead of subordinated verb) elsif($node->getAttribute('pos') eq 'cs' && !$parent->exists('child::NODE[@pos="vs"]') ) { &attachCSToCorrectHead($node, $sentence); } # if this is punctuation mark elsif ($node->exists('self::NODE[starts-with(@mi,"F")]')) { my $fpchunk = XML::LibXML::Element->new( 'CHUNK' ); $fpchunk->setAttribute('type', 'F-term'); $fpchunk->setAttribute('si', 'term'); $fpchunk->setAttribute('ord', $node->getAttribute('ord')); $node->removeAttribute('rel'); $node->removeAttribute('head'); $fpchunk->appendChild($node); # if punctuation has childnodes -> wrong, append those to parent of punctuation mark # unless this is the head of the sentence, in this case make first verb head of sentence if($parent->nodeName eq 'SENTENCE') { my $realMainVerb = @{$node->findnodes('child::NODE[@cpos="v" and not(@rel="v")][1]')}[0]; my $firstchild = @{$node->findnodes('child::NODE[not(@cpos="F")][1]')}[0]; if($realMainVerb) { $parent->appendChild($realMainVerb); $realMainVerb->setAttribute('head', '0'); $parent = $realMainVerb; } # else, no main verb (this is a title), take first child as head of sentence elsif($firstchild) { $parent->appendChild($firstchild); $firstchild->setAttribute('head', '0'); $parent = $firstchild; } # else: sentence consists only of punctuation marks? # append to Chunk and leave as is.. else { $fpchunk->appendChild($node); eval {$parent->appendChild($fpchunk);}; warn "could not append punctuation chunk to parent chunk".$node->getAttribute('ord')." in sentence: $sentenceId" if $@; next; } } my @children = $node->childNodes(); foreach my $child (@children) { { eval { $parent->appendChild($child); $child->setAttribute('head', $parent->getAttribute('ord')); }; warn "could not reattach child of punctuation chunk".$node->getAttribute('ord')." in sentence: $sentenceId" if $@; } } eval {$parent->appendChild($fpchunk);}; warn "could not append punctuation chunk to parent chunk".$node->getAttribute('ord')." in sentence: $sentenceId" if $@; # the key in hash should point now to the chunk instead of the node my $ord = $node->getAttribute('ord'); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $fpchunk; } # if this is a date elsif ($node->exists('self::NODE[@mi="W"]')) { my $datechunk = XML::LibXML::Element->new( 'CHUNK' ); $datechunk->setAttribute('type', 'date'); $datechunk->setAttribute('si', $node->getAttribute('rel')); $datechunk->setAttribute('ord', $node->getAttribute('ord')); $node->removeAttribute('rel'); $node->removeAttribute('head'); $datechunk->appendChild($node); $parent->appendChild($datechunk); # the key in hash should point now to the chunk instead of the node my $ord = $node->getAttribute('ord'); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $datechunk; } # if this is an interjection elsif ($node->exists('self::NODE[@mi="I"]')) { my $interjectionchunk = XML::LibXML::Element->new( 'CHUNK' ); $interjectionchunk->setAttribute('type', 'interjec'); $interjectionchunk->setAttribute('si', $node->getAttribute('rel')); $interjectionchunk->setAttribute('ord', $node->getAttribute('ord')); $node->removeAttribute('rel'); $node->removeAttribute('head'); $interjectionchunk->appendChild($node); $parent->appendChild($interjectionchunk); # the key in hash should point now to the chunk instead of the node my $ord = $node->getAttribute('ord'); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $interjectionchunk; } else { #if this is a chunk if($node->nodeName() eq 'CHUNK') { $parent->appendChild($node); } } # set si of root to 'top' if($head eq '0') { my $chunkparent = $node->parentNode(); if($chunkparent && $chunkparent->exists('self::CHUNK') ) { $chunkparent->setAttribute('si', 'top'); $chunkparent->setAttribute('ord', $node->getAttribute('ord')); } } } #my $docstring = $dom->toString(3); #print STDERR $docstring; #print STDERR "\n------------------------\n"; # sentence complete: check if topnode is a CHUNK, if not, change this # otherwise lexical transfer crashes! if($sentence->exists('child::NODE')) { &moveTopNodeUnderChunk($sentence); } # check if main verb is in fact a subordinated clause, if so, make second grup-verb head # if coordinated vp: don't take first child grup-verb (this is the coordinated vp), take the last # note: if parser made something else head of sentence, the top verb might not have si=top my $topverbchunk = @{$sentence->findnodes('child::CHUNK[(@type="grup-verb" or @type="coor-v") and @si="top"][1]')}[0]; #my $topverbchunk = @{$sentence->findnodes('child::CHUNK[(@type="grup-verb" or @type="coor-v")][1]')}[0]; if($topverbchunk && $topverbchunk->exists('child::NODE[@cpos="v"]/descendant::NODE[@pos="cs"]')) { print STDERR "in sentence $sentenceId, top chunk is".$topverbchunk->getAttribute('ord')."\n" if $verbose; my $realMain = @{$topverbchunk->findnodes('child::CHUNK[@type="grup-verb" or @type="coor-v"]/NODE[@cpos="v" and not(child::NODE[@pos="cs"])]')}[-1]; if($realMain) { print STDERR "real main verb: ".$realMain->toString() if $verbose; $topverbchunk->parentNode->appendChild($realMain->parentNode()); $realMain->parentNode()->appendChild($topverbchunk); $topverbchunk->setAttribute('si', 'S'); $realMain->parentNode->setAttribute('si', 'top'); } } my @verbchunks = $sentence->findnodes('descendant::CHUNK[@type="grup-verb" or @type="coor-v"]'); foreach my $verbchunk (@verbchunks) { # check if one of the verbs in this sentence has more than one subject (can happen with statistical parsers!), if only one is congruent with the verb, make this the subject # and the other 'cd-a', if more than one is congruent, make the first one the subject (the one that precedes the verb) # simpler: check if first subject is congruent, if not, check next etc my @subjectNodes = $verbchunk->findnodes('child::CHUNK[@si="suj"]/NODE[@rel="suj"]'); if(scalar(@subjectNodes) > 1) { #print STDERR "verb chunk ord: ".$verbchunk->getAttribute('ord'). "\n" if $verbose; my %subjs =(); foreach my $subjCand (@subjectNodes) { my $ord = $subjCand->getAttribute('ord'); $subjs{$ord} = $subjCand; print STDERR "to many subjects: ".$subjCand->getAttribute('lem')." ord: ".$ord."\n" if $verbose; } my $candIsSubj = 0; foreach my $ord (sort {$a<=>$b} (keys (%subjs))) { my $subjCand = $subjs{$ord}; if(&isCongruent($subjCand,$verbchunk) && $candIsSubj == 0) { print STDERR "correct subj: ".$subjCand->getAttribute('lem')."\n" if $verbose; $candIsSubj =1; } else { $subjCand->parentNode->setAttribute('si', 'cd-a'); $subjCand->setAttribute('rel', 'cd-a'); } #print STDERR "sorted lemma subj: ".$subjCand->getAttribute('lem')." ord: ".$ord."\n" if $verbose; } } } # check if all chunks are children of chunks (if nodes have child chunks, the lexical transfer module is not amused) foreach my $chunk ($sentence->getElementsByTagName('CHUNK')) { if($chunk->parentNode->nodeName eq 'NODE') { my $realparent = @{$chunk->findnodes('ancestor::CHUNK[1]')}[0]; if($realparent){ $realparent->appendChild($chunk); } else{ $sentence->appendChild($chunk); } } } # make sure no chunk has a sibling node, lexical transfer module doesn't like that either my @nodesWithChunkSiblings = $sentence->findnodes('descendant::NODE[preceding-sibling::CHUNK]'); foreach my $node (@nodesWithChunkSiblings) { # print STDERR "node sibl: ".$node->toString()."\n" if $verbose; # if CC or CS -> try to attach it to the following verb chunk, if that fails to the preceding # if there's no verb chunk, attach it to the next higher chunk (probably an error by the tagger, but let's try to avoid # making the lexical transfer fail) # NOTE: no need to copy children of sibling, as NODE with child CHUNKS have already been taken care of above my $possibleHead = @{$node->findnodes('ancestor::CHUNK[@type="grup-verb" or @type="coor-v"]/NODE/descendant-or-self::NODE')}[0]; my $possibleHead2 = @{$node->findnodes('descendant::CHUNK[@type="grup-verb" or @type="coor-v"]/NODE/descendant-or-self::NODE')}[0]; if($possibleHead){ $possibleHead->appendChild($node); } elsif($possibleHead2){ $possibleHead->appendChild($node); } else{ $possibleHead = @{$node->findnodes('ancestor::SENTENCE/CHUNK[@si="top"]/NODE/descendant-or-self::NODE')}[0]; #print $possibleHead->toString()."\n\n"; if($possibleHead){ $possibleHead->appendChild($node); } } } # make sure nodes have no (node) siblings, again, lexical transfer module will crash # solution: attach second sibling as (last) child of first my @nodesWithNodeSiblings = $sentence->findnodes('descendant::NODE[preceding-sibling::NODE]'); foreach my $node (@nodesWithNodeSiblings){ my $prevsibling = $node->previousSibling(); if($prevsibling){ if ($prevsibling->getAttribute('mi') =~ /V...[1-3][SP]./) { # finite $node->appendChild($prevsibling); } else { $prevsibling->appendChild($node); } } } # delete chunks that have only chunk children, but no node children (otherwise lexical transfer crashes) # -> those are probably leftovers from changes to the tree, should not occur my @chunksWithNoNODEchildren = $sentence->findnodes('descendant::CHUNK[count(child::NODE)=0]'); foreach my $chunk (@chunksWithNoNODEchildren){ my $parentchunk = $chunk->parentNode(); if($parentchunk && $parentchunk->nodeName eq 'CHUNK'){ # attach this chunks' chunk children to its parent chunk, then delete it my @childChunks = $chunk->childNodes(); foreach my $child (@childChunks){ $parentchunk->appendChild($child); } $parentchunk->removeChild($chunk); } } # make sure final punctuation (.!?) is child of top chunk, if not, append to top chunk # -> otherwise punctuation will appear in some random position in the translated output! # TODO: ! and ? -> direct speech!! # my @finalPunc = $sentence->findnodes('descendant::NODE[@lem="." or @lem="!" or @lem="?"]'); my @finalPunc = $sentence->findnodes('descendant::NODE[@lem="."]'); foreach my $punc (@finalPunc){ if(isLastNode($punc,$sentence) && !$punc->exists('parent::CHUNK/parent::SENTENCE') ){ my $topchunk = @{$sentence->findnodes('child::CHUNK[1]')}[0]; my $puncChunk = $punc->parentNode(); if($topchunk && $puncChunk){ $topchunk->appendChild($puncChunk); } } } # if there's a sólo/solamente -> find right head # parser ALWAYS attaches this to the verb, but that may not be correct, # e.g. 'Sólo Juan sabe lo que ha hecho.' TODO: nomás! if( $sentence->exists('descendant::NODE[@lem="sólo" or @lem="sólamente"]') ) { my @solos = $sentence->findnodes('descendant::NODE[@lem="sólo" or @lem="sólamente"]'); my $nodeHashref = &nodesIntoSortedHash($sentence); foreach my $solo (@solos){ my $soloOrd = $solo->getAttribute('ord'); my $chunk = @{$solo->findnodes('ancestor::CHUNK[1]')}[0]; my $parent = $chunk->parentNode(); my $nodeAfterSolo = $nodeHashref->{$soloOrd+1}; # if next node is a noun, sólo probably refers to that if($nodeAfterSolo && $nodeAfterSolo->getAttribute('mi') =~ /^N/ ){ my $nodeAfterSoloParentChunk = @{$nodeAfterSolo->findnodes('ancestor::CHUNK[1]')}[0]; if($nodeAfterSoloParentChunk && $chunk && $parent) { $parent->removeChild($chunk); # if $nodeAfterSoloParentChunk is descendant of solo -> attach this chunk first to parent, # then attach chunk to $nodeAfterSoloParentChunk to avoid hierarchy request errors if(&isAncestor($nodeAfterSoloParentChunk, $chunk)){ $parent->appendChild($nodeAfterSoloParentChunk); } $nodeAfterSoloParentChunk->appendChild($chunk); } } } } my ($speechverb) = $sentence->findnodes('descendant::CHUNK[count(descendant::CHUNK[@si="suj"] )=0]/NODE[@lem="hablar" or @lem="contestar" or @lem="decir"]'); # X le habla/contesta/dice -> parser NEVER labels X as suj, but instead as cc or cd.. if no complement clause with que -> automatically make suj if($speechverb){ my @potentialsubjs = $speechverb->findnodes('parent::CHUNK/CHUNK[(@type="sn" or @type="coor-n") and (@si="cc" or @si="cd")]'); if(scalar(@potentialsubjs)>0){ # find le/les my ($clitic) = $speechverb->findnodes('parent::CHUNK/CHUNK[@type="sn"]/NODE[@lem="le" and @pos="pp"]'); if($clitic){ my $cliticOrd = $clitic->getAttribute('ord'); foreach my $potsub (@potentialsubjs){ my $subjOrd= $potsub->getAttribute('ord'); if($cliticOrd-1 == $subjOrd){ $potsub->setAttribute('si', 'suj-a'); last; } } } } } # very rare, but possible: sentence has 2 top chunks (e.g. Autor: Braddy Romero Ricalde) # <SENTENCE ord="1"> # <CHUNK type="sn" si="top" ord="1"> # <NODE ord="1" form="Autor" lem="autor" pos="nc" cpos="n" rel="sentence" mi="NCMS000"/> # <CHUNK type="F-term" si="term" ord="2"> # <NODE ord="2" form=":" lem=":" pos="Fd" cpos="F" mi="FD"/> # </CHUNK> # </CHUNK> # <CHUNK type="sn" si="top" ord="3"> # <NODE ord="3" form="Braddy_romero_ricalde" lem="braddy_romero_ricalde" pos="np" cpos="n" rel="sentence" mi="NP00SP0"/> # </CHUNK> # </SENTENCE> # ---> attach second top chunk as child of first top chunk: otherwise, ordering will make them both ord=0 my @topChunks = $sentence->findnodes('child::CHUNK'); if(scalar(@topChunks)>1){ my $firstTopChunk = @topChunks[0]; for(my $i=1;$i<scalar(@topChunks);$i++){ my $chunk = @topChunks[$i]; $firstTopChunk->appendChild($chunk); } } # check if this sentence contains a verb chunk with more than one finite verb in it # -> make two chunks my @verbchunksWithTwoFiniteVerbs = $sentence->findnodes('descendant::CHUNK[@type="grup-verb" or @type="coor-v" and child::NODE/descendant-or-self::NODE[@cpos="v" and ( contains(@mi,"1") or contains(@mi,"2") or contains(@mi,"3") )]/descendant::NODE[@cpos="v" and ( contains(@mi,"1") or contains(@mi,"2") or contains(@mi,"3"))] ]' ); if(scalar(@verbchunksWithTwoFiniteVerbs)>0) { foreach my $doubleVerbChunk (@verbchunksWithTwoFiniteVerbs) { #get both finite verbs my $topFiniteVerb = @{$doubleVerbChunk->findnodes('child::NODE/descendant-or-self::NODE[@cpos="v" and ( contains(@mi,"1") or contains(@mi,"2") or contains(@mi,"3") )][1]')}[0]; if($topFiniteVerb) { my @dependendFiniteVerbs = $topFiniteVerb->findnodes('descendant::NODE[@cpos="v" and ( contains(@mi,"1") or contains(@mi,"2") or contains(@mi,"3") )]'); # make new chunks and attach the chunks to verb chunk foreach my $finiteVerb (@dependendFiniteVerbs) { my $newVerbChunk = XML::LibXML::Element->new( 'CHUNK' ); $newVerbChunk->setAttribute('type', 'grup-verb'); $newVerbChunk->setAttribute('si', $finiteVerb->getAttribute('rel')); $newVerbChunk->setAttribute('ord', $finiteVerb->getAttribute('ord')); $finiteVerb->removeAttribute('rel'); $finiteVerb->removeAttribute('head'); $newVerbChunk->appendChild($finiteVerb); $doubleVerbChunk->appendChild($newVerbChunk); } } } } } # print new xml to stdout #my $docstring = $dom->toString(3); #print STDOUT $docstring; return $dom; } sub toEaglesTag{ my $pos= $_[0]; my $info=$_[1]; my $eaglesTag; #adjectives # 0: A # 1: Q,O,0 (type) # 2: 0 (grade, Spanish always 0) # 3: M,F,C (gender) # 4: S,P (number) # 5: P,0 (function, participe/zero) if($pos=~ /^a/) { my ($gen, $num) = ($info =~ m/gen=(.)\|num=(.)/ ); my $fun ="0"; if($info =~ /fun=/) { my @fun = ($info =~ m/fun=(.)/ ); $fun = @fun[0]; } $eaglesTag = $pos."0"."$gen$num$fun"; #print STDERR "feat: $eaglesTag\n" if $verbose; } #determiners # 0: D # 1: D,P,T,E,I,A+N (numeral) -> type # 2: 1,2,3 (person) # 3: M,F,C,N (gender) # 4: S,P,N (number) # 5: S,P (possessor number) elsif ($pos=~/^d/) { my ($gen, $num)= ($info =~ m/gen=(.)\|num=(.)/ ); my $per = "0"; my $pno = "0"; if($info =~ /per=/) { ($per) = ($info =~ m/per=(.)/ ); } if($info =~ /pno=/) { ($pno) = ($info =~ m/pno=(.)/ ); } $eaglesTag = "$pos$per$gen$num$pno"; #print STDERR "feat: $eaglesTag\n" if $verbose; } # nouns # 0: N # 1: C,P (type) # 2: M,F,C (gender) # 3: S,P,N (number) # 4-5: semantics (NP): SP, G0, O0, V0 (not present atm...) # 6: A,D (grade, augmentative, diminutive) -> always zero from freeling elsif ($pos=~/^n/) { my ($gen, $num)= ($info =~ m/gen=(.)\|num=(.)/ ); my ($nptype) = ($info =~ m/np=(..)/ ); #print STDERR "feat: $gen, $num, $info\n" if $verbose; if($gen eq 'c') { $gen = '0'; } if($num eq 'c') { $num = '0'; } #if proper noun if($nptype ne '') { $pos = "np"; $eaglesTag = "$pos$gen$num$nptype"."0"; } else { $eaglesTag = "$pos$gen$num"."000"; } #print STDERR "feat: $eaglesTag, $info\n" if $verbose; } # verbs # 0: V # 1: M,A,S (type) # 2: I,S,M,N,G,P (mode) # 3: P,I,F,S,C,0 (tense) # 4: 1,2,3 (person) # 5: S,P (number) # 6: M,F (gender, participles) #gen=c|num=p|per=3|mod=i|ten=s , per,mod,ten optional elsif ($pos=~/^v/) { my $per = "0"; my $mod = "0"; my $ten = "0"; my ($gen, $num) = ($info =~ m/gen=(.)\|num=(.)/); if($gen eq 'c') { $gen = '0'; } if($num eq 'c') { $num = '0'; } if($info =~ /per=/) { ($per) = ($info =~ m/per=(.)/ ); } if($info =~ /mod=/) { ($mod) = ($info =~ m/mod=(.)/ ); } if($info =~ /ten=/) { ($ten) = ($info =~ m/ten=(.)/ );; } $eaglesTag = "$pos$mod$ten$per$num$gen"; #print STDERR "feat: $eaglesTag\n" if $verbose; } #pronouns que PR0CN000 # 0: P # 1: P,D,X,I,T,R,E (type) # 2: 1,2,3 (person) # 3: M,F,C (gender) # 4: S,P,N (number) # 5: N,A,D,O (case) # 6: S,P (possessor number) # 7: Politeness (P,0) # gen+num oblig, rest optional elsif ($pos=~/^p/) { my $per = "0"; my $cas = "0"; my $pno = "0"; my $polite = "0"; my ($gen, $num) = ($info =~ m/gen=(.)\|num=(.)/); if($gen eq 'c') { $gen = 'C'; } if($num eq 'c') { $num = 'N'; } if($info =~ /cas=/) { ($cas) = ($info =~ m/cas=(.)/ ); } if($info =~ /per=/) { ($per) = ($info =~ m/per=(.)/ ); } if($info =~ /pno=/) { ($pno) = ($info =~ m/pno=(.)/ ); } if($info =~ /pol=/) { ($polite) = ($info =~ m/pol=(.)/ ); } $eaglesTag = "$pos$per$gen$num$cas$pno$polite"; #print STDERR "feat pronoun: $eaglesTag\n" if $verbose; } #prepositions # 0: S # 1: P (type) # 2: S,C (form -> simple, contracted) # 3: M (gender -> only for al+del) # 4: S (number -> al+del) elsif ($pos=~/^s/) { my ($gen, $num, $form) = ($info =~ m/gen=(.)\|num=(.)\|for=(.)/); if($num eq 'c') { $num = "0"; } if($gen eq 'c') { $gen = "0"; } $eaglesTag = "$pos$form$gen$num"; #print STDERR "feat: $eaglesTag\n" if $verbose; } # other cases else { $eaglesTag = $pos; } if($eaglesTag =~ /^Z|z/){return ucfirst($eaglesTag); } else{return uc($eaglesTag); } } sub isCongruent{ my $subjNode =$_[0]; my $parentNode = $_[1]; if($parentNode && $subjNode) { #if parent is verb chunk, get the finite verb if($parentNode->nodeName() eq 'CHUNK') { $parentNode = &getFiniteVerb($parentNode); if($parentNode == -1) { return -1; } } # if this is not a finite verb, get finite verb! (wrong analysis, may happen) elsif($parentNode->getAttribute('mi') !~ /1|2|3/) { my $parentNodeCand = &getFiniteVerb($parentNode); if($parentNodeCand != -1) { $parentNode = $parentNodeCand; $parentNodeCand->toString()."\n\n"; } #if no finite verb found, don't change anything else { return 1; } } #print STDERR "parentnode: ".$parentNode->toString."\n" if $verbose; my $verbMI = $parentNode->getAttribute('mi'); my $verbPerson = substr ($verbMI, 4, 1); my $verbNumber = substr ($verbMI, 5, 1); my $subjMI = $subjNode->getAttribute('mi'); my $nounPerson; my $nounNumber; # no need to disambiguate false 1/2 person subjects (parser gets those right, as they are marked with 'a' if cd) # but sometimes 'me, te, nos..' are labeled as 'suj' -> cd-a if($subjNode->getAttribute('pos') eq 'pp') { my $prs = $subjNode->getAttribute('mi'); if($subjNode->exists('child::NODE[@lem="ni" or @rel="coord"]')) { my @coordElems = $subjNode->childNodes(); foreach my $coordnode (@coordElems) { $coordnode = $coordnode->toString(); } # if head is 2 prs sg/pl -> always 2pl or 3pl , except with 1 sg/pl-> 1pl # tú y el, vosotros y ellos,-> 3pl, but tú y yo, vosotros y nosotros -> 1pl if( $prs =~ /^PP2/) { #tú y yo/nosotros/as -> 1pl if(grep {$_ =~ /mi="PP1/} @coordElems) { $nounPerson = '1'; $nounNumber = 'P'; } #tú y Manuel, tú y el padre... -> 2pl else { $nounPerson = '23'; $nounNumber = 'P'; } } # if head is 1 sg/pl -> coordination always 1pl (yo y tú/yo y él/yo y ustedes..vamos al cine) # nosotros y él, nosotros y tú, etc elsif($prs =~ /^PP1/) { $nounPerson = '1'; $nounNumber = 'P'; } # if PP3 else { # él y yo, ellos y nosostros -> 1pl if(grep {$_ =~ /mi="PP1/} @coordElems) { $nounPerson = '1'; $nounNumber = 'P'; } # él y tú, ellos y vosostros -> 2pl elsif(grep {$_ =~ /mi="PP2/} @coordElems) { $nounPerson = '2'; $nounNumber = 'P'; } else { $nounPerson = '3'; $nounNumber = 'P'; } } } # if 'me,te,se,nos,vos,os' as suj -> change to cd-a elsif($subjNode->exists('self::NODE[@lem="me" or @lem="te" or @lem="se" or @lem="nos" or @lem="vos" or @lem="os" or @lem="le" or @lem="lo"]')) { return 0; } #no coordination else { $nounPerson = substr ($subjMI, 2, 1); $nounNumber = substr ($subjMI, 4, 1); # if yo,él,ella and not congruent and verb is ambiguous 3rd/1st form # cantaba (pasado imperfecto), cantaría (condicional), cante (subjuntivo presente), cantara (subjuntivo imperfecto),cantare (subjuntivo futuro) # -> change tag of verb! if($subjNode->exists('self::NODE[@lem="él" or @lem="ella"]') && $verbMI =~ /V.II1S0|V.IC1S0|V.SP1S0|V.SI1S0|V.SF1S0/ ) { $verbMI =~ s/1/3/; $parentNode->setAttribute('mi', $verbMI); return 1; } elsif($subjNode->exists('self::NODE[@lem="yo"]') && $verbMI =~ /V.II3S0|V.IC3S0|V.SP1S0|V.SI3S0|V.SF3S0/ ){ $verbMI =~ s/3/1/; $parentNode->setAttribute('mi', $verbMI); return 1; } } } #interrogative pronouns: no person (quién eres, quién soy..) elsif($subjMI =~ /^PT/){ return 1; } else { $nounPerson = '3'; # plural if coordinated subjects if($subjNode->exists('child::NODE[@lem="ni" or @rel="coord"]') ) { $nounNumber = 'P'; } # exception with 'parte' -> 'una buena parte de ellos radican en países pobres..' -> ignore number elsif( $subjNode->getAttribute('lem') =~ /parte|n.mero/ || $subjNode->exists('child::NODE[@lem="%"]') || $subjNode->exists('child::CHUNK/NODE[@lem="%"]')) { return 1; } else { # if subject is a demonstrative or an indefinite pronoun (pd/pi), number is the 5th letter if($subjNode->getAttribute('cpos') eq 'p') { $nounNumber = $nounNumber = substr ($subjMI, 4, 1); } elsif($subjNode->getAttribute('pos') eq 'Z' && ($subjNode->getAttribute('lem') eq '1' || $subjNode->getAttribute('lem') eq 'uno' )) { $nounNumber = 'S'; } elsif($subjNode->getAttribute('pos') eq 'Z' && ($subjNode->getAttribute('lem') ne '1' || $subjNode->getAttribute('lem') ne 'uno' )) { $nounNumber = 'P'; } else { $nounNumber = substr ($subjMI, 3, 1); # proper names have no number, assume singular if($nounNumber eq '0') { #if number unknown, leave as is return 1; #$nounNumber = 'S'; } } } } # my $verbform = $parentNode->getAttribute('form'); # my $nounform = $subjNode->getAttribute('form'); # my $nounmi = $subjNode->getAttribute('mi'); # print STDERR "$nounform:$verbform verbprs:$verbPerson, verbnmb:$verbNumber, nounPrs:$nounPerson, nounNumb:$nounNumber, nounMI: $nounmi\n" if $verbose; return ($nounPerson =~ $verbPerson && $nounNumber eq $verbNumber); } # if subject node or parent node doees not exist, don't change anything (this should not happen) else { return 1; } } sub getFiniteVerb{ my $verbchunk = $_[0]; #print STDERR "verbchunk: ".$verbchunk->toString() if $verbose; # finite verb is the one with a person marking (1,2,3) # case: only finite verb in chunk my @verb = $verbchunk->findnodes('child::NODE[starts-with(@mi,"V") and (contains(@mi,"3") or contains(@mi,"2") or contains(@mi,"1"))][1]'); if(scalar(@verb)>0) { return @verb[0]; } else { @verb = $verbchunk->findnodes('NODE/NODE[starts-with(@mi,"V") and (contains(@mi,"3") or contains(@mi,"2") or contains(@mi,"1")) ][1]'); if(scalar(@verb)>0) { return @verb[0]; } else { #get sentence id my $sentenceID = $verbchunk->findvalue('ancestor::SENTENCE/@ord'); print STDERR "finite verb not found in sentence nr. $sentenceID: \n " if $verbose; print STDERR $verbchunk->toString() if $verbose; print STDERR "\n" if $verbose; return -1; } } } sub correctCoord{ my $prsprn = $_[0]; my $sentenceId = $_[1]; if($prsprn) { my $coord = @{$prsprn->findnodes('child::NODE[@lem="ni" or @rel="coord"][1]')}[0]; my @children = $prsprn->childNodes(); # if no coordinated element attached, children =1 (only coord, 'y', 'o') # with ni: 2 childs ('ni tú ni yo vamos al cine') if(( $coord && scalar(@children) < 2 )|| ($prsprn->exists('child::NODE[@lem="ni"]') && scalar(@children) < 3 ) ) { # if 'y'/'o' has a child, this is the coordinated element if($coord->hasChildNodes()) { my @coordElems = $coord->childNodes(); foreach my $coordElem (@coordElems) { #attach to prsprn $prsprn->appendChild($coordElem); my $ord = $coordElem->getAttribute('ord'); my $head = $prsprn->getAttribute('ord'); $coordElem->setAttribute('head', $head); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $prsprn; } } else { #get coordinated element, probably first following sibling of prsprn my $coordElem = @{$prsprn->findnodes('following-sibling::NODE[1]')}[0]; if($coordElem) { #attach coordinated element to coordination ('y', 'o'..) $prsprn->appendChild($coordElem); my $ord = $coordElem->getAttribute('ord'); my $head = $prsprn->getAttribute('ord'); $coordElem->setAttribute('head', $head); my $idKey = "$sentenceId:$ord"; $docHash{$idKey}= $prsprn; } } } } } sub getHeadNoun{ my $verbNode= $_[0]; if($verbNode) { my $parentchunk = @{$verbNode->findnodes('../../self::CHUNK[@type="sn"][1]')}[0]; my $headNoun; if($parentchunk) { #if preceded by single noun if($parentchunk->exists('self::CHUNK[@type="sn"]')) { # if head noun is a demonstrative pronoun (doesn't ocurr? TODO: check) $headNoun = @{$parentchunk->findnodes('child::NODE[starts-with(@mi,"N") or starts-with(@mi,"PP")][1]')}[-1]; } #if head noun is defined, return if($headNoun) { return $headNoun; } else { #get sentence id print STDERR "Head noun not found in: \n" if $verbose; print STDERR $parentchunk->toString()."\n" if $verbose; return 0; } } } } sub hasRealSubj{ my $verb = $_[0]; my $subj = @{$verb->findnodes('child::NODE[@rel="suj"][1]')}[0]; if($verb && $subj && &isCongruent($subj,$verb)) { # check if 'real' subject (not 'me','te,'se' etc, check if really congruent!) # -> if prsprn and congruent: check case of prs-prn, if accusative-> this can't be a subject my $mi= $subj->getAttribute('mi'); if($mi =~ /^PP/) { my $case = substr($mi,5,1); return ($case =~ /N|0/); } return 1; } return 0; } sub nodesIntoSortedHash{ my $sentence = $_[0]; my %nodeHash =(); # read sentence into hash, key is 'ord' foreach my $node ($sentence->getElementsByTagName('NODE')) { my $key = $node->getAttribute('ord'); $nodeHash{$key} = $node; } my @sequence = sort {$a<=>$b} keys %nodeHash; return \%nodeHash; } sub attachCSToCorrectHead{ my $cs = $_[0]; my $sentence = $_[1]; if($cs) { my $currentParent = $cs->parentNode; #if parent of subjunction is verb -> check if it's the right verb if($currentParent && $currentParent->getAttribute('cpos') eq 'v') { my %nodeHash =(); my $followingMainVerb; # read sentence into hash, key is 'ord' foreach my $node ($sentence->getElementsByTagName('NODE')) { my $key = $node->getAttribute('ord'); $nodeHash{$key} = $node; } my $csord = $cs->getAttribute('ord'); my $parentord = $currentParent->getAttribute('ord'); my @sequence = sort {$a<=>$b} keys %nodeHash; #print STDERR "@sequence\n length ".scalar(@sequence)."\n" if $verbose; my $isRelClause=0; for (my $i=$csord+1; $i<=scalar(@sequence);$i++) { my $node = $nodeHash{$i}; #print STDERR "i: $i ".$node->getAttribute('form')."\n" if $verbose; if($node && $node->getAttribute('pos') eq 'pr'){ $isRelClause =1; } if($node && $node->getAttribute('pos') eq 'vm' && (!$nodeHash{$i+1} || $nodeHash{$i+1}->getAttribute('pos') ne 'vm' ) ) #if($node && $nodeHash{$i+1} && $node->getAttribute('pos') eq 'vm' && $nodeHash{$i+1}->getAttribute('pos') ne 'vm' ) { if($isRelClause){ # if this is a relative Clause, skip, but set isRelClause to 0 $isRelClause =0; } else{ $followingMainVerb = $node; last; } } } #print STDERR "foll verb: ".$followingMainVerb->getAttribute('form')."\n" if $verbose; #print STDERR "current verb: ".$currentParent->getAttribute('form')."\n" if $verbose; if($followingMainVerb && !$followingMainVerb->isSameNode($currentParent)) { #print STDERR "foll verb: ".$followingMainVerb->toString() if $verbose; #if verb is descendant of cs, first attach verb to head of cs, then attach cs to verb # otherwise we get a hierarchy request err if(&isAncestor($followingMainVerb,$cs)) { $currentParent->appendChild($followingMainVerb); $followingMainVerb->setAttribute('head', $currentParent->getAttribute('ord')); } $followingMainVerb->appendChild($cs); $cs->setAttribute('head', $followingMainVerb->getAttribute('ord')); # if cs has child nodes -> attach them to head of cs # my @csChildren = $cs->childNodes(); # foreach my $child (@csChildren){ # $followingMainVerb->appendChild($child); # $child->setAttribute('head', $followingMainVerb->getAttribute('ord')); # } } #TODO: check linear sequence, subjunction belongs to next following verb chunk (no verb in between!) } # if parent is not a verb, subjunction is probably the head of the clause.. look for verb in children! # <NODE ord="6" form="para_que" lem="para_que" pos="cs" cpos="c" head="5" rel="CONCAT" mi="CS"> # <CHUNK type="sn" si="cd" ord="7"> # <NODE ord="7" form="lo" lem="lo" pos="pp" cpos="p" rel="cd" mi="PP3MSA00"> # <NODE ord="8" form="lean" lem="leer" pos="vm" cpos="v" head="7" rel="CONCAT" mi="VMSP3P0"/> else { my $headverb = @{$cs->findnodes('descendant::NODE[@pos="vm"][1]')}[0]; if($headverb) { $currentParent->appendChild($headverb); $headverb->appendChild($cs); $cs->setAttribute('head', $headverb->getAttribute('ord')); $headverb->setAttribute('head', $currentParent->getAttribute('ord')); #append other children of cs to verb my @otherChildren = $cs->childNodes(); foreach my $child (@otherChildren) { $headverb->appendChild($child); $child->setAttribute('head', $headverb->getAttribute('ord')); } } } } } sub isAncestor{ my $node = $_[0]; my $maybeAncestor = $_[1]; if($node && $maybeAncestor) { my $maybeAncestorOrd = $maybeAncestor->getAttribute('ord'); my $xpath = 'ancestor::*[@ord="'.$maybeAncestorOrd.'"]'; return($node->exists($xpath)); } # this should not happen else { return 0; } } sub attachNewChunkUnderChunk{ my $newChunk = $_[0]; my $parent = $_[1]; my $sentence = $_[2]; if($newChunk && $parent) { #print STDERR "parent node before ". $parent->toString() . "\n" if $verbose; #print STDERR "parent nodeName before ". $parent->nodeName . "\n" if $verbose; if ($parent->nodeName eq 'NODE') { #print STDERR "new chunk" . $newChunk->toString(). " within NODE ". $parent->toString() ." has to be appended to a higher CHUNK\n" if $verbose; $parent = @{$parent->findnodes('ancestor::CHUNK[1]')}[0]; } #print STDERR "parent node after ". $parent->toString() . "\n" if $verbose; if($parent) { $parent->appendChild($newChunk); return $parent; } # no parent chunk, attach to sentence else { $sentence->appendChild($newChunk); return $sentence; } } #this should not happen else { print STDERR "failed to attach node to new chunk \n"; } } sub model2{ my $sentence = $_[0]; my $desrPort2= $_[1]; if($sentence) { $sentence->removeChildNodes(); my $sentenceId = $sentence->getAttribute('ord'); my $path = File::Basename::dirname(File::Spec::Functions::rel2abs($0)); my $tmp = $path."/tmp/tmp2.conll"; open (TMP, ">:encoding(UTF-8)", $tmp); print TMP $conllHash{$sentenceId}; open(DESR,"-|" ,"cat $tmp | desr_client $desrPort2" ) || die "parsing failed: $!\n"; while (<DESR>) { #print STDERR "bla".$_; unless(/^\s*$/) { # create a new word node and attach it to sentence my $wordNode = XML::LibXML::Element->new( 'NODE' ); $sentence->appendChild($wordNode); my ($id, $word, $lem, $cpos, $pos, $info, $head, $rel, $phead, $prel) = split (/\t|\s/); # special case with estar (needs to be vm for desr and form instead of lemma -> set lemma back to 'estar') if($pos =~ /vm|va/ && $lem =~ /^est/ && $lem !~ /r$/) { $lem = "estar"; #$pos = "va"; } my $eaglesTag = &toEaglesTag($pos, $info); # if verb (gerund,infinitve or imperative form) has clitic(s) then make new node(s) # exclude certain words that may occur at the end of the lemma in locutions (e.g. echar_de_menos) -> we don't want to split -os in this case! if($eaglesTag =~ /^V.[GNM]/ and $word !~ /parte|frente|adelante|base|menos$/ and $word =~ /(me|te|nos|os|se|[^l](la|las|lo|los|le|les))$/ and $word != /_/) { print STDERR "clitics in verb $lem: $word\n" if $verbose; my $clstr = splitCliticsFromVerb($word,$eaglesTag,$lem); if ($clstr !~ /^$/) # some imperative forms may end on "me|te|se|la|le" and not contain any clitic { &createAppendCliticNodes($sentence,$sentenceId,$id,$clstr); } } if($eaglesTag =~ /^NP/) { $pos="np"; } # often: 'se fue' -> fue tagged as 'ser', VSIS3S0 -> change to VMIS3S0, set lemma to 'ir' if($eaglesTag =~ /VSIS[123][SP]0/ && $lem eq 'ser'){ my $precedingWord = $docHash{$sentenceId.":".($id-1)}; #print STDERR "preceding of fue: ".$precedingWord->getAttribute('lem')."\n" if $verbose; if($precedingWord && $precedingWord->getAttribute('lem') eq 'se'){ $eaglesTag =~ s/^VS/VM/ ; #print STDERR "new tag: $eaglesTag\n" if $verbose; $lem = 'ir'; } } if($lem =~ /\/reir/){ $lem = 'reír'; } $wordNode->setAttribute( 'ord', $id ); $wordNode->setAttribute( 'form', $word ); $wordNode->setAttribute( 'lem', $lem ); $wordNode->setAttribute( 'pos', $pos ); $wordNode->setAttribute( 'cpos', $cpos ); $wordNode->setAttribute( 'head', $head ); $wordNode->setAttribute( 'rel', $rel ); $wordNode->setAttribute( 'mi', $eaglesTag ); # print "$eaglesTag\n"; # store node in hash, key sentenceId:wordId, in order to resolve dependencies my $key = "$sentenceId:$id"; $docHash{$key}= $wordNode; # print STDERR "\n##################\n"; # foreach my $key (keys %docHash){print STDERR "key $key $docHash{$key}\n";} # print STDERR "\n##################\n"; # print $sentence->toString(); # print "\n\n"; } } close TMP; close DESR; #unlink("tmp.conll"); } # this should not happen! else { print STDERR "failed to parse sentence!\n"; } } # clitics stuff # freeling could retokenize the enclitics but we don't split the verb forms before parsing # because desr parser was apparently not trained on data with separate clitics sub getCliticRelation{ my $cltag = $_[0]; my $rel; if ($cltag =~ /^PP...A/) { $rel = "cd"; } elsif ($cltag =~ /^PP...D/) { $rel = "ci"; } else { $rel = "cd/ci"; } return $rel; } sub splitCliticsFromVerb{ my $word = $_[0]; my $vtag = $_[1]; my $vlem = $_[2]; my @vfcl; # TODO change the verb form in the verb node? currently not... # gerund if ($vtag =~ /V.G/ and $word =~ /(.*ndo)([^d]+)/) { $vfcl[0] = $1; $vfcl[1] = $2; print STDERR "verb gerund $vfcl[0] ; clitics $vfcl[1]\n" if $verbose; } # infinitive elsif ($vtag =~ /V.N/ and $word =~ /(.*r)([^r]+)/) { $vfcl[0] = $1; $vfcl[1] = $2; print STDERR "verb infinitive $vfcl[0] ; clitics $vfcl[1]\n" if $verbose; } # imperative elsif ($vtag =~ /V.M/) { my $vend = ""; # some imperative forms may end on "me|te|se|la|le" and not contain any clitic if ($vtag =~ /V.M02S0/ and $vlem =~ /([mst][ei]|la)r$/) # cómetelas => come-telas (comer) ; vístete => viste-te (vestir) { $vend = $1; } elsif ($vtag =~ /V.M03S/) { if ($vlem =~ /([mst]a)r$/) # mátelo => mate-lo (matar) { $vend = $1; $vend =~ s/a/e/; } elsif ($vlem =~ /ler$/) # demuélala => demuela-la (demoler) { $vend = "la"; } } elsif ($vtag =~ /V.M01P0/) { $vend = "mos"; } print STDERR "$vtag verb $vlem form ends in $vend\n" if $verbose; if ($word =~ /(.*?$vend)((me|te|nos|os|se|la|las|lo|los|le|les)+)$/) { $vfcl[0] = $1; $vfcl[1] = $2; } else { $vfcl[0] = $word; $vfcl[1] = ""; } print STDERR "verb imperative $vfcl[0] ; clitics $vfcl[1]\n" if $verbose; } return $vfcl[1]; # only return a single variable, the clitic string } sub getClitics{ my $clstr = $_[0]; my $cl = $clstr; my @clitics; while ($cl !~ /^$/) { if ($cl =~ /(.*)(la|las|lo|los|le|les)$/) { $cl = $1; unshift(@clitics,$2); } elsif ($cl =~ /(.*)(me|te|se|nos)$/) { $cl = $1; unshift(@clitics,$2); } elsif ($cl =~ /(.*)(os)$/) { $cl = $1; unshift(@clitics,$2); } } return \@clitics; } sub createAppendCliticNodes{ my $sentence = $_[0]; my $scount = $_[1]; my $verbid = $_[2]; my $clstr = $_[3]; my $clid = int($verbid) + 0.1; my $clitics = &getClitics($clstr); foreach my $c (@{$clitics}) { print STDERR "$c\n" if $verbose; my $cliticNode = XML::LibXML::Element->new( 'NODE' ); $sentence->appendChild($cliticNode); $cliticNode->setAttribute( 'ord', $clid ); # TODO new id... $cliticNode->setAttribute( 'form', $c ); $cliticNode->setAttribute( 'lem', $mapCliticFormToLemma{$c} ); $cliticNode->setAttribute( 'pos', "pp" ); $cliticNode->setAttribute( 'cpos', "p" ); $cliticNode->setAttribute( 'head', $verbid ); # head of clitics is the verb itself my $cleaglesTag = $mapCliticToEaglesTag{$c}; print STDERR "eagles tag for clitic $c : $cleaglesTag\n" if $verbose; my $clrel = &getCliticRelation($cleaglesTag); $cliticNode->setAttribute( 'rel', $clrel ); # TODO rel = cd|ci|creg? refl? print STDERR "possible relation for clitic $c : $clrel\n" if $verbose; $cliticNode->setAttribute( 'mi', $cleaglesTag ); my $clkey = "$scount:$clid"; $docHash{$clkey}= $cliticNode; $clid += 0.1; } } sub isLastNode{ my $node = $_[0]; my $sentence = $_[1]; my %nodeHash =(); # read sentence into hash, key is 'ord' foreach my $node ($sentence->findnodes('descendant::NODE')) { my $key = $node->getAttribute('ord'); #print STDERR $node->getAttribute('form')."key: $key\n" if $verbose; $nodeHash{$key} = $node; } my $nodeord = $node->getAttribute('ord'); my @sequence = sort {$a<=>$b} keys %nodeHash; #print STDERR "last node: ".@sequence[0]."n" if $verbose; return ( scalar(@sequence)>1 && $nodeHash{@sequence[-1]}->isSameNode($node) ); } sub moveTopNodeUnderChunk{ my $sentence = $_[0]; my $sentenceId = $sentence->getAttribute('ord'); # wrong analysis, head of sentence is a node instead of chunk -> get first verb chunk and make this the head # if there is no verb chunk -> take the first child that a chunk (any type) and make this the head my $topnode = @{$sentence->findnodes('child::NODE[1]')}[0]; my $firstverbchunk = @{$sentence->findnodes('descendant::CHUNK[@type="grup-verb" or @type="coor-v"][1]')}[0]; if($firstverbchunk && $topnode) { $sentence->appendChild($firstverbchunk); $firstverbchunk->appendChild($topnode); $firstverbchunk->setAttribute('si', 'top'); print STDERR "moved verb chunk to top in sentence: $sentenceId\n" if $verbose; } else { my $firstAnyChunk = @{$sentence->findnodes('descendant::CHUNK[1]')}[0]; if($firstAnyChunk && $topnode) { $sentence->appendChild($firstAnyChunk); # attach original topnode as child to child node of new top node # note: node must be attached to child NODE of top chunk, otherwise we have node siblings and the lexical transfer module is not happy my $newtopnode = @{$firstAnyChunk->findnodes('child::NODE[1]')}[0]; $newtopnode->appendChild($topnode); $firstAnyChunk->setAttribute('si', 'top'); print STDERR "moved non-verbal chunk to top in sentence: $sentenceId\n" if $verbose; } # if no chunk: create an artificial chunk (otherwise lexical module will crash!) elsif($topnode) { my $dummyChunk = XML::LibXML::Element->new( 'CHUNK' ); $dummyChunk->setAttribute('si', 'top'); $dummyChunk->setAttribute('type', 'dummy'); $dummyChunk->setAttribute('ord', $topnode->getAttribute('ord')); $sentence->appendChild($dummyChunk); $dummyChunk->appendChild($topnode); print STDERR "inserted dummy chunk as head in sentence: $sentenceId\n" if $verbose; } } # check if topnode is now chunk, if not, repeat if($sentence->findnodes('child::NODE')){ &moveTopNodeUnderChunk($sentence); } } 1;
35.181377
334
0.570038
ed214e2e85b3e7aad4f1ac5bc1f32571f9062787
12,749
pm
Perl
lib/Geonode/Free/ProxyList.pm
juliodcs/Geonode-Free-ProxyList
457f6595184ab3e8c09e10809ccc2be9b0440360
[ "ClArtistic" ]
null
null
null
lib/Geonode/Free/ProxyList.pm
juliodcs/Geonode-Free-ProxyList
457f6595184ab3e8c09e10809ccc2be9b0440360
[ "ClArtistic" ]
null
null
null
lib/Geonode/Free/ProxyList.pm
juliodcs/Geonode-Free-ProxyList
457f6595184ab3e8c09e10809ccc2be9b0440360
[ "ClArtistic" ]
null
null
null
package Geonode::Free::ProxyList; use 5.010; use strict; use warnings; use Carp 'croak'; use List::Util qw( shuffle ); use List::MoreUtils qw( uniq ); use LWP::UserAgent; use JSON::PP; use utf8; use Geonode::Free::Proxy; =head1 NAME Geonode::Free::ProxyList - Get Free Geonode Proxies by using some filters =head1 VERSION Version 0.0.5 =cut our $VERSION = '0.0.5'; my $API_ROOT = 'https://proxylist.geonode.com/api/proxy-list?'; =head1 SYNOPSIS Get Geonode's free proxy list and apply some filters. You can later choose them by random. my $proxy_list = Geonode::Free::ProxyList->new(); $list->set_filter_google('true'); $list->set_filter_port(3128); $list->set_filter_limit(200); $list->add_proxies; # Add proxies to the list for current filters $list->set_filter_google('false'); $list->set_filter_port(); # reset filter $list->set_filter_limit(); # reset filter $list->set_filter_protocol_list( [ 'socks4', 'socks5' ] ); $list->set_filter_speed('fast'); $list->add_proxies; # Add proxies to the list for current filters # List of proxies is shuffled my $some_proxy = $list->get_next; # Repeats when list is exhausted my $other_proxy = $list->get_next; # Repeats when list is exhausted my $random_proxy = $list->get_random_proxy; # Can repeat $some_proxy->get_methods(); # [ 'http', 'socks5' ] Geonode::Free::Proxy::prefer_socks(); # Will use socks for url, if available $some_proxy->get_url(); # 'socks://127.0.0.1:3128'; Geonode::Free::Proxy::prefer_http(); # Will use http url, if available $some_proxy->get_url(); # 'http://127.0.0.1:3128'; $some_proxy->can_use_http(); # 1 $some_proxy->can_use_socks(); # 1 $other_proxy->can_use_socks(); # q() $other_proxy->can_use_http(); # 1 Geonode::Free::Proxy::prefer_socks(); # Will use socks for url, if available $some_proxy->get_url(); # 'http://foo.bar.proxy:1234'; =head1 SUBROUTINES/METHODS =head2 new Instantiate Geonode::Free::ProxyList object =cut sub new { my $self = bless { proxy_list => [], index => 0, filters => {}, ua => LWP::UserAgent->new() }, shift; $self->reset_filters(); return $self; } =head2 reset_proxy_list Clears proxy list =cut sub reset_proxy_list { my $self = @_; $self->{proxy_list} = []; return; } =head2 reset_filters Reset filtering options =cut sub reset_filters { my ($self) = @_; $self->{filters} = { country => undef, google => undef, filterPort => undef, protocols => undef, anonymityLevel => undef, speed => undef, filterByOrg => undef, filterUpTime => undef, filterLastChecked => undef, limit => undef }; return; } =head2 set_filter_country Set country filter. Requires a two character uppercase string or undef to reset the filter =cut sub set_filter_country { my ( $self, $country ) = @_; if ( defined $country && $country !~ m{^[A-Z]{2}$}sxm ) { croak q() . "ERROR: '$country' is not a two character uppercase code\n" . "Please, check valid values at following url:\n" . 'https://geonode.com/free-proxy-list'; } $self->{filters}{country} = $country; return; } =head2 set_filter_google Set google filter. Allowed values are 'true'/'false'. You can use undef to reset the filter =cut sub set_filter_google { my ( $self, $google ) = @_; if ( defined $google && $google !~ m{^(?: true|false )$}sxm ) { croak q() . "ERROR: '$google' is not a valid value for google filter\n" . 'Valid values are: true/false'; } $self->{filters}{google} = $google; return; } =head2 set_filter_port Set port filter. Allowed values are numbers that does not start by zero. You can use undef to reset the filter =cut sub set_filter_port { my ( $self, $port ) = @_; if ( defined $port && $port !~ m{^(?: (?!0)[0-9]++ )$}sxm ) { croak "ERROR: '$port' is not a valid value for por filter"; } $self->{filters}{filterPort} = $port; return; } =head2 set_filter_protocol_list Set protocol list filter. Allowed values are http, https, socks4, socks5. You can use an scalar or a list of values. By using undef you can reset the filter =cut sub set_filter_protocol_list { my ( $self, $protocol_list ) = @_; if ( defined $protocol_list && ref $protocol_list eq q() ) { $protocol_list = [$protocol_list]; } elsif ( defined $protocol_list && ref $protocol_list ne 'ARRAY' ) { croak 'ERROR: just a single scalar or an array reference are accepted'; } if ( !defined $protocol_list ) { $self->{filters}{protocols} = undef; return; } my @list; for my $option ( @{$protocol_list} ) { if ( $option !~ m{ ^(?:https?|socks[45])$ }sxm ) { croak "ERROR: '$option' is not a valid value for protocol list"; } push @list, $option; } if ( defined $protocol_list && @list == 0 ) { croak 'ERROR: Cannot set empty protocol list'; } $self->{filters}{protocols} = [ uniq @list ]; return; } =head2 set_filter_anonymity_list Set anonimity list filter. Allowed values are http, https, socks4, socks5. You can use an scalar or a list of values. By using undef you can reset the filter =cut sub set_filter_anonymity_list { my ( $self, $anonymity_list ) = @_; if ( defined $anonymity_list && ref $anonymity_list eq q() ) { $anonymity_list = [$anonymity_list]; } elsif ( defined $anonymity_list && ref $anonymity_list ne 'ARRAY' ) { croak 'ERROR: just a single scalar or an array reference are accepted'; } if ( !defined $anonymity_list ) { $self->{filters}{anonymityLevel} = undef; return; } my @list; for my $option ( @{$anonymity_list} ) { if ( $option !~ m{ ^(?:elite|anonymous|transparent)$ }sxm ) { croak "ERROR: '$option' is not a valid value for anonymity list"; } push @list, $option; } if ( defined $anonymity_list && @list == 0 ) { croak 'ERROR: Cannot set empty protocol list'; } $self->{filters}{anonymityLevel} = [ uniq @list ]; return; } =head2 set_filter_speed Set speed filter. Allowed values are: fast, medium, slow. You can use undef to reset the filter =cut sub set_filter_speed { my ( $self, $speed ) = @_; if ( defined $speed && $speed !~ m{^(?: fast|medium|slow )$}sxm ) { croak q() . "ERROR: '$speed' is not a valid value for por speed\n" . 'Valid values are: fast/slow/medium'; } $self->{filters}{speed} = $speed; return; } =head2 set_filter_org Set organization filter. Requires some non empty string. You can use undef to reset the filter =cut sub set_filter_org { my ( $self, $org ) = @_; if ( defined $org && $org eq q() ) { croak 'ERROR: Cannot set empty organization filter'; } $self->{filters}{filterByOrg} = $org; return; } =head2 set_filter_uptime Set uptime filter. Allowed values are: 0-100 in 10% increments. You can use undef to reset the filter =cut sub set_filter_uptime { my ( $self, $uptime ) = @_; if ( defined $uptime && $uptime !~ m{^(?: 0 | [1-9]0 | 100 )$}sxm ) { croak q() . "ERROR: '$uptime' is not a valid value for por uptime\n" . 'Valid values are: 0-100% in 10% increments'; } $self->{filters}{filterUpTime} = $uptime; return; } =head2 set_filter_last_checked Set last checked filter. Allowed values are: 1-9 and 20-60 in 10% increments. You can use undef to reset the filter =cut sub set_filter_last_checked { my ( $self, $last_checked ) = @_; if ( defined $last_checked && $last_checked !~ m{^(?:[1-9]|[1-6]0)$}sxm ) { croak q() . "ERROR: '$last_checked' is not a valid value for por uptime\n" . 'Valid values are: 0-100% in 10% increments'; } $self->{filters}{filterLastChecked} = $last_checked; return; } =head2 set_filter_limit Set speed filter. Allowed values are numbers greater than 0. You can use undef to reset the filter =cut sub set_filter_limit { my ( $self, $limit ) = @_; if ( defined $limit && $limit !~ m{^ (?!0)[0-9]++ $}sxm ) { croak q() . "ERROR: '$limit' is not a valid value for por speed\n" . 'Valid values are: numbers > 0'; } $self->{filters}{limit} = $limit; return; } =head2 set_env_proxy Use proxy based on environment variables See: https://metacpan.org/pod/LWP::UserAgent#env_proxy Example: $proxy_list->set_env_proxy(); =cut sub set_env_proxy { my ($self) = @_; $self->{ua}->env_proxy; return; } =head2 set_proxy Exposes LWP::UserAgent's proxy method to configure proxy server See: https://metacpan.org/pod/LWP::UserAgent#proxy Example: $proxy_list->proxy(['http', 'ftp'], 'http://proxy.sn.no:8001/'); =cut sub set_proxy { my ( $self, @params ) = @_; $self->{ua}->proxy(@params); return; } =head2 set_timeout Set petition timeout. Exposes LWP::UserAgent's timeout method See: https://metacpan.org/pod/LWP::UserAgent#timeout Example: $proxy_list->timeout(10); =cut sub set_timeout { my ( $self, @params ) = @_; $self->{ua}->timeout(@params); return; } =head2 add_proxies Add proxy list according to stored filters =cut sub add_proxies { my ($self) = @_; my $response = $self->{ua}->get( $API_ROOT . $self->_calculate_api_url ); if ( !$response->is_success ) { croak 'ERROR: Could not get url, ' . $response->status_line; } my $data = encode( 'utf-8', $response->decoded_content, sub { q() } ); $self->{proxy_list} = [ shuffle @{ $self->_create_proxy_list($data) } ]; $self->{index} = 0; return; } sub _create_proxy_list { my ( $self, $struct ) = @_; $struct = decode_json $struct; my %proxies = map { $_->id => $_ } $self->get_all_proxies; for my $item ( @{ $struct->{data} } ) { $proxies{ $item->{_id} } = Geonode::Free::Proxy->new( $item->{_id}, $item->{ip}, $item->{port}, $item->{protocols} ); } return [ values %proxies ]; } sub _calculate_api_url { my $self = shift; return join q(&), map { $self->_serialize_filter($_) } grep { defined $self->{filters}{$_} } sort keys %{ $self->{filters} }; } sub _serialize_filter { my ( $self, $filter ) = @_; my $value = $self->{filters}{$filter}; return ref $value eq 'ARRAY' ? join q(&), map { "$filter=$_" } sort @{ $value } : $filter . q(=) . $value; } =head2 get_all_proxies Return the whole proxy list =cut sub get_all_proxies { my ($self) = @_; return @{ $self->{proxy_list} }; } =head2 get_random_proxy Returns a proxy from the list at random (with repetition) =cut sub get_random_proxy { my ($self) = @_; my $rand_index = int rand @{ $self->{proxy_list} }; return $self->{proxy_list}[$rand_index]; } =head2 get_next Returns next proxy from the shuffled list (no repetition until list is exhausted) =cut sub get_next { my ($self) = @_; my $proxy = $self->{proxy_list}[ $self->{index} ]; $self->{index} = $self->{index} + 1; if ( $self->{index} > @{ $self->{proxy_list} } - 1 ) { $self->{index} = 0; } return $proxy; } =head1 AUTHOR Julio de Castro, C<< <julio.dcs at gmail.com> >> =head1 BUGS Please report any bugs or feature requests to C<bug-geonode-free-proxylist at rt.cpan.org>, or through the web interface at L<https://rt.cpan.org/NoAuth/ReportBug.html?Queue=Geonode-Free-ProxyList>. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT You can find documentation for this module with the perldoc command. perldoc Geonode::Free::ProxyList You can also look for information at: =over 4 =item * RT: CPAN's request tracker (report bugs here) L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=Geonode-Free-ProxyList> =item * CPAN Ratings L<https://cpanratings.perl.org/d/Geonode-Free-ProxyList> =item * Search CPAN L<https://metacpan.org/release/Geonode-Free-ProxyList> =back =head1 ACKNOWLEDGEMENTS =head1 LICENSE AND COPYRIGHT This software is Copyright (c) 2021 by Julio de Castro. This is free software, licensed under: The Artistic License 2.0 (GPL Compatible) =cut 1; # End of Geonode::Free::ProxyList
21.608475
157
0.612519
73edab4de56f41d7f40d4561875820d070b3988e
43,486
pm
Perl
fatlib/Date/Manip/TZ/amdaws00.pm
bokutin/RecordStream
580c0957042c5005b41056ee1dd6ae6a8d614c56
[ "Artistic-1.0" ]
142
2015-01-23T18:35:10.000Z
2022-02-02T12:07:31.000Z
fatlib/Date/Manip/TZ/amdaws00.pm
bokutin/RecordStream
580c0957042c5005b41056ee1dd6ae6a8d614c56
[ "Artistic-1.0" ]
30
2015-01-08T18:15:47.000Z
2020-06-29T18:59:40.000Z
fatlib/Date/Manip/TZ/amdaws00.pm
bokutin/RecordStream
580c0957042c5005b41056ee1dd6ae6a8d614c56
[ "Artistic-1.0" ]
15
2015-01-23T01:15:24.000Z
2021-06-16T19:14:11.000Z
package # Date::Manip::TZ::amdaws00; # Copyright (c) 2008-2014 Sullivan Beck. All rights reserved. # This program is free software; you can redistribute it and/or modify it # under the same terms as Perl itself. # This file was automatically generated. Any changes to this file will # be lost the next time 'tzdata' is run. # Generated on: Thu Aug 21 13:06:11 EDT 2014 # Data version: tzdata2014f # Code version: tzcode2014f # This module contains data from the zoneinfo time zone database. The original # data was obtained from the URL: # ftp://ftp.iana.org/tz use strict; use warnings; require 5.010000; our (%Dates,%LastRule); END { undef %Dates; undef %LastRule; } our ($VERSION); $VERSION='6.47'; END { undef $VERSION; } %Dates = ( 1 => [ [ [1,1,2,0,0,0],[1,1,1,14,42,20],'-09:17:40',[-9,-17,-40], 'LMT',0,[1900,8,20,9,17,39],[1900,8,19,23,59,59], '0001010200:00:00','0001010114:42:20','1900082009:17:39','1900081923:59:59' ], ], 1900 => [ [ [1900,8,20,9,17,40],[1900,8,20,0,17,40],'-09:00:00',[-9,0,0], 'YST',0,[1918,4,14,10,59,59],[1918,4,14,1,59,59], '1900082009:17:40','1900082000:17:40','1918041410:59:59','1918041401:59:59' ], ], 1918 => [ [ [1918,4,14,11,0,0],[1918,4,14,3,0,0],'-08:00:00',[-8,0,0], 'YDT',1,[1918,10,27,9,59,59],[1918,10,27,1,59,59], '1918041411:00:00','1918041403:00:00','1918102709:59:59','1918102701:59:59' ], [ [1918,10,27,10,0,0],[1918,10,27,1,0,0],'-09:00:00',[-9,0,0], 'YST',0,[1919,5,25,10,59,59],[1919,5,25,1,59,59], '1918102710:00:00','1918102701:00:00','1919052510:59:59','1919052501:59:59' ], ], 1919 => [ [ [1919,5,25,11,0,0],[1919,5,25,3,0,0],'-08:00:00',[-8,0,0], 'YDT',1,[1919,11,1,7,59,59],[1919,10,31,23,59,59], '1919052511:00:00','1919052503:00:00','1919110107:59:59','1919103123:59:59' ], [ [1919,11,1,8,0,0],[1919,10,31,23,0,0],'-09:00:00',[-9,0,0], 'YST',0,[1942,2,9,10,59,59],[1942,2,9,1,59,59], '1919110108:00:00','1919103123:00:00','1942020910:59:59','1942020901:59:59' ], ], 1942 => [ [ [1942,2,9,11,0,0],[1942,2,9,3,0,0],'-08:00:00',[-8,0,0], 'YWT',1,[1945,8,14,22,59,59],[1945,8,14,14,59,59], '1942020911:00:00','1942020903:00:00','1945081422:59:59','1945081414:59:59' ], ], 1945 => [ [ [1945,8,14,23,0,0],[1945,8,14,15,0,0],'-08:00:00',[-8,0,0], 'YPT',1,[1945,9,30,9,59,59],[1945,9,30,1,59,59], '1945081423:00:00','1945081415:00:00','1945093009:59:59','1945093001:59:59' ], [ [1945,9,30,10,0,0],[1945,9,30,1,0,0],'-09:00:00',[-9,0,0], 'YST',0,[1965,4,25,8,59,59],[1965,4,24,23,59,59], '1945093010:00:00','1945093001:00:00','1965042508:59:59','1965042423:59:59' ], ], 1965 => [ [ [1965,4,25,9,0,0],[1965,4,25,2,0,0],'-07:00:00',[-7,0,0], 'YDDT',1,[1965,10,31,8,59,59],[1965,10,31,1,59,59], '1965042509:00:00','1965042502:00:00','1965103108:59:59','1965103101:59:59' ], [ [1965,10,31,9,0,0],[1965,10,31,0,0,0],'-09:00:00',[-9,0,0], 'YST',0,[1973,10,28,8,59,59],[1973,10,27,23,59,59], '1965103109:00:00','1965103100:00:00','1973102808:59:59','1973102723:59:59' ], ], 1973 => [ [ [1973,10,28,9,0,0],[1973,10,28,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1980,4,27,9,59,59],[1980,4,27,1,59,59], '1973102809:00:00','1973102801:00:00','1980042709:59:59','1980042701:59:59' ], ], 1980 => [ [ [1980,4,27,10,0,0],[1980,4,27,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1980,10,26,8,59,59],[1980,10,26,1,59,59], '1980042710:00:00','1980042703:00:00','1980102608:59:59','1980102601:59:59' ], [ [1980,10,26,9,0,0],[1980,10,26,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1981,4,26,9,59,59],[1981,4,26,1,59,59], '1980102609:00:00','1980102601:00:00','1981042609:59:59','1981042601:59:59' ], ], 1981 => [ [ [1981,4,26,10,0,0],[1981,4,26,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1981,10,25,8,59,59],[1981,10,25,1,59,59], '1981042610:00:00','1981042603:00:00','1981102508:59:59','1981102501:59:59' ], [ [1981,10,25,9,0,0],[1981,10,25,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1982,4,25,9,59,59],[1982,4,25,1,59,59], '1981102509:00:00','1981102501:00:00','1982042509:59:59','1982042501:59:59' ], ], 1982 => [ [ [1982,4,25,10,0,0],[1982,4,25,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1982,10,31,8,59,59],[1982,10,31,1,59,59], '1982042510:00:00','1982042503:00:00','1982103108:59:59','1982103101:59:59' ], [ [1982,10,31,9,0,0],[1982,10,31,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1983,4,24,9,59,59],[1983,4,24,1,59,59], '1982103109:00:00','1982103101:00:00','1983042409:59:59','1983042401:59:59' ], ], 1983 => [ [ [1983,4,24,10,0,0],[1983,4,24,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1983,10,30,8,59,59],[1983,10,30,1,59,59], '1983042410:00:00','1983042403:00:00','1983103008:59:59','1983103001:59:59' ], [ [1983,10,30,9,0,0],[1983,10,30,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1984,4,29,9,59,59],[1984,4,29,1,59,59], '1983103009:00:00','1983103001:00:00','1984042909:59:59','1984042901:59:59' ], ], 1984 => [ [ [1984,4,29,10,0,0],[1984,4,29,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1984,10,28,8,59,59],[1984,10,28,1,59,59], '1984042910:00:00','1984042903:00:00','1984102808:59:59','1984102801:59:59' ], [ [1984,10,28,9,0,0],[1984,10,28,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1985,4,28,9,59,59],[1985,4,28,1,59,59], '1984102809:00:00','1984102801:00:00','1985042809:59:59','1985042801:59:59' ], ], 1985 => [ [ [1985,4,28,10,0,0],[1985,4,28,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1985,10,27,8,59,59],[1985,10,27,1,59,59], '1985042810:00:00','1985042803:00:00','1985102708:59:59','1985102701:59:59' ], [ [1985,10,27,9,0,0],[1985,10,27,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1986,4,27,9,59,59],[1986,4,27,1,59,59], '1985102709:00:00','1985102701:00:00','1986042709:59:59','1986042701:59:59' ], ], 1986 => [ [ [1986,4,27,10,0,0],[1986,4,27,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1986,10,26,8,59,59],[1986,10,26,1,59,59], '1986042710:00:00','1986042703:00:00','1986102608:59:59','1986102601:59:59' ], [ [1986,10,26,9,0,0],[1986,10,26,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1987,4,5,9,59,59],[1987,4,5,1,59,59], '1986102609:00:00','1986102601:00:00','1987040509:59:59','1987040501:59:59' ], ], 1987 => [ [ [1987,4,5,10,0,0],[1987,4,5,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1987,10,25,8,59,59],[1987,10,25,1,59,59], '1987040510:00:00','1987040503:00:00','1987102508:59:59','1987102501:59:59' ], [ [1987,10,25,9,0,0],[1987,10,25,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1988,4,3,9,59,59],[1988,4,3,1,59,59], '1987102509:00:00','1987102501:00:00','1988040309:59:59','1988040301:59:59' ], ], 1988 => [ [ [1988,4,3,10,0,0],[1988,4,3,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1988,10,30,8,59,59],[1988,10,30,1,59,59], '1988040310:00:00','1988040303:00:00','1988103008:59:59','1988103001:59:59' ], [ [1988,10,30,9,0,0],[1988,10,30,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1989,4,2,9,59,59],[1989,4,2,1,59,59], '1988103009:00:00','1988103001:00:00','1989040209:59:59','1989040201:59:59' ], ], 1989 => [ [ [1989,4,2,10,0,0],[1989,4,2,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1989,10,29,8,59,59],[1989,10,29,1,59,59], '1989040210:00:00','1989040203:00:00','1989102908:59:59','1989102901:59:59' ], [ [1989,10,29,9,0,0],[1989,10,29,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1990,4,1,9,59,59],[1990,4,1,1,59,59], '1989102909:00:00','1989102901:00:00','1990040109:59:59','1990040101:59:59' ], ], 1990 => [ [ [1990,4,1,10,0,0],[1990,4,1,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1990,10,28,8,59,59],[1990,10,28,1,59,59], '1990040110:00:00','1990040103:00:00','1990102808:59:59','1990102801:59:59' ], [ [1990,10,28,9,0,0],[1990,10,28,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1991,4,7,9,59,59],[1991,4,7,1,59,59], '1990102809:00:00','1990102801:00:00','1991040709:59:59','1991040701:59:59' ], ], 1991 => [ [ [1991,4,7,10,0,0],[1991,4,7,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1991,10,27,8,59,59],[1991,10,27,1,59,59], '1991040710:00:00','1991040703:00:00','1991102708:59:59','1991102701:59:59' ], [ [1991,10,27,9,0,0],[1991,10,27,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1992,4,5,9,59,59],[1992,4,5,1,59,59], '1991102709:00:00','1991102701:00:00','1992040509:59:59','1992040501:59:59' ], ], 1992 => [ [ [1992,4,5,10,0,0],[1992,4,5,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1992,10,25,8,59,59],[1992,10,25,1,59,59], '1992040510:00:00','1992040503:00:00','1992102508:59:59','1992102501:59:59' ], [ [1992,10,25,9,0,0],[1992,10,25,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1993,4,4,9,59,59],[1993,4,4,1,59,59], '1992102509:00:00','1992102501:00:00','1993040409:59:59','1993040401:59:59' ], ], 1993 => [ [ [1993,4,4,10,0,0],[1993,4,4,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1993,10,31,8,59,59],[1993,10,31,1,59,59], '1993040410:00:00','1993040403:00:00','1993103108:59:59','1993103101:59:59' ], [ [1993,10,31,9,0,0],[1993,10,31,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1994,4,3,9,59,59],[1994,4,3,1,59,59], '1993103109:00:00','1993103101:00:00','1994040309:59:59','1994040301:59:59' ], ], 1994 => [ [ [1994,4,3,10,0,0],[1994,4,3,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1994,10,30,8,59,59],[1994,10,30,1,59,59], '1994040310:00:00','1994040303:00:00','1994103008:59:59','1994103001:59:59' ], [ [1994,10,30,9,0,0],[1994,10,30,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1995,4,2,9,59,59],[1995,4,2,1,59,59], '1994103009:00:00','1994103001:00:00','1995040209:59:59','1995040201:59:59' ], ], 1995 => [ [ [1995,4,2,10,0,0],[1995,4,2,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1995,10,29,8,59,59],[1995,10,29,1,59,59], '1995040210:00:00','1995040203:00:00','1995102908:59:59','1995102901:59:59' ], [ [1995,10,29,9,0,0],[1995,10,29,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1996,4,7,9,59,59],[1996,4,7,1,59,59], '1995102909:00:00','1995102901:00:00','1996040709:59:59','1996040701:59:59' ], ], 1996 => [ [ [1996,4,7,10,0,0],[1996,4,7,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1996,10,27,8,59,59],[1996,10,27,1,59,59], '1996040710:00:00','1996040703:00:00','1996102708:59:59','1996102701:59:59' ], [ [1996,10,27,9,0,0],[1996,10,27,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1997,4,6,9,59,59],[1997,4,6,1,59,59], '1996102709:00:00','1996102701:00:00','1997040609:59:59','1997040601:59:59' ], ], 1997 => [ [ [1997,4,6,10,0,0],[1997,4,6,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1997,10,26,8,59,59],[1997,10,26,1,59,59], '1997040610:00:00','1997040603:00:00','1997102608:59:59','1997102601:59:59' ], [ [1997,10,26,9,0,0],[1997,10,26,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1998,4,5,9,59,59],[1998,4,5,1,59,59], '1997102609:00:00','1997102601:00:00','1998040509:59:59','1998040501:59:59' ], ], 1998 => [ [ [1998,4,5,10,0,0],[1998,4,5,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1998,10,25,8,59,59],[1998,10,25,1,59,59], '1998040510:00:00','1998040503:00:00','1998102508:59:59','1998102501:59:59' ], [ [1998,10,25,9,0,0],[1998,10,25,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[1999,4,4,9,59,59],[1999,4,4,1,59,59], '1998102509:00:00','1998102501:00:00','1999040409:59:59','1999040401:59:59' ], ], 1999 => [ [ [1999,4,4,10,0,0],[1999,4,4,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[1999,10,31,8,59,59],[1999,10,31,1,59,59], '1999040410:00:00','1999040403:00:00','1999103108:59:59','1999103101:59:59' ], [ [1999,10,31,9,0,0],[1999,10,31,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2000,4,2,9,59,59],[2000,4,2,1,59,59], '1999103109:00:00','1999103101:00:00','2000040209:59:59','2000040201:59:59' ], ], 2000 => [ [ [2000,4,2,10,0,0],[2000,4,2,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2000,10,29,8,59,59],[2000,10,29,1,59,59], '2000040210:00:00','2000040203:00:00','2000102908:59:59','2000102901:59:59' ], [ [2000,10,29,9,0,0],[2000,10,29,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2001,4,1,9,59,59],[2001,4,1,1,59,59], '2000102909:00:00','2000102901:00:00','2001040109:59:59','2001040101:59:59' ], ], 2001 => [ [ [2001,4,1,10,0,0],[2001,4,1,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2001,10,28,8,59,59],[2001,10,28,1,59,59], '2001040110:00:00','2001040103:00:00','2001102808:59:59','2001102801:59:59' ], [ [2001,10,28,9,0,0],[2001,10,28,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2002,4,7,9,59,59],[2002,4,7,1,59,59], '2001102809:00:00','2001102801:00:00','2002040709:59:59','2002040701:59:59' ], ], 2002 => [ [ [2002,4,7,10,0,0],[2002,4,7,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2002,10,27,8,59,59],[2002,10,27,1,59,59], '2002040710:00:00','2002040703:00:00','2002102708:59:59','2002102701:59:59' ], [ [2002,10,27,9,0,0],[2002,10,27,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2003,4,6,9,59,59],[2003,4,6,1,59,59], '2002102709:00:00','2002102701:00:00','2003040609:59:59','2003040601:59:59' ], ], 2003 => [ [ [2003,4,6,10,0,0],[2003,4,6,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2003,10,26,8,59,59],[2003,10,26,1,59,59], '2003040610:00:00','2003040603:00:00','2003102608:59:59','2003102601:59:59' ], [ [2003,10,26,9,0,0],[2003,10,26,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2004,4,4,9,59,59],[2004,4,4,1,59,59], '2003102609:00:00','2003102601:00:00','2004040409:59:59','2004040401:59:59' ], ], 2004 => [ [ [2004,4,4,10,0,0],[2004,4,4,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2004,10,31,8,59,59],[2004,10,31,1,59,59], '2004040410:00:00','2004040403:00:00','2004103108:59:59','2004103101:59:59' ], [ [2004,10,31,9,0,0],[2004,10,31,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2005,4,3,9,59,59],[2005,4,3,1,59,59], '2004103109:00:00','2004103101:00:00','2005040309:59:59','2005040301:59:59' ], ], 2005 => [ [ [2005,4,3,10,0,0],[2005,4,3,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2005,10,30,8,59,59],[2005,10,30,1,59,59], '2005040310:00:00','2005040303:00:00','2005103008:59:59','2005103001:59:59' ], [ [2005,10,30,9,0,0],[2005,10,30,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2006,4,2,9,59,59],[2006,4,2,1,59,59], '2005103009:00:00','2005103001:00:00','2006040209:59:59','2006040201:59:59' ], ], 2006 => [ [ [2006,4,2,10,0,0],[2006,4,2,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2006,10,29,8,59,59],[2006,10,29,1,59,59], '2006040210:00:00','2006040203:00:00','2006102908:59:59','2006102901:59:59' ], [ [2006,10,29,9,0,0],[2006,10,29,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2007,3,11,9,59,59],[2007,3,11,1,59,59], '2006102909:00:00','2006102901:00:00','2007031109:59:59','2007031101:59:59' ], ], 2007 => [ [ [2007,3,11,10,0,0],[2007,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2007,11,4,8,59,59],[2007,11,4,1,59,59], '2007031110:00:00','2007031103:00:00','2007110408:59:59','2007110401:59:59' ], [ [2007,11,4,9,0,0],[2007,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2008,3,9,9,59,59],[2008,3,9,1,59,59], '2007110409:00:00','2007110401:00:00','2008030909:59:59','2008030901:59:59' ], ], 2008 => [ [ [2008,3,9,10,0,0],[2008,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2008,11,2,8,59,59],[2008,11,2,1,59,59], '2008030910:00:00','2008030903:00:00','2008110208:59:59','2008110201:59:59' ], [ [2008,11,2,9,0,0],[2008,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2009,3,8,9,59,59],[2009,3,8,1,59,59], '2008110209:00:00','2008110201:00:00','2009030809:59:59','2009030801:59:59' ], ], 2009 => [ [ [2009,3,8,10,0,0],[2009,3,8,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2009,11,1,8,59,59],[2009,11,1,1,59,59], '2009030810:00:00','2009030803:00:00','2009110108:59:59','2009110101:59:59' ], [ [2009,11,1,9,0,0],[2009,11,1,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2010,3,14,9,59,59],[2010,3,14,1,59,59], '2009110109:00:00','2009110101:00:00','2010031409:59:59','2010031401:59:59' ], ], 2010 => [ [ [2010,3,14,10,0,0],[2010,3,14,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2010,11,7,8,59,59],[2010,11,7,1,59,59], '2010031410:00:00','2010031403:00:00','2010110708:59:59','2010110701:59:59' ], [ [2010,11,7,9,0,0],[2010,11,7,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2011,3,13,9,59,59],[2011,3,13,1,59,59], '2010110709:00:00','2010110701:00:00','2011031309:59:59','2011031301:59:59' ], ], 2011 => [ [ [2011,3,13,10,0,0],[2011,3,13,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2011,11,6,8,59,59],[2011,11,6,1,59,59], '2011031310:00:00','2011031303:00:00','2011110608:59:59','2011110601:59:59' ], [ [2011,11,6,9,0,0],[2011,11,6,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2012,3,11,9,59,59],[2012,3,11,1,59,59], '2011110609:00:00','2011110601:00:00','2012031109:59:59','2012031101:59:59' ], ], 2012 => [ [ [2012,3,11,10,0,0],[2012,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2012,11,4,8,59,59],[2012,11,4,1,59,59], '2012031110:00:00','2012031103:00:00','2012110408:59:59','2012110401:59:59' ], [ [2012,11,4,9,0,0],[2012,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2013,3,10,9,59,59],[2013,3,10,1,59,59], '2012110409:00:00','2012110401:00:00','2013031009:59:59','2013031001:59:59' ], ], 2013 => [ [ [2013,3,10,10,0,0],[2013,3,10,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2013,11,3,8,59,59],[2013,11,3,1,59,59], '2013031010:00:00','2013031003:00:00','2013110308:59:59','2013110301:59:59' ], [ [2013,11,3,9,0,0],[2013,11,3,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2014,3,9,9,59,59],[2014,3,9,1,59,59], '2013110309:00:00','2013110301:00:00','2014030909:59:59','2014030901:59:59' ], ], 2014 => [ [ [2014,3,9,10,0,0],[2014,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2014,11,2,8,59,59],[2014,11,2,1,59,59], '2014030910:00:00','2014030903:00:00','2014110208:59:59','2014110201:59:59' ], [ [2014,11,2,9,0,0],[2014,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2015,3,8,9,59,59],[2015,3,8,1,59,59], '2014110209:00:00','2014110201:00:00','2015030809:59:59','2015030801:59:59' ], ], 2015 => [ [ [2015,3,8,10,0,0],[2015,3,8,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2015,11,1,8,59,59],[2015,11,1,1,59,59], '2015030810:00:00','2015030803:00:00','2015110108:59:59','2015110101:59:59' ], [ [2015,11,1,9,0,0],[2015,11,1,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2016,3,13,9,59,59],[2016,3,13,1,59,59], '2015110109:00:00','2015110101:00:00','2016031309:59:59','2016031301:59:59' ], ], 2016 => [ [ [2016,3,13,10,0,0],[2016,3,13,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2016,11,6,8,59,59],[2016,11,6,1,59,59], '2016031310:00:00','2016031303:00:00','2016110608:59:59','2016110601:59:59' ], [ [2016,11,6,9,0,0],[2016,11,6,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2017,3,12,9,59,59],[2017,3,12,1,59,59], '2016110609:00:00','2016110601:00:00','2017031209:59:59','2017031201:59:59' ], ], 2017 => [ [ [2017,3,12,10,0,0],[2017,3,12,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2017,11,5,8,59,59],[2017,11,5,1,59,59], '2017031210:00:00','2017031203:00:00','2017110508:59:59','2017110501:59:59' ], [ [2017,11,5,9,0,0],[2017,11,5,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2018,3,11,9,59,59],[2018,3,11,1,59,59], '2017110509:00:00','2017110501:00:00','2018031109:59:59','2018031101:59:59' ], ], 2018 => [ [ [2018,3,11,10,0,0],[2018,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2018,11,4,8,59,59],[2018,11,4,1,59,59], '2018031110:00:00','2018031103:00:00','2018110408:59:59','2018110401:59:59' ], [ [2018,11,4,9,0,0],[2018,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2019,3,10,9,59,59],[2019,3,10,1,59,59], '2018110409:00:00','2018110401:00:00','2019031009:59:59','2019031001:59:59' ], ], 2019 => [ [ [2019,3,10,10,0,0],[2019,3,10,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2019,11,3,8,59,59],[2019,11,3,1,59,59], '2019031010:00:00','2019031003:00:00','2019110308:59:59','2019110301:59:59' ], [ [2019,11,3,9,0,0],[2019,11,3,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2020,3,8,9,59,59],[2020,3,8,1,59,59], '2019110309:00:00','2019110301:00:00','2020030809:59:59','2020030801:59:59' ], ], 2020 => [ [ [2020,3,8,10,0,0],[2020,3,8,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2020,11,1,8,59,59],[2020,11,1,1,59,59], '2020030810:00:00','2020030803:00:00','2020110108:59:59','2020110101:59:59' ], [ [2020,11,1,9,0,0],[2020,11,1,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2021,3,14,9,59,59],[2021,3,14,1,59,59], '2020110109:00:00','2020110101:00:00','2021031409:59:59','2021031401:59:59' ], ], 2021 => [ [ [2021,3,14,10,0,0],[2021,3,14,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2021,11,7,8,59,59],[2021,11,7,1,59,59], '2021031410:00:00','2021031403:00:00','2021110708:59:59','2021110701:59:59' ], [ [2021,11,7,9,0,0],[2021,11,7,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2022,3,13,9,59,59],[2022,3,13,1,59,59], '2021110709:00:00','2021110701:00:00','2022031309:59:59','2022031301:59:59' ], ], 2022 => [ [ [2022,3,13,10,0,0],[2022,3,13,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2022,11,6,8,59,59],[2022,11,6,1,59,59], '2022031310:00:00','2022031303:00:00','2022110608:59:59','2022110601:59:59' ], [ [2022,11,6,9,0,0],[2022,11,6,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2023,3,12,9,59,59],[2023,3,12,1,59,59], '2022110609:00:00','2022110601:00:00','2023031209:59:59','2023031201:59:59' ], ], 2023 => [ [ [2023,3,12,10,0,0],[2023,3,12,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2023,11,5,8,59,59],[2023,11,5,1,59,59], '2023031210:00:00','2023031203:00:00','2023110508:59:59','2023110501:59:59' ], [ [2023,11,5,9,0,0],[2023,11,5,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2024,3,10,9,59,59],[2024,3,10,1,59,59], '2023110509:00:00','2023110501:00:00','2024031009:59:59','2024031001:59:59' ], ], 2024 => [ [ [2024,3,10,10,0,0],[2024,3,10,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2024,11,3,8,59,59],[2024,11,3,1,59,59], '2024031010:00:00','2024031003:00:00','2024110308:59:59','2024110301:59:59' ], [ [2024,11,3,9,0,0],[2024,11,3,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2025,3,9,9,59,59],[2025,3,9,1,59,59], '2024110309:00:00','2024110301:00:00','2025030909:59:59','2025030901:59:59' ], ], 2025 => [ [ [2025,3,9,10,0,0],[2025,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2025,11,2,8,59,59],[2025,11,2,1,59,59], '2025030910:00:00','2025030903:00:00','2025110208:59:59','2025110201:59:59' ], [ [2025,11,2,9,0,0],[2025,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2026,3,8,9,59,59],[2026,3,8,1,59,59], '2025110209:00:00','2025110201:00:00','2026030809:59:59','2026030801:59:59' ], ], 2026 => [ [ [2026,3,8,10,0,0],[2026,3,8,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2026,11,1,8,59,59],[2026,11,1,1,59,59], '2026030810:00:00','2026030803:00:00','2026110108:59:59','2026110101:59:59' ], [ [2026,11,1,9,0,0],[2026,11,1,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2027,3,14,9,59,59],[2027,3,14,1,59,59], '2026110109:00:00','2026110101:00:00','2027031409:59:59','2027031401:59:59' ], ], 2027 => [ [ [2027,3,14,10,0,0],[2027,3,14,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2027,11,7,8,59,59],[2027,11,7,1,59,59], '2027031410:00:00','2027031403:00:00','2027110708:59:59','2027110701:59:59' ], [ [2027,11,7,9,0,0],[2027,11,7,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2028,3,12,9,59,59],[2028,3,12,1,59,59], '2027110709:00:00','2027110701:00:00','2028031209:59:59','2028031201:59:59' ], ], 2028 => [ [ [2028,3,12,10,0,0],[2028,3,12,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2028,11,5,8,59,59],[2028,11,5,1,59,59], '2028031210:00:00','2028031203:00:00','2028110508:59:59','2028110501:59:59' ], [ [2028,11,5,9,0,0],[2028,11,5,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2029,3,11,9,59,59],[2029,3,11,1,59,59], '2028110509:00:00','2028110501:00:00','2029031109:59:59','2029031101:59:59' ], ], 2029 => [ [ [2029,3,11,10,0,0],[2029,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2029,11,4,8,59,59],[2029,11,4,1,59,59], '2029031110:00:00','2029031103:00:00','2029110408:59:59','2029110401:59:59' ], [ [2029,11,4,9,0,0],[2029,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2030,3,10,9,59,59],[2030,3,10,1,59,59], '2029110409:00:00','2029110401:00:00','2030031009:59:59','2030031001:59:59' ], ], 2030 => [ [ [2030,3,10,10,0,0],[2030,3,10,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2030,11,3,8,59,59],[2030,11,3,1,59,59], '2030031010:00:00','2030031003:00:00','2030110308:59:59','2030110301:59:59' ], [ [2030,11,3,9,0,0],[2030,11,3,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2031,3,9,9,59,59],[2031,3,9,1,59,59], '2030110309:00:00','2030110301:00:00','2031030909:59:59','2031030901:59:59' ], ], 2031 => [ [ [2031,3,9,10,0,0],[2031,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2031,11,2,8,59,59],[2031,11,2,1,59,59], '2031030910:00:00','2031030903:00:00','2031110208:59:59','2031110201:59:59' ], [ [2031,11,2,9,0,0],[2031,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2032,3,14,9,59,59],[2032,3,14,1,59,59], '2031110209:00:00','2031110201:00:00','2032031409:59:59','2032031401:59:59' ], ], 2032 => [ [ [2032,3,14,10,0,0],[2032,3,14,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2032,11,7,8,59,59],[2032,11,7,1,59,59], '2032031410:00:00','2032031403:00:00','2032110708:59:59','2032110701:59:59' ], [ [2032,11,7,9,0,0],[2032,11,7,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2033,3,13,9,59,59],[2033,3,13,1,59,59], '2032110709:00:00','2032110701:00:00','2033031309:59:59','2033031301:59:59' ], ], 2033 => [ [ [2033,3,13,10,0,0],[2033,3,13,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2033,11,6,8,59,59],[2033,11,6,1,59,59], '2033031310:00:00','2033031303:00:00','2033110608:59:59','2033110601:59:59' ], [ [2033,11,6,9,0,0],[2033,11,6,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2034,3,12,9,59,59],[2034,3,12,1,59,59], '2033110609:00:00','2033110601:00:00','2034031209:59:59','2034031201:59:59' ], ], 2034 => [ [ [2034,3,12,10,0,0],[2034,3,12,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2034,11,5,8,59,59],[2034,11,5,1,59,59], '2034031210:00:00','2034031203:00:00','2034110508:59:59','2034110501:59:59' ], [ [2034,11,5,9,0,0],[2034,11,5,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2035,3,11,9,59,59],[2035,3,11,1,59,59], '2034110509:00:00','2034110501:00:00','2035031109:59:59','2035031101:59:59' ], ], 2035 => [ [ [2035,3,11,10,0,0],[2035,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2035,11,4,8,59,59],[2035,11,4,1,59,59], '2035031110:00:00','2035031103:00:00','2035110408:59:59','2035110401:59:59' ], [ [2035,11,4,9,0,0],[2035,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2036,3,9,9,59,59],[2036,3,9,1,59,59], '2035110409:00:00','2035110401:00:00','2036030909:59:59','2036030901:59:59' ], ], 2036 => [ [ [2036,3,9,10,0,0],[2036,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2036,11,2,8,59,59],[2036,11,2,1,59,59], '2036030910:00:00','2036030903:00:00','2036110208:59:59','2036110201:59:59' ], [ [2036,11,2,9,0,0],[2036,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2037,3,8,9,59,59],[2037,3,8,1,59,59], '2036110209:00:00','2036110201:00:00','2037030809:59:59','2037030801:59:59' ], ], 2037 => [ [ [2037,3,8,10,0,0],[2037,3,8,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2037,11,1,8,59,59],[2037,11,1,1,59,59], '2037030810:00:00','2037030803:00:00','2037110108:59:59','2037110101:59:59' ], [ [2037,11,1,9,0,0],[2037,11,1,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2038,3,14,9,59,59],[2038,3,14,1,59,59], '2037110109:00:00','2037110101:00:00','2038031409:59:59','2038031401:59:59' ], ], 2038 => [ [ [2038,3,14,10,0,0],[2038,3,14,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2038,11,7,8,59,59],[2038,11,7,1,59,59], '2038031410:00:00','2038031403:00:00','2038110708:59:59','2038110701:59:59' ], [ [2038,11,7,9,0,0],[2038,11,7,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2039,3,13,9,59,59],[2039,3,13,1,59,59], '2038110709:00:00','2038110701:00:00','2039031309:59:59','2039031301:59:59' ], ], 2039 => [ [ [2039,3,13,10,0,0],[2039,3,13,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2039,11,6,8,59,59],[2039,11,6,1,59,59], '2039031310:00:00','2039031303:00:00','2039110608:59:59','2039110601:59:59' ], [ [2039,11,6,9,0,0],[2039,11,6,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2040,3,11,9,59,59],[2040,3,11,1,59,59], '2039110609:00:00','2039110601:00:00','2040031109:59:59','2040031101:59:59' ], ], 2040 => [ [ [2040,3,11,10,0,0],[2040,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2040,11,4,8,59,59],[2040,11,4,1,59,59], '2040031110:00:00','2040031103:00:00','2040110408:59:59','2040110401:59:59' ], [ [2040,11,4,9,0,0],[2040,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2041,3,10,9,59,59],[2041,3,10,1,59,59], '2040110409:00:00','2040110401:00:00','2041031009:59:59','2041031001:59:59' ], ], 2041 => [ [ [2041,3,10,10,0,0],[2041,3,10,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2041,11,3,8,59,59],[2041,11,3,1,59,59], '2041031010:00:00','2041031003:00:00','2041110308:59:59','2041110301:59:59' ], [ [2041,11,3,9,0,0],[2041,11,3,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2042,3,9,9,59,59],[2042,3,9,1,59,59], '2041110309:00:00','2041110301:00:00','2042030909:59:59','2042030901:59:59' ], ], 2042 => [ [ [2042,3,9,10,0,0],[2042,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2042,11,2,8,59,59],[2042,11,2,1,59,59], '2042030910:00:00','2042030903:00:00','2042110208:59:59','2042110201:59:59' ], [ [2042,11,2,9,0,0],[2042,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2043,3,8,9,59,59],[2043,3,8,1,59,59], '2042110209:00:00','2042110201:00:00','2043030809:59:59','2043030801:59:59' ], ], 2043 => [ [ [2043,3,8,10,0,0],[2043,3,8,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2043,11,1,8,59,59],[2043,11,1,1,59,59], '2043030810:00:00','2043030803:00:00','2043110108:59:59','2043110101:59:59' ], [ [2043,11,1,9,0,0],[2043,11,1,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2044,3,13,9,59,59],[2044,3,13,1,59,59], '2043110109:00:00','2043110101:00:00','2044031309:59:59','2044031301:59:59' ], ], 2044 => [ [ [2044,3,13,10,0,0],[2044,3,13,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2044,11,6,8,59,59],[2044,11,6,1,59,59], '2044031310:00:00','2044031303:00:00','2044110608:59:59','2044110601:59:59' ], [ [2044,11,6,9,0,0],[2044,11,6,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2045,3,12,9,59,59],[2045,3,12,1,59,59], '2044110609:00:00','2044110601:00:00','2045031209:59:59','2045031201:59:59' ], ], 2045 => [ [ [2045,3,12,10,0,0],[2045,3,12,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2045,11,5,8,59,59],[2045,11,5,1,59,59], '2045031210:00:00','2045031203:00:00','2045110508:59:59','2045110501:59:59' ], [ [2045,11,5,9,0,0],[2045,11,5,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2046,3,11,9,59,59],[2046,3,11,1,59,59], '2045110509:00:00','2045110501:00:00','2046031109:59:59','2046031101:59:59' ], ], 2046 => [ [ [2046,3,11,10,0,0],[2046,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2046,11,4,8,59,59],[2046,11,4,1,59,59], '2046031110:00:00','2046031103:00:00','2046110408:59:59','2046110401:59:59' ], [ [2046,11,4,9,0,0],[2046,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2047,3,10,9,59,59],[2047,3,10,1,59,59], '2046110409:00:00','2046110401:00:00','2047031009:59:59','2047031001:59:59' ], ], 2047 => [ [ [2047,3,10,10,0,0],[2047,3,10,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2047,11,3,8,59,59],[2047,11,3,1,59,59], '2047031010:00:00','2047031003:00:00','2047110308:59:59','2047110301:59:59' ], [ [2047,11,3,9,0,0],[2047,11,3,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2048,3,8,9,59,59],[2048,3,8,1,59,59], '2047110309:00:00','2047110301:00:00','2048030809:59:59','2048030801:59:59' ], ], 2048 => [ [ [2048,3,8,10,0,0],[2048,3,8,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2048,11,1,8,59,59],[2048,11,1,1,59,59], '2048030810:00:00','2048030803:00:00','2048110108:59:59','2048110101:59:59' ], [ [2048,11,1,9,0,0],[2048,11,1,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2049,3,14,9,59,59],[2049,3,14,1,59,59], '2048110109:00:00','2048110101:00:00','2049031409:59:59','2049031401:59:59' ], ], 2049 => [ [ [2049,3,14,10,0,0],[2049,3,14,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2049,11,7,8,59,59],[2049,11,7,1,59,59], '2049031410:00:00','2049031403:00:00','2049110708:59:59','2049110701:59:59' ], [ [2049,11,7,9,0,0],[2049,11,7,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2050,3,13,9,59,59],[2050,3,13,1,59,59], '2049110709:00:00','2049110701:00:00','2050031309:59:59','2050031301:59:59' ], ], 2050 => [ [ [2050,3,13,10,0,0],[2050,3,13,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2050,11,6,8,59,59],[2050,11,6,1,59,59], '2050031310:00:00','2050031303:00:00','2050110608:59:59','2050110601:59:59' ], [ [2050,11,6,9,0,0],[2050,11,6,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2051,3,12,9,59,59],[2051,3,12,1,59,59], '2050110609:00:00','2050110601:00:00','2051031209:59:59','2051031201:59:59' ], ], 2051 => [ [ [2051,3,12,10,0,0],[2051,3,12,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2051,11,5,8,59,59],[2051,11,5,1,59,59], '2051031210:00:00','2051031203:00:00','2051110508:59:59','2051110501:59:59' ], [ [2051,11,5,9,0,0],[2051,11,5,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2052,3,10,9,59,59],[2052,3,10,1,59,59], '2051110509:00:00','2051110501:00:00','2052031009:59:59','2052031001:59:59' ], ], 2052 => [ [ [2052,3,10,10,0,0],[2052,3,10,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2052,11,3,8,59,59],[2052,11,3,1,59,59], '2052031010:00:00','2052031003:00:00','2052110308:59:59','2052110301:59:59' ], [ [2052,11,3,9,0,0],[2052,11,3,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2053,3,9,9,59,59],[2053,3,9,1,59,59], '2052110309:00:00','2052110301:00:00','2053030909:59:59','2053030901:59:59' ], ], 2053 => [ [ [2053,3,9,10,0,0],[2053,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2053,11,2,8,59,59],[2053,11,2,1,59,59], '2053030910:00:00','2053030903:00:00','2053110208:59:59','2053110201:59:59' ], [ [2053,11,2,9,0,0],[2053,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2054,3,8,9,59,59],[2054,3,8,1,59,59], '2053110209:00:00','2053110201:00:00','2054030809:59:59','2054030801:59:59' ], ], 2054 => [ [ [2054,3,8,10,0,0],[2054,3,8,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2054,11,1,8,59,59],[2054,11,1,1,59,59], '2054030810:00:00','2054030803:00:00','2054110108:59:59','2054110101:59:59' ], [ [2054,11,1,9,0,0],[2054,11,1,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2055,3,14,9,59,59],[2055,3,14,1,59,59], '2054110109:00:00','2054110101:00:00','2055031409:59:59','2055031401:59:59' ], ], 2055 => [ [ [2055,3,14,10,0,0],[2055,3,14,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2055,11,7,8,59,59],[2055,11,7,1,59,59], '2055031410:00:00','2055031403:00:00','2055110708:59:59','2055110701:59:59' ], [ [2055,11,7,9,0,0],[2055,11,7,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2056,3,12,9,59,59],[2056,3,12,1,59,59], '2055110709:00:00','2055110701:00:00','2056031209:59:59','2056031201:59:59' ], ], 2056 => [ [ [2056,3,12,10,0,0],[2056,3,12,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2056,11,5,8,59,59],[2056,11,5,1,59,59], '2056031210:00:00','2056031203:00:00','2056110508:59:59','2056110501:59:59' ], [ [2056,11,5,9,0,0],[2056,11,5,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2057,3,11,9,59,59],[2057,3,11,1,59,59], '2056110509:00:00','2056110501:00:00','2057031109:59:59','2057031101:59:59' ], ], 2057 => [ [ [2057,3,11,10,0,0],[2057,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2057,11,4,8,59,59],[2057,11,4,1,59,59], '2057031110:00:00','2057031103:00:00','2057110408:59:59','2057110401:59:59' ], [ [2057,11,4,9,0,0],[2057,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2058,3,10,9,59,59],[2058,3,10,1,59,59], '2057110409:00:00','2057110401:00:00','2058031009:59:59','2058031001:59:59' ], ], 2058 => [ [ [2058,3,10,10,0,0],[2058,3,10,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2058,11,3,8,59,59],[2058,11,3,1,59,59], '2058031010:00:00','2058031003:00:00','2058110308:59:59','2058110301:59:59' ], [ [2058,11,3,9,0,0],[2058,11,3,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2059,3,9,9,59,59],[2059,3,9,1,59,59], '2058110309:00:00','2058110301:00:00','2059030909:59:59','2059030901:59:59' ], ], 2059 => [ [ [2059,3,9,10,0,0],[2059,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2059,11,2,8,59,59],[2059,11,2,1,59,59], '2059030910:00:00','2059030903:00:00','2059110208:59:59','2059110201:59:59' ], [ [2059,11,2,9,0,0],[2059,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2060,3,14,9,59,59],[2060,3,14,1,59,59], '2059110209:00:00','2059110201:00:00','2060031409:59:59','2060031401:59:59' ], ], 2060 => [ [ [2060,3,14,10,0,0],[2060,3,14,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2060,11,7,8,59,59],[2060,11,7,1,59,59], '2060031410:00:00','2060031403:00:00','2060110708:59:59','2060110701:59:59' ], [ [2060,11,7,9,0,0],[2060,11,7,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2061,3,13,9,59,59],[2061,3,13,1,59,59], '2060110709:00:00','2060110701:00:00','2061031309:59:59','2061031301:59:59' ], ], 2061 => [ [ [2061,3,13,10,0,0],[2061,3,13,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2061,11,6,8,59,59],[2061,11,6,1,59,59], '2061031310:00:00','2061031303:00:00','2061110608:59:59','2061110601:59:59' ], [ [2061,11,6,9,0,0],[2061,11,6,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2062,3,12,9,59,59],[2062,3,12,1,59,59], '2061110609:00:00','2061110601:00:00','2062031209:59:59','2062031201:59:59' ], ], 2062 => [ [ [2062,3,12,10,0,0],[2062,3,12,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2062,11,5,8,59,59],[2062,11,5,1,59,59], '2062031210:00:00','2062031203:00:00','2062110508:59:59','2062110501:59:59' ], [ [2062,11,5,9,0,0],[2062,11,5,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2063,3,11,9,59,59],[2063,3,11,1,59,59], '2062110509:00:00','2062110501:00:00','2063031109:59:59','2063031101:59:59' ], ], 2063 => [ [ [2063,3,11,10,0,0],[2063,3,11,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2063,11,4,8,59,59],[2063,11,4,1,59,59], '2063031110:00:00','2063031103:00:00','2063110408:59:59','2063110401:59:59' ], [ [2063,11,4,9,0,0],[2063,11,4,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2064,3,9,9,59,59],[2064,3,9,1,59,59], '2063110409:00:00','2063110401:00:00','2064030909:59:59','2064030901:59:59' ], ], 2064 => [ [ [2064,3,9,10,0,0],[2064,3,9,3,0,0],'-07:00:00',[-7,0,0], 'PDT',1,[2064,11,2,8,59,59],[2064,11,2,1,59,59], '2064030910:00:00','2064030903:00:00','2064110208:59:59','2064110201:59:59' ], [ [2064,11,2,9,0,0],[2064,11,2,1,0,0],'-08:00:00',[-8,0,0], 'PST',0,[2065,3,8,9,59,59],[2065,3,8,1,59,59], '2064110209:00:00','2064110201:00:00','2065030809:59:59','2065030801:59:59' ], ], ); %LastRule = ( 'zone' => { 'dstoff' => '-07:00:00', 'stdoff' => '-08:00:00', }, 'rules' => { '03' => { 'flag' => 'ge', 'dow' => '7', 'num' => '8', 'type' => 'w', 'time' => '02:00:00', 'isdst' => '1', 'abb' => 'PDT', }, '11' => { 'flag' => 'ge', 'dow' => '7', 'num' => '1', 'type' => 'w', 'time' => '02:00:00', 'isdst' => '0', 'abb' => 'PST', }, }, ); 1;
49.02593
88
0.498459
73f479747ded904acb2a875ed00f4e2e06f89433
249
pl
Perl
Examples/Programs/pascals_triangle.pl
geoorge1d127/ProFL
adfd64cbf93c28bdb0f7979d6a7dec98cdb2deec
[ "MIT" ]
5
2020-07-20T20:43:56.000Z
2021-07-06T07:42:57.000Z
Examples/Programs/pascals_triangle.pl
geoorge1d127/ProFL
adfd64cbf93c28bdb0f7979d6a7dec98cdb2deec
[ "MIT" ]
null
null
null
Examples/Programs/pascals_triangle.pl
geoorge1d127/ProFL
adfd64cbf93c28bdb0f7979d6a7dec98cdb2deec
[ "MIT" ]
null
null
null
pascal(0, []) :- !. pascal(X, P) :- numlist(1, X, NL), maplist(pascalH, NL, P). pascalH(1, [1]) :- !. pascalH(N, [X|L]) :- succ(N1, N), pascalH(N1, [X|L1]), build([X|L1], L), !. build([X], [X]). build([X,Y|Z], [H|R]) :- H is X-Y, build([Y|Z], R).
41.5
75
0.481928
ed1f26a4ef2b5c8305d82ab06bf72d88360691d9
348
pm
Perl
lib/App/perlimports/Role/Logger.pm
nicomen/App-perlimports
e5d275604486fb9b304b31de963c2a6aa6815eea
[ "Artistic-1.0" ]
null
null
null
lib/App/perlimports/Role/Logger.pm
nicomen/App-perlimports
e5d275604486fb9b304b31de963c2a6aa6815eea
[ "Artistic-1.0" ]
null
null
null
lib/App/perlimports/Role/Logger.pm
nicomen/App-perlimports
e5d275604486fb9b304b31de963c2a6aa6815eea
[ "Artistic-1.0" ]
null
null
null
package App::perlimports::Role::Logger; use Moo::Role; our $VERSION = '0.000028'; use Types::Standard qw( InstanceOf ); has logger => ( is => 'ro', isa => InstanceOf ['Log::Dispatch'], predicate => '_has_logger', writer => 'set_logger', ); 1; # ABSTRACT: Provide a logger attribute to App::perlimports objects
18.315789
66
0.614943
ed1086aaa180c3bb76964058110d0a62a3cd9626
825
pm
Perl
lib/TauHead/Controller/Vendor/List.pm
taustation-fan/tauhead-server
00802b51529d8043358a3e4dec9420314e48db19
[ "MIT" ]
1
2019-02-06T22:20:29.000Z
2019-02-06T22:20:29.000Z
lib/TauHead/Controller/Vendor/List.pm
taustation-fan/tauhead-server
00802b51529d8043358a3e4dec9420314e48db19
[ "MIT" ]
1
2018-10-25T21:58:42.000Z
2018-10-25T21:58:42.000Z
lib/TauHead/Controller/Vendor/List.pm
taustation-fan/tauhead-server
00802b51529d8043358a3e4dec9420314e48db19
[ "MIT" ]
null
null
null
package TauHead::Controller::Vendor::List; use Moose; use namespace::autoclean; BEGIN { extends 'TauHead::BaseController' } sub list : Path('/vendor/list') : Args(0) { my ( $self, $c ) = @_; my $model = $c->model('DB'); $c->stash->{areas} = $model->resultset('Area')->search( { 'vendors.id' => { '!=' => undef }, }, { join => 'vendors', prefetch => [ { station => 'system' }, 'parent_area', ], order_by => [ 'system.sort_order', 'system.slug', 'station.sort_order', 'station.slug', 'me.sort_order', 'me.slug', ], } ); return; } __PACKAGE__->meta->make_immutable; 1;
21.153846
59
0.427879