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.
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 setis hosted online in comma-separated values format (CSV) by the Rdatasets repository. We could download the file locally andthen load it using read_csv, but pandas takes care of all of this automatically for us:
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
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.
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 anduses 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.
Seaborn HeatmapGuerry 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
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:
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()');
Python for Delphi at maXbox statsmodels console Weather extreme statistic GEOStatInformatik Workshop 19942 Nation Locs France – ItalymX 5.2.9.180Its all about correlationTrain your Main BrainMuseum near RotterdammX5.2.9.185Othello Win Situation CodDocmX5.2.9.190 BS EditionEKON 29 Session
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;
This libraryand 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:
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:
NBayes, SVM, Classifiers with 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:
Face Detection Playground
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 mX51Classifier ComparisonTrix 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:
It reads what we’ve typed
Then it evaluates it, meaning it runs the code
Then it prints any value that’s returned to it
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:
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.
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
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.
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:
From the WinForm to a WebForm
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.
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
Tests on Android Delphi 10.4 Sydney Targets API Level Android 29 (Android 10)Timeline as an output from directions trackerstation2station tracker test VIIstation2station tracker test VIIIstation2station tracker test IXstation2station tracker test XEKON 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.
Pydemo67Interrail in the meantimeRe 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:
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:
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”:
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 fineEKON Talks – Leipzig Central Stationpy modul package sympyGoldbachs Comet4 Nations: Märklin DB E10 1266 – B 1606 – TAB SNCF CC 6544 – Piko SBB Re 4/4 1034 TEE ClassicCologne Dom Sunday Night
Der kosmopolitische Stadtteil Pempelfort ist für seine kulturellen Einrichtungen am Rhein bekannt.
Düsseldorf Nov. 2024Düsseldorf Hofgarten ParkEKON 28 ImpressionsHappy 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
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 andpywintypes38.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 LocsBR E 10 Tracks4. Advent – चतुर्थः आगमनम्BPM #120 with a post API image pipeline from station2stationSNCF, locomotive électrique CC 6526 « Le Capitole », ép. IV – coffret anniversaireSNCF, 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 TecinaFM SNCF 68006, Jouef CC 6542, Trix CC 40105, Märklin BB 22347 – @TfrmMtxPlotRheingold SetTrier – Bern – ZürichOne Month Test 8.1.-5.2. 2025 (8 + 4*7=36)-31= 5.From Lichfield to Geneva
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.
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;
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.
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.
from CreateOleObject(‘InternetExplorer.Application’) to EdgeView
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.
Runtime in mX5 with MS WebView2 Runtime + 32/64 WebView2Loader.dll.
Geo Tracking Solution
Geo Tracking Post Logistic Test IIIGeo Tracking Post Logistic Test IVGoogle Directions as Tetris Maps
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.
Codemap screensUnicode Codemap 5Unicode Codemap 5 IILemaco CC 40110 Blason NiceCC 40110 on stageCC 40101 from RailPicDB 184 Eurolok4 Nations Locs SNCF CC 6510 – SBB 10101 – DB E 10 158 – ÖBB 1042.10Pink Floyd: This is the peak of music itself, it literally can´t go any higher than thisLast Picture I got with N. Wirth from 2023EKON 28 2024CologneBreisach, July 2024Elsass: S.A.C.M. Elsässische Maschinenbauanstalt Graffenstaden C-Kuppler (2x) – Baujahr 1900, Pic: MaxDragon Curve – Die Welt ist Klang – Nada Brahma – Joachim-Ernst-BerendtWurmlingen /Tübingen 18.08.2024V 218 Lokomotive 218 105-5 der Westfrankenbahn in Aschaffenburg und V 200 035V 5.1.6.98 XIXV 5.1.6.98 XX
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.
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
RAD 12.1 Base PackagesRAD 12.1 Community Edition Live – Vector&VictorPython & Pascal executedEKON 28 PromotionEKON Archive 1997-2024EKON Samples from the Archive
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 similarto 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.
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.
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;
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;
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 6500CC 6516 RocoCollectionBahnpark AugsburgModel versus RealSpecial 95 et 105
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.
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.
Track to Gallizien
Mit einer Fallhöhe von 54 Metern ist der Wildensteiner Wasserfall einer der höchsten freifallenden Wasserfälle Europas.
1-4 Weather Report GPS coordinates: 46° 37′ 55.4891” N 14° 8′ 39.2042” EGPS coordinates: 46° 37′ 55.4891” N 14° 8′ 39.2042” EmX5.1.4.98 XI
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.
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.
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
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;
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.
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:
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.
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.
Dole get geocoords: lat: 47.0948 — lon: 5.49728 DoleDole JardinDole Jardin IIDole of Louis PasteurTEE & TEN Directions MapJouef CC 6511 & 6512LS Models CC 6505TEE 5 Nations Locs SNCF-DB-SBB-FS-ÖBB
Winter Melody Kandersteg 07/03/2024
My beloved Kandersteg
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 MapperCryptobox2 32- and 64-bit
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.
64 and 32-bit compareUp 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 MagicDole Espace Doctor Billard
“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
Nature versus AIMultipartFormDataStream can result in a Bad Request (400)
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 ProfileHofgartenKöKö-BogenDüsseldorf November 2022EKON 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.
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.
Avatarify & NN-SVGPerson Detector with false positive and false negativeCologne 2023EKON 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
InOut2023 from Melia Pempelfort
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
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:
Prompt: ICE Age by Salvador DaliStable Diffusion KI Generator
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.
Python 64bit in a maXbox 64 bitAlexandria 11 on Win 11BPM 113madExcept at work as circular unit reference sock error with invalid handleFleischmann BR 103 113-7BR 110 126-062493 Electric locomotive, class E 10.1 of the DB 110 126-0733002 Fleischmann NMärklin 39408 – CC 1804 B TEE II Wattwil August 2023Jouef1982 Paris Gare de Lyon FerImageCC 21004 Cisalpin
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-6574Jouef CC 21004 CisalpinNazareth Rock of Ages 2023 Seebronn Tübingen Germany Animals & RisingRock group Pink Floyd plays at the 1977 Day on the Green concert at the Oakland Coliseum. (Photo by Roger Ressmeyer/Corbis/VCG via Getty Images)Pink Floyd 1977 Animals Tour 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)
FireWaterEarthAirGroningen IV Elements
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.
alpha07 maXbox5 as mXVFix 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!
Build or ShieldRef 64bit with TeeChart, JSONLib and WinHttpRequest.5.1one step beyond as unit doit Compare 32bit script – 64bit script – 64bit exeFull 64 bit on osboxes.org as Kalilinux with 01:07 runtimeV5.0.1.22 another Kali64Linux SessionPas2JS with maXbox5Bodensee FriedrichshafenE-Lok BR 112 DB Ep.IV RheingoldPython and Pascal Training V 5.0.1.22 shine as 64-bit-boxLogo ServiceHofgarten KönigsalleeBest of Düsseldorf Nov. 2023
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.
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:
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
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 MAGAZINELIBRARY 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.orgKalilinux 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 mindmaker visualsEKON27 ON
Bloom Filter
A Bloom filter is a space-efficient probabilisticdata 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.
{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.
the old exe and the new one scriptingthe way to solve
{************* 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.
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.
RAD Studio 11.4, maXbox4 and Python 3.8 with Seaborn
Python4Delphi with SVG Plot
From Data to Plot
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.
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.
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.
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.
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.
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
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
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()
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.
This Exception was prior to change between 32- and 64 bit.
1096_2022-11-11_exception.png
Develop Overview
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.
Installing collected packages: numpy Successfully installed numpy-1.17.0Classify with PyScripterREE BB 9288REE Modeles SNCF BB 9288 Capitole MB-082 SACLIMA 9210 versus 9291LIMA 92833D 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. ModelsmX4.7.6.20 on WineG9YOU – IMPROVERThreshold 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 SpectrumChianti 1993Borland Magazin 5/9430 Years agoScrapy 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 3DS Max 8 format Printing Model of BB 9200ChatGPT solves code