EKON 29

Statistic Packages for Delphi and Python

A truly cross-platform library for numerical analysis and statistical functions isn’t easy to find in Delphi. Especially since quality and licensing are also important. In this session, we’ll delve into the most useful packages and libraries suitable for performing statistical calculations, all the way up to advanced modeling and data visualization. We’ll also compile a statistics on the top and flops of Delphi projects over the past 30 years.

https://entwickler-konferenz.de/delphi-innovations-fundamentals/statistic-packages-fuer-delphi-oder-python

Hands-On

  • Setting up the mrMath and mrMatrix mrAI toolchain
  • Open AI for Delphi Demo
  • Calculating DMath correlations, pattern recognition, and trends
  • Introducing the 7 well-known statistical methods
  • Demonstrating the 5 most important chart types (Bar Chart, Scatter Plot,
    Histogram, Box Plot and Correlationmatrix)
  • Setting up an energy storage time series AGSI project statistics
  • Descriptive statistics with the reference dataset for morale statistics (Guerry, “HistData”)
  • Data Science Tutorial AGSI or Guerry

Contents

  • Overview of the statistical packages with Delphi and Python (P4D).
  • Configuration and spec features of DMath, SKLearn, Statsmodels, & DataLab library
  • Troubleshooting: Typical miscalculations and their solutions with cleaned data
  • First steps in implementing regression, cluster analysis, and correlation matrix

We download the Guerry dataset, a collection of historical data used in support of 
Andre-Michel Guerry’s 1833 Essay on the Moral Statistics of France. The data set is hosted 
online in comma-separated values format (CSV) by the Rdatasets repository. We could download the file 
locally and then load it using read_csv, but pandas takes care of all of this automatically for us:

https://github.com/friendly/Guerry
 OLS Regression Results 
==============================================================================
Dep. Variable: Lottery R-squared: 0.414
Model: OLS Adj. R-squared: 0.392
Method: Least Squares F-statistic: 19.30
Date: Thu, 26 Jun 2025 Prob (F-statistic): 1.47e-09
Time: 17:35:22 Log-Likelihood: -375.28
No. Observations: 86 AIC: 758.6
Df Residuals: 82 BIC: 768.4
Df Model: 3
Covariance Type: nonrobust
================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------
Intercept 194.3951 37.768 5.147 0.000 119.263 269.527
Wealth 0.2820 0.093 3.024 0.003 0.097 0.468
Literacy -0.3840 0.127 -3.033 0.003 -0.636 -0.132
np.log(Pop1831) -25.2363 6.047 -4.174 0.000 -37.265 -13.207
==============================================================================
Omnibus: 7.602 Durbin-Watson: 1.890
Prob(Omnibus): 0.022 Jarque-Bera (JB): 7.051
Skew: -0.651 Prob(JB): 0.0294
Kurtosis: 3.524 Cond. No. 1.13e+03
==============================================================================

Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
[2] The condition number is large, 1.13e+03. This might indicate that there are
strong multicollinearity or other numerical problems.
mX5 executed: 26/06/2025 17:35:23 Runtime: 0:0:47.680 Memload: 58% use
Partial Regression Plot Grid

https://spatialanalysis.github.io/geodaData/reference/guerry.html

 Execstring('import statsmodels.api as sm; import numpy as np'); Execstr('model = smf.ols("Lottery ~ Wealth + Literacy + np.log(Pop1831)", data=df).fit()'); execstr('print(model.summary())'); execstr('sm.graphics.plot_partregress_grid(model)'); 

Statsmodels is a Python library designed for statistical modeling, hypothesis testing, and data exploration. It provides a wide range of statistical models, including linear regression, time series analysis, and generalized linear models. 
The library supports both formula-based modeling (similar to R) and direct use of NumPy arrays. The data science tutorial explains the so called AGSI data storage and his visualization of the timeline. AGSI is the Aggregated Gas Storage Inventory and offers you the possibility to be kept up to date whenever a new service announcement or update from one of our data providers is posted on the website.

Data representation of gas in storage as a timeline AGSI dataset.

https://blogs.embarcadero.com/why-a-data-scientist-chooses-delphi-for-powerful-real-world-visualizations/

Scikitlearns model.score(X,y) calculation works on coefficient of determination i.e R^2 is a simple functionthat takes model.score= (X_test,y_test). It doesn’t require y_predicted value to be supplied externally to calculate the score for you, rather it calculates y_predicted internally and uses it in the calculations.

  • Mean Function: Calculates the average of an array.
  • Covariance Function: Computes the covariance between two arrays.
  • Correlation: Uses covariance and standard deviations for the correlation coefficient.
  • ComputeCorrelationMatrix: Iterates through all variable pairs to compute corr-matrix.
  • PrintMatrix: Outputs the matrix to the console.

Delphi does not have a built-in correlation matrix function with a heatmap too, but you can implement one using standard math operations.

Guerry Dataset – from a csv file to a dataframe

The mrMath, mrStats, mrMatrix, mrImgUtils package includes:

  • Standard Fisher LDA classifier
  • Robust (and Fast Robust) version of this classifier
  • Incremental (and Robust) Fisher LDA classifier learning.
  • Support Vector Machines (least squares and lagrangian learning)
  • Naive Bayes
  • Simple Decission stumps
  • Radial basis function
  • C4.5 Decission trees.
  • K-means
  • Ensemble classifiers: AdaBoost, Gentle Boost, Bagging
  • Simple feed forward Neural Nets
mX5.2 with Statsmodels Console Output

Learn how to install statsmodels, a Python package for statistical modeling, using Anaconda, PyPI, source or development version.

Statsmodels Py 3.13.4

You can compute a correlation matrix in Delphi by iterating over all pairs of variables, extracting columns, and applying the Pearson correlation formula. For more advanced matrix operations or large datasets, consider using a Delphi matrix library.

 procedure ComputeCorrelationMatrix(const Data: DMatrix; var CorrMatrix: DMatrix); var i, j, k, nVars, nObs: Integer; colI, colJ: array of Double; begin nObs:= Length(Data); nVars:= Length(Data[0]); //SetLength(CorrMatrix, nVars, nVars); SetMatrixLength(corrMatrix, nvars, nvars); for i:= 0 to nVars-1 do begin SetLength(colI, nObs); for j:= 0 to nObs - 1 do colI[j]:= Data[j][i]; for j:= i to nVars-1 do begin SetLength(colJ, nObs); for k:= 0 to nObs - 1 do colJ[k]:= Data[k][j]; CorrMatrix[i][j]:= PearsonCorrelation(colI, colJ); CorrMatrix[j][i]:= CorrMatrix[i][j]; // Matrix is symmetric end; end; end; 

To transform the CSV data from file to matrix and dataframe you need 4 steps:

 S:= TStringList.Create; try //S.StrictDelimiter := True; S.LineBreak := #10; //S1.Delimiter := ','; s.loadfromfile(exepath+'\examples\1417_export_dataframe.csv'); writ('size: '+itoa(s.count)); SetMatrixLength(mData, 86, 6); TStringListToMatrix(s, mData); 

Input: The StringList contains rows of data as strings, separated commas.

Parsing: Each string is split into columns using CommaText of a temporary TStringList.

Matrix Population: The parsed values are stored in a 2D array (Matrix).

Output: The matrix is printed to verify the conversion.

 procedure TStringListToMatrix(strList: TStringList; var matrix: DMatrix); var i, j: Integer; RowData: TStringList; begin if strList.Count = 0 then Exit; // Create a temporary TStringList to parse each row RowData:= TStringList.Create; try RowData.Delimiter:= ','; // Assuming comma-separated values RowData.StrictDelimiter:= True; //RowData.commatext // Resize matrix to match the TStringList dimensions SetLength(matrix, strList.Count); for i := 1 to strList.Count - 1 do begin RowData.DelimitedText:= strList[i]; //writ('debug '+itoa(rowdata.count)); SetLength(Matrix[i], RowData.Count); for j:= 4 to RowData.Count - 15 do begin //slice 4-9 Matrix[i][j-4]:= strtofloat(RowData[j]); //writ('debug '+flots(matrix[i][j])); end; end; finally RowData.Free; end; end; 
Partial Regression Plot with Statsmodels

debug: 208-RuntimeError: CPU dispatcher tracer already initlized 865 err:20
debug: 209-RuntimeError: CPU dispatcher tracer already initlized 865 err:20
Exception: RuntimeError: CPU dispatcher tracer already initlized at 865.3134

 //# Fit an OLS regression model //eng.Execstring('model = smf.ols("Lottery ~ Literacy + np.log(Pop1831)", data=data).fit()'); Execstr('model = smf.ols("Lottery ~ Wealth + Literacy + np.log(Pop1831)", data=df).fit()'); //# Display the summary of results execstr('print(model.summary())'); {Notice that there is one missing observation in the Region column. We eliminate it using a DataFrame method provided by pandas:} execstr('df = df.dropna()'); execstr('sm.graphics.plot_partregress("Lottery","Wealth", ["Region","Distance"],'+ 'data=df, obs_labels=False)'); ExecStr('plt.show()'); 
sample or observation tracer obs_labels=True

Scripts at:

https://sourceforge.net/projects/maxbox5/files/EKON29/1385_DCorrelation3SeabornPyCompare2_uc.txt/download

https://sourceforge.net/projects/maxbox5/files/examples/1417_statsmodels_64_delphi_python3.12.4debug30.txt/download

Python for Delphi at maXbox statsmodels console
Informatik Workshop 1994
2 Nation Locs France – Italy
Train your Main Brain
Museum near Rotterdam
EKON 29 Session

https://entwickler-konferenz.de/delphi-innovations-fundamentals/statistic-packages-fuer-delphi-oder-python

30 Jahre Delphi – 30 Jahre 4Gewinnt Gewinnspiel

You can find the script to run in maXbox VM

https://github.com/maxkleiner/maXbox5/blob/main/examples/170_4gewinnt_main3_2025.txt

Script: https://github.com/maxkleiner/maXbox5/blob/main/examples/4gewinnt2025.txt
Bug hunting in V5.2.9.196
CC 6572 Cité du Train – Mulhouse – France
The Heat Beat

Weatherapp5.4 with OpenWeathermap and OWM forecaster plus mapbox city maps

AKE AKE-Eisenbahntouristik
3 Nation Multisystem Locs – DB, B, SNCF – BB 181 212-2, BB 1608, CC 40110
ICE 411 (ICE-T) Hannover – Fulda, 24/08/2025

Char Statistic

So, for example, if passed “aAAbbbb” for ‘stones’ and “aA” for ‘jewels‘, the function should return 3.

 function CommonLetters(S1,S2: string): integer; {Count the number of letters in S1 are found in S2} var i, j: integer; begin result:=0; for i:=1 to Length(S1) do for j:=1 to Length(S2) do if S1[i]=S2[j] then Inc(result); end; procedure ShowJewelsStones(Memo: TMemo; Jewels,Stones: string); {Show one Jewels-Stones comparison} begin Memo2.Lines.Add(Jewels+' '+Stones+' '+IntToStr(CommonLetters(Jewels,Stones))); end; 

Both strings can contain any number of upper or lower case letters. However, in the case of ‘jewels’, all letters must be distinct.

 const PYFUNC = 'def countJewels(s, j): '+LF+ ' return sum(x in j for x in s) '; with TPythonEngine.Create(Nil) do begin loadDLL; try ExecString('import sys'); ExecString(PYFUNC); println('pyout:'+evalstr('countJewels("taAAbbbb","aA"),sys.version')); println('pyout:'+evalstr('countJewels("12345643","34"),sys.version')); except raiseError; finally unloadDll; Free; end; end; 

https://rosettacode.org/wiki/Jewels_and_stones#Python

TEE Capitole – Jouef CC 6526, Roco BB 9278, L.S. Models CC 6513
EKON 29

    result:= ‘GEO_Code Data Map Out: ‘+UTF8ToString(lStream.ReadString(lStream.Size));

mX52 SynEdit Upgrade
mX5.2.9.198 Upgrade
Tokyo Bay
EKON History

The slides for the session:

Click to access maxbox_starter157.pdf

Test Classifier App

This library and app contains classes for easy classifier design. For simple classifier design check out the TestApp – basically this is a unit test application – and see there which classifieres and face detectors are available and how to use them. It’s recommended to have base knowledge about the underlying algorithms. Quite a few algorithms have been designed with robustness in mind (robustness in terms of outlying pixels or occluded areas).

* Support Vector Machines with Least Squares and Lagragian Learning
* Ensemble Classification Algorithms:AdaBoost,GentleBoost and Bagging
* All the above classifiers may be used in the Ensemble classification tasks.
* Features Extractors: Haar1D, Haar2D and the Integral Image approach.
Test App for training & teaching
The package from mrsoft.org includes:

* Standard Fisher LDA classifier
* Robust (and Fast Robust) version of this classifier
* Incremental (and Robust) Fisher LDA classifier learning.
* Support Vector Machines (least squares and lagrangian learning)
* Naive Bayes
* Simple Decission stumps
* Radial basis function
* C4.5 Decission trees.
* K-means
* Ensemble classifiers: AdaBoost, Gentle Boost, Bagging
* Simple feed forward Neural Nets

On top of these classifiers there exists a few image database handling routines
and an 1D, 2D Haar Feature extractor which is based on an integral image approach.

A testing application TestClassifier.dpr which shows the usage and performance of these classifiers on various tasks (e.g. face recognition) which we slightly improved, compiled and signed can be found on git or sourceforge:

https://github.com/maxkleiner/mrai_mx5/tree/master/TestApp

https://sourceforge.net/projects/maxbox5/files/binaries/TestClassifier64bit.exe/download
 uses BaseMatrixExamples, math, mathutilfunc, SimpleDecisionStump, AdaBoost, CustomBooster, Bagging, EnsembleClassifier, FisherBatchLDA, FisherClassifiers, ImageDataSet, ImageMatrixConv, {jpeg,} IncrementalImageDataSet, IncrementalFisherLDA, FisherIncrementalClassifiers, BaseIncrementalLearner, IntegralImg, Haar2DDataSet, MatrixImageLists, BinaryReaderWriter, BaseMathPersistence, DecisionTree45, TreeStructs, NaiveBayes, SVM, RBF, kmeans, NeuralNetwork, JSONReaderWriter, MatrixASMStubSwitch, ThreadedMatrix; unit ufrmTestClassifier; interface {.$DEFINE INITRANDSEED} // uncomment if you do not want the same train set uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, BaseClassifier, ExtCtrls, StdCtrls, Matrix, ComCtrls, Haar2DAdaBoost, Haar2DImageSweep, Image2DSweep, Types, Vcl.Imaging.jpeg; type TTrainSetType = (stGauss, stXOR, stCircles); type TfrmClassifierTest = class(TForm) 
Build with Embarcadero compiler D12.1

The source with precompiled binaries (This library is an extension of the mrMath, mrAI and mrImgUtils libraries and therefore depending on it!) are on:

https://github.com/maxkleiner/mrai_mx5/tree/master/TestApp

The momentum approach has been added to the neural network learner. In addition a certain percentage of the training set can now be selected to be a distinct validation set. This functionality has been moved into the base class so it may be used for other custom algorithms as well.

A simple feed forward neural network has also been added to the AI library whic hincludes linear, tanh and exponential neuron activation. For the learning step a simple backpropagation aglorithm has been added. The library now utilizes the new random engine provided by the mrMath library and also a confidence map:

The kmeans classifier features normal or median update steps as well as kmeans++ initial center search. The Radial Basis Classifier features different Kernels (Gauss, Quad, Inverse Multiquad, Multiquad) as well as different radial basis extractors. These are randomly selected subset from the learning set or mean/median of the class centers.

A simple version of the Viola Jones Face detection algorithm is also available as unit and app test:

Models can be saved and loaded from files like haarClassifier21.cls. Tested also with memleaks cause this is not very troublesome but if this already used memory has some NAN in it it may happen that the QR, Cholesky, LU and SVD decompositions raise exceptions.

memleak tests

Conclusion: You can build and compile the whole library or start easy with the compiled app on git: TestClassifier64bit.exe

Or build then first download both of these 4 libraries mrMath290, mrMathIDE, mrImgUtils, mrAI and compile the included dpk files. Also add the directories to the library (and or) search paths!

Circle Set Tester mX51
Classifier Comparison
Trix International

Python and Print from the shell to maXbox (python4delphi)

Sometimes you’ll hear it referred to as the Python prompt, the Python console, or the Python shell, but it’s most often called the Python REPL.

REPL is an acronym. It stands for Read, Evaluate, Print, and Loop.

Those four words describe how the REPL works:

  1. It reads what we’ve typed
  2. Then it evaluates it, meaning it runs the code
  3. Then it prints any value that’s returned to it
  4. Then it loops (to step 1), meaning it waits for more input

So if we want to return the python consol print back to maXbox terminal we just had to set the standard output to our terminal with the help of io.String() as output:

 Execstr('import io, sys'); execstr('output = io.StringIO()') execstr('sys.stdout = output') execstr('for i, value in enumerate(["Python", "Rocks", "Always"]): '+LF+ ' print(i, value)'); println(stringReplace(evalstr('output.getvalue().strip()'), #10,#13#10,[rfReplaceAll, rfIgnoreCase])); 

Using StringIO, you can capture output and check if it is desired output or not. With the stringreplace() above we change the linebreak from python to pascal so newlines are seen at the right place:

0 Python
1 Rocks
2 Always
[(‘Alice’, 95), (‘Bob’, 85)]

The script you can find at: http://www.softwareschule.ch/examples/pydemo78_1.htm

StringIO returns Python Shell to maXbox terminal with evalstr(‘output.getvalue().strip()’)

Work with the TStatisticClass

Write a stateful function, class, generator or co-routine that takes a series of floating point numbers, one at a time, and returns the running standard deviation of the series.

Use this to compute the standard deviation of this demonstration set, {2,4,4,4,5,5,7,9} which is 2.

{\displaystyle \{2,4,4,4,5,5,7,9\}}
 var dat: array of double; //Extended; statclass: TStatisticClass; setlength(dat,7); dat:= [2,4,4,4,5,5,7,9] statclass:= TStatisticClass.create; for it:= 0 to high(dat) do formatF('%2.0f -> %18.16f',[dat[it],AppendAndCalcStat(statclass,dat[it])]); statclass.Free; 

The AppendAndCalcStat() takes the statistic object to get filled and the continues dataset:

 function AppendAndCalcStat(statobj: TStatisticClass; newVal:Extended):Extended; begin statobj.add(newval); result:= statobj.PopulationStdDev; end; 
  • 2 -> 0.0000000000000000
  • 4 -> 1.0000000000000000
  • 4 -> 0.9428090415820630
  • 4 -> 0.8660254037844387
  • 5 -> 0.9797958971132709
  • 5 -> 1.0000000000000000
  • 7 -> 1.3997084244475306
  • 9 -> 2.0000000000000000
  • mX5🐞 executed: 18/12/2024 13:59:59 Runtime: 0:0:3.84 Memload: 67% use
https://sourceforge.net/projects/maxbox5/files/examples/1354_StdDevD.pas/download
 (*----------------------------------------------------------------------------*) Proc SIRegister_TStatisticClass(CL: TPSPascalCompiler); begin //with RegClassS(CL,'TOBJECT', 'TStatisticClass') do with CL.AddClassN(CL.FindClass('TOBJECT'),'TStatisticClass') do begin Proc Assign( const S : TStatisticClass); Func Duplicate : TStatisticClass'); Proc Clear'); Func IsEqual( const S : TStatisticClASS):Bool'); Proc Add( const V : MFloat); Proc Add1( const V : array of MFloat); Proc Add2( const V : TStatisticClass); Proc AddNegated( const V : TStatisticClass); Proc Negate'); Count', 'Integer', iptr); Min', 'MFloat', iptr); Max', 'MFloat', iptr); Sum', 'MFloat', iptr); SumOfSquares', 'MFloat', iptr); SumOfCubes', 'MFloat', iptr); SumOfQuads', 'MFloat', iptr); Func Range : MFloat'); Func Mean : MFloat'); Func PopulationVariance : MFloat'); Func PopulationStdDev : MFloat'); Func Variance : MFloat'); Func StdDev : MFloat'); Func M1 : MFloat'); Func M2 : MFloat'); Func M3 : MFloat'); Func M4 : MFloat'); Func Skew : MFloat'); Func Kurtosis : MFloat'); Func GetAsString :Str'); end; end; 

Python Solution

 procedure STDDEv_PySolution(loc: string); begin with TPythonEngine.Create(Nil) do begin //pythonhome:= PYHOME64; loaddll; autofinalize:= false; try Execstring('from math import sqrt'); Execstr('import io, sys'); //Execstring('import plotly.express as px'); Execstr(DEFSD); execstr('output = io.StringIO()') execstr('sys.stdout = output') execstr('sd.sum = sd.sum2 = sd.n = 0 '+LF+ 'for value in (2,4,4,4,5,5,7,9):'+LF+ ' print (value, sd(value))'); println(stringreplace(evalstr('output.getvalue().strip()'), #10,#13#10,[rfReplaceAll, rfIgnoreCase])); except raiseError; finally UnloadDll; Free; end; end; end; 

Python Solution:
2 0.0
4 1.0
4 0.9428090415820626
4 0.8660254037844386
5 0.9797958971132708
5 1.0
7 1.399708424447531
9 2.0
mX5🐞 executed: 18/12/2024 15:33:08 Runtime: 0:0:2.386 Memload: 66% use

CC Parade Jouef – TAB – Roco
CC 21000 Parade
from Archive digitized Re 4/4 II 11253



Station2Station

Use this tool as a script (1274_GoogleDirForm2GeocodeDirectionsGeneral2request62.pas) to get the directions between any point using google maps. Enter a city or an address in both the From and the To address inputs. You can also set direct an lat- and longitude. Click Got to Google… (Find Directions), and the tool will display the route you need to take to get from your starting location to your end location in the browser. The turn by turn directions will be displayed below the map, and will contain the distance and approximate time it will take to get from one location to the other.

The GoogleDirForm from to box with geocoding and from open street maps.

The licence is a “licence”: “Data © OpenStreetMap contributors, ODbL 1.0. http:\/\/osm.org\/copyright”, and you can also get your own API-key. The a browser starts with the google maps directions window, as we checked the “Check To See Link In Browser”:

Berlin – Leipzig as Station to Station

Get or find coordinates: Search for a place using its latitude and longitude coordinates, or get the coordinates of a place you’ve already found.

Code behind

TDirection is working as a URL Builder: IsNavUtils – Provides a RNavigateLongLat record as class to manipulate Longitude and Latitude references and the functions and constants required to achieve this.
 procedure TDirectionsBtnGoGoogleClick(Sender: TObject); Var LocFrom,LocTo:RNavigateLongLat; Long,Lat:Double; begin LocFrom:=RNavigateLongLat.create; Locto:=RNavigateLongLat.create; Long:=RealFrmDegreeText(EdtLong.Text); Lat:= RealFrmDegreeText(EdtLat.Text); LocFrom.CreateDec(Long,Lat); Long:=RealFrmDegreeText(EdtLong2.Text); Lat:= RealFrmDegreeText(EdtLat2.Text); LocTo.CreateDec(Long,Lat); // { 0 Start 1 End 3 Center } EdtGoogleLink.Text:=LocFrom.GoogleLinkDirectionsTo(LocTo, 0); LBlCrowFlies.Caption:='Distance as Crow Flys ='+FormatFloat('0.0km',LocTo.MetresFrom(LocFrom)/1000); if CBxGoNow.Checked then LocFrom.GoGoogleDirectionsTo(LocTo, 0); end; 

For the geocoding we use a restclient THttpRequestC a JSON Lib and the OSM API from nominatim. Nominatim uses OpenStreetMap data to find locations on Earth by name and address (geocoding). It can also do the reverse, find an address for any location on the planet. For occasional use. Use the API. Usage policy. API documentation. For power users. Install your own. The latest release is 4.5.0.

 function TAddressGeoCodeOSM8(AURL, location, aApikey: string): tlatlong; var Httpreq: THttpRequestC; httpres: string; Body: TMultipartFormBody; jsn: TMcJsonItem; begin httpreq:= THttpRequestC.create(self); httpreq.headers.add('Accept: application/json; charset=utf-8'); httpreq.useragent:= USERAGENT4; httpreq.SecurityOptions:= [soSsl3, soPct, soIgnoreCertCNInvalid]; try if httpreq.get(Format(AURL,[location])) then begin //httpres:= (httpreq.Response.ContentAsString) httpres:= (httpreq.Response.ContentAsUTF8String) //writeln('conttype '+httpreq.Response.ContentType); writ('debug back '+formatJson(httpres)); jsn:= TMcJsonItem.Create; jsn.AsJSON:= httpres; result.lat:= jsn.at(0,'lat').asnumber; result.long:= jsn.at(0,'lon').asnumber; result.descript:= Format('Coords: lat %2.5f lng %2.5f %s place_id: %d', [result.lat,result.long,jsn.at(0,'display_name').asstring, jsn.at(0,'place_id').asinteger]); end else Writeln('APIError '+inttostr(Httpreq.Response.StatusCode2)); //StrReplace(httpres, '[{', '{'); finally writeln('Status3: '+gethttpcod(httpreq.Response.statuscode2)) httpreq.Free; sleep(200) jsn.Free; end; end; 
Result: OSM _from: Coords: lat 46.94724 lng 7.45158 Münster, 1, Münsterplatz, Altstadt, Grünes Quartier, Stadtteil I, Bern, Verwaltungskreis Bern-Mittelland, Verwaltungsregion Bern-Mittelland, Bern/Berne, 3000, Schweiz/Suisse/Svizzera/Svizra place_id: 78089330
OSM _to: Coords: lat 51.33933 lng 12.37260 Thomaskirche, 18, Thomaskirchhof, Zentrum, Mitte, Leipzig, Sachsen, 04109, Deutschland place_id: 118838745
get geocoords: lat: 51.3393 - lon: 12.3726
mX5🐞 executed: 26/09/2024 09:52:14 Runtime: 0:0:4.38 Memload: 62% use

The GoogleDirForm is simple and a really simple form to put in Long/Lat references and also Locations and then get Google Directions in Browser:

Get Response Header Data and JSON Path Selection

HTTP headers are additional pieces of information sent along with an HTTP request or response. They provide important metadata about the request or response, such as the content type, caching directives, authentication credentials, and more.

These headers are sent by the server in response to a client’s request and provide information about the server or the response itself. Some commonly used response headers include:

  • Content-Type: Specifies the media type of the response body.
  • Cache-Control: Controls caching behavior for the response.
  • Set-Cookie: Sets a cookie in the client’s browser for maintaining the session state.
  • Location: Used in redirection to specify the new location for the requested resource.
  • RateLimit: httpq.GetResponseHeader(‘x-ratelimit-requests-remaining‘):

With THttpRequestC you can find a response header with hreq.Response.headers.values[‘server’]); and with TMcJsonItem you can parse JSON arrays of objects or get the json-path with jsn.path(‘data/name/store’).asstring:

 function getEnergyStreamJSON4(AURL, feedstream, aApikey: string): string; var Hreq: THttpRequestC; httpres, encodURL: string; Body: TMultipartFormBody; jsn, jsno: TMcJsonItem; asp: TStringArray; rcnt: integer; begin hreq:= THttpRequestC.create(self); hreq.headers.add('Accept: application/json; charset=utf-8'); hreq.headers.add('x-key:'+aAPIkey); hreq.useragent:= USERAGENTE; hreq.SecurityOptions:= [soSsl3, soPct, soIgnoreCertCNInvalid]; try asp:= splitStr(feedstream,','); encodURL:= Format(AURL,[HTTPEncode(asp[0]),(asp[1]),asp[2]]); writeln(encodurl) if hreq.get(encodURL) then begin httpres:= (hreq.Response.ContentAsUTF8String) writ('contenttype: '+hreq.Response.contenttype); rcnt:= hreq.Response.headers.count; writ('server: '+hreq.Response.headers.values['server']); for it:= 0 to rcnt-1 do writ('resp_head: '+itoa(it)+' '+hreq.Response.headers[it]); //writ('debug back '+formatJson(httpres)); jsn:= TMcJsonItem.Create; jsn.AsJSON:= httpres; result:= httpres; //writ(jsn.path('data/name').asstring); writ(jsn.values['dataset'].asstring); writ(jsn.values['data'].items[1]['code'].asstring); writ(jsn.values['data'].items[1]['gasInStorage'].asstring); jsno:= jsn.values['data'].items[1].asobject; writ(jsno['gasInStorage'].asstring); result:= Format('AGSI: store: %2.3f cons: %2.3f status:%s trend: %2.2f', [jsno['gasInStorage'].asnumber,jsno['consumption'].asnumber, jsno['status'].asstring, jsno['trend'].asnumber]); //} end else Writeln('APIError '+inttostr(Hreq.Response.StatusCode2)); finally writeln('Status4: '+gethttpcod(hreq.Response.statuscode2)) hreq.Free; sleep(200) jsn.Free; end; end; 

A major learning curve was how the user interface needs to be adapted for the very small screens and make it scriptable at runtime with maXbox5. I chose a Multi Layer Tab control template “Tabbed with Navigation” offered with Tokyo as a basis for my trail app. I had to add the functionality to support the hardware back button and was not very successful with gesture use opting in the end for Forward and Back Speed buttons so more to learn there. The Templates were for the time being not offered with my Rio and Alexandria Community Install.

Another point is to integrate the EdgeView browser with the RAD Studio 10.4 Sydney brings support for working with web content through the Chromium-based Edge WebView2 browser control in VCL applications via the new TEdgeBrowser component.

TEdgeBrowser supersedes TWebBrowser, which uses the Internet Explorer WebBrowser browser control. However TWebBrowser remains in the VCL component set, with some notable changes.

Delphi form as a browser plugin with a forthcoming web assembly

The script you can find at: https://sourceforge.net/projects/maxbox/files/Examples/EKON/EKON28/1274_GoogleDirForm2GeocodeDirectionsGeneral2request62.pas/download

station2station tracker test VII
station2station tracker test IX
station2station tracker test X
EKON 28 will be xenomorph

Trefft mich auf der EKON 28! In meiner Session zeige ich, wie du mit Google Directions API und Google Maps Wegbeschreibungen und Routen für verschiedene Transportmittel berechnest und visualisierst. Ich erstelle ein Navigation Advisor Projekt und demonstriere Geocoding sowie die Verwaltung von Diensten und Karten mit APIs und SDKs. Nutze den Rabattcode MaKl_EKON_28 und erhalte 15 % Ermäßigung auf die Tickets.

Pydemo67
Interrail in the meantime
Re 4/4 I-IV Track N (Lemaco, Fleischmann, Hobbytrain)

Summary

  • The Station2Station tool is a script (1274_GoogleDirForm2GeocodeDirectionsGeneral2request62.pas) that uses Google Maps to get directions between any two points.
  • Users can enter a city or address in the From and To address inputs, or set direct latitude and longitude coordinates. The tool displays the route in the browser, along with turn-by-turn directions, distance, and approximate time it will take to get from one location to the other.
  • The GoogleDirForm uses geocoding and Open Street Maps, with a license from OpenStreetMap contributors under ODbL 1.0. Users can get their own API-key for the tool.
  • The code behind the tool uses TDirection as a URL Builder, with RNavigateLongLat record as a class to manipulate longitude and latitude references. The tool uses a rest client, THttpRequestC, a JSON Lib, and the OSM API from Nominatim for geocoding.
  • Nominatim uses OpenStreetMap data to find locations on Earth by name and address, and can also do reverse geocoding.
  • The tool has been tested on Android Delphi 10.4 Sydney Targets API Level Android 29 (Android 10).
  • The tool’s author will be presenting a session at EKON 28, demonstrating how to use Google Directions API and Google Maps to calculate and visualize routes for different modes of transportation. A discount code, MaKl_EKON_28, is available for 15% off tickets to EKON 28.

2Rex

In the following section we can see the integration of weather- or geocode data in our app station2station. We use an API and a RegEx:

 Const UrlWeatherReport25= 'https://api.openweathermap.org/data/2.5/weather?q=%s&units=metric&APPID'+ '=55013bf3d09cfb0619989a00ed5bed_____yourAPIKey'; GEOCoordREX3 = '"lon":([\d\.-]+).*"lat":([\d\.-]+).*"temp":([\d\.-]+).*'; 

Better solution is to get the API from an include file with a const called OWMKEY:

 {$I owmapikey.inc } Const UrlWeatherReport25= 'https://api.openweathermap.org/data/2.5/weather?q=%s&units=metric&APPID'+ OWMKEY; 

Next we call the API with a simple HTTPGet() to return the JSON String Stream:

 function GetGeoWeather(const location: string; const UrlRestAPI: string): string; var lStrm: TStringStream; begin lStrm:= TStringStream.Create(''); try try HTTPGet(Format(UrlRestAPI,[location]),lStrm); except //if something wrong try using a backup server. //writeln('htmlback: '+GetURLAsString('http://api.openweathermap.org')); writeln('OWeather_Map Exception: '+Gethtm(UrlWeatherReport25)) end; lStrm.Seek(0,0); result:= +(lStrm.ReadString(lStrm.Size)); finally lStrm.Free; end; end; 

With the https result we parse the Utf8 JSON with a RegEx:

 function GEOCoord2PointX2(apistr: string): TFloatPoint; begin setdecimalseparator('.') with TRegEx.Create(GEOCoordREX3,[rroIgnoreCase]) do try if match(apistr).success then begin result.x:= strtofloat(match(apistr).groups[1].value) result.y:= strtofloat(match(apistr).groups[2].value) temp:= strtofloat(match(apistr).groups[3].value) end; finally Free; end; end; 

In the end we do have separation of concern in call the API, parse the result and show the data on console or as a return function ShowGeoWeather(): string for further format:

 procedure ShowGeoWeather; begin //sr:= GetGeoWeather(removespaces('Melbourne,AU'),UrlWeatherReport25); sr:= GetGeoWeather(removespaces('Bern, CH'),UrlWeatherReport25); writeln(formatjson(sr)) // writeln('GEO_Weather_Report5: '+sr); lonf:= GEOCoord2PointX2(sr).x latf:= GEOCoord2PointX2(sr).y PrintF('Lon: %.4f - Lat: %.4f ',[lonf, latf]) writ('geoweather coords: '+format('Lon: %.4f -Lat: %.4f -temp:%.2f°', [lonf,latf,temp])); end; 

Beginner RegEx question. I have lines of JSON in a textfile, each with slightly different Fields like coords or weather array, but there are 3 fields I want to extract for each object line if it has it, ignoring everything else. How would I use a regex (in editpad, script, shell or anywhere else) to do this?

Don’t try to parse JSON yourself. This is a solved problem. People have already written, tested and debugged code that handles this already. You can use a JSON Parser or a RegEx Group!

This next with a JSON Parser:

 function GEOCoord2PointX3(apistr: string): TFloatPoint; begin setdecimalseparator('.') with TMcJsonItem.Create do begin AsJSON:= apistr; result.x:= at(0,'lat').asnumber; result.y:= at(0,'lon').asnumber; temp:= at(3,'temp').asnumber; sunrise:= path('sys/sunrise').asinteger; //index independent! sunset:= path('sys/sunset').asinteger; free; end; end; 

Get a key-value JSON with a Regular Expression, the following regex expression extract exactly the “fid” field value “321”:

 regs:= '{"fid":"321","otherAttribute":"value"} '; writeln(formatjson(regs)) writ(regexFindall(regs, '(?<=\"fid\":\")[^\"]*')); 
 { "coord": { "lon": 7.4474, "lat": 46.9481 }, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10n" } ], "base": "stations", "main": { "temp": 11.03, "feels_like": 10.33, "temp_min": 10.27, "temp_max": 12.74, "pressure": 1011, "humidity": 82, "sea_level": 1011, "grnd_level": 939 }, "visibility": 10000, "wind": { "speed": 0.81, "deg": 142, "gust": 0.47 }, "rain": { "1h": 0.52 }, "clouds": { "all": 60 }, "dt": 1728239017, "sys": { "type": 2, "id": 2012960, "country": "CH", "sunrise": 1728192953, "sunset": 1728234020 }, "timezone": 7200, "id": 2661552, "name": "Bern", "cod": 200 } 
JSON Parser Online

"dt": 1728209107,
"sys": {
"type": 1,
"id": 6937,
"country": "CH",
"sunrise": 1728192953,
"sunset": 1728234020
},
"timezone": 7200,
"id": 2661552,
"name": "Bern",
"cod": 200
}
Lon: 7.4474 - Lat: 46.9481
geoweather coords: Lon: 7.4474 - Lat: 46.9481 -temp:9.01°
mX5🐞 executed: 06/10/2024 12:08:21 Runtime: 0:0:3.244 Memload: 59% use

JSON Parser as RegEx

 This regular expression finds a key-value pair in JSON formatted strings 

For those who want to see that a TMachCollection are matches of groups I found a stackoverflow testdocument in which we convert the RegEx in a TMatchCollection:

 const TESTJSON = '[ '+LF+ ' { '+LF+ ' "_id": "56af331efbeca6240c61b2ca", '+LF+ ' "index": 120000, '+LF+ ' "guid": "bedb2018-c017-429E-b520-696ea3666692", '+LF+ ' "isActive": false, '+LF+ ' "balance": "$2,202,350", '+LF+ ' "object": { '+LF+ ' "name": "amx", '+LF+ ' "lastname": "lang" '+LF+ ' } '+LF+ ' } '+LF+ '] '; writ(regexFindall(TESTJSON, '(?:\"|\'')(?<key>[^"]*)(?:\"|\'')(?=:)(?:\:\s*)(?:\"|\'')?(?<value>true|false|[0-9a-zA-Z\+\-\,\.\$]*)')); >>> 8 Matches [ ]: [ "_id": "56af331efbeca6240c61b2ca ][ "index": 120000, ] [ "guid": "bedb2018-c017-429E-b520-696ea3666692 ] [ "isActive": false ][ "balance": "$2,202,350 ][ "object": ] [ "name": "am ][ "lastname": "lang ] with TRegEx.Create(sr,[rroIgnoreCase]) do try mats:= Matches(TESTJSON); //for group in matches do for m:= 0 to mats.count-1 do begin for g:= 1 to mats[it].groups.count-1 do writ(format('matchgrp[%d,%d]: %s ',[m,g,mats[m].groups[g].value])); end; writ('match group[direct] balance: '+mats[4].groups[2].value); finally Free; end; >>> 8 matches each 3 groups matchgrp[0,1]: _id matchgrp[0,2]: 56af331efbeca6240c61b2ca matchgrp[1,1]: index matchgrp[1,2]: 120000, matchgrp[2,1]: guid matchgrp[2,2]: bedb2018-c017-429E-b520-696ea3666692 matchgrp[3,1]: isActive matchgrp[3,2]: false matchgrp[4,1]: balance matchgrp[4,2]: $2,202,350 matchgrp[5,1]: object matchgrp[5,2]: matchgrp[6,1]: name matchgrp[6,2]: amx matchgrp[7,1]: lastname matchgrp[7,2]: lang match group[direct] balance: $2,202,350 mX5 executed: 06/10/2024 16:49:24 Runtime: 0:0:3.482 Memload: 57% use https://regex101.com/r/zR2vU9/4 
Märklin 3067.5, from ‘1975 to ‘1976, body Roed/Black DSB inscription fine
py modul package sympy
Goldbachs Comet
4 Nations: Märklin DB E10 1266 – B 1606 – TAB SNCF CC 6544 – Piko SBB Re 4/4 1034 TEE Classic

Der kosmopolitische Stadtteil Pempelfort ist für seine kulturellen Einrichtungen am Rhein bekannt.

Happy New Year 2025

Compare OWM Python – Pascal

Get real-time weather updates every hour and never forget your umbrella again:

 Const PyWeather = 'def get_weather(): '+LF+ ' url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}"'+LF+ ' response = requests.get(url) '+LF+ ' data = response.json() '+LF+ ' return data[''weather''][0][''description''], data[''main''][''temp'']-273.15'; procedure Weather_PySolution(loc: string); var OWMKEYS: string; begin with TPythonEngine.Create(Nil) do begin loaddll; //pythonhome:= PYHOME64; autofinalize:= false; try Execstring('import re, requests, time'); OWMKEYS:= ''''+ReplaceStr(OWMKEYPY,'''','''''')+''''; writeln('apikey:'+ OWMKEYS); Execstring('API_KEY = '+OWMKEYS+'; CITY = '+loc); Execstring(PyWeather); Execstr('weather, temp = get_weather()'); println(evalstr('(f"Current weather in {CITY}: {weather}, {temp:.2f} C.")')); except raiseError; finally UnloadDll; Free; end; end; end; 

And in pure Python:

 import requests import time API_KEY = 'your_api_key' CITY = 'Basel,CH' def get_weather(): url = f"http://api.openweathermap.org/data/2.5/weather?q={CITY}&appid={API_KEY}" response = requests.get(url) data = response.json() return data['weather'][0]['description'], data['main']['temp'] - 273.15 while True: weather, temp = get_weather() print(f"Current weather in {CITY}: {weather}, {temp:.2f}°C") time.sleep(3600) # Run every hour 
 const DEF_SPEECH = 'def text_to_speech(text): '+LF+ ' engine = pyttsx3.init() '+LF+ ' engine.say(text) '+LF+ ' engine.runAndWait() '; 

Voice in Python

You has to install C:\maxbox\maxbox4\maxbox4>py -3.12 -m pip install pyttsx3

Then I have had this error when trying to create a python service using pywin32 module. 
I copied pythoncom38.dll and pywintypes38.dll into the root directory of the project and it solved the issue. (Exception: ModuleNotFoundError: No module named ‘pywintypes’ at 868.1496)

For me it worked to copy the files (pythoncom38.dll and pywintypes38.dll) from: C:\Users\”Your user id”\AppData\Roaming\Python\Python38\site-packages\pywin32_system32 to the path: C:\Users\”Your user id”\AppData\Roaming\Python\Python38\site-packages\win32\lib

 procedure Weather_PySolution(loc: string); var OWMKEYS: string; begin with TPythonEngine.Create(Nil) do begin //pythonhome:= PYHOME64; loaddll; autofinalize:= false; try Execstring('import re, requests, time, pyttsx3'); println('Py_Weather_algorithm#Functional _requests strip-split-slice: '); OWMKEYS:= ''''+ReplaceStr(OWMKEYPY,'''','''''')+''''; writeln('apikey:'+ OWMKEYS); Execstring('API_KEY = '+OWMKEYS+'; CITY = '+loc); Execstring(PyWeather); Execstring(DEF_SPEECH); Execstr('weather, temp = get_weather()'); println(evalstr('(f"Current weather in {CITY}: {weather}, {temp:.2f} C.")')); Execstr('text_to_speech('''+evalstr('(f"Current weather in {CITY}:{weather},{temp:.2f} C.")')+''')'); except raiseError; finally UnloadDll; Free; end; end; end; 

The interesting line is the combination of execstr() and evalstr() cause we want to make the result audible (nous voulons rendre le résultat audible).

 {To get the current weather data of any city using the OpenWeatherMap 
     API in Python, you can use the requests and json modules. Here is an example: 

 ‘data = requests.get(f”https://api.openweathermap.org/data/2.5/weather?q={city}&units=metric&appid={api_key}”).json()’+LF+ ‘print(f”Weather in {city}: {data[”weather”][0][”description”]}”) ‘+LF+ ‘print(f”Temperature (in celcius) = {data[”main”][”temp”]}”)’);  
      
The OpenWeatherMap API is a service that provides weather data, including current weather data, forecasts,  and historical data. It offers an API with JSON, XML, and HTML endpoints, and a limited free usage tier. 
     To use the API, you need to create an account on openweathermap.org and obtain an API key.}

5 Nations Locs
BR E 10 Tracks
BPM #120 with a post API image pipeline from station2station
SNCF, locomotive électrique CC 6526 « Le Capitole », ép. IV – coffret anniversaire
SNCF, locomotive électrique CC 6526 « Le Capitole », ép. IV –
Re 4/4 II Märklin Z 11161, Fleischmann N 11251, Roco H0 11160, Hermann 0 11161

Linear Regression Fit

Linear regression is widely used in business to model relationships between variables. It helps predict outcomes based on input data.

 execstr('from sklearn.linear_model import LinearRegression'); execstr('# Data: Months and Sales (in thousands of dollars) '+LF+ 'months = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) '+LF+ 'sales = np.array([10, 12, 15, 20, 22]) # Sales in $1000s '+LF+ ' '+LF+ '# Create a linear regression model '+LF+ 'model = LinearRegression() '+LF+ ' '+LF+ '# Fit the model to our data '+LF+ 'model.fit(months, sales) '+LF+ '# Predict sales for the 6th month '+LF+ 'predicted_sales = model.predict([[6]]) '); execstr('print(f"Predicted Sales for month 6: ${predicted_sales[0]:.2f}k")'); 

We’ll use linear regression to predict future sales based on the previous month’s data.

The model predicts sales of $24,400 for month 6 based on historical sales data. Linear regression is an essential tool in sales forecasting, helping businesses plan inventory and marketing campaigns.

 from sklearn.linear_model import LinearRegression import numpy as np # Data: Months and Sales (in thousands of dollars) months = np.array([1, 2, 3, 4, 5]).reshape(-1, 1) sales = np.array([10, 12, 15, 20, 22]) # Sales in $1000s # Create a linear regression model model = LinearRegression() # Fit the model to our data model.fit(months, sales) # Predict sales for the 6th month predicted_sales = model.predict([[6]]) print(f"Predicted Sales for month 6: ${predicted_sales[0]:.2f}k") 
La Gomera Jardin Tecina
FM SNCF 68006, Jouef CC 6542, Trix CC 40105, Märklin BB 22347 – @TfrmMtxPlot
Rheingold Set
One Month Test 8.1.-5.2. 2025 (8 + 4*7=36)-31= 5.
From Lichfield to Geneva

EKON 28

More than 25 Speakers and over 30 Sessions with interaction and support: Profit from family conferences EKON 28 and learning, innovation and development in individual projects.

4. – 6. November | Düsseldorf

Use modern RegEx

When you start building scripts and apps, you are often faced with almost the same problems. Instead of laboriously constructing loops and queries, we look at the use of modern RegEx in Delphi and Python. Modern refers to 64-bit and Unicode, and pattern matching and stemming are also in demand in AI development or the Human Genome Project. Google, for example, probably uses an analogous process for organic search. Tips and tricks from the PCRE round off the express.

PCRE RegEx

System.RegularExpressionsCore

Packagertl270.bpl

Classes

ERegularExpressionError
TPerlRegExDelphi wrapper around the open source PCRE library.
TPerlRegExListA list of TPerlRegEx instances.
RegularExpression as Client uses Core (uses System.SysUtils, System.RegularExpressionsCore;)
 envlist:= Tstringlist.create; InStr:= loadfile(Exepath+'\restcountrieskeysutf812.txt'); writ(formatJSON(utf8decode(instr))); //getJsonData2(utf8decode(instr),'translations','common'); //jSplit( const Delimiter : char; Input :Str; Strings : TStrings); jSplit( '}', utf8decode(instr), envlist); //StrtoList(InStr, envlist, CRLF) writeln('envlist count: '+itoa(envlist.count)); cnt:= 0; regEx:= TRegEx.create('common":"[\w]',[rroNotEmpty]); //regEx.regex:='common [\w+:\w:\w :,]+ Sui'; // Execute search ot TMatch for it:= 0 to envlist.count-1 do if regEx.match((envlist[it])).success then begin writeln(itoa(cnt)+':'+envlist[it]); inc(cnt) end; regex.Free; envlist.Free; //*) 
langitem: 19	Švajčiarska konfederácia, slk
langitem: 20 Confederación Suiza, spa
langitem: 21 Швајцарска Конфедерација, srp
langitem: 22 Schweiziska edsförbundet, swe
langitem: 23 İsviçre Konfederasyonu, tur
langitem: 24 سوئیس متحدہ, urd
langitem: 25 瑞士联邦, zho
 N:= TMcJsonItem.Create; N.AsJSON := savestr; for it:= 0 to N['name']['translations'].count-1 do begin //writ('enumerator count '+itoa(N['name'].count-1)); item:= N['name']['translations'].items[it]; write(item.S['official']+' ') end; 
NLTK (Natural Language Toolkit) uses Regex package

Regex in Python

 procedure PyCodeREgEx(tex: string); begin with TPythonEngine.Create(Nil) do begin try loadDLL; //autofinalize:= false; ExecString('import re, json'); execstr('txt = "The rain in Explain"'); //if it starts with "The" and ends with "plain": Println('regex test: '+EvalStr('re.search("^The.*plain$", txt)')); execstr('x = re.search("^The.*plain$", txt)'); Println('regex test: '+EvalStr('type(x)')); Println('regex test: '+EvalStr('bool(x)')); // Println(EvalStr('decode_and_print_json('+JSONDATA+')')); except raiseError; finally unloadDLL; free; end; end; end; 
regex test: <re.Match object; span=(0, 19), match='The rain in Explain'>
regex test: <class 're.Match'>
regex test: True
TMatchEvaluator Problem closed
ask the ai
 procedure RegexExamplePerplex2; //uses //SysUtils, RegExpr; var matchr: TMatch; begin with TRegEx.Create1('\d{3}') do // pattern to match three digits try matchr:= Match('abc 123 def 456') ; repeat WriteLn('Found match: '+matchr.value); matchr:= matchr.NextMatch; until not matchr.success finally Free; end; end; 

Integrate Google Maps API.

The Google Directions API and Maps (Earth) are two powerful tools that can be used to calculate and visualize directions and routing between locations using various modes of transportation. The Google Maps Platform is also demonstrated with geocoding, I create a Trip Advisor project to then manage services, credentials, calculations, maps, coordinates in APIs and SDKs.

Google Directions
map editor with resource editor
Geo Coding with URL_APILAY_GEO = ‘https://api.apilayer.com/geo/country/capital/%s&#8217;;  
 function TAddressGeoCodeOSM8(AURL, location, aApikey: string): tlatlong; var Httpreq: THttpRequestC; httpres: string; Body: TMultipartFormBody; jsn: TMcJsonItem; begin httpreq:= THttpRequestC.create(self); httpreq.headers.add('Accept: application/json; charset=utf-8'); httpreq.useragent:= USERAGENT5; httpreq.SecurityOptions:= [soSsl3, soPct, soIgnoreCertCNInvalid]; try if httpreq.get(Format(AURL,[location])) then begin httpres:= (httpreq.Response.ContentAsString) writ('debug back '+FormatJson(httpres)); jsn:= TMcJsonItem.Create; jsn.AsJSON:= httpres; result.lat:= jsn.at(0,'lat').asnumber; result.long:= jsn.at(0,'lon').asnumber; result.descript:= Format('Coords: lat %2.5f lng %2.5f %s place_id: %d', [result.lat,result.long,jsn.at(0,'display_name').asstring, jsn.at(0,'place_id').asinteger]); end else Writeln('APIError '+inttostr(Httpreq.Response.StatusCode2)); //StrReplace(httpres, '[{', '{'); finally writeln('Status3: '+gethttpcod(httpreq.Response.statuscode2)) httpreq.Free; sleep(200) jsn.Free; end; end; 

McJson use a Simple Object-Pascal native code using TList as internal data structure with a Single-pass string parser and is just one unit (McJSON) and just one class(TMcJsonItem) integrated in maXbox.

Status3: SC_OK
debug back [{
"place_id": 56362293, "licence": "Data B) OpenStreetMap contributors, ODbL 1.0. http:\/\/osm.org\/copyright", "osm_type": "relation", "osm_id": 1676328,
"lat": "46.5576439", "lon": "15.6455854",
"class": "boundary", "type": "administrative",
"place_rank": 16, "importance": 0.5929484692666679,
"addresstype": "municipality",
"name": "Maribor", "display_name": "Maribor, Slovenija",
"boundingbox": ["46.4994068","46.6342916","15.5169925","15.7722677"
]
}
]
Status3: SC_OK

RAD Studio 10.4 Sydney brings support for working with web content through the Chromium-based Edge WebView2 browser control in VCL applications via the new TEdgeBrowser component.

TEdgeBrowser requires access to WebView2Loader.dll for it to work. I’m guessing this is what you might be missing in older project. 

Geo Tracking Solution

Geo Tracking Post Logistic Test III
Geo Tracking Post Logistic Test IV
 loadFMXForm(); //function TAddressGeoCodeOSM5 is now internal precompiled > V51470 //latlong:= TAddressGeoCodeOSM5('Hauptbahnhof, Graz, Austria'); writeln('OSM _from: '+f_latlong.descript); writeln('OSM _to: '+t_latlong.descript); writeln('get geocoords: '+format(' lat: %.4f - lon: %.4f',[t_latlong.lat,t_latlong.long])); coords.caption:= coords.caption+format(' Dest: lat: %.4f - lon: %.4f',[t_latlong.lat,t_latlong.long]); OpenWeb('https://www.latlong.net/c/?lat='+flots(t_latlong.lat)+'&long='+flots(t_latlong.long)); loadWebform(); WebBrowser1.Navigate('https://wttr.in/Ljubljana'); 
Modern Weather Report Map

mX5.1.4.98 XII

The latitude 46.6320803 and longitude 14.144223381010908 shown on map. Picture: Max K.
GPS coordinates: 46° 37′ 55.4891” N 14° 8′ 39.2042” E

GPS coordinates: 46° 37′ 12.6595” N 14° 19′ 31.4436” E
Weather Report GPS coordinates: 46° 37′ 55.4891” N 14° 8′ 39.2042” E
OpenStreetMap Weather Report GPS coordinates: 46° 37′ 55.4891” N 14° 8′ 39.2042” E

Python 3.12.x 64-bit in maXbox5.1

Normally it shuts down after one run, so you have to set autofinalize:= false

 with TPythonEngine.Create(Nil) do begin //pythonhome:= PYHOME64; optional //opendll(PYDLL64) loadDLL; autofinalize:= false; try 
Matplotlib 3.9.0 as py -3.12 -m pip install -U matplotlib
Updated Pandas 2.2.2

Codemap in maXbox5

The extension functionality is straightforward. Just click the code map item code search <Ctrl F3> and it will trigger the navigation to the document where the corresponding code element / block is defined in the document and you can just load a new script by dblclick.

Unicode Codemap 5
Unicode Codemap 5 II
Lemaco CC 40110 Blason Nice
CC 40110 on stage
CC 40101 from RailPic
4 Nations Locs SNCF CC 6510 – SBB 10101 – DB E 10 158 – ÖBB 1042.10
Pink Floyd: This is the peak of music itself, it literally can´t go any higher than this
Last Picture I got with N. Wirth from 2023
EKON 28 2024
Breisach, July 2024
Elsass: S.A.C.M. Elsässische Maschinenbauanstalt Graffenstaden C-Kuppler (2x) – Baujahr 1900, Pic: Max
Wurmlingen /Tübingen 18.08.2024
V 218 Lokomotive 218 105-5 der Westfrankenbahn in Aschaffenburg und V 200 035

AsciiShape

The main difference between this implementation and others is the ability to specify colors of the shapes. After the shape you can define as much colors then the number of shapes in the picture.

https://sourceforge.net/projects/maxbox/files/Examples/13_General/1327_ascii_shape_imageMain_demo1.pas/download

An other difference with the original code is that the lines do not need to be all equals in lenght, the largest one define the final image width.

RAD Studio 12.1

Python & Pascal executed
EKON Samples from the Archive

Modern Regex

The king of code is back, namely regular expressions as the Rex of Code in scripts.

TPerlRegEx is a Delphi VCL wrapper around the open-source PCRE (Perl-Compatible  Regular Expressions) library. It provides powerful regular expression capabilities similar to those found in the Perl or Python programming language. This version of TPerlRegEx is compatible with the TPerlRegEx class in the RegularExpressionsCore unit in Delphi XE. You can use TPerlRegEx to perform pattern matching, search, and replace operations using regular expressions.

The supplied pcrelib.dll contains PCRE 7.9, compiled with Unicode support.

Compiled with a makefile in maXbox5 for example

By default, OBJ files are used (like above), but you can use the DLL if you have multiple apps using TPerlRegEx and want to save space by linking the OBJ files only once. There’s no need to add the pcre unit to your uses clause; it’s used internally by TPerlRegEx. TPerlRegEx is licensed under the Mozilla Public License, version 1.1. To download the latest version of TPerlRegEx, visit the official page.

https://www.pcre.org/original/doc/html/pcre16.html

Starting with release 8.30, it is possible to compile a PCRE library that supports 16-bit character strings, including UTF-16 strings, as well as or instead of the original 8-bit library. The majority of the work to make this possible was done by Zoltan Herczeg. The two libraries contain identical sets of functions, used in exactly the same way. Only the names of the functions and the data types of their arguments and results are different.

To avoid over-complication and reduce the documentation maintenance load, most of the PCRE documentation describes the 8-bit library, with only occasional references to the 16-bit library.

Usage Example:

 var reg: TPerlRegEx; begin reg := TPerlRegEx.Create(nil); try reg.RegEx := 'ab'; reg.Replacement := '◆'; reg.Subject := 'ababab'; reg.ReplaceAll; ShowMessage(reg.Subject); // Returns: ◆◆◆ finally reg.Free; end; end; 

Or you want to replace a pattern-string at the fly or at runtime:

 with TPerlRegEx.Create do try Subject :='<p>This is text.<br/> This is line 2</p>'; RegEx := '<[^>]*>'; //RegEx:= '([</pbr>])*' replacement:= ' '; replaceall(); writeln('res: '+subject); finally Free; end; 

The output is: res: This is text. This is line 2

A more modern implementation is to code with a TMatch and TMatchCollection class. This example demonstrates the use of TMatchCollection and TGroupCollection. This example assumes that you have placed a TButton, a TEdit and a TMemo on a form.

 var Form1: TForm1; mycoll: TMatchCollection; myenum: TMatchCollectionEnumerator; implementation {$R *.dfm} // Creates and lists the match collection, the matches in that // collection and the groups in those matches. procedure TForm1.Button1Click(Sender: TObject); const bigString = 'Look for a the strings in this strang of strungs.'; littlestring = '(str)([iau]ng)'; var regex: TRegEx; i, j: integer; mygrps: TGroupCollection; begin regex:= TRegEx.Create(littlestring); mycoll:= regex.Matches(bigString); Edit1.Text:= 'Count: ' + IntToStr(mycoll.Count); memo1.Lines.Add('First Collection: '); for i:= 0 to mycoll.Count-1 do begin memo1.Lines.Add('Match #' + IntToStr(i) + ': ' + mycoll.Item[i].Value); memo1.Lines.Add('Group: ' + IntToStr(i)); mygrps:= mycoll.Item[i].Groups; for j:= 0 to mygrps.Count-1 do memo1.Lines.Add('Value: ' + mygrps.Item[j].Value); end; end; 
Code as script: https://sourceforge.net/projects/maxbox/files/Examples/13_General/646_pi_evil2_64_12.TXT/download

The item of a TMatchCollection returns the Match identified by index from the collection (ex. tmatches[it-1].value] below).

https://docwiki.embarcadero.com/CodeExamples/Alexandria/en/TMatchCollectionCount_(Delphi)

In general matches from a TRegEx returns all the matches present in the input string an is useful to iterate through a group or captured group:

 function getMatchString2(arex, atext: string): string; var Match: TMatch; tMatches: TMatchCollection; myenum: TMatchCollectionEnumerator; begin with TRegEx.Create1(arex) do try it:= 0; { Match format search...} result:= result+CRLF; if ismatch(atext) then tMatches:=Matches(aText); writeln('captured groups: '+itoa(tmatches.count )); repeat Inc(it); result:= result+Format(#09'%d: %-12s',[it, tmatches[it-1].value]) if it mod 5=0 then result:= result+#13#10; //until match(atext).success; //MatchNext < 0; until it = tmatches.count; finally Free; end; WriteLn('Done REX2 - Hit NOthing to exit'); end; 
PI EXplore5:
1: 33 2: 88 3: 99 4: 44 5: 99
6: 11 7: 66 8: 44 9: 55 10: 22
11: 111 12: 11 13: 555 14: 44 15: 22
16: 44 17: 88 18: 66 19: 33 20: 44
21: 33 22: 66 23: 66 24: 33 25: 00
26: 66 27: 55 28: 88 29: 88 30: 00
31: 11 32: 33 33: 88 34: 66 35: 11
36: 33 37: 11 38: 11 39: 11 40: 44
41: 99 42: 88 43: 22 44: 11 45: 33
46: 33 47: 44 48: 66 49: 22 50: 77
51: 66 52: 000 53: 77 54: 77 55: 77
56: 44 57: 22 58: 22 59: 99 60: 11
61: 44 62: 77 63: 77 64: 99 65: 11
66: 999999 67: 99 68: 44 69: 55 70: 22
71: 33 72: 44 73: 11 74: 88 75: 000
76: 88 77: 33 78: 77 79: 66 80: 55
81: 11 82: 88 83: 77 84: 77 85: 22
86: 66 87: 00 88: 66 89: 111

Matches returns all the matches present in the Input string in the form of a TMatchCollection instance. If the Pattern parameter is not present the regular expression used is specified in the TRegEx constructor.

StartPos specifies the starting position to start the search. TMatchCollection has no public constructor. It is created as the return value of the Matches method. The collection is populated with one TMatch instance for each match found in the input string. The Count property is the length of the TMatchCollection set. Length specifies the substring, starting at StartPos to match with the regular expressions.

Group Collection

TMatchCollection has no public constructor. It is created as the return value of the Matches method. A collection is populated with one TMatch instance for each match found in input string.

A collection of groups as the result of a match with a single regular expression. A regular expression pattern can include subpatterns, which are defined by enclosing a portion of the regular expression pattern in parentheses. Every such subpattern captures a subexpression or group. 

 var mygrps: TGroupCollection; regEx:=TRegEx.create('"common":"[\w]*(su)*',[rroNotEmpty,rrosingleline]); mycoll:= regex.Matches(envlist.text); writeln('Count: ' + IntToStr(mycoll.Count)); // Execute search3 ot TMatchCollection for it:= 0 to mycoll.count-1 do begin writeln(itoa(it)+':'+(mycoll.Item[it].Value)); mygrps:= mycoll.Item[it].Groups; for j := 0 to mygrps.Count-1 do writeln('Value: ' + mygrps.Item[j].Value); end; regex.Free; envlist.Free; //*) 

Performance Object versus Static

The source for TRegEx.IsMatch(const Input, Pattern: string; Options: TRegExOptions) shows that a TRegEx is created at every invocation (which is a costly operation):

 procedure TForm1Button1ClickRegExPerformance1(Sender: TObject); var i: integer; t1, t2: cardinal; arex: TRegEx; begin t1 := GetTickCount; arex:= TRegEx.Create1('') for i:= 1 to 100000 do arex.IsMatch3('abcdef', 'cd', [rroIgnoreCase]); t2:= GetTickCount; writeln('rextime1: '+IntToStr(t2-t1)+' ms'); end; 

This version of TPerlRegEx is compatible with the TPerlRegEx class in the RegularExpressionsCore unit in Delphi XE. In fact, the unit in Delphi XE is derived from the version of TPerlRegEx that you are using now.
This new version of TPerlRegEx descends from TObject. There are no packages to install into Delphi and nothing appears on the component palette. Simply add PerlRegEx to the uses clause of any units you want to use it in. There’s no need to add the pcre unit to the uses clause. This unit is used internally by TPerlRegEx.

 procedure TForm1Button2ClickRegExPerformance2(Sender: TObject); var i: integer; t1, t2: cardinal; LRegEx: TRegEx; begin t1 := GetTickCount; LRegEx:= TRegEx.Create('cd', [rroIgnoreCase]); processmessagesOFF; for i := 1 to 100000 do LRegEx.IsMatch('abcdef'); processmessagesON; t2 := GetTickCount; writeln('rextime2: '+IntToStr(t2-t1)+' ms'); lregex.free; end; 
rextime1: 3628 ms
rextime2: 176 ms
1: Start
<Word1>
End
2: Start
<Word2>
End
TEE Trio as SNCF CC 6500
CC 6516 Roco

EKON 28

Use modern RegEx
When you start building scripts and apps, you are often faced with almost the same problems. Instead of laboriously constructing loops and queries, we look at the use of modern RegEx in Delphi and Python. Modern refers to 64-bit and Unicode, and pattern matching and stemming are also in demand in AI development or the Human Genome Project. Google, for example, probably uses an analogous process for organic search. Tips and tricks from the PCRE round off the express.

PCRE RegEx

Integrate Google Maps API.
The Google Directions API and Maps (Earth) are two powerful tools that can be used to calculate and visualize directions and routing between locations using various modes of transportation. The Google Maps Platform is also demonstrated with geocoding, I create a Trip Advisor project to then manage services, credentials, calculations, maps, coordinates in APIs and SDKs.

Google Directions
The latitude 46.6320803 and longitude 14.144223381010908 shown on map. Picture: Max K.
GPS coordinates: 46° 37′ 55.4891” N 14° 8′ 39.2042” E

GPS coordinates: 46° 37′ 12.6595” N 14° 19′ 31.4436” E

Sorry, we processed more than 1M requests today and we ran out of our datasource capacity. We hope to solve the problem as soon as possible, so you can enjoy your favourite weather service 24×365 even if it rains or snows. We will solve the problem as soon as possible. Follow @igor_chubin for the updates. If you like to code (and you surely do), you can check the wttr.in repository to see how the scalability problem is (not yet) solved.

Mit einer Fallhöhe von 54 Metern ist der Wildensteiner Wasserfall einer der höchsten freifallenden Wasserfälle Europas.

GPS coordinates: 46° 37′ 55.4891” N 14° 8′ 39.2042” E

http://osm.org/copyright&#8221;,”osm_type”:”node”,”osm_id”:301015385,”lat”:”38.4789855″,”lon”:”22.4940231″,”class”:”place”,”type”:”village”,”place_rank”:19,”importance”:0.2975805605530676,”addresstype”:”village”,”name”:”Δελφοί“,”display_name”:”Δελφοί, Δημοτική Ενότητα Δελφών, Δήμος Δελφών, Περιφερειακή Ενότητα Φωκίδας, Περιφέρεια Στερεάς Ελλάδας, Αποκεντρωμένη Διοίκηση Θεσσαλίας – Στερεάς Ελλάδος, 330 54, Ελλάς”,”boundingbox”:[“38.4589855″,”38.4989855″,”22.4740231″,”22.5140231”]}]

Δελφοί lat”:”38.4789855″,”lon”:”22.4940231
Greek Resource Mapbox

Post API Image Pipeline

The Object Detection API provides fast and accurate image object recognition using advanced neural networks developed by machine learning experts and pretrained models.

First we send an input image by Post (PostMultipartFormDataStream), return a list of detected objects labels, confidence percentages and bounding boxes. Objects with confidence less than 0.3 (30%) are filtered out. The image we get with the first step of the pipeline:

 function GEO_to_text_API2_randimage2(AURL, url_name, aApikey: string): string; var httpq: THttpConnectionWinInet; rets: TMemoryStream; heads: TStrings; iht: IHttpConnection; Decoder: TIdDecoderMIME; begin httpq:= THttpConnectionWinInet.Create(true); rets:= TMemoryStream.create; heads:= TStringlist.create; try heads.add('X-Api-Key='+aAPIkey); heads.add('Accept=image/jpg'); iht:= httpq.setHeaders(heads); httpq.Get(Format(AURL,[urlencode(url_name)]), rets); if httpq.getresponsecode=200 then begin rets.Position:= 0; //ALMimeBase64decodeStream(rets, rets2) rets.savetofile((exepath+'randimage0.jpg')); openfile(exepath+'randimage0.jpg'); end else result:='Failed:'+ itoa(Httpq.getresponsecode)+Httpq.GetResponseHeader('message'); except writeln('EWI_HTTP: '+ExceptiontoString(exceptiontype,exceptionparam)); finally httpq:= Nil; heads.Free; rets.Free; end; end; //} 

The Random Image API generates random images for all your placeholder and design needs. It Returns a random, base64-encoded image in JPEG format. Don’t forget to set the Accept Header otherwise you have to decode with ALMimeBase64decodeStream. The Accept (required) – header indicating the content type to accept in the result. Must be set to the following: image/jpg.

The Randimage we get

Second step is to post the image for object-detection.

https://api-ninjas.com/api/objectdetection

The image (required) – must be an input image file. Must be either JPEG or PNG format and smaller than 2000 by 2000. Also the X-Api-Key (required) – API Key associated with your account.

 Procedure PyCodeObjectDetect(imgpath, aAPIKey: string); begin with TPythonEngine.Create(Nil) do begin //pythonhome:= 'C:\Users\User\AppData\Local\Programs\Python\Python312\'; try loadDLL; ExecString('import requests'); ExecStr('url= "https://api.api-ninjas.com/v1/objectdetection"'); ExecStr('image_file_descriptor = open("'+imgpath+'", "rb")'); ExecStr('headers= {"X-Api-Key": "'+aAPIKey+'"}'); ExecStr('files = {"image": image_file_descriptor} '); ExecStr('r=requests.post(url, headers=headers, files=files)'); println(EvalStr('r.json()')); except raiseError; finally free; end; end; end; 

Behind the is the complicated configuration of a multipartformdata mechanism. On the other hand, multipart/form-data is the encoding used when an HTML form has a file upload field. When you make a POST request, you have to encode the data that forms the body of the request in some way.

  • application/x-www-form-urlencoded is more or less the same as a query string on the end of the URL.
  • multipart/form-data is significantly more complicated but it allows entire files to be included in the data.
  • multipart/form-data: adds a few bytes of boundary overhead to the message, and must spend some time calculating it, but sends each byte in one byte.
 Procedure PostMultipartFormData(const aUrl:AnsiString; const aRequestFields: TALStrings; const aRequestFiles: TALMultiPartFormDataContents; const aResponseContent: TStream; const aResponseHeader: TALHTTPResponseHeader2; const ARequestHeaderValues: TALNameValueArray = nil); overload; https://code-maze.com/aspnetcore-multipart-form-data-in-httpclient/ 

Then we send the request and get the following JSON result of the detector (Sample Response):

[{‘label’: ‘boat‘, ‘confidence’: ‘0.52’, ‘bounding_box’: {‘x1’: ‘308’, ‘y1’: ‘179’, ‘x2’: ‘527’, ‘y2’: ‘328’}}, {‘label’: ‘umbrella’, ‘confidence’: ‘0.46’, ‘bounding_box’: {‘x1’: ‘308’, ‘y1’: ‘179’, ‘x2’: ‘527’, ‘y2’: ‘328’}}, {‘label’: ‘boat’, ‘confidence’: ‘0.34’, ‘bounding_box’: {‘x1’: ‘385’, ‘y1’: ‘277’, ‘x2’: ‘425’, ‘y2’: ‘295’}}, {‘label’: ‘bed’, ‘confidence’: ‘0.32’, ‘bounding_box’: {‘x1′: ’10’, ‘y1′: ’14’, ‘x2’: ‘630’, ‘y2’: ‘449’}}, {‘label’: ‘boat’, ‘confidence’: ‘0.31’, ‘bounding_box’: {‘x1’: ‘384’, ‘y1’: ‘285’, ‘x2’: ‘426’, ‘y2’: ‘298’}}, {‘label’: ‘cat’, ‘confidence’: ‘0.31’, ‘bounding_box’: {‘x1’: ‘9’, ‘y1′: ’15’, ‘x2’: ‘630’, ‘y2’: ‘449’}}, {‘label’: ‘person‘, ‘confidence’: ‘0.3’, ‘bounding_box’: {‘x1’: ‘8’, ‘y1′: ’11’, ‘x2’: ‘633’, ‘y2’: ‘444’}}]

Yes we can see the boat and the small person, the umbrella maybe a false positive of the cave. A cat or a bed could be an imagination. We also have a false negative, the unseen sea or sky. Also a live demo is available:

Live API Demo

You can use a late binding with an OleObject and OleVariants of :WinHttp.WinHttpRequest

https://api-ninjas.com/api/textsimilarity

 function TextSimilarity_API6(AURL, url_name, aApikey: string): string; var httpReq,hr: Olevariant; JPostdatabody: string; jo: TJSON; begin Result:= ''; JPostDataBody:= '{' + '"text_1": "gpt-3.5-turbo-instruct",'+ //'"prompt": "%s",'+ '"text_2": "gpt-3.5-turbo-instruct777"'+ '}'; // Use JSON for REST API calls and set API KEY via requestheader httpReq:= CreateOleObject('WinHttp.WinHttpRequest.5.1'); jo:= TJSON.Create(); try hr:= httpReq.Open('POST', AURL, false); httpReq.setRequestheader('user-agent',SUSERAGENT); // Select HTTPS POST method, set POST data, specify endpoint URL httpReq.setRequestheader('content-type','application/json'); httpReq.setRequestheader('X-Api-Key',aApikey); if hr= S_OK then HttpReq.Send(JPostDataBody); If HttpReq.Status = 200 Then result:= HttpReq.responseText Else result:= 'Failed getresponse:'+itoa(HttpReq.Status)+HttpReq.responseText; // writeln('debug response '+HttpReq.GetAllResponseHeaders); // Process returned JSON when request was successful jo.parse(result) result:='Answer2similarity: '+jo.values['similarity'].asstring; finally jo.Free; httpreq:= unassigned; end; end; 

Answer2similarity: 0.911304295063019
True
mX5🐞 executed: 17/04/2024 20:40:42 Runtime: 0:0:3.895 Memload: 71% use
RemObjects Pascal Script. Copyright (c) 2004-2024 by RemObjects Software & maXbox5

BR V221 TEE Merkur, Rheingold
Liliput 1042
TEE Adriatico with TEE Le Rhodanien

AGSI Update

 function getEnergyStreamJSON21(AURL, feedstream, aApikey: string): string; var encodURL: string; httpRq,hr: Olevariant; asp: TStringArray; begin httpRq:= CreateOleObject('WinHttp.WinHttpRequest.5.1'); // Opens HTTPs connection. try asp:= splitStr(feedstream,','); encodURL:= Format(AURL,[HTTPEncode(asp[0]),(asp[1]),asp[2]]); writeln(encodurl) hr:= httpRq.Open('GET', encodURL, false); httpRq.setRequestheader('user-agent',USERAGENTE); httpRq.setRequestheader('x-key',aAPIkey); if hr= S_OK then HttpRq.Send(); If HttpRq.Status = 200 Then result:= HttpRq.responseText Else result:= 'Failed getting response:'+itoa(HttpRq.Status)+HttpRq.responseText; //writeln('debug response: '+HttpReq.GetAllResponseHeaders); except writeln('Error: '+HttpRq.responseText); writeln('EHTTP: '+ExceptiontoString(exceptiontype, exceptionparam)); finally httprq:= unassigned; end; end; 
AGSI Update
HttpResponse:= getEnergyStreamJSON21(URL_AGSIAPI2,’DE,2024-03-15,200′,AGSI_APIKEY);
View3D := true;

The future of gas storage: green hydrogen

Gas storage could also play an important role in the energy system of the future. If we switch completely to renewable energies as part of the energy transition, balancing demand is absolutely necessary. This is because renewable energies such as wind and solar depend on the weather.

When wind conditions are favorable or when the sun shines often, more energy is generated than is currently needed. At other times, energy is needed even though none is currently being produced. The production and consumption of energy must therefore be decoupled in time in order to be able to cover energy needs at all times. However, electricity cannot currently be stored in large quantities and for long periods of time – the longer-term storage of hydrogen, on the other hand, is possible.

The excess green electricity from volatile wind and solar energy could be converted into green hydrogen in a power-to-gas (PtG) plant and fed into the gas storage facilities. At peak demand, when more energy is needed, the hydrogen from the gas storage facilities could be converted back into electricity and fed into the power grid.

A research project entitled “Storing hydrogen – that much is certain”, in which GASAG is also involved, has examined the gas storage facilities in Germany for their suitability for hydrogen storage. The result: all cavern storage facilities and four of the pore storage facilities in Germany are – after the necessary conversions – available for storing hydrogen. This would be another step towards the energy transition.

https://www.gasag.de/magazin/neudenken/wie-funktioniert-ein-gasspeicher

Geocoding IV

Just like every actual house has its address (which includes the number, the name of the street, city), every single point on the surface of earth can be specified by the latitude and longitude coordinates (lat & long).

So how we did this? With the OpenStreetMap API Nominatim and maXbox5.

The OSM Nominatim is a search engine for OpenStreetMap data. From this site you may search for a name or address (like Bahnhof, Graz, Austria), or look up place names by geographic coordinates. Each result will link to details page where you can inspect what data about the object is saved in the database and investigate how the address of the object has been computed (URI and JSON for example):

 type Tlatlong = record lat, long: double; descript: string; end; function TAddressGeoCodeOSM5(faddress: string): Tlatlong; var url, res, display: string; jo: TJSONObject; urlid: TIduri; winapi: TWinApiDownload; begin urlid:= TIdURI.create(''); url:= urlid.URLEncode('https://nominatim.openstreetmap.org/search?format=json&q='+ fAddress); winapi:= TWinApiDownload.create; winapi.useragent:= 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1'; winapi.url:= url; writeln('check url: '+itoa(winapi.CheckURL(url))); winapi.download1(res); if (res <> '') and (res <> '[]') then begin //windown.OnWorkStart StrReplace(res, '[{', '{'); jo:= TJSONObject.create4(res); try if jo.getString('place_id') <> ' ' then display:= jo.getstring('display_name'); result.descript:= Format('Coords: lat %2.5f lng %2.5f %s place_id: %d', [jo.getdouble('lat'),jo.getdouble('lon'),display, jo.getint('place_id')]); result.lat:= jo.getdouble('lat'); result.long:= jo.getdouble('lon'); except writeln('Geo E: '+ExceptiontoString(exceptiontype, exceptionparam)); finally jo.Free; urlid.free; winapi.free; end; end else showmessagebig('OSM geo location not found! '); end; 
Testunit From Cologne to Graz

I use an URI, a struct Tlatlong, a JSON and a HTTPGet object and call the function from the main:

writeln(‘res back_: ‘+TAddressGeoCodeOSM5(‘Bonnaud, France’));

 latlong:= TAddressGeoCodeOSM5('Hauptbahnhof, Graz, Austria'); writeln('OSM5 res back_: '+latlong.descript); >>> OSM5 res back_: Coords: lat 47.07391 lng 15.41681 Hauptbahnhof, Europaplatz, Smart City, Lend, Graz, Steiermark, 8020, Österreich place_id: 56301250 writeln('get geoCoords: '+format(' lat: %.4f - lon: %.4f',[latlong.lat,latlong.long])); OpenWeb('https://www.latlong.net/c/?lat='+flots(latlong.lat)+'&long='+flots(latlong.long)); 

You should in particular verify that you have set a custom HTTP referrer or HTTP user agent ( windown.useragent:=) that identifies your application, and that you are not overusing the service with massive bulk requests. Otherwise you get following message:

<p>You have been blocked because you have violated the<a href=”https://operations.osmfoundation.org/policies/nominatim/”>usage policy</a>of OSM’s Nominatim geocoding service. Please be aware that OSM’s resources are limited and shared between many users. The usage policy is there to ensure that the service remains usable for everybody.</p>

Fusion of OpenStreetMap with Google Maps Directions (OSM&GMD)

You can get directions for driving, public transit, walking, ride sharing, cycling, flight, or motorcycle on Google Maps. If there are multiple routes, the best route to your destination is blue, all other routes are gray. Some directions in Google Maps are in development and may have limited availability. 

Now we pass the coordinates of two locations , for example Cologne to Graz, in a automated script and call the computed link in a browser.

Script Ref: http://www.softwareschule.ch/examples/directions3.htm

Testunit From Cologne to Graz
         get geocoords:  lat: 50.9473 – lon: 6.9503 Cologne
         get geocoords:  lat: 47.0739 – lon: 15.4168  Graz

latlong:=  TAddressGeoCodeOSM(‘Gereonswall 66, Cologne, Germany’);
latlong:=  TAddressGeoCodeOSM(‘Hauptbahnhof, Graz, Austria’);

UnitTest GeoCode
The result of open the computed link (go to google) from the script

Behind the scene from click to link:

 procedure TDirectionsBtnGoGoogleClick(Sender: TObject); Var LocFrom,LocTo:RNavigateLongLat; Long,Lat:Double; begin LocFrom:=RNavigateLongLat.create; Locto:=RNavigateLongLat.create; Long:=RealFrmDegreeText(EdtLong.Text); Lat:= RealFrmDegreeText(EdtLat.Text); LocFrom.CreateDec(Long,Lat); Long:=RealFrmDegreeText(EdtLong2.Text); Lat:= RealFrmDegreeText(EdtLat2.Text); LocTo.CreateDec(Long,Lat); // { 0 Start 1 End 3 Center } EdtGoogleLink.Text:=LocFrom.GoogleLinkDirectionsTo(LocTo, 0); LBlCrowFlies.Caption:='Distance as CrowFlys = '+FormatFloat('0.0km',LocTo.MetresFrom(LocFrom)/1000); if CBxGoNow.Checked then LocFrom.GoGoogleDirectionsTo(LocTo, 0); end; 

Important: Stay alert when you use directions on Google Maps. Always be aware of your surroundings to ensure the safety of yourself and others. When in doubt, follow actual traffic regulations and confirm signage from the road or path that you’re on.

Max Kleiner, 06/03/2024

Geo Ref Directions

Testunit From Cologne to Graz
get geocoords: lat: 50.9473 – lon: 6.9503 Cologne
get geocoords: lat: 47.0739 – lon: 15.4168 Graz

latlong:= TAddressGeoCodeOSM(‘Gereonswall 66, Cologne, Germany’);
latlong:= TAddressGeoCodeOSM(‘Hauptbahnhof, Graz, Austria’);

UnitTest GeoCode

https://www.google.com/maps/dir/050.94730,006.95031/047.07389,015.41674/@050.94730,006.95031,9z

Dole get geocoords: lat: 47.0948 — lon: 5.49728 Dole
Dole Jardin
Dole Jardin II
TEE & TEN Directions Map
Jouef CC 6511 & 6512
LS Models CC 6505
TEE 5 Nations Locs SNCF-DB-SBB-FS-ÖBB

Winter Melody Kandersteg 07/03/2024

Geocoding is very important in many fields, like real estate, finance, and logistics. Without this technique, you can’t be able to analyze and visualize the data into a map. 

XN in maXbox5 as Geocode Mapper

The aliquot sum is the sum of the aliquot divisors so, for example, the aliquot divisors of 12 are 1, 2, 3, 4, and 6 and it’s aliquot sum is 16.    A number whose aliquot sum equals its value is a PERFECT number (6 for example). 

AliquotSums is a  program that will let you search for Perfect, Amicable and Sociable numbers, including one remarkable cycle 28 numbers in length.

Up to 100000
 {***************** TForm1.AliquotSum **************} function AliquotSum(n:int64):int64; {calculate an aliquot sum for n} var i:integer; p:array [0..Maxfactors] of integer; e:array [1..Maxfactors] of integer; nf:integer; pfactors: Array of int64; begin //writeln('factors1 '+itoa(n)) primes.getfactors(n); {get unique prime factors and powers} nf:=0; p[1]:=0; e[1]:=0; result:=0; //setlength(pfactors, 101) //writeln('factors2 '+itoa(primes.nbrfactors)) if primes.nbrfactors> maxfactors then showmessage('Number '+inttostr(n)+ ' has more than '+inttostr(maxint) +' factors , program change required') else begin for i:= 1 to primes.nbrfactors do begin pfactors:= primes.factors; //writeln(itoa(pfactors[i])) if (nf>0) and (pfactors[i]=p[nf]) //bugfix p init as 0 or nf+1 then inc(e[nf]) else begin inc(nf); pfactors:= primes.factors; //p[nf]:=primes.factors[i]; p[nf]:=pfactors[i]; e[nf]:=2;//} end; end; result:=1; try for i:= 1 to nf do if p[i]<>1 then result:=result*round(power(p[i],e[i])-1) div (p[i]-1); except result:=n; end; result:=result-n; end; //*) end; 
Dole TGV Travel Magic

“I knew from the start that I was bound to be crucified either way I moved. If I left the woman I really loved — the Great Society — in order to get involved in that bitch of a war on the other side of the world, then I would lose everything at home. All my programs. … But if I left that war and let the Communists 
take over South Vietnam, then I would be seen as a coward and my nation would be seen as 
an appeaser and we would both find it impossible to accomplish anything for anybody 
anywhere on the entire globe.”bv Lyndon B. Johnson

MultipartFormDataStream can result in a Bad Request (400)

EKON 27

With its exquisite interior and exclusive service, the Hotel Meliá Düsseldorf is the ideal choice for your conference stay. It is located in the immediate vicinity of the Hofgarten, the oldest public park in Germany. Trendy restaurants and bars, the old town and the famous shopping street Königsallee (“Kö”) can be reached in a few minutes from maXbox4 to maXbox5 ;-).

EKON 27 Profile
EKON 27 Talks

This is a small Project about Neural Networks and Back-propagation. It uses de MNIST Database to learn how to recognize Handwriting. The whole Neural Network was built up from scratch in Delphi 10.2 and maXbox4 with no external libraries. The Implementation still needs to get tweaked at some points, for example that the Network stops if it’s just memorizing the input data, or that its automatically calculates the validation accuracy.

https://entwickler-konferenz.de/speaker/max-kleiner/

1. The MachineLearning Package presented

MLP for Delphi and Lazarus is an open source package with MachineLearning examples and demos that combines modern machine learning interpretation techniques like CNN or KMeans under one directory. With this package you can train interpretative glass box models and try to explain black box systems. MLP helps to understand the global behavior of the model or the reasons for individual predictions. We take a bit look inside the black box.

MLP with Delphi, Lazarus and maXbox on the same script

NN-SVG is a tool to sketch out the architecture of your neural networks using a few buttons and sliders.

It supports building classic DNN architectures or CNNs with max pooling and dropout layers.

Avatarify is a project for swapping your face with anyone you like on Zoom and Skype. Apart from the initial fun of it, you might be interested in the implementation of the project.

Person Detector with false positive and false negative
EKON 27 Live Experience Person Detector

C:\Program Files\Streaming\IBZ2021\Module2_3\EKON27\992_oma_objectdetector21.py:54: DeprecationWarning: ‘detectCustomObjectsFromImage()’ function has been deprecated and will be removed in future versions of ImageAI.
Kindly use ‘detectObjectsFromImage()’
detections=detector.detectCustomObjectsFromImage(custom_objects=custom, \
this first line fine
person : 80.82948923110962
person : 69.58852410316467
chair : 70.0934886932373
person : 63.592731952667236
person : 66.48526191711426
laptop : 63.93558382987976
person : 67.9198682308197
person : 64.5257830619812
bottle : 93.70498657226562
integrate image detector compute ends…

elapsedSeconds:= 14.045784900000

Stop with Return Key—>

out from maXbox5 console
Second Session from Object Detector

Kindly use ‘detectObjectsFromImage()’
detections=detector.detectCustomObjectsFromImage(custom_objects=custom, \
this first line fine
person : 80.82948923110962
person : 69.58852410316467
chair : 57.98184275627136
chair : 70.0934886932373
person : 63.592731952667236
person : 66.48526191711426
laptop : 63.93558382987976
person : 67.9198682308197
person : 56.174236536026
person : 64.5257830619812
laptop : 50.28797388076782
bottle : 93.70498657226562
bottle : 55.75599670410156
integrate image detector compute ends…

second output I/O error 6
no console attached..
mX5 executed: 06/11/2023 18:19:49 Runtime: 0:0:24.221 Memload: 54% use

elapsedSeconds:= 20.520187500000

Kindly use ‘detectObjectsFromImage()’
detections=detector.detectCustomObjectsFromImage(custom_objects=custom, \
this first line fine
person : 58.7100088596344
person : 92.42247343063354
person : 64.66829180717468
person : 70.5344557762146
person : 53.462618589401245
integrate image detector compute ends…

elapsedSeconds:= 9.331543800000

Pempelfort is a city part in the North-east of the central Borough 1 of Düsseldorf. It borders on Stadtmitte, Derendorf, the Cologne–Duisburg railway, connecting Flingern and Düsseltal, Oberbilk, Golzheim and the river Rhine. Pempelfort has 33,137 inhabitants in an area of 2.70 km², or over 12,000 inhabitants per km².

2. Integrate Pas2js transpiler into projects

Pas2js is an open source Pascal to JavaScript transpiler. It parses and interprets Object Pascal and emits JavaScript. The JavaScript currently corresponds to the ECMAScript 5 level and should actually run in any browser or in a Node.js target. We look at the 5 known forms: library, CLI, webserver, node.js and in the browser itself.

Prototype on Kali Linux before publish as js-web-app

http://www.softwareschule.ch/examples/pacman.html

Five Steps to start with Pas2JS

First you change to change to the demo: C:\Program Files\Streaming\maxbox4\examples\pas2js-windows-2.2.0\pas2js-windows-2.2.0\demo\jspdf

Second you trans-pile the basic.lpr to basic.js with a command-line tool

 Const fileName = 'angles_pdf.txt'; pas2jsPATH = 'C:\Program Files\Streaming\maxbox4\examples\pas2js-windows-2.2.0\pas2js-windows-2.2.0\bin\i386-win32\'; //ChangeDir(pas2jsPATH) writeln(GETDOSOutput('cmd.exe /c "'+ pas2jsPATH+'pas2js" -Jc -Jirtl.js -Tbrowser ..\..\demo\jspdf\basic.lpr', pas2jsPATH)); sleep(500) OpenWeb('http://www.softwareschule.ch/examples/basicpdf.html'); 

C:\Program Files\Streaming\maxbox4\examples\pas2js-windows-2.2.0\pas2js-windows-2.2.0\bin\i386-win32>pas2js -Jc -Jirtl.js -Tbrowser ….\demo\jspdf\basic.lpr
Pas2JS Compiler version 2.2.0 [2022/02/22] for Win32 i386
Copyright (c) 2021 Free Pascal team.
Info: 16018 lines in 8 files compiled, 0.1 secs

3. As we can see the target is TBrowser so we upload basicpdf.html and basic.js to the webserver. I just changed the name basic to basicpdf.html.

4. Then we call in the browser http://www.softwareschule.ch/examples/basicpdf.html

5. We chose an option and download the preset converted pdf:

Demo of pas2js in Webserver

Githack CDN for source code

Direct test and publish js with githack
https://tinyurl.com/maxboxtetris
https://raw.githack.com/breitsch2/maXbox4/master/assets/text2jstester.html#

JavaScript is a useful scripting language which you can incorporate within your Delphi 10.2 Tokyo apps in a number of ways. There are open source, commercial component sets, and libraries which quickly allow you to do this in Delphi or Lazarus. These include JSEngine, Pas2JS, ScriptGate, paxCompiler, v8delphiwrapper, BESEN, and ChakraCore headers.

In about half of the SVG examples I see on the internet, the code is wrapped in plain simple <svg></svg> tags.

The xmlns="http://www.w3.org/2000/svg" attribute is:

  • Required for image/svg+xml files. 1
  • Optional for inlined <svg>. 2
https://raw.githack.com/breitsch2/maXbox4/master/assets/graph2.html

As a non commercial open source project we are always searching for helping hands. If you want to contribute see here.

Leave no one behind.
https://rosettacode.org/wiki/Five_weekends#Delphi

Pixabay API

Stunning royalty-free images & royalty-free stock

Over 4.1 million+ high quality stock images, videos and music shared by our talented community.

 {$I .\PIXABAYAPIKEY.INC} Const BASEURLTXT = 'https://api.deepai.org/api/text-generator'; URLFANTASYTXT = 'https://api.deepai.org/api/fantasy-world-generator'; URLIMAGESTYLE = 'https://api.deepai.org/api/fast-style-transfer'; URLPIXABAY = 'https://pixabay.com/api/?key='+PIXABAY_APIKEY+ '&q=%s&image_type='+ '%s&pretty=true'; function TRestClient3_Pixapay(askstream, imagetype: string; responseHeader:TRestResponseHandler): string; var JPostdat: string; urlid: TIduri; jo: TJSON; rest: TRestResource; begin JPostDat:= '{'+ '"ask": "%s",'+ '"content": "%s",'+ '"style": 0.15}'; with TRestClient.create(self) do begin urlid:= TIdURI.create(''); rest:= Resource(urlid.URLEncode(Format(URLPIXABAY,[askstream,imagetype]))); println('@addr:'+objtostr(rest)) rest.ContentType('application/json'); rest.header('User-Agent',UAGENT); rest.accept('application/json,text/plain; q=0.9, text/html;q=0.8'); ConnectionType:= hctWinInet; OnafterRequest:= @TRestOnRequestEvent2; OnResponse:= @TRestOnResponseEvent2; try jo:= TJSON.Create(); jo.parse(rest.Get()); writeln('return total hits: '+jo.values['totalhits'].asstring) result:=jo.values['hits'].asarray[randomrange(1,20)].asobject['webformatURL'].asstring; finally Free; jo.Free; urlid.Free; except writeln('EWI_Exc:'+ExceptiontoString(exceptiontype,exceptionparam)); end; end; //with end; openWeb(TRestClient3_Pixapay('locomotion','photo', nil)); https://pixabay.com/get/gda5c11dc246815b8884ddff0db08e7d9db5d096aec200fc2c13a4e269bf5f378b377659769ce643c4fea14f8a050bd5c_640.jpg 

CNC milling machine

Conversion of a mini CNC milling machine into a solder paste dispenser for SMD assembly:

If you as a maker not only produce individual pieces, but also occasionally a small series, you cannot avoid an unpopular work step: The application of the SMD soldering paste with a stainless steel template and spatula regularly ends in a blatant mess – from the costs for the (possibly only a few Times used) stencil not to mention. A small, cheap CNC milling machine called the CNC1610 had been sitting around in our Make workshop for many months, and nobody really wanted to use it anymore because of the wobbling spindle motor and the rather unstable construction. This gave us the idea of using a soldering paste dosing syringe instead of the motor so that the paste can be applied programmatically.

 procedure FormCreate(Sender: TObject); var Ini: TIniFile; begin AppFilePath:= ExtractFilePath(Application.ExeName); try ComPort.LoadSettings(stIniFile, AppFilePath + '.\dispenser.ini'); except writeln(ExceptionToString(ExceptionType, ExceptionParam)); end; TForm(sender).icon.loadfromresourcename(hinstance, 'XNETWORK'); SgBlocks.Cells[0, 0]:= '#'; SgBlocks.Cells[1, 0]:= 'Pos X'; SgBlocks.Cells[2, 0]:= 'Pos Y'; SgBlocks.Cells[3, 0]:= 'Aperture'; SgBlocks.Cells[4, 0]:= 'Size X'; SgBlocks.Cells[5, 0]:= 'Size Y'; SgBlocks.Cells[6, 0]:= 'Type'; SgApert.Cells[0, 0]:= '#'; SgApert.Cells[1, 0]:= 'DX'; SgApert.Cells[2, 0]:= 'DY'; SgApert.Cells[3, 0]:= 'Type'; SgApert.Cells[4, 0]:= 'Ena'; SgBlocks.Row:= 1; SgApert.Row:= 1; GerberBitmap:= TBitmap.create; LastFileName:=''; ZeroXok:= false; ZeroYok:= false; ZeroZok:= false; ZeroAllok:= false; Homed:= false; //false; bm_scroll.X:= 0; bm_scroll.Y:= 0; Ini := TIniFile.Create(AppFilePath + '.\dispenser.ini'); try form1.Top:= Ini.ReadInteger('Form', 'Top', 100); form1.Left:= Ini.ReadInteger('Form', 'Left', 100); form1.Height:= Ini.ReadInteger('Form', 'Height', 709); form1.Width:= Ini.ReadInteger('Form', 'Width', 900); EditSavedX.Text:= Ini.ReadString('Positions', 'SavedX', '0.0'); EditSavedY.Text:= Ini.ReadString('Positions', 'SavedY', '0.0'); EditSavedZ.Text:= Ini.ReadString('Positions', 'SavedZ', '0.0'); EditPadTime.Text:= Ini.ReadString('Params', 'PadTime', '50'); EditDwellTime.Text:= Ini.ReadString('Params', 'DwellTime', '230'); Trackbar1.Position:= Ini.ReadInteger('Params', 'Zoom', 7); finally Ini.Free; end; BitBtnCreatePatternClick(nil); end; 

https://github.com/breitsch2/Solder-Paste-Dispenser

Master Thesis 2023

C:\Program Files\Streaming\IBZ2021\Module2_3>py -3.7-32 -m pip install –upgrade pip
Collecting pip
Downloading pip-23.2.1-py3-none-any.whl (2.1 MB)
|████████████████████████████████| 2.1 MB 1.6 MB/s
Installing collected packages: pip
Attempting uninstall: pip
Found existing installation: pip 20.1.1
Uninstalling pip-20.1.1:
Successfully uninstalled pip-20.1.1
Successfully installed pip-23.2.1

C:\Program Files\Streaming\IBZ2021\Module2_3>

Sir Self

** Visual Studio 2019 Developer Command Prompt v16.11.28
** Copyright (c) 2021 Microsoft Corporation


C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools>dir
Volume in drive C is Acer
Volume Serial Number is 0C7D-2BFC

Directory of C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools

26/07/2023 16:14 .
26/07/2023 16:14 ..
26/07/2023 16:14 Common7
26/07/2023 16:13 DIA SDK
26/07/2023 16:14 ImportProjects
26/07/2023 16:14 Licenses
26/07/2023 16:03 MSBuild
26/07/2023 16:12 SDK
26/07/2023 16:13 Team Tools
26/07/2023 16:13 VC
26/07/2023 16:14 VC#
26/07/2023 16:14 Xml
0 File(s) 0 bytes
12 Dir(s) 197,349,670,912 bytes free

C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools>

Sir Build

Work on 64bitbox has first alpha

Python 64bit in a maXbox 64 bit
BPM 113
madExcept at work as circular unit reference sock error with invalid handle
Fleischmann BR 103 113-7
BR 110 126-0
62493 Electric locomotive, class E 10.1 of the DB 110 126-0
733002 Fleischmann N
Märklin 39408 – CC 1804 B
TEE II Wattwil August 2023

CC 21004 with the Mistal69 coaches of TEE 23 Cisalpin is waiting for departure in Paris Gare-de-Lyon. CC 21004 hauls the coaches up to Vallorbe. Swiss and Italian engines replace the CC 21004 in Vallorbe and Domodossola. At the time TEE Mistral (Paris – Marseille – Nice) was still running, within four minutes both TEE trains Cisalpin and Mistral ran one behind the other between Paris and Dijon, covering the 315 km with an average speed of 135 kph. CC 21004 as well as the Mistral69 coaches entered service in 1974. In January 1984 the TEE Cisalpin service with the CC 21000 and the Mistral69 coaches came to an end. Travelers had to use the new introduced TGV-SE service between Paris and Lausanne. Travelers for Brig, Domodossola and Milano had to change trains in Lausanne or to look for an alternative.In October 1996 the CC 21004 was overhauled and came into service as CC 6578 for another 9 years. Before CC 21000 and the Mistral69 coaches took over the TEE Cisalpin in 1974, the Swiss RAe TEE II multi current train sets ran the TEE Cisalpin service between Paris and Milano.

Roco CC-6574
Nazareth Rock of Ages 2023 Seebronn Tübingen Germany
Circular Unit Reference Socks Error (CURSE)

Steps to 64-bit maXbox5

 It can currently handle :- Constants(both with explicit & implicit type),- Global variables are parsed, but no output is generated for them  As I would need to be able to set their value at startup, or generate  getters & setters for them(need info before I can do this)- Normal Delphi routines are properly encaptulatedThe following different types :- simple typing ie 'MyInt = Integer;'- type identity ie 'MyInt =  type Integer;' (it drops the 'type' and then  handles it like simple typing)- method pointers(function pointers are not supported by ifps3)- Enums ie 'MyEnum = (ab,abc);'- sets are correctly parsed- records, and nested records- classes- dynamic arrays only (static arrays are not implemented by the ifps3 to my  knowlage)- On discovering a function marked with the overload directive, it prompts  for a new function name, and then generates wrapper code that maps the  new method name to the original version. Press enter to use the same name  * NVDS> fixed some bug's here.- Some constant expressions cause the parser to get confused  (<constname>=<constname>). It will then prompt for the correct  Expression type (string, integer, char, boolean, etc) 
 This software is provided 'as-is', without any expressed or impliedwarranty. In no event will the author be held liable for any damages arising from the use of this software. 
Fix the Python Engine

I compared sources from 4.0.5 and 4.0.9 and found a diff in method HandleException().
The flag MESettings.SuspendThreads is now checked. It turns out that we had this flag true all the time. We set it back to false and the problem is and had maybe gone!

Ref 64bit with TeeChart, JSONLib and WinHttpRequest.5.1
Full 64 bit on osboxes.org as Kalilinux with 01:07 runtime
V5.0.1.22 another Kali64Linux Session
Pas2JS with maXbox5
Bodensee Friedrichshafen
E-Lok BR 112 DB Ep.IV Rheingold
Python and Pascal Training
V 5.0.1.22 shine as 64-bit-box

mindmaker

ProcessMessages is a function in maXbox4 that is used to process messages sent to the maXbox4 application. It is responsible for handling the messages sent to the application, such as mouse clicks, key presses, and other user input. It also handles messages sent from the application to other parts of the system, such as the graphics engine or sound system. Switching off ProcessMessages! means more speed but less updated events in a message loop.

maXbox4 is a powerful and versatile tool for creating and managing digital content. It offers a wide range of features that make it easier to create, store, and share digital content. It also provides a secure platform for collaboration and communication. The main advantages of Maxbox4 include:

  • Easy to use interface: Maxbox4 has an intuitive user interface that makes it easy to create, store, and share digital content.
  • Secure platform: Maxbox4 provides a secure platform for collaboration and communication. It also offers a range of security features to protect your data.
  • Flexible storage: Maxbox4 offers a range of storage options, including cloud storage, local storage, and external storage.
  • Collaboration tools: Maxbox4 provides a range of collaboration tools, such as chat, file sharing, and task management.
  • Automation tools: Maxbox4 offers a range of automation tools, such as automated workflows and scheduled tasks.

For example to get a QR-code as code:

 const QRCODE='def Qrcode_Maker(data):'+LB+ ' qr = pyqr.QRCode(version=1,box_size=10,border=5)'+LB+ ' qr.add_data(data) '+LB+ ' qr.make(fit=True) '+LB+ ' pic = qr.make_image() '+LB+ ' pic.save("qrcodemx4.png") '; 

Here we first define the function, then we call the main part in Python4maXbox:

 eng.Execstr('import qrcode as pyqr'); eng.Execstr(QRCODE); eng.Execstr('Qrcode_Maker("https://maxbox4.wordpress.com/")'); OpenDoc(exepath+'qrcodemx4.png'); 

Now you can create your own Qrcode with this awesome Python4maXbox script that will let you generate customize Qr Code by using the Qrcode module. This script is helpful when you need to share something or share text data in Qrcode form. Of course you has to install the module first:

C:\Program Files\Streaming\IBZ2021\IBZ_Module1_4_2022\Uebungen2019\Uebungen2019>pip3 install Qrcode Collecting Qrcode Downloading qrcode-7.4.2-py3-none-any.whl (46 kB) |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 46 kB 552 kB/s Requirement already satisfied: colorama; platform_system == "Windows" in c:\users\breitsch\appdata\local\programs\python\python37-32\lib\site-packages (from Qrcode) (0.4.4) Requirement already satisfied: typing-extensions in c:\users\breitsch\appdata\local\programs\python\python37-32\lib\site-packages (from Qrcode) (4.5.0) Collecting pypng Downloading pypng-0.20220715.0-py3-none-any.whl (58 kB) |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 58 kB 2.6 MB/s Installing collected packages: pypng, Qrcode Successfully installed Qrcode-7.4.2 pypng-0.20220715.0
maXbox as Cryptobox in a Sandbox – Falcon Sandbox v9.5.2 © Hybrid Analysis

Release Notes maXbox 4.7.6.50 June 2023 mX476


Add 51 Units + 14 Tutorials

1527 unit uPSI_dprocess; TProcess2
1528 unit uPSI_uXmlStorage.pas
1529 unit uPSI_AsphyreTimer.pas
1530 unit uPSI_Pas2JSUtils.pas
1531 unit uPSI_pacMain; (Form1pac: TForm1pac;)
1532 unit dwsWebUtils.pas; DWS
1533 unit uPSI_dwsWebUtils.pas; DWS beta
1534 unit uPSI_RestUtils2.pas;
1535 unit uPSI_Pas2jsFileUtils.pas; beta
1536 unit uPSI_JPerson.pas;
1537 unit uPSI_OldRttiMarshal;
1538 unit uPSI_superxmlparser;
1539 unit uPSI_superobject.pas; beta
1540 uPSI_NovusWindows.pas
1541 uPSI_NovusStringUtils.pas
1542 unit uPSI_NovusUtilities.pas;
1543 unit uPSI_NovusNumUtils;
1544 unit uPSI_NovusFileUtils;
1545 unit uPSI_NovuscURLUtils.pas; curl beta
1546 unit uPSI_uDM.pas;
1547 unit uPSI_dpipes.pas;
1548 unit uPSI_ShellAPI2;
1549 uPSI_NovusStringBuilder.pas
1550 unit NovusDateDiffUtil.pas
1551 unit NovusDateUtils;
1552 unit NovusDateStringUtils;
1553 unit uPSI_PJCBView;
1554 uPSI_NovusWinVersionUtils.pas
1555 unit uPSI_PJResFile.pas;
1556 unit PJResFile_Routines2;
1557 unit uPSI_JvCreateProcess2
1558 unit uPSI_JVCLHelpUtils.pas;
1559 unit uPSI_ModuleLoader;
1560 unit uPSI_JvLogClasses;
1561 uPSI_uExporter.pas;
1562 unit uExporterDestinationCSV.pas;
1563 uPSI_uOptionParser.pas
1564 uPSI_TOptionDefs;
1565 unit uPSI_GUIUtils.pas //dunit
1566 unit uPSI_GUIAutomation.pas; //dunit
1567 unit uPSI_GUIActionRecorder; //dunit
1568 unit TypeHelpers.pas //dunit
1569 unit uPSI_API_base; //API
1570 unit uPSI_API_audio; //API
1571 unit uPSI_API_ledgrid;
1572 uPSI_API_graphics.pas;
1573 uPSI_API_files.pas;
1574 uPSI_API_tools.pas;
1575 unit uPSI_API_winprocess;
1576 unit API_strings.pas;
1577 unit uPSI_API_services.pas

Total of Function Calls: 37372
SHA1: 4.7.6.50 D047DBD5412C3E4A436089018B9C7FACF17A2EB5
CRC32: 38562FA8 34.04 MB (35,697,944 bytes)
Compilation Timestamp 2023-06-15 06:40:19 UTC Sign-time 15 June 2023 08:42:33
Entry Point 25484072 – Contained Sections 10
sha1: d047dbd5412c3e4a436089018b9c7facf17a2eb5
sha256: 193679043c46821c4b2460269111ff112e7c67b49e9cd9d951854e61bceedac7
Docu: http://www.softwareschule.ch/maxbox_functions.txt
ZIP maxbox4.zip SHA1: EE2E955B14D85A6703F2F1A2976077DC2119A943
https://www.hybrid-analysis.com/sample/193679043c46821c4b2460269111ff112e7c67b49e9cd9d951854e61bceedac7

BPM 110/111
  • CONTENT
  • Image Classifier with loading and testing a pre-trained model by Max Kleiner
  • The Number guessing project
  • Debugging with the new debugger in Lazarus 
    lessons part 2
  • AI-enabled brain scanner reads thoughts
  • Lazarus compiling Delphi code
  • BLAISE PASCAL MAGAZINE LIBRARY By Internet and on USB Stick
    The Library kit for BPM has been extended with new features:
    Search over ALL 111 issues and per issue.
  • Raize SoftWare DropMaster
  • Lazarus for Visual Studio
  • Delphi Community version for Delphi 11
  • Jim McKeeth leaving Embarcadero/Delphi
  • FastReport for Lazarus on LINUX in a Trial and as Professional version
Kalilinux 64-bit Osboxes.org
Kalilinux 64-bit Osboxes.org with BBC Newsfeed API

The MindMaker AI Plugin is an open-source plugin that enables games and simulations within UE4 and UE5 to function as OpenAI Gym environments for training autonomous machine learning agents. The plugin facilitates a network connection between an Unreal Engine Project containing the learning environment, and a python ML library that receives data from Unreal Engine and parses into a custom OpenAI Gym environment for training the agent. The standalone machine learning library can either be a custom python script in the event you are creating your own ML tool using MindMaker’s Remote ML Server, or it could be a precompiled learning engine such as MindMaker’s DRL Engine(Stable-Baselines3 Algorithms). Regardless of which option you choose, using the MindMaker AI Plugin developers and researchers can easily train machine learning agents for 2D, 3D and VR projects.

 #imports for open AI gym and a compatible machine library (stable baselines, neuroevolution etc) import gym import tensorflow as tf from stable_baselines.deepq.policies import MlpPolicy as DqnMlpPolicy from stable_baselines.deepq.policies import LnMlpPolicy as DqnLnMlpPolicy from stable_baselines.deepq.policies import CnnPolicy as DqnCnnPolicy from stable_baselines.deepq.policies import LnCnnPolicy as DqnLnCnnPolicy from stable_baselines.sac.policies import MlpPolicy as SacMlpPolicy from stable_baselines.sac.policies import LnMlpPolicy as SacLnMlpPolicy from stable_baselines.sac.policies import CnnPolicy as SacCnnPolicy from stable_baselines.sac.policies import LnCnnPolicy as SacLnCnnPolicy from stable_baselines.td3.policies import MlpPolicy as Td3MlpPolicy from stable_baselines.td3.policies import LnMlpPolicy as Td3LnMlpPolicy from stable_baselines.td3.policies import CnnPolicy as Td3CnnPolicy from stable_baselines.td3.policies import LnCnnPolicy as Td3LnCnnPolicy 
BFH Diploma 2023
EKON27 ON

Bloom Filter

A Bloom filter is a space-efficient probabilistic data structure, conceived by Burton Howard Bloom in 1970, that is used to test whether an element is a member of a set. False positive matches are possible, but false negatives are not – in other words, a query returns either “possibly in set” or “definitely not in set”. Elements can be added to the set, but not removed (though this can be addressed with the counting Bloom filter variant); the more items added, the larger the probability of false positives.

The high level idea is to map elements x∈X to values y=h(x)∈Y using a hash function h, and then test for membership of x’ in X by checking whether y’=h(x’)∈Y, and do that using multiple hash functions h.

Fleischmann N Scale 67335
Tillig Museumslok
https://rosettacode.org/wiki/Sylvester%27s_sequence#Pascal
 {integer sylvester_next(const integer& n) { return n * n - n + 1; } var s,h : Tinteger;//UIntX.TIntX; // arbitrarily large integer i : integer; begin s:= TInteger.create(1); h:= TInteger.create(0); //n*n-n+1 for i:= 0 to 9 do begin //inc(s); s.add1(1); h.assign(s); WriteLn( {SysUtils.}Format('s[%d] = %s',[i, s.ToString(normal)])); //s := s*(s - 1); s.mult(s); s.subtract(h) end; s.free; h.free; WriteLn( 'Sum of reciprocals ='); //WriteLn( (s - 1).ToString); WriteLn( '/'); // on a separate line for clarity WriteLn( s.ToString(normal)); end. 

Digitree puzzle

Place the digits 1 through 9 in the circles at right so that the value in any circle will be the sum of the digits in the circles connected from below.

 {************* LabelDragDrop ************} procedure Label9DragDrop(Sender, Source: TObject; X, Y: Integer); {dropping a label on a label..} var i:integer; begin { if the label is in its home column, then reset the label being dropped} {if the label is in the figure, then reset the label being dropped on} If TControl(sender).left=labelstart.x then resetlabel(TControl(source).tag) else begin {the label we are dropping is already in a shape} for i:=1 to 7 do {find the shape holdng the label we are dropping on} if shapes[i].tag=TControl(sender).tag then begin resetlabel(TControl(sender).tag); {move that label back home} Shape1dragDrop(shapes[i],source,x,y); {and simulate a drop on that shape} break; {might as well stop searching} end; end; end; 

Here is the second little puzzle program adapted from my most recent puzzle book acquisition,  Giant Book of Mensa Mind Challenges , Stirling Publications, 2003.   

The operation of the program is simple:  Drag digits to the circles until the conditions are satisfied.  Clearly, since there are nine digits and only seven circles, some of the circles will contain two digits.  Drag and drop digits on the left or right side of the circle, depending whether you are setting the left or right digit. 

You find the script at: http://www.softwareschule.ch/examples/digitree.txt

http://delphiforfun.org/Programs/DigitTree.htm
Lematec CC-6552 10/20 2013

TNeuralNetwork2 Component

TNeuralNetwork is a general purpose component to be used under Delphi to develop intelligent programs ranging from signal processing to intelligent internet applications. It uses a mixture of Artificial Neural Network Technology to converge to correct solutions with shorter training times. It is quite flexible and accepts different ranges of inputs and outputs defined by the user. Network allows any number of hidden layers and the structure of the network can be visually displayed.

train neural network start..:15000 iterators train neural network finished: RMS ERROR: 0.000343334505114 evaluate neural network.. i:0 j:0 0.000408506287775 i:0 j:1 0.979020608953271 i:1 j:0 0.977755606887612 i:1 j:1 0.026143966742426 debug inf nncount:3 mX4 executed: 19/07/2023 11:11:37 Runtime: 0:0:8.786 Memload: 56% use
 procedure createNetwork(AOWner: TComponent); begin //inherited create(AOwner); FClsblr:=true; nNetwork:=TStringList.Create; FNetwork:= nNetwork; FInitialized:=false; FLearningRate :=0.9; FMomentumRate :=0.39; //Width := 120; //Height :=120; FNeuronWidth:=15; FRMSError:=1; FNumberOfTraining:=1; end; 

https://github.com/breitsch2/TNeuralNetwork

https://github.com/breitsch2/Neural-Network-in-Delphi

CORS Schema

Data Science Story

Author Max Kleiner

Data Science Story

maXbox Starter 100

Links and Sources
Title
https://www.kaggle.com/code/parulpandey/penguin-dataset-the-new-iris
python4delphi/Tutorials/Webinar II at master · maxkleiner/python4delphi (github.com)
https://medium.com/p/d978f4c374a1
tutorials

Teach and Train it with the Jupyter Notebook:

https://github.com/maxkleiner/Bayes_theorem/blob/master/clusterclass4penguins.ipynb

https://github.com/maxkleiner/maXbox4/blob/master/clusterclass4penguins.ipynb

1096_2022-11-12_svg_delphi_maxbox_seaborn4.png

1096_2022-11-12_svg_delphi_maxbox_seaborn4.png

RAD Studio 11.4, maXbox4 and Python 3.8 with Seaborn

Python4Delphi with SVG Plot

  1. From Data to Plot
  1. Functions Routines

The Iris flower data set or Fisher’s Iris data set is a multivariate data set introduced by the British statistician and biologist Ronald Fisher in his 1936 paper.

Palmer Archipelago (Antarctica) penguin dataset appears to be a drop in replacemnt for the same. It is a great intro dataset for data exploration & visualization. But the penguins dataset has different number of samples for each species.

First we get the data:

import seaborn as sns
df = sns.load_dataset(“penguins”)
load dataset

Or alternate

df = pd.read_csv('../input/palmer-archipelago-antarctica-penguin-data/penguins_size.csv') df.head()
speciesislandculmen_length_mmculmen_depth_mmflipper_length_mmbody_mass_gsex
0AdelieTorgersen39.118.7181.03750.0MALE
1AdelieTorgersen39.517.4186.03800.0FEMALE
2AdelieTorgersen40.318.0195.03250.0FEMALE
3AdelieTorgersenNaNNaNNaNNaNNaN
4AdelieTorgersen36.719.3193.03450.0FEMALE
data table set

1096_2022-11-12_svg_python2seaborn.png

1096_2022-11-12_svg_python2seaborn.png
df.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 344 entries, 0 to 343 Data columns (total 7 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 species 344 non-null object 1 island 344 non-null object 2 culmen_length_mm 342 non-null float64 3 culmen_depth_mm 342 non-null float64 4 flipper_length_mm 342 non-null float64 5 body_mass_g 342 non-null float64 6 sex 334 non-null object dtypes: float64(4), object(3) memory usage: 18.9+ KB memory shape core cube #7

The dataset consists of 7 columns.

  • species: penguin species (Chinstrap, Adélie, or Gentoo)
  • culmen_length_mm: culmen length (mm)
  • culmen_depth_mm: culmen depth (mm)
  • flipper_length_mm: flipper length (mm)
  • body_mass_g: body mass (g)
  • island: island name (Dream, Torgersen, or Biscoe) in the Palmer Archipelago (Antarctica)
  • sex: penguin sex

1096_2022-11-12_svg_python_delphi_scalable.png

1096_2022-11-12_svg_python_delphi_scalable.png

Seaborn is a Python data visualization library based on matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics.

  1. Covariance

“Covariance” indicates the direction of the linear relationship between variables. “Correlation” on the other hand measures both the strength and direction of the linear relationship between two variables.

Source: https://tinyurl.com/yd2pezss

1096_Figure_1_species.png

The scatter plot which shows us the correlation with respect to other features. This method helps just to figure out the important features which account the most for the classification in our model.

  1. Scatter Plot

A scatter plot (aka scatter chart, scatter graph) uses dots to represent values for two different numeric variables. The position of each dot on the horizontal and vertical axis indicates values for an individual data point. Scatter plots are used to observe relationships between variables.

A common modification of the basic scatter plot is the addition of a third variable. Values of the third variable can be encoded by modifying how the points are plotted. For a third variable that indicates categorical values (like geographical region or gender), the most common encoding is through point color.

Seaborn lets you create relational plots using the relplot() function. The function technically lets you create more than scatter plots.

Numpy arrays are a good substitute for python lists. They are better than python lists. They provide faster speed and take less memory space. Let’s begin with its definition for those unaware of numpy arrays. They are multi-dimensional matrices or lists of fixed size with similar elements.

Pandas is a popular Python library used to manipulate tabular data. It provides a versatile dataframe object that can read data from many popular formats, such as Excel, SQL, CSV and more.

The Pandas style API provides you with many different tools that makes working with styling tabular data much easier.

1096_2022-11-12_var_python.png

1096_2022-11-12_svg_python.png

python – Scaling a plot (matplotlib) – Stack Overflow

The graph is quite big, so in order to not only see many overlapping dots indicating the nodes, I have to scale the output picture. I used: f,ax = plt.subplots (1,1) ax.set_aspect (‘equal’) zoom=30 w, h = f.get_size_inches () f.set_size_inches (w * zoom, h * zoom) .

1096_2022-11-12_svg_python2.png

  1. Predict and Dict the Pic

When you hear the word, ‘Bayesian’, you might think of Naive Bayes. However, Bayesian principles can also be used to perform regression. In this article, we will discuss and implement Bayesian Ridge Regression, which is not the same as regular Ridge Regression. To understand more about regular Ridge Regression, you can follow this link.

1096_2022-11-11_analytics.png

  1. Predict in a Script

Regression is a Machine Learning task to predict continuous values (real numbers), as compared to classification, that is used to predict categorical (discrete) values.

1096_2022-11-11_analytics_script.png

The algorithm uses a hyperparameter to control regularization strength and fully integrates over the hyperparameter in the posterior distribution, applying a hyperprior selected so as to be approximately noninformative.

Scikit-learn’s algorithm makes use of conjugate priors and because of that is restricted to use the Gamma prior which requires four hyperparameters chosen arbitrarily to be small values. Additionally, it requires initial values for parameters αα and λλ that are then updated from the data.

import numpy as np iimport matplotlib.pyplot as plt from sklearn.linear_model import BayesianRidge

In comparison, the algorithm we presented requires no initial parameters; and because the hyperparameter is integrated over, poor performing values contribute little to the posterior probability mass.

# ######################################################################### # Plot true and predicted curves for bbai's BayesianRidgeRegression model from bbai.glm import BayesianRidgeRegression reg = BayesianRidgeRegression(fit_intercept=False) fig, ax = plt.subplots(1, 1, figsize=(4, 4)) # Note: there are no parameters to tweak reg.fit(X_train, y_train) ymean, ystd = reg.predict(X_test, return_std=True) ax.plot(x_test,func(x_test),color="blue",label="sin($2\\pi x$)") ax.scatter(x_train, y_train, s=50, alpha=0.5, label="observation") ax.plot(x_test, ymean, color="red", label="predict mean") ax.fill_between( x_test,ymean-ystd,ymean+ ystd,color="pink",alpha=0.5,label="predict std" ) ax.set_ylim(-1.3, 1.3) ax.legend() plt.tight_layout() plt.show()
 # ############################################################## # Plot true and predicted curves for bbai's BayesianRidgeRegression model from bbai.glm import BayesianRidgeRegression reg = BayesianRidgeRegression(fit_intercept=False) fig, ax = plt.subplots(1, 1, figsize=(4, 4)) # Note: there are no parameters to tweak reg.fit(X_train, y_train) ymean, ystd = reg.predict(X_test, return_std=True) ax.plot(x_test, func(x_test), color="blue", label="sin($2\\pi x$)") ax.scatter(x_train, y_train, s=50, alpha=0.5, label="observation") ax.plot(x_test, ymean, color="red", label="predict mean") ax.fill_between( x_test,ymean-ystd,ymean+ystd,color="pink",alpha=0.5,label="predict std" ) ax.set_ylim(-1.3, 1.3) ax.legend() plt.tight_layout() plt.show() 
  1. Technical Description

maxkleiner (Max Kleiner) (github.com)

A Python program terminates as soon as it encounters an error. In Python, an error can be a syntax error or an exception. In his article, you will see what an exception is and how it differs from a syntax error. After that, you will learn about raising exceptions and making assertions. Then, you’ll finish with a demonstration of the try and except block.

https://realpython.com/python-exceptions/

This Exception was prior to change between 32- and 64 bit.

1096_2022-11-11_exception.png

  1. Develop Overview

  2. We value the quality of the material each student is learning. Our Instructor led classes help provide hands-on learning, one-on-one mentoring with experienced developers and peer-to-peer learning. To allow the most flexibility for students, we have Day and Night programs to choose from. *No prior coding experience required.

1096_2022-11-12_develop_overview.png

procedure pyBank_VCL4Python;

var eg: TPythonEngine; sw: TStopWatch; begin  eg:= TPythonEngine.Create(Nil); try  eg.pythonhome:= PYHOME;  eg.loadDLL;  println('test import '+GetPythonEngine.EvalStr('__import__("decimal").Decimal(0.1)'));  writeln('')   //println(eg.EvalStr('__import__("faker").Faker()'));   sw:= TStopWatch.Create();  sw.Start;  eg.execStr('import importlib.machinery, importlib.util');  eg.execStr('from decimal import Decimal, getcontext');  importlib.machinery.ExtensionFileLoader("DelphiVCL",'+VCLHOME+')')  eg.execStr(ANALYTICSSVG);  sw.Stop;  //sw.ElapsedMilliseconds;  writeln('Stop Analytics Tester1: '+sw.getValueStr) except  eg.raiseError;  writeln(ExceptionToString(ExceptionType, ExceptionParam));  finally  eg.Free;  sw.Free;  sw:= Nil; end; end; 
 procedure pyBank_VCL4Python; var eg: TPythonEngine; sw: TStopWatch; begin eg:= TPythonEngine.Create(Nil); try eg.pythonhome:= PYHOME; eg.loadDLL; println('test import '+GetPythonEngine.EvalStr('__import__("decimal").Decimal(0.1)')); writeln('') //println(eg.EvalStr('__import__("faker").Faker()')); sw:= TStopWatch.Create(); sw.Start; eg.execStr('import importlib.machinery, importlib.util'); eg.execStr('from decimal import Decimal, getcontext'); importlib.machinery.ExtensionFileLoader("DelphiVCL",'+VCLHOME+')') eg.execStr(ANALYTICSSVG); //println(eg.evalStr(''#39'MSE:'#39',mean_squared_error(test_bayesian_pred, y_test_confirmed)')); sw.Stop; //sw.ElapsedMilliseconds; writeln('Stop Analytics Tester1: '+sw.getValueStr) except eg.raiseError; writeln(ExceptionToString(ExceptionType, ExceptionParam)); finally eg.Free; sw.Free; sw:= Nil; end; end; 

Cluster Attack

 +'from sklearn.cluster import KMeans'+LF +'print("CLUSTERING ON CULMEN LENGTH AND CULMEN DEPTH")'+LF +'X = df[["bill_length_mm","bill_depth_mm"]]'+LF +'kmeans = KMeans(n_clusters=3)'+LF +'kmeans.fit(X)'+LF +'y_kmeans = kmeans.predict(X)'+LF +'plt.scatter(X.loc[:,"bill_length_mm"], X.loc[:,"bill_depth_mm"],c=y_kmeans,s=50,cmap="viridis")'+LF +'centers = kmeans.cluster_centers_'+LF +'plt.scatter(centers[:, 0], centers[:, 1], c="black", s=200, alpha=0.5)'+LF +'plt.show()'; 
Installing collected packages: numpy
Successfully installed numpy-1.17.0
Classify with PyScripter
REE BB 9288
3D Printing Study of BB 9200 Capitole

BB 9200 Short Story

The French SNCF Class BB 9200 electric locomotives were built by Schneider-Jeumont/CEM between 1958-1964. 92 of them were built, the last being withdrawn in 2014. These locomotives are products of the Jacquemin product family, offspring of the prototype BB 9004, and named after the engineer who designed their bogies. The locomotives were designed for a maximum speed of 160 km/h (99 mph) and were the first such engines in France. In the late sixties, a small group of locomotives was converted for 200 km/h (120 mph) operation, hauling prestige TEE trains like the Capitole – these locomotives were called the BB 9200 Capitole. These types were later superseded by the CC 6500 locomotives.

Some of these locomotives travelled more than 10 million kilometers (6.2 million miles) since they entered service. The regular services of the BB 9200 locomotivess were inter-regional trains between Paris Montparnasse and Le Mans, between Paris Austerlitz and Tours and between Paris Gare de Lyon, Dijon and Lyon. Some were in service on freight trains. Phasing out of the class was completed by 2014. The BB 9200 Capitole was a variant of the SNCF Class BB 9200 locomotive specially constructed for operating high speed trains running at speeds greater than 160 km/h or 99 mph). Due to the special colour scheme they were also called the BB rouge. They also sported Capitole front plates and single-arm pantographs; the rest of the class had diamond pantographs. From 1967 to 1970 the SNCF started the high speed service with the Capitole between Paris and Toulouse. This route included some sections with a speed of more than 200 km/h (120 mph).

15015 of L.S. Models
mX4.7.6.20 on Wine
G9YOU – IMPROVER
Threshold at 30 % Schwan, Sternstrasse, Pempelfort, Duesseldorf, Germany, 8th November 2022

W1216 14:06:45.366872 2948 ag_logging.py:146] AutoGraph could not transform .predict_function at 0x0000026BCAF7D268> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, export AUTOGRAPH_VERBOSITY=10) and attach the full output.
Cause: ‘arguments’ object has no attribute ‘posonlyargs’
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert

Data Science Spectrum
Scrapy Tutorial
 ##################################################### # Trainingsprogramm für das neuronale Netz des # BrickClassifi3r Roboters mit Hilfe von TensorFlow # # Autor: Detlef Heinze mX4 Max Kleiner 2023 # Version: 1.3d ##################################################### import tensorflow as tf from numpy import loadtxt, savetxt, reshape import datetime as dt #Abschalten der Warnmeldungen von TensorFlow, die #melden, dass die TensorFlow-Library nicht #alle Eigenschaften dieser HW nutzt. import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' scriptpath="C:\\maXbox\\softwareschule\\MT-HS12-23\\mentor_xml\\mxscripts\\pidataset\\" print('Training eines Neuronalen Netzes(V1.1)\n') start= dt.datetime.now() # Step 1: Import Training Data (xTrain und yTrain) print('Lese xTrain- und yTrain-Daten') xTrain= loadtxt(scriptpath+'xTrain_TwoCubesCylinder375-24.csv') yTrain= loadtxt(scriptpath+'yTrain_TwoCubesCylinder375-3.csv') # Step 2: Import Test Data (xTest und yTest) print('Lese xTest und yTest-Daten') xTest= loadtxt(scriptpath+'xTest_TwoCubesCylinder300-24.csv') yTest= loadtxt(scriptpath+'yTest_TwoCubesCylinder300-3.csv') # Step 3: Definition der Lernparameter learning_rate = 0.001 num_epochs = 250 num_examples= xTrain.shape[0] print('Anzahl der Trainingdaten: '+repr(num_examples)) print('Anzahl der Testdaten: ' + repr(xTest.shape[0])) #Parameter für das 24 - 6 - 3 neuronale Netz n_input = 24 #24 Neuronen für die gemessene Daten n_hidden_1 = 6 #Größe der versteckten Neuronenschicht n_classes = 3 #Größe der ausgebenden Neuronenschicht #ist gleich der Anzahl der Klassen print('NN-Architektur: ' + repr(n_input) +' - ' + repr(n_hidden_1) + ' - ' + repr(n_classes)) # Platzhalter im TensorFlow-Graph x = tf.placeholder("float", shape=(None, n_input)) y = tf.placeholder("float", shape=(None, n_classes)) # Step 4: Berechnungsschritte des NN festlegen def multilayer_perceptron(x, weights, biases): # Die versteckte Schicht mit RELU-Aktivierung layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1']) layer_1 = tf.nn.relu(layer_1) # Die Ausgabeschicht mit linearer Aktivierung out_layer = tf.matmul(layer_1, weights['out'])+biases['out'] return out_layer # Step 5: Initialisiere Model mit Zufallszahlen weights = { 'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1])), 'out': tf.Variable(tf.random_normal([n_hidden_1,n_classes])) } biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1])), 'out': tf.Variable(tf.random_normal([n_classes])) } # Step 6: Maschinelles Lernen vorbereiten # Platzhalter für x und Anfangsmodell übergeben predict = multilayer_perceptron(x, weights, biases) # Kosten und den Optimizer definieren cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=predict,labels=y)) optimizer =tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost) # Variablen von tf initialisieren init = tf.global_variables_initializer() #Step 7: Training print('\n-------------Trainingsphase-----------------') with tf.Session() as sess: sess.run(init) for i in range(num_epochs): for j in range(num_examples): _, c = sess.run([optimizer, cost], feed_dict={x: [xTrain[j]], y: [yTrain[j]]}) if i % 25 == 0: print('epoch {0}: cost = {1}'.format(i, c)) print('epoch {0}: cost = {1}'.format(i, c)) print('Training beendet.') duration = (dt.datetime.now() - start) print("Dauer: " + str(duration)) #Step 8: Berechnung der Treffsicherheit anhand der Testdaten correct_prediction = tf.equal(tf.argmax(predict, 1), tf.argmax(y, 1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) print('Testergebnis:', accuracy.eval({x: xTest, y: yTest})) #Step 9: Ausgabe des berechneten Models print('\n-----------------Modelübersicht----------------------') print('Weights für h1') wh1= weights['h1'].eval(sess) print(wh1) print('\nBiases für b1') bb1= biases['b1'].eval(sess) print(bb1) print('\nWeights für out') wo= weights['out'].eval(sess) print(wo) print('\nBiases für out') bo= biases['out'].eval(sess) print(bo) #Step 10: Sicherung des berechneten Models als csv und rtf print('\n--------------Model wird gespeichert(csv)-------------') print('Sichere Weights für h1: NNweights_h1.csv') savetxt(scriptpath+'NNweights_h1x.csv', wh1, fmt='%10.8f', delimiter=' ') print('Sichere Biases für b1: NNbiases_b1.csv') savetxt(scriptpath+'NNbiases_b1x.csv', bb1, fmt='%10.8f', delimiter=' ') print('Sichere Weights für out: NNweights_out.csv') savetxt(scriptpath+'NNweights_outx.csv', wo, fmt='%10.8f', delimiter=' ') print('Sichere Biases für out: NNbiases_out.csv') savetxt(scriptpath+'NNbiases_outx.csv', bo, fmt='%10.8f', delimiter=' ') print('\n--Model wird gespeichert(rtf für Lego Mindstorms EV3)--') #Format: <Anzal Zeilen>CR<Anzahl Spalten>CR<{<aReal>CR}* print('Sichere Weights für h1: NNweights_h1.rtf') tmpArray = reshape(wh1, (wh1.shape[0] * wh1.shape[1],)) result= [wh1.shape[0],wh1.shape[1]] + tmpArray.tolist() savetxt(scriptpath+'NNweights_h1x.rtf',result,fmt='%10.8f',delimiter='\r',newline='\r') print('Sichere Biases für b1: NNbiases_b1.rtf') result= [1,bb1.shape[0]] + bb1.tolist() savetxt(scriptpath+'NNbiases_b1x.rtf',result,fmt='%10.8f',delimiter='\r',newline='\r') print('Sichere Weights für out: NNweights_out.rtf') tmpArray = reshape(wo, (wo.shape[0] * wo.shape[1],)) result= [wo.shape[0],wo.shape[1]] + tmpArray.tolist() savetxt(scriptpath+'NNweights_outx.rtf',result,fmt='%10.8f',delimiter='\r',newline='\r') print('Sichere Biases für out: NNbiases_out.rtf') result= [1,bo.shape[0]] + bo.tolist() savetxt(scriptpath+'NNbiases_outx.rtf',result,fmt='%10.8f',delimiter='\r',newline='\r') print('Neuro Model gesichert. Programmende Quit.') 
mX4.7.6.20 2023
ChatGPT solves code