Sie sind auf Seite 1von 44

F O R D E L P H I, L A Z A R U S, A N D P A S C A L

R E L A T E D L A N G U A G E S / A N D R O I D,
I O S, M A C , W I N D O W S & L I N U X
P R I N T E D, P D F, & O N L I N E V I E W

DX

BLAISE PASCAL MAGAZINE 63

Windows Management Instrumentation


By Max Kleiner
Quantum computing
Part 2 Building a quantum computer
Detlef Overbeek
Getting Framed (The Framework project)
By David Dirkse
Storing objects in the Google Firebase cloud
with TMS Cloud Pack
By Bruno Fierens
Video processing Part 2
By Boian Mitov
Rest Easy With kbmMW Part1
By Kim Madsen

PRINTED ISSUE PRICE €15,00


DOWNLOAD ISSUE PRICE € 5,00
THE

WHERE KNOWLEDGE MEETS

EUROPEAN DELPHI &


C++BUILDER CONFERENCE

C++
DELPHI BUILDER
19 SEPTEMBER 2017
EVOLUON IN EINDHOVEN
VCL FMX

RAD
UI SERVER

barnsten
BLAISE PASCAL MAGAZINE 63
D E L P H I, L A Z A R U S, S M A R T M O B I L E S T U D I O,
A N D P A S C A L R E L A T E D L A N G U A G E S
F O R A N D R O I D, I O S, M A C, W I N D O W S & L I N U X

CONTENTS
ARTICLES
Windows Management Instrumentation Page 6
By Max Kleiner
Quantum computing Page 10
Part 2 Building a quantum computer
Detlef Overbeek
Getting Framed (The Framework project) Page 16
By David Dirkse
Storing objects in the Google Firebase cloud Page 24
with TMS Cloud Pack
By Bruno Fierens
Video processing Part 2 Page 30
By Boian Mitov
Rest Easy With kbmMW Part1 Page 37
By Kim Madsen

Quantum computing
Image 1

ADVERTISERS
BARNSTEN / PASCON: THE LAB PAGE 2 / 22+23
BARNSTEN / PASCON: THE LAB PAGE 9 / 43
COMPONENTS4DEVELOPERS PAGE 44
EMBARCADERO PAGE 5
VISUINO PAGE 36

Publisher: Foundation for Supporting the Pascal Programming Language


in collaboration with the Dutch Pascal User Group (Pascal Gebruikers Groep)
© Stichting Ondersteuning Programmeertaal Pascal

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 3


Stephen Ball Peter Bijlsma -Editor Dmitry Boyarintsev
http://delphiaball.co.uk peter @ blaisepascal.eu dmitry.living @ gmail.com
@DelphiABall

Michaël Van Canneyt, Marco Cantù David Dirkse


michael @ freepascal.org www.marcocantu.com www.davdata.nl
marco.cantu @ gmail.com E-mail: David @ davdata.nl

Benno Evers Bruno Fierens Primož Gabrijelčič


b.evers www.tmssoftware.com www.primoz @ gabrijelcic.org
@ everscustomtechnology.nl bruno.fierens @ tmssoftware.com

Fikret Hasovic Cary Jensen Peter Johnson


fhasovic @ yahoo.com www.jensendatasystems.com http://delphidabbler.com
http://caryjensen.blogspot.nl delphidabbler@gmail.com

Max Kleiner John Kuiper Wagner R. Landgraf


www.softwareschule.ch john_kuiper @ kpnmail.nl wagner @ tmssoftware.com
max @ kleiner.com

Kim Madsen Andrea Magni Boian


Kim Madsen
Mitov
kbm @ components4developers.com www.andreamagni.eu mitov
www.component4developers
@ mitov.com
andrea.magni @ gmail.com
www.andreamagni.eu/wp
Olaf MONIEN Paul Nauta PLM Solution Jeremy North
olaf@developer-experts.net Architect CyberNautics jeremy.north @ gmail.com
paul.nauta@cybernautics.nl
Detlef Overbeek - Editor in Chief Howard Page Clark Heiko Rompel
www.blaisepascal.eu hdpc @ talktalk.net info@rompelsoft.de
editor @ blaisepascal.eu

Wim Van Ingen Schenau -Editor Peter van der Sman Rik Smit
wisone @ xs4all.nl sman @ prisman.nl rik @ blaisepascal.eu
www.romplesoft.de

Bob Swart B.J. Rao Daniele Teti


www.eBob42.com contact@intricad.com www.danieleteti.it
Bob @ eBob42.com d.teti @ bittime.it

Anton Vogelaar Siegfried Zuhr


ajv @ vogelaar-electronics.com siegfried @ zuhr.nl

Editor - in - chief
Detlef D. Overbeek, Netherlands Tel.: +31 (0)30 890.66.44 / Mobile: +31 (0)6 21.23.62.68
News and Press Releases email only to editor@blaisepascal.eu

Editors
Peter Bijlsma, W. (Wim) van Ingen Schenau, Rik Smit,
Correctors
Howard Page-Clark, James D. Duff
Trademarks
All trademarks used are acknowledged as the property of their respective owners.
Caveat Whilst we endeavour to ensure that what is published in the magazine is correct, we cannot accept responsibility for any errors or omissions.
If you notice something which may be incorrect, please contact the Editor and we will publish a correction where relevant.
Subscriptions ( 2013 prices )
1: Printed version: subscription € 85.-- Incl. VAT 6 % (including code, programs and printed magazine,
10 issues per year excluding postage).
2: Electronic - non printed subscription € 50.-- Incl. VAT 21% (including code, programs and download magazine)

Subscriptions can be taken out online at www.blaisepascal.eu or by written order, or by sending an email to office@blaisepascal.eu
Subscriptions can start at any date. All issues published in the calendar year of the subscription will be sent as well.
Subscriptions run 365 days. Subscriptions will not be prolonged without notice. Receipt of payment will be sent by email.
Subscriptions can be paid by sending the payment to:
ABN AMRO Bank Account no. 44 19 60 863 or by credit card: Paypal
Name: Pro Pascal Foundation-Foundation for Supporting the Pascal Programming Language (Stichting Ondersteuning Programeertaal Pascal)
IBAN: NL82 ABNA 0441960863 BIC ABNANL2A VAT no.: 81 42 54 147 (Stichting Programmeertaal Pascal)
Subscription department Edelstenenbaan 21 / 3402 XA IJsselstein, The Netherlands / Tel.: + 31 (0) 30 890.66.44 / Mobile: + 31 (0) 6 21.23.62.68
office@blaisepascal.eu

Copyright notice
All material published in Blaise Pascal is copyright © SOPP Stichting Ondersteuning Programeertaal Pascal unless otherwise noted and may
not be copied, distributed or republished without written permission. Authors agree that code associated with their articles will be made
available to subscribers after publication by placing it on the website of the PGG for download, and that articles and code will be placed on
distributable data storage media. Use of program listings by subscribers for research and study purposes is allowed, but not for commercial
purposes. Commercial use of program listings and code is prohibited without the written permission of the author.

4 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


NEW FREE “DELPHI 22 YEAR”
BIRTHDAY MAGAZINE
FROM EMBARCADERO
DOWNLOAD IT HERE
http://online.flowpaper.com/79e6075d/Delphi22Magazine/
maXbox
maXbox Starter 52 Second you call the query and iterate
through the object set:
WORK WITH WINDOWS isQuery:=
MANAGEMENT 'SELECT * FROM Win32_Service WHERE State = "Running"';
INSTRUMENTATION iset:= WMIExecQuery(isser, isQuery); //WbemObjectSet;
WMIRowFindFirst(iset, ENum, tempObj);
BY MAX KLEINER PAGE 1/4 repeat
writeln('case: '+tempobj.name+' --
MANAGEMENT INSTRUMENTATION
'+(tempobj.state))
Most Win computers these days have something until not WMIRowFindNext(ENum, tempobj); //}
on them called WMI or Windows Management tempObj:= unassigned;
Instrumentation. You can do a number of useful
things on the local computer or even a remote Code and script can be found at:
computer using WMI like network management, http://www.softwareschule.ch/examples/
security or real-time health monitoring. * 766_wmi_management.txt
*(A hint to the web of things) For me the best is the
query possibility called WQL for example.:
isQuery:=
'SELECT * FROM Win32_Service WHERE State = "Running"';
iset:= WMIExecQuery(isser, isQuery); //Wbem ObjectSet;

Then you get a list of your services running! Even


more so, this is the recommended standard
Microsoft way to do operational things and it is
ever more so when it comes to Win 7 and 10.
WMI (most cases I've seen) is arranged in the form
of object tables, whose data (fields or properties)
are accessed in a subset of SQL that Microsoft
calls WQL. So you don't need a DB or a server to
execute those queries.
To grasp the power and use of WMI, consider
how you managed and monitored Win
workstations and servers yesterday, and perhaps
even today. You probably used, or use, numerous
graphical administrative tools to manage
resources, such as disks, event logs, files, folders,
file systems, networking components,
OS settings, performances, printers, processes,
registry settings, security services, shares, users,
groups, and so on. So how do you start? with a
locator and a connector to pass:
var isloc : ISWBemLocator ;
isser: ISWBemServices; Enum: IEnumVariant;
isloc:= WMIStart;
isser:= WMIConnect(isloc,
'maxbox10','max',''); // WMIServices;

These are the interfaces which are mapped


to a type library:
function WMIStart: ISWBemLocator;
function WMIConnect(WBemLocator:ISWBemLocator;Server,account,password:string): ISWBemServices;
function WMIExecQuery(WBemServices:ISWBemServices; query:string): ISWbemObjectSet;
function WMIRowFindFirst(ObjectSet:ISWbemObjectSet; var Enum:IEnumVariant;
var tempobj: OleVariant):boolean;
function WMIRowFindNext(ENum: IENumVariant; var tempobj: OleVariant): boolean;
function WMIColFindFirst(var propENum:IENumVariant;var tempObj:OleVariant):boolean;
function WMIColFindNext(propENum: IENumVariant; var tempobj: OleVariant):boolean;
function WMIGetValue(wbemservices:ISWBemServices;tablename,fieldname:string):string;
function WMIConvValue(tempobj: OleVariant; var keyname: string): string;

6 maXbox Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


WORK WITH WINDOWS
MANAGEMENT
INSTRUMENTATION PAGE 2/4
maXbox
WMI Consumer
WMI Script

WMI Scripting Library WMI INFRASTRUCTURE


%SystemRoot%\system32\
wbem\wbemdisp.dll

Common Information
CIM Object Manager (CIMOM) Model ()CIM)
WMI Service) WMI Repository
%SystemRoot%\system32\
wbem\winmgnt.exe

%SystemRoot%\system32\
WMI Provider wbem\Repository\FS\
%SystemRoot%\system32\ objects.data
wbem\*.dll

Managed Resource Native


Application Programming Interfaces

Common Information Figure 1 WMI Infrastructure


Model ()CIM)
WMI Repository

What is allowed and not allowed, along with these table definitions are in the
MSDN reference for WMI:
http://msdn.microsoft.com/en-us/library/aa394582(VS.85).aspx

Of course there's a great number of them, and you can find out just about anything regarding your
local system or any system on the network that you can connect to like the running hardware
statistic, along with memory usages, processes, and threads or a physical element like temp:
FWbemObjectSet:= FWMIService.Get('Win32_TemperatureProbe');

Beware, that selecting all the data in some of the tables will take a very large time and a huge amount
of resources, so be careful to limit your statements as you would in dealing with a regular database.
You do also have more than one root name space available, even the query language in the object set
is chose able:

const
WbemComputer ='localhost'; // wbemFlagForwardOnly= $00000020;
WbemRootNameSpace ='root\CIMV2';

FWbemObjectSet:= FWMIService.ExecQuery(Format('Select %s from %s',


[WMIProperty, WMIClass]),'WQL',wbemFlagForwardOnly);

Each item in a SWbemObjectSet is a SWbemObject (yet another object (Interface) in the WMI
scripting library) that represents a single instance of the requested resource. You use SWbemObject
and WMIRowFindNext to access the methods and properties defined in the managed resource's
class definition WMIClass.

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE maXbox 7


WORK WITH WINDOWS
MANAGEMENT
INSTRUMENTATION PAGE 3/4
maXbox
The WMI architecture consists of three primary
layers as shown in the Figure 1 on page 7:
• Managed resources
• WMI infrastructure
• Consumers
Let's do a second example in the same script, we want to list all running processes like a task
manager does:
isQuery:= 'SELECT * FROM Win32_Process';
iset:= WMIExecQuery(isser, isQuery); //WbemObjectSet;
writeln(botoStr(WMIRowFindFirst(iset, ENum, tempObj)));
it:= 0;
repeat
PrintF('Processes run: %s - PID %s',[tempobj.name,vartoStr(tempobj.processid)])
inc(it)
until not WMIRowFindNext(ENum, tempObj);
writeln('running Processes : '+itoa(it))

So, if the scripting steps to retrieve information from WMI are identical, what are the
Win32_Process, Win32_Service, and Win32_NTLogEvent classes? Furthermore, where do
they come from, what other classes are available, and how do you use them? The answers to these
questions lie in the components that make up the WMI architecture. As I said we mapped the type
library to functions to simplify the handling in a dynamic script, let’s have a look at the interface:
// *********************************************************************//
// DispIntf: ISWbemPropertyDisp
// Flags: (4432) Hidden Dual OleAutomation Dispatchable
// GUID: {1A388F98-D4BA-11D1-8B09-00600806D9B6}
// *********************************************************************//
ISWbemPropertyDisp = dispinterface
['{1A388F98-D4BA-11D1-8B09-00600806D9B6}']
function Value: OleVariant; dispid 0;
property Name: WideString readonly dispid 1;
property IsLocal: WordBool readonly dispid 2;
property Origin: WideString readonly dispid 3;
property CIMType: WbemCimtypeEnum readonly dispid 4;
property Qualifiers_: ISWbemQualifierSet readonly dispid 5;
property IsArray: WordBool readonly dispid 6;
end;

The dispinterface statement defines a set of properties and methods on which you can call.
This function value will add a value of the type OleVariant that are represented by their properties
(digits, strings and more) so we use in most cases strings as the representation of the value
(VarToStr()).
You can use WMI in maXbox by early binding (pre compiled with WbemScripting_TLB; ) or late
binding with CreateOleObject() .
wmiLocator:= CreateOleObject('WbemScripting.SWbemLocator');
As you begin to write scripts to interact with WMI managed resources, you'll often see the term
instance used to refer to a virtual representation of the managed resource in the running script.
So we check the availability of the WMI late binding:
(ClassIDToString(StringToClassID('WbemScripting.SWbemLocator'));
writeln('WMI Installed:
'+botoStr(ProgIDInstalled('WbemScripting.SWbemLocator')))

>>> {76A64158-CB41-11D1-8B02-00600806D9B6}
WMI Installed: TRUE

an interesting service is always BITS : (you guess why?)


case: BITS - Background Intelligent Transfer Service --Running
Also within WMI, there are numerous growing provider methods which will do different things.
At least there are two ways to install and configure your box tool into a directory you want.
The first way is to use the unzip command-line tool or IDE, which is discussed above.
That means no installation needed. Another way is to copy all the files to navigate to a folder you like,
and then simply drag and drop another scripts into the /examples directory.
https://maxbox.codeplex.com/
The only thing you need to backup is the ini file maxboxdef.ini with your history or another root
files with settings that have changed

8 maXbox Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


WORK WITH WINDOWS
MANAGEMENT
INSTRUMENTATION PAGE 4/4
maXbox
Feedback @ max@kleiner.com
Literature: Kleiner et al., Patterns konkret, 2003, Software & Support
https://github.com/maxkleiner/maXbox4/releases
https://www.academia.edu/31112544/
Work_with_microservice_maXbox_starter48.pdf

REFERENCES
Examples and Version of this Tutorial 52:
2017-05 Cumulative Update for Windows 10 Version 1607 for x64-based
Systems (KB4019472) – maXbox 4.2.5.10
http://www.softwareschule.ch/examples/766_wmi_management.txt
http://www.softwareschule.ch/examples/
210_public_private_cryptosystem5_ibz_herdt2.txt

Examples of WMI Routines:


WMI Scripting Primer:
https://msdn.microsoft.com/en-us/library/ms974579.aspx
http://www.softwareschule.ch/examples/750_RSA_Toolproof4.txt

WMI and Database SQL Programming Starter 12 Tutorial and Tutorial 52


http://www.softwareschule.ch/download/maxbox_starter12.pdf

DispInterface explain:
https://msdn.microsoft.com/en-us/library/ebhsdt9x.aspx
http://www.delphidabbler.com/tips/216

_od#HMM6&*MMMH::-_
_dHMMMR??MMM? ""| `"'-?Hb_
.~HMMMMMMMMHMMM#M? `*HMb.
./?HMMMMMMMMMMM"*""" &MHb.
/'|MMMMMMMMMMM' - `*MHM\
/ |MMMMMMHHM'' .MMMHb
| 9HMMP .Hq, TMMMMMH
/ |MM\,H-""&&6\__ `MMMMMMb
| `""HH#, \ - MMMMMMM|
| `HoodHMM###. `9MMMMMH
| .MMMMMMMM##\ `*"?HM
| .. ,HMMMMMMMMMMMo\. |M
| |M'MMMMMMMM'MMMMMHo |M
| ?MMM'MMMMMMM'MMMM* |H
|. `#MMMM'MM'MMMMM' .M|
\ `MMMMMMMMMMM* |P
`\ MMMMMMMMT"' ,H
`\ `MMMMMMH? ./
\. |MMMH#" ,/
`\. |MMP' ./'
`~\ `HM:.- . ,/'
„-\_ '_\ . _.-"
„-\-#odMM\_,oo==-"

THE

IS AT THE EUROPEAN PASCAL, DELPHI


& C++BUILDER CONFERENCE 19 SEPTEMBER
EINDHOVEN

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE maXbox 9


QUANTUM COMPUTING BASIC INSIGHTS PAGE 1/6
BY DETLEF OVERBEEK

INTRODUCTION
This article attempts to remove some of the fog
surrounding the complex subject of quantum
computing.
I was privileged recently to talk to Koen Bertels, one
of the leaders of the quantum project at the Computer
Engineering Lab & QuTech (Delft University of
Technology) http://ce.et.tudelft.nl.

Right at the first time I talked to Mr. Bertels I


suggested that I was very proud that this all happened
at the Dutch University of Delft as being Dutch myself.
His answer was very nice, but he let me know that he
was a Belgian, working since over 15 years on the
project, and I had of course to correct my mistake and
apologised, mumbled something like international and
realized that this kind of research is done all over the Figure 1 Left: Koen Bertels, the head of the
world in many countries. Department of Quantum Engineering
Figure 2 Right; The quantum Chip
The architecture of a quantum computer is essentially
two-part: a classical module (running as a normal
computers, because of the exponential cost for
non-quantum computer) and a quantum computing classical computers. So we start first by looking
module. at Superposition and Entanglement.
The classical module is needed to resolve errors and (There are some nice videos illustrating
problems and run algorithms that use both classical superposition visually, see page 14).
logic and quantum logic. Quantum logic is not
SUPERPOSITION:
explained here in depth because it is very abstract and
Qubit is short for quantum bit, a type of bit
hard to understand, requiring a deep dive into a new,
alien world. which differs from the classical computer bit
which is an information carrier that is only ever
Here I will try to explain a typical quantum system by in one of two mutually exclusive states, 0 and 1.
describing in some detail the layers within a quantum
computer, using as many illustrations as possible. I aim to
help you understand how it works, and what you can expect To understand the underlying theory, you must
of it… So don't be afraid, even though the description is realise that we are talking about infinitesimally
sometimes rather abstract. Much of this article is based on a small, moving particles, particles that are never
very technical document entitled in only one position.
“Computing_Frontiers__Quantum_Execution”. The particles cannot be seen, only traced at a
If this sparks your interest, you can download the full paper
(with all its technical detail) from our web download page. particular moment.
Strangely, at this quantum level, the particle is
With such completely new concepts as we encounter in never in one unambiguous state.
quantum computing it is hard for a brief article to convey all
It could be seen as 1 at one moment, yet an
you need to know without diving deep into very theoretical
realms. So my approach will be to describe a quantum instant later it could be seen as 0, so what you
system by enumerating the various different layers needed to “see” is a continual change between states.
build a working quantum computer. I’ll illustrate the control Like a picture of a mountain which a moment
logic needed, and the path it follows in order to execute
“quantum instructions”. later shows an absolutely flat plain.
This continuously changing aspect of the qubit
is called superposition. (See figure below).
While you look at it, it has one state (or position),
and the next moment it has another.
The research on quantum computing began in
1982 when Richard Feynman* suggested using a
quantum system to simulate another quantum
system.
The basic idea is to make practical use of two
fundamental quantum mechanical phenomena:
superposition and entanglement.
These phenomena make it possible to develop
unbelievably advanced computational capacity,
1
01101 01
101
so much so that quantum computers can tackle
problems that are hard to solve using classical Figure 3: Superposition

10 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


QUANTUM COMPUTING BASIC INSIGHTS PAGE 2/6

To demonstrate that superposition you can send ENTANGLEMENT


an electromagnetic wave to the quantum object. Qubits have certain properties which are very
It then collapses and reveals its position. hard to visualise. A qubit’s ability to become
But your interaction with it has changed it entangled with another qubit is one such
completely. property.
That is why it is very difficult to read its value, Entanglement is something like a close
implying that a quantum state cannot be connection. It means that any change made to
measured directly without losing the stored one qubit immediately provokes a reaction in its
information, and that your measurement can be entangled qubit. It’s like a human twin who
misleading. intuitively knows immediately when something
happens to its other twin.
However we can, with difficulty, measure the Here the distance between them is immaterial.
state of a qubit: it is either one or zero. This qubit property has the great advantage that
This is essential for the creation of a quantum measurement of the value of one entangled qubit
computer, which we see is an extension of a enables you to know the properties of its
classic computer which also works with the entangled counterpart, without the need to
value of bits (as either one or zero). measure it.
In classic computers the internal chips have A classical computer’s logic gate can collect a
transistors which are connected to form logic simple set of inputs and then the gate will output
gates. a final value.
A QUANTUM STATE CANNOT
A transistor is the simplest A quantum gate can
BE MEASURED DIRECTLY
form of data processor. It is manipulate the input of
a switch that can either block
WITHOUT LOSING THE superpositions and move the
or allow the information STORED INFORMATION possibilities around and
coming through. The transistors are arranged to create an other superposition as its output.
form a logic gate . For example in a classical A quantum computer first sets up some
computer, an AND gate outputs 1 if all of its entangled qubits, then uses quantum gates to
inputs are 1 and outputs 0 if any input is not 1. process their superpositioned values, and then
collapses the superposition output to an actual
Quantum chips do not use transistors, even sequence of classical bits (0s and 1s) giving a final
microscopic transistors of atomic dimensions, output value.
but use subatomic particles .
Laser beam
A qubit based on such a particle can be in a
superposition of probabilities for 0 and 1, and it’s
not possible to predict which one it is or will be. Crystal
However its actual value can be measured. In
current implementations the maximum number Vertically-polarized
of operational qubits achieved per quantum chip photons
is ten (and several companies are racing to try to
develop chips which exceed this number of qubits per
chip).

The closing section of this article lists a number


of web links giving further in-depth discussion
of these topics, including some really beautiful
and helpful web pages.
Horizontally
As you know, 4 classical bits can be in 1 of 2 to -polarized
the power of 4 different configurations at one photons
time, i. e. 16 possible combinations. A qubit is a
little different: if it’s in superposition it can be in
all of these 16 states at once.
So the number of combinations grows
exponentially with each added qubit.
Twenty qubits can store 220 (1,048,576) values.
Figure 4: Entaglement Entangled photons

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 11


QUANTUM COMPUTING BASIC INSIGHTS PAGE 3/6

Quantum computers have this huge advantage: 2. will thus be executed by their respective
they process all the required calculations (based computing blocks.
on their setup conditions) at the same time! It is You must realize that the Quantum computer
only possible to measure one of all the possible Chip needs to be at a very low temperature.
results. Perhaps it is the one you want. You have Otherwise we would never be capable of
to check and double-check and try again if collecting any Qubits. These temperatures are
necessary. Maybe with repeated inspection and near(very near) the absolute lowest temperature
investigation of the superposition and we can achieve.
entanglement you can find an answer that has
been reached far more efficiently than by using a This is done by Laser-cooling and is primarily
classic computer alone. used to create ultracold atoms for experiments in
quantum physics. These experiments are
Even though the potential of quantum performed near absolute zero. In 2011, a team
computing is huge, its weak point is the fragility from the California Institute of Technology and
of the qubits. Qubits inevitably interact with their the University of Vienna became the first to
environment, and their information of qubits laser-cool a (10 μm x 1 μm)* mechanical object to
leaks to the environment. This is called its quantum ground state.
“decoherence” because the information you want *(micrometer 10 μm = 0,01mm).
is lost. Coping with qubit fragility is therefore
one of the main challenges involved in building QUANTUM ERROR CORRECTION
and operating a quantum As I already mentioned,
computer. Qubit fragility
CURRENT STATE-OF-THE-ART the main handicap of
causes errors during QUANTUM CHIPS CONTAIN quantum technology is its
computation. To reduce AROUND 10 QUBITS. fragility. QEC is more
errors to minimum most challenging than classical
quantum computers operate at super-cooled error correction. The basic idea of QEC techniques
temperatures close to absolute zero, and so is to use several physical imperfect qubits to
require large and sophisticated refrigeration compose more reliable units called “logical
apparatus. qubits” . Such encoding does not need to clone the
qubit state, as it is done by entangling several
Quantum Error Correction (QEC) mechanisms qubits called “data qubits” . Since quantum errors
are needed to make quantum computing fault- accumulate as time elapses, Error Syndrome
tolerant. The challenge of building fault-tolerant Measurement (ESM) has to be done repeatedly.
quantum circuits, developing a quantum QEC allows fault tolerant computation and is thus
computer called the “standard universal a fundamental part of any quantum computing
quantum computer“ are huge. The physics system. The drawback is that it dramatically
challenges include: increasing the number of increases the number of physical qubits needed
qubits per chip that can be entangled, for running any quantum algorithm.
increasing the qubits’ lifetimes, and increasing
the qubits’ operational fidelity.
Quantum engineers are currently developing
technology that they hope will provide high
speed control-logic in a scalable and flexible way.
(The work on this University of Delft quantum
computer is funded by Intel in the context of the
QuTech-Intel collaboration.)
Current state-of-the-art quantum chips contain
around 10 qubits.

A quantum computer will always consist of


both quantum and conventional computing
components because of the following two
reasons:
1. the quantum algorithms and consequently the
quantum applications that will be executed,
consist of both classical as well as quantum parts Figure 5: Overview of quantum computer system stack

12 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


QUANTUM COMPUTING BASIC INSIGHTS PAGE 4/6

Pragma Parser
Annotated
Code

QUANTUM ACCELERATOR COMPILER

Logil Q Circuit

Logical QIS
Reversible Circuit
decomposition &
Design
optimization

Logical QASM

Host Logical Circuit Mapping(with schedule)


Compiler

Logical QISA
FT Implementation of Logical Circuits

Physical Circuit Mapping (with schedule)

Physical QASM (virtual Q adresses)


Figure 6: Compiler infrastructure

Linker Loader

RELATED RESEARCH
The first quantum algorithm was proposed by David Deutsch in 1985 along with the Quantum Turing
Machine. A lot of work has been done since then and nowadays we can find more than 50 basic
quantum algorithms. The most representative example of a quantum algorithm is the famous Shor’s
Factoring algorithm that is used to factorize a very large number.
It is the first quantum algorithm that has an application to real world problems, e.g. decryption, and
shows exponential speed up over its classical counterparts. However, Shor’s algorithm requires
millions if not billions of physical qubits for factorizing big numbers.

Figure 7 Peter Shor at work.


About Shor's algorithm, named after mathematician Peter Shor, is a quantum algorithm
(an algorithm that runs on a quantum computer) for integer factorization formulated in 1994.
Informally it solves the following problem: given an integer N, find its prime factors. Take a look
at the video where he himself explains it.

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 13


QUANTUM COMPUTING BASIC INSIGHTS PAGE 4/6

I wanted to show the enormous complexity of the design.


Because of that there is no explanation of all the different details.
If you are interested you can download the paper where all the
details are explained in, but its very technical and needs a lot of
explanation, which is out of the scope of this article...
“Computing_Frontiers__Quantum_Execution”

What is Shor's factoring Quantum superposition of states Where are the limits of human Quantum Computer in a
algorithm? and decoherence technology? And can we Nutshell with the newest
somehow avoid them? technolgies of the moment:
https://www.youtube.com/ http://toutestquantique.fr/ This is where quantum computers
watch?v=hOlOY7NyMfs en/superposition/ become very interesting. https://www.youtube.com/
watch?v=0dXNmbiGPS4
https://www.youtube.com/
watch?v=JhHMJCUmq28

14 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


QUANTUM COMPUTING BASIC INSIGHTS PAGE 4/6

CONCLUSION
I have shown how the phenomena of Superposition and Entanglement form two key components in quantum
computers. I am not sure the future will give us even more strange phenomena which will make it possible to solve
one of the biggest problems: the cooling of the chips (needed for the molecules to be as steady as possible). There might be a
solution: Pressure. So the outcome for now is that we will not see in the near future a Quantum Notebook. It would
probably be a little-bit costly as well. But by creating more and more algorithms for the quantum machine we will
even be capable of creating better algorithms for classic computers we would otherwise not be able to achieve. If
you look at it, we all want to have computers that work faster and faster.
We want immediate answers instead of surfing the Internet. We want to solve problems that we just can't
do(Yet). We want more graphics and the market wants things smaller, we want it ultra fast. We can use the
quantum computer: one would be able to solve enormous problems you simply can’t solve with classical
computers: voice-activation, device technology and translations, the development of new drugs, climate
change prediction models, weather predictions on long term, optimization of traffic control, development of
robotics, machine navigation and shape recognition.
We need algorithms and software. We need them for the use of encryption.
For now we have for the first time a starting point for a real quantum computer.
It already exists and is used, - experimental still. Yet quantum computer development is still in its infancy.
However, this is not a stepwise development from classical computers, but a revolutionary jump.
15
We live in very exciting times!
GETTING FRAMED (THE FRAMEWORK PROJECT) PAGE 1/6
BY DAVID DIRKSE
If ever you wanted to create
your own storage rack, you
probably know the trouble you
will have making it stable. If
force is applied to a rectangular
box, it may become distorted
and turn into a parallellogram.
However, if a brace is attached
between opposite
joints, the rectangle
is now transformed
into two triangles and
distortion is not
possible. See Figure 1.

Figure1.
Using above boxes we may build frames of several
rows and columns.
Then the question arises which boxes should be
braced to make a rigid structure.
This framework project was built to answer this
question.
If a frame is not rigid, the distortion is showed.
Also superfluous braces may be marked and
removed to obtain a minimally braced rigid frame.
Figure3.
Below is a picture of the framework program at
work.
Per box the brace must be
recorded. bbRemoved
indicates a removed brace,
which was superfluous.
Figure2.
The frame is defined by its
Note: there is no difference in the effect of coordinates (x,y). All drawing is done in a bitmap
ascending- and descending braces. (map). The map is displayed in a paintbox when
drawing is finished. This prevents drawing actions
Distortion depends on the direction of applied to cause flickering of the screen. Figure4.
forces. I have choosen right- and down forces.
CODING THE PROBLEM
Columns and rows count 0..7 (maximum).
Boxes are coded 0..3

box type 0: vertical and horizontal edges.( binary code 00)


box type 1: rotated horizontal edges. (binary code 01)
box type 2: rotated vertical edges. (binary code 10)
box type 3 both edges rotated. (binary code 11)

Below is a picture showing columns,rows, box types


and braces.

16 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


GETTING FRAMED (THE FRAMEWORK PROJECT) PAGE 2/6

So, to display the frame distortion, simply the


(x,y) coordinates have to be changed.
Here are the types, constants and variables
needed for drawing:
type TBoxBrace = (bbNone,bbBrace,bbRemoved);

const leftmargin = 40;


topmargin = 40;

var framewidth : byte; // 1..8 number of boxes


frameheight : byte; // 1..8
boxbrace : array[0..7,0..7] of TBoxBrace;
coords : array[0..8,0..8] of TPoint; // coordinates of joints
map : TBitmap; // holds frame

The left-top (x,y) angle of a box is the


reference. The other coordinates of the box
angles depend on the box type and are relative
to the left-top

PAINTFRAME
Boxes are painted left to right,
top to bottom.
The box position is coded in
variable code:

0 : left top
paint all edges
1 : top row
paint top, right and bottom edges
2 : left column
paint left , bottom and right edges
3 : other
paint bottom and right edges

The dx-,dy- values are stored in a Reason is to save time by avoiding drawing of
constants array[0..3] per box type 0..3: the same lines. Part of typical source code:
const offset : array[0..3] of TOffset = case code of
((dx1: 0; dy1: 60; dx2: 100; dy2: 60; dx3: 100; dy3: 0), //0 0 : begin //l eft top
(dx1:-25; dy1: 54; dx2: 75; dy2: 54; dx3: 100; dy3: 0), //1 moveto(coords[i,j].x, coords[i,j].y);
(dx1: 0; dy1: 60; dx2: 91; dy2: 102; dx3: 91; dy3: 42), //2 lineto(coords[i+1,j].x, coords[i+1,j].y);
(dx1:-25; dy1: 54; dx2: 66; dy2: 96; dx3: 91; dy3: 42)); //3 lineto(coords[i+1,j+1].x, coords[i+1,j+1].y);
lineto(coords[i,j+1].x, coords[i,j+1].Y);
lineto(coords[i,j].x, coords[i,j].y);
end;
Above dx,dy values are calculated using basic …......................
goniometric functions. 2 : begin // left
Procedure testframe tests the frame and modifies moveto(coords[i+1,j].x, coords[i+1,j].y);
lineto(coords[i+1,j+1].x, coords[i+1,j+1].y);
the coordinates.
lineto(coords[i,j+1].x, coords[i,j+1].Y);
Procedure paintFrame paints the frame. lineto(coords[i,j].x, coords[i,j].y);
end;
….......................
end; // case

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 17


GETTING FRAMED (THE FRAMEWORK PROJECT) PAGE 3/6

For details please refer to procedure paintframe PRACTICE OF RIGID BOX TESTING
source code. So far for the painting. Now the Function rigid(xcol,xrow : byte) : boolean;
harder part: testing the frame for rigidity. returns true if box(xcol,xrow) is rigid.
This function is the core of this project.
THEORY OF RIGID BOX TESTING These are the local variables:
A box is called rigid if it cannot be distorted. It var stepNr,n,v : byte;
keeps straight angles. box : array[1..16] of Tbox;
So these boxes are of type 0 or 3. colEnables : byte;
Of course a braced box is rigid. rowEnables : byte;
GO : boolean; // false to exit repeat loop
But look at the next picture where the left-top
box is not braced but sure is rigid:
stepNr:
counts 1,2,3... as we step from row to column.
StepNr 1 finds a brace in its row, stepNr 2 a brace in
its column ...etc.
box[1..16] :
search path of (x,y) coordinates
ColEnables, rowEnables
start at value $ff [11111111] binary, enabling all
rows/columns. If a column or row is part of the path,
the corresponding bit is set to zero to
avoid visiting this row/column again.
This avoids loops in the path.
Go:
a boolean flag for repeat loop exit control.
Other variables
defined outside this function are playing a role:
var columnvector : array [0..7 ] of byte ;
To examine box (0,0) for rigidity : rowvector : array[0..7] of byte;
look for a brace in row 0 and find one in column 2
now look for a brace in this column and find one in columnvector, rowvector:
row 2. Next look for a brace in row 2 and find one bit coded brace positions in rows 0..7, columns 0..7
in column 0 made by makeconnectionvectors from boxbrace[ ]
array;
box :
This is the column where we started, which shows
history of boxes on path, used to trace backward
that box(0,0) is rigid. If such a path from box(0,0)
on row 0 to column 0 is not found then box(0,0) is Function rigid has this little helper function:
not rigid and will be a parallellogram, type 1 in
function nextRect(var n : byte; vec : byte) : boolean;
this case. // true if brace(bit) in vector vec; n : lowest bit set in vec
begin
Why is this true? result := vec <> 0;
Looking back to previous pictures we notice that if result then
in a row all left-right edges of the boxes are begin
parallel. In a column all top-bottom edges of the n := 0;
boxes are parallel while ((1 shl n) and vec) = 0 do inc(n);
end;
Box(0,0) and box(2,0) vertical edges are parallel. end;
Box(2,0) and box(2,2) horizontal edges are parallel.
Because both boxes are braced also box(2,0) and
box(2,2) vertical edges are parallel.
Same is true for box(2,2) and box(0,2).
So, boxes(2,2) and box(0,2) have parallel edges.
So, column 0 is perpendicular to row 0 and
box(0,0) is a rectangle.

When is the complete frame rigid?


From the previous theory we conclude that it is
sufficient to proof that all boxes in row-0 and all
boxes in column-0 are rigid.
The type of these top and left boxes fully
determines the type of all other boxes.

18 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


GETTING FRAMED (THE FRAMEWORK PROJECT) PAGE 4/6

Byte vec has bits set for a brace in the column/row


if this column/row has not been visited before.
Below is the flowchart of function rigid:

FRAME TESTING The first test is for the left-top box. If rigid, the
Testing the complete frame for rigidity is box type becomes 0, else the type is 1.
accomplished by procedure testframe. Then the next box at (1,0) is tested. This box type
It is sufficient to test only the top row boxes by depends on 1. rigidity and 2. the previous
calling function rigid. box(0,0).
This procedure also changes the frame For a rigid box, the next boxtype is precoded in
coordinates according to the box type found. contstant topcodesR[0..3]
Variables: for a non-rigid box this is topcodesNR[0..3]
var i,j : byte; // column, row Example:
bxt : byte; // box type etc. if box(0,0) is non-rigid (so type 1) and box (1,0)
topbox : array[0..7] of byte; // top row box types is rigid then box (1,0) is of type
leftbox : array[0..7] of byte; // left column box types
topcodesR[1] which is type 3.
xref,yref : smallInt; // left-top box coordinates
corr : smallInt; // correction value, shift frame
If box(0,0) is rigid and box (1,0) is non-rigid then
RFlag,CFlag : boolean; box (1,0) is of type topcodesNR[0] = 2.
The previous boxtype is the index into these
constant arrays.

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 19


GETTING FRAMED (THE FRAMEWORK PROJECT) PAGE 5/6

Next picture lists the top box choices:

So far the top boxes. The horizontal bit comes from the top box, the
At this point the bottom and top edge directions vertical bit from the left box. Afterward the frame
of all boxes are fixed. is shifted horizontally by value corr to maintain a
This means that the left- and right edges in a row left margin.
are also fixed if this row contains a braced box.
Testing continues with the left column box (0,1), SAVING AND LOADING
just below the top-left box. If this row has a braced Frames may be saved / loaded to/from disc.
box, boolean variable Cflag sets true. The data format allows for future expansion to
Source code (without code for coordinates change): frames of 32 * 32 columns/rows maximum.
Cflag := nextRect(bxt,rowvector[j]); // braced box in row? Data I/O is typed. Files have no extension.
if CFlag then The data pack consists of 37 dwords (cardinals)
begin
bxt := topbox[bxt];
bxt := ((bxt and $2) shr 1) or (leftbox[0] and $2);
end
else bxt := leftCodesNR[bxt];

The vertical edge is derived from the topbox


horizontal direction and the horizontal edge is
the left-top horizontal edge direction.
Left column successor box types:

The pack starts with text “davdataframework”


For boxes not at the top row or the left column, for identification. Brace fields have a bit set for a
this code does the job: brace in the row.
for j := 1 to frameheight-1 do // not top or left Please refer to the source code for more details.
for i := 1 to framewidth-1 do
begin
xref := coords[i,j].x;
yref := coords[i,j].y;
bxt := (leftbox[j] and $1) or (topbox[i] and $2);
coords[i+1,j+1].x := xref + offset[bxt].dx2;
coords[i+1,j+1].y := yref + offset[bxt].dy2;
end;
Issue Nr 5 2017 BLAISE PASCAL MAGAZINE
GETTING FRAMED (THE FRAMEWORK PROJECT) PAGE 6/6

POSTSCRIPT
This problem was found in the book “Graphs, an
introductory Approach” by Wilson and Watkins.
About the author
A graph in mathematics is a drawing of points David Dirkse
which may, or may be not, connected by lines. After a study of electrical engineering,
Such a drawing is abstract and may represent David joined the Control Data Corporation,
topics like: an American computer company, and worked
road maps almost 25 years installing and maintaining
networks scientific data centers in the Netherlands.
chemical molecules He has witnessed the evolution of computer
interdependent processes hardware from the first transistorized
mainframes (CDC3300) to the supercomputers
There are many varieties of graphs, one being a so of the eighties (CYBER205). During this period
called bipartite graph where lines connect he attended over 100 technical courses and
was instructor in over 30 occasions. At the
between 2 groups of points without lines between
decline of CDC around 1990, David started a
points in the same group. study of mathematics and became a math
Also graphs may have several properties one teacher in 1993. One of his hobbies is
being connected. This means that using programming, specializing in puzzle solving,
connecting lines travel from a point to any other drawing and basic algorithms.
point is possible.

The frame problem may be represented by a


bipartite graph by assigning a point in group 1 for
each column and a point in group 2 for each row.
A line from a column to a row shows that the box
in this column / row is braced.
The frame is rigid if the graph is connected.

See examples below:

disconnected graph connected graph


The top row of points are the columns (0,1,2,3,4) .
The bottom points are the rows (0,1,2,3) of the
frame.

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 21


THE

EUROPEAN DELPHI &


C++BUILDER CONFERENCE
19 SEPTEMBER 2017
Bob Swart - Dutch spoken / Maak Services based Keynote:Mattias
09:30-10:15 Pawel Glowacki
Gärtner -- English
Technicalspoken
Lead Embarcadero - The New Direction David Millington
of Delphi- English Spoken
applicaties in RAD Server Pas2JS Compiler Jens Fudge - FireDAC Fun „Updates", "What's New", "Stuff you're missing
In deze sessie laat Bob zien wat RAD
10:20-11:15 Server
Showing various in welke
is en bits and piecesThe
of FireDAC
Pas2JS including is a new type
Compiler ArrayDML, of Pascal
LocalSQL, 2 Javascript
cached Updates, FDMemtable
out on“and other goodies from FireDAC.
situaties RAD Server uitermate goed toepasbaar is. Na deze compiler. We will show
Also an Introduction of examples of programs
CData - Connect you can
via FireDAC build
with Are you a C++Builder developer, but not yet using the latest
all Applications
korte introductie gaan we in op het uitbreiden van RAD
11:15-11:30 and show a demo. HighlightsGo toof the compiler:
Break Out Session technologies. David will show you all about the Clang
Server met eigen microservices. U zult zien hoe u met - Delphi and ObjFPC syntax. You can choose which one for compilers, codegen, linker fixes, and some great new stuff
Delphi nieuwe EMS Swart - Dutch
Bobpackages kunnenspoken
maken / enMaak
debuggen,
Services every
basedunit.Mattias Gärtner - English spoken for Android Millington
David and - English Spoken
iOS development. In addition he will show
inclusief customapplicaties in RAD Server
REST API endpoints. In combinatie met Pas2JS
- "Source Maps" Compiler
allow browsers to show the Pascal code „Updates",
the new "What's
world around New",
us and what "Stuff
you canyou're
do withmissing
your
FireDAC kunnenIn deze
deze sessie laat
packages Bob
data uitzien wat RAD Server is en
verschillende while The Pas2JS Compiler is a new type of Pascal 2
in debugging. existing
outand
on“new applications to get there. During his
welke situaties RAD Server uitermate goed toepasbaar
databases deployen. Javascript
- Use strong compiler.
typing, while still be will show
Weable to useexamples
low level of session you
Arehe will C++Builder
a use inspiringdeveloper,
examples,but not yet
provide using
tips and the
is. Na deze korte introductie gaan we in op het whenever you programs
choose.
you can build and show a demo. Highlightstrickslatest technologies.
and get David will show
you highly motivated whithyou
newall about
idea's the
and
uitbreiden van RAD Server met eigen microservices. U
- Supports of the compiler:
syntax elements Clang
technical compilers, codegen, linker fixes, and some great
possibilities.
zult zien hoe u met Delphi nieuwe EMS packages - Delphi and ObjFPC syntax. You can choose which one new stuff for Android and iOS development. In addition
11:30-12:20 kunnen maken en debuggen, inclusief custom REST for every unit. he will show the new world around us and what you
API endpoints. In combinatie met FireDAC kunnen - "Source Maps" allow browsers to show the Pascal can do with your existing and new applications to get
deze packages data uit verschillende databases code while debugging. there. During his session he will use inspiring
deployen. - Use strong typing, while still be able to use low level examples, provide tips and tricks and get you highly
whenever you choose. motivated whith new idea's and technical possibilities.
- Supports syntax elements
Andrea Magni - English spoken Bruno Fierens - Dutch spoken David Millington - English spoken
Building FMX Linux Client Application for MARS Geografische functies in Delphi applicaties inbouwen C++Builder and Linux
MARS is a REST library for Delphi that enables each via Google Maps David wil show you a preview LLVM based Linux compiler for
developer to build application servers and client Via Google Maps is het mogelijk tal van geografische Enterprise development, enabling C++Builder developers to
applications, on 5 platforms! Thanks to the Linux support functionaliteit in VCL Windows applicaties of FMX cross- target 64-bit Intel Linux servers and devices. The Linux
(added by Embarcadero with 10.2 Tokyo) and third party platform applicaties in te bouwen. In deze sessie wordt compiler is certified for Ubuntu Server (LTS 16.04) and
12:20-13:00 Lunch in the restaurant
products like FMX Linux, there is no limit for Delphi getoond hoe je kan omgaan met programmatorisch locaties RedHat Enterprise (V7) and is built on top of the LLVM
developers wanting to implement
Andrea Desktop,
Magni - English mobile, web
spoken aan te duiden,
Brunoclusteren
Fierensvan locaties,
- Dutch fotos aan locaties te
spoken engine.
David is enabled for
ARCMillington effective
- English memory management,
spoken
service-to-service
applications andBuilding FMX Linux solutions.
Client Application for MARS adres naar locatie
koppelen, Geografische en omgekeerd
functies in Delphi bepalen, POI
teapplicaties to ensure compatibility
whileC++Builder and Linux with code written for Windows
In this session you
MARSwillissee
a REST
how library a visual
to buildfor DelphiFMX
thatclient (point of interest
enables each inbouwenbestanden)
via Googleop een
Mapskaart te visualiseren, Server,
David based
one wil showstrings
you a are
preview by default.
used LLVM based Linux
for a MARS (REST) application server.
developer to build application servers and client routes te bepalen en routes te importeren en exporteren
Via Google Maps is het mogelijk tal van geografische compiler for Enterprise development, enabling
applications, on 5 platforms! Thanks to the Linux naar navigatie
functionaliteit
systemen in tenslotte
enVCL Windowsgeografische
applicaties of FMX C++Builder developers to target 64-bit Intel Linux
support (added by Embarcadero with 10.2 Tokyo) informatie
and cross-platform GeoJSON formaat
aangeleverd inapplicaties in te bouwen.
op eenInmap
deze
te sessie servers and devices. The Linux compiler is certified for
tonen.
third party products like FMX Linux, there is no limit wordt getoond hoe je kan omgaan met Ubuntu Server (LTS 16.04) and RedHat Enterprise (V7)
13:00-13:50 for Delphi developers wanting to implement Desktop, programmatorisch locaties aan te duiden, clusteren and is built on top of the LLVM engine. ARC is enabled
mobile, web applications and service-to-service van locaties, fotos aan locaties te koppelen, adres naar for effective memory management, while to ensure
solutions. locatie en omgekeerd te bepalen, POI (point of interest compatibility with code written for Windows Server,
In this session you will see how to build a visual FMX bestanden) op een kaart te visualiseren, routes te one based strings are used by default.
client for a MARS (REST) application server. bepalen en routes te importeren en exporteren naar
Den Zubov - English spoken Danny Windnavigatie
- Dutchsystemen
spokenen tenslotte geografische Ludo Stroetenga - Dutch spoken
Introduction FastReport VCL version 6 (beta) informatie
Modernizing VCL applications,
aangeleverd a GeoJSON
infield guideformaat
to bring
op een Case Study : CurieWise
Den will inform you about the great new features of your VCL map
application
te tonen.to 2017 Het werken met radioactieve straling of het werken in een
FastReport 6 VCL. During this live-demo he will show you Deze sessie laat Danny zien hoe u een bestaande applicatie werkomgeving waarin dit voorkomt, brengt risico’s voor de
how and why you should use interactive objects in the met een wat oudere User Interface en onderliggende gezondheid met zich mee. Deze risico’s worden beperkt
report and report designer. Learn more about the new technieken weer helemaal up-to-date kunt maken. Hij laat door het verzorgen van een veilige werkomgeving. Met het
report objects. Where and how to save rport outpunt and zien hoe u een applicatie een frisse look geeft met Styling, product CurieWise wordt deze omgeving nagebootst. Het
atemplates.
13:50-14:00 WYSYWYG in export? And last subject he new Win10 elementen en tactile to Break Out
Go feedback. Ook Session
versnelling en doel van dit product is een realistische weerspiegeling van
vector export engine. optimalisatie van de User Experience komt aan bod met de werkelijkheid te creëren waarin deelnemers getraind
Den Zubov - English spoken Async SQL,Danny
achtergrond Dutch spoken
Wind -threading en Interbase Ludo
kunnen Stroetenga
worden. - Dutch
Het product CurieWise
spokenbestaat uit een
Introduction FastReport VCL version 6 (beta) Modernizing
ChangedViews. Tevens laatVCL applications,
Danny zien hoe je
a code
field guide to aantal Case
applicaties CurieWise
Study :namelijk:
Den will inform you about the great new features of bring
optimaliseert metyour
o.a. VCL application
het gebruik van Generics
to 2017en Het werken
- CurieWise Controlmet(FireMonkey
radioactievewindows of het werken in
straling desktop)
show
FastReport 6 VCL. During this live-demo he will TDictionary. Deze sessie laat Danny zien hoe u een bestaande een werkomgeving
- CurieWise waarin dit voorkomt,
Dosismeter (FireMonkey brengt risico’s
Android mobile)
you how and why you should use interactive objects in applicatie met een wat oudere User Interface en - CurieWise gezondheid
voor deAccess (C# op met zich mee.
windows IOT Deze
core)risico’s
the report and report designer. Learn more about the onderliggende technieken weer helemaal up-to-date - CurieWise wordenMonitor door het verzorgen
beperkt(FireMonkey Androidvan een veilige
Tablet)
new report objects. Where and how to save report kunt maken. Hij laat zien hoe u een applicatie een werkomgeving.
- CurieWise Server (VCL het product
Met datasnap CurieWise
server wordt deze
via JSON)
outpunt and frisse look geeft met Styling, Win10 elementen en Ludo omgeving nagebootst.
gebruikt hiervoor JSONHetals doel van dit product
communicatie en is een
14:00-14:50 templates. WYSYWYG in export? And last subject he realistische
tactile feedback. Ook versnelling en optimalisatie vanconfiguratie weerspiegeling
/ MS-SQL als databasevan/ de werkelijkheid
SQLite . te
new vector export engine. de User Experience komt aan bod met Async SQL, creëren waarin deelnemers getraind kunnen worden.
achtergrond threading en Interbase ChangedViews. Het product CurieWise bestaat uit een aantal
Danny van Hooren - Dutch spoken Stefan Glienke English
Tevens- laat Danny spoken
zien hoe je code optimaliseert metDavid Millington
applicaties - English spoken
namelijk:
Open Data Principe ReactiveXo.a.- the
hetobserver
gebruik vanpattern done
Generics enright
TDictionary. Cross-platform C++
- CurieWise Control (FireMonkey windows desktop)
In Nederland is erg veel data vrij beschikbaar. Soms in een ReactiveX is a combination of the best ideas from the Learn- how
CurieWise
to use Dosismeter
C++Builder(FireMonkey multi-platform
to develop a Android mobile)
direct bruikbare vorm soms bruikbaar na aanpassingen. Observer pattern, the Iterator pattern, and functional app from one code base for Android and
- CurieWise Access (C# op windows IOTusingiOS core)
Door data te integreren in uw applicatie en te verrijken programming. FireMonkey
- CurieWise Monitor (FireMonkey Android Tablet)
krijgt u te maken met het Big Data principe. In deze And it is more than an API, it's an idea and a breakthrough - CurieWise Server (VCL datasnap server via JSON)
presentatie laat Danny zien hoe zijn bedrijf via een zelf in programming. It has inspired several other APIs, Ludo gebruikt hiervoor JSON als communicatie en
ontwikkelde applicatie connectie maakt met een frameworks, and even programming languages. configuratie / MS-SQL als database / SQLite .
geografische databron en hoe deze data commercieel This talk will give a first look at an implementation for
14:50-15:00 Go to Break Out Session
gebruikt wordt in hun eigen applicatie. Het betreft hier een Delphi as part of the Spring4D library (Spring.Reactive).
GIS applicatie maar
Danny principe
hetvan Hooren is toepasbaar op allerlei
- Dutch spoken Stefan Glienke - English spoken David Millington - English spoken
databronnen enOpenmeetwaarden.
Data Principe ReactiveX - the observer pattern done right Cross-platform C++
In Nederland is erg veel data vrij beschikbaar. Soms in ReactiveX is a combination of the best ideas from the Learn how to use C++Builder to develop a multi-
een direct bruikbare vorm soms bruikbaar na Observer pattern, the Iterator pattern, and functional platform app from one code base for Android and iOS
aanpassingen. programming. using FireMonkey
Door data te integreren in uw applicatie en te verrijken And it is more than an API, it's an idea and a
krijgt u te maken met het Big Data principe. In deze breakthrough in programming. It has inspired several
presentatie laat Danny zien hoe zijn bedrijf via een zelf other APIs, frameworks, and even programming
15:00-15:50 ontwikkelde applicatie connectie maakt met een languages.
geografische
Jens Fudge - English spoken databron en hoe deze data commercieelCoolblue This talk will give a first look at an implementation for Peter van Vlierberghe
AppTethering gebruikt
with extra wordt in hun eigen applicatie. Het betreft hier
stuff Delphi as part of the Spring4D library
Jens is having aeen GIS applicatie
session where he willmaarbuild
het aprincipe
system isintoepasbaar op (Spring.Reactive).
allerlei
three sprints. The first databronnen
sprint will be en meetwaarden.
a “standard”
client/Server multiuser application hooking onto a
database. He is for this sprint going with sort of an ORM
approach, with generic lists of objects, using anonymous
methods to sort objects in a list (Just to get some
interesting stuff going on). In sprint two he will hook the
multiuser applications together with App Tethering so they
15:50-16:00
can reflect on changes made to the database. Sprint three Go to Break Out Session
will extend the reflection a little bit so they no longer need
to reflect on theJens Fudge
database English spoken
at -all. Erik Stok - English spoken Peter van Vlierberghe / Ludo Stroetenga
AppTethering with extra stuff How Coolblue uses Delphi in multi channel retail - Dutch spoken
Jens is having a session where he will build a system in A behind the scenes look on how Coolblue has used Use case: globalisering en taal
three sprints. The first sprint will be a “standard” Delphi in the past decade and is still using it to build In deze presentatie wordt een oplossing voor het
client/Server multiuser application hooking onto a software that scales and adapts in the rapidly evolving aanbieden en onderhoud van meerdere talen in een
database. He is for this sprint going with sort of an e-commerce market. Different aspects of this journey software pakket van redelijke omvang in de kijker
16:00-16:50 ORM approach, with generic lists of objects, using will be touched, like the development of an application gezet. Het begint al bij de vraag hoe een team van
anonymous methods to sort objects in a list (Just to framework, leveraging database interaction, ontwikkelaars het aantal te vertalen zinnen onder
get some interesting stuff going on). In sprint two he application integration in a service oriented controle kan houden. Hoe kan het vertalen optimaal
will hook the multiuser applications together with App architecture and the move towards continuous georganiseerd worden en kan de eindgebruiker zelf
Tethering so they can reflect on changes made to the integration. daar een rol in spelen?
database. Sprint three will extend the reflection a little Na deze 25 minuten durende sessie volgt een sessie
bit so they no longer need to reflect on the database at over de communicatie server op basis van JSON.
all.
16:50-17:30 Slot note: David Millington - Be blown away when you see how Delphi programmers can add C++ to their apps and make use of either performance or C++ libraries.
STORING OBJECTS IN THE GOOGLE FIREBASE CLOUD PAGE 1/6
WITH TMS CLOUD PACK BY BRUNO FIERENS
INTRODUCTIOM and this ID is used to access the project via the
Since the latest release of TMS VCL Cloud Pack
Google Firebase API.
(http://www.tmssoftware.com/site/cloudpack.asp)
and TMS FMX Cloud Pack (http://www.tmssoftware.com Furthermore, to access a Google REST service,
/site/tmsfmxcloudpack.asp) there is now also built-in you need application credentials (for native
support to use Google Firebase for cloud data storage. client) you can request via
The architecture of Google's Firebase data storage is https://console.developers.google.com
quite simple. It offers storage of JSON data in the cloud. /apis/credentials and this consists of your
The JSON data has a unique identifier in a table and via unique application key and secret.
access with this unique identifier, this JSON data can be
read, updated or deleted. In addition, indexing rules can GETTING STARTED WITH ACCESS
be set to perform queries on the data in a Firebase table, FROM A DELPHI APP
for example, retrieve all JSON objects where a field X has To make it very easy to use data on Google
value Y. Firebase data storage from a Delphi or
C++Builder application, TMS software has
added capabilities to put objects or generic lists
of objects in a Firebase table. This is done via
SETTING UP A GOOGLE FIREBASE PROJECT
To get started with Google Firebase, navigate to the non-visual component
https://console.firebase.google.com/ TFirebaseObjectDatabase that you can put on
from where you can add a new project: the form.

When the project is created, you can find its unique ID under project settings:

24 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


STORING OBJECTS IN THE GOOGLE FIREBASE CLOUD PAGE 2/6

Setup the All published properties of the object will be


TAdvFirebaseObjectDatabase.App.Key, automatically persisted on the Google Firebase
TAdvFirebaseObjectDatabase.App.Secret with cloud. This is how the data looks when inspecting it
the credentials retrieved from the Google on the firebase console
developer console. Also setup
TAdvFirebaseObjectDatabase.DatabaseName
with the name of the database project as created
from the Google Firebase console.

To demonstrate how to use


TAdvFirebaseObjectDatabase, consider a class
we want to use in the Delphi application that
descends from TFirebaseObject:
1. TFirebaseCustomer = class(TFirebaseObject)
2. private
3. FName: string;
4. FStreet: string;
5. FZIP: integer;
6. FDoB: TDate; Note that we have explicitly set the
7. FCity: string;
8. public unique ID of the object via the cst.ID
9. constructor Create; override; property. When the ID is set at
10. destructor Destroy; override; application level, it is the
11. published responsibility of the app to use
12. property Name: string read FName write FName;
unique IDs. When no ID is set, the
13. property Street: string read FStreet write FStreet;
14. property City: string read FCity write FCity; TAdvFirebaseObjectDatabase will
15. property ZIP: integer read FZIP write FZIP; automatically create a GUID as ID.
16. property DoB: TDate read FDoB write FDoB;
17. end;

Now, after we have retrieved a connection


for TAdvFirebaseObjectDataBase to Firebase via:

1. AdvFirebaseObjectDatabase1.DatabaseName := 'TMS';
2. AdvFirebaseObjectDatabase1.TableName := 'Customers';
3. AdvFirebaseObjectDatabase1.Connect;

we can create and put TFirebaseCustomer


objects in the Google Firebase realtime data cloud:
1. var
2. cst: TFireBaseCustomer;
3. begin
4. cst := TFireBaseCustomer.Create;
5. try
6. cst.Name := 'Bill Gates';
7. cst.Street := 'Microsoft Av';
8. cst.ZIP := 2123;
9. cst.City := 'Redmond';
10. cst.DoB := EncodeDate(1969,04,18);
11. cst.ID := '1240';
12. AdvFirebaseObjectDatabase1.InsertObject(cst);
13. finally
14. cst.Free;
15. end;
16. end;

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 25


STORING OBJECTS IN THE GOOGLE FIREBASE CLOUD PAGE 3/6

In this example, we have created a rather simple


object with simple data types. But nothing
prevents you from using class properties as in
this example:
1. TCareerPeriod = class(TPersistent)
2. private
3. FFinish: integer;
4. FStart: integer;
5. published
6. property Start: integer
7. property Finish: integer read FFinish write FFinish;
8. end;
9.
10. TFirebaseCustomer = class(TFirebaseObject)
11. private
12. FName: string;
13. FStreet: string;
14. FZIP: integer;
15. FDoB: TDate;
16. FCity: string;
17. FPicture: TFireBasePicture;
18. FCareer: TCareerPeriod;
19. procedure SetCareer(const Value: TCareerPeriod);
20. public
21. constructor Create; override;
22. destructor Destroy; override;
23. published
24. property Name: string read FName write FName;
25. property Street: string read FStreet write FStreet;
26. property City: string read FCity write FCity;
27. property ZIP: integer read FZIP write FZIP;
28. property DoB: TDate read FDoB write FDoB;
29. property Career: TCareerPeriod read FCareer write SetCareer;
30. end;

With respect to types of fields, there is


And now this code can be used to persist this
one caveat though, Google Firebase
slightly more complex object:
doesn't offer out of the box support for
binary blobs. Imagine that we'd want to
1. var
2. cst: TFireBaseCustomer; persist a Delphi object that has a
3. begin TPicture property. The TPicture is
4. cst := TFireBaseCustomer.Create; internally streamed in a custom way to
5. try the DFM (via the DefineProperties(Filer:
6. cst.Name := 'Elon Musk';
TFiler); override) and the JSON persister
7. cst.Street := '3500 Deer Creek Road';
8. cst.ZIP := 2123; does not automatically get this data.
9. cst.City := 'Palo Alto'; There is however an easy workaround to
10. cst.DoB := EncodeDate(1975,03,21); add a published string property to a
11. cst.ID := '1241'; class descending from TPicture and use
12. cst.Career.Start := 2011; this string to hold hex encoded binary
13. cst.Career.Finish := 2017;
data of the picture. The DataString
14. AdvFirebaseObjectDatabase1.InsertObject(cst);
15. finally property getter & setter methods use the
16. cst.Free; StreamToHex() and HexToStream()
17. end; functions that are included in the unit
18. end; CloudCustomObjectFirebase:

As you can see, more complex classes can be


easily & automatically persisted in the Google
Firebase cloud.

26 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


STORING OBJECTS IN THE GOOGLE FIREBASE CLOUD PAGE 4/6

TFireBasePicture = class(TPicture)
2. private
3. function GetDataString: string;
4. procedure SetDataString(const Value: string);
5. published
6. property DataString: string read GetDataString write SetDataString;
7. end;
8.
9.
10. { TFireBasePicture }
11.
12. function TFireBasePicture.GetDataString: string;
13. var
14. ms: TMemoryStream;
15. begin
16. ms := TMemoryStream.Create;
17. try
18. SaveToStream(ms);
19. Result := StreamToHex(ms);
20. finally
21. ms.Free;
22. end;
23. end;
24.
25. procedure TFireBasePicture.SetDataString(const Value: string);
26. var
27. ms: TMemoryStream;
28. begin
29. ms := HexToStream(Value);
30. try
31. LoadFromStream(ms);
32. finally
33. ms.Free;
34. end;
35. end;

This way, we can extend the class to have a


picture property:
1. TFireBaseCustomer = class(TFirebaseObject)
2. private
3. FName: string;
4. FStreet: string;
5. FZIP: integer;
6. FDoB: TDate;
7. FCity: string;
8. FPicture: TFireBasePicture;
9. FCareer: TCareerPeriod;
10. procedure SetPicture(const Value: TFireBasePicture);
11. procedure SetCareer(const Value: TCareerPeriod);
12. public
13. constructor Create; override;
14. destructor Destroy; override;
15. published
16. property Name: string read FName write FName;
17. property Street: string read FStreet write FStreet;
18. property City: string read FCity write FCity;
19. property ZIP: integer read FZIP write FZIP;
20. property DoB: TDate read FDoB write FDoB;
21. property Career: TCareerPeriod read FCareer write SetCareer;
22. property Picture: TFireBasePicture read FPicture write SetPicture;
23. end;

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 27


STORING OBJECTS IN THE GOOGLE FIREBASE CLOUD PAGE 5/6

and persist the object with picture via:


With this class and its generic list, we
1. var can add a list of data at once in the
2. cst: TFireBaseCustomer; Google Firebase cloud:
3. begin
4. cst := TFireBaseCustomer.Create; 1. var
5. try 2. sl: TFirebaseObjectList;
6. cst.Name := 'Tim Cook'; 3. sc: TSimpleClass;
7. cst.Street := '1 Infinite Loop'; 4. I: Integer;
8. cst.ZIP := 2123; 5. begin
9. cst.City := 'Cupertino'; 6. sl := TFirebaseObjectList.Create;
10. cst.DoB := EncodeDate(1975,03,21); 7. try
11. cst.ID := '1242'; 8. sc := TSimpleClass.Create;
12. cst.Picture.LoadFromFile('tim_cook.jpg'); 9. sc.Name := 'Bruno';
13. cst.Career.Start := 2006; 10. sc.Score := 48;
14. cst.Career.Finish := 2017; 11. sc.ID := '1';
15. 12. sl.Add(sc);
16. AdvFirebaseObjectDatabase1.InsertObject(cst); 13.
17. finally 14. sc := TSimpleClass.Create;
18. cst.Free; 15. sc.Name := 'Nancy';
19. end; 16. sc.Score := 83;
20. end; 17. sc.ID := '2';
18. sl.Add(sc);
19.
To retrieve the objects back that were persisted, 20. sc := TSimpleClass.Create;
we can use: 21. sc.Name := 'Pieter';
1. var 22. sc.Score := 17;
2. fbo: TFirebaseObject; 23. sc.ID := '3';
3. begin 24. sl.Add(sc);
4. fbo := 25.
AdvFirebaseObjectDatabase1.ReadObject('1240'); 26. sc := TSimpleClass.Create;
5. 27. sc.Name := 'Bart';
6. if Assigned(fbo) then 28. sc.Score := 299;
7. begin 29. sc.ID := '4';
8. if (fbo is TFirebaseCustomer) then 30. sl.Add(sc);
9. ShowMessage((fbo as TFirebaseCustomer).Name 31.
+';’+(fbo as TFirebaseCustomer).City); 32. sc := TSimpleClass.Create;
10. fbo.Free; 33. sc.Name := 'Wagner';
11. end; 34. sc.Score := 55;
12. end; 35. sc.ID := '5';
36. sl.Add(sc);
To persist a property change of the object, for 37.
38. AdvFirebaseObjectDatabase1.TableName:=
example to change the career date of customer 1241 'List';
to 2018, we could write: 39. AdvFirebaseObjectDatabase1.InsertList(sl);
40.
WORKING WITH GENERIC LISTS 41. for I := 0 to sl.Count - 1 do
The previous samples all showed how to perform 42. sl[I].Free;
CRUD operations on single objects in the Google 43. finally
Firebase cloud. Our component 44. sl.Free;
TAdvFirebaseObjectDatabase also facilitates 45. end;
46. end;
dealing with generic lists of objects. Imagine you
want to persist a score table of game and have
following simple classes to store this:
1. TSimpleClass = class(TFirebaseObject)
2. private
3. FName: string;
4. FScore: integer;
5. published
6. property Name: string read FName write FName;
7. property Score: integer read FScore write FScore;
8. end;
9.
10. TSimpleList = TList<TSimpleClass>;

28 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


STORING OBJECTS IN THE GOOGLE FIREBASE CLOUD PAGE 6/6

Inspecting this on the This performs a query on the List table for value
Google Firebase console results in: 'Bart' set in the 'Name' field. The result of the
query is a generic list (in case multiple matching
results are found).

CONCLUSION
This was a glimpse at the TAdvFirebaseObjectDataBase
component as an introduction for the new Google
Firebase access features in the TMS VCL Cloud Pack and
TMS FMX Cloud Pack.
Storing all kinds of data from desktop applications,
mobile apps or web applications in the cloud opens
numerous new possibilities for sharing data.
Explore the full set of powerful capabilities of
TAdvFirebaseObjectDataBase and the many other
components in TMS Cloud Pack and TMS FMX Cloud Pack
to make consuming cloud services in Delphi &
C++Builder a piece of cake.

About the author Bruno Fierens


Studied civil electronic engineering at university of
Ghent, Belgium (1987-1992) and started a career as
R&D digital hardware engineer. Besides the fascination
for electronics, Bruno Fierens set the first steps in
programming with Turbo Pascal v3.0 and used all
Borland Pascal & Delphi versions since that time. In
1996, he founded TMS software for the activity of
application and component development with Delphi.
TMS software became Borland Technology Partner in
1998, developed Delphi Informant award-winning grid
& scheduling components and now has an
international team of software developers working on
a large portfolio of components. Bruno Fierens is from
2012 Embarcadero MVP and frequent speaker at
Delphi conferences world-wide. He does and oversees
VCL, IntraWeb, .NET and FireMonkey component
development

If, at a later time, we'd like to retrieve the


score of Bart, we could use the code:

1. var
2. c: TFirebaseObjectList;
3. I: Integer;
4.
5. begin
6. AdvFirebaseObjectDatabase1.TableName := 'List';
7. c:= AdvFirebaseObjectDatabase1.QueryList('Name', 'Bart');
8. if Assigned(c) then
9. begin
10. for I := 0 to c.Count - 1 do
11. begin
12. ShowMessage((c[I] as TSimpleClass).Score.ToString);
13. c[I].Free;
14. end;
15. c.Free;
16. end;
17. end;

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 29


VIDEO PROCESSING PART 2: PAGE 1/6
BY BOIAN MITOV
starter expert

INTRODUCTION
In the previous article I introduced you to some basic
video playback, and processing. I mainly And drop it on the form:
demonstrated geometric transformations of the Double click on the component to open the File
image.
Open Dialog. In the File Open Dialog , select a
The geometric transformations are very exciting, but
they are only one type of video filtering. VideoLab video file to play, and click the “Open” button:
contains many more filtering and transformation
components, and in this article we will continue to
explore them.
There are many different types of filters in
VideoLab, but they tend to performs one of few
typical tasks. In the previous article we used filter
performing Geometric transformations, by
changing the locations of the pixels. Another
common type of filters is to calculate the value of
each pixel based on the values of the surrounding
pixels usually in rectangular region called kernel.

Pixel
Surrounding Pixels
Rectangular Kernel

VideoLab contains a number of such filters, so


let’s explore some of them.
Start a new VCL Form application:

The AVI Player can decode only limited number of


video types, so to be sure that it will be able to
decode the selected video, it is best to use one of
the videos included in the VideoLab installation.
To make the video play constantly restarting
automatically when it reaches the end of the file,
set the “Loop” property to “True”:

Type “player” in the Tool Palette search box,


then select TVLAVIPlayer component from the
palette:

Type “display” in the Tool Palette search box,


then select TVLImageDisplay from the palette,
and drop 2 of them on the form:

30 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


VIDEO PROCESSING PART 2: PAGE 2/6

Type “box” in the Tool Palette search box, then


select TVLBoxFilter from the palette, and
Compile and run the application. You should see
drop it on the form:
the original and the processed video playing:

Switch to the “Open Wire” tab, and connect the


“Video” Output Pin of the VLAVIPlayer1 to the
“Video” Input Pin of the VLImageDisplay1:

Connect the “Video” Output Pin of the


VLAVIPlayer1 to the “Video” Input Pin of
the VLBoxFilter1 component:

Next connect the “Video” Output Pin of the


VLBoxFilter1 to the “Video” Input Pin of the
VLImageDisplay2 component:

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 31


VIDEO PROCESSING PART 2: PAGE 3/6

By default the Box


Filter is set to
perform averaging
on the surrounding
pixels.
You can change it
to perform Max by Switch to the “Open Wire” tab, and connect the
setting the “Video” Output Pin of the VLAVIPlayer1 to
FilterMode property the “Video” Input Pin of the VLFixedFilter1.
to bmmMax: Next connect the “Video” Output Pin of the
VLFixedFilter1 to the “Video” Input Pin of the
Compile and run the application. You should see
VLImageDisplay2 component:
the original and the processed video playing:

Compile and run the application. You should


see the original and the processed video playing:
You can change it
to perform Min by
setting the
FilterMode
property to
bmmMin:

Compile and run


the application.
You should see
the original and By default the Fixed Filter performs
the processed Horizontal Prewitt filtering. The filter has
video playing: filter effect explorer dialog. You can open the
dialog by clicking on the component.
In the drop down box, you can select another
filter, as example ftLaplace, and the dialog
will show you the result of the filtering:

The TVLBoxFilter has more modes, and settings,


but I will let you explore them yourself. Next we
will explore the TVLFixedFilter. It has a large
number of filtering operations with fixed kernel
sizes, and shapes. Switch to the Form Designer.
Delete the VLBoxFilter1. Type “fixed” in the
Tool Palette search box, then select
TVLFixedFilter from the palette, and drop it on
the form:

32 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


VIDEO PROCESSING PART 2: PAGE 4/6

Once you are happy with the selected filter, you


can click the OK Button.
Compile and run the application. You should see Double-click on the VLRectKernelFilter1
the original and the processed video playing: component to open the Kernel Dialog , and enter
some values for the coefficient to use when
calculating the value of the pixel. The value
of the pixel will be sum of the values of the
surrounding pixels each multiplied by the
corresponding coefficient:

There are many more kernel based filters in


VideoLab, but I will let you explore them yourself.
VideoLab includes a plenty of kernel type filters,
however sometimes you need to have filter of your
own design. For this VideoLab includes a
TVLRectKernelFilter component, that can be
used to implement custom kernel filters.
Once done, click on the OK Button to close the
Switch to the Form Designer . Dialog. Compile and run the application. You
Delete the VLFixedFilter1. should see the original and the processed video
Type “kernel” in the Tool Palette search box, playing:
then select TVLRectKernelFilter from the
palette, and drop it on the form:

Switch to the “Open Wire” tab, and connect the Kernel filters are only one type of filters.
“Video” Output Pin of the VLAVIPlayer1 to the Sometimes we simply need to change the color of
“Video” Input Pin of the each pixel without looking at the surrounding
VLRectKernelFilter1. pixels. VideoLab contains such filters too.
Next connect the “Video” Output Pin of the The simplest one is the Gamma Correction Filter .
VLRectKernelFilter1 to the “Video” Input Switch to the Form Designer .
Pin of the VLImageDisplay2 component: Delete the VLRectKernelFilter1. Type
“gamma” in the Tool Palette search
box, then select TVLGammaFilter
from the palette, and drop it
on the form:

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 33


VIDEO PROCESSING PART 2: PAGE 5/6

Switch to the “Open Wire” tab, and connect the


“Video” Output Pin of the VLAVIPlayer1 to Expand the “BlueTwist” sub-property of the
the “Video” Input Pin of the VLGammaFilter1. “ColorTwists”.
Next connect the “Video” Output Pin of the Set the value of the “Green” sub-property of the
VLGammaFilter1 to the “Video” Input Pin of BlueTwist to “0.5”. Set the value of the
the VLImageDisplay2 component: “Blue” the BlueTwist to “0.5”.

Compile and run the application. You should see


the original and the processed video playing:

A more complex component is a Color Twisting


component. In it you can specify how much each
of the color channels affects the others. Each color
channel is calculated as a sum of all the color
channels each multiplied by a coefficient.
Switch to the Form Designer . Delete the
VLGammaFilter1. Type “twist” in the Tool Switch to the “Open Wire” tab, and connect the
Palette search box, then select TVLColorTwist “Video” Output Pin of the VLAVIPlayer1 to
from the palette, and drop it on the form: the “Video” Input Pin of the VLColorTwist1.
Next connect the “Video” Output Pin of the
VLColorTwist1 to the “Video” Input Pin of the
VLImageDisplay2 component:

In the Object Inspector, expand the


“ColorTwists” property, then the
“RedTwist” sub-property.
Set the value of the “Red” sub-property of the
Compile and run the application. You should see
RedTwist to “0.5” .
the original and the processed video playing:
Set the value of the “Green” sub-property of the
RedTwist to “0.5” .
Expand the “GreenTwist” sub-property of the
“ColorTwists”.
Set the value of the “Red” sub-property of the
GreenTwist to “0.5” .
Set the value of the “Blue” sub-property of the
GreenTwist to “0.5” .ub-property of the
BlueTwist to “0.5” .

34 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE


VIDEO PROCESSING PART 2: PAGE 6/6

An even more complex color changing


filter is the Color Lookup component.
It uses a lookup table for each channel to
get the color value. Switch to the
Form Designer . Delete the
VLColorTwist1.
Type “lookup” in the Tool Palette
search box, then select TVLColorLookup
from the palette, and drop it on the form: Compile and run the application. You should see the
original and the processed video playing:

Double-click on the component to open


the Lookup Table editor:

To keep the tutorial simple, I will show you how


you can populate only the Red channel, leaving
the Green and Blue channels unchanged. You can In this Article, I introduced you to a variety of ready
experiment with mapping the other channels on to use image processing filters included in
your own. Enter as example these values in the VideoLab. There are many more filters included in
editor (right): the library, and they are equally easy to use and
experiment with, so I will let you explore them on
Then click on the OK Button to close the Dialog. your own.
The values between the entries of the table will be However, no matter how many filters a library
interpolated. offers, there always is a need to write filters of your
own.
Switch to the “Open Wire” tab, and connect the In the next Article, I will show you how you can
access the Image data in code, write your own
“Video”Output Pin of the VLAVIPlayer1 to the
filters in Delphi, convert between video images and
“Video” Input Pin of the VLColorLookup1. bitmaps, and draw on the images from code.
Next connect the “Video” Output Pin of the
VLColorLookup1 to the “Video” Input Pin of the
VLImageDisplay2 component:

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE 35


36 Issue Nr 2 2017 BLAISE PASCAL MAGAZINE
REST EASY WITH KBMMW PART 1
BYKIM MADSEN
PAGE 1/7 COMPONENTS
DEVELOPERS 4
starter expert DX Delphi In this case we will add a simple form both
providing a GUI and a place for our kbmMW
INTRODUCTION
components. In Delphi click File – New – VCL
REpresentational State Transfer (REST) or RESTful
web services is one way of providing interoperability
Forms application.Add one of each of the
between computer systems on the Internet. following kbmMW components to the form:
REST-compliant Web services allow requesting • TkbmMWServer
systems to access and manipulate textual • TkbmMWTCPIPIndyServerTransport
representations of Web resources using a uniform and
predefined set of stateless operations. Other forms of
Web service exist, which expose their own arbitrary
sets of operations such as WSDL and SOAP.
"Web resources" were first defined on the World
Wide Web as documents or files identified by their
URLs, but today they have a much more generic and
abstract definition encompassing every thing or entity
that can be identified, named, addressed or handled,
in any way whatsoever, on the Web.
In a RESTful Web service, requests made to a
resource's URI (Uniform Resource Identifier) will elicit a
response that may be in XML, HTML, JSON or some
other defined format.
The response may confirm that some alteration has Set the Server property of
been made to the stored resource, and it may provide kbmMWTCPIPIndyServerTransport1 to
hypertext links to other related resources or kbmMWServer1. Double click the Bindings
collections of resources. property of kbmMWTCPIPIndyServerTransport1
Using HTTP, as is most common, the kind of to open its editor.
operations available include those predefined by the
HTTP verbs GET, POST, PUT, DELETE and so on.
Add a binding for 0.0.0.0 port 80, which is the
By making use of a stateless protocol and standard default HTTP server port. You can choose any
operations, REST systems aim for fast performance, other binding you want, but make sure to tell your
reliability, and the ability to grow, by re- REST users which port to access.
using components that can be managed and
updated without affecting the system as a
whole, even while it is running.
The term representational state transfer
was introduced and defined in 2000 by Roy
Fielding in his doctoral dissertation.Fielding
used REST to design HTTP 1.1 and Uniform
Resource Identifiers (URI).
The term is intended to evoke an image of
how a well-designed Web application
behaves: it is a network of Web resources
(a virtual state-machine) where the user
progresses through the application by
selecting links, such as /user/tom, and
operations such as GET or DELETE
(state transitions), resulting in the next
resource (representing the next state of the application) Set the Streamformat property of
being transferred to the user for their use.
kbmMWTCPIPIndyTransport1 to REST.
REST SERVERS are very easy to make using kbmMW.
First we make a server application
(or service… it’s up to you).

1
Issue Nr 5 2017 BLAISE PASCAL MAGAZINE COMPONENTS
DEVELOPERS 4 37
REST EASY WITH KBMMW PART 1 PAGE 2/7 COMPONENTS
DEVELOPERS 4
Save your project. Saving it will prompt
Delphi to update your uses section with
required units.
Double click on the form, to create a form
OnCreate event handler.
Enter two lines of code so it looks like this:

procedure TForm7.FormCreate(Sender: TObject);


begin
kbmMWServer1.AutoRegisterServices;
kbmMWServer1.Active:=true;
end;

Locate the interface section’s uses clause and add


an additional unit kbmMWRESTTransStream.
Save again.
Now your unit code should look similar to this:

unit Unit7;

interface

uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, kbmMWCustomTransport, kbmMWServer,
kbmMWTCPIPIndyServerTransport, kbmMWRESTTransStream;

type
TForm7 = class(TForm)
kbmMWServer1: TkbmMWServer;
kbmMWTCPIPIndyServerTransport1: TkbmMWTCPIPIndyServerTransport;

procedure FormCreate(Sender: TObject);


private
{ Private declarations }
public
{ Public declarations }
end;

var
Form7: TForm7;

implementation

{$R *.dfm}

procedure TForm7.FormCreate(Sender: TObject);


begin
kbmMWServer1.AutoRegisterServices;
kbmMWServer1.Active:=true;
end;

end.

38 COMPONENTS
DEVELOPERS 4 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE
REST EASY WITH KBMMW PART 1 PAGE 3/7 COMPONENTS
DEVELOPERS 4
Basically we now have the foundation for a REST
capable web server.
Let’s add some functionality that can be called
from any REST client.
In Delphi, Click File – New – Other –
Components4Developers Wizards and select the
kbmMW Service Wizard . Click OK .

Before continuing to select the type of kbmMW


service we will add, we need to decide what type
of REST server we want to create.
It can be a pure REST server, which only serves
data from your own code, or it can be a regular
web server, which will also be able to serve data
from files on disk, like html templates, images,
CSS files etc.
For our purpose we just want to make a pure
REST server, so we select
Smart service/kbmMW_1.0.
If you wanted it to be able to serve files from
disk, and even proxy requests on to other
FastCGI compatible servers (like PHP etc) you
would have chosen HTTP Smart service.

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 39
REST EASY WITH KBMMW PART 1 PAGE 4/7 COMPONENTS
DEVELOPERS 4

Click the funny looking next


button. Type in the default name
your REST service should be
known as. In this sample, I’ve
called it MyREST.

Click next until you get to


this page, then click the
green checkmark button

Now an almost empty service


has been generated for you.
On the surface it looks like a
regular TDataModule, and as
such can contain any component
that you can put on a
TDataModule. But right now
we are more interested in its
code. Press F12 to switch to code

40 COMPONENTS
DEVELOPERS 4 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE
REST EASY WITH KBMMW PART 1 PAGE 5/7 COMPONENTS
DEVELOPERS 4
Browse past the explanatory remarks at the top, until you get to the actual code.
type

[kbmMW_Service('name:MyREST, flags:[listed]')]
[kbmMW_Rest('path:/MyREST')]
// Access to the service can be limited using the [kbmMW_Auth..] attribute.
// [kbmMW_Auth('role:[SomeRole,SomeOtherRole], grant:true')]

TkbmMWCustomSmartService8 = class(TkbmMWCustomSmartService)
private
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
// HelloWorld function callable from both a regular client,
// due to the optional [kbmMW_Method] attribute,
// and from a REST client due to the optional [kbmMW_Rest] attribute.
// The access path to the function from a REST client (like a browser)+
// is in this case relative to the services path.
// In this example: http://.../MyREST/helloworld
// Access to the function can be limited using the [kbmMW_Auth..] attribute.
// [kbmMW_Auth('role:[SomeRole,SomeOtherRole], grant:true')]
[kbmMW_Rest('method:get, path:helloworld')]
[kbmMW_Method]
function HelloWorld:string;
end;

implementation

uses kbmMWExceptions;

{$R *.dfm}

// Service definitions.
//---------------------

function TkbmMWCustomSmartService8.HelloWorld:string;
begin
Result:='Hello world';
end;

The interesting bits are shown above in bold.


If you compile and run your application now, you have a REST only capable webserver which have one
function… HelloWorld taking no arguments, and that returns a string.
Open up your favorite web browser and lets test the function by typing this in the address field:
http://localhost/MyREST/helloworld
Make sure that case is correct, since the HTTP standard describes that the URL part of the address must
be case sensitive.
If you would write http://localhost/MyREST/HelloWorld instead you would be told that the
request is invalid.
This is all nice… but my REST client expect to receive a JSON object, not just simple text.
Ok.. I’ll show 3 ways to do that… the very manual way, the semi automated way and the
fully automated way.
The manual way. Change the HelloWorld function to look like this:
function TkbmMWCustomSmartService8.HelloWorld:string;
begin
Result:='{''result'':''Hello world''}';
end;

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 41
REST EASY WITH KBMMW PART 1 PAGE 6/7 COMPONENTS
DEVELOPERS 4
The REST client will receive an anonymous object with a property called result, containing “Hello world”.
The semi automated way:
uses kbmMWExceptions
,kbmMWObjectNotation
,kbmMWJSON;

{$R *.dfm}

// Service definitions.
//---------------------

function TkbmMWCustomSmartService8.HelloWorld:string;
var
o:TkbmMWONObject;
jsonstreamer:TkbmMWJSONStreamer;
begin
o:=TkbmMWONObject.Create;
jsonstreamer:=TkbmMWJSONStreamer.Create;

o.AsString['result']:='Hello world';
Result:=jsonstreamer.SaveToUTF16String(o);

jsonstreamer.Free;
o.Free;
end;

This allows you to create complex JSON documents pretty easily. The cool part is that since we use
kbmMW’s object notation framework, we could have chosen to stream it as XML or YAML or BSON or
MessagePack instead by simply instantiating the appropriate streamer.
The automated way:
type

TMyResult = class
private
FResult:string;
public
property Result:string read FResult write FResult;
end;
[kbmMW_Service('name:MyREST, flags:[listed]')]
[kbmMW_Rest('path:/MyREST')]
// Access to the service can be limited using the [kbmMW_Auth..] attribute.
// [kbmMW_Auth('role:[SomeRole,SomeOtherRole], grant:true')]

TkbmMWCustomSmartService8 = class(TkbmMWCustomSmartService)
private
[kbmMW_Rest('method:get, path:helloworld, anonymousResult:true')]
[kbmMW_Method]
function HelloWorld:TMyResult;
end;

implementation

uses kbmMWExceptions;
{$R *.dfm}
// Service definitions.
//---------------------

function TkbmMWCustomSmartService8.HelloWorld:TMyResult;
begin
Result:=TMyResult.Create;
Result.Result:='Hello world';
end;

initialization
TkbmMWRTTI.EnableRTTI(TkbmMWCustomSmartService8);
kbmMWRegisterKnownClasses([TMyResult]);
end.

42 COMPONENTS
DEVELOPERS 4 Issue Nr 5 2017 BLAISE PASCAL MAGAZINE
REST EASY WITH KBMMW PART 1 PAGE 7/7 COMPONENTS
DEVELOPERS 4
The automated way simply means returning an kbmMW also understands returning
object with the desired information. TkbmMemTable instances, arrays and many other
types of information, so it is really easy to REST’
kbmMW will automatically convert the object to if your kbmMW business functionality with almost
JSON (because we are using the REST streamformat). no lines of additional code.
To make sure that kbmMW knows about the object As a final comment, since the HelloWorld
type, we register it via the method is also tagged with the attribute
kbmMWRegisterKnownClasses. [kbmMW_Method], it is also callable by native
If we didn’t, kbmMW would complain that it does kbmMW clients.
not know about the object.
Do not worry about the TMyResult instance kbmMW also understands returning
being leaked. kbmMW will automatically free it TkbmMemTable instances, arrays and many other
when it goes out of scope. If you specifically do types of information, so it is really easy to REST’
not want the returned object to be freed by if your kbmMW business functionality with almost
kbmMW, you can tell so by including no lines of additional code.
freeResult:false in the kbmMW_Rest attribute As a final comment, since the HelloWorld
for the HelloWorld method. method is also tagged with the attribute
Also notice that the kbmMW_Rest attribute now [kbmMW_Method], it is also callable by native
includes anonymousResult:true. kbmMW clients.
This tells kbmMW that we want the resulting
Because of the importance of the subject we will
JSON to be anonymous. If we didn’t include
create a series of articles that will hopefully make it
that attribute setting, the result would have clear for you how you might handle rest and what it
looked like this: really can do for you.
{"TMyResult":{"Result":"Hello world"}} Kim wrote a number of articles about this and we are
Which is not necessarily wrong, but different. publishing at least 1 or two in each issue.
There are lots of control options of how the object For now are planned:
should be streamed by setting various attributes REST easy with kbmMW #2 – Database
on it. One can for example choose that the Result REST easy with kbmMW #3 – SSL
REST easy with kbmMW #4 – Access management
property should be returned under a different
REST easy with kbmMW #5 – Logging
name etc. It might well be that new items will be published as
well.

THE

IS AT THE EUROPEAN PASCAL, DELPHI & C++BUILDER CONFERENCE


19 SEPTEMBER EINDHOVEN

FOR RESERVATION AS A SUBSCRIBER TO BLAISE PASCAL MAGAZINE


OFFICIAL PRICE EARLY BIRD RESERVATION 99,--
FOR OUR SUBSCRIBERS EARLY BIRD RESERVATION 79,--
GET YOUR COUPONCODE: office@blaisepascal.eu

Issue Nr 5 2017 BLAISE PASCAL MAGAZINE COMPONENTS


DEVELOPERS 4 43
GALILEO AND HIS TELSCOPE

KBMMW PROFESSIONAL AND ENTERPRISE EDITION


V. 5.02.10 RELEASED! NEW! CRON COMPATIBLE SCHEDULER SUPPORT
- RAD Studio 10.2 Tokyo support including Linux support - Native improved XSD importer
(in beta). for generating marshal
- Huge number of new features and improvements! able Delphi objects from XML schemas.
- New Smart services and clients for very easy - High speed, unified database access
publication of functionality and use from clients (35+ supported database APIs) with connection
and REST aware systems without any boilerplate code. pooling, metadata and data caching on all tiers
- New ORM OPF (Object Relational Model Object - Multi head access to the application server,
Persistence Framework) to easy storage and retrieval via REST/AJAX, native binary, Publish/Subscribe, SOAP,
of objects from/to databases. XML, RTMP from web browsers, embedded devices,
- New high quality random functions. linked application servers, PCs, mobile devices, Java
- New high quality pronouncable password systems and many more clients
generators. - Full FastCGI hosting support.
- New support for YAML, BSON, Messagepack Host PHP/Ruby/Perl/Python applications in kbmMW!
in addition to JSON and XML. - Native AMQP support ( Advanced Message Queuing
- New Object Notation framework which JSON, YAML, Protocol) with AMQP 0.91 client side gateway
BSON and Messagepack is directly based on, support and sample.
making very easy conversion between these formats and - Fully end 2 end secure brandable Remote Desktop
also XML which now also supports the object notation with near REALTIME HD video, 8 monitor support,
framework. texture detection, compression and clipboard sharing.
- Lots of new object marshalling improvements, - Bundled kbmMemTable Professional
including support for marshalling native Delphi objects which is the fastest and most feature rich in
to and from YAML, BSON and Messagepack in addition to memory table for Embarcadero products.
JSON and XML.
- New LogFormatter support making it possible to
customize actual logoutput format.
- CORS support in REST/HTML services. kbmMemTable is the fastest and most feature rich in
- High performance HTTPSys transport for Windows. memory table for Embarcadero products.
- Focus on central performance improvements. - Easily supports large datasets with millions of records
- Pre XE2 compilers no longer officially supported. - Easy data streaming support
- Bug fixes - Optional to use native SQL engine
- Multimonitor remote desktop V5 (VCL and FMX) - Supports nested transactions and undo
- RAD Studio and Delphi XE2 to 10.2 Tokyo support - Native and fast build in M/D, aggregation /grouping,
- Win32, Win64, Linux64, Android, IOS 32, IOS 64 range selection features
and OSX client and server support! - Advanced indexing features for extreme performance
- Native PHP, Java, OCX, ANSI C, C#,
Apache Flex client support!
- High performance LZ4 and Jpeg compression
- Native high performance 100% developer defined app
server with support for loadbalancing and failover

COMPONENTS
DEVELOPERS 4 DX
EESB, SOA,MoM, EAI TOOLS FOR INTELLIGENT SOLUTIONS. kbmMW IS THE PREMIERE N-TIER PRODUCT FOR DELPHI /
C++BUILDER BDS DEVELOPMENT FRAMEWORK FOR WIN 32 / 64, .NET AND LINUX WITH CLIENTS RESIDING ON WIN32 / 64, .NET, LINUX, UNIX
MAINFRAMES, MINIS, EMBEDDED DEVICES, SMART PHONES AND TABLETS.