text
stringlengths 313
1.33M
|
---|
# How To Assemble A Desktop PC/Development
This page is for developing sections that will eventually go into the
book How To Build A Computer (only
if there is enough material present to justify a new subpage).
## Places to Find, Compare, and Check Price and Compatibility
### PCPartPicker
An online tool that includes several tools for first time or experienced
PC builders. The main feature is being able to create part lists. In the
part list tool, there are 2 more tools, the wattage estimation tool, and
the compatibility checker.
<https://pcpartpicker.com/>
### PCPickerpro
Assemble your PC parts online to build customized Gaming PC.
<https://pcpickerpro.com>
### Tom\'s Hardware
<http://www.tomshardware.com/>
### Overclockers
<http://www.overclockers.com/>
### SilentPcReview
<http://www.silentpcreview.com/>
Microsoftwin108576
(discuss •
contribs) 22:40,
26 December 2015 (UTC)
## Troubleshooting
You just finished building your computer, you turn it on, and it
doesn\'t work. This section helps you in case this happens.
### The drives act strange
Make sure the IDE/ATA cable isn\'t longer than 18 inches (46 cm).
### I pressed the power button and nothing happened
This could be due to a variety of reasons
- You forgot to connect the power button
- The power cable is loose
- The power is out
- The motherboard is grounded out
- You forgot (on certain motherboards) to connect the 12V 4-PIN cable
to the motherboard.
### My New Computer Randomly Restarts
- Bad UPS, check the voltage rails for your UPS
- Insufficient cooling of components, especially CPU
### My New Computer Randomly Shuts Down / Crashes
- You have overclocked it above what the processor can do at it\'s
current vcore voltage. Increase the vcore voltage.
- An internal/external cable is loose.
### RMA
You found your problem component using the above sections, and you need
to get a replacement for a part you bought online. This is known as an
RMA(Return Merchandise Authorization). This is usually done through
either the manufacturer or the store where you bought the item from.
## Modding + Decoration
So you don\'t just want to make a computer, you want to show it off. Or
maybe you want to do something creative with your computer.
## Optimizing the System
If you are using a Windows system, you\'ll probably want to remove
useless features and \'tweak\' your system. Searching the internet for
\'Windows Tweaks\' will throw up a load of tweaks. Be warned. Don\'t do
anything crazy and if you are scared-DON\'T DO IT!
# Build a Laptop
Few people know this but let me tell you a little secret- It IS possible
to build a laptop/notebook computer. Be warned-It IS more difficult than
building a desktop. Heres how:
## Getting Parts
Here are the parts you will need to make your pride and joy. But before
you rush out to get it all, please scroll down to my DISCLAIMER. The
parts are:
A Barebone
Notebook
- A compatible Processer (search with
Froogle)
- A compatible storage device (search with
Froogle) -- as of 2021, it is
recommended to install a solid state drive rather than a mechanical
hard drive for reasons outlined at Choosing the parts §
SSD.
The added robustness and reduced power consumption of solid state
drives are especially beneficial for portable devices. Hard drives
may be used where much storage at a low price is a priority, but
external portable hard drives can serve this purpose too.
- Some RAM (search with Froogle)
- WiFi Card (optional unless you have a Centrino notebook)(search with
Froogle)
## Building It
THIS SITE has a good guide on
how to make the \'book. (I\'m WAY too lazy to type it myself)
## Disclaimer
1. I HATE Going out shopping. If you do too, I have provided links to
all the parts to buy online. However:
- These may not ship to your area
- I AM NOT advertising/selling/recommending all these parts!!!
2. If anything goes wrong I\'M NOT RESPONSIBLE
3. Operating System (OS) installation is the same as on a desktop
4. Please ensure you read and understand
- These instructions/instructions on links
- The Desktop building instructions in ths book
5. DO NOT attempt if you have never done a desktop before
6. Most important:
- Slag your friends saying- \"I can build a laptop computer and
you can\'t-HaHa\"
- Enjoy your shiny new handbuilt laptop :)
7. If all goes wrong just BUY
ONE
(see 1b)
Consider getting a laptop with modular and user-replaceable parts such
as RAM and storage, which allows later upgrading.
# fault-tolerant storage
- RAID
- distributed file systems
# computer repair
- the BuildRepair wiki
|
# How To Assemble A Desktop PC/Choosing the parts
The first step to building a computer is acquiring the parts. This guide
will start with a quick explanation of essential parts and elaborate on
them further on.
These are the parts that a standard PC will use. You might want to make
a check list (perhaps using a spreadsheet) of parts to use as you go
about your process of research and selection. That way you won't find
yourself sitting down with a pile of brand new hardware only to find
that you forgot an essential component.
## The primary parts
### Key Parts
- **Case** - The case houses and
protects rest of the parts, and contains additional functions like
button, front IO ports, and other features.
```{=html}
<!-- -->
```
- **Power Supply
Unit "wikilink")**/**PSU** -- *Power
Supply Unit*, converts outlet power, which is alternating current
(AC), to direct current (DC) which is required by internal
components, as well as providing appropriate voltages and currents
for these internal components.
```{=html}
<!-- -->
```
- **Motherboard**/**mainboard** -- A board
that facilitates communications between components and offers ports
to connect them together.
```{=html}
<!-- -->
```
- **CPU** -- *central
processing unit*, the main processor of the computer. The CPU
handles general and mathematically complicated tasks.
```{=html}
<!-- -->
```
- **RAM** -- *random access memory*, the
\"short-term memory\" of a computer, used by the CPU to store
program instructions and data upon which it is currently operating.
Data in RAM is lost when the computer is powered off, thus
necessitating a *storage drive*.
```{=html}
<!-- -->
```
- **Storage** - either
**HDD** (Hard disk drive - noisy and
slower of the two but less expensive) and/or
**SSD** (solid state drive. Quiet, very
fast but not as cheap) -- the \"long-term memory\" of the computer,
used for persistent storage -- i.e. the things stored on it remain
even when the computer is powered down. The operating system, and
all your programs and data are stored here, so if you choose SSD
then the system will be faster. These days, SSDs have replaced HDDs
for almost everything but the lowest-end laptops and desktops, but
if you only need to surf the web, HDDs are the best option. OSes can
be booted and use storage from inexpensive **USB
Drives**, although this is only
with extremely lightweight systems.
### Optional Components
Optional components follow: (Components that depend on the function that
will be given to the machine)
- **GPU**/**Graphics Card** -- does
processing relating to video output. If you want to build a gaming
PC, a good GPU is almost mandatory. Some processors have an
integrated GPU built in so you don't need (but may add) a separate
video card. Otherwise, you will need a video card. These plug into a
slot on the motherboard and provide ports to connect a monitor to
your computer.
```{=html}
<!-- -->
```
- **Optical Drive** -- device for
handling optical disks. May read CDs, DVDs, Blu-Rays or other
optical media. Some drives are able to write optical media as well
as read it.
```{=html}
<!-- -->
```
- **Sound hardware** - Now integrated into
motherboards, higher end sound hardware may be a good option for
some users.
### External Components
On top of the internal components listed above, you will also need these
external components:
- **Keyboard** -- for typing on. A good
keyboard will increase your comfort, as well as make you a more
productive typist.
```{=html}
<!-- -->
```
- **Mouse** -- for pointing and clicking. A
comfortable mouse can significantly improve your experience.
```{=html}
<!-- -->
```
- **Monitor** -- Displays graphics from your
computer. They come in many forms, the most common being
LCD displays.
## Planning the Build
Before you go on a shopping spree and start spending lots of money on
expensive computer parts, there are some important questions you should
answer which will guide your purchases:
- What will be the main function of the computer?
- What useful parts do you have on hand, from an old computer or
otherwise?
- How much can you afford to spend on the system?
- Some functions benefit from certain components more then others.
What components, if any, should you skimp on to afford better
components elsewhere?
- Do you want to upgrade your computer later, or will you be content
with your build?
## What operating system am I going to use?
Before you buy components, be sure that they are supported by the
operating system you plan to use. Almost all commonly available PC
devices have drivers (small programs that allow the operating system to
recognize and work with a hardware device) available for current
versions of Windows. If you want to run an alternative operating system,
you\'ll have to do some research to make sure your hardware choice will
be compatible. Many alternatives have extensive \'Hardware Compatibility
Lists\' (HCLs) as well as software compatibility.
### Main operating systems available
- **Microsoft Windows** - Windows 10/11
(Home/Pro).
- **Popular Linux Distros** - Ubuntu, Linux
Mint, OpenSUSE,
Fedora "wikilink"),
Debian, and others
- **Popular BSD Variants** - FreeBSD,
OpenBSD, NetBSD, and
others
- **Android** - A variety of Android based operating systems exist for
x86 Personal computers. While not ideal for the desktop form factor,
they are free and offer compatibility with Android\'s software
library.
- **MacOS** - You can install MacOS on non-Apple hardware which is
called \"Hackintosh\" in which an end user installs MacOS on a
non-Apple computer. Be warned that this is risky and takes more
knowledge than other operating systems.
### Windows information and hardware support lists
**Microsoft Windows** is a series of operating systems made by the
Microsoft corporation. Thanks to its popularity and widespread support
Windows is ideal for most personal computing and fits the needs or wants
of just about anyone: gamers, video/graphics editors, office workers, or
the average user who wants to surf the web and play a bit of solitaire.
In general Windows supports most available consumer processors from AMD
or Intel, as well as most internal and external devices, including
Graphics Cards, Wi-Fi adapters, and specialty hardware.
For general consumers, Windows comes in a few flavors:
- Windows 11 Home is the basic version of Windows 11 and costs about
\$140, but purchases from bulk retailers can be as cheap as \$50.
- Windows 11 Pro is the more advanced version of Windows 11 and costs
about \$200. This version includes business-oriented features like
drive encryption, better virtual machine support and a built-in
remote desktop function.
- Windows 11 Pro for Workstations provides support for
workstation-class hardware such as motherboards with multiple
processor sockets and costs \$310.
If you are a student you may be able to get a free version of Windows 11
through your school using Azure Dev Teaching (formerly Imagine Premium).
Any Windows 7, 8, 8.1 or 10 product key can be used to activate a copy
of Windows 11. This essentially gives you a free upgrade from an older
version of Windows to the latest.
Microsoft maintains a list of
hardware
compatible with Windows.
### Linux information and hardware support lists
As one of the most popular open-source (free) operating systems,
**GNU/Linux** is a good alternative. Linux is a UNIX-like series of
operating systems and comes in many different distributions, called
\"distros\" for short. Popular distros of Linux intended for the desktop
include Ubuntu, Debian,
openSUSE, MX Linux,
Elementary OS,
Fedora "wikilink"),
KDE, Linux Mint, and
Arch Linux.
Linux has applications that can match most of the functionality of their
proprietary alternatives. It should be noted, however, that many popular
programs are not available for Linux, and the only way to run them is
with special compatibility layers like
Wine "wikilink"), which may or may not work with a
specific program, or could only run with significant issues.
Unlike Windows, drivers in Linux are usually included in the distro.
This means different distributions will support different hardware
(generally more \'bleeding-edge\' distributions will support newer
hardware -- look at Fedora, SUSE or Ubuntu, compared to the latest
stable release of Debian). A search online will normally establish
compatibility, otherwise a good rule of thumb to figure out
compatibility is to buy hardware that is 12 to 18 months old, as it most
likely has Linux support with most distributions, but won\'t be too old.
Graphics Drivers on Linux are interesting. AMD GPUs typically work fine
out of the box thanks to the manufacturer backed open source AMDGPU
driver project, where the community open source
nouveau "wikilink") project generally works well,
but not to the same level as Nvidia\'s Proprietary drivers, which many
distros do not include out of the box due to the licensing used by the
driver. Intel Integrated Graphics typically works very well in Linux.
### BSDs information and hardware support lists
**BSD**, or the **Berkeley Software Distribution**, is also a UNIX-Like
series of operating systems and could be considered the alternative to
Linux. BSD is an open-source (free) operating system and has its own
descendants, such as FreeBSD and
OpenBSD. Unlike Linux, BSD tends not to support
\"new\" hardware but can handle a lot of both older and modern
components. BSD and Linux share a variety of applications supported on
both operating systems.
- DesktopBSD, see FreeBSD
5.4/i386
and FreeBSD
5.4/amd64
- Dragonfly
BSD
- FreeBSD
- NetBSD
- OpenBSD
- PC-BSD, see FreeBSD
6.0/i386
### Hackintosh
!A Hackintosh A
Hackintosh is a computer based on commodity
hardware which runs macOS. This is **extremely**
risky and could end in utter failure if it is not done properly. macOS
is designed with Apple computers in mind and trying to port them to a PC
is risky and difficult. If you still want to attempt the same, read
this.
1. You\'ll be violating the Apple EULA.
2. You should be using a comparable Intel CPU which should\'ve been
used by Apple in one of their computers. Although 14th gen Intel
CPUs and 700-series motherboards are available, 10th gen Intel CPUs
and 400-series motherboards are the last components fully supported
by macOS.
3. Apple is moving away from X86 CPUs, and your configuration may not
work in the future. Updating between releases could be difficult
even before this transition.
4. CPU choice and graphics also matter. Look up your CPU/GPU
combination to see if it works.
5. You\'ll need to (mostly) get modified installers, as the official
installers may block installation.
6. You\'ll need patience and tinkering up with things if something goes
wrong. An unsupported motherboard could even be destroyed by macOS.
+----------------------+----------------------+----------------------+
| CPU | CPU supported? | iGPU supported? |
+======================+======================+======================+
| AMD Ryzen | A workstation was originally a single-user computer with more muscle
than a PC intended to support a demanding technical application, like
CAD or complicated array-based simulations of real world phenomena. Once
the domain of cutting edge computer companies, this category has
experienced a rebirth as high performance and reliable PCs for
professional use. Unlike a gaming PC, reliability becomes much more
important - Time is money after all.
For any of the following uses, you will want
- A solid and reliable power supply
- A processor and motherboard platform that supports ECC
memory.
- Lots of ECC memory more reliability.
- A 64 bit version of the OS to take full advantage of the extra ram
and software features used by many workstation programs.
- A GPU that can run desired applications on multiple high resolution
displays.
PC level Budget PC case Motherboard CPU CPU cooler RAM Graphics Storage Power supply
-------------------------- ----------- ----------------------------- -------------------------------- ---------------------------------------- ------------------------------- --------------------------------------- ------------------------------------------------------------- -------------------------------------------- --------------------------------------
**Mid-range** \~\$800 Basic micro ATX case (\$60) B660 DDR4 motherboard (\$100) Intel Core i5-13400 (\$210) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) Nvidia T600 4 GB (\$220) 1 TB PCIe 3.0 SSD (\$50) 600 W Gold power supply (\$140)
**Upper mid-range** \~\$1000 Basic micro ATX case (\$60) B660 DDR4 motherboard (\$100) Intel Core i5-13500 (\$260) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) Nvidia T1000 4 GB (\$320) 1 TB PCIe 3.0 SSD (\$50) 600 W Gold power supply (\$140)
**Lower high-end** \~\$1200 Basic micro ATX case (\$60) B660 DDR4 motherboard (\$100) Intel Core i5-13600K (\$300) Mid-range cooler (\$40) 32 GB DDR4-3600 (2 x 16 GB) (\$60) Nvidia RTX A2000 6 GB (\$450) 1 TB PCIe 3.0 SSD (\$50) 650 W Gold power supply (\$150)
**High-end** \~\$1500 Basic micro ATX case (\$60) B760 DDR5 motherboard (\$140) Intel Core i5-13600K (\$300) Mid-range cooler (\$40) 32 GB DDR5-5200 (2 x 16 GB) (\$90) Nvidia RTX A2000 12 GB (\$500) 1 TB PCIe 4.0 SSD (\$80) 850 W Gold power supply (\$230)
**Upper high-end** \~\$2000 Premium ATX case (\$160) Z790 DDR5 motherboard (\$380) Intel Core i7-13700K (\$440) Mid-range cooler (\$40) 32 GB DDR5-5600 (2 x 16 GB) (\$100) Nvidia RTX A2000 12 GB (\$500) 2 TB PCIe 4.0 SSD (\$130) 850 W Gold power supply (\$230)
**Flagship** \~\$2500 Premium ATX case (\$160) Z790 DDR5 motherboard (\$380) Intel Core i7-13700K (\$440) Mid-range cooler (\$40) 32 GB DDR5-5600 (2 x 16 GB) (\$100) Nvidia RTX 4000 Ada 20 GB (\$1200) 2 TB PCIe 4.0 SSD (\$130) 850 W Gold power supply (\$230)
**True flagship** \~\$3000 Premium ATX case (\$160) Z790 DDR5 motherboard (\$380) Intel Core i9-13900K (\$590) Premium liquid cooler (\$180) 64 GB DDR5-5600 (2 x 32 GB) (\$190) Nvidia RTX 4000 Ada 20 GB (\$1200) 4 TB PCIe 4.0 SSD (\$250) 1000 W Gold power supply (\$280)
**Ultimate flagship** \~\$4000 Premium ATX case (\$160) Z790 DDR5 motherboard (\$380) Intel Core i9-13900KS (\$720) Premium liquid cooler (\$180) 128 GB DDR5-6400 (4 x 32 GB) (\$560) Nvidia RTX 4000 Ada 20 GB (\$1200) 4 TB PCIe 4.0 SSD (\$250) 1000 W Platinum power supply (\$350)
**Ultimate flagship v2** \~\$6000 Premium ATX case (\$160) Z790 DDR5 motherboard (\$380) Intel Core i9-13900KS (\$720) Premium liquid cooler (\$180) 128 GB DDR5-7200 (4 x 32 GB) (\$800) Nvidia RTX 4500 Ada 24 GB (\$2500) 2 x 4 TB PCIe 4.0 SSD RAID0 array (\$500) 1200 W Platinum power supply (\$450)
**Ultimate flagship v3** \~\$10000 Premium ATX case (\$160) sWRX8 DDR4 motherboard (\$800) AMD Ryzen Threadripper 5975WX (\$2400) Premium liquid cooler (\$180) 256 GB DDR4-3600 (8 x 32 GB) (\$400) Nvidia RTX 6000 Ada 48 GB (\$6500) 4 x 4 TB PCIe 4.0 SSD RAID0 array (\$1000) 1200 W Platinum power supply (\$450)
**Ultimate flagship v4** \~\$20000 Premium ATX case (\$160) sWRX8 DDR4 motherboard (\$800) AMD Ryzen Threadripper 5995WX (\$4600) Premium liquid cooler (\$180) 512 GB DDR4-3600 (8 x 64 GB) (\$1000) Dual Nvidia RTX 6000 Ada 48 GB GPUs (96 GB total) (\$13000) 4 x 4 TB PCIe 4.0 SSD RAID0 array (\$1000) 1500 W Platinum power supply (\$650)
: Typical PC build by budget
#### Video editing
Big and fast storage drives are key. Solid State Drives in RAID0 as
working space with multiple multi Terabyte or larger drives for storage
is a good target. A large amount of memory would be beneficial, as would
a fast CPU, with many cores/threads, especially if you intend to render
effects or wish to quickly transcode video. Most editing and transcoding
programs utilize some form of GPU acceleration (primarily OpenCL and/or
CUDA), where the graphics processor is used, along with the CPU, to
perform many calculations at the same time, greatly reducing processing
time, compared to CPU-only processing.
#### Music production
Plenty of disk space and RAM is important, but a music production
(recording and mixing) workstation is chiefly distinguished by
specialized external components -- studio reference monitors instead of
normal speakers, mixing consoles, microphones, etc. Even the acoustics
of the room your computer is in becomes an important factor. If you want
to record external sources, like vocals or instruments, you\'ll need an
audio interface which allows you to plug mics or instruments into your
computer.
Computers meant to be installed near live recordings often use near or
totally silent cooling solutions.
Audio interfaces allow anything from a single microphone or instrument
on up to pro level systems that have 32 or more simultaneous inputs.
These separate inputs will allow you to record each one as a separate
track in your DAW. Most use Steinberg\'s ASIO interface (a software
driver that connects your hardware to your DAW software). If you don\'t
wish to invest in anything other than the onboard sound card your
computer comes with, consider ASIO4All, a free driver that imitates the
ASIO framework for almost any sound card.
One piece of advice, if you have extra money, get better microphones -
even if you have to trade the Bluesmobile.
#### CAD/CAM
(**C**omputer **A**ssisted **D**esign / **C**omputer **A**ided
**M**anufacturing)
A CAD/CAM workstation is usually a machine that runs a single, very
intense, application. These machines often utilize specialized video
hardware, like the Nvidia Quadro andAMD
Radeon Pro series of GPUs, which are designed
specifically for CAD/CAM rendering. Since these machines are usually
devoted to a single, expensive, application it\'s especially important
to pay close attention to the requirements of that application. Spec the
hardware to support the software - always a good idea but especially
important here.
Some examples of this specialized software are Autodesk 3ds
Max, Autodesk
Maya, AutoCAD,
Cinema 4D and Maxwell
Render amongst many
others.
### Mining rig
A mining rig is a computer designed to mine cryptocurrency with the use
of multiple high-end GPUs. Graphics cards are the most important for
mining. You should get a case and motherboard that are specifically
designed for multiple graphics cards. To supply all of power to the
components, you will need a Gold or better power supply capable of
supplying lots of power. CPU, RAM and storage are the lowest priorities.
PC level Budget PC case Motherboard CPU CPU cooler RAM Graphics Storage Power supply
-------------------------- ----------- ----------------------------- ---------------------------------- ---------------------------- ------------------------------- ----------------------------------- ----------------------------------------------------------- ------------------------ ----------------------------------------------
**Mid-range** \~\$800 Basic ATX case (\$80) B660 DDR4 motherboard (\$100) Intel Celeron G6900 (\$50) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) Nvidia GeForce RTX 4060 Ti 8 GB (\$400) 240 GB SATA SSD (\$15) 600 W Gold power supply (\$140)
**Upper mid-range** \~\$1000 Basic ATX case (\$80) B660 DDR4 motherboard (\$100) Intel Celeron G6900 (\$50) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) Nvidia GeForce RTX 4070 12 GB (\$600) 240 GB SATA SSD (\$15) 650 W Gold power supply (\$150)
**Lower high-end** \~\$1200 Basic ATX case (\$80) B660 DDR4 motherboard (\$100) Intel Celeron G6900 (\$50) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) Nvidia GeForce RTX 4070 Ti 12 GB (\$800) 240 GB SATA SSD (\$15) 750 W Gold power supply (\$190)
**High-end** \~\$1500 Basic ATX case (\$80) B660 DDR4 motherboard (\$100) Intel Celeron G6900 (\$50) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) Nvidia GeForce RTX 4080 16 GB (\$1150) 240 GB SATA SSD (\$15) 850 W Gold power supply (\$230)
**Upper high-end** \~\$2000 Basic ATX case (\$80) B660 DDR4 motherboard (\$100) Intel Celeron G6900 (\$50) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) Nvidia GeForce RTX 4090 24 GB (\$1600) 240 GB SATA SSD (\$15) 1000 W Gold power supply (\$280)
**Flagship** \~\$2500 Premium ATX case (\$160) B760 DDR5 motherboard (\$140) Intel Celeron G6900 (\$50) Intel stock cooler (included) 16 GB DDR5-4800 (2 x 8 GB) (\$55) Nvidia GeForce RTX 4090 24 GB (\$1600) 240 GB SATA SSD (\$15) 1200 W Gold power supply (\$340)
**True flagship** \~\$3000 Mining case (6 GPUs) (\$50) Biostar TB360-BTC PRO 2.0 (\$60) Intel Core i3-8100 (\$60) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) 2 x Nvidia GeForce RTX 4080 16 GB (32 GB total) (\$2300) 240 GB SATA SSD (\$15) 1200 W Gold power supply (\$340)
**Ultimate flagship** \~\$4000 Mining case (6 GPUs) (\$50) Biostar TB360-BTC PRO 2.0 (\$60) Intel Core i3-8100 (\$60) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) 2 x Nvidia GeForce RTX 4090 24 GB (48 GB total) (\$3200) 240 GB SATA SSD (\$15) 1500 W Gold power supply (\$420)
**Ultimate flagship v2** \~\$6000 Mining case (6 GPUs) (\$50) Biostar TB360-BTC PRO 2.0 (\$60) Intel Core i3-8100 (\$60) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) 3 x Nvidia GeForce RTX 4090 24 GB (72 GB total) (\$4800) 240 GB SATA SSD (\$15) 2300 W Platinum power supply (\$800)
**Ultimate flagship v3** \~\$10000 Mining case (6 GPUs) (\$50) Biostar TB360-BTC PRO 2.0 (\$60) Intel Core i3-8100 (\$60) Intel stock cooler (included) 16 GB DDR4-3200 (2 x 8 GB) (\$30) 6 x Nvidia GeForce RTX 4090 24 GB (144 GB total) (\$9600) 240 GB SATA SSD (\$15) Dual 2300 W Platinum power supplies (\$1600)
: Typical PC build by budget
## Do I plan on overclocking my computer?
!An aftermarket CPU heatsink side by side with a stock heatsink. Larger
heatsinks help keep components cool during overclocking, and larger fans
often help either move much more air through a system for the same level
of noise, or move the same amount of air for much less
noise.
Overclocking consists of running components at faster internal speeds
than they are rated for, gaining a bit of extra performance out of the
part. If you are serious about overclocking your computer, you need to
do extensive research into the components you select, as some parts
respond to overclocking better than others. Overclocking usually voids
your warranty and is risky as you can shorten the life of your
components or even burn them out completely! You need to take cooling
the computer more seriously as overclocking generates additional heat.
Anything from a few extra fans to a liquid-cooled system may be
necessary depending on the nature of your system.
Many parts that are the same model can overclock differently due to
manufacturer binning, leading to a \"Silicon Lottery\" of sorts. For
example, consider three different Raptor Lake 13700K CPUs that are
installed in identical systems - a good chip can clock up to about 5.7
GHz, an excellent one may be able to hit 6.1 GHz, while a bad one may
stop at 5.3 GHz. If you are willing to pay more, some vendors sell
pre-binned CPUs which have been previously tested to overclock well.
Most AMD processors can be overclocked. For Intel processors, only the K
series CPUs (which cost about \$20-40 USD more than the normal version)
and the Extreme Series generally allow full overclocking.
## Do I plan on underclocking my computer?
This can be ideal for always-on entertainment systems. Underclocked
parts run cooler, often enabling passive cooling options to be used,
which leads to a much quieter system, and you\'ll also save on power.
However, you\'ll lose performance from the CPU. You may wish to
*undervolt* the CPU instead; see the
Silencing section to find out how.
## Can I use any of the parts from my old computer?
!A 2017 PC built in a case from the 1990\'s. While this decision
sacrifices front IO and modern airflow designs, it does save money on
the case. Some communities exist that build \"Sleeper PCs\", modern high
performance computers built to look like under powered or obsolete
computers.
This depends on your situation; if your computer is more than four years
old, chances are that most of the parts will be too old, slow or
incompatible for your new machine. On the other hand, if you are
upgrading from a fairly new machine, you may be able to use many of the
parts. All of this assumes the old computer will no longer be used. If
you, or someone else, is going to continue using your old computer,
it\'s probably best just to leave it intact.
One important point -- if you are selling your old computer it\'s a good
idea to erase the hard drive before giving it to its new owner. A simple
\'delete\' command does not actually erase the data on your hard
drive,leaving things like financial documents, passwords, healthcare
records, browser history, and personal photos potentially recoverable
through easy to use recovery software. To avoid this, programs are
available that will effectively \'shred\' your data, making it
unrecoverable. Driver software that comes with some hard drives may also
have programs to do this, that write 0s or 1s (either way,
\"blankness\") to the whole drive. Lower-tech approaches include
drilling a few holes in the drive or taking a blowtorch to it.
Obviously, either prevents it from being used again (Be planet friendly
and try to avoid this).
Since monitor technology moves quite slowly, you can probably keep your
current monitor and use it on the new computer if it\'s of sufficient
size and clarity for your work. The same can go for keyboards, as well
as mice, printers, scanners, and possibly speaker sets. On the inside,
you may be able to take out the storage drive, and expansion cards. If
your components are especially old, the features integrated into the
motherboard may actually be superior to your old components, so testing
with and without these your old devices is recommended. Sometimes so
much is used from the old computer, that the line between an upgrade and
a new computer can become blurred.
Reusing a hard drive is an easy way to keep data from your old computer.
With most Windows operating systems moving a boot drive from one
motherboard to another will entail a series of reboots and installation
of new drivers. Back up your data before trying this, and note that
Windows will usually ask you to reactivate. Keep the licence key ready.
## Where do I find the parts?
!Computer retailers can be a handy source for parts, and often offer
easy
returns.
Once you have decided what you're going to use your computer for, and
have reviewed which parts are available for reuse, you should make a
list of what components you will need to buy. A few hours of research
can save you years of regret, so make sure that the computer you build
will do what you need it to do.
Computer terminology can be confusing, so if there are terms you don't
understand, be sure to look them up. Wikipedia is an excellent place to
start if, for example, you're not clear on the difference between, say,
DDR4 and DDR5 memory.
There are several places to buy parts:
- **Internet retailers** generally offer the best price for new parts.
If a part needs to be returned, you may be stuck for the shipping;
check return policies before you purchase.
- **Auction sites** like eBay and several others offer very good
prices for used parts. This is especially useful for parts which do
not wear out, like RAM, and unlike HDD/SSDs. Returns can be
problematic or impossible. Some auctions may not be legitimate.
Always check the shipping cost before you bid.
- **Local PC shops** - Their prices are often higher, but they may
make up for this by providing a lot of expertise. Get opinions from
other sources, however, as they may be eager to sell you parts you
don\'t need.
- **Big box stores** often lack technical expertise and charge higher
prices, but can be useful because they usually handle returns
quickly. Also good if you need something right away.
- **Trade shows** that occur from time to time also provide a good
place to shop, as the prices are often significantly reduced, and
the variety of prefabricated computers built towards specific
computing needs tend to be higher.
Also, your local town dump may have a special section for computers and
monitors that others have got rid of. These can be more or less brand
new computers with trivial problems such as a busted power supply or
faulty cables. Of course if the dump does have such a section, you
should ask permission of those in charge. They\'re usually glad to let
you go through it, but don\'t leave a mess. Taking advantage of this can
yield incredible finds, with a price tag of nothing or very little.
### OEM vs Retail
!An OEM CPU: AMD Ryzen 7 Pro
4750G.
Many hardware manufacturers will sell the same components in both OEM
and Retail versions. Retail hardware is intended to be sold to the
end-user through retail channels, and will come fully packaged with
manuals, accessories, software, etc. OEM stands for \"original equipment
manufacturer\"; items labeled as such are intended to be sold in bulk
for use by firms which integrate the components into their own products.
However, many online stores will offer OEM hardware at (slightly)
cheaper prices than the corresponding retail versions. You will usually
receive such an item by itself in an anti-static bag. It may or may not
come with a manual or a CD containing drivers. Warranties on OEM parts
may often be shorter or nonexistent, and sometimes require you to obtain
support through your vendor, rather than the manufacturer. OEM
components are also sometimes specified differently than their retail
counterparts, parts may be clocked slower, and ports or features may be
missing. Some of the support may be less (as in the case of Microsoft).
Again, do your research.
## What should affect the choice of any part/peripheral?
Many things should be taken into account when deciding what parts to
buy. Below are some things to consider.
### Compatibility
You'll want to make sure that all the parts you buy work together
without problems. The CPU, the motherboard, and the RAM in particular
must be compatible with each other. Check the motherboard
manufacturer\'s web site; most will list compatible RAM and processors.
Often quality RAM that is not on the approved list (but is of the proper
type) will work anyway, but the manufacturers list of processors should
be rigidly adhered to, as even when a processor is supported by the
socket on the motherboard, the motherboard firmware may not support it.
You'll also want to make sure that your operating system supports the
hardware you choose. Windows is supported by almost everything, though
watch out for older components if you\'re planning on using Windows 11.
If you have any interest in running Linux, or another operating system
now or in the future, buy parts that are supported by that OS (Operating
System). Check online to make sure there is no history of your chosen
components causing issues when used together, or with software you plan
on running.
### Ergonomics
!This ergonomic mouse looks strange, but it is designed to reduce
strain on your
hands.
Ergonomics is the science of designing things so that they work with the
human body. This is obviously important when choosing peripherals such
as a keyboard or mouse but should also be considered when selecting a
monitor, and especially when setting up the computer for your use. If
your wrist hurts or you're getting a crick in your neck, look at the
physical setup of your computer, check your chair height and posture. An
ounce of prevention here can avert troublesome repetitive strain
injuries. Learning to type without looking down at the keyboard is very
useful for avoiding neck strain.
### Operating temperature
!A computer chip that has burnt out. Preventing damage like this is
much easier then repairing
it.
Modern components, notably processors, GPUs, RAM, and some elements on
the motherboard, are very small and draw a lot of power. A small area
doing a lot of work with a lot of power leads to high temperatures.
Various factors can cause electronic parts to break down over time and
all of these factors are exacerbated by heat. Very high temperatures can
burn out chips almost instantly, while running hot can shorten the
useful life of a part, so the cooler we can make these parts, the
better.
If you are not going to overclock your system, stock air cooling, when
paired with a good case with adequate fans, should be enough to keep
your system cool. If you want a quiet computer then components designed
for passive (fan-less) cooling can be paired with very low noise case
fans (or a well-vented case). In general, high-end parts will require
more attention to cooling.
To keep your system at a proper operating temperature, you can monitor
vital components with software (which usually comes with your
motherboard). If you are seeing high temps, make sure the interior of
your case is dust free, and remember that most cooling solutions can not
reduce the temperature of your computer parts below room temperature. Of
course, unless you happen to have your computer outdoors in a climate
such as the Sahara, room temperature will be well within the thermal
limits of any component on your computer.
Which brings us to overclocking. It\'s specialty cooling solutions that
make overclocking possible, a processor that might run stable at a
maximum of 4.4 GHz at could hit speeds
as high as 5.6 GHz with specialized cooling systems. A sensible person
wanting a 20% overclock could add a special fan/heatsink to his CPU and
some extra case fans. An enthusiast seeking a major overclock might go
with a water-cooling solution for the CPU and GPU and sometimes other
chips. The real fanatics have been known to use liquid nitrogen or total
immersion in pure water or oil. You should not try any of the more
extreme solutions unless you really know what you\'re doing.
### Price
Today, there are a wide array of hardware components and peripherals
tailored to fit every home computing need and budget. With all these
options to choose from, it can be a bit overwhelming if you\'ve never
bought computer parts before. Shop around and remember to factor in
shipping and handling, and taxes. Some places may be priced a bit
higher, but offer perks such as free shipping, limited warranties, or
24-hour tech support. Many websites, such as CNET
and ZDNet offer comprehensive reviews, user
ratings, and links to stores, including price comparisons.
Since prices for any given part are always falling, it's tempting to
just wait until the part you want goes down in price. Unfortunately the
reason prices decline is that better/faster parts are coming out all the
time, so the part you want this year that costs \$500 may well be \$300
next year, but by that time you won't want it any more, you'll want the
new, better part that still costs \$500. At some point you've got to get
on the bus and ride, even if the prices are still falling.
Usually the best bet is to buy just behind the bleeding edge, where,
typically, you can get 90% of the performance of the top of the line
part for 50% or 60% of the price. That last 10% is very expensive and if
you don't need it, you can save a lot of money with the second-tier
part.
It\'s a good idea to think about future upgradeability when selecting
some components. While the computer that you\'re building today may be
fine for your current needs you may want to upgrade it later. So look
for components that support the newest standards and have room for
future expansion, like a motherboard that will allow you to fit more
memory than you are planning to use, or a case that has room for extra
storage drives. If your current machine is maxed out the only possible
upgrade is often a new machine.
You may also find that by over-specifying in some areas you can save
money on others, e.g. if you don\'t currently need WiFi but you do need
Bluetooth then you might want to purchase a WiFi card anyway as some of
the higher end WiFi cards also support Bluetooth.
### Performance
If money is no object just buy the most powerful components you can
find. If, like most of us, there are limits to what you can/want to
spend, then focus on those areas where more powerful parts will pay off
for you and scrimp on others. Always look for that sweet spot on the
price/performance curve where you get the most bang for your buck. When
deciding where to cut back, remember that you have the option to upgrade
in the future. Some components are easier to upgrade then others such as
RAM, where an upgrade is as simple as popping more into a free slot.
Other upgrades, such as replacing the CPU or GPU with a better model are
more costly, as the original often serves no purpose following the
upgrade (But may be resold online to recoup some of the cost).
## Primary components
These are the components that will be the core of your new computer. It
is impractical to put together a PC compatible computer without these
components and a bare set of peripherals.
!Exploded view of a personal computer:\
1 Monitor\
2 Motherboard\
3 CPU
(Microprocessor)\
4 ATA sockets\
5 Main memory (RAM)\
6 Expansion cards\
7 Power supply unit\
8 Optical disc drive\
9 Hard disk drive
(HDD)\
10 Keyboard\
11 Mouse "wikilink")
4 ATA sockets 5 Main memory (RAM) 6 Expansion cards 7 Power supply unit 8 Optical disc drive 9 Hard disk drive (HDD) 10 Keyboard 11 Mouse "){width="350"}
### Case
The case is one of the most practical straightforward parts of a
computer. A case can also be aesthetically pleasing, and help improve
your computing experience.
#### Form factor
Form factor is the specification that provides the physical measurements
for the size of components supported. Your case should support one or
more of the following common formfactors. It\'s a good idea to match the
formfactor of a case with a motherboard.
##### Large Form Factors
- EATX or Extended ATX boards are
12x13cm. This format is almost
exclusive to workstation and high end gaming computers.
- ATX is the most common form factor and
is the de facto standard. Supports about 7 expansion slots.
These formfactors offer the most amount of flexibility in expansion.
These spacious cases are often easy to work in, but hard to move around.
##### Small Form Factors
- microATX, or µATX, is smaller than
standard ATX. Many cases that support ATX also allow micro-ATX.
Supports about 4 expansion slots.
- Mini-ITX is even smaller at
6.75cm square. Supports at most one
expansion slot.
These form-factors let you build relatively small and even portable
computers, ideal for taking to LAN parties or for people who frequently
move.
Slim cases are offered in these form factors. These cases are
significantly thinner then regular cases. However, you will be limited
to using slim expansion cards as well. You may also need to use laptop
components in some areas to save space depending on the case.
Particularly small cases can be hard to work in and offer limited
expansion. They may have airflow problems, and cable management can be a
challenge. You may need to find low profile cooling units, and the case
may not support regular sized power supplies. You may also want to get
angled cables or adapters if spacing between parts is tight, and you
suspect it would make your work easier.
#### Drive Bays
Internal storage drives take up space in the case, so make sure you
consider how many drives you will need and what size slot they require.
Not all cases support every drive size.
There are several bay sizes, and each has a typical use.
- 5.25\" bays typically hold optical drives, fan controllers, or other
accessories, and are external facing.
- 3.5\" external bays are typically used for smaller versions of
accessories found in 5.25\" bays (But not optical drives).
- 3.5\" internal bays are used for holding desktop hard disks or an
SSD.
- 2.5\" bays are typically used for holding an SSD or laptop size hard
disk.
Note that it\'s possible to buy adapters to fit items that go in small
bays (usually hard drives) into large bays.
Many cases offer modular drive bays, which can be removed if they are
not needed to make space for other components. This can be useful if a
drive bay is getting in the way of another component, such as a long
graphics card.
Some cases designed for minimalist aesthetics or gaming will not use
external drive bays to make room for better airflow. If you use a case
like this and need an optical drive, you will have to get an external
drive.
If you are planning on using an M.2 SSD, your motherboard will provide a
slot for your storage device. Some cases will have dedicated mounting
points for 2.5\" storage drives, which can free up space in other areas
of the case.
#### Front IO
Almost all cases will feature a power on button on the front of the
case. Other common IO featured on the front of cases includes audio
jacks, USB ports, a reset button, status lights, and other features.
It\'s important to consider where the front IO is on the case you buy,
and how it factors into your workspace. For example, if your case will
just barely fit under your desk, IO located on the very top of your case
could be hard to use.
In rare instances when you are not purchasing a new case you need new to
get front IO separately from your case, (For example, when using an very
old, nonstandard, or DIY case) there are simple kits available that give
you a power button and a few IO ports. Alternatively you can manually
use a jumper each time you want to turn the computer on, though this is
somewhat tedious.
#### Computer Aesthetics
Cases are typically made of steel or more rarely aluminum, and usually
have accents made out of plastic. More exotic case materials are
sometimes used such as wood.
Some cases hide their 5.25\" bays with a door for a cleaner look. This
has a practical benefit of helping reduce drive noise.
A quality case will include features that make it easier to manage
cables. Besides looking better, by keeping cables out of the way and
orderly, maintenance and troubleshooting is made easier.
Cases typically mount the power supply in either the top of the case, or
the bottom. Some higher end cases will have a separate chamber for the
power supply, assisting cable management and giving it a degree
separation from the hot components in the rest of the case.
Many cases will have windows installed. These provide a view into the
system, and can highlight nice looking components. When moving a
computer with a windowed case, keep in mind that an acrylic window will
easily scratch, and a glass window may shatter. A solid sheet of metal
is best when it comes to blocking noise and durability.
Many gamers use components with RGB lighting to give their computer
flair. Keep in mind that there aren\'t really unified standards for RGB
lighting, so if you want to mix and match between different
manufacturers and coordinate the resulting lightshow you\'ll need to use
multiple software products at the same time. RGB LED light strips, or
their older counterpart cold cathode lights can be used to provide
lighting if your components lack integrated lights.
Some cases feature integral noise reducing foam, offering a clean look
while providing the benefits of noise reduction.
Many people like to mod their cases. There
are many easy mods that can be done before your computer is built (And
all electronics are removed from the case), such as painting the case a
different color, or giving it a funky coat of paint through Hydro
dipping
A case stand can be a good tool to use if you plan on placing your
computer on the ground, as it creates additional clearance from things
such as dirt, dust, and carpets.
You may want to use a dust cover for unused ports. This helps you avoid
trying to plug in devices into the wrong ports when reaching behind a
case, and helps make cleaning easier. Dust covers also exist for
external peripherals such as monitors if you plan on storing them away
for a while.
### Cooling
#### Fans
!Two fans of different
sizes.
Most cases mount one or more case fans, distinct from the fans that may
be attached to the power supply, video card and CPU. The purpose of a
case mounted fan is to move air through the system and carry excess heat
out. This is why some cases may have two or more fans mounted in a
push-pull configuration (one fan pulls cool outside air in, the other
pushes hot interior air out). The more air these fans can move, the
cooler things will generally be.
Fans for case cooling currently come in two common sizes, 80 mm and
120 mm, and computer cases tend to support one size or the other. The
larger 120 mm fans spin more slowly while moving a given volume of air,
and slower fans are usually quieter fans, so the 120 mm fans are
generally preferred, even though they cost a little more. Good 80 mm
fans can still be fairly quiet, so while fan size is a factor, it
shouldn\'t be a deal-breaker if the case has other features you like.
Make sure the power plug on the chosen case fan is supported by your
motherboard; 3- and 4-pin connectors are common. Fans can also be
powered directly by the PSU, but in that configuration, the motherboard
can\'t control or report the fan\'s speed.
Variable speed fans with built-in temperature sensing are available.
Variable speed fans tend to run quieter than constant speed fans, as
they only move as much air as needed to maintain a set temperature
within the case or the power supply box. Under typical operating
conditions they may be barely audible.
Since fans run continuously when the computer is turned on, bearing
selection may be important for long life.
- The least expensive fans use **sleeve bearings**. As the fan ages,
the lubricant in the sleeve bearing dries out and eventually the
bearing wears, allowing the fan blade to nutate or vibrate, making
it very noisy. In severe cases the bearing may seize and the fan
will stop turning entirely, possibly jeopardizing the computer when
ventilation fails.
- The most expensive fans tend to be those that use **ball bearings**,
but they also have very long service lives. It isn\'t uncommon for a
ball bearing fan to run continuously for 7 to 10 years --- possibly
longer than the useful technological life of the computer within
which it is mounted. Ball bearing fans tend to be slightly noisier
than sleeve bearing fans.
- A fairly recent type of fan bearing is a **magnetic** or
**\"maglev\"** bearing, which uses a magnetic field to suspend the
fan rotor without physical contact. Such fans exhibit practically
zero bearing wear and barring a failure in their motor drive
components, have essentially an infinite service life. Maglev
bearings also tend to be completely silent, and when used in a
variable speed fan, can produce practically silent ventilation.
The orientation of fans inside your case can have a big impact on
cooling, as well as how quickly dust builds up. Some cases will include
dust traps to reduce the amount of dust entering a system. Aftermarket
dust filters also exist, but can be harder to mount.
#### Water Cooling
!An all in one cooler mounted on a
CPU. A
water cooling system will cool parts by running water over a heatsink. a
pump moves the water in a closed loop, which goes to a radiator for
cooling. Additional parts, such as flow sensors and quick connects, can
make maintaining a water cooling setup easier. Since the radiator can be
placed anywhere, it can be much bigger then a typical heatsink, allowing
for more efficient cooling. Typically water cooling is used for the CPU,
but it can also be used for other components, such as graphics cards.
Custom water cooling setups can either use hard tubing or soft tubing.
Some manufacturers make All in One (AIO) watercooling units, which is
basically a water cooling solution that\'s prebuilt.
Compared to air cooling, water cooling adds significant cost,
complexity, and risk to a system build. However it can allow for quieter
operation, and a well built water cooling setup can look great.
#### Minor component cooling
While shopping for coolers you may see passive, fan, or even water
cooling solutions for RAM, chipsets, SSDs and other devices. These
devices do not typically produce significant heat, and do not require
additional cooling. These devices are mainly aimed at serious
overclockers and those who want to improve the aesthetics of these
components. However running components cooler to a point can be good for
their lifespan, and adding these components typically only hurts your
wallet.
### Power Supply
!A modular power supply on the left sits next to a non-modular power
supply on the right. By allowing you to select only the cables you need,
Modular power supplies make cable management much
easier.
#### Power Supply Basics
The power supply unit (PSU) is a device that converts the electricity
from the power grid into a form you can use. The power supply you choose
needs to supply enough stable DC power to all the components and even to
some of the peripherals. It needs also to be consistent, by complying
with accurate standard voltages, i.e. the 12 volt rail needs to supply
12 volts (within normal tolerances of 10% or so) steadily under any
foreseeable load, likewise the 3 and 5v rails at their respective
voltages. Cheap power supplies tend to fall down in these areas. There
are several tech-heavy websites that actually throw a multimeter on the
PSU in the course of a review, seek these out and make sure you select a
quality PSU.
#### PSU Specs
Power supplies typically use one of two ratings, one being the
continuous rating and the other being the peak rating. The continuous
rating is how much power can be delivered indefinitely, and the peak
rating is how much power can be delivered for a limited period of time.
You want to go by the continuous rating to be safe. There are several
calculators that try to help you select an adequate PSU for your system,
which are linked in the footer.
Your power supply should have the right number of connectors for your
needs e.g. six-pin PCI power, ATX12VO vs. 24-pin motherboard connectors,
etc. If you are planning on running two or more video cards in SLI
(NVIDIA) or Crossfire (AMD) mode, make sure your power supply is
certified for that use. Most power supplies will have cables long enough
for most any case, but some larger cases will make good cable management
difficult with power-supplies that have shorter cables.
Cheap power supplies often require you to select your mains voltage with
a switch. Higher quality power supplies have circuitry that actively
adjusts for incoming voltage, and thus do not need to be told what
voltage to expect. It\'s always a good idea to check to make sure a
power supply is compatible with the mains power used in your country
prior to use.
Choose an efficient PSU. Efficient PSUs run cooler and more quietly and
thus do not create as much noise which is important if you plan to sleep
or think in the same room with it or use it as a media center PC. They
also reduce energy usage, which in turn saves money on the electric
bill.
If your budget allows, consider opting for a modular PSU. These have
connectors that can be added or removed, which allows for more
versatility and also reduces clutter. The power supply also has an
exhaust fan that is responsible for cooling the power supply, as well as
providing a hot air exhaust for the entire case. Some power supplies
have two fans to promote this effect.
It is important to buy a power supply that can accommodate all of the
components involved. A bad or inadequate power supply can fail and
destroy not only itself, but potentially the rest of the computer, so
it\'s important to get a decent one. Keep in mind that having a
higher-rated power supply will not draw much more power than what your
computer actually uses, but it may decrease the efficiency of the unit
if significantly less power is being drawn then what the power supply is
rated for.
#### PSU accessories
A surge protector is a good idea. Not only does this help protect your
computer, it also can expand an outlet for more peripherals. Higher end
surge protectors often include protection for network cables as well.
To supplement a PSU, consider getting an Uninterruptible Power
Supply (UPS). This is a
device that provides a few minutes of temporary power to your computer
and monitor during a brownout or blackout giving you enough time to
safely shut down your computer. UPS units are typically external and
look and function like big power strips. Many consumer UPS units have
built in surge protectors. If you live in an area with poor power
quality or frequent blackouts, a UPS can help save your PSU from
significant wear.
### CPU (processor)
We discuss choosing a CPU in the next chapter, How To Assemble A
Desktop PC/Choosing the
parts/CPU.
### Motherboard
!A PC motherboard: IDE connectors and the motherboard power connector
(white with large holes) are on the left edge. Between them and the
large quadratic CPU socket in the lower middle are the longish RAM
sockets. The extension slots are above the CPU socket (two white, one
black) and the ports for external devices are on the right
edge. are on the left edge. Between them and the large quadratic CPU socket in the lower middle are the longish RAM sockets. The extension slots are above the CPU socket (two white, one black) and the ports for external devices are on the right edge."){width="350"}
The motherboard is a very important part of your computer. A good
motherboard allows a modest CPU and RAM to run at maximum efficiency
whereas a bad motherboard restricts high-end products to run only at
modest levels. Higher end motherboards often offer additional features,
such as faster built in networking, better built in audio, built in
Wi-Fi, a small display that shows diagnostic codes, better power
delivery to support overclocking and reliability, RGB LED controllers,
built in IO Shield, or other features. The difference between a cheap
and a quality motherboard is typically around \$100.
There are many things one must consider in choosing a motherboard: CPU
interface, Chipset, form factor, expansion slot interfaces, and other
connectors.
#### CPU interface
The CPU interface is the \"plug\" that your processor goes into. For
your processor to physically fit in the motherboard, the interface must
be an **exact match** to your processor. Intel currently has two
mainstream formats, the LGA 1700 for their current Core processors
(i7-13700K or i3-12100) or the LGA 1200 supporting their older
processors. AMD currently uses a few sockets: AM5 for their current
Ryzen CPUs (Ryzen 9 7950X or Ryzen 5 7600X), AM4 for older Ryzen
processors, and TR4 for their thread ripper processors.
Check with the motherboard manufacturer to ensure that the slot on the
motherboard will support the CPU you want to use. It is important to
know whether the motherboard\'s bus can support the exact CPU you plan
on using.
If the motherboard, CPU, and heatsink/fan are not compatible and
installed correctly, you can destroy the CPU and/or the motherboard in a
matter of seconds. Most modern processors come with a stock cooling fan
which will work well at stock speeds, stick with this if you have any
doubts.
#### Chipset
The Chipset is a piece of hardware integrated into the motherboard and
cannot be upgraded later. This often determines what processors are
supported by the motherboard, as well as how many lanes and the
generation of PCI Express, USB ports, and SATA ports/slots the
motherboard supports. USB and SATA ports can be expanded by add on
cards, but PCI express lanes are fixed. Cheaper motherboards tend to use
cheaper chipsets with reduced features.
#### UEFI
Motherboards come with a piece of software that called UEFI or BIOS in
older models. This software is responsible for preparing your computer
for use by an operating system, as well as for configuring low level
details of your system. Features offered by UEFI or BIOS vary quite a
bit between manufactures and product lines. Some UEFI or BIOS can be
updated, allowing for security fixes or new features to be added after
purchase, and many of these systems will feature some form of redundancy
to recover from a failed update (Which otherwise may turn the
motherboard into a paperweight). Other motherboards allow BIOS control
of overclocking of CPU, RAM and Graphics card which are much more stable
and safer for overclocking. Newer BIOS have temperature controls, and
functions that shut down the computer if the temperature gets too high.
Some motherboards are supported by open source firmware like
coreboot which can offer a fast and secure
booting environment.
#### M.2 and SATA interface
SATA (Serial ATA) connections for hard drives and optical drives. SATA
data connections are simple - one plug, one cable, one device. SATA
power connections follow the same principal.
The serial ATA (SATA) interface has a separate motherboard connection
for each drive that allow independent access and can increase the speed
at which drives work. The cables are also narrow, improving the flow of
air inside the case.
An M.2 Slot can be found on some motherboards to add an SSD. Unlike a
SATA Drive, M.2 drives are small enough to be mounted directly on the
motherboard.
#### Expansion slot interfaces
!PCI Express slots (from top to bottom: x4, x16, x1 and x16), compared
to an old 32-bit PCI slot
(bottom), compared to an old 32-bit PCI slot (bottom)"){width="300"}
Due to the evolution of new graphics cards on the serial PCI-Express
Technology, current newer motherboards have the following connections:
- **PCI-Express(Gen 1/2/3/4) 16x/8x/4x** for mainstream graphics cards
(PCI Express Gen 1 x16 is 4 times speed of AGP 8x)
- **PCI-Express(Gen 1/2/3/4) 1x** for faster expansion cards
(replacing older PCI)
+-------------------------------------------+-------+----+-----+-----+
| it:Costruire un
computer/Componenti
[^1]: intel :
serious-gaming
[^2]: <https://www.pcgamesn.com/fastest-ddr4-ram>
[^3]: graphicscardhub:
gpu-slot-type
|
# How To Assemble A Desktop PC/Assembly
Now that you have selected your parts, you get to what is arguably the
most fun part of the process: putting the parts together.
## Tools and equipment
!Combination flanged-hex/Phillips-head screw used in
computers
You won't need many tools to assemble your computer, in fact the only
one you must have is the screwdriver, but if you can get most of the
following together, you'll find things go a little easier.
### Basic tools
Before you begin building or refitting a computer, you should have some
basic tools:
1. #2 Phillips-head (cross-shaped) screwdriver
2. Needle-nose pliers
3. A large level working space
4. Brush
!An anti-static wrist strap with
crocodile
clip.
### Optional, but useful tools
Some other tools and equipment can come in handy as well, such as:
1. Anti-static Wrist Strap (**Highly Recommended**)
2. An Anti-static mat can help provide a safe place to set components
down.
3. Spring action parts grabber.
4. Electrical tape
5. Wire or nylon ties
6. Flashlight, preferably hands-free
7. A second, working computer to swap parts, look for tips, ask for
help on-line, download drivers and patches, etc. - very useful
8. A can of compressed air - useful when working with older parts that
have collected dust. A better alternative but also more costly, is a
vacuum cleaner designed for cleaning electronics.
9. Magnetic screwdriver
10. Zip ties or velcro ties for cable management
## Preparation
Proper preparation is the key to a successful build. Before you begin,
make sure you have all the tools you will need, secure a clear, well-lit
workspace, gather all the components you'll be using and unpack them one
at a time, verifying that everything that is supposed to be there is
actually present. At this point you should leave the parts themselves in
their protective anti-static bags, and assemble all the accompanying
manuals. Now I know you want to get started, but trust me, *read the
manuals*, check the diagrams, make sure you understand where each part
goes and how it attaches. If there is anything you don't understand, now
is the time to do a little extra Internet research or call the
manufacturer with your questions.
Find a dry, well-ventilated place to do your work. You should have
plenty of light and if possible, you should choose an area without
carpet on the floor, as carpet tends to generate a lot of static. An
unfurnished basement is a good work location.
### Safety precautions
1. Static electricity is the biggest danger to the expensive parts you
are about to assemble. Even a tiny shock, which is much too small
for you to feel, can damage or ruin the delicate electronic traces
many times smaller than a human hair that make up your CPU, RAM and
other chips. It's important to use your anti-static wrist strap to
prevent damage to these components. Once you have the power supply
installed in the case, clip the end of the wrist strap to the
outside of the power supply. (Never plug your computer in while you
are connected to it by a wrist strap.) This will ensure that you,
the case and the power supply are all connected to a common ground,
in other words there will be no inequality of charge that will allow
a spark to jump from you to the case. It's also helpful to have an
anti-static mat to set the case and other components on.
2. Nobody but you is at fault if you shock your components with static
electricity. Make sure that you take the precautions in the previous
paragraph to ground yourself from static electricity. (Note: if you
really must work on a computer and have not got proper anti-static
equipment, it is *usually* OK if you make sure that you do not move
about much; are not wearing any static-prone clothing; handle
components by the edges; and regularly (once a minute or so), touch
a grounded object.). The *case metal* of your PC\'s power supply
will usually be a suitable grounded object (please note that the
metal must be unpainted). As noted above, touch it every few minutes
while you are working on your PC if you haven't got a wrist strap.
3. Turn off your computer and switch off your Power Supply at the wall
before installing or removing any components - if power is flowing
to components as they are installed or removed, they can be
seriously damaged. In order to have a computer properly grounded,
you need it plugged in at the wall but turned off at the power
supply and at the wall. The neutral line may be earthed.
4. Never cut the grounding pin off your power cord. This \"safety
ground\" stands between you and potentially lethal voltages inside
the power supply.
5. Be wary of sharp edges! Many lower-end PC cases have sharp,
unfinished edges. This is especially so on interior surfaces, and
where the case has been cut or punched-out. Use care and take your
time to avoid cutting your hands. If your case has this problem, a
little time with some sandpaper before you begin construction can
spare you a lot of pain. Be extra careful not to cut yourself when
installing the I/O Shield.
6. Dismantling discrete electronic components such as your Power Supply
or Monitor is dangerous. They contain high voltage capacitors, which
can cause a severe electric shock if you touch them. These hold a
charge even when the unit is not plugged in and are capable of
delivering a fatal shock.
## Construction
Start by putting your case down on your work surface, with the case door
facing up, and open the case.
### Motherboard
!{width="800"
height="800"} Find the motherboard standoffs
(spacers) that should have come with the case. They are screws, usually
brass, with large hexagonal heads that are tapped so you can fasten
screws into the top. These hold the motherboard up off the case
preventing a short-circuit. Set these aside.
!A variety of io shields. Make sure to install this before installing
the
motherboard!.jpg "A variety of io shields. Make sure to install this before installing the motherboard!")
Remove the I/O Shield from the back of the case where the ports on the
back of the motherboard will fit, and put in the I/O Shield that came
with your motherboard. There may be small metal tabs on the inside of
this face plate, if so you may have to adjust them to accommodate the
ports on the back of the motherboard.
Some case styles make it difficult to install the motherboard or the CPU
with the power supply installed. If the power supply is in your way,
take it out and set it aside (we\'ll put it back in later).
Now locate the screw holes on your motherboard and find the
corresponding holes on the motherboard plate (or tray) in the case. Put
a standoff in each of these holes on the tray and position the
motherboard so that you can see the holes in the top of the standoffs
through the screw holes in the motherboard.
Now is the time to make sure the ports on the motherboard are mating
with the backplate you just installed, and make any necessary
adjustments. The small metal tabs are intended to make contact with the
metal parts of the connections on the back of the motherboard and ground
them, but you may have to bend these tabs a bit to get the ports all
properly mounted, this is where those needle-nose pliers may come in
handy.
Now fasten a screw through each of the motherboard screw holes into the
standoffs underneath. These screws should be snug but not tight, there
is no reason to torque down on them, hand tight is fine, otherwise you
can damage the motherboard.
Once the motherboard is installed, it is time to plug the other
components.
### CPU
!Some motherboard CPU sockets come with a plastic protector. This
should be removed before the CPU is inserted, and saved for
later.
!An example of a Intel CPU socket,
LGA2066.
!An AM4 socket for AMD
processors_02.jpg "An AM4 socket for AMD processors")
Installing the CPU, and the CPU's heat-sink
and fan, are by far the most difficult steps you'll have to complete
during your build. Here, more than anywhere else, it will pay to read
the instructions carefully, look at the parts, study the diagrams that
came with your CPU and/or third party cooling solution, and make sure
you thoroughly understand what you are going to do *before you try to do
it*. During the process, if anything does not seem to fit or make sense,
put the parts down and look things over carefully before you proceed.
Some operations, especially installing the heat-sink/fan combination,
can require pretty firm pressure, so don't be afraid to push a little
harder if you're sure everything is set up correctly.
The details of the installation process differ in slight but important
ways for each manufacturer's processors, and even within a
manufacturer\'s product line. Therefore, for these details, you should
rely on the instructions that are provided with the CPU.
The two things that go wrong the most often and most expensively
(minimum of a killed CPU, sometimes more) in building one\'s own
computer are both related to the CPU and its cooler:
1. Switching the computer on \"just to see if it works\" before adding
any CPU cooling unit. Without cooling, CPUs heat up at extreme rates
(a CPU heats up anywhere between ten times and a thousand times as
fast as a cooking area on your stove!). By the time you see the
first display on the screen, your CPU will already be severely
overheating and might be damaged beyond repair.
2. Mounting the CPU cooler improperly. Read the instructions that came
with your CPU and cooler very carefully and ensure you are using all
components in the correct order and correct place.
!The base of a CPU heatsink. Remove any plastic film on the bottom of
the heatsink before
installation.
If you buy a third party cooling solution for your CPU make sure you get
one that is compatible with the CPU you have. \"Compatibility\" here
just means, \"Can you fit it in next to your RAM or whatever else is
sticking up in the neighborhood.\" Most brands come with multiple
mounting brackets that will suit many different chipsets, but it is best
to check for compatibility just in case.
After the CPU is installed in the socket and secured in place, it\'s
time to add thermal paste and then install the cooler. The plain metal
back of the CPU, which is what you\'re now seeing, is exactly matched by
the bottom plate of the cooler. You add thermal paste *only* on the CPU,
*never* on the cooler\'s surface. Very little is needed. The two flat
metallic surfaces will spread the paste between them, and it will spread
a bit more when it becomes hot. (The cooler surface may have a
protective piece of film over it; don\'t forget to remove it. But see
below for the possibility of \"thermal pad\" being supplied, instead of
paste. This is rare nowadays, but *read the instructions.*) A pea-sized
dot is the amount usually advised, though some people make a thin \"X\"
on the CPU surface, and some draw a line. (There are numerous videos on
YouTube advocating one or another, some with photos using glass plates.)
Don\'t overdo \-- you don\'t want paste squeezing out the edges. Some
people suggest spreading paste over the whole surface, then cleaning it
off with a razor blade, then adding the pea. The idea is to close
invisible imperfections in the metal. This is probably overkill, and
involves extra handling of the CPU, never a good idea. Try not to touch
the mating surfaces of the CPU and cooler \-- the oils from your skin
will impede heat transfer. You should receive a tube or applicator of
thermal paste in the CPU or cooler package, some CPU coolers come
pre-applied with thermal paste (such as AMD\'s wraith cooler), you can
optionally add your own to the CPU as extra or continue with the
pre-applied compound. If your CPU didn\'t come with thermal paste and
the cooler didn\'t have any pre-applied, thermal paste is readily
available from most computer retailers.
*See Arctic Silver
Instructions for more
info on how to apply and remove thermal paste/grease. (It was written to
be specifically for Arctic Silver paste, but the same techniques can be
applied to other brands of thermal paste.)*
If using a thermal pad supplied with your cooler, make sure you remove
any protective tape from the die just before installing and do not get
it dirty - and do not combine thermal pads with thermal paste, it is
either one or the other. Then, check that you install the cooler in the
right orientation and that you set it flat on the CPU die without
exerting undue pressure on any edges or corners - the latter can make
small pieces of the die break off, killing the CPU.
One option you may consider, before installing the heat-sink, is to
\"lap\" the heat-sink, which means to smooth out the bottom surface. To
do this, you will need a very flat surface; a piece of thick window
glass will work. Fasten your sandpaper on the flat surface, invert the
heat-sink on the sandpaper and sand in small circles, applying minimum
pressure. Check frequently and when you see a uniform pattern of
scratches, switch to finer grained sandpaper (the numbers go up as the
sandpaper is finer, so something such as 220 is coarse while 2000 will
be very fine.) Remember that you are not trying to remove any material,
just polish out surface irregularities. If you get it right, you should
have a surface which feels completely smooth to the touch (but don't
touch it, the oil in your fingers can cause corrosion of the fresh
surface) with a mirror finish. Some companies producing heat-sinks lap
the surface themselves, so if the surface already looks like a perfect
mirror, leave it alone. A lapped heat-sink is more effective as it will
have better surface contact with the chip.
Tighten the cooler using only the specified holding devices - if you did
everything right, they will fit. If they do not fit, check your setup -
most likely something is wrong. After mounting the cooler, connect any
power cables for the fan that is attached to the cooler.
As an aside to the instructions above, it has been my personal
experience that fitting the CPU and heat sink is best done on a
supportive surface (a telephone directory on a table in my case) prior
to installation, to avoid excessive flexing of the motherboard.
A last note: if something goes wrong and the cooler has to be removed
(like maybe you realize you didn\'t take the protective film off the
cooler surface), the paste will have to be removed from the CPU for the
restart. *Don\'t panic!* All it takes is a coffee filter (not paper
towels or anything else that will leave fibers) and a little isopropyl
alcohol (from the drugstore). Thermal paste removes easily with a little
gentle rubbing. Work from the outside edge in.
If you\'ve got the CPU and its cooler installed, and the motherboard in
the case, you're over the hump, there are just a few more easy pieces to
go before that momentous first power-up.
### Memory slots
!RAM module in a
socket{width="325"}
Next, you will need to install your RAM (random access memory). Find the
RAM slots on your motherboard; they will look something like the picture
on your left. To install the RAM modules, first push on the levers
(white plastic in the picture) on either side of the DIMM socket, so
that they move to the sides. Do not force them, they should move fairly
easily.
Put the RAM module in the socket. Line up the notch in the center of the
module with the small bump in the center of the RAM socket, making sure
to insert it the right way. Push down on the module until both levers
move up into the notches on the sides of the module. There should be a
small \"snap\" when the module is fully seated. Although this does
require a fair bit of force, do not overdo it or you may break the RAM
module.
!Motherboards often use color coded slots to indicate which slot
corresponds to which RAM
channel
Take a good look at your seated RAM, if one side seems to be higher than
the other, odds are it is improperly seated - take it out and try again.
As you handle the RAM, try not to touch the copper stripes you can see
along the bottom edge, as doing so is the best way to damage the part.
Start adding RAM at the slot labeled \"Bank 0\" or \"DIMM 1\". If you do
not have a stick in \"Bank 0\" or \"DIMM 1\" the system will think there
is no RAM and will not boot.
On motherboards with 4 slots, you\'ll see alternating colours. For
example, slot 1 is blue, slot 2 is black, slot 3 is blue, slot 4 is
black.
If you were to put 16 gigabytes of RAM in your personal computer, it is
best to use dual channel 8 GBx2 sticks. Put the first 8 GB stick in
**slot 1**, and put the 2nd stick in **slot 3** (the two slots that are
blue) - leaving slot 2 empty. This will give you better performance,
than putting 16 GB in slot 1 alone.
### Power supply
Installing your power supply is pretty straightforward, if it came with
your case it was pre-installed and if you took it out earlier to get the
motherboard in, now is the time to put it back. Otherwise a few moments
of screwdriver work will get the job done. Generally there will be a
bracket on the top of the case where the power supply is mounted and a
few screws used to fix it in place. Some cases place the Power Supply
differently, see the documentation that came with yours.
Some power supplies come with modular cables, so you can plug in only
those you'll be using; now is a good time to figure out what you'll need
and plug them in. Other power supplies have all the cables hardwired in,
you'll want to separate out the ones you'll need and neatly coil the
remainder somewhere out of the way.
If your power supply has a switch to select 115 V or 220 V make sure it
is set properly, this is important. Many newer power supplies can
automatically select and don't have such a switch.
Once you get the power supply installed make sure you check the
motherboard documentation carefully for the location of the power
sockets. You may then connect the main power, a 20 or 24 pin plug, into
the motherboard. There may also be an additional four or eight pin power
lead that needs to be plugged in to the motherboard (the CPU power
connector) usually located near the processor socket.
### Graphics card
!Insert the card into a matching slot on the
motherboard.{width="300"}
If your motherboard or CPU has a built-in graphics adapter you want to
use (like Intel HD Graphics), skip this section.
If you have a PCI Express video card, install it into the PCI Express
socket. Your computer will have a few of them, but choose the one which
is most convenient for you and will allow you to fit it into the desktop
case easily. Check your motherboard manual for instructions.
When your card is properly installed the line formed by the top of the
card will be exactly perpendicular to the motherboard, if one side seems
to be higher than the other, chances are that it is not fully inserted,
press a little harder on the high side or pull it out and try again.
### Installing drives
!A Serial ATA connector
!A M.2 slot on a motherboard with mounting posts
highlighted
Next install the storage drive and optical drives.
How a drive is physically installed will depend on the case.
Most drives are SATA (Serial ATA) which use simple, small cables for a
data connection. The ends of the cables are L shaped, just look
carefully at the cable ends and the connector on the drive and match
them up. Only one drive can be connected to each SATA port on the
motherboard.
Next install the SATA power cable. Some SATA drives also have a molex
power connector - make sure you connect **only one** of these ports to
the power supply, connecting both can damage the drive.
Newer SSD\'s will often use the PCI Express standard; for those, follow
the same instructions as you would do for a PCI Express graphics card.
### Other connections
!Some cables are attached to pins on a board (e.g. motherboard or
extension
card)"){width="300"}
In order to turn the computer on, you will need to connect the power
button and while you are at it, you might as well do the reset buttons
and front panel lights as well.
There will be a set of pins, usually near the front edge of the
motherboard to which you will attach the cables sometimes already
connected to the front of the case, or if needed to be supplied with the
motherboard. Most of the time the plugs will be labeled as the pins they
will connect to in the motherboard, there they can be difficult to read
since the print is very small or you may not be in the right orientation
to do so. The documentation that came with your case and motherboard
should tell where these connectors
are.
In addition, you can connect any case-specific ports if they are
supported by the motherboard. Many cases have front mounted USB ports
and audio jacks.
### Prepare for power up
Some people will put power to a system several times during assembly and
for experienced builders this may serve some purpose. For first timers
though, it's best to assemble a minimal complete system before powering
up. Minimal because that way there are comparatively few potential
sources of trouble, complete so that you can test everything at once and
because the fewer times you have to put power to an open machine, the
better..
If you've been working along with us you should now have such a minimal
system put together. Briefly this includes a case with a motherboard in
it, a processor (and its cooling unit) and some RAM plugged into the
motherboard, hard and floppy drives installed, and some kind of video
available. If your motherboard has built-in video, you might want to use
that for this first try, even if you are going to install a video card
later.
For this test, you'll want to have the computer open, so that you can
see all of the fans, and you'll need to connect a monitor and a keyboard
and a mouse (OK, you don't really need the mouse . . .)
!Comparison of VGA, DVI and
HDMI{width="180"}
Monitors will either have a VGA, DVI, HDMI (see picture, as they are a
lot less apparent than PS/2 / USB by comparison) or for newer ones, a
Thunderbolt 3/USB 3.1 plug. Most monitors use HDMI connectors, and so
most graphics cards have HDMI output. If you have one type of plug and
the graphics card has another, you can easily buy an adapter. Some cards
even come with one.
There are two standard connectors for mice and keyboards; PS/2
connectors and the more modern USB connectors. Plug the mouse and
keyboard in the appropriate slot.
Note: If you intend to install an operating system from a boot CD or
floppy, or modify BIOS settings you will need to use either a PS/2
keyboard, a USB to PS/2 converter, or a motherboard that supports USB
devices. Otherwise your keyboard will not work until the operating
system has loaded USB drivers.
Once you have this all set up, it's time to double check, then triple
check that you have made all the necessary connections and that you
haven't left any foreign objects (where's that screwdriver?) in the
case.
## Power up
Take a moment to check one more time that everything is as it should be
. On the first power up, you will be observing the computer itself to
confirm the cooling system is working correctly, making sure that your
fans work. The first thing to look for is that the CPU cooler fan spins
up, if it does not, cut the power immediately. This fan should start up
right away. If it does not, then something is wrong and you should
shutdown the computer immediately. When you are ready remove your wrist
strap, turn on the monitor, then press the power button, and observe the
inside of the open machine. (*Do not touch any part of the inside of the
machine while it is powered up*)
If the CPU fan spins up, check that all the other fans that should be
spinning -- case fans and fans on the power supply and video card (if
installed) are also spinning. Some of these fans may not spin up until a
temperature threshold is passed, check your documentation if anything is
not spinning.
If the fans spin, you can turn your attention to the monitor, what you
are hoping to see is the motherboard's splash-screen, usually featuring
the manufacturer's logo. If you see this, take a moment to bask in the
glow, you've built a computer!
If this happy event does not occur, if smoke appears, or if the computer
does not do anything, unplug the power cord immediately and check the
steps above to make sure you have not missed anything. Give special
attention to the cables and power connections. If the computer does
appear to come on, but, you hear beeps, listen carefully to the beeps,
turn the computer off, and refer to your motherboard\'s manual for the
meaning of the beeps. Some boards have an optional diagnostic device,
usually a collection of LEDs, which when properly plugged in will inform
you of the nature of the problem. Instructions for installing this as
well as the meaning of its display should be in the manual for the
motherboard. If the computer turns on but the only thing that comes on
is your power supply, turn it off. This probably means something is
shorted, and leaving it on could damage the parts.
If all is well it is time to turn the computer off, and close it up.
Then you may want to turn it on again and set certain options in the
computer\'s BIOS/UEFI (usually by pressing \'F1\' or \'Del\' a few
seconds after boot.) These options will be explained in the motherboard
manual. In general, the default options are OK, but you may wish to set
the computer\'s hardware clock to the correct time and date. The
BIOS/UEFI is also where you determine the default boot order of the
system, typically F\\floppy, then CD-ROM, then Hard Disc.
If you want a further quick test before you install an operating system,
you may find a bootable Disk or USB flashdrive such as
Knoppix extremely useful.
## Additional hardware and peripherals
Now that you have a working system it's time to think about installing
an operating system, which is covered in the next section. It's best to
leave the installation of additional components (like expansion cards,
and second video cards) and peripherals (printers, joysticks, etc.)
until after the OS install in order to allow the plug n' play features
of the OS to do their trick.
## References
```{=html}
<references />
```
|
# How To Assemble A Desktop PC/Software
Now that you've got a functioning computer, you'll need to install some
software if you're going to do anything with it. An operating system or
two must come first, then hardware drivers (so that the operating system
can access your hardware) followed by security software and utilities.
And that's as far as we're going to go with you, but you'll also want to
install some application software -- games, word processors, databases,
programming languages -- whatever floats your boat\... That's pretty
much the point of this whole computer business after all, though I hope
you've found the journey of building it yourself has been worthwhile in
its own way.
In this section we'll consider what software you'll want to install and
how you might go about doing so.
## BIOS updates
One important step that can be required as the starting point after you
have a working PC, depending on how stable your BIOS is (bugs or any
lacking specific software and hardware support), is to do an update of
it (called \"flashing\" the BIOS). This step can be overlooked if you
are sure that any later versions of your BIOS will not solve any issues
or requirements you have. The simplest way as an initial step is to,
find another computer, download the flash update and put it on a USB
thumb drive (or another a bootable support media) and boot the new
computer with it. If you do not have another computer or thumb drive,
you will need to put off this step until after you install the operating
system (you can also use a boot disk that permits you to get an OS
running out of it) to get the new computer connected to the network.
## Operating system(s)
If you have a workable machine that recognizes the basic hardware (CPU,
memory, HD, mouse and keyboard) you can now start installing an
operating system (OS). You may select from several available on the
Internet or from your local computer store.
Options can be varied, there are many operating systems to choose from,
including commercial ones like Microsoft Windows (of which the current
version is Windows 11 version 22H2) or free ones like GNU/Linux
distribution (a free software operating system) or BSD. It all depends
on the uses you will be giving to your machine (function and required
software) and the price tag you are willing to pay and the support you
require. Simply put, can you accomplish your day to day tasks with the
software that will run under the operating system in question? Do you
require some special software availability, ability to run on older
equipment? Have you considered the costs? Determine your needs before
installing an operating system.
Note that you also have the option of installing more than one operating
system in what is called a multiboot setup. Having installed an OS, you
can always install another later. The complexity of doing so may vary,
depending on how the last one automates (or not at all) the process. If
your multi-boot setup is Windows-only, install the oldest Windows
version first.
### Installing Windows
The installation of Windows is relatively easy. Push the power button on
the front of the PC, put the DVD-ROM in your optical drive or insert the
USB, and follow the on-screen instructions (you may have to configure
your BIOS to start with the DVD or USB). If you are doing a Windows-only
install, just allocate all of the hard drive to Windows.
Some people find that it\'s useful to create separate partitions for the
operating system and data. This means that if something goes wrong with
the operating system, the partition can be formatted and the operating
system can be reinstalled, possibly without losing data. If you have
already allocated the whole disk to 1 partition and you want to change
it later, you can do so and create new partition (from the existing
partition) using Disk Management in Windows Vista and later or use a
third-party tool.
If you are installing Windows on a RAID drive, or a SATA drive in some
cases, you are going to have to provide drivers to the Windows installer
so that it can access the hard drive on the raid controller. At the
prompt where you are asked to choose a partition, you can click Load
Driver and browse (or ask Windows to search) for the driver. Unlike
Windows XP, you are not limited to floppies; a USB flash drive suffices.
It\'s a good idea to save your license key for windows in a safe place
in case reinstalling becomes necessary.
### Installing Windows to dual-boot with GNU/Linux
!Dual booting allows you to select your operating system on
boot.
If you are dual-booting, some extra factors must be considered. NTFS,
which is the default file system that Windows uses, is fairly well
supported in Linux. NTFS-3g has reached a
usable stage, with users reporting no data corruption or loss during
ordinary use of the latest versions of the driver, providing GNU/Linux
users with a reliable way to read and write NTFS partitions. This system
is now in widespread use and most up-to-date Linux distros will support
the NTFS file system. Previously only read support was safe, and this
may still be the case for some distributions. However, NTFS does have
some advantages over FAT32, in that a 4GB file size limit no longer
exists. Though Linux supports NTFS, Windows does not have built-in
support for any of the standard GNU/Linux file systems. However, there
are Windows applications, such as Ext2
IFS that can be used to read/write
ext2 and ext3 systems.
When it comes to partition the hard disk(s), remember to leave space for
GNU/Linux (a good amount is on the order of a third of your total hard
disk space). You may want to have a spare FAT32 partition (of around one
third of your disk space) on which to share documents between Windows
and GNU/Linux. Though this will most likely not be necessary unless you
are using a distro which cannot read/write NTFS. You should also modify
the partition table as necessary - you may not need as much space for
Windows or you may need more in your FAT32 transfer area. But you must
ensure that you leave at least 30 GB for your Windows installation,
since the standard installation of Windows takes up about 10-15 GB of
hard drive space, and it is always wise to leave extra on, to allow for
any changes that may occur. Windows 8 in particular blocks installing on
drives less than 16GB (20GB for 64-bit) free space. If you have 16 GB or
higher RAM, you\'ll need more space.
### Installing GNU/Linux
The primary problem faced in installing GNU/Linux is choosing between
distributions. Of the many variants of GNU/Linux, Fedora, SuSE, and
Ubuntu are generally recommended, as they are updated regularly and
compatible with a broad range of hardware:
- Ubuntu, widely regarded as one of the easiest
to use versions of GNU/Linux. The amount of community documentation
and support makes this a solid choice for a beginner.
- Fedora, a distribution known for it\'s pursuit of leading edge tech
while remaining stable.
- openSuSE, A feature rich distribution and relative of SUSE Linux
Enterprise.
- Debian, not feature packed, but a very stable operating system and a
solid base for learning more about GNU/Linux.
Some GNU/Linux variants may support hardware that these do not. If you
have obscure or old hardware, you may want to search forum sites for
various GNU/Linux variants to ensure compatibility. For example, Puppy
Linux is a small Linux distro designed to run
on older systems.
For example, let's consider Ubuntu. It\'s a variant of Debian, and is
the current standard for easy-to-use GNU/Linux distributions. One can
download the .iso image or order a DVD (containing a combined
installation and Live disk) from its website. An .iso is nothing more
than a special file format that your CD drive burning software uses to
create a copy of the software, in this case a copy of Ubuntu GNU/Linux.
The installation of most distros GNU/Linux is relatively easy. Push the
button on the front of the PC, put the disk in your optical drive, and
follow the on-screen instructions. By default, the installation version
of Ubuntu will erase all files on the hard drive and partition 1.8 GB
for the OS. If you want to customize, follow the on-screen instructions
carefully. The LiveDVD version does not erase your hard drive and is
intended solely for a user to test drive Ubuntu GNU/Linux.
When installing a GNU/Linux distro, you may be asked to choose between
alternatives -- whether to run KDE or Gnome (The desktop interfaces),
for instance, or to install vi or Emacs or nano (Text editors). If the
terms are unfamiliar a quick Google search will usually yield answers.
Most choices have comparable features, and the choice usually comes down
to preference. It can be a good idea to \"Distro hop\" or trying
multiple different distros in a short period of time, to figure out what
works best for you.
## Security
After installation, security should be your priority.
### Updates
From time to time, software companies and independent programmers
release new and improved versions to their software; these are known as
updates. Updates usually install new features or fix problems. Usually,
you should download the latest updates to improve system performance
though it\'s sometimes wise to wait a little while to be sure the update
itself does not cause problems. Many programs update themselves and this
process is known as an automatic update. If you have to manually update
your software, do so through the software developer\'s site, not through
a secondary source. This approach will reduce the chance of contracting
a virus or other piece of malicious software.
#### Windows
A newly installed computer can be attacked within moments of being
connected to the Internet. In severe cases, the attacks can render a
system unbootable or make a second reinstallation faster or easier than
manually removing the malicious programs causing the problems. To avoid
having your new computer attacked, install a firewall, or activate the
one that came with your OS. Both Windows and GNU/Linux have in-built
firewalls: in some GNU/Linux distributions, it is enabled by default.
Windows 10 includes an antivirus, but you should update to the latest
version for better protection against current threats.
As soon as you are on the Internet, run your operating system\'s update
facility to fix any security flaws that have been found since your CD
was printed. To do this before Windows 10, simply click on your Start
Menu, click on \'All Programs\', and then click on Windows
Update, and follow the instructions. On
Windows 10, open Settings and click Update and Security .
#### GNU/Linux
!The YaST (Yet another Setup Tool) Control
Center Control Center")
The method of updating your GNU/Linux system varies greatly from
distribution to distribution.
For SuSE, there are two ways:
1. YaST (Yet another Setup Tool), the default package manager/system
management tool for SuSE
2. ZENworks updater, a GUI-based updating service
For Fedora, type
: `dnf update`
as the root user inside a terminal window.
It is perhaps easiest to update the OS from Debian-based distributions
such as Debian, Ubuntu and Linspire. For Debian and Linspire you type
the following into a terminal window while running as the root user:
: `apt update`
: `apt-get dist-upgrade`
Ubuntu has you run sudo to switch run a program as root. Type the
following into a terminal:
: `sudo apt update`
: `sudo apt-get dist-upgrade`
Most distros, including Ubuntu, also have a GUI-based updater program.
#### Automatic updates
If your computer will be running overnight (or if you\'re just lazy), it
may be good to have your computer update itself.
**Debian-based (LINUX) -** Debian-based operating
systems (including Ubuntu, but Ubuntu already has a more simplified
automatic updater) will typically use a cron script
for receiving automatic updates by the console (although you can
download some GUI-based updating tools - that is, if you\'re working
with a GUI).
**Ubuntu (LINUX) -** As Ubuntu is based on Debian, you can use a cron
script, but an easier way of doing it (if you\'re using
GNOME) is to go to the \"System\" menu, then
\"Administration\", then \"Software Sources\". Then open up the
\"Updates\" tab and select \"Automatic updates\", also select \"Install
security updates without confirmation\".
**SuSE (LINUX) -** SuSE uses YaST to manage
updates, packages (applications), and system settings. YaST can be
configured to use automatic updates in the YaST control centre.
**Microsoft Windows -** Microsoft has always used the Microsoft
Update service (formerly called
\"Windows Update\") to manage updates both automatically and manually
(although by default it usually is a automatic update). Windows XP
onwards reminds you when the computer is needed to be restarted if an
update requires one via a special icon in the notification area.
Windows 10 provides an option of setting *active hours*; the computer
will not restart to complete updates during that time.
If you have Windows 10 Pro, it is possible to *defer* (postpone) updates
for up to one year or one month, depending on the type of update. It is
also possible to completely stop updates for up to 35 days (with the
caveat that all updates will then have to be installed before the
updates can be stopped again). To configure such options, go to
Settings\>Update and Security\>Advanced Options.
### Anti-malware
Anti-virus, anti-spyware, and anti-spam programs (which generically are
all called anti-malware programs) of commercial quality or better can be
found for free online quite easily and can protect your computer from
various nasties you might get while surfin\' on the Internet. Windows
programs are listed in the software section below. Third-party firewalls
for Windows are recommended as the built-in default one Windows provides
is not nearly powerful as, for example, ZoneAlarm, a third-party
Firewall solution that not only monitors incoming traffic, but monitors
outgoing traffic as well. The latest versions of Windows 10 include
Microsoft Defender, a antivirus and
antispyware program.
Security software is important and should be set up first. The best
procedure is not to connect to the Internet at all until your choice of
anti-virus, anti-spyware and firewall software is installed and
activated, then connect to the Internet and update each of these
programs, though it is usually fine to connect to the Internet for the
purpose of downloading it.
Once secured, your system should be safe for prudent Internet browsing;
however, remember to schedule regular scans and keep your security
software up to date.
## Drivers
Now that your computer is relatively secure, you will need to install
software to control your various hardware components. This type of
software is known as a driver.
Although you may find that all of your hardware works out of the box,
consider downloading the driver straight from the company\'s Internet
site. This will ensure you have the latest edition of the software.
Knowing where to download the driver is also good in case you lose the
CD that came with the device.
If you do not have a fast Internet connection (broadband), the company
usually provides an option to receive the driver CD in the mail, in
which case you\'ll want to use the CD you have now and update the driver
later. Even if something seems to be working fine, downloading new
drivers may help increase computer efficiency, though there is always a
risk that a brand new version may break something. Downloading drivers
for your motherboard\'s chipset can often help if you are having a
problem. Finally, many monitors will not go above a certain refresh rate
without the proper driver, which may be of great concerns to gamers.
If you are using Microsoft Windows, you can generally find drivers for
your selected hardware on the manufacturer\'s website. Most GNU/Linux
systems already have all of the drivers installed, with the exception of
proprietary modem and graphics drivers. If you can\'t find the driver
you need, a simple Google search will often
yield the best results. Windows Update also often can install the latest
drivers (though you may have to go to Windows Update to install it, as
they may not be considered important).
## Software
Before buying software for your new PC, remember that there is an
abundance of useful software, free for downloading, available on the
Internet. From web browsers to word processors to graphic manipulation
programs, there is plenty of software available online.
Though most of what is available is safe and useful, it's always a good
idea to do a little research and make a backup before installing
anything new. The following are some proven and reliable programs that
are available, free (or gratis), for individual use (and sometimes more;
check the license).
Broadly speaking, there are three types of licenses:
- Proprietary - This is the type of license that comes with most
software that is purchased. Source code is not available, and you
cannot make copies for others.
- Freeware - The software is zero cost (free), and you may share
copies with others. You cannot make copies and sell them, however.
The source code is usually not available.
- Free software/Open Source - The source code is available. This means
that if you know how to program, you can make and distribute
variations of the program yourself, fix bugs you find, etc. You may
share copies with others, and you may pay for the software on disk,
or download it for free. (The \"free\" in \"free software\" refers
to \"free\" as in \"free speech\", not as in \"free beer\".)
Of course, there is a lot of overlap and many exceptions to these
generalizations. Be sure to check the license that comes with your
software to be sure of what your rights are!
### Windows
- Web Browser: Mozilla Firefox,
Google
Chrome/Chromium "wikilink"),
or Microsoft Edge.
- E-mail Client: Windows Mail "wikilink"), Mozilla
Thunderbird
- Office Suite: LibreOffice, Office
365, Microsoft
Office
- Disc Tools: InfraRecorder, Nero
Multimedia Suite
- Instant Messenger: Pidgin "wikilink"),
Trillian "wikilink"),
Telegram "wikilink")
- Media Player: VLC media player,
Winamp, iTunes,
Windows Media Player
- Anti-malware: Malwarebytes "wikilink"),
AVG AntiVirus, Avast
Antivirus, ESET
NOD32, Microsoft
Defender
- Security: Spybot -- Search &
Destroy, ZoneAlarm
Firewall
- Utilities: 7-Zip,
Rainmeter, Copernic Desktop
Search
- PDF Reader: Adobe Acrobat Reader or
Foxit Reader
- Photo Editing: Paint.net,
GIMP, Microsoft
Paint
To ease out the installation process for utilities and other basic
software, you can use Ninite. Check all the
software that you need and download the installation utility. However,
note that this utility will only install in your Windows partition and
you cannot manually specify the directories in which you want the
applications installed.
You can also get many of these programs (or alternatives) from the
Microsoft Store.
### GNU/Linux
!An example of GNOME Software, a common graphical utility for managing
software on GNU/Linux
computers
Unlike Windows, on a GNU/Linux system the majority of the software that
you will want for everyday use of your computer is usually included out
of the box, or handled by the package manager provided by your
distribution. Many distros that focus on ease of use have a graphical
interface for installing software that is similar to a mobile phone app
store.
As an example, to install the software git on Ubuntu, only a single
command is needed
``` bash
sudo apt install git
```
The *sudo* command confirms you have permission to use apt. The *apt*
command calls the apt package manager. *install* lets apt know you want
to install the following item, in this case *git*.
Some distros contain an additional package manager, typically either
Flatpak, or
Snap "wikilink"). Applications installed from
these managers run in their own *sandbox* that limit their access to the
rest of the system, increasing security.
If they aren\'t already installed by your distribution:
- Web Browser: Mozilla Firefox, Google
Chrome/Chromium "wikilink"),
Konqueror or
Opera "wikilink").
- Email Client: Mozilla
Thunderbird, GNOME
Evolution, or
Kmail
- Office Suite: LibreOffice, or Calligra
Suite
- Instant Messenger: Pidgin "wikilink") or
Kopete.
- Media Players: Kodi "wikilink"), GNOME
Videos,
Rhythmbox,
Amarok "wikilink"), or VLC Media
Player.
- Movie/DVD Players: Xine or
MPlayer.
- Disk Tools: Brasero "wikilink"),
GParted
- Windows Compatibility: WINE "wikilink"),
Proton "wikilink"), or
Lutris
- Virtual systems: QEMU or GNOME
Boxes.
- Photo Editing: GIMP or
Darktable
- Art: Krita (2D Raster), Inkscape (2D
Vector), Blender (3D
Art) "wikilink")
- Audio: Audacity, LMMS,
Ardour "wikilink")
### Additional Software
#### Open source
For additional software some excellent sources of free and open-source
software are
- GitHub, GitLab, and
SourceForge - Sites featuring many Open
Source projects.
- Portable Apps - Provides portable
versions of applications meant
for running on USB keys.
- AlternativeTo - Provides lists of
alternatives to common software.
- Free Software Directory
#### Proprietary
Of course, it is also possible to *buy* copies of software.
- Microsoft Store "wikilink") - Sells
software for Windows 10 and 11.
- Xbox Game Pass - Microsoft\'s
subscription game service, available for Windows 10 and 11.
- GOG Galaxy - Sells games without
DRM.
- Steam "wikilink"), Humble
Store - Large markets of games and some
software.
- itch.io - Indie game host
- Epic Games Store,
Origin "wikilink"),
Uplay, Battle.net -
Publisher focused game sellers.
- Adobe Creative Cloud - Sells
Adobe creative products through a subscription model.
- Autodesk - Sells engineering and 3D
Software.
## See also
- A Neutral Look at Operating
Systems
|
# How To Assemble A Desktop PC/Overclocking
Overclocking is the practice of making a
component run at a higher clock speed than the manufacturer\'s
specification. The idea is to increase performance for free or to exceed
current performance limits, but this may come at the cost of stability.
Extensive overclocking will result in the destruction of hardware so
ensure proper cooling before overclocking.
Overclocking is like souping up a car: if you just want to get where
you\'re going, there\'s no need for it. But it is fun and educational
and can get you a machine that provides performance all out of
proportion to its cost.
Think of the 4 GHz on your new 4 GHz Core i7 as a speed limit asking to
be broken. Some other components in your computer can also be
overclocked, including RAM and your video card in many cases. Over
clocking is possible because of the way electronic parts, especially
VLSI (Very Large Scale Integration) chips are made and sold. All
processors in a given line, the i7 for example, are made the same way,
on a large die that is cut up into individual processors, those
processors are then tested and graded as to speed, the best chips will
be marked as 4 GHz, the second best 3.8 etc. As time goes by and
production processes and masks improve, even the lower rated chips may
be capable of faster speeds, especially if vigorous cooling is
implemented. Also many manufacturers will mark chips that test faster at
slower speeds if there is higher demand for the lower end component.
It's important to note that not every chip will be overclockable; it's
really the luck of the draw. Some companies that sell 'factory
overclocked' systems engage in a practice called "binning" where they
buy a number of processors, test them for overclocking potential and
throw the ones that don't overclock in a bin to be resold at their rated
speed. Even with processors that have a reputation for overclocking
well, some parts simply will not exceed their rating.
That said, effective cooling can give a boost to a chip\'s
overclockability. With luck you will be able to get extra performance
out of your components for free. With luck and skill you can get
performance that is not possible even when using the top of the line
components. Sometimes you can buy cheaper parts, and then OC them to the
clock speed of the higher end component, though the cost of extra
cooling can compromise any money you may be saving on the part, not to
mention warranty and part life issues.
## Things that can\'t be overclocked
Although it is possible to overclock many of the components of a
computer (such as the CPU, memory and video card), it is not possible to
overclock all components. In particular mechanical components do not use
a clock speed and can not be overclocked. For example, it is not
possible to overclock a hard disk drive, a fan, or an optical drive such
as a Blu-Ray drive. For such devices other solutions exist, i.a. use a
quicker file system and/or faster components in the first place; also in
some special cases of hard disks drives, update the driver (which
contains optimized code); remap blocks with high latencies to low
latency blocks (using a tool such as mhdd), and in event a RAID is
present, change the configuration, driver and/or software and/or
settings. However such techniques and procedures are beyond the scope of
this document.
## Components
### CPU
#### Choosing the CPU
While the CPU is usually the best component to overclock, most CPU\'s
these days are locked, which means that the multiplier cannot be changed
from its default clocks. While previously (until Sandy Bridge), users
used to work around this limitation by adjusting the base clock of the
CPU, on Sandy Bridge till Broadwell (2^nd^ to 5^th^), attempting to do
so over a few megahertz would usually cause the system to crash, even if
the CPU itself is stable. This is because increasing the base clock
would also affect other system components.
This means that, at a best case scenario of a 5 MHz increase over the
usual 100 MHz base clock, an i3-4370 (3.8 GHz) can only be overclocked
by 38\*5 = 190 MHz, which would increase the clock speed to only 3.99
GHz.
This limits your Intel CPU choice to the following, if you want to
overclock:
1. CPU\'s labelled with a K at the end of their model number (eg:-
i5-13600K)
2. Extreme Edition processors (X series). An example would be the
12-core i9-10920X.
3. Pentium G3258 (more on that later)
4. C (high end graphics) line.
Most (if not all) AMD Ryzen CPU are overclockable; it is *not* necessary
to buy the highest-end model (aka the X variant) solely for
overclocking, though such variants may include better coolers instead.
For Intel chips, these overclockable chips usually come at a 5-15%
premium over the non overclockable but otherwise identical CPU.
Now about the Intel Pentium G3258. This chip caused a lot of hype when
it was first released back in 2014, as it was the cheapest and
lowest-end Pentium chip released by Intel in honour of its 20th year
anniversary. However, the main steal in this is the fact that this CPU
is highly overclockable, which made all the difference. Still though, it
won\'t reach the level of a stock i5 with overclocking; its dual-core no
hyperthreading design can hurt it badly, and it\'s now over {{#expr:
- 2014}} years old. If you really need to
build an ultra-budget PC, then a Ryzen 3 or a non-overclockable Pentium
Gold processor would be a better choice.
The integrated graphics (if present) on the chip can often be
overclocked even on otherwise non-overclockable CPU\'s.
#### How to overclock
For older computers, one changes the clock speed of the CPU in the BIOS.
This holds true for newer computers as well, but you can usually use
Intel\'s Extreme Tuning
Utility
(XTU) or AMD\'s Wattman if you want to do it in Windows itself. This
method, while probably safer, is not the best method to overclock.
Assuming that you have a multiplier-unlocked CPU, head on to the BIOS,
look for a CPU-modifying option within the BIOS (it depends between
manufacturers), and raise the All-Core multiplier by a notch(For
example, if you have a 3.5 GHz chip with a multiplier of 35x, raise it
to 36x).
Then boot back into Windows and then run a stress tool like
Prime95. It is a good idea to run it for
some time (like an hour) but not for too long as you may end up damaging
your CPU instead. Keep a watchful eye at the CPU temperatures; you
should not go over 85C. If you do, you may need a better CPU cooler. Do
NOT use the stock cooler if you are overclocking!
If it passes, go back into the BIOS and increase the multiplier again by
a notch. If it fails, return back to the BIOS and then raise the CPU
voltage slightly. Then repeat the stress test.
Continue this process till
1. The stress test has failed and you\'ve applied enough voltage, or
2. The CPU is running too hot.
3. The CPU is throttling (reducing speeds)
It is important that you do not apply too much CPU voltage as you may
end up damaging the CPU. Also remember to keep any adaptive voltage
settings on, as they reduce the voltage and prolong the life of your CPU
when it is in idle.
### Video card
Two different parts of a video card may be overclocked[^1], the GPU
(Graphics Processing Unit) and the RAM. In addition, disabled pipelines
on a video card may also be enabled through third-party drivers,
third-party software, or direct hardware modifications depending on your
video card type. Overclocking a video card is usually done through
third-party or proprietary software.
Recent AMD proprietary Catalyst drivers feature an interface called
Overdrive that allows for dynamic GPU frequency scaling based on its
temperature and load. Increase the load, the clock rate increases for
performance, but it\'s balanced against the increasing temperature.
Sufficient for simple increases in overall performance, this doesn\'t
allow for the best performance increase which requires overclocking the
memory. For that you\'ll need third-party applications or drivers.
An application example is ATITool. This program has many options,
including GPU and memory overclocking, temperature monitoring, and fan
control, allowing for a much more complete solution to overclocking ATI
based video cards. There are many third party drivers, omegadrivers.net,
for example hosts ATI and nVidia drivers as well. Both of which include
integrated overclocking and many unlocked features, including enhanced
image quality for nVidia-based cards.
nVidia users can use one of the many overclocking tools like MSI
Afterburner to overclock their GPU. Many of them also include
stress-testing tools built-in to validate the stability of the
overclock.
For Intel integrated graphics, one can overclock using Intel\'s Extreme
Tuning Utility, in much the same way as one would overclock the
processor.
The most important thing to remember about overclocking a video card is
cooling. This can\'t be stressed enough. Just as a CPU can be damaged or
have a shortened lifespan by overclocking or excessive and prolonged
heat, so can a video card. In the past year many inexpensive and easy to
install options have surfaced for cooling a video card, from adhesive
ram heatsinks which attach to un-cooled ram chips, to rather expensive
water-cooling solutions. A good midpoint (both in cost and
effectiveness) solution is to purchase and install a direct exhaust,
\"sandwich\" cooling solution. Direct exhaust means all air from the
cooling fan is blown across the video card and directly out of the
computer case, usually using the open PCI slot below the AGP (or PCIe)
slot. This allows for substantially lower GPU temperatures.
A sandwich cooler is two aluminum or copper heatsinks, shape formed for
a particular video card, that \"sandwiches\" the video card in between
the two and are usually connected by some kind of copper heat pipe which
allows for the hotter side to convey heat to the cooler side for
dissipation. The GPU should never surpass 80 degrees Celsius for optimal
performance and to avoid damaging the card. Most of the latest video
cards are rated to go up to 90 C, but this is NOT recommended by anyone.
The optimal temperature for a video card is 55 - 70 C for the card
itself (the GPU\'s temperature differs depending on which you have,) but
the lower you can get it, the better.
It is also possible to use software to change the fan speed on certain
cards. Changing the fan to run at full speed can cool the card better,
dependening on your card and the speed of the fan in the first place.
Software such as Rivatuner can be used for
Nvidia based cards.
## Getting the few extra MHz out of a chip
!Some people treat overclocking as a sort of sport, and try to get
ludicrous performance out of parts. While using liquid nitrogen for
cooling is fun, it\'s not very practical for day to day
use.
### Cooling
When increasing the speed of any computer components you are making the
components work harder and by doing so they output more heat. Heat can
cause system instability so cooling is necessary to help keep your
components stable at higher speeds. Without good cooling you could harm
or shorten the life of your system. CPU temperature can usually be
checked from within the BIOS. However, these are inaccurate as your CPU
is under almost no load in the bios. SiSoftware Sandra may be used
within Windows to check temperature. This should be done when your CPU
has been under a heavy load for a while for optimum results.
There are three types of cooling that are generally accepted for
overclocking: Air, water and peltier.
With both air cooling and water cooling some type of transfer material
is needed to move the energy away from the sensitive electronics. The
device used for this purpose is a heatsink. The two most popular
heatsink materials are Aluminum and Copper. The heatsink that is stock
on factory computers by major manufacturers (Dell, HP, Acer, Etc) is
usually made of aluminum, which has satisfactory heat transfer
characteristics. However when overclocking more heat is being produced
from the increase in power consumption. In order to obtain lower
temperatures a material with better heat transfer properties is
important and copper is the material that offers the best ratio of
price/performance.
### Power
Chips at higher speeds may need more power. Raising the vcore voltage on
a CPU might enable it to go at slightly faster speeds but by doing so
you add a lot more heat output from the CPU. The V~core~ of a processor
is the voltage at which a chip is set to run at with the stock speed.
This voltage may need to be changed when the multiplier is raised
because otherwise the transistors in the chip won\'t switch fast
enough - transistors switch faster the higher the supply voltage. If
there is not enough voltage then the chip will become unstable and crash
randomly. Good cooling is needed to keep the system stable at higher
speeds. Raising the vcore too much may harm or shorten the life of your
system. Raising the vcore can also greatly affect the stability of the
system. This is where a high quality PSU will come into play. While many
cheap, no-name brand PSU\'s will crash and die with more V~core~, a good
quality one will live to serve you for a long time. For most modern
Intel and AMD processors, it is strongly recommended not to exceed 1.45V
on the vcore, however even 1.45V can significantly reduce the lifetime
of a CPU.
Note: increasing the speed via multiplier without changing the voltage
will also increase heat output, but not as much as when also increasing
voltage. Having said that, increasing the multiplier without adjusting
the voltage may make your system unstable (undervolt).
## Undervolting
{width="800"}
The above screenshot shows the process of undervolting in ThrottleStop -
click (1) and adjust (2). -50 mV to -100 mV is around the tolerance
range of most laptops.
Instead of raising V~core~ during overclocking, you could also simply
*reduce* V~core~ and stay at stock clock speed. This is possible because
modern CPU\'s are ususually set at a voltage above the voltage it really
requires so as to account for manufacturing variances. The advantage to
undervolting include
1. Lower heat output and power consumption
2. Potentially higher performance (since the CPU can boost for a longer
period and will hit the TDP limit less often)
3. It works with any CPU; an overclockable CPU is not required.
Laptops can benefit the most from undervolting; their thin chassis means
that power and temperatures play a greater role than in a desktop.
Similar to overclocking, one can undervolt the CPU using tools like
Intel Extreme Tuning Utility, ThrottleStop or in the BIOS. For Ryzen
Mobile CPUs, an open-source tool AATU (AMD APU Tuning Utility) can be
downloaded
here,
which would especially help if your laptop is throttling due to STAPM
(skin temperature) issues.
Remember that just like when overclocking, you should start slowly and
also test the stability of the CPU undervolt (eg: by running Prime95).
## References
```{=html}
<references />
```
## External links
- Introduction to Overclocking Guide for
Beginners
by Vito Cassisi
- Overclocking the NVIDIA GeForce Video
Card
by Olin Coles
- PC Performance
Tips
Mostly Video Guides To Speeding Up And Overclocking Your PC.
- BIOS settings
- Book on BIOS optimization for
PCs
- Overclocking guide for Centrino
notebooks
- BlazingPC.com
- 3 methods to Overclocking Your
Computer
- How to Lower Temperatures, Stop Throttling, and Increase Battery
Life: The ThrottleStop
Guide
[^1]:
|
# How To Assemble A Desktop PC/Silencing
In contrast to overclocking, you may prefer to silence your computer.
Some high-performance PCs are very loud indeed, and it is possible to
reduce the noise dramatically. The main sources of noise are: Fans (CPU,
case, power supply, motherboard, Graphics card), and Hard disks. While
total silence in a PC is possible, it is far cheaper and easier to aim
for something \'virtually inaudible\'.
Note that quieter computers sometimes run slightly hotter, especially in
small form factor (SFF) systems, so you need to monitor carefully what
you do. Usually you can\'t overclock and silence at the same time
(although it is possible with the right CPU and cooling techniques).
Sometimes CPUs (and even GPUs) are *underclocked* and/or *undervolted*
to achieve greater silence at the expense of performance.
Designing a powerful and quiet machine requires careful consideration in
selecting components, but need not be much more expensive than a normal,
loud PC. If you are looking to quiet an existing PC, find the
*offending* component that produces the loudest or most irritating noise
and replace it first, then work down from there.
Another way to do this is by undervolting; see
here to find out
more about it.
## Fans
!An operating fan with red
LEDs.
In general, large diameter (120 mm), high quality fans are much quieter
than small diameter ones, because they can move the same amount of air
as smaller (80mm or 92mm) fans, but at slower speeds.
Temperature-regulated fans are also much quieter, as they will
automatically spin at a reduced speed when your computer is not in heavy
use. Wire mesh grills (or no grill at all) allow better airflow than the
drilled holes used in many cases.
CPU
: Modern CPUs can generate *a lot* of heat in a very small area:
sometimes as much as 100-watt lightbulb! For the vast majority of
processors, a dedicated fan will be a necessity. There are some,
like VIA processors, that require only a heat sink, but you will not
find passively cooled CPUs at nearly the same speeds allowed by
active cooling. However, for modern computers, CPUs are not the
limiting component for speed in daily tasks, so unless you do
demanding 3D gaming or video editing, then a passively cooled
processor may be just for you. They would also be very attractive in
media-center PCs, or other specialized applications where computer
noise would be more noticeable.
: The noisiest fan is usually the CPU fan: the Intel-supplied
fan-heatsinks are particularly loud, although they do provide good
cooling. Some BIOSs allow you to slow the CPU fan down automatically
when it is not too hot - if this option is available, turn it on.
Also, you can get 3rd party coolers, which are designed to be less
noisy: for example, those made by
Zalman.
```{=html}
<!-- -->
```
Power Supply (PSU) : Noisy power-supplies simply have to be replaced with quieter ones. Consider selecting a power supply that intelligently throttles fan speed based on load, or an altogether fanless model, though those can be hard to find depending on the wattage you need. As a compromise, some power supplies will stay silent as long as it is under light load.
```{=html}
<!-- -->
```
Case Fans : Case fans can be slowed down by using fan-speed controllers, or resistors (but beware of insufficient cooling). Also, they can be replaced with higher quality (ball bearing) or (sometimes) larger fans, both of which will make less noise.
```{=html}
<!-- -->
```
Video Card and Motherboard Chipset
: A graphics card with active fan-cooling is very common in gamer PCs.
Since 2004, most of these cards have a built in fan-speed
controller, so the fan will slow down if 3D acceleration is not
needed.`<ref>`{=html}
Casey Labine. \"How to Adjust a Graphics Card Fan
Speed\"
```{=html}
</ref>
```
As you will lose warranty coverage if you change the fan, you should
check (through reviews) if the card is a noisy one. If you insist on
exchanging the cooling device, be sure the card is compatible with the
new fan. Motherboard and lower-end video card fans can often be replaced
with a passive heatsink.
Many systems only have fan-speed controllers for the CPU and for the
graphics card. Some people make the other fans quieter by undervolting
them: running the 12 V fan on 9 V or 7 V or 5 V,[^1][^2][^3] or adding a
series resistor to the fan cable.[^4]
Dust and debris can accumulate on fan blades in a short period of time.
Dust on PC components acts as an insulator, trapping in heat and forcing
your fans to spin at higher speeds to keep everything cool. Keep your PC
clean to reduce noise and increase efficiency.
## Water cooling
!A water cooled
computer{width="250"}
An efficient, if expensive way to eliminate the need for most fans in
ones computer system is the implementation of water cooling devices.
Water cooling kits are available for beginners, and additional
components or \"water blocks\" can be added to the system, allowing
virtually any system needing cooling to be put \"on water\".
Most water cooling systems are not fanless as the radiator component
still needs to spread the heat. There are fanless solutions but they
need to be placed exterior of the PC case making the computer less
transportable. [^5] [^6]
Other cooling fluids are possible in a sealed system, although plain
water is generally preferred because it has higher heat
capacity and thermal
conductivity than oil, and
it is easier to clean up if a leak ever occurs: turn off the computer,
shake off most of the water, and use a hair dryer to evaporate the rest
of the water.
Keep in mind, however, that water and electronics don\'t mix, and that
leaks could cause components to short out, seriously damaging them. Be
sure you\'re willing to risk this and thoroughly check for leaks before
providing power to the system components. If possible, activate the
water pump(s) for 10-15 minutes and check potential trouble spots.
## Full immersion cooling
!An example of an immersion cooling
setup.
Some people are experimenting with cooling personal computers by
immersing them almost completely in non-conductive liquids such as
transformer oil and flourinert.
### Oil cooling
Transformer oil has been used to
cool electrical equipment for decades.
Some people are experimenting with oil cooling personal computers. Since
oil is non-conductive, the motherboard and graphics card and power
supply (but not the hard drives or optical drives!) will continue to run
submerged in a \"fishtank\" filled with oil. Some people prefer
colorless transparent \"mineral oil\" or cooking oil, but Frank Völkel
recommends motor
oil1.
Oil cooling is lower cost than water cooling, because it doesn\'t
require water-tight \"blocks\" or hoses. Some people leave the fans
running on the motherboard and power supply to \"stir\" the oil. Other
people remove all the fans and add a (submerged) pump to \"blow\" a
stream of oil onto the CPU hot spot. Some CPUs, if given a big enough
metal heat sink, can be adequately cooled by passive convection currents
in the oil (and the large surface area of the oil-to-case and
case-to-air), without any fans or pumps.
If any cable (the hard drive ribbon cable, the power cable, the monitor
cable, etc.) exits the case below the oil line, it must have an
oil-tight exit seal \-- consider making all cables exit the top of the
case instead.
### Low boiling point chemicals
Another point of recent experimentation has been Novec
1230 (trademarked and produced by 3M),
which has a boiling point of . This
means that as the liquid touches a part above that temperature, it
evaporates immediately. It then condenses at the top of the tank, only
to drip down and convect through the tank again. CPUs usually have no
problem running in Novec 1230 without any heatsink at all. The force of
convection is enough to drive the liquid around the tank, so it does not
need any fans
either23.
Immersion in other cooling fluids has been attempted, such as
fluorinert or liquid nitrogen,
however they are generally not used because of the costs involved in the
equipment and the liquid nitrogen [^7][^8].[^9][^10][^11]
## Storage
### Solid State Disk
Solid state disks have no moving parts, and thus don\'t make audible
noise. When trying to build a totally silent system, consider only using
SSDs for your storage.
### Hard Drive
A \'resting\' hard disk is generally quite quiet compared with any fan,
but increases dramatically when it starts \'churning\', as when you open
or save a file or perform a virus scan. There will usually be a
compromise between performance and sound, so opting for a slower RPM or
smaller capacity single-platter HDD may be necessary to reach very quiet
levels. Also, 2.5\" notebook drives can be much quieter than 3.5\"
desktop drive, but come in smaller capacities.
After selecting a quiet drive, or if you want to reduce the noise coming
from a loud drive, look into mounting options. Hard drives are usually
mounted with four screws attaching them directly to the case, providing
very stable support, some heat dissipation and a lot of direct
transmission of HDD vibrations to the case. Reducing this transmission
to almost nothing is possible, though it is not always easy.
The best noise reductions come from suspending the hard drive with
elastic, providing no direct route for sound transmission to the case.
You can make your own from elastic in a fabric store, or buy kits that
provide materials and instructions. (Rubber bands are not recommended,
as they will become weak from the HDD heat and oxidation and snap.)
Foam can be used to dampen vibrations, but may trap more heat than is
safe. Resting the hard drive on the floor of your case on a bed of foam
can be very effective at reducing noise.
Using silicone or rubber screws instead of metal mounting screws will
give you marginal sound reduction, but is easiest and cheapest to
implement. You also won\'t have to worry about shifting of the HDD if
you move your computer.
## Other
- Steel cases are quieter than aluminum ones, because the denser
material vibrates less easily.`<ref>`{=html}
Mike Chin. Silent PC Review: \"Case Basics &
Recommendations\"
```{=html}
</ref>
```
- Quiet cases are available, containing noise-damping acoustic foam.
There are 3rd-party acoustic foams you may decide to add as well.
- Experiment with rubber or foam washers when mounting drives and
fans. These will dampen any vibration these devices cause.
- Keep cables tied up and neat. Not only will this keep them clear of
fans (which could quickly cause dangerous heat build-up), but the
reduced impedance of airflow throughout your case will make things
cooler. Flat, ribbon-shaped cables can safely be folded up to a
fraction of their original width.
- Make sure your case has rubber or foam feet if it rests on a hard
surface. Placing it on carpeting will also reduce vibrations.
- Underclocking will reduce system performance, but you can also then
reduce the CPU voltage, and power consumption as a whole. Noisy fans
may then also be operated at reduced speed or eliminated altogether,
as the computer will produce less heat. The converse of the
diminishing-returns law for overclocking is that underclocking can
prove surprisingly effective.
- The really obvious, but surprisingly effective: keep the computer
under your desk or even in a closed cupboard, rather than under or
beside your monitor.
NOTE: No matter what technique you use to quiet the machine, be sure to
keep a steady supply of fresh air over all components. Don\'t put your
machine in a closed cupboard unless you are sure heat will not be an
issue. If you use acoustic foams, be sure they aren\'t acting as
insulators, too - and keeping components hot.
## See also
- Noise from cooling
fans
## Further reading
## External links
- Silent PC review
- Microchip AN771: Suppressing Acoustic Noise in PWM Fan Speed
Control
Systems
- \"The Buzz on Quieter
Computers\"
article by Daniel Greenberg in The Washington Post, September 3,
2006.
- Technorati \"silent PC\" blog
posts
- \"A Plea for Silence\" by Loyd Case
(ExtremeTech)
- \"How to Quiet Your PC\" by Jason Cross
(ExtremeTech)
- \"a diskless, fanless, completely silent
PC\"
-
- Koolu: a fanless PC that runs Linux; Koolu
wiki
- \"Building a Silent PC: My Quest for Quiet\" by Terry
Gray
- the oil-cooled computer
wiki (in German) and
oil-cooled computer discussion
forum (in
English)
- \"Quiet PCs... shhh\" by Thomas Ricker (oil-cooled
computer)
- \"Aquarium Full of Oil For PC Cooling\" on
slashdot
- \"Want a Cool and Quiet PC? Dunk it in Oil\" on
slashdot
- \"Xoxide Resource Center: Building a Quiet
Computer
- fit-PC, a tiny quiet PC
- \"Project:
Passive\"
by Ville \'Willek\' Kyrö, a PC that uses no fans, only completely
passive cooling.
- \"Tiny, sub-\$100 PC runs Puppy
Linux\":
a PC with no moving parts.
- \"0 dBA ion cooled
computer\":
a PC with no moving parts; blows air using \"ion wind\".
[^1]: \"How to: Silence My Fans By
Undervolting?\"
[^2]: Silent PC Review: \"Stock Fan
Measurements\"
[^3]: Gabriel Torres. \"How to Create a Three-Speed Fan Control without
Spending a
Dime\".
[^4]: Igor Wallossek. Tom\'s Hardware: \"Case Fans: Speed
Control\"
[^5]: \"Silent Convective Water Cooled
PC\"
[^6]: \"Design and Performance Evaluation of a Compact
Thermosyphon\"
by Aniruddha Pal, Yogendra Joshi, Monem H. Beitelmal, Chandrakant D.
Patel, Todd Wenger, 2002
[^7]: 4
[^8]: 5
[^9]: Tom\'s Hardware: 5 GHz
project
[^10]: Server help: Liquid Nitrogen
Project and
Hard forum: Liquid Nitrogen
Project
[^11]: Wikipedia: computer cooling#Liquid
nitrogen
|
# How To Assemble A Desktop PC/Conclusion
If you\'re serious you've probably at least glanced over this book as
you considered building your own computer, and I hope it has inspired
you to go ahead with that project. Throughout we've tried to steer you
clear of some of the pitfalls and alert you to some of the safety issues
involved, and in so doing, we have undoubtedly overemphasized the
dangers and difficulty. In sooth, it's pretty hard to hurt yourself
building a computer and most people get through their first build
without burning up any parts. With a little planning, anyone who can use
a screwdriver can build a computer.
The computer you build will always mean a little bit more to you than
one you buy, not least because you designed it yourself and will no
doubt be upgrading it from time to time for years to come. You may find
a little smile of satisfaction creeping onto your face each time you hit
the power button, and I think you'll find that smile is an ample return
for your time and effort.
Lastly, if you go through with it and build your own PC, you're bound to
run into something we\'ve missed here; a problem we didn't anticipate,
something we forgot to mention, or something that has changed recently.
If you do, please come back here and add to or change this book. You
don't have to know everything to contribute, just one thing that's true.
If this guide has helped you at all, think of it as payback.
|
# XML - Managing Data Exchange/A single entity
------------------------------------------------------------------------
+-------------------------------------------------------+
| **Learning objectives** |
| |
| - introduce XML documents, schemas, and stylesheets |
| - describe and create an XML document |
| - describe and create an XML schema |
| - describe and create an XML stylesheet |
+-------------------------------------------------------+
| |
+-------------------------------------------------------+
## Introduction
In this chapter, we start to practice working with XML using XML
documents, schemas, and stylesheets. An XML document organizes data and
information in a structured, hierarchical format. An XML schema provides
standards and rules for the structure of a given XML document. An XML
schema also enables data transfer. An XSL (XML stylesheet) allows unique
presentations of the material found within an XML document.
In the first chapter, *Introduction to XML*, you learned what XML is,
why it is useful, and how it is used. So, now you want to create your
very own XML documents. In this chapter, we will show you the basic
components used to create an XML document. This chapter is the
foundation for all subsequent chapters\--it is a little lengthy, but
don\'t be intimidated. We will take you through the fundamentals of XML
documents.
This chapter is divided into three parts:
- XML Document
- XML Schema
- XML Stylesheets (XSL)
As you learned in the previous chapter, the XML Schema and Stylesheet
are essentially specialized XML Documents. Within each of these three
parts we will examine the layout and components required to create the
document. There are links at the end of the XML document, schema, and
stylesheet sections that show you how to create the documents using an
XML editor. At the bottom of the page there is a link to Exercises for
this chapter and a link to the Answers.
The first thing you will need before starting to create XML documents is
a problem\--something you want to solve by using XML to store and share
data or information. You need some entity you can collect information
about and then access in a variety of formats. So, we created one for
you.
To develop an XML document and schema, start with a data model depicting
the reality of the actual data that is exchanged. Once a high fidelity
model has been created, the data model can be readily converted to an
XML document and schema. In this chapter, we start with a very simple
situation and in successive chapters extend the complexity to teach you
more features of XML.
Our starting point is a single entity, CITY, which is shown in the
following figure. While our focus is on this single entity, to map CITY
to an XML schema, we need to have an entity that contains CITY. In this
case, we have created TOURGUIDE. Think of a TOURGUIDE as containing many
cities, and in this case TOURGUIDE has no attributes nor an identifier.
It is just a container for data about cities.
**Exhibit 1: Data model - Tourguide** 
:
:
:
## XML document
An XML document is a file containing XML code and syntax. XML documents
have an .xml file extension.
We will examine the features & components of the XML document.
- Prologue (XML Declaration)
- Elements
- Attributes
- Rules to follow
- Well-formed & Valid XML documents
Below is a sample XML document using our TourGuide model. We will refer
to it as we describe the parts of an XML document.
**Exhibit 2: XML document for city entity**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<tourGuide xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:noNamespaceSchemaLocation='city.xsd'>
<city>
<cityName>Belmopan</cityName>
<adminUnit>Cayo</adminUnit>
<country>Belize</country>
<population>11100</population>
<area>5</area>
<elevation>130</elevation>
<longitude>88.44</longitude>
<latitude>17.27</latitude>
<description>Belmopan is the capital of Belize</description>
<history>Belmopan was established following the devastation of the
former capital, Belize City, by Hurricane Hattie in 1965. High
ground and open space influenced the choice and ground-breaking
began in 1966. By 1970 most government offices and operations had
already moved to the new location.
</history>
</city>
<city>
<cityName>Kuala Lumpur</cityName>
<adminUnit>Selangor</adminUnit>
<country>Malaysia</country>
<population>1448600</population>
<area>243</area>
<elevation>111</elevation>
<longitude>101.71</longitude>
<latitude>3.16</latitude>
<description>Kuala Lumpur is the capital of Malaysia and the largest
city in the nation</description>
<history>The city was founded in 1857 by Chinese tin miners and
preceded Klang. In 1880 the British government transferred their
headquarters from Klang to Kuala Lumpur, and in 1896 it became the
capital of Malaysia.
</history>
</city>
<city>
<cityName>Winnipeg</cityName>
<adminUnit>St. Boniface</adminUnit>
<country>Canada</country>
<population>618512</population>
<area>124</area>
<elevation>40</elevation>
<longitude>97.14</longitude>
<latitude>49.54</latitude>
<description>Winnipeg has two seasons. Winter and Construction.</description>
<history>The city was founded by people at the forks (Fort Garry)
trading in pelts with the Hudson Bay Company. Ironically,
The Bay was bought by America.
</history>
</city>
</tourGuide>
```
### Prologue (XML declaration)
The XML document starts off with the prologue. The prologue informs both
a reader and the computer of certain specifications that make the
document XML compliant. The first line is the XML declaration (and the
only line in this basic XML document).
**Exhibit 3: XML document - prologue**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
```
**xml** = this is an XML document\
**version=\"1.0\"** = the XML version (XML 1.0 is the
W3C-recommended version)\
**encoding=\"UTF-8\"** = the character encoding used in the
document - UTF 8 corresponds to 8-bit encoded Unicode characters (i.e.
the standard way to encode international documents) -
Unicode provides a unique number for every
character.\
Another potential attribute of the XML declaration:\
**standalone=\"yes\"** = the dependency of the document (\'yes\'
indicates that the document does not require another document to
complete content)
### Elements
The majority of what you see in the XML document consists of XML
**elements**. Elements are identified by their **tags** that **open**
with \< or \</ and **close** with \> or /\>. The **start tag** looks
like this: `<element attribute="value">`{=html}, with a left angle
bracket (\<) followed by the **element type name**, optional
**attributes**, and finally a right angle bracket (\>). The **end tag**
looks like this: `</element>`{=html}, similar to the start tag, but with
a slash (/) between the left angle bracket and the element type name,
and no attributes.
When there\'s nothing between a start tag and an end tag, XML allows you
to combine them into an **empty element tag**, which can include
everything a start tag can: `<img src="Belize.gif" />`{=html}. This one
tag must be closed with a slash and right angle bracket (/\>), so that
it can be distinguished from a start tag.
The XML document is designed around a major theme, an umbrella concept
covering all other items and subjects; this theme is analyzed to
determine its component parts, creating categories and subcategories.
The major theme and its component parts are described by elements. In
our sample XML document, \'tourGuide\' is the major theme; \'city\' is a
category; \'population\' is a subcategory of \'city\'; and the hierarchy
may be carried even further: \'males\' and \'females\' could be
subcategories of \'population\'. Elements follow several rules of syntax
that will be described in the Rules to Follow section.
We left out the attributes within the `<tourGuide>`{=html} start tag ---
that part will be explained in the XML Schema section.
**Exhibit 4: Elements of the city entity XML document**
``` XML
<tourGuide>
<city>
<cityName>Belmopan</cityName>
<adminUnit>Cayo</adminUnit>
<country>Belize</country>
<population>11100</population>
<area>5</area>
<elevation>130</elevation>
<longitude>88.44</longitude>
<latitude>17.27</latitude>
<description>Belmopan is the capital of Belize</description>
<history>Belmopan was established following the devastation of the
former capital, Belize City, by Hurricane Hattie in 1965. High
ground and open space influenced the choice and ground-breaking
began in 1966. By 1970 most government offices and operations had
already moved to the new location.
</history>
</city>
</tourGuide>
```
#### Element hierarchy
- **root element** - This is the XML document\'s major theme
element. Every document must have exactly one and only one root
element. All other elements are contained within this one root
element. The root element follows the XML declaration. In our
example, `<tourGuide>`{=html} is the root element.
```{=html}
<!-- -->
```
- **parent element** - This is any element that contains other
elements, the child elements. In our example, `<city>`{=html} is a
parent element.
```{=html}
<!-- -->
```
- **child element** - This is any element that is contained within
another element, the parent element. In our example,
`<population>`{=html} is a child element of `<city>`{=html}.
```{=html}
<!-- -->
```
- **sibling element** - These are elements that share the same
parent element. In our example, `<cityName>`{=html},
`<adminUnit>`{=html}, `<country>`{=html}, `<population>`{=html},
`<area>`{=html}, `<elevation>`{=html}, `<longitude>`{=html},
`<latitude>`{=html}, `<description>`{=html}, and `<history>`{=html}
are all sibling elements.
\
### Attributes
Attributes aid in modifying the content of a given element by providing
additional or required information. They are contained within the
element\'s opening tag. In our sample XML document code we could have
taken advantage of attributes to specify the unit of measure used to
determine the area and the elevation (it could be feet, yards, meters,
kilometers, etc.); in this case, we could have called the attribute
\'measureUnit\' and defined it within the opening tag of \'area\' and
\'elevation\'.
` <adminUnit `**`class="state"`**`>Cayo``</adminUnit>`{=html}
` <adminUnit `**`class="region"`**`>Selangor``</adminUnit>`{=html}
The above attribute example can also be written as:
1\. using child elements
``` XML
<adminUnit>
<class>state</class>
<name>Cayo</name>
</adminUnit>
```
``` XML
<adminUnit>
<class>region</class>
<name>Selangor</name>
</adminUnit>
```
2\. using an empty element
` ``<adminUnit class="state" name="Cayo" />`{=html}
` ``<adminUnit class="region" name="Selangor" />`{=html}
Attributes can be used to:
- provide more information that is not defined in the data
- define a characteristic of the element (size, color, style)
- ensure the inclusion of information about an element in all
instances
Attributes can, however, be a bit more difficult to manipulate and they
have some constraints. Consider using a child element if you need more
freedom.
### Rules to follow
These rules are designed to aid the computer reading your XML document.
- The first line of an XML document must be the XML declaration (the
prologue).
```{=html}
<!-- -->
```
- The main theme of the XML document is established in the root
element and all other elements must be contained within the opening
and closing tags of this root element.
```{=html}
<!-- -->
```
- Every element must have an opening tag and a closing tag - **no
exceptions**\
(e.g. `<element>`{=html}data stuff`</element>`{=html}).
- Tags must be nested in a particular order
=\> the parent element\'s opening and closing tags must contain all of
its child elements\' tags; in this way, you close first the tag that was
opened last:
`<parentElement>`{=html}\
` ``<childElement1>`{=html}`data``</childElement1>`{=html}\
` ``<childElement2>`{=html}\
` ``<subChildElementA>`{=html}`data``</subChildElementA>`{=html}\
` ``<subChildElementB>`{=html}`data``</subChildElementB>`{=html}\
` ``</childElement2>`{=html}\
` ``<childElement3>`{=html}`data``</childElement3>`{=html}\
`</parentElement>`{=html}
- Attribute values should have quotation marks around them and no
spaces.
```{=html}
<!-- -->
```
- Empty tags or empty elements must have a space and a slash (/) at
the end of the tag.
```{=html}
<!-- -->
```
- Comments in the XML language begin with \"\<!\--\" and end with
\"\--\>\".
#### XML Element Naming Convention
Any name can be used but the idea is to make names meaningful to those
who might read the document.
- XML elements may only start with either a letter or an underscore
character.
```{=html}
<!-- -->
```
- The name must not start with the string \"xml\" which is reserved
for the XML specification.
```{=html}
<!-- -->
```
- The name may not contain spaces.
```{=html}
<!-- -->
```
- The \":\" should not be used in element names because it is reserved
to be used for namespaces (This will be covered in more detail in a
later chapter).
```{=html}
<!-- -->
```
- The name may contain a mixture of letters, numbers, or other
characters.
XML documents often have a corresponding database. The database will
contain fields which correspond to elements in the XML document. A good
practice is to use the naming rules of your database for the elements in
the XML documents.
### DTD (Document Type Definition) Validation - Simple Example
##### Simple Internal DTD
``` XML
<?xml version="1.0"?>
<!DOCTYPE cdCollection [
<!ELEMENT cdCollection (cd)>
<!ELEMENT cd (title, artist, year)>
<!ELEMENT title (#PCDATA)>
<!ELEMENT artist (#PCDATA)>
<!ELEMENT year (#PCDATA)>
]>
<cdCollection>
<cd>
<title>Dark Side of the Moon</title>
<artist>Pink Floyd</artist>
<year>1973</year>
</cd>
</cdCollection>
```
Every element that will be used MUST be included in the DTD. Don't
forget to include the root element, even though you have already
specified it at the beginning of the DTD. You must specify it again, in
an \<!ELEMENT\> tag. \<!ELEMENT cdCollection (cd)\> The root element,
`<cdCollection>`{=html}, contains all the other elements of the
document, but only one direct child element: `<cd>`{=html}. Therefore,
you need to specify the child element (only direct child elements need
to be specified) in the parentheses. \<!ELEMENT cd (title, artist,
year)\> With this line, we define the `<cd>`{=html} element. Note that
this element contains the child elements
```{=html}
<title>
```
, `<artist>`{=html}, and `<year>`{=html}. These are spelled out in a
particular order. This order must be followed when creating the XML
document. If you change the order of the elements (with this particular
DTD), the document won't validate. \<!ELEMENT title (#PCDATA)\> The
remaining three tags,
```{=html}
<title>
```
, `<artist>`{=html}, and `<year>`{=html} don't actually contain other
tags. They do however contain some text that needs to be parsed. You may
remember from an earlier lecture that this data is called Parsed
Character Data, or #PCDATA. Therefore, #PCDATA is specified in the
parentheses. So this simple DTD outlines exactly what you see here in
the XML file. Nothing can be added or taken away, as long as we stick to
this DTD. The only thing you can change is the #PCDATA text part between
the tags.
##### Adding complexity
There may be times when you will want to put more than just character
data, or more than just child elements into a particular element. This
is referred to as mixed content. For example, let's say you want to be
able to put character data OR a child element, such as the \<b\> tag
into a `<description>`{=html} element:
` <!ELEMENT description (#PCDATA | b | i )*>`
This particular arrangement allows us to use PCDATA, the \<b\> tag, or
the \<i\> tag all at once. One particular caveat though, is that if you
are going to mix PCDATA and other elements, the grouping must be
followed by the asterisk (\*) suffix. This declaration allows us to now
add the following to the XML document (after defining the individual
elements of course)
``` XML
<cd>
<title>Love. Angel. Music. Baby</title>
<artist>Gwen Stefani</artist>
<year>2004</year>
<genre>pop</genre>
<description>
This is a great album from former
<nowiki><i>No Doubt</i> singer <b>Gwen Stephani</b>.</nowiki>
</description>
</cd>
```
With attributes this is done a little differently than with elements.
Please see following example:
``` XML
<cd remaster_date=”1992”>
<title>Dark Side of the Moon</title>
<artist>Pink Floyd</artist>
<year>1973</year>
</cd>
```
In order for this to validate, it must be specified in the DTD.
Attribute content models are specified with:
` <!ATTLIST element_name attribute_name attribute_type default_value>`
Let's use this to validate our CD example:
` <!ATTLIST cd remaster_date CDATA #IMPLIED>`
##### Choices
` <ATTLIST person gender (male|female) “male”>`
##### Grouping Attributes for an Element
If a particular element is to have many different attributes, group them
together like so:
`<!ATTLIST car horn CDATA #REQUIRED`\
` seats CDATA #REQUIRED`\
` steeringwheel CDATA #REQUIRED`\
` price CDATA #IMPLIED>`
##### Adding STATIC validation, for items that must have a certain value
`<!ATTLIST classList classNumber CDATA #IMPLIED`\
` building (UWINNIPEG_DCE|UWINNIPEG_MAIN) "UWINNIPEG_MAIN"`\
` originalDeveloper CDATA #FIXED "Khal Shariff">`
#### Suffixes
= So what happens with our last example with the CD collection, when we
want to add more CDs? With the current DTD, we cannot add any more CDs
without getting an error. Try it and see. When you specify a child
element (or elements) the way we did, only one of each child element can
be used. Not very suitable for a CD collection is it? We can use
something called suffixes to add functionality to the \<!ELEMENT\> tag.
Suffixes are added to the end of the specified child element(s). There
are 3 main suffixes that can be used:
- ( No suffix ): Only 1 child can be used.
- ( + ): One or more elements can be used.
- ( \* ): Zero or more elements can be used.
- ( ? ): Zero or one element may be used.
##### Validating for multiple children with a DTD
So in the case of our CD collection XML file, we can add more CDs to the
list by adding a + suffix:
`<!ELEMENT cd_collection(cd+)>`
##### Using more internal formatting tags
Bold tags, B\'s for example are also defined in the DTD as elements,
that are optional like thus:
`<ELEMENT notes (#PCDATA | b | i)*>`\
` <!ELEMENT b (#PCDATA)*>`\
` <!ELEMENT i (#PCDATA)*>`\
`]>`
\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_
`<classList classNumber="303" building="UWINNIPEG_DCE" originalDeveloper="Khal Shariff">`{=html}\
` ``<student>`{=html}\
` ``<firstName>`{=html}`Kenneth`\
` ``</firstName>`{=html}\
` ``<lastName>`{=html}`Branaugh`\
` ``</lastName>`{=html}\
` ``<studentNumber>`{=html}\
` ``</studentNumber>`{=html}\
` <notes><b>Excellent </b>, Kenneth is doing well.`\
` ``</notes>`{=html}\
`etc`
+----------------------------------------------------------------------+
| ## Case Study on BMEcat |
| |
| One of the first major national projects for the use of XML as a B2B |
| exchange format was initiated by the federal association for |
| material management, purchasing and logistics (BME) in cooperation |
| with leading German companies, e.g. Bayer, BMW, SAP and Siemens. |
| They all created a standard for the exchange of product catalogues. |
| This project was named \[<http://www.bmecat.org/English/index.asp>? |
| BMEcat\]. The result of this initiative is a DTD collection for the |
| description of product catalogues and related transactions (new |
| catalogue, updating of product data and updating of prices). |
| |
| Companies operating in the electronic commerce (suppliers, |
| purchasing companies and market places) exchange increasingly large |
| amounts of data. They quickly reach their limits here by the variety |
| of data exchange formats. The BMEcat solution creates a basis for a |
| straightforward transfer of catalogue data from various data |
| formats. This lays the foundation to bringing forward the goods |
| traffic through the Internet in Germany. The use of the BMEcat |
| reduces the costs for all parties as standard interfaces can be |
| used. |
| |
| The XML-based standard BMEcat was successfully implemented in many |
| projects. Nowadays a variety of companies applies BMEcat and use it |
| for the exchange of their product catalogs in this established |
| standard. |
| |
| **A BMEcat catalogue (Version 1.2) consists of the following main |
| elements:** |
| |
| **CATALOG** This element contains the essential information of a |
| shopping catalog, e.g. language version and validity. BMEcat expects |
| exactly one language per catalog. |
| |
| **SUPPLIER** This element includes identification and address of the |
| catalog suppliers. BMEcat expects exactly one supplier per catalog. |
| |
| **BUYER** This element contains the name and address of the |
| catalogue recipient. BMEcat expects no more than one recipient per |
| catalog. |
| |
| **AGREEMENT** This element contains one or more framework agreement |
| IDs associated with the appropriate validity period. BMEcat expects |
| all prices of a catalogue belonging to the contract mentioned above. |
| |
| **CLASSIFICATION SYSTEM** This element allows the full transfer of |
| one or more classification systems, including feature definitions |
| and key words. |
| |
| **CATALOG GROUP SYSTEM** This element originates from version 1.0. |
| It is mainly used for the transfer of tree-structures which |
| facilitate the navigation of a user in the target system (Browser). |
| |
| **ARTICLE** (since 2005 PRODUCT) This element represents a product. |
| It contains a set of standard attributes. |
| |
| **ARTICLE PRICE** (since 2005 PRODUCT PRICE) This element represents |
| a price. The support of different pricing models is very powerful in |
| comparison with other exchange formats. Season prices, country |
| prices, different currencies and different validity periods, etc. |
| will be supported. |
| |
| **ARTICLE FEATURE** (since 2005 PRODUCT FEATURE) This element allows |
| the transfer of characteristic values. You can either record |
| predefined group characteristics or individual product |
| characteristics. |
| |
| **VARIANT** This element allows listing of product variants, without |
| having to duplicate them. However, the variations of BMEcat only |
| apply to individual changes in value, leading to a change of Article |
| ID. Otherwise there can't exist any dependences on other attributes |
| (especially at prices). |
| |
| **MIME** This element includes any number of additional documents |
| such as product images, data sheets, or websites. |
| |
| **ARTICLE REFERENCE** (since 2005 REFERENCE PRODUCT) This element |
| allows cross-referencing between articles within a catalogue as well |
| as between catalogues. These references may used restrictedly for |
| mapping product bundles. |
| |
| **USER DEFINED EXTENSION** This element enables transportation of |
| data at the outside the BMEcat standards. The transmitter and |
| receiver have to be coordinated. |
| |
| You can find a typical BMEcat file |
| here. |
+----------------------------------------------------------------------+
##### ONLINE Validator
GIYBF
### Well-formed and valid XML
**Well-formed XML** - An XML document that correctly abides by the
rules of XML syntax.
**Valid XML** - An XML document that adheres to the rules of an XML
schema (which we will discuss shortly). To be valid an XML document must
first be well-formed.
A Valid XML Document must be Well-formed. But, a Well-formed XML
Document might not be valid - in other words, a well-formed XML
document, that meets the criteria for XML syntax, might not meet the
criteria for the XML schema, and will therefore be invalid.
For example, think of the situation where your XML document contains the
following (for this schema):
` ``<city>`{=html}\
` ``<cityName>`{=html}`Boston``</cityName>`{=html}\
` ``<country>`{=html}`United States``</country>`{=html}\
` ``<adminUnit>`{=html}`Massachusetts``</adminUnit>`{=html}\
` :`\
` :`\
` :`\
` ``</city>`{=html}
Notice that the elements do not appear in the correct sequence according
to the schema (cityName, adminUnit, country). The XML document can be
validated (using validation software) against its declared schema -- the
validation software would then catch the out of sequence error.
------------------------------------------------------------------------
#### Using an XML Editor
Check chapter ../XML Editor/ for
instructions on how to start an XML editor. Once you have followed the
steps to get started you can copy the code in the sample XML document
and paste it into the XML editor. Then check your results. Is the XML
document well-formed? Is the XML document valid? (you will need to have
copied and pasted the schema in order to validate - we will look at
schemas next)
------------------------------------------------------------------------
## XML schema
An XML schema is an XML document. XML schemas have an .xsd file
extension.
An XML schema is used to govern the structure and content of an XML
document by providing a template for XML documents to follow in order to
be valid. It is a guide for how to structure your XML document as well
as indicating your XML document\'s components (elements and attributes -
and their relationships). An XML editor will examine an XML document to
ensure that it conforms to the specifications of the XML schema it is
written against - to ensure it is valid.
XML schemas engender confidence in data transfer. With schemas, the
receiver of data can feel confident that the data conforms to
expectations. The sender and the receiver have a mutual understanding of
what the data represent.
Because an XML schema is an XML document, you use the same language -
standard XML markup syntax - with elements and attributes specific to
schemas.
A schema defines:
- the structure of the document
- the elements
- the attributes
- the child elements
- the number of child elements
- the order of elements
- the names and contents of all elements
- the data type for each element
For more detailed information on XML schemas and reference lists of:
Common XML Schema Primitive Data Types, Summary of XML Schema Elements,
Schema Restrictions and Facets for data types, and Instance Document
Attributes, click on this wikibook link =\>
<http://en.wikibooks.org/wiki/XML_Schema>
## Schema reference
This is the part of the XML Document that references an XML Schema:
**Exhibit 5: XML document\'s schema reference**
``` XML
<tourGuide
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:noNamespaceSchemaLocation='city.xsd'>
```
This is the part we left out when we described the root element in the
basic XML document from the previous section. The additional attributes
of the root element `<tourGuide>`{=html} reference the XML schema (it is
the schemaLocation attribute).
**xmlns:xsi=\'<http://www.w3.org/2001/XMLSchema-instance>\'** -
references the W3C Schema-instance namespace\
**xsi:noNamespaceSchemaLocation=\'city.xsd\'** - references the XML
schema document (city.xsd)
### Schema document
Below is a sample XML schema using our TourGuide model. We will refer to
it as we describe the parts of an XML schema.
**Exhibit 6: XML schema document for city entity**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="unqualified">
<xsd:element name="tourGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="city" type="cityDetails" minOccurs = "1" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="cityDetails">
<xsd:sequence>
<xsd:element name="cityName" type="xsd:string"/>
<xsd:element name="adminUnit" type="xsd:string"/>
<xsd:element name="country" type="xsd:string"/>
<xsd:element name="population" type="xsd:integer"/>
<xsd:element name="area" type="xsd:integer"/>
<xsd:element name="elevation" type="xsd:integer"/>
<xsd:element name="longitude" type="xsd:decimal"/>
<xsd:element name="latitude" type="xsd:decimal"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="history" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
<!--
Note: Latitude and Longitude are decimal data types.
The conversion is from the usual form (e.g., 50º 17' 35")
to a decimal by using the formula degrees+min/60+secs/3600.
-->
```
#### Prolog
Remember that the XML schema is essentially an XML document and
therefore must begin with the prolog, which in the case of a schema
includes:
- the XML declaration
- the schema element declaration
\
The XML declaration:
``` XML
<?xml version="1.0" encoding="UTF-8"?>
```
The schema element declaration:
``` XML
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
```
The **schema element** is similar to a root element - it contains all
other elements in the schema.
Attributes of the schema element include:
**xmlns** - XML NameSpace - the URL for the site that describes the
XML elements and data types used in the schema.
You can find more about namespaces here =\>
../Namespace/.
**xmlns:xsd** - All the elements and attributes with the \'xsd\'
prefix adhere to the vocabulary designated in the given namespace.
**elementFormDefault** - elements from the target namespace are either
required or not required to be qualified with the namespace prefix. This
is mostly useful when more than one namespace is referenced. In this
case, \'elementFormDefault\' must be *qualified*, because you must
indicate which namespace you are using for each element. If you are
referencing only one namespace, then \'elementFormDefault\' can be
*unqualified*. Perhaps, using *qualified* as the default is most
prudent, this way you do not accidentally forget to indicate which
namespace you are referencing.
#### Element declarations
Define the elements in the schema.
Include:
- the element name
- the element data type (optional)
Basic element declaration format:
``` XML
<xsd:element name="name" type="type">
```
##### Simple type
declares elements that:
- do NOT have Child Elements
- do NOT have Attributes
example:
``` XML
<xsd:element name="cityName" type="xsd:string" />
```
**Default Value**
If an element is not assigned a value then the default value is
assigned.
example:
``` XML
<xsd:element name="description" type="xsd:string" default="really cool place to visit!" />
```
**Fixed Value**
An attribute that is defined as fixed must be empty or contained the
specified fixed value. No other values are allowed.
example:
``` XML
<xsd:element name="description" type="xsd:string" '''fixed="you must visit this place - it is awesome!"''' />
```
##### Complex type
declares elements that:
- can have Child Elements
- can have Attributes
examples:
**1.** The root element \'tourGuide\' contains a child element \'city\'.
This is shown here:
***Nameless complex type***
``` XML
<xsd:element name="tourGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="city" type="cityDetails" minOccurs = "1" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
```
**Occurrence Indicators**:
- *minOccurs* = the minimum number of times an element can occur (here
it is 1 time)
- *maxOccurs* = the maximum number of times an element can occur (here
it is an unlimited number of times, \'unbounded\')
**2.** The parent element \'city\' contains many child elements:
\'cityName\', \'adminUnit\', \'country\', \'population\', etc. Why does
this complex element set not start with the line:
``` XML
<xsd:element name="city" type="cityDetails">
```
? The element \'city\' was already defined above within the complex
element \'tourGuide\' and it was given the type, \'cityDetails\'. This
data type, \'cityDetails\', is utilized here in identifying the sequence
of child elements for the parent element \'city\'.
***Named Complex Type*** - and therefore can be reused in other parts of
the schema
``` XML
<xsd:complexType name="cityDetails">
<xsd:sequence>
<xsd:element name="cityName" type="xsd:string"/>
<xsd:element name="adminUnit" type="xsd:string"/>
<xsd:element name="country" type="xsd:string"/>
<xsd:element name="population" type="xsd:integer"/>
<xsd:element name="area" type="xsd:integer"/>
<xsd:element name="elevation" type="xsd:integer"/>
<xsd:element name="longitude" type="xsd:decimal"/>
<xsd:element name="latitude" type="xsd:decimal"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="history" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
```
The **`<xsd:sequence>`{=html}** tag indicates that the child elements
must appear in the order, the sequence, specified here.
Compare the sample XML Schema and the sample XML Document - try to
observe patterns in the code and how the XML Schema sets up the XML
Document.
**3.** Elements that have attributes are also designated as complex
type.
a\. this XML Document line:
``` XML
<adminUnit class="state" name="Cayo" />
```
would be defined in the XML Schema as:
``` XML
<xsd:element name="adminUnit">
<xsd:complexType>
<xsd:attribute name="class" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
```
b\. this XML Document line:
``` XML
<adminUnit class="state">Cayo</adminUnit>
```
would be defined in the XML Schema as:
``` XML
<xsd:element name="adminUnit">
<xsd:complexType>
<xsd:simpleContent>
<xsd:extension base="xsd:string">
<xsd:attribute name="class" type="xsd:string" />
</xsd:extension>
</xsd:simpleContent>
</xsd:complexType>
</xsd:element>
```
#### Attribute declarations
Attribute declarations are used in complex type definitions. We saw some
attribute declarations in the third example of the Complex Type Element.
``` XML
<xsd:attribute name="class" type="xsd:string" />
```
#### Data type declarations
These are contained within element and attribute declarations as:
**type=\" \"**.
Common XML Schema Data Types
XML schema has a lot of built-in data types. The most common types are:
---------- -------------------------------------------------------------------
string a string of characters
decimal a decimal number
integer an integer
boolean the values true or false or 1 or 0
date a date, the date pattern can be specified such as YYYY-MM-DD
time a time of day, the time pattern can be specified such as HH:MM:SS
dateTime a date and time combination
anyURI if the element will contain a URL
---------- -------------------------------------------------------------------
For an entire list of built-in simple data types see
<http://www.w3.org/TR/xmlschema-2/#built-in-datatypes>
------------------------------------------------------------------------
Using an XML Editor =\> ../XML Editor/
This link will take you to instructions on how to start an XML editor.
Once you have followed the steps to get started you can copy the code in
the sample XML schema document and paste it into the XML editor. Then
check your results. Is the XML schema well-formed? Is the XML schema
valid?
------------------------------------------------------------------------
## XML stylesheet (XSL)
An XML Stylesheet is an XML Document. XML Stylesheets have an .xsl file
extension.
The eXtensible Stylesheet Language (XSL) provides a means to transform
and format the contents of an XML document for display. Since an XML
document does not contain tags a browser understands, such as HTML tags,
browsers cannot present the data without a stylesheet that contains the
presentation information. By separating the data and the presentation
logic, XSL allows people to view the data according to their different
needs and preferences.
The XSL Transformation Language (XSLT) is used to transform an XML
document from one form to another, such as creating an HTML document to
be viewed in a browser. An XSLT stylesheet consists of a set of
formatting instructions that dictate how the contents of an XML document
will be displayed in a browser, with much the same effect as Cascading
Stylesheets (CSS) do for HTML. Multiple views of the same data can be
created using different stylesheets. The output of a stylesheet is not
restricted to a browser.
During the transformation process, XSLT analyzes the XML document and
converts it into a **node tree** -- a hierarchical representation of the
entire XML document. Each node represents a piece of the XML document,
such as an element, attribute or some text content. The XSL stylesheet
contains predefined "templates" that contain instructions on what to do
with the nodes. XSLT will use the match attribute to relate XML element
nodes to the templates, and transform them into the resulting document.
**Exhibit 7: XML stylesheet document for city entity**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Tour Guide</title>
</head>
<body>
<h2>Cities</h2>
<xsl:apply-templates select="tourGuide"/>
</body>
</html>
</xsl:template>
<xsl:template match="tourGuide">
<xsl:for-each select="city">
<br/><xsl:value-of select="continentName"/><br/>
<xsl:value-of select="cityName"/><br/>
<xsl:text>Population: </xsl:text>
<xsl:value-of select='format-number(population, "##,###,###")'/><br/>
<xsl:value-of select="country"/>
<br/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
```
The output of the city.xsl stylesheet in Table 2-3 will look like the
following:
You will notice that the stylesheet consists of HTML to inform the media
tool (a web browser) of the presentation design. If you do not already
know HTML this may seem a little confusing. Online resources such as the
W3Schools tutorials can help with the basic understanding you will need
=\>(http://www.w3schools.com/html/default.asp).
Incorporated within the HTML is the XML that supplies the data, the
information, contained within our XML document. The XML of the
stylesheet indicates what information will be displayed and how. So, the
HTML constructs a display and the XML plugs in values within that
display. **XSL is the tool that transforms the information into
presentational form, but at the same time keeps the meaning of the
data.**
+----------------------------------------------------------------------+
| `<big>`{=html}**XML at Bertelsmann - a case study**`</big>`{=html} |
| |
| The German Bertelsmann Inc. is a privately owned media conglomerate |
| operating in 56 countries. It has interests in such businesses as TV |
| broadcast (RTL), magazine (Gruner & Jahr), books (Random House) etc. |
| In 2005 its 89 000 employees generated 18 billion € of revenue.\ |
| \ |
| A major concern of such a diversified business is utilizing |
| synergies. Management needs to make sure the Random House employees |
| don´t spend time and money figuring out what RTL TV journalists |
| already have come up with.\ |
| \ |
| Thus knowledge management based on IT promises huge time savings. |
| Consequently Bertelsmann in 2002 started a project called BeCom. |
| BeCom´s purpose was to enable the different Bertelsmann businesses |
| to use the same data for their different media applications. XML is |
| crucial in this project, because it allows for separating data |
| (document) from presentation (style sheet). Thus data can both be |
| examined statistically and be modified to fit different media like |
| TV and newspapers.\ |
| \ |
| Statistical XML data management for example enables employees to |
| benefit from CBR (Case Based Reasoning). |
| CBR allows a |
| Bertelsmann employee who searches for specific content to profit |
| from previous search findings of other Bertelsmann employees, thus |
| gaining info which is much more contextual than isolated research |
| results only. Besides XML data management, Bertelsmann TV and Book |
| units can apply this optimized data in their specific media using a |
| variety of lay-out applications like 3B2 or QuarkXPress. |
+----------------------------------------------------------------------+
### Prolog
- the XML declaration;
- the stylesheet declaration;
- the namespace declaration;
- the output document format.
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
```
**The XML declaration**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
```
**The stylesheet & namespace declarations**
``` XML
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
```
- identifies the document as an XSL style sheet;
- identifies the version number;
- refers to the W3C XSL namespace - the URL for the site that
describes the XML elements and data types used in the schema. You
can find more about namespaces here =\>
../Namespace/. Every time the xsl:
prefix is used it references the given namespace.
**The output document format**
``` XML
<xsl:output method="html"/>
```
This element designates the format of the output document and must be a
child element of
``` XML
<xsl:stylesheet>
```
### Templates
The **`<xsl:template>`{=html}** element is used to create templates that
describe how to display elements and their content. Above, in the XSL
introduction, we mentioned that XSL breaks up the XML document into
nodes and works on individual nodes. This is done with templates. Each
template within an XSL describes a single node. To identify which node a
given template is describing, use the \'match\' attribute. The value
given to the \'match\' attribute is called a **pattern**. Remember:
(**node tree** -- a hierarchical representation of the entire XML
document. Each node represents a piece of the XML document, such as an
element, attribute or some text content). Wherever there is branching in
the node tree, there is a node. `<xsl:template>`{=html} defines the
start of a template and contains rules to apply when a specified node is
matched.
**the match attribute**
` ``<xsl:template match="/">`{=html}
This template match attribute associates the XML document root (/), the
whole branch of the XML source document, with the HTML document root.
Contained within this template element is the typical HTML markup found
at the beginning of any HTML document. This HTML is written to the
output. The XSL looks for the root match and then outputs the HTML,
which the browser understands.
` ``<xsl:template match="tourGuide">`{=html}
This template match attribute associates the element \'tourGuide\' with
the display rules described within this element.
### Elements
Elements specific to XSL:
-------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
**XSL Element** **Meaning**
(from our sample XSL)
`<xsl:text>`{=html} Prints the actual text found between this element\'s tags
`<xsl:value-of>`{=html} This element is used with a \'select\' attribute to look up the value of the node selected and plug it into the output.
`<xsl:for-each>`{=html} This element is used with a \'select\' attribute to handle elements that repeat by looping through all the nodes in the selected node set.
`<xsl:apply-templates>`{=html} This element will apply a template to a node or nodes. If it uses a \'select\' attribute then the template will be applied only to the selected child node(s) and can specify the order of child nodes. If no \'select\' attribute is used then the template will be applied to the current node and all its child nodes as well as text nodes.
-------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
For more XSL elements =\>
<http://www.w3schools.com/xsl/xsl_w3celementref.asp> .
### Language-Specific Validation and Transformation Methods
#### PHP Methods of XML Dom Validation
Using the DOM DocumentObjectModel to
validate XML and with a DTD
DocumentTypeDeclaration and the
PHP language on a server and more <http://wiki.cc/php/Dom_validation>
#### Browser Methods
Place this line of code in your .xml document after the XML declaration
(prologue).
``` XML
<?xml-stylesheet type="text/xsl" href="tourGuide.xsl"?>
```
#### PHP XML Production
``` PHP
<?php
$xmlData = "";
mysql_connect('localhost','root','')
or die('Failed to connect to the DBMS');
// make connection to database
mysql_select_db('issd')
or die('Failed to open the requested database');
$result = mysql_query('SELECT * from students') or die('Query to like get the records failed');
if (mysql_num_rows($result)<1){
die ('');
}
$xmlString = "<classlist>\n";
$xmlString .= "\t<student>";
while ($row = mysql_fetch_array($result)) {
$xmlString .= "
\t<firstName>
".$row['firstName']."
</firstName>\n
\t<lastName>
".$row['lastName']."
\t</lastName>\n";
}
$xmlString .= "</student>\n";
$xmlString .= "</classlist>";
echo $xmlString;
$myFile = "classList.xml"; //any file
$fh = fopen($myFile, 'w') or die("can't open file"); //create filehandler
fwrite($fh, $xmlString); //write the data into the file
fclose($fh); //ALL DONE!
?>
```
#### PHP Methods of XSLT Transformation
This one is good for PHP5 and wampserver (latest). Please ensure that
\*xsl\* is NOT commented out in the php.ini file.
``` PHP
<?php
// Load the XML source
$xml = new DOMDocument;
$xml->load('tourguide.xml');
$xsl = new DOMDocument;
$xsl->load('tourguide.xsl');
// Configure the transformer
$proc = new XSLTProcessor;
$proc->importStyleSheet($xsl); // attach the xsl rules
echo $proc->transformToXML($xml);
?>
```
Example 1, Using within PHP itself (use phpInfo() function to check XSLT
extension; enable if needed) This example might produce XHTML. Please
note it could produce anything defined by the XSL.
``` PHP
<?php
$xhtmlOutput = xslt_create();
$args = array();
$params = array('foo' => 'bar');
$theResult = xslt_process(
$xhtmlOutput,
'theContentSource.xml',
'theTransformationSource.xsl',
null,
$args,
$params
);
xslt_free($xhtmlOutput); // free that memory
// echo theResult or save it to a file or continue processing (perhaps instructions)
?>
```
Example 2:
``` PHP
<?php
if (PHP_VERSION >= 5) {
// Emulate the old xslt library functions
function xslt_create() {
return new XsltProcessor();
}
function xslt_process($xsltproc,
$xml_arg,
$xsl_arg,
$xslcontainer = null,
$args = null,
$params = null) {
// Start with preparing the arguments
$xml_arg = str_replace('arg:', '', $xml_arg);
$xsl_arg = str_replace('arg:', '', $xsl_arg);
// Create instances of the DomDocument class
$xml = new DomDocument;
$xsl = new DomDocument;
// Load the xml document and the xsl template
$xml->loadXML($args[$xml_arg]);
$xsl->loadXML($args[$xsl_arg]);
// Load the xsl template
$xsltproc->importStyleSheet($xsl);
// Set parameters when defined
if ($params) {
foreach ($params as $param => $value) {
$xsltproc->setParameter("", $param, $value);
}
}
// Start the transformation
$processed = $xsltproc->transformToXML($xml);
// Put the result in a file when specified
if ($xslcontainer) {
return @file_put_contents($xslcontainer, $processed);
} else {
return $processed;
}
}
function xslt_free($xsltproc) {
unset($xsltproc);
}
}
$arguments = array(
'/_xml' => file_get_contents("xml_files/201945.xml"),
'/_xsl' => file_get_contents("xml_files/convertToSql_new2.xsl")
);
$xsltproc = xslt_create();
$html = xslt_process(
$xsltproc,
'arg:/_xml',
'arg:/_xsl',
null,
$arguments
);
xslt_free($xsltproc);
print $html;
?>
```
#### PHP file writing code
``` PHP
$myFile = "testFile.xml"; //any file
$fh = fopen($myFile, 'w') or die("can't open file"); //create filehandler
$stringData = "<foo>\n\t<bar>\n\thello\n"; // get a string ready to write
fwrite($fh, $stringData); //write the data into the file
$stringData2 = "\t</bar>\n</foo>";
fwrite($fh, $stringData2); //write more data into the file
fclose($fh); //ALL DONE!
```
### XML Colors
For use in your stylesheet: these colors can be used for both background
and font
<http://www.w3schools.com/html/html_colors.asp>
<http://www.w3schools.com/html/html_colorsfull.asp>
<http://www.w3schools.com/html/html_colornames.asp>
------------------------------------------------------------------------
Using an XML Editor =\> ../XML Editor/
This link will take you to instructions on how to start an XML editor.
Once you have followed the steps to get started you can copy the code in
the sample XML stylesheet document and paste it into the XML editor.
Then check your results. Is the XML stylesheet well-formed?
------------------------------------------------------------------------
## XML at Thomas Cook - a case study
+----------------------------------------------------------------------+
| As the leading travel company and most widely recognized brands in |
| the world, Thomas Cook works across the travel value chain - |
| airlines, hotels, tour operators, travel and incoming agencies, |
| providing its customers with the right product in all market |
| segments across the globe. Employing over 11,000 staff, the Group |
| has 33 tour operators, around 3,600 travel agencies, a fleet of 80 |
| aircraft and a workforce numbering some 26,000. Thomas Cook operates |
| throughout a network of 616 locations in Europe and overseas. The |
| company is now the second largest travel group in Europe and the |
| third largest in the world. |
| |
| As Thomas Cook sells other companies´ products, ranging from |
| packaged holidays to car hires, it needs to regularly change its |
| online brochure. Before Thomas Cook started using XML, it put |
| information into HTML format, and would take upto six weeks to get |
| an online brochure up and running online. XML helps do this job in |
| about three days. This helps provide all of Thomas Cook´s current |
| and potential customers and its various agencies in different |
| geographical locations with updated information, instead of having |
| to wait six weeks for new information to be released.\ |
| \ |
| XML allows Thomas Cook to put content information into a single |
| database, which can be re-used as many times as required. \"We did |
| not want to keep having to re-do the same content, we wanted the |
| ability to switch it on immediately,\" said Gwyn Williams, who is |
| content manager at Thomascook.com. \"This has brought internal |
| benefits such as being able to re-deploy staff into more value added |
| areas.\" Thomascook.com currently holds 65,000 pages of brochure and |
| travel guide information and an online magazine in XML format.\ |
| \ |
| Thomas Cook started using XML at a relatively early stage. As Thomas |
| Cook has a large database, the early use of XML will stand it in |
| good stead. At some point, the databases will have to be |
| incorporated into XML, and it is reported that XML databases are |
| quicker than conventional databases, giving Thomas Cook a slight |
| competitive advantage against those who do not use XML.\ |
| \ |
| Thomas Cook has found that this can lead to substantial cost |
| reductions as well as consistency of information across all |
| channels. By implementing a central content management system to |
| facilitate brochure production and web publications, they have |
| centralized the production, maintenance and distribution of content |
| across their brands and channels. |
+----------------------------------------------------------------------+
## Summary
+----------------------------------------------------------------------+
| From the previous chapter *Introduction to XML*, you have learned |
| the need for data exchange and the usefulness of XML in data |
| exchange. In this chapter, you have learned more about the three |
| major XML files: the XML document, the XML schema, and the XML |
| stylesheet. You learned the correct documentation required for each |
| type of file. You learned basic rules of syntax applicable for all |
| XML documents. You learned how to integrate the three types of XML |
| documents. And you learned the definition and distinction between a |
| *well-formed* document and a *valid* document. By following the *XML |
| Editor* links, you were able to see the results of the sample code |
| and learn how to use an XML Editor. |
| |
| Below are Exercises and Answers for further practice. Good Luck! |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
## /Definitions/
`XML`\
`SGML`\
`Dan Connelly`\
`RSS`\
`XML Declaration`\
`parent`\
`child`\
`sibling`\
`element`\
`attribute`
`*Well-formed XML`
`PCDATA`
## /Exercises/
Exercise 1.
a)Using \"tourguide\" above as a good example, create an XML document
whose root is \"classlist\" . This CLASSLIST is created from a starting
point of single entity, STUDENT. Any number of students contain
elements: firstname, lastname, emailaddress.
## /Answers/
|
# XML - Managing Data Exchange/Basic data structures
------------------------------------------------------------------------
+---------------------------------------------------------------------+
| **Learning objectives** |
| |
| - introduce the concept and uses of basic data structures |
| - describe how XML may be used to represent basic data structures |
| - enumerate common technical considerations |
+---------------------------------------------------------------------+
| |
+---------------------------------------------------------------------+
------------------------------------------------------------------------
## Introduction
In reviewing the four central problems in data management, (capture,
storage, retrieval, and exchange) the typical user of XML encounters
recurring fundamental structural patterns that apply to all sorts of
data throughout the *storage* and *exchange* phases. These patterns
recur consistently because their use transcends the particular contexts
in which the underlying data are processed. We call these patterns
\"data structures\" (or datatypes).
In this section, we discuss a few of the most fundamental \"basic data
structures\" and explain why they are useful, as well as how to work
with them using XML.
We start our introduction with a simple example. Consider an ordinary
grocery shopping list for a single-person household.
**Introductory Shopping List Example:**
` Andy's shopping list:`\
` * eggs`\
` * cough syrup(pick up for granny)`\
` * orange juice `\
` * bread`\
` * laundry detergent **don't forget this**`
When analyzing aspects of the information contained in this shopping
list, we can make some basic generalizations:
- **Portability:** the shopping list can be represented and
transferred easily. If necessary, it could be stored in a database
and processed by custom-designed software, but it could just as
easily be written on a scrap of paper;
- **Comprehensibility:** the shopping list is readily understood by
its intended audience (in this instance, the sole person who wrote
the list) and therefore needs no additional information or structure
in order to be immediately usable;
- **Adaptability:** if any changes become necessary (such as additions
or removals to the list) there is an existing and well-known
methodology for accomplishing this (e.g., in the case of a
handwritten list, simply write down new entries or cross out
unwanted entries).
### The fundamental concept of basic data structures
Given that we have the previous example for background, we can now
introduce the fundamental concept of \"basic data structures\".
```{=html}
<table class="wikitable">
```
```{=html}
<tr>
```
```{=html}
<td>
```
{width="50"}
```{=html}
</td>
```
```{=html}
<td>
```
The concept of \"basic data structures\" describes the fundamental
conventions we use to *store* our data, so that we can more easily
*exchange* our data. When we follow these fundamental conventions, we
help to ensure the *portability*, *comprehensibility* and *adaptability*
of information.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## Basic data structures defined
Now that we have introduced our concept of data structures, we can start
with some concrete definitions, and then review those definitions in the
context of our shopping list example.
### Overview of \"core\" data structures
The following terms define some \"core\" data structures[^1] that we use
throughout this chapter. This list is ordered in ascending degrees of
complexity:
- **SimpleBoolean**: Any value capable of being expressed as either
\"True\" or \"False\".
- **SimpleString**: A contiguous sequence of characters, including
both alphanumeric and non-alphanumeric.
- **SimpleSequence**: An enumeration of items generally accessible by
numeric indexing.
- **Name-value pair**: An arbitrary singular name attached to a
singular value.
- **SimpleDictionary**: An enumeration of items generally accessible
by alphanumeric indexing.
- **SimpleTable**: An ordered arrangement of columns and rows. A
SimpleTable can be classified as a \"composite\" data structure
(e.g., SimpleSequence where each item in the sequence is a single
SimpleDictionary).
An important point to remember while reviewing these \"core\" data
structures is that they are *elemental* and *complementary*. That is,
the core structures, when used in combination, can form even more
complex structures. Once the reader comes to understand this fact, it
will become apparent that there is no conceivable application or data
specification that cannot be wholly described in XML using nothing more
than these \"core\" data structures.
```{=html}
<table class="wikitable">
```
```{=html}
<tr>
```
```{=html}
<td>
```
{width="50"}
```{=html}
</td>
```
```{=html}
<td>
```
Once we understand the \"core\" data structures, we can use them in
combination to represent any conceivable kind of structured information.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
Now review the \"Introductory Shopping List Example\" above. When we
compare it with the \"core\" data structures that we\'ve just defined,
we can make some fairly straightforward observations:
- The entire shopping list cannot be represented using a SimpleBoolean
data structure, because the information is more complex than either
\"True\" or \"False\".
- The entire shopping list *can* be represented using a SimpleString.
- There may be reasons why we would not want to use a SimpleString to
represent the entire shopping list. For example, we might want to
transfer the list into a database or other software application and
then be able to sort, query, duplicate or otherwise process
*individual items* on the list. Treating the entire list as a
SimpleString would therefore complicate our processing requirements.
### SimpleString
**Different ways to represent a SimpleString in XML:**
``` XML
<Example>
<String note="This XML attribute contains a SimpleString.">
This XML Text Node represents a SimpleString.
</String>
<!-- This XML comment contains a SimpleString -->
<![CDATA[ This XML CDATA section contains a SimpleString. ]]>
</Example>
```
### SimpleSequence
**Different ways to represent a SimpleSequence in XML:**
``` XML
<Example>
<!-- use a single XML attribute with a space-delimited list of items -->
<ShoppingList items="bread eggs milk juice" />
<!-- use a single XML attribute with a semicolon-delimited list of items
(this allows us to add items with spaces in them) -->
<ShoppingList items="bread;cough syrup;milk;juice;laundry detergent" />
<!-- yet another way (but not necessarily a good way)
using multiple XML attributes -->
<ShoppingList item00="bread" item01="eggs" item02="cough syrup" />
<!-- yet another way
using XML child elements -->
<ShoppingList>
<item>eggs</item><item>milk</item><item>cough syrup</item>
</ShoppingList>
</Example>
```
### Name-value pair
### SimpleDictionary
### SimpleTable
#### Side-by-side examples
**SimpleTable (XML_Elem):**
``` XML
<table>
<tr><item>eggs</item><getfor>andy</getfor><notes></notes></tr>
<tr><item>milk</item><getfor>andy</getfor><notes></notes></tr>
<tr><item>laundry detergent</item><getfor>andy</getfor><notes></notes></tr>
<tr><item>cough syrup</item><getfor>granny</getfor><notes>try to get grape flavor</notes></tr>
</table>
```
**SimpleTable (XML_Attr):**
``` XML
<table>
<tr item="eggs" getfor="andy" notes="" />
<tr item="milk" getfor="andy" notes="" />
<tr item="laundry detergent" getfor="andy" notes="" />
<tr item="cough syrup" getfor="granny" notes="try to get grape flavor" />
</table>
```
**SimpleTable (XML_Mixed):**
``` XML
<table>
<tr>
<item getfor="andy" >eggs</item><notes></notes>
</tr>
<tr>
<item getfor="andy" >milk</item><notes></notes>
</tr>
<tr>
<item getfor="andy" >laundry detergent</item><notes></notes>
</tr>
<tr>
<item getfor="granny">cough syrup</item><notes>try to get grape flavor</notes>
</tr>
</table>
```
## Basic data structures in programming
To further illustrate how basic data structures apply in many different
contexts, some of the basic data structures enumerated previously are
examined and compared here in the context of computer programming.
For the first part of the comparison, we examine the generic terminology
against that used commonly in programming languages:
- **SimpleBoolean**: is commonly called a `boolean` and can usually
take the values `true` or `false`, `0` or `1`, or other values,
depending on the language.
- **SimpleString**: commonly called a `string` or `stringBuffer`.
- **SimpleSequence**: numerically indexed variables in programming are
commonly represented with an `array`.
- **Name-value pair**: (explained in more detail below)
- **SimpleDictionary**: these are commonly represented with a
`dictionary`, or an `associative array`.
- **SimpleTable**: (explained in more detail below)
## Technical considerations
Now that we\'ve introduced and discussed specific examples of the basic
data structures, there are a few technical considerations that apply to
all of the data structures, and are particularly important to those who
may be responsible for implementing and designing XML schemas to deal
with specific implementation scenarios.
- **Exact terminology depends on context:** Although the \"basic\"
structures described here apply to many different scenarios, the
terms used to describe them can overlap or conflict. For example,
the term \"SimpleSequence\" as used here closely coincides with what
is called an \"array\" in many programming languages. Similarly, the
term \"SimpleDictionary\" is shorthand for what some programming
languages call an \"associative array\". Although this close
correlation is intentional, one must always remember that the
specific nuances of an application or programming language will
require additional attention. Sometimes minor conflicts or
discrepancies arise when one digs into the details for any specific
data structure in any given project or technology.
```{=html}
<!-- -->
```
- **Basic structures are flexible concepts:** Structures can be
defined in terms of one another, and some structures can be applied
recursively. For example, one could easily define a SimpleSequence
using a SimpleString along with some basic assumptions. (e.g., a
SimpleSequence is a string of alphanumeric characters where each
item in the sequence is separated by one or more whitespace
characters: \"eggs bread butter milk\").
```{=html}
<!-- -->
```
- **Abstract structures tend to hide tricky details:** For example,
the term \"SimpleString\" describes the abstract notion of a
sequence of characters (e.g.,
\"\"). The abstract notion is
fairly intuitive and uncomplicated. Nevertheless, the precise
notation used to *implement* that abstract notion, and represent it
in real-live working code is a different matter entirely. Different
programming languages and different environments may use different
conventions for representing the same \"string\". Because of this
variability, one can also recognize that the abstract notion of a
\"SimpleString\" in XML is also subject to differing
representations, based on the needs of any given project.
## Notes and references
fr:Programmation XML/Structure d\'un document
XML
[^1]: An important note: the basic terms used here are generalizations.
Although they may coincide with terms used in specific software,
specific programming languages, or specific applications, these are
not intended as technically precise definitions. The concepts
described here are presented to help emphasize the context-neutral
principle of interoperability in XML.
|
# XML - Managing Data Exchange/The one-to-many relationship
------------------------------------------------------------------------
```{=html}
<table cellspacing=10 cellpadding=10 border=5>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<font size=4>`{=html}`<b>`{=html}Learning
objectives`</b>`{=html}`</font>`{=html}\
- `<font size=3>`{=html} Learn different techniques of implementing
one-to-many relationships in XML`</font>`{=html}
- `<font size=3>`{=html} create custom data types in an XML
schema`</font>`{=html}
- `<font size=3>`{=html} create empty elements with attributes in an
XML document`</font>`{=html}
- `<font size=3>`{=html} define a presentation layout for an XML
document using a table with varying background colors and font
characteristics, and display images in an XML
stylesheet`</font>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
\
==Introduction== In a one-to-many relationship, one object can reference
several instances of another. A model is mapped into a schema whereby
each data model entity becomes a complex element type. Each data model
attribute becomes a simple element type, and the one-to-many
relationship is recorded as a sequence.\
\
**Exhibit 1:Data model for 1:m relationship**\
:::\
In the previous chapter, we introduced a simple XML schema, XML
document, and an XML stylesheet for a single entity data model. We now
include more features of each of the key aspects of XML.
### Implementing a one-to-many relationship
There are three different techniques for implementing a one-to-many
relationship:
Containment relationship: A structure is defined where one element is
contained within another. The \"contained\" element ceases to exist when
the \"container\" element is removed. For instance, where a city has
many hotels, the hotels are \"contained\" in the city.
``` XML
<cityDetails>
<cityName>Belmopa</cityName>
<hotelDetails>
<hotelName>Bull Frog Inn</hotelName>
</hotelDetails>
<hotelDetails>
<hotelName>Pook's Hill Lodge</hotelName>
</hotelDetails>
</cityDetails>
<cityDetails>
<cityName>Kuala Lumpur</cityName>
<hotelDetails>
<hotelName>Pan Pacific Kuala Lumpur</hotelName>
</hotelDetails>
<hotelDetails>
<hotelName>Mandarin Oriental Kuala Lumpur</hotelName>
</hotelDetails>
</cityDetails>
```
Intra-document relationships: In a case where you have one city with
many hotels, rather than a city containing hotels, a hotel will have a
\"location in\" relationship to a city. A city id is used as a reference
on the hotel element. Therefore, rather than the hotels being contained
in the city, they now just reference the city\'s id via the cityRef
attribute. This is very similar to a foreign key in a relational
database.
``` XML
<cityDetails>
<city ID="c1">
<cityName>Belmopa</cityName>
</city ID>
<city ID="c2">
<cityName>Kuala Lumpur</cityName>
</city ID>
</cityDetails>
<hotelDetails>
<hotel cityRef="c1">
<hotelName>Bull Frog Inn</hotelName>
</hotel>
<hotel cityRef="c2">
<hotelName>Pan Pacific Kuala Lumpur</hotelName>
</hotel>
</hotelDetails>
```
Inter-document relationships: The inter-document relationship is much
like the intra-document relationship. It also uses the id and idRef
attributes to assign an attribute to a parent attribute. The difference
is that the inter-document relationship is used when tables, such as the
city and hotel tables, might live in different filesystems or
tablespaces.
``` XML
<city id="c1">
<cityName>Belmopa</cityName>
</city>
<city id="c2">
<cityName>Kuala Lumpur</cityName>
</city>
```
``` XML
<hotel>
<city href="cityDetails.xml#c1"/>
<hotelName>Bull Frog Inn</hotelName>
</hotel>
<hotel>
<city href="cityDetails.xml#c2"/>
<hotelName>Pan Pacific Kuala Lumpur</hotelName>
</hotel>
```
**Exhibit 2:Checklist for deciding what technique to use:**
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<th width="30%">
```
Technique
```{=html}
</th>
```
```{=html}
<th width="25%">
```
Passing Data
```{=html}
</th>
```
```{=html}
<th width="15%">
```
Flexibility
```{=html}
</th>
```
```{=html}
<th width="30%">
```
Ease of Use
```{=html}
</th>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
Containment
```{=html}
</td>
```
```{=html}
<td>
```
Excellent
```{=html}
</td>
```
```{=html}
<td>
```
Fair
```{=html}
</td>
```
```{=html}
<td>
```
Excellent
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
Intra-Document
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Good
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Good
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Good
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
Inter-Document
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Fair
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Excellent
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Fair
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## XML schema
Some of the built-in data types for an XML schema were introduced in the
previous chapter, but still, there are more that are very useful, such
as anyURI, date, time, year, and month. In addition to the built-in data
types, a custom data type can be defined by the schema designer to
accept specific data input. As we have learned, data are defined in XML
documents using markup tags defined in an XML schema. However, some
elements might not have values. An empty element tag can be used to
address this situation. An empty element tag (and any custom markup tag)
can contain attributes that add additional information about the tag
without adding extra text to the element. An example will be shown in
the chapter, using attributes in an empty element tag.
### Empty elements with attributes in XML document
Elements can have different content types depending on how each element
is defined in the XML schema. The different types are element content,
mixed content, simple content, and empty content. An XML element
consists of everything from the start of the element tag to the close of
that element tag.
- An element with element content is the root element - everything in
between the opening and closing tags consists of elements only.
```{=html}
<table border="0" width="85%" style="margin:auto">
```
```{=html}
<tr>
```
```{=html}
<td width="13%">
```
Example:
```{=html}
</td>
```
```{=html}
<td width="87%">
```
`<tourGuide>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
:
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
`</tourGuide>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
- A mixed content element is one that has text and as well as other
elements between its opening and closing tags.
```{=html}
<table border="0" width="85%" style="margin:auto">
```
```{=html}
<tr>
```
```{=html}
<td width="13%">
```
Example:
```{=html}
</td>
```
```{=html}
<td width="87%">
```
`<restaurant>`{=html}My favorite restaurant is
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
`<restaurantName>`{=html}Provino\'s Italian
Restaurant`</restaurantName>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
:
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
`</restaurant>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
- A simple content element is one that contains only text between its
opening and closing tags.
```{=html}
<table border="0" width="85%" style="margin:auto">
```
```{=html}
<tr>
```
```{=html}
<td width="13%">
```
Example:
```{=html}
</td>
```
```{=html}
<td width="87%">
```
`<restaurantName>`{=html}Provino\'s Italian
Restaurant`</restaurantName>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
- An empty content element, which is an empty element, is one that
does not contain anything between its opening and closing tags (or
the element tag is opened and ended with a single tag, by using /
before the closing of the opening tag.
```{=html}
<table border="0" width="85%" style="margin:auto">
```
```{=html}
<tr>
```
```{=html}
<td width="13%">
```
Example:
```{=html}
</td>
```
```{=html}
<td width="87%">
```
\<hotelPicture filename=\"pan_pacific.jpg\" size=\"80\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
value=\"Image of Pan Pacific\"/\>
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
An empty element is useful when there is no need to specify its content
or that the information describing the element is fixed. Two examples
illustrated this concept. First, a picture element that references the
source of an image with its attributes, but has no need in specifying
text content. Second, the owner's name is fixed for a company, thus it
can specify the related information inside the owner tag using
attributes. An attribute is meta-information, information that describes
the content of the element.
### European Central Bank\'s use of XML
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01"
xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2004-05-28">
<Cube currency="USD" rate="1.2246"/>
<Cube currency="JPY" rate="135.77"/>
<Cube currency="DKK" rate="7.4380"/>
<Cube currency="GBP" rate="0.66730"/>
<Cube currency="SEK" rate="9.1150"/>
<Cube currency="CHF" rate="1.5304"/>
<Cube currency="ISK" rate="87.72"/>
<Cube currency="NOK" rate="8.2120"/>
</Cube>
</Cube>
<!--For the sake of illustration, some of the currencies are omitted
in the preceding code.Banks, consultants, currency traders,
and firms involved in international trade are the major users
of this information.-->
</gesmes:Envelope>
```
### XML schema data types
Some of the commonly used data types, such as string, decimal, integer,
and boolean, are introduced in chapter 2. The following are a few more
data types that are useful.
**Exhibit 3:Other data types:**
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<th width="7%">
```
Type
```{=html}
</th>
```
```{=html}
<th width="25%">
```
Format
```{=html}
</th>
```
```{=html}
<th width="18%">
```
Example
```{=html}
</th>
```
```{=html}
<th width="50%">
```
Comment
```{=html}
</th>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
year
```{=html}
</td>
```
```{=html}
<td>
```
YYYY
```{=html}
</td>
```
```{=html}
<td>
```
1999
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
month
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
YYYY-MM
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
1999-03
```{=html}
</td>
```
```{=html}
<td>
```
Month type is used when the day is irrelevant for the data element
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
time
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
hh:mm:ss.sss with optional time zone indicator
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
20:14:05
```{=html}
</td>
```
```{=html}
<td>
```
Z for UTC or one of --hh:mm or +hh:mm to indicate the difference from
UTC. This time type is used when you want the content to represent a
particular time of day that recurs every day, such as 4:15 pm.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
date
```{=html}
</td>
```
```{=html}
<td>
```
YYYY-MM-DD
```{=html}
</td>
```
```{=html}
<td>
```
1999-03-14
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
anyURI
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
The domain name specified beginning with <http://>
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
<http://www.panpacific.com>
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
### More data types
Besides the built-in data types, custom data types can be created as
required. A custom data type can be a simple type or complex type. For
simplicity, we create a custom data type that is a simple type, which
means that the element does not contain other elements or attributes. It
contains text only. The creation of a custom simple type starts from
using a built-in simple type and applying it with restrictions, or
facets, to limit the acceptable values of the tag. A custom simple type
can be nameless or named. If the custom simple type is to be used only
once, then it makes sense to not name it; thus, that custom type will
only be used in where it is defined. Since a named custom type can be
referenced (by its name), that custom type can be used wherever
necessary.
A pattern can be used to specify exactly how the content of the element
should look. For example, one might want to specify the format of a
telephone number, a postal code, or a product code. By having a defined
pattern for certain elements, the data exchanged will be uniform and the
values will be consistent when stored in a database. A useful way to set
patterns is through Regex, which will be discussed in later chapters.
### Schema examples
The following is a schema that extends the schema introduced in the
previous chapter to include a one-to-many relationship of city to hotels
with two examples of custom data types.
**Exhibit 1:Data model for 1:m relationship**
:
: !1:m relationship - City
Hotel
Important, this is a continuing example, so new code is added to the
last chapter\'s example!
#### Containment example
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<!--Tour Guide-->
<xsd:element name="tourGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="city" type="cityDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<!--This will contain the City details-->
<xsd:complexType name="cityDetails">
<xsd:sequence>
<xsd:element name="cityName" type="xsd:string"/>
<xsd:element name="adminUnit" type="xsd:string"/>
<xsd:element name="country" type="xsd:string"/>
<!--The element Continent uses a Nameless Custom Simple Type-->
<xsd:element name="continent">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Asia"/>
<xsd:enumeration value="Africa"/>
<xsd:enumeration value="Australia"/>
<xsd:enumeration value="Europe"/>
<xsd:enumeration value="North America"/>
<xsd:enumeration value="South America"/>
<xsd:enumeration value="Antarctica"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="population" type="xsd:integer"/>
<xsd:element name="area" type="xsd:integer"/>
<xsd:element name="elevation" type="xsd:integer"/>
<xsd:element name="longitude" type="xsd:decimal"/>
<xsd:element name="latitude" type="xsd:decimal"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="history" type="xsd:string"/>
<xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<!-- This will contain the Hotel details-->
<xsd:complexType name="hotelDetails">
<xsd:sequence>
<xsd:element name="hotelName" type="xsd:string"/>
<xsd:element name="hotelPicture"/>
<xsd:element name="streetAddress" type="xsd:string"/>
<xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
<xsd:element name="phone" type="xsd:string"/>
<xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>
<!-- The custom simple type, emailAddressType, defined in the xsd:complexType,
is used as the type of the emailAddress element. -->
<xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
<xsd:element name="hotelRating" type="xsd:integer"/>
</xsd:sequence>
</xsd:complexType>
<!-- NOTE: Since postalCode, emailAddress, and websiteURL are not standard elements that
must be provided, the minOccurs=”0” indicates that they are optional -->
<!--This is a Named Custom SimpleType that is called from Hotel whenever someone types in an
email address-->
<xsd:simpleType name="emailAddressType">
<xsd:restriction base="xsd:string">
<!--You can learn more about this pattern by reading the Regex section.-->
<xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
```
#### Intra-document example
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<!--Tour Guide-->
<xsd:element name="tourGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="city" type="cityDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<!--This will contain the City details-->
<xsd:complexType name="cityDetails">
<xsd:sequence>
<xsd:element name="cityID" type="xsd:ID"/>
<xsd:element name="cityName" type="xsd:string"/>
<xsd:element name="adminUnit" type="xsd:string"/>
<xsd:element name="country" type="xsd:string"/>
<!--The element Continent uses a Nameless Custom Simple Type-->
<xsd:element name="continent">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Asia"/>
<xsd:enumeration value="Africa"/>
<xsd:enumeration value="Australia"/>
<xsd:enumeration value="Europe"/>
<xsd:enumeration value="North America"/>
<xsd:enumeration value="South America"/>
<xsd:enumeration value="Antarctica"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="population" type="xsd:integer"/>
<xsd:element name="area" type="xsd:integer"/>
<xsd:element name="elevation" type="xsd:integer"/>
<xsd:element name="longitude" type="xsd:decimal"/>
<xsd:element name="latitude" type="xsd:decimal"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="history" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<!-- This will contain the Hotel details-->
<xsd:complexType>
<xsd:sequence>
<xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="hotelDetails">
<xsd:sequence>
<xsd:element name="cityRef" type="xsd:IDRef"/>
<xsd:element name="hotelName" type="xsd:string"/>
<xsd:element name="hotelPicture"/>
<xsd:element name="streetAddress" type="xsd:string"/>
<xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
<xsd:element name="phone" type="xsd:string"/>
<xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>
<!-- The custom simple type, emailAddressType, defined in the xsd:complexType,
is used as the type of the emailAddress element. -->
<xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
<xsd:element name="hotelRating" type="xsd:integer"/>
</xsd:sequence>
</xsd:complexType>
<!-- NOTE: Since postalCode, emailAddress, and websiteURL are not standard elements that
must be provided, the minOccurs=”0” indicates that they are optional -->
<!--This is a Named Custom SimpleType that is called from Hotel whenever someone types in an
email address-->
<xsd:simpleType name="emailAddressType">
<xsd:restriction base="xsd:string">
<!--You can learn more about this pattern by reading the Regex section.-->
<xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
```
#### Inter-document example
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<!--Tour Guide-->
<xsd:element name="tourGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="city" type="cityDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<!--This will contain the City details-->
<xsd:complexType name="cityDetails">
<xsd:sequence>
<xsd:element name="cityID" type="xsd:ID"/>
<xsd:element name="cityName" type="xsd:string"/>
<xsd:element name="adminUnit" type="xsd:string"/>
<xsd:element name="country" type="xsd:string"/>
<!--The element Continent uses a Nameless Custom Simple Type-->
<xsd:element name="continent">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Asia"/>
<xsd:enumeration value="Africa"/>
<xsd:enumeration value="Australia"/>
<xsd:enumeration value="Europe"/>
<xsd:enumeration value="North America"/>
<xsd:enumeration value="South America"/>
<xsd:enumeration value="Antarctica"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="population" type="xsd:integer"/>
<xsd:element name="area" type="xsd:integer"/>
<xsd:element name="elevation" type="xsd:integer"/>
<xsd:element name="longitude" type="xsd:decimal"/>
<xsd:element name="latitude" type="xsd:decimal"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="history" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
```
``` XML
<!-- This will contain the Hotel details-->
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<!--Tour Guide 2-->
<xsd:element name="tourGuide2">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="hotelDetails">
<xsd:sequence>
<xsd:element name="cityRef" type="xsd:IDRef"/>
<xsd:element name="hotelName" type="xsd:string"/>
<xsd:element name="hotelPicture"/>
<xsd:element name="streetAddress" type="xsd:string"/>
<xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
<xsd:element name="phone" type="xsd:string"/>
<xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>
<!-- The custom simple type, emailAddressType, defined in the xsd:complexType,
is used as the type of the emailAddress element. -->
<xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
<xsd:element name="hotelRating" type="xsd:integer"/>
</xsd:sequence>
</xsd:complexType>
<!-- NOTE: Since postalCode, emailAddress, and websiteURL are not standard elements that
must be provided, the minOccurs=”0” indicates that they are optional -->
<!--This is a Named Custom SimpleType that is called from Hotel whenever someone types in an
email address-->
<xsd:simpleType name="emailAddressType">
<xsd:restriction base="xsd:string">
<!--You can learn more about this pattern by reading the Regex section.-->
<xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
```
Refers to Chapter 2 - A single entity for steps in using NetBeans to
create the above XML schema.
## XML document
`<B>`{=html}Attributes`</B>`{=html}
- The valid element naming structure applies to attribute names as
well
- In a given element, all attributes' names must be unique
- An attribute may not contain the symbol '\<' The character string
'<' can be used to represent it
- Each attribute must have a name and a value. (i.e.
`<hotelPicture filename=“pan_pacific.jpg” />`{=html}, filename is
the name and pan_pacific.jpg is the value)
- If the assigned value itself contains a quoted string, the type of
quotation marks must differ from those used to enclose the entire
value. (For instance, if double quotes are used to enclose the whole
value then use single quotes for the string:
`<name familiar=”’Jack’”>`{=html}John Smith`</name>`{=html})
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="city_hotel.xsl"?>
<tourGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="TourGuide3.xsd">
<!--This is where you define the first city and all its attributes-->
<city>
<cityName>Belmopa</cityName>
<adminUnit>Cayo</adminUnit>
<country>Belize</country>
<!--The content of the element “continent” must be one of the values specified in the set of
acceptable values in the XML schema for the element “continent”-->
<continent>South America</continent>
<population>11100</population>
<area>5</area>
<elevation>130</elevation>
<longitude>12.3</longitude>
<latitude>123.4</latitude>
<description>Belmopan is the capital of Belize</description>
<history>Belmopan was established following devastation of the former capitol, Belize City ,
by Hurricane Hattie in 1965. High ground and open space influenced the choice and
ground-breaking began in 1966. By 1970 most government offices and operations had
already moved to the new location. </history>
<!--This is where you would store the name of the Hotel and its attributes-->
<!--Notice that the hotelDetails elements did not contain the postalCode entity. The document is
still valid, because postalCode is optional-->
<hotel>
<hotelName>Bull Frog Inn</hotelName>
<!--The empty element, hotelPicture, contains attributes: “filename”, “size”, and “value”, to
indicate the name and location of the image file, the desired size, and
the description of the empty element, hotelPicture-->
<hotelPicture filename="bull_frog_inn.jpg" size="80" value="Image of Bull Frog Inn"
imageURL="http://www.bullfroginn.com"/>
<streetAddress>25 Half Moon Avenue</streetAddress>
<phone>501-822-3425</phone>
<!--The emailAddress elements must match the pattern specified in the schema to be valid -->
<emailAddress>[email protected]</emailAddress>
<websiteURL>http://www.bullfroginn.com/</websiteURL>
<hotelRating>4</hotelRating>
</hotel>
<!--This is where you put the information for another Hotel-->
<hotel>
<hotelName>Pook's Hill Lodge</hotelName>
<hotelPicture filename="pook_hill_lodge.jpg" size="80" value="Image of Pook's Hill
Lodge" imageURL="http://www.global-travel.co.uk/pook1.htm"/>
<streetAddress>Roaring River</streetAddress>
<phone>440-126-854-1732</phone>
<emailAddress>[email protected]</emailAddress>
<websiteURL>http://www.global-travel.co.uk/pook1.htm</websiteURL>
<hotelRating>3</hotelRating>
</hotel>
</city>
<!--This is where you define another city and its attributes-->
<city>
<cityName>Kuala Lumpur</cityName>
<adminUnit>Selangor</adminUnit>
<country>Malaysia</country>
<continent>Asia</continent>
<population>1448600</population>
<area>243</area>
<elevation>111</elevation>
<longitude>101.71</longitude>
<latitude>3.16</latitude>
<description>Kuala Lumpur is the capital of Malaysia and is the largest city in the nation.
</description>
<history>The city was founded in 1857 by Chinese tin miners and superseded Klang. In 1880
the British government transferred their headquarters from Klang to Kuala Lumpur , and
in 1896 it became the capital of Malaysia. </history>
<!--This is where you put the information for a Hotel-->
<hotel>
<hotelName>Pan Pacific Kuala Lumpur </hotelName>
<hotelPicture filename="pan_pacific.jpg" size="80" value="Image of Pan Pacific"
imageURL="http://www.malaysia-hotels-discount.com/hotels/kualalumpur/pan_pacific_hotel/index.shtml"/>
<streetAddress>Jalan Putra</streetAddress>
<postalCode>50746</postalCode>
<phone>1-866-260-0402</phone>
<emailAddress>[email protected]</emailAddress>
<websiteURL>http://www.panpacific.com</websiteURL>
<hotelRating>5</hotelRating>
</hotel>
<!--This is where you put the information for another Hotel-->
<hotel>
<hotelName>Mandarin Oriental Kuala Lumpur </hotelName>
<hotelPicture filename="mandarin_oriental.jpg" size="80" value="Image of Mandarin
Oriental" imageURL="http://www.mandarinoriental.com/kualalumpur"/>
<streetAddress>Kuala Lumpur City Centre</streetAddress>
<postalCode>50088</postalCode>
<phone>011-603-2380-8888</phone>
<emailAddress>[email protected]</emailAddress>
<websiteURL>http://www.mandarinoriental.com/kualalumpur/</websiteURL>
<hotelRating>5</hotelRating>
</hotel>
</city>
</tourGuide>
```
`<small>`{=html}**Table 3-2: XML Document for a one-to-many relationship
--
city_hotel.xml**`</small>`{=html}
Refers to Chapter 2 - A single entity for steps in using NetBeans to
create the above XML document.
## XML style sheet
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Tour Guide</title>
</head>
<body>
<h2>Cities</h2>
<xsl:apply-templates select="tourGuide"/>
</body>
</html>
</xsl:template>
<xsl:template match="tourGuide">
<xsl:for-each select="city">
<xsl:text>City: </xsl:text>
<xsl:value-of select="cityName"/>
<br/>
<xsl:text>Population: </xsl:text>
<xsl:value-of select="population"/>
<br/>
<xsl:text>Country: </xsl:text>
<xsl:value-of select="country"/>
<br/>
<xsl:for-each select="hotel">
<xsl:text>Hotel: </xsl:text>
<xsl:value-of select="hotelName"/>
<br/>
</xsl:for-each>
<br/>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>
```
## Summary
+----------------------------------------------------------------------+
| Besides the simple built-in data types (e.g, year, month, time, |
| anyURI, and date) schema designers may create custom data types to |
| suit their needs. A simple custom data type can be created from one |
| of the built-in data types by applying to it some restrictions, |
| facets (enumerations that specify a set of acceptable values), or |
| specific patterns. |
| |
| An empty element does not contain any text, however, it may contain |
| attributes to provide additional information about that element. |
| |
| The presentation layout for displaying a HTML page can include code |
| for style tags, background color, font size, font weight, and |
| alignment. Table tags can be used to organize the layout of content |
| in a HTML page, and images can also be displayed using an image tag. |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
## Exercises
In order to learn more about the one-to-many relationship,
exercises are provided.\
## Answers
In order to learn more about the one-to-many relationship,
answers are provided to go with the exercises
above.
|
# XML - Managing Data Exchange/The one-to-one relationship
+----------------------------------------------------------------------+
| `<span style="font-size:large;">`{=html}`<b>`{=html}Learning |
| objectives`</b>`{=html}`</span>`{=html}\ |
| |
| - `<span style="font-size:medium;">`{=html}Create a schema for a |
| data model containing a 1:1 relationship `</span>`{=html} |
| - `<span style="font-size:medium;">`{=html}Place restrictions on |
| elements or attributes in an XML schema`</span>`{=html} |
| - `<span style="font-size:medium;">`{=html}Specify fixed or |
| default values for an element in an XML schema`</span>`{=html} |
+----------------------------------------------------------------------+
## Introduction
In the previous chapter, some new features of XML schemas, documents,
and stylesheets were introduced as well as how to model a one-to-many
relationship. In this chapter, we will introduce the modeling of a
one-to-one relationship in XML. We will also introduce more features of
an XML schema.
## A one-to-one (1:1) relationship
The following diagram shows a one-to-one and a one-to-many relationship.
The one-to-one relationship records each country as a single top
destination.

**Exhibit 4-1: Data model for a 1:1 relationship**
## XML schema
A one-to-one (1:1) relationship is represented in the data model in
Exhibit 4-1. The addition of country and destination to the data model
allows the 1:1 relationship named topDestination. A country has many
different destinations, but only one top destination. The XML schema in
Exhibit 4-2 shows how to represent a 1:1 relationship in an XML schema.
### XML schema example
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<!--
Tour Guide
-->
<xsd:element name="tourGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="country" type="countryDetails" minOccurs="1" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<!--
Country
-->
<xsd:complexType name="countryDetails">
<xsd:sequence>
<xsd:element name="countryName" type="xsd:string" minOccurs="1" maxOccurs="1"/>
<xsd:element name="population" type="xsd:integer" minOccurs="0" maxOccurs="1" default="0"/>
<xsd:element name="continent" minOccurs="0" maxOccurs="1">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Asia"/>
<xsd:enumeration value="Africa"/>
<xsd:enumeration value="Australasia"/>
<xsd:enumeration value="Europe"/>
<xsd:enumeration value="North America"/>
<xsd:enumeration value="South America"/>
<xsd:enumeration value="Antarctica"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="topDestination" type="destinationDetails" minOccurs="0" maxOccurs="1"/>
<xsd:element name="destination" type="destinationDetails" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<!--
Destination
-->
<xsd:complexType name="destinationDetails">
<xsd:all>
<xsd:element name="destinationName" type="xsd:string"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="streetAddress" type="xsd:string" minOccurs="0"/>
<xsd:element name="telephoneNumber" type="xsd:string" minOccurs="0"/>
<xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
</xsd:all>
</xsd:complexType>
</xsd:schema>
```
\
`<small>`{=html}**Exhibit 4-2: XML Schema for a one-to-one
relationship**`</small>`{=html}
### New elements in schema
\
Let's examine the new elements and attributes in the schema in Exhibit
4-2.
- Country is a complex type defined in City to represent the 1:M
relationship between a country and its cities.
- Destination is a complex type defined in Country to represent the
1:M relationship between a country and its many destinations.
- topDestination is a complex type defined in Country to represent the
1:1 relationship between a country and its top destination.
### Restrictions in schema
\
Placing restrictions on elements was introduced in the previous chapter;
however, there are more potentially useful restrictions that can be
placed on an element. Restrictions can be placed on elements and
attributes that affect how the processor handles whitespace characters:
``` XML
<xsd:element name="streetAddress">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:whiteSpace value="preserve"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
```
#### White space & length constraints
The whiteSpace constraint is set to \"preserve\", which means that the
XML processor **will not** remove any white space characters. Other
useful restrictions include the following:
- Replace -- the XML processor will replace all whitespace characters
with spaces.
:
: `<xsd:whiteSpace value="replace"/>`{=html}
- Collapse -- The processor will remove all whitespace characters.
:
: `<xsd:whiteSpace value="collapse"/>`{=html}
- Length, maxLength, minLength---the length of the element can be
fixed or can have a predefined range.
:
: `<xsd:length value="8"/>`{=html}
: `<xsd:minLength value="5"/>`{=html}
: `<xsd:maxLength value="8"/>`{=html}
#### Order indicators
In addition to placing restrictions on elements, order indicators can be
used to define in what order elements should occur.
##### All indicator
The `<all>`{=html} indicator specifies by default that the child
elements can appear in any order and that each child element must occur
once and only once:
``` XML
<xsd:element name="person">
<xsd:complexType>
<xsd:all>
<xsd:element name="firstname" type="xsd:string"/>
<xsd:element name="lastname" type="xsd:string"/>
</xsd:all>
</xsd:complexType>
</xsd:element>
```
##### Choice indicator
The `<choice>`{=html} indicator specifies that either one child element
or another can occur:
``` XML
<xsd:element name="person">
<xsd:complexType>
<xsd:choice>
<xsd:element name="employee" type="employee"/>
<xsd:element name="visitor" type="visitor"/>
</xsd:choice>
</xsd:complexType>
</xsd:element>
```
##### Sequence indicator
The `<sequence>`{=html} indicator specifies that the child elements must
appear in a specific order:
``` XML
<xsd:element name="person">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="firstname" type="xsd:string"/>
<xsd:element name="lastname" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
```
## XML document
\
The XML document in Exhibit 4-3 shows how the new elements (country and
destination) defined in the XML schema found in Exhibit 4-2 are used in
an XML document. Note that the child elements of
`<topDestination>`{=html} can appear in any order because of the
`<xsd:all>`{=html} order indicator used in the schema.
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="newXMLSchema.xsl" media="screen"?>
<tourGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="XMLSchema.xsd">
<!--
Malaysia
-->
<country>
<countryName>Malaysia</countryName>
<population>22229040</population>
<continent>Asia</continent>
<topDestination>
<description>A popular duty-free island north of Penang.</description>
<destinationName>Pulau Langkawi</destinationName>
</topDestination>
<destination>
<destinationName>Muzium Di-Raja</destinationName>
<description>The original palace of the Sultan</description>
<streetAddress>122 Muzium Road</streetAddress>
<telephoneNumber>48494030</telephoneNumber>
<websiteURL>www.muziumdiraja.com</websiteURL>
</destination>
<destination>
<destinationName>Kinabalu National Park</destinationName>
<description>A national park</description>
<streetAddress>54 Ocean View Drive</streetAddress>
<telephoneNumber>4847101</telephoneNumber>
<websiteURL>www.kinabalu.com</websiteURL>
</destination>
</country>
<!--
Belize
-->
<country>
<countryName>Belize</countryName>
<population>249183</population>
<continent>South America</continent>
<topDestination>
<destinationName>San Pedro</destinationName>
<description>San Pedro is an island off the coast of Belize</description>
</topDestination>
<destination>
<destinationName>Belize City</destinationName>
<description>Belize City is the former capital of Belize</description>
<websiteURL>www.belizecity.com</websiteURL>
</destination>
<destination>
<destinationName>Xunantunich</destinationName>
<description>Mayan ruins</description>
<streetAddress>4 High Street</streetAddress>
<telephoneNumber>011770801</telephoneNumber>
</destination>
</country>
</tourGuide>
```
`<small>`{=html}**Exhibit 4-3: XML Document for a one-to-one
relationship**`</small>`{=html}
## Summary
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Schema designers may place restrictions on the length of elements and on how the processor handles white space. Schema designers may also specify fixed or default values for an element. Order indicators can be used to specify the order in which elements must appear in an XML document.
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## Exercises
\
## Answers
|
# XML - Managing Data Exchange/The many-to-many relationship
+----------------------------------------------------------------------+
| **Learning objectives** |
| |
| - Learn different methods to represent a many-to-many relationship |
| using XML |
| - Create XML schemas using the \"Eliminate\" and \"ID/IDREF\" |
| methods to structure content based on a many-to-many |
| relationship |
| - Create the corresponding XML documents for the \"Eliminate\" and |
| \"ID/IDREF\" methods |
| - Learn to use the key function in an XML stylesheet to format |
| data structured with the \"ID/IDREF\" method |
| - Create a basic XML stylesheet that incorporates the key function |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
## Introduction
In the previous chapters, you learned how to use XML to structure and
format data based on one-to-one and one-to-many relationships. Because
XML provides the means to model data using hierarchical parent-child
relationships, the one-to-one and one-to-many relationships are
relatively simple to represent in XML. However, this hierarchical
parent-child structure is difficult to use to model the many-to-many
relationship, a common relationship between entities in many situations.
In this chapter, we will explore the pros and cons of a few methods that
are used to model a many-to-many relationship in XML; these methods
offer compromises in overcoming the problems that arise when applying
this relationship to XML. In particular, we will see examples of how to
model the many-to-many relationship using two different methods,
\"Eliminate\" and \"ID/IDREF.\" Additionally, in the XML stylesheet, we
will learn how to implement the key function to display the data that
was modeled using the \"ID/IDREF\" method.
## Problems: many-to-many relationship
In XML, the parent-child relationship is most commonly used to represent
a relationship. This can easily be applied to a one-to-one or
one-to-many relationship. A many-to-many relationship is not supported
directly by XML; the parent-child relationship will not work as each
element may only have a single parent element. There are couple of
possible solutions to get around this.
## Solutions: many-to-many relationship
### Eliminate
**Create XML documents that eliminate the need for a many-to-many
relationship**\
By limiting the extent of information that is conveyed, you can get
around the need for a many-to-many relationship. Instead of trying to
have one XML document encompass all of the information, separate the
information where one document describes only one of the entities that
participates in the many-to-many relationship. Using our tourGuide
relationship for example, one way for us to accomplish this would be
creating a separate XML document for each hotel. The relationship with
amenity would ultimately then become a one-to-many. This method is more
suitable for situations in which the scope of data exchange can be
limited to subsets of data. However, using this method for more broadly
scoped data exchange, you may repeat data several times, especially if
there are many attributes. To avoid this redundancy, use the ID/IDREF
method.
### ID/IDREF
**Represent the many-to-many relationship using unique identifiers**\
Although not the most user-friendly way to handle this problem, one way
of getting around the many-to-many relationship is by creating keys that
would uniquely identify each entity. To do this, an element with ID or
IDREF attributes-types must be specified within the XML schema. To use a
data modeling analogy, ID is similar to the primary key, and IDREF is
similar to the foreign key.
## Many-to-many relationship data model
**Exhibit 1: Data model for a m:m relationship**\
!Data Model for a m:m
relationship
The relationship reads, *a hotel can have many amenities, and an amenity
can exist at many hotels*.
As you will notice, in order to represent a many-to-many relationship,
two entities were added. The middle entity is necessary for the data
model to represent an associative entity that stores data about the
relationship between hotel and amenity. Using our Tour Guide example,
\"Amenity\" was added to represent a list of possible amenities that a
hotel can possess.
The following examples illustrate methods to represent a many-to-many
relationship in XML.
## Eliminate: sample solution
In this example, the many-to-many relationship has been converted to a
one-to-many relationship.
### XML schema
**Exhibit 2: XML schema for \"Eliminate\" method**
``` XML
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Document : amenity1.xsd
Created on : February 4, 2006
Author : Dr. Rick Watson
-->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<xsd:element name="hotelGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:simpleType name="emailAddressType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:complexType name="hotelDetails">
<xsd:sequence>
<xsd:element name="hotelPicture"/>
<xsd:element name="hotelName" type="xsd:string"/>
<xsd:element name="streetAddress" type="xsd:string"/>
<xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
<xsd:element name="telephoneNumber" type="xsd:string"/>
<xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>
<xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
<xsd:element name="hotelRating" type="xsd:integer" default="0"/>
<xsd:element name="lowerPrice" type="xsd:positiveInteger"/>
<xsd:element name="upperPrice" type="xsd:positiveInteger"/>
<xsd:element name="amenity" type="amenityValue" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="amenityValue">
<xsd:sequence>
<xsd:element name="amenityType" type="xsd:string"/>
<xsd:element name="amenityOpenHour" type="xsd:time"/>
<xsd:element name="amenityCloseHour" type="xsd:time"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
```
### XML document
**Exhibit 3: XML document for \"Eliminate\" method**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : amenity1.xml
Created on : February 4, 2006
Author : Dr. Rick Watson
-->
<hotelGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="amenity1.xsd">
<hotel>
<hotelPicture/>
<hotelName>Narembeen Hotel</hotelName>
<streetAddress>Churchill Street</streetAddress>
<telephoneNumber>+61 (08) 9064 7272</telephoneNumber>
<emailAddress>[email protected]</emailAddress>
<hotelRating>1</hotelRating>
<lowerPrice>50</lowerPrice>
<upperPrice>100</upperPrice>
<amenity>
<amenityType>Restaurant</amenityType>
<amenityOpenHour>06:00:00</amenityOpenHour>
<amenityCloseHour>22:00:00 </amenityCloseHour>
</amenity>
<amenity>
<amenityType>Pool</amenityType>
<amenityOpenHour>06:00:00</amenityOpenHour>
<amenityCloseHour>18:00:00 </amenityCloseHour>
</amenity>
<amenity>
<amenityType>Complimentary Breakfast</amenityType>
<amenityOpenHour>07:00:00</amenityOpenHour>
<amenityCloseHour>10:00:00 </amenityCloseHour>
</amenity>
</hotel>
<hotel>
<hotelPicture/>
<hotelName>Narembeen Caravan Park</hotelName>
<streetAddress>Currall Street</streetAddress>
<telephoneNumber>+61 (08) 9064 7308</telephoneNumber>
<emailAddress>[email protected]</emailAddress>
<hotelRating>1</hotelRating>
<lowerPrice>20</lowerPrice>
<upperPrice>30</upperPrice>
<amenity>
<amenityType>Pool</amenityType>
<amenityOpenHour>10:00:00</amenityOpenHour>
<amenityCloseHour>22:00:00 </amenityCloseHour>
</amenity>
</hotel>
</hotelGuide>
```
## ID/IDREF: sample solution
To avoid redundancy, we create a separate element, \"amenity,\" which is
included at the top of the schema along with \"hotel.\" Remember, the
data types ID and IDREF are synonymous with the primary key and foreign
key, respectively. For every foreign key (IDREF), there must be a
matching primary key (ID). Note that the IDREF data type has to be an
alphanumeric string.
The following example illustrates the ID/IDREF approach. Notice that the
ID for the amenity pool is defined as \"k1,\" and every hotel with a
pool as an amenity references \"k1,\" using IDREF. If the IDREF does not
match any ID, then the document will not validate.
### XML schema
**Exhibit 4: XML schema for \"ID/IDREF\" method**
``` XML
<?xml version="1.0" encoding="UTF-8" ?>
<!--
Document : amenity2.xsd
Created on : February 4, 2006
Author : Dr. Rick Watson
-->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<xsd:element name="hotelGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="hotel" type="hotelDetails" minOccurs="1" maxOccurs="unbounded"/>
<xsd:element name="amenity" type="amenityList" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:simpleType name="emailAddressType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\w+\W*\w*@{1}\w+\W*\w+.\w+.*\w*"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:complexType name="hotelDetails">
<xsd:sequence>
<xsd:element name="hotelPicture"/>
<xsd:element name="hotelName" type="xsd:string"/>
<xsd:element name="streetAddress" type="xsd:string"/>
<xsd:element name="postalCode" type="xsd:string" minOccurs="0"/>
<xsd:element name="telephoneNumber" type="xsd:string"/>
<xsd:element name="emailAddress" type="emailAddressType" minOccurs="0"/>
<xsd:element name="websiteURL" type="xsd:anyURI" minOccurs="0"/>
<xsd:element name="hotelRating" type="xsd:integer" default="0"/>
<xsd:element name="lowerPrice" type="xsd:positiveInteger"/>
<xsd:element name="upperPrice" type="xsd:positiveInteger"/>
<xsd:element name="amenities" type="amenityDesc" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="amenityDesc">
<xsd:sequence>
<xsd:element name="amenityIDREF" type="xsd:IDREF"/>
<xsd:element name="amenityOpenHour" type="xsd:time"/>
<xsd:element name="amenityCloseHour" type="xsd:time"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="amenityList">
<xsd:sequence>
<xsd:element name="amenityID" type="xsd:ID"/>
<xsd:element name="amenityType" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
```
### XML document
**Exhibit 5: XML document for \"ID/IDREF\" method**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : amenity2.xml
Created on : February 4, 2006
Author : Dr. Rick Watson
-->
<?xml-stylesheet href="amenity2.xsl" type="text/xsl" media="screen"?>
<hotelGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="amenity2.xsd">
<hotel>
<hotelPicture/>
<hotelName>Narembeen Hotel</hotelName>
<streetAddress>Churchill Street</streetAddress>
<telephoneNumber>+61 (08) 9064 7272</telephoneNumber>
<emailAddress>[email protected]</emailAddress>
<hotelRating>1</hotelRating>
<lowerPrice>50</lowerPrice>
<upperPrice>100</upperPrice>
<amenities>
<amenityIDREF>k2</amenityIDREF>
<amenityOpenHour>06:00:00</amenityOpenHour>
<amenityCloseHour>22:00:00 </amenityCloseHour>
</amenities>
<amenities>
<amenityIDREF>k1</amenityIDREF>
<amenityOpenHour>06:00:00</amenityOpenHour>
<amenityCloseHour>18:00:00 </amenityCloseHour>
</amenities>
<amenities>
<amenityIDREF>k5</amenityIDREF>
<amenityOpenHour>07:00:00</amenityOpenHour>
<amenityCloseHour>10:00:00 </amenityCloseHour>
</amenities>
</hotel>
<hotel>
<hotelPicture/>
<hotelName>Narembeen Caravan Park</hotelName>
<streetAddress>Currall Street</streetAddress>
<telephoneNumber>+61 (08) 9064 7308</telephoneNumber>
<emailAddress>[email protected]</emailAddress>
<hotelRating>1</hotelRating>
<lowerPrice>20</lowerPrice>
<upperPrice>30</upperPrice>
<amenities>
<amenityIDREF>k1</amenityIDREF>
<amenityOpenHour>10:00:00</amenityOpenHour>
<amenityCloseHour>22:00:00 </amenityCloseHour>
</amenities>
</hotel>
<amenity>
<amenityID>k1</amenityID>
<amenityType>Pool</amenityType>
</amenity>
<amenity>
<amenityID>k2</amenityID>
<amenityType>Restaurant</amenityType>
</amenity>
<amenity>
<amenityID>k3</amenityID>
<amenityType>Fitness room</amenityType>
</amenity>
<amenity>
<amenityID>k4</amenityID>
<amenityType>Complimentary breakfast</amenityType>
</amenity>
<amenity>
<amenityID>k5</amenityID>
<amenityType>in-room data port</amenityType>
</amenity>
<amenity>
<amenityID>k6</amenityID>
<amenityType>Water slide</amenityType>
</amenity>
</hotelGuide>
```
### Key function: XML stylesheet
In order to set up an XML stylesheet using the ID/IDREF method for a
many-to-many relationship, the key function should be used. In the
stylesheet, the \<xsl:key\> element specifies the index, which is used
to return a node-set from the XML document.
A key consists of the following:
1\. the node that has the key\
2. the name of the key\
3. the value of a key
The following XML stylesheet illustrates how to use the key function to
present content that is structured in a many-to-many relationship.
### XML stylesheet
**Exhibit 6: XML stylesheet for \"ID/IDREF\" method**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : amenity2.xsl
Created on : February 4, 2006
Author : Dr. Rick Watson
-->
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="amList" match="amenity" use="amenityID"/>
<xsl:output method="html"/>
<xsl:template match="/">
<html>
<head>
<title>Hotel Guide</title>
</head>
<body>
<h2>Hotels</h2>
<xsl:apply-templates select="hotelGuide"/>
</body>
</html>
</xsl:template>
<xsl:template match="hotelGuide">
<xsl:for-each select="hotel">
<xsl:value-of select="hotelName"/>
<br/>
<xsl:for-each select="amenities">
<xsl:value-of select="key('amList',amenityIDREF)/amenityType"/>
<xsl:text> </xsl:text>
<xsl:value-of select="amenityOpenHour"/> -
<xsl:value-of select="amenityCloseHour"/>
<BR/>
</xsl:for-each>
<br/>
<br/>
</xsl:for-each>
<br/>
</xsl:template>
</xsl:stylesheet>
```
## Expedia.de: XML and affiliate marketing
+----------------------------------------------------------------------+
| Expedia.de is the German subsidiary of expedia.com, the |
| internet-based travel agency headquartered in Bellevue, Washington, |
| USA. It offers its customers the booking of airline tickets, car |
| rentals, vacation packages and various other attractions and |
| services via its website and by phone. Its websites attract more |
| than 70 million visitors each month. Currently expedia.com employs |
| 4.600 employees serving customers in the United States, Canada, the |
| UK, France, Germany, Italy, and Australia. |
| |
| For marketing purposes expedia.de set up an affiliate marketing |
| program. Affiliate marketing is a way to reach potential customers |
| without any financial risk for the company intending to advertise |
| (merchant). The merchant gives website owners, which are called |
| affiliates, the opportunity to refer to the merchant page, offering |
| commission-based monetary rewards as incentives. In the case of |
| Expedia.de the affiliate partners receive a commission every time |
| users from their websites book travel on expedia.de. So the |
| affiliates can concentrate on selling and the merchant takes care of |
| handling the transactions. |
| |
| To ease the business of the affiliate partners -- and of course to |
| make the program more attractive -- Expedia.de offers its partners a |
| service called xmlAdEd. xmlAdEd is a service providing current |
| product information on using XML. Affiliates using this service are |
| able to request more than 8 million of travel offerings in XML |
| format via HTTP-request. The data is updated several times a day. In |
| the HTTP-request you can set certain parameters such as location, |
| price, airport code, \... |
| |
| The use of XML in this case gives the affiliates several |
| advantages:\ |
| - Efficient and flexible processing of the data because of |
| separation of structure, content and style.\ |
| - Platform-independent processing of the data.\ |
| - Lossless conversion into other file formats.\ |
| - Easy integration in their websites.\ |
| - Possibility to create an own web shop in individual design |
| |
| By providing their affiliates product information in XML, expedia.de |
| not only eases the business of their partners, but also ensures that |
| customers receive consistent, up-to-date information on their |
| services. |
+----------------------------------------------------------------------+
### Summary
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
When describing a many-to-many relationship in XML, there are a few solutions available for designers to use. In choosing how to represent the many-to-many relationship, the designer not only must consider the most efficient way to represent the information, but also the audience for which the document is intended and how the document will be used.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## References
<http://www-128.ibm.com/developerworks/xml/library/x-xdm2m.html>
<http://www.w3.org/TR/xslt#key>
## Exercises
## Answers
|
# XML - Managing Data Exchange/Recursive relationships
+----------------------------------------------------------------------+
| `<font size=4>`{=html}`<b>`{=html}Learning |
| objectives`</b>`{=html}`</font>`{=html}\ |
| |
| - Understand the concept of a recursive relationship |
| - Create a schema for a one-to-one recursive relationship |
| - Create a schema for a one-to-many recursive relationship |
| - Create a schema for a many-to-many recursive relationship |
| - Define a unique identifier in a schema |
| - Create a primary key/foreign key relationship |
+----------------------------------------------------------------------+
\
\
## Introduction
Recursive relationships are an interesting and more complex concept than
the relationships you have seen in the previous chapters. A recursive
relationship occurs when there is a relationship between an entity and
itself. For example, a one-to-many recursive relationship occurs when an
employee is the manager of other employees. The employee entity is
related to itself, and there is a one-to-many relationship between one
employee (the manager) and many other employees (the people who report
to the manager). Because of the more complex nature of these
relationships, we will need slightly more complex methods of mapping
them to a schema and displaying them in a style sheet.
## The one-to-one recursive relationship
Continuing with the tour guide model, we will develop a schema that
shows cities that have hosted the Olympics and the previous host city.
Since the previous host is another city and only one city can be the
previous host this is a one to one recursive relationship.
:
: !Recursive
### host.xsd (XML schema for a one-to-one recursive model)
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:element name="cities">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="city" type="cityType" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="cityType">
<xsd:sequence>
<xsd:element name="cityID" type="xsd:ID"/>
<xsd:element name="cityName" type="xsd:string"/>
<xsd:element name="cityCountry" type="xsd:string"/>
<xsd:element name="cityPop" type="xsd:integer"/>
<xsd:element name="cityHostYr" type="xsd:integer"/>
<xsd:element name="cityPreviousHost" type="xsd:IDREF" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
```
**`<SMALL>`{=html}Exhibit 1: XML schema for Host City
Entity`</SMALL>`{=html}**
### host.xml (XML document for a one-to-one recursive model)
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<cities xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:noNamespaceSchemaLocation='host.xsd'>
<city>
<cityID>c1</cityID>
<cityName>Atlanta</cityName>
<cityCountry>USA</cityCountry>
<cityPop>4000000</cityPop>
<cityHostYr>1996</cityHostYr>
</city>
<city>
<cityID>c2</cityID>
<cityName>Sydney</cityName>
<cityCountry>Australia</cityCountry>
<cityPop>4000000</cityPop>
<cityHostYr>2000</cityHostYr>
<cityPreviousHost>c1</cityPreviousHost>
</city>
<city>
<cityID>c3</cityID>
<cityName>Athens</cityName>
<cityCountry>Greece</cityCountry>
<cityPop>3500000</cityPop>
<cityHostYr>2004</cityHostYr>
<cityPreviousHost>c2</cityPreviousHost>
</city>
</cities>
```
`<SMALL>`{=html}**Exhibit 2: XML Document for Olympic Host
City**`</SMALL>`{=html}
## The one-to-many recursive relationship
A hypothetical sports team is divided into squads with each squad having
a captain. Every person on the team is a player, regardless of whether
they are a squad captain. Since a squad captain is a player, this
situation meets the definition of a recursive relationship---a squad
captain is also a player and has a one-to-many relationship with the
other players. This is a one-to-many recursive relationship because one
captain has many players under him/her. See the example below for how to
model the relationship.
### team.xsd (XML schema for a one-to-many recursive model)
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<xsd:element name="team">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="player" type="playerType" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="playerType">
<xsd:sequence>
<xsd:element name="playerID" type="xsd:ID"/>
<xsd:element name="playerName" type="xsd:string"/>
<xsd:element name="playerCap" type="playerC" minOccurs="0" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="playerC">
<xsd:sequence>
<xsd:element name="memberOf" type="xsd:IDREF"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
```
`<SMALL>`{=html}**Exhibit 3: XML schema for Team
Entity**`</SMALL>`{=html}
### team.xml (XML document for a one-to-many recursive model)
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<team xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xsi:noNamespaceSchemaLocation='Recursive1toMSchema.xsd'>
<player>
<playerID>c1</playerID>
<playerName>Tommy Jones</playerName>
<playerCap>
<memberof>c3</memberof>
</playerCap>
</player>
<player>
<playerID>c2</playerID>
<playerName>Eddie Thomas</playerName>
<playerCap>
<memberof>c3</memberof>
</playerCap>
</player>
<player>
<playerID>c3</playerID>
<playerName>Sean McCombs</playerName>
</player>
<player>
<playerID>c4</playerID>
<playerName>Patrick O’Shea</playerName>
<playerCap>
<memberof>c3</memberof>
</playerCap>
</player>
</team>
```
`<SMALL>`{=html}**Exhibit 4: XML Document for Team
Entity**`</SMALL>`{=html}
#### Natural one-to-many recursive structure
A more natural approach for most one-to-many recursive relationships is
to use XML\'s hierarchical nature to directly represent the heirarchy.
Consider Locations:
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<location type="country">
<name>USA</name>
<sub-locations>
<location type="state">
<name>Ohio</name>
<sub-locations>
<location type="city"><name>Akron</name></location>
<location type="city"><name>Columbus</name></location>
</sub-location>
</location>
</sub-locations>
</location>
```
## The many-to-many recursive relationship
Think you\'re getting a feel for recursive relationships yet? Well,
there is still the third and final relationship to add to your
repertoire --- the many-to-many recursive. A common example of a
many-to-many recursive relationship is when one item can be comprised of
many items of the same data type as itself, and each of those sub-items
may belong to another parent item of the same data type. Sound
confusing? Let\'s look at the example of a product that can consist of a
single item or multiple items (i.e., a packaged product). The example
below describes tourist products that can be packaged together to create
a new product.
### product.xsd (XML schema for a many-to-many recursive model)
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<xsd:element name="products">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="product" type="prodType" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="prodType">
<xsd:sequence>
<xsd:element name="prodID" type="xsd:ID"/>
<xsd:element name="prodName" type="xsd:string"/>
<xsd:element name="prodCost" type="xsd:decimal" minOccurs="0"/>
<xsd:element name="prodPrice" type="xsd:decimal"/>
<xsd:element name="components" type="componentsType" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="componentsType">
<xsd:sequence>
<xsd:element name="component" type="xsd:IDREF"/>
<xsd:element name="componentqty" type="xsd:integer"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
```
`<SMALL>`{=html}**Exhibit 5: XML schema for Product
Entity**`</SMALL>`{=html}
### product.xml (XML document for a many-to-many recursive model)
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" href="product.xsl"?>
<products xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="product.xsd">
<product>
<prodID>p1000</prodID>
<prodName>Animal photography kit</prodName>
<prodPrice>725</prodPrice>
<components>
<component>p101</component>
<componentqty>1</componentqty>
</components>
</product>
<product>
<prodID>p101</prodID>
<prodName>Camera case</prodName>
<prodCost>150</prodCost>
<prodPrice>300</prodPrice>
</product>
</products>
```
`<SMALL>`{=html}**Exhibit 6: XML Document for Product
Entity**`</SMALL>`{=html}
## Summary
When the child has the same type of data as its parent in a parent-child
type data relationship, this is a sign of the existence of a recursive
relationship. The `<b>`{=html}xsd:ID`</b>`{=html} and
`<b>`{=html}xsd:IDREF`</b>`{=html} elements can be used in a schema to
create primary key-foreign key values in an XML document.
## Exercises
\
## Answers
**External Links**
- XML Schema
|
# XML - Managing Data Exchange/Data schemas
------------------------------------------------------------------------
+----------------------------------+----------------------------------+
| `<span style="font | Initiated by:\ |
| -size:large;">`{=html}**Learning | \ |
| objectives**`</span>`{=html}\ | |
| \* | ```{=html} |
| `<span st | <div class="center"> |
| yle="font-size:medium;">`{=html} | ``` |
| Overview of Data | `<big>`{=html}`<big>`{=html}The |
| Schemas`</span>`{=html} | University of |
| | Georgi |
| - `<span st | a`</big>`{=html}`</big>`{=html}\ |
| yle="font-size:medium;">`{=html} | \ |
| Starting your schema the | `<big>`{=html}`<big>`{= |
| right way`</span>`{=html} | html}`<big>`{=html}`<span style= |
| - `<span st | "color:#990000;">`{=html}**Terry |
| yle="font-size:medium;">`{=html} | College of |
| Entities in | Business |
| general`</span>`{=html} | **`</span>`{=html}`</big>`{=html |
| - `<span st | }`</big>`{=html}`</big>`{=html}\ |
| yle="font-size:medium;">`{=html} | \ |
| The Parent Child | `<big> |
| Structure`</span>`{=html} | `{=html}`<big>`{=html}Department |
| - `<span st | of Management Information |
| yle="font-size:medium;">`{=html} | Syste |
| Attributes and | ms`</big>`{=html}`</big>`{=html} |
| Restrictions`</span>`{=html} | |
| - `<span st | ```{=html} |
| yle="font-size:medium;">`{=html} | </div> |
| Ending your schema the right | ``` |
| way`</span>`{=html} | |
+----------------------------------+----------------------------------+
## Introduction
Data schemas are the foundation of all XML pages. They define objects,
their relationships, their attributes, and the structure of the data
model. Without them, XML documents would not exist. In this chapter, you
will come to understand the purpose of XML data schemas, their intricate
parts, and how to utilize them. Also, examples will be included for you
to copy when creating your own data schema, making your job a lot
easier. At the bottom of this Web page a whole Schema has been included,
from which parts have been included in the different sections throughout
this chapter. Refer to it if you would like to see how the whole Schema
works as one.
## Overview of Data Schemas
The data schema, all technicalities aside, is the data model with which
all the XML information is conveyed. It has a hierarchy structure
starting with a root element (to be explained later) and goes all the
way down to cover even the most minute detail of the model with detailed
steps in between. Data schemas have two main parts, the
`<i>`{=html}entities`</i>`{=html} and their
`<i>`{=html}relationships`</i>`{=html}. The entities contained in a data
schema represent objects from the model. They have unique identifiers,
attributes, and names for what kind of object they are. The
relationships in the schema represent the relationships between the
objects, simple enough. Relationships can be one to one, one to many,
many to many, recursive, and any other kind you could find in a data
model. Now we will begin to create our own data schema.
## Starting your schema the right way
All schemas begin the same way, no matter what type of objects they
represent. The first line in _every_ Schema is
this declaration:
``` xml
<?xml version="1.0" encoding="UTF-8"?>
```
`<small>`{=html}Exhibit 1: XML Declaration `</small>`{=html}
Exhibit 1 simply tells the browser or whatever file/program accessing
this schema that it is an XML file and uses the encoding structure
\"UTF-8\". You can copy this to use to start your own XML file. Next
comes the Namespace declaration:
``` xml
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
```
`<small>`{=html}Exhibit 2: Namespace Declaration `</small>`{=html}
Namespaces are basically dictionaries containing definitions of most of
the coding in the schema. For example, when creating a schema, if you
declare an object to be of type \"String\", the definition of the type
\"String\" is contained in the Namespace along with all of its
attributes. This is true for most of the code you write. If you have
made or seen other schemas, most of the code is prefaced by \"xsd:\". A
good example is something like \"xsd:sequence\" or \"xsd:complexType\".
sequence and complexType are both objects defined in the Namespace that
has been linked to the prefix \"xsd\". In fact, you could theoretically
name the default Namespace anything, as long as you referenced it the
same way throughout the Schema. The most common Namespace which contains
most of the XML objects is
`<i>`{=html}http://www.w3.org/2001/XMLSchema`</i>`{=html}. Now onto
Exhibit 2.
The first part lets any file/program know that this file is a schema.
Pretty easy to understand. Like the XML declaration, this is universal
to XML schemas and you can use it in yours. The second part is the
actual Namespace declaration; xmlns stands for **XML**
**N**ame**S**pace. This defines the Schema\'s default Namespace and is
usually the one given in the code. Again, I would recommend using this
code to start your Schemas. The last part is difficult to understand,
but here is a pretty detailed explanation. Using \"unqualified\" is most
applicable until you get to some really complicated code.
## Entities in general
Entities are basically the objects a Schema is created to represent. As
stated before, they have attributes and relationships. We will now go
much further into explaining exactly what they are and how to write code
for them.
There are two types of Entities: **simpleType** and **complexType**. A
simpleType object has one value associated with it. A string is a
perfect example of a simpleType object as it only contains the value of
the string. Most simpleTypes used will be defined in the default
Namespace; however, you can define your own simpleType at the bottom of
the Schema (this will be brought up in the restrictions section).
Because of this, the only objects you will most often need to include in
your Schema are complexTypes. A complexType is an object with more than
one attribute associated with it, and it may or may not have a child
elements attached to it. Here is an example of a complexType object:
``` xml
<xsd:complexType name="GenreType">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="movie" type="MovieType" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
```
`<small>`{=html}Exhibit 3: The complexType Element `</small>`{=html}
This code begins with the declaration of a complexType and its name.
When other entities refer to it, such as a parent element, it will refer
to this name. The 2nd line begins the sequence of attributes and child
elements, which are all declared as an \"element\". The elements are
declared as elements with the 1st part of the line of code, and their
name to which other documents will refer is included as the \"name\" as
the 2nd part. After the first two declarations comes the \"type\"
declaration. Note that for the *name* and *description* elements their
type is \"xsd:string\" showing that the type string is defined in the
Namespace \"xsd\". For the *movie* element, the type is \"MovieType\",
and because there is no Namespace before \"MovieType\", it is assumed
that this type is included in this Schema. (it could refer to a type
defined in another Schema if the other Schema was included at the top of
the Schema. don\'t worry about that now) \"minOccurs\" and \"maxOccurs\"
represents the relationship between Genre\'s and MovieTypes.
\"minOccurs\" can be either 0 or an arbitrary number, depending only on
the data model. \"maxOccurs\" can be either 1 (a one to one
relationship), an arbitrary number (a one to many relationship), or
\"unbounded\" (a one to many relationship).
For each schema, there must be one `<b>`{=html}root
element`</b>`{=html}. This entity contains every other entity underneath
it in the hierarchy. For instance, when creating a schema to include a
list of movies, the root element would be something like MovieDatabase,
or maybe MovieCollection, just something that would logically contain
all the other objects (like genre, movie, actor, director, plotline,
etc.) It is always started with this line of code:
`<xsd:element name="xxx">`{=html} showing that it is the root element
and then goes on as a normal complexType. All other objects will begin
with either simpleType or complexType. Here is sample code for a
MovieDatabase root element:
``` xml
<xsd:element name="MovieDatabase">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Genre" type="GenreType" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
```
`<small>`{=html}Exhibit 4: The Root Element `</small>`{=html}
This represents a MovieDatabase where the child element of MovieDatabase
is a Genre. From there it goes onto movie, etc. We will continue to use
this example help you better understand.
## The Parent / Child Relationship
The Parent / Child Relationship is a key topic in Data Schemas. It
represents the basic structure of the data model\'s hierarchy by clearly
laying out the top down configuration. Look at this piece of code which
shows how movies have actors associated with them:
``` xml
<xsd:complexType name="MovieType">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="actor" type="ActorType" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ActorType">
<xsd:sequence>
<xsd:element name="lname" type="xsd:string"/>
<xsd:element name="fname" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
```
`<small>`{=html}Exhibit 5: The Parent/Child
Relationship`</small>`{=html}
Within each MovieType, there is an element named \"actor\" which is of
\"ActorType\". When the XML document is populated with information, the
surrounding tags for actor will be `<actor>`{=html}`</actor>`{=html} and
not `<ActorType>`{=html}`</ActorType>`{=html}. To keep your Schema
flowing smoothly and without error, the *type* field in the Parent
Element will always equal the *name* field in the declaration of the
complexType Child Element.
## Attributes and Restrictions
An attribute of an entity is a simpleType object in that it only
contains one value.
`<xsd:element name="lname" type="xsd:string"/>`{=html} is a good example
of an attribute. It is declared as an element, has a name associated
with it, and has a type declaration. Located in the appendix of this
chapter is a long list of simpleTypes built into the default Namespace.
Attributes are incredibly simple to use, until you try and restrict
them.
In some cases, certain data must abide by a standard to maintain data
integrity. An example of this would be a Social Security number or an
email address. If you have a database of email addresses that sends mass
emails to, you would need all of them to be valid addresses, or else
you\'d get tons of error messages each time you send out that mass
email. To avoid this problem, you can essentially take a known
simpleType and add a restriction to it to better suit your needs. Now
you can do this two ways, but one is simpler and better to use in Data
Schemas. You could edit the simpleType within its declaration in the
Parent Element, but it gets messy, and if another Schema wants to use
it, the code must be written again. The better way to do it is to list a
new type at the bottom of the Schema that edits a previously known
simpleType. Here is an example of this with a Social Security number:
``` xml
<xsd:simpleType name="emailaddressType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="[^@]+@[^\.]+\..+"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="ssnType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-\d{2}-\d{4}"/>
</xsd:restriction>
</xsd:simpleType>
```
`<small>`{=html}Exhibit 6: Restriction on a simpleType `</small>`{=html}
This was included in the Schema below the last Child Element and before
the closing `</xsd:schema>`{=html}. The first line declares the
simpleType and gives it a name, \"ssnType\". You could name yours
anything you want, as long as you reference it correctly throughout the
Schema. By doing this, you can use this type anywhere in the Schema, or
anywhere in another Schema, provided the references are correct. The
second line lets the Schema know it is a restricted type and its base is
a string defined in the default Namespace. Basically, this type is a
string with a restriction on it, and the third line is the actual
restriction. It can be one of many types of restrictions, which are
listed in the Appendix of this chapter. This one happens to be of type
\"pattern\". A \"pattern\" means that only a certain sequence of
characters will be allowed in the XML document and is defined in the
`<i>`{=html}value`</i>`{=html} field. This particular one means three
digits, a hyphen, two digits, a hyphen, and four digits. To learn more
about how to use restrictions, follow this
link to the
W3 school\'s section on restrictions.
## Not of little import: Introducing the `<xsd:import>`{=html} tag
The `<xsd:import>`{=html} tag is used to import a schema document and
the namespace associated with the data types defined within the schema
document. This allows an XML schema document to reference a type library
using namespace names (prefixes). Let\'s take a closer look at a simple
XML instance document for a store that uses these multiple namespace
names:
> ``` xml
> <?xml version="1.0" encoding="UTF-8"?>
> <store:SimpleStore xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
> xsi:schemaLocation="http://www.opentourism.org/xmltext/SimpleStore.xsd"
> xmlns:store="http://www.opentourism.org/xmltext/Store"
> xmlns:MGR="http://www.opentourism.org/xmltext/CoreSchema">
> <!-- Note the explicitly defined namespace declarations, the prefix store
> represents data types defined in the
> <code>http://www.opentourism.org/xmltext/Store.xml</code> namespace and the
> prefix MGR represents data types defined in the
> <code>http://www.opentourism.org/xmltext/CoreSchema</code> namespace.
> Also, notice that there is no default namespace declaration – every element
> and attribute must be associated with a namespace (we will see this is
> necessary weh we examine the schema document)
> -->
> <store:Store>
> <MGR:Name xmlns:MGR=" http://www.opentourism.org/xmltext/CoreSchema ">
> <MGR:FirstName>Michael</MGR:FirstName>
> <MGR:MiddleNames>Jay</MGR:MiddleNames>
> <MGR:LastName>Fox</MGR:LastName>
> </MGR:Name>
> <store:StoreName>The Gap</store:StoreName>
> <store:StoreAddress>
> <store:Street>86 Nowhere Ave.</store:Street>
> <store:City>Los Angeles</store:City>
> <store:State>CA</store:State>
> <store:ZipCode>75309</store:ZipCode>
> </store:StoreAddress>
> <!-- More store information would go here. -->
> </store:Store>
> <!-- More stores would go here. -->
> </store:SimpleStore>
> ```
`<small>`{=html}Exhibit 7 XML Instance Document --
1`</small>`{=html}
Let\'s look at the schema document and see how the `<xsd:import>`{=html}
tag was used to import data types from a type library (external schema
document).
> ``` xml
> <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
> xmlns="http://www.opentourism.org/xmltext/Store.xml"
> xmlns:MGR="http://www.opentourism.org/xmltext/CoreSchema"
> targetNamespace="http://www.opentourism.org/xmltext/Store.xml" elementFormDefault="qualified">
> <!-- The prefix MGR is bound to the following namespace name:
> <code>http://www.opentourism.org/xmltext/CoreSchema</code>
> The managerTypeLib.xsd schema document is imported by associating the
> schema with the <code>http://www.opentourism.org/xmltext/CoreSchema</code>
> namespace name, which was bound to the MGR prefix.
> The elementFormDefault attribute has the value ‘qualified' indicating that
> an XML instance document must use qualified names for every element(default
> namespace can not be used)
> -->
> <!-- The target namespace and default namespace are the same -->
> <xsd:import namespace="http://www.opentourism.org/xmltext/CoreSchema"
> schemaLocation="ManagerTypeLib.xsd"/>
> <xsd:element name="SimpleStore">
> <xsd:complexType>
> <xsd:sequence>
> <xsd:element name="Store" type="StoreType" maxOccurs="unbounded"/>
> </xsd:sequence>
> </xsd:complexType>
> </xsd:element>
> <xsd:complexType name="StoreType">
> <xsd:sequence>
> <xsd:element ref="MGR:Name"/>
> <xsd:element name="StoreName" type="xsd:string"/>
> <xsd:element name="StoreAddress" type="StoreAddressType"/>
> </xsd:sequence>
> </xsd:complexType>
> <xsd:complexType name="StoreAddressType">
> <xsd:sequence>
> <xsd:element name="Street" type="xsd:string"/>
> <xsd:element name="City" type="xsd:string"/>
> <xsd:element name="State" type="xsd:string"/>
> <xsd:element name="ZipCode" type="xsd:string"/>
> </xsd:sequence>
> </xsd:complexType>
> </xsd:schema>
> ```
`<small>`{=html}Exhibit 8: XML Schema
\[<http://www.opentourism.org/xmltext/SimpleStore.xsd>`</small>`{=html}
Like the include tag and the redefine tag, the import tag is another
means of incorporating any data types from an external schema document
into another schema document and must occur before any element or
attribute declarations. These mechanisms are important when XML schemas
are modularized and type libraries are being maintained and used in
multiple schema documents.
## When the whole is greater than the sum of its parts: Schema Modularization
Now that we have covered all three methods of incorporating external XML
schemas, let's consider the importance of these mechanisms. As is
typical with most programming code, redundancy is frowned upon; this is
true for custom data type definitions as well. If a custom data type
already exists that can be applied to an element in your schema
document, does it not make sense to use this data type rather than
create it again within your new schema document? Moreover, if you know
that a single data type can be reused for several applications, should
you not have a method for referencing that data type when you need it?
The idea behind modular schemas is to examine what your schema does,
determine what data types are frequently used in one form or another and
develop a type library. As your needs for more complex schemas increase
you can continue to add to your library, reuse data types in your type
library, and redefine those data types as needed. An example of this
reuse would be a schema for customer information -- different
departments would use different schemas as they would need only partial
customer information. However most, if not all, departments would need
some specific customer information, like name and contact information,
which could be incorporated in the individual departmental schema
documents.
Schema modularization is a "best practice". By maintaining a type
library and reusing and redefining types in the type library, you can
help ensure that your XML schema documents don\'t become overwhelming
and difficult to read. Readability is important, because you may not be
the only one using these schemas, and it is important that others can
easily understand your schema documents.
## "Choose, but choose wisely...": Schema alternatives
Thus far in this book we have only discussed XML schemas as defined by
the World Wide Web Consortium (W3C). Yet there are other methods of
defining the data contained within an XML instanced document, but we
will only mention the two most popular and well known alternatives:
Document Type Definition (DTD) and Relax NG Schema.
We will cover DTDs in the next chapter. Relax NG schema is a newer and
has many of the same features that W3C XML schema have; Relax NG also
claims to be simpler, and easier to learn, but this is very subjective.
For more about Relax NG, visit: <http://www.relaxng.org/>
## Appendix
First is the full Schema used in the examples throughout this chapter:
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
elementFormDefault="unqualified">
<xsd:element name="MovieDatabase">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Genre" type="GenreType" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="GenreType">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="movie" type="MovieType" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="MovieType">
<xsd:sequence>
<xsd:element name="name" type="xsd:string"/>
<xsd:element name="rating" type="xsd:string"/>
<xsd:element name="director" type="xsd:string"/>
<xsd:element name="writer" type="xsd:string"/>
<xsd:element name="year" type="xsd:int"/>
<xsd:element name="tagline" type="xsd:string"/>
<xsd:element name="actor" type="ActorType" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="ActorType">
<xsd:sequence>
<xsd:element name="lname" type="xsd:string"/>
<xsd:element name="fname" type="xsd:string"/>
<xsd:element name="gender" type="xsd:string"/>
<xsd:element name="bday" type="xsd:string"/>
<xsd:element name="birthplace" type="xsd:string"/>
<xsd:element name="ssn" type="ssnType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="ssnType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-\d{2}-\d{4}"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:schema>
```
It's time to go back to the beginning...and review all of the schema
data types, elements, and attributes that we have covered thus far (and
maybe a few that we have not). The following tables will detail the XML
data types, elements and attributes that can be used in an XML Schema.
```{=html}
<h4 align="center">
```
Primitive Types
```{=html}
</h4>
```
This is a table with all the primitive types the attributes in your
schema can be.
------------------------ -------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------------------------
**Type** **Syntax** **Legal value example** **Constraining facets**
xsd:anyURI \<xsd:element name = "url" type = "xsd:anyURI" /\> <http://www.w3.com> length, minLength, maxLength, pattern, enumeration, whitespace
xsd:boolean \<xsd:element name = "hasChildren" type = "xsd:boolean" /\> true `<em>`{=html}or `</em>`{=html} false `<em>`{=html}or `</em>`{=html} 1 `<em>`{=html}or `</em>`{=html} 0 pattern and whitespace
xsd:byte \<xsd:element name = "stdDev" type = "xsd:byte" /\> -128 `<em>`{=html}through `</em>`{=html} 127 length, minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, whitespace, and totalDigits
xsd:date \<xsd:element name = "dateEst" type = "xsd:date" /\> 2004-03-15 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:dateTime \<xsd:element name = "xMas" type = "xsd:dateTime" /\> 2003-12-25T08:30:00 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:decimal \<xsd:element name = "pi" type = "xsd:decimal" /\> 3.1415292 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, whitespace, fractionDigits, and totalDigits
xsd:double \<xsd:element name = "pi" type = "xsd:double" /\> 3.1415292 `<em>`{=html}or `</em>`{=html} INF `<em>`{=html}or `</em>`{=html} NaN minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:duration \<xsd:element name = "MITDuration" type = "xsd:duration" /\> P8M3DT7H33M2S
xsd:float \<xsd:element name = "pi" type = "xsd:float" /\> 3.1415292 `<em>`{=html}or `</em>`{=html} INF `<em>`{=html}or `</em>`{=html} NaN minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:gDay \<xsd:element name = "dayOfMonth" type = "xsd:gDay" /\> \-\--11 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:gMonth \<xsd:element name = "monthOfYear" type = "xsd:gMonth" /\> \--02\-- minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:gMonthDay \<xsd:element name = "valentine" type = "xsd:gMonthDay" /\> \--02-14 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:gYear \<xsd:element name = "year" type = "xsd:gYear" /\> 1999 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:gYearMonth \<xsd:element name = "birthday" type = "xsd:gYearMonth" /\> 1972-08 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:ID \<xsd:attribute name=\"id\" type=\"xsd:ID\"/\> id-102 length, minLength, maxLength, pattern, enumeration, and whitespace
xsd:IDREF \<xsd:attribute name=\"version\" type=\"xsd:IDREF\"/\> id-102 length, minLength, maxLength, pattern, enumeration, and whitespace
xsd:IDREFS \<xsd:attribute name=\"versionList\" type=\"xsd:IDREFS\"/\> id-102 id-103 id-100 length, minLength, maxLength, pattern, enumeration, and whitespace
xsd:int \<xsd:element name = "age" type = "xsd:int" /\> 77 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, whitespace, and totalDigits
xsd:integer \<xsd:element name = "age" type = "xsd:integer" /\> 77 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:long \<xsd:element name = "cannelNumber" type = "xsd:int" /\> 214 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace
xsd:negativeInteger \<xsd:element name = "belowZero" type = "xsd:negativeInteger" /\> -123 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, whitespace, and totalDigits
xsd:nonNegativeInteger \<xsd:element name = "numOfchildren" type = "xsd:nonNegativeInteger" /\> 2 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, whitespace, and totalDigits
xsd:nonPositiveInteger \<xsd:element name = "debit" type = "xsd:nonPositiveInteger" /\> 0 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, whitespace, and totalDigits
xsd:positiveInteger \<xsd:element name = "credit" type = "xsd:positiveInteger" /\> 500 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, whitespace, and totalDigits
xsd:short \<xsd:element name = "numOfpages" type = "xsd:short" /\> 476 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, whitespace, and totalDigits
xsd:string \<xsd:element name = "name" type = "xsd:string" /\> Joeseph length, minLength, maxLength, pattern, enumeration, whitespace, and totalDigits
xsd:time \<xsd:element name = "credit" type = "xsd:time" /\> 13:02:00 minInclusive, maxInclusive, minExclusive, maxExclusive, pattern, enumeration, and whitespace,
------------------------ -------------------------------------------------------------------------- ------------------------------------------------------------------------------------------------------------- -----------------------------------------------------------------------------------------------------------------------------
```{=html}
<h4 align="center">
```
Schema Elements\
`<span style="font-size:x-small;">`{=html} ( from
<http://www.w3schools.com/schema/schema_elements_ref.asp>
)`</span>`{=html}
```{=html}
</h4>
```
Here is a list of all the elements which can be included in your
schemas.
+---+----+
| ` | `< |
| < | st |
| s | ro |
| t | ng |
| r | >` |
| o | {= |
| n | ht |
| g | ml |
| > | }E |
| ` | xp |
| { | la |
| = | na |
| h | ti |
| t | on |
| m | `< |
| l | /s |
| } | tr |
| E | on |
| l | g> |
| e | `{ |
| m | =h |
| e | tm |
| n | l} |
| t | |
| ` | |
| < | |
| / | |
| s | |
| t | |
| r | |
| o | |
| n | |
| g | |
| > | |
| ` | |
| { | |
| = | |
| h | |
| t | |
| m | |
| l | |
| } | |
+---+----+
| a | S |
| l | pe |
| l | ci |
| | fi |
| | es |
| | th |
| | at |
| | t |
| | he |
| | c |
| | hi |
| | ld |
| | el |
| | em |
| | en |
| | ts |
| | c |
| | an |
| | ap |
| | pe |
| | ar |
| | in |
| | a |
| | ny |
| | or |
| | de |
| | r. |
| | Ea |
| | ch |
| | c |
| | hi |
| | ld |
| | e |
| | le |
| | me |
| | nt |
| | c |
| | an |
| | o |
| | cc |
| | ur |
| | 0 |
| | or |
| | 1 |
| | ti |
| | me |
+---+----+
| a | S |
| n | pe |
| n | ci |
| o | fi |
| t | es |
| a | t |
| t | he |
| i | t |
| o | op |
| n | -l |
| | ev |
| | el |
| | e |
| | le |
| | me |
| | nt |
| | f |
| | or |
| | sc |
| | he |
| | ma |
| | co |
| | mm |
| | en |
| | ts |
+---+----+
| a | E |
| n | na |
| y | bl |
| | es |
| | t |
| | he |
| | au |
| | th |
| | or |
| | to |
| | ex |
| | te |
| | nd |
| | t |
| | he |
| | X |
| | ML |
| | do |
| | cu |
| | me |
| | nt |
| | wi |
| | th |
| | el |
| | em |
| | en |
| | ts |
| | n |
| | ot |
| | s |
| | pe |
| | ci |
| | fi |
| | ed |
| | by |
| | t |
| | he |
| | sc |
| | he |
| | ma |
+---+----+
| a | E |
| n | na |
| y | bl |
| A | es |
| t | t |
| t | he |
| r | au |
| i | th |
| b | or |
| u | to |
| t | ex |
| e | te |
| | nd |
| | t |
| | he |
| | X |
| | ML |
| | do |
| | cu |
| | me |
| | nt |
| | wi |
| | th |
| | at |
| | tr |
| | ib |
| | ut |
| | es |
| | n |
| | ot |
| | s |
| | pe |
| | ci |
| | fi |
| | ed |
| | by |
| | t |
| | he |
| | sc |
| | he |
| | ma |
+---+----+
| a | S |
| p | pe |
| p | ci |
| I | fi |
| n | es |
| f | i |
| o | nf |
| | or |
| | ma |
| | ti |
| | on |
| | to |
| | be |
| | us |
| | ed |
| | by |
| | t |
| | he |
| | a |
| | pp |
| | li |
| | ca |
| | ti |
| | on |
| | ( |
| | mu |
| | st |
| | go |
| | in |
| | si |
| | de |
| | a |
| | nn |
| | ot |
| | at |
| | io |
| | n) |
+---+----+
| a | D |
| t | ef |
| t | in |
| r | es |
| i | an |
| b | a |
| u | tt |
| t | ri |
| e | bu |
| | te |
+---+----+
| a | D |
| t | ef |
| t | in |
| r | es |
| i | an |
| b | a |
| u | tt |
| t | ri |
| e | bu |
| G | te |
| r | g |
| o | ro |
| u | up |
| p | to |
| | be |
| | us |
| | ed |
| | in |
| | c |
| | om |
| | pl |
| | ex |
| | ty |
| | pe |
| | d |
| | ef |
| | in |
| | it |
| | io |
| | ns |
+---+----+
| c | Al |
| h | lo |
| o | ws |
| i | on |
| c | ly |
| e | o |
| | ne |
| | of |
| | t |
| | he |
| | el |
| | em |
| | en |
| | ts |
| | c |
| | on |
| | ta |
| | in |
| | ed |
| | in |
| | t |
| | he |
| | \< |
| | ch |
| | oi |
| | ce |
| | \> |
| | d |
| | ec |
| | la |
| | ra |
| | ti |
| | on |
| | to |
| | be |
| | p |
| | re |
| | se |
| | nt |
| | wi |
| | th |
| | in |
| | t |
| | he |
| | co |
| | nt |
| | ai |
| | ni |
| | ng |
| | e |
| | le |
| | me |
| | nt |
+---+----+
| c | D |
| o | ef |
| m | in |
| p | es |
| l | ex |
| e | te |
| x | ns |
| C | io |
| o | ns |
| n | or |
| t | re |
| e | st |
| n | ri |
| t | ct |
| | io |
| | ns |
| | on |
| | a |
| | c |
| | om |
| | pl |
| | ex |
| | ty |
| | pe |
| | th |
| | at |
| | co |
| | nt |
| | ai |
| | ns |
| | m |
| | ix |
| | ed |
| | c |
| | on |
| | te |
| | nt |
| | or |
| | el |
| | em |
| | en |
| | ts |
| | on |
| | ly |
+---+----+
| c | D |
| o | ef |
| m | in |
| p | es |
| l | a |
| e | c |
| x | om |
| T | pl |
| y | ex |
| p | ty |
| e | pe |
| | e |
| | le |
| | me |
| | nt |
+---+----+
| d | D |
| o | ef |
| c | in |
| u | es |
| m | te |
| e | xt |
| n | co |
| t | mm |
| a | en |
| t | ts |
| i | in |
| o | a |
| n | sc |
| | he |
| | ma |
| | ( |
| | mu |
| | st |
| | go |
| | in |
| | si |
| | de |
| | a |
| | nn |
| | ot |
| | at |
| | io |
| | n) |
+---+----+
| e | D |
| l | ef |
| e | in |
| m | es |
| e | an |
| n | e |
| t | le |
| | me |
| | nt |
+---+----+
| e | E |
| x | xt |
| t | en |
| e | ds |
| n | an |
| s | ex |
| i | is |
| o | ti |
| n | ng |
| | si |
| | mp |
| | le |
| | Ty |
| | pe |
| | or |
| | c |
| | om |
| | pl |
| | ex |
| | Ty |
| | pe |
| | e |
| | le |
| | me |
| | nt |
+---+----+
| f | S |
| i | pe |
| e | ci |
| l | fi |
| d | es |
| | an |
| | X |
| | Pa |
| | th |
| | ex |
| | pr |
| | es |
| | si |
| | on |
| | th |
| | at |
| | s |
| | pe |
| | ci |
| | fi |
| | es |
| | t |
| | he |
| | v |
| | al |
| | ue |
| | us |
| | ed |
| | to |
| | de |
| | fi |
| | ne |
| | an |
| | id |
| | en |
| | ti |
| | ty |
| | co |
| | ns |
| | tr |
| | ai |
| | nt |
+---+----+
| g | D |
| r | ef |
| o | in |
| u | es |
| p | a |
| | g |
| | ro |
| | up |
| | of |
| | el |
| | em |
| | en |
| | ts |
| | to |
| | be |
| | us |
| | ed |
| | in |
| | c |
| | om |
| | pl |
| | ex |
| | ty |
| | pe |
| | d |
| | ef |
| | in |
| | it |
| | io |
| | ns |
+---+----+
| i | Ad |
| m | ds |
| p | mu |
| o | lt |
| r | ip |
| t | le |
| | s |
| | ch |
| | em |
| | as |
| | wi |
| | th |
| | d |
| | if |
| | fe |
| | re |
| | nt |
| | ta |
| | rg |
| | et |
| | n |
| | am |
| | es |
| | pa |
| | ce |
| | to |
| | a |
| | do |
| | cu |
| | me |
| | nt |
+---+----+
| i | Ad |
| n | ds |
| c | mu |
| l | lt |
| u | ip |
| d | le |
| e | s |
| | ch |
| | em |
| | as |
| | wi |
| | th |
| | t |
| | he |
| | sa |
| | me |
| | ta |
| | rg |
| | et |
| | n |
| | am |
| | es |
| | pa |
| | ce |
| | to |
| | a |
| | do |
| | cu |
| | me |
| | nt |
+---+----+
| k | S |
| e | pe |
| y | ci |
| | fi |
| | es |
| | an |
| | a |
| | tt |
| | ri |
| | bu |
| | te |
| | or |
| | e |
| | le |
| | me |
| | nt |
| | v |
| | al |
| | ue |
| | as |
| | a |
| | k |
| | ey |
| | (u |
| | ni |
| | qu |
| | e, |
| | n |
| | on |
| | -n |
| | ul |
| | la |
| | bl |
| | e, |
| | a |
| | nd |
| | al |
| | wa |
| | ys |
| | pr |
| | es |
| | en |
| | t) |
| | wi |
| | th |
| | in |
| | t |
| | he |
| | co |
| | nt |
| | ai |
| | ni |
| | ng |
| | e |
| | le |
| | me |
| | nt |
| | in |
| | an |
| | in |
| | st |
| | an |
| | ce |
| | do |
| | cu |
| | me |
| | nt |
+---+----+
| k | S |
| e | pe |
| y | ci |
| r | fi |
| e | es |
| f | th |
| | at |
| | an |
| | a |
| | tt |
| | ri |
| | bu |
| | te |
| | or |
| | e |
| | le |
| | me |
| | nt |
| | v |
| | al |
| | ue |
| | co |
| | rr |
| | es |
| | po |
| | nd |
| | to |
| | t |
| | ho |
| | se |
| | of |
| | t |
| | he |
| | s |
| | pe |
| | ci |
| | fi |
| | ed |
| | k |
| | ey |
| | or |
| | un |
| | iq |
| | ue |
| | e |
| | le |
| | me |
| | nt |
+---+----+
| l | D |
| i | ef |
| s | in |
| t | es |
| | a |
| | si |
| | mp |
| | le |
| | ty |
| | pe |
| | e |
| | le |
| | me |
| | nt |
| | as |
| | a |
| | li |
| | st |
| | of |
| | va |
| | lu |
| | es |
+---+----+
| n | D |
| o | es |
| t | cr |
| a | ib |
| t | es |
| i | t |
| o | he |
| n | fo |
| | rm |
| | at |
| | of |
| | n |
| | on |
| | -X |
| | ML |
| | da |
| | ta |
| | wi |
| | th |
| | in |
| | an |
| | X |
| | ML |
| | do |
| | cu |
| | me |
| | nt |
+---+----+
| r | R |
| e | ed |
| d | ef |
| e | in |
| f | es |
| i | si |
| n | mp |
| e | le |
| | a |
| | nd |
| | c |
| | om |
| | pl |
| | ex |
| | ty |
| | pe |
| | s, |
| | g |
| | ro |
| | up |
| | s, |
| | a |
| | nd |
| | a |
| | tt |
| | ri |
| | bu |
| | te |
| | gr |
| | ou |
| | ps |
| | fr |
| | om |
| | an |
| | ex |
| | te |
| | rn |
| | al |
| | sc |
| | he |
| | ma |
+---+----+
| r | D |
| e | ef |
| s | in |
| t | es |
| r | re |
| i | st |
| c | ri |
| t | ct |
| i | io |
| o | ns |
| n | on |
| | a |
| | s |
| | im |
| | pl |
| | eT |
| | yp |
| | e, |
| | si |
| | mp |
| | le |
| | Co |
| | nt |
| | en |
| | t, |
| | or |
| | a |
| | co |
| | mp |
| | le |
| | xC |
| | on |
| | te |
| | nt |
+---+----+
| s | D |
| c | ef |
| h | in |
| e | es |
| m | t |
| a | he |
| | ro |
| | ot |
| | e |
| | le |
| | me |
| | nt |
| | of |
| | a |
| | sc |
| | he |
| | ma |
+---+----+
| s | S |
| e | pe |
| l | ci |
| e | fi |
| c | es |
| t | an |
| o | X |
| r | Pa |
| | th |
| | ex |
| | pr |
| | es |
| | si |
| | on |
| | th |
| | at |
| | s |
| | el |
| | ec |
| | ts |
| | a |
| | s |
| | et |
| | of |
| | el |
| | em |
| | en |
| | ts |
| | f |
| | or |
| | an |
| | id |
| | en |
| | ti |
| | ty |
| | co |
| | ns |
| | tr |
| | ai |
| | nt |
+---+----+
| s | S |
| e | pe |
| q | ci |
| u | fi |
| e | es |
| n | th |
| c | at |
| e | t |
| | he |
| | c |
| | hi |
| | ld |
| | el |
| | em |
| | en |
| | ts |
| | mu |
| | st |
| | ap |
| | pe |
| | ar |
| | in |
| | a |
| | s |
| | eq |
| | ue |
| | nc |
| | e. |
| | Ea |
| | ch |
| | c |
| | hi |
| | ld |
| | e |
| | le |
| | me |
| | nt |
| | c |
| | an |
| | o |
| | cc |
| | ur |
| | fr |
| | om |
| | 0 |
| | to |
| | a |
| | ny |
| | nu |
| | mb |
| | er |
| | of |
| | t |
| | im |
| | es |
+---+----+
| s | Co |
| i | nt |
| m | ai |
| p | ns |
| l | ex |
| e | te |
| C | ns |
| o | io |
| n | ns |
| t | or |
| e | re |
| n | st |
| t | ri |
| | ct |
| | io |
| | ns |
| | on |
| | a |
| | t |
| | ex |
| | t- |
| | on |
| | ly |
| | c |
| | om |
| | pl |
| | ex |
| | ty |
| | pe |
| | or |
| | on |
| | a |
| | si |
| | mp |
| | le |
| | ty |
| | pe |
| | as |
| | c |
| | on |
| | te |
| | nt |
| | a |
| | nd |
| | co |
| | nt |
| | ai |
| | ns |
| | no |
| | el |
| | em |
| | en |
| | ts |
+---+----+
| s | D |
| i | ef |
| m | in |
| p | es |
| l | a |
| e | si |
| T | mp |
| y | le |
| p | ty |
| e | pe |
| | a |
| | nd |
| | s |
| | pe |
| | ci |
| | fi |
| | es |
| | t |
| | he |
| | c |
| | on |
| | st |
| | ra |
| | in |
| | ts |
| | a |
| | nd |
| | i |
| | nf |
| | or |
| | ma |
| | ti |
| | on |
| | a |
| | bo |
| | ut |
| | t |
| | he |
| | va |
| | lu |
| | es |
| | of |
| | at |
| | tr |
| | ib |
| | ut |
| | es |
| | or |
| | t |
| | ex |
| | t- |
| | on |
| | ly |
| | el |
| | em |
| | en |
| | ts |
+---+----+
| u | D |
| n | ef |
| i | in |
| o | es |
| n | a |
| | si |
| | mp |
| | le |
| | ty |
| | pe |
| | as |
| | a |
| | co |
| | ll |
| | ec |
| | ti |
| | on |
| | ( |
| | un |
| | io |
| | n) |
| | of |
| | va |
| | lu |
| | es |
| | fr |
| | om |
| | s |
| | pe |
| | ci |
| | fi |
| | ed |
| | si |
| | mp |
| | le |
| | da |
| | ta |
| | t |
| | yp |
| | es |
+---+----+
| u | D |
| n | ef |
| i | in |
| q | es |
| u | th |
| e | at |
| | an |
| | e |
| | le |
| | me |
| | nt |
| | or |
| | an |
| | a |
| | tt |
| | ri |
| | bu |
| | te |
| | v |
| | al |
| | ue |
| | mu |
| | st |
| | be |
| | un |
| | iq |
| | ue |
| | wi |
| | th |
| | in |
| | t |
| | he |
| | s |
| | co |
| | pe |
+---+----+
```{=html}
<h4 align="center">
```
Schema Restrictions and Facets for data types\
`<span style="font-size:x-small;">`{=html}( from
<http://www.w3schools.com/schema/schema_elements_ref.asp>
)`</span>`{=html}
```{=html}
</h4>
```
Here is a list of all the types of restrictions which can be included in
your schema.
------------------------------------------------ ---------------------------------------------------------------------------------------------------------
`<strong>`{=html}Constraint `</strong>`{=html} `<strong>`{=html}Description `</strong>`{=html}
enumeration Defines a list of acceptable values
fractionDigits Specifies the maximum number of decimal places allowed. Must be equal to or greater than zero
length Specifies the exact number of characters or list items allowed. Must be equal to or greater than zero
maxExclusive Specifies the upper bounds for numeric values (the value must be less than this value)
maxInclusive Specifies the upper bounds for numeric values (the value must be less than or equal to this value)
maxLength Specifies the maximum number of characters or list items allowed. Must be equal to or greater than zero
minExclusive Specifies the lower bounds for numeric values (the value must be greater than this value)
minInclusive Specifies the lower bounds for numeric values (the value must be greater than or equal to this value)
minLength Specifies the minimum number of characters or list items allowed. Must be equal to or greater than zero
pattern Defines the exact sequence of characters that are acceptable
totalDigits Specifies the exact number of digits allowed. Must be greater than zero
whiteSpace Specifies how white space (line feeds, tabs, spaces, and carriage returns) are handled
------------------------------------------------ ---------------------------------------------------------------------------------------------------------
```{=html}
<h4 align="center">
```
Regex\
```{=html}
</h4>
```
Special regular expression (regex) language can be used to construct a
pattern. The regex language in XML Schema is based on Perl\'s regular
expression language. The following are some common notations:
--------------- -----------------------------------------------------------------
. (the period for any character at all
\\d for any digit
\\D for any non-digit
\\w for any word (alphanumeric) character
\\W for any non-word character (i.e. -, +, =)
\\s for any white space (including space, tab, newline, and return)
\\S for any character that is not white space
x\* to have zero or more x\'s
(xy)\* to have zero or more xy\'s
x+ repetition of the x, at least once
x? to have one or zero x\'s
(xy)? To have one or no xy\'s
\[abc\] to include one of a group of values
\[0-9\] to include the range of values from 0 to 9
x{5} to have exactly 5 x\'s (in a row)
x{5,} to have at least 5 x\'s (in a row)
x{5,8} at least 5 but at most 8 x\'s (in a row)
(xyz){2} to have exactly 2 xyz\'s (in a row)
--------------- -----------------------------------------------------------------
+----------------------------------------------------------------------+
| For example, the pattern for validating a Social Security Number is |
| \\d{3}-\\d{2}-\\d{4} |
| |
| The schema code for **emailAddressType** is |
| \\w+\\W\*\\w\*@{1}\\w+\\W\*\\w+.\\w+.\*\\w\* |
+----------------------------------------------------------------------+
| \[w+\] |
+----------------------------------------------------------------------+
| \[W\*\] |
+----------------------------------------------------------------------+
| \[w\*@{1}\] |
+----------------------------------------------------------------------+
| \[w+\] |
+----------------------------------------------------------------------+
| \[W\*\] |
+----------------------------------------------------------------------+
| \[w+.\] |
+----------------------------------------------------------------------+
| \[w+.\*\] |
+----------------------------------------------------------------------+
| \[w\*\] |
+----------------------------------------------------------------------+
| email-address: **answer-my@mail_please.opentourism.org** |
+----------------------------------------------------------------------+
```{=html}
<h4 align="center">
```
Instance Document Attributes\
`<span style="font-size:small;">`{=html}These attributes do NOT need to
be declared within the schemas`</span>`{=html}
```{=html}
</h4>
```
+----------------------+----------------------+----------------------+
| **Attribute** | **Explanation** | **Example** |
+----------------------+----------------------+----------------------+
| xsi:nil | Indicates that a | \<full_name |
| | certain element does | xmlns:xsi= |
| | not have a value or | "http |
| | that the value is | ://www.w3.org/2001/X |
| | unknown. The | MLSchema-instance"\> |
| | element must be set | |
| | to nillable inside | \<first_name\>Mad |
| | the schema | onna\</first_name\>\ |
| | document:\ | \<last_name |
| | \<xsd:element | xsi:nil="true"/\> |
| | name="last_name" | \</full_name\> |
| | type="xsd:string" | |
| | nillable=true"/\> | |
+----------------------+----------------------+----------------------+
| xsi:noNam | Locates the schema | \<radio |
| espaceSchemaLocation | for elements that | xsi:noName |
| | are not in any | spaceSchemaLocation= |
| | namespace | "http:/ |
| | | /www.opentourism.org |
| | | /xmtext/radio.xsd"\> |
| | | \<!---radio stuff |
| | | goes here \-- \> |
| | | \</radio\> |
+----------------------+----------------------+----------------------+
| xsi:schemaLocation | Locates schemas for | \<radio xmlns= |
| | elements and | "ht |
| | attributes that are | tp://www.opentourism |
| | in a specified | .org/xmtext/NS/radio |
| | namespace | xmlns:xsi= |
| | | "ht |
| | | tp://www.w3.org/2001 |
| | | /XMLSchema-instance" |
| | | xsi:schemaLocation= |
| | | "http://www.arc |
| | | hes.uga.eduNS/radio" |
| | | "http:/ |
| | | /www.opentourism.org |
| | | /xmtext/radio.xsd"\> |
| | | \<!---radio stuff |
| | | goes here \-- \> |
| | | \</radio\> |
+----------------------+----------------------+----------------------+
| xsi:type | Can be used in | \<height |
| | instance documents | xsi:type="xsd:decim |
| | to indicate the type | al"\>78.9\</height\> |
| | of an element. | |
+----------------------+----------------------+----------------------+
For more information on XML Schema structures, data types, and tools you
can visit <http://www.w3.org/XML/Schema>.
fr:Programmation XML/XML
Schema pl:XML
Schema
|
# XML - Managing Data Exchange/DTD
A **D**ocument **T**ype **D**efinition is a file that links to an XML
page. It controls what must or can be displayed, what attributes and
their values must/can have and how the XML file should look like. XHTML,
HTML and other markup languages use DTDs to validate their documents.
**Note**: Web browsers accept bad markup in HTML.
## Uses OF DTDs
DTDs are used to store large amounts of data in a custom markup language
that can be used for a specific program or organization. Like schemas
they can have elements, attributes and entities. The only difference is
how it is displayed.
## Prologue
Like in a schema, a DTD has a prolog. It is one line of text.
``` XML
<?xml version="1.0" encoding="UTF-8"?>
```
The question mark is to tell the computer you are giving him an
instruction. The word xml tells him that you are using XML, the version
attribute tells what version of XML you are using and the encoding
attribute tells him how to encode the data (you would use a different
encoding if you wanted to use chinese text).
## \<!ELEMENT\> tag
The element tag is used to display an element of the page, depending on
how you declare it. It can go only on a specific part of the page or
anywhere on the page.
The first element you declare is the root element (in HTML it\'s html).
Let\'s pretend that there was an organization that wanted a bunch of XML
files containing info about each person. They probably would have a root
element of the file named \"person\". The standard for declaring an
element with children elements is
<!ELEMENT elementName (childElement, childElement2, childElement3)>
So the orginization root element tag declaration would be
<!ELEMENT person (firstName, lastName, postalCode, cellNumber, homeNumber, email)>
**Note**: A child element must be declared in a separate element tag to
be valid.
**Note**: The comma is used where you identify the child element is an
occurrence indicator (something that tells the computer how it should
occur). There are other occurrence indicators. We will cover them later
in this chapter.
**Note**: The parentheses define what content type is found in the
bracket. Different content types are found later in this chapter.
Some elements you don\'t want to be linked to specific tags (like a
formatting tag you want to use to highlight important info), you do the
same thing except you don\'t use it as a child element for any element
depending on your needs, you may use the ANY content type, which allows
you to use character data or other tags in your tag, the EMPTY content
type, which looks like \"`<exampleXmlTag />`{=html}\" or #PCDATA for
text.
**Note**:In an element declaration you can combine parentheses with
#PCDATA. It looks like this \<!ELEMENT elementName ( #PCDATA\|
childName). The pipe bar means that you can use text or other tags.
fr:Programmation XML/Définition de Type
Document
|
# XML - Managing Data Exchange/XHTML
------------------------------------------------------------------------
+---------------------------------------------------------+
| `<strong>`{=html}Learning objectives`</strong>`{=html}\ |
| |
| - List the differences between XHTML and HTML |
| - Create a valid, well-formed XHTML document |
| - Convert an existing HTML document to XHTML |
| - Decide when XHTML is more appropriate than HTML |
+---------------------------------------------------------+
In previous chapters, we have learned how to generate HTML documents
from XML documents and XSL stylesheets. In this chapter, we will learn
how to convert those HTML documents into valid XHTML. We will discuss
why XHTML has evolved as a standard and when it should be used.
## The Evolution of XHTML
Originally, Web pages were designed in HTML. Unfortunately most
implementations of this markup language allow all sorts of mistakes and
bad formatting. Major browsers were designed to be forgiving, and poor
code would display with few problems in most cases. This poor code was
often not portable between browsers, e.g. a page would render in
Netscape but not Internet Explorer or vice versa. The accounting for
human error and bad formatting takes an amount of processing power that
small handheld devices might not have. Thus when displaying data on
handhelds, a tiny mistake can crash the device.
XHTML partially mitigates these problems. The processing burden is
reduced by requiring XHTML documents to conform to the much stricter
rules defined in XML. Aside from the stricter rules, HTML 4.01 and XHTML
1.0 are functionally equivalent. If a document breaks XML\'s
well-formedness rules, an XHTML-compliant browser must not render the
page. If a document is well-formed but invalid, an XHTML-compliant
browser may render the page, so a significant number of mistakes still
slip through.
In this chapter, we will examine in detail how to create an XHTML
document.
The biggest problem with HTML from a design standpoint is that it was
never meant to be a graphical design language. The original version of
HTML was intended to structure human readable content (e.g. marking a
section of text as a paragraph), not to format it (e.g. this paragraph
should be displayed in 14pt Arial). HTML has evolved far past its
original purpose and is being stretched and manipulated to cover cases
that the original HTML designers never imagined.
The recommended solution is to use a separate language to describe the
presentation of a group of documents. Cascading Style Sheets (CSS) is a
language used for describing presentation. From version 1.1 of XHTML
upwards web pages must be formatted using CSS or a language with
equivalent capabilites such as XSLT (XSL Transformations). The use of
CSS or XSLT is optional in XHTML 1.0 unless the strict variant is used.
HTML 4.01 supports CSS but not XSLT.
## So What is XHTML?
As you might have guessed, XHTML stands for eXtensible HyperText Markup
Language. It is a cross between HTML and XML. It fulfills two major
purposes that were ignored by HTML:
1. XHTML is a stricter standard than HTML. XHTML documents must be
well-formed just like regular XML. This reduces vagaries and
inconsistency between browsers, because browsers do not have to
decide how to display a badly-formed page. Malformed XHTML is not
allowed.\
**Note 1:** Browsers only enforce well-formedness if the MIME
type is set to `application/xhtml+xml`. If
the MIME type is set to `text/html`, the browser will allow
badly-formed documents. There are a large number of \'XHTML\'
documents on the web that are badly-formed and get away with it
because their MIME type is `text/html`.\
**Note 2:** Browsers are not required to check for validity. See
Invalid XHTML below for an example.
2. XHTML allows for modularization (*m12n*). For different environments
different element and attribute subsets can be defined.
The best thing about XHTML is that it is almost the same as HTML! If you
know how to write an HTML document, it will be very simple for you to
create an XHTML document without too much trouble. The biggest thing
that you must keep in mind is that unlike with HTML, where simple errors
like missing a closing tag are ignored by the browser, XHTML code must
be written according to an exact specification. We will see later that
adhering to these strict specifications actually allows XHTML to be more
flexible than HTML.
## XHTML Document Structure
At a minimum, an XHTML document must contain a DOCTYPE declaration and
four elements: html, head, title, and body:
``` XML
<!DOCTYPE ... >
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="...">
<head>
<title></title>
</head>
<body></body>
</html>
```
The opening `html` tag of an XHTML document must include a namespace
declaration for the XHTML namespace.
The DOCTYPE declaration should appear immediately before the html tag in
an XHTML document. It can follow one of three formats.
### XHTML 1.0 Strict
``` XML
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
```
The Strict declaration is the least forgiving. This is the preferred
DOCTYPE for new documents. Strict documents tend to be streamlined and
clean. All formatting will appear in Cascading Style
Sheets rather than the document itself. Elements
that should be included in the Cascading Style Sheet and not the
document itself include, but are not limited to:
<nowiki><body text="blue">, <u>nderline</u>, <b>old</b>, <i>talics</i>, and <font color="#9900FF" face="Arial" size="+2"></nowiki>
There are also certain instances where your code needs to be nested
within block elements. **Incorrect Example:**
<nowiki><p>I hope that you enjoy</p> your stay.</nowiki>
**Correct Example:**
<nowiki><p>I hope that you enjoy your stay.</p></nowiki>
### XHTML 1.0 Transitional
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
This declaration is intended as a halfway house for migrating legacy
HTML documents to XHTML 1.0 Strict. The W3C encourages
authors to use the Strict DOCTYPE for new documents. (The XHTML 1.0
Transitional DTD
refers readers to the relevant note in the HTML4.01 Transitional
DTD.)
This DOCTYPE does not require CSS for formatting; although, it is
recommended. It generally tolerates inline elements found where
block-level elements are expected.
There are a couple of reasons why you might choose this DOCTYPE for new
documents.
- You require backwards compatibility with browsers that support the
formatting elements of XHTML but do not support CSS. This is a very
small fraction of general users (less than 1%). Many browsers that
don\'t support CSS don\'t support HTML 4.0 or XHTML either. However,
it may be useful on a corporate intranet that has a larger than
normal fraction of very old (pre-2000) browsers.
- You need to link to frames. Using frames is discouraged as they work
badly in many browsers.
### XHTML 1.0 Frameset
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
If you are creating a page with frames, this declaration is appropriate.
However, since frames are generally discouraged when designing Web
pages, this declaration should be used rarely.
### XML Prolog
Additionally, XHTML authors are encouraged by the W3C to include the
following processing instruction as the first line of each document:
``` XML
<?xml version="1.0" encoding="UTF-8"?>
```
Although it is recommended by the standard, this processing instruction
may cause errors in older Web browsers including Internet Explorer
version 6. It is up to the individual author to decide whether to
include the prolog.
## Language
It is good practice to include the optional `xml:lang` attribute
1 on the html element to
describe the document\'s primary language. For compatibility with HTML
the `lang` attribute should also be specified with the same value. For
an English language document use:
``` XML
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
```
The `xml:lang` and `lang` attributes can also be specified on other
elements to indicate changes of language within the document, e.g. a
French quotation in an English document.
## Converting HTML to XHTML
In this section, we will discover how to transform an HTML document into
an XHTML document. We will examine each of the following rules:
- Documents must be well-formed
- Tags must be properly nested
- Elements must be closed
- Tags must be lowercase
- Attribute names must be lowercase
- Attribute values must be quoted
- Attributes cannot be minimized
- The name attribute is replaced with the id attribute (in XHTML 1.0
both name and id should be used with the same value to maintain
backwards-compatibility).
- Plain ampersands are not allowed
- Scripts and CSS must be escaped(enclose them within the tags
\<!\[CDATA\[ and \]\]\>) or preferably moved into external files.
### Documents must be well-formed
Because XHTML conforms to all XML standards, an XHTML document must be
well-formed according to the W3C\'s recommendations for an XML document.
Several of the rules here reemphasize this point. We will consider both
incorrect and correct examples.
#### Tags must be properly nested
Browsers widely tolerate badly nested tags in HTML documents.
``` html4strict
<b><u>
This text is probably bold and underlined, but inside incorrectly nested tags.
</b></u>
```
The text above would display as bold and underlined, even though the end
tags are not in the proper order. An XHTML page will not display if the
tags are improperly nested, because it would not be considered a valid
XML document. The problem can be easily fixed.
``` html4strict
<b><u>
This text is bold and underlined and inside properly nested tags.
</u></b>
```
#### Elements must be closed
Again, XHTML documents must be considered valid XML documents. For this
reason, all tags must be closed. HTML specifications listed some tags as
having \"optional\" end tags, such as the `<p>` and `<li>` tags.
``` html4strict
<p>Here is a list:
<ul>
<li>Item 1
<li>Item 2
<li>Item 3
</ul>
```
In XHTML, the end tags must be included.
``` XML
<p>Here is a list: </p>
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
```
What should we do about HTML tags that do not have a closing tag? Some
special tags do not require or imply a closing tag.
``` html4strict
<img src="titlebar.gif" alt="Title">
<hr>
<br>
<p>Welcome to my web page!</p>
```
In XHTML, the XML rule of including a closing slash within the tag must
be followed.
``` XML
<img src="titlebar.gif" alt="title" />
<hr />
<br />
<p>Welcome to my Web page!</p>
```
Note that some of today\'s browsers will incorrectly render a page if
the closing slash does not have a space before it (`<br/>`). Although it
is not part of the official recommendation, you should always include
the space (`<br />`) for compatibility purposes.
Here are the common empty tags in HTML:
- area
- base
- basefont
- br
- hr
- img
- input
- link
- meta
- param
### Tags must be lowercase
In HTML, tags could be written in either lowercase or uppercase. In
fact, some Web authors preferred to write tags in uppercase to make them
easier to read. XHTML requires that all tags be lowercase.
``` XML
<H1>This is an example of bad case.</h1>
```
This difference is necessary because XML differentiates between cases.
XML would read `<H1>` and `<h1>` as different tags, causing problems in
the above example.
``` XML
<h1>This is an example of good case.</h1>
```
The problem can be easily fixed by changing all tags to lowercase.
### Attribute names must be lowercase
Following the pattern of writing all tags in lowercase, all attribute
names must also be in lowercase.
``` XML
<p CLASS="specialText">Important Notice</p>
```
The correct tags are easy to create.
``` XML
<p class="specialText">Important Notice</p>
```
### Attribute values must be quoted
Some HTML values do not require quotation marks around them. They are
understood by browsers.
``` XML
<table border=1 width=100%>
</table>
```
XHTML requires all attributes to be quoted. Even numeric, percentage,
and hexadecimal values must appear in quotations for them to be
considered part of a proper XHTML document.
``` XML
<table border="1" width="100%">
</table>
```
### Attributes cannot be minimized
HTML allowed some attributes to be written in shorthand, such as
selected or noresize.
``` html4strict
<form>
<input checked ... />
<input disabled ... />
</form>
```
When using XHTML, attribute minimization is forbidden. Instead, use the
syntax `x="x"`, where x is the attribute that was formerly minimized.
``` XML
<form>
<input checked="checked" .../>
<input disabled="disabled" .../>
</form>
```
A complete list of minimized attributes follows:
- checked
- compact
- declare
- defer
- disabled
- ismap
- nohref
- noresize
- noshade
- nowrap
- readonly
- selected
- multiple
### The `name` attribute is replaced with the `id` attribute
HTML 4.01 standards define a name attribute for the tags
`a, applet, frame, iframe, img,` and `map`.
``` html4strict
<a name="anchor">
<img src="banner.gif" name="mybanner" />
</a>
```
XHTML has deprecated the name attribute. Instead, the id attribute is
used. However, to ensure backwards compatibility with today\'s browsers,
it is best to use both the name and id attributes.
``` XML
<a name="anchor" id="anchor" >
<img src="banner.gif" name="mybanner" id="mybanner" />
</a>
```
As technology advances, it will eventually be unnecessary to use both
attributes and XHTML 1.1 removed name altogether.
### Ampersands are not supported
Ampersands are illegal in XHTML.
``` XML
<a href="home.aspx?status=done&itWorked=false">Home & Garden</a>
```
They must instead be replaced with the equivalent character code &.
``` XML
<a href="home.aspx?status=done&amp;itWorked=false">Home &amp; Garden</a>
```
### Image alt attributes are mandatory
Because XHTML is designed to be viewed on different types of devices,
some of which are not image-capable, alt attributes must be included for
all images.
``` XML
<img src="titlebar.gif">
```
Remember that the img tag must include a closing slash in XHTML!
``` XML
<img src="titlebar.gif" alt="title" />
```
### Scripts and CSS must be escaped
Internal scripts and CSS often include characters like the ampersand and
less-than characters.
``` XML
<script language="JavaScript">
<!--
document.write('Hello World!');
//-->
</script>
```
If you are using internal scripts or CSS, enclose them within the tags
and `]]>`. This will mark them as character data that should not be
parsed. If you do not use these tags, characters like & and \< will be
treated as start-of-character entities (like ) and tags (like
\<b\>) respectively. This will cause your page to behave unpredictably,
and it may invalidate your code.
Additionally, the type attribute is mandatory for scripts. The comment
tags `<!--` and `-->` that have traditionally been used to hide
JavaScript from noncompliant browsers should not be included. The XML
standard states that text enclosed in comment tags may be completely
excluded from rendered documents, which would lose all script enclosed
in the tags.
``` XML
<script type="text/javascript" language="javascript">
/*<![CDATA[*/
document.write('Hello World!');
/*]]>*/
</script>
```
Also `document.write();` is not permitted in XHTML documents. You must
used node creation methods such as `document.createElementNS();`
instead. Confusingly, `document.write();` will appear to work as
expected if the document is incorrectly served with a MIME type of
`text/html` (the type for HTML documents), instead of
`application/xhtml+xml` (the type for XHTML documents). If the MIME type
is `text/html` the document will be parsed as HTML which allows
`document.write();`. Parsing the document as HTML defeats the purpose of
writing it in XHTML.
Similar changes must be made for internal stylesheets.
``` XML
<style>
<!--
.SpecialClass {
color: #000000;
}
-->
</style>
```
The type attribute must be included, and the CDATA tags should be used.
``` XML
<style type="text/css">
/*<![CDATA[*/
.SpecialClass {
color: #000000;
}
/*]]>*/
</style>
```
Because scripts and CSS may complicate an XHTML document, it is strongly
recommended that they be placed in external .js and .css files,
respectively. They can then be linked to from your XHTML document.
``` XML
<script src="myscript.js" type="text/javascript" />
<link href="styles.css" type="text/css" rel="stylesheet" />
```
### Some elements may not be nested
The W3C recommendations state that certain elements may not be contained
within others in an XHTML document, even when no XML rules are violated
by the inclusion. Elements affected are listed below.
Element Cannot contain \...
--------- -------------------------------------------------------------------------
a a
pre big, img, object, small, sub, sup
button button, fieldset, form, iframe, input, isindex, label, select, textarea
label label
form form
## When to convert
By now, it probably sounds as though converting an HTML document into
XHTML is easy, but tedious. When would you want to convert your existing
pages into XHTML? Before deciding to change your entire Web site,
consider these questions.
- **Do you want your pages to be easily viewed over a nontraditional
Internet-capable device, such as a PDA or Web-enabled telephone?
Will this be a goal of your site in the future?** XHTML is the
language of choice for Web-enabled portable devices. Now may be a
good time for you to commit to creating an all-XHTML site.
- **Do you plan to work with XML in the future?** If so, XHTML may be
a logical place to begin. If you head up a team of designers who are
accustomed to using HTML, XHTML is a small step away. It may be less
intimidating for beginners to learn XHTML than it is to try teaching
them all about XML from scratch.
- **Is it important that your site be current with the most recent W3C
standards?** Staying on top of current standards will make your site
more stable and help you stay updated in the future, as you will
only have to make small changes to upgrade your site to the newest
versions of XHTML as they are approved by the W3C.
- **Will you need to convert your documents to another format?** As a
valid XML document, XHTML can utilize XSL to be converted into text,
plain HTML, another XHTML document, or another XML document. HTML
cannot be used for this purpose.
If you answered yes to any of the above questions, then you should
probably convert your Web site to XHTML.
### MIME Types
XHTML 1.0 documents should be served with a MIME
Type of `application/xhtml+xml`
to Web browsers that can accept this type. XHTML 1.0 may be served with
the MIME type `text/html` to clients that cannot accept
`application/xhtml+xml` provided that the XHTML complies with the
additional constraints in http://www.w3.org/TR/html/#guidelines
Appendix C
of the XHTML 1.0 specification. If you cannot configure your Web server
to serve documents as different MIME types, you probably should not
convert your Web site to XHTML.
You should check that your XHTML documents are served correctly to
browsers that support `application/xhtml+xml`, e.g. Mozilla Firefox. Use
\'Page Info\' to verify that the type is correct.
XHTML 1.1 documents are often not backwards compatible with HTML and
should not be served with a MIME type of
`text/html`.2
### Help Converting
- Strict Alternatives to Deprecated Attributes for Elements in XHTML
1.0 Strict
### HTML Tidy
When creating HTML, it\'s very easy to make a mistake by leaving out an
end tag or not properly nesting tags. HTML Tidy is a wonderful
application that can be used to correct a number of errors with poorly
formed HTML documents and convert it into XHTML. Tidy can also format
ugly code to be more readable, including code generated by WYSIWYG
editors. HTML Tidy can\'t generate clean code when it encounters
problems it isn\'t sure of how to fix. In these cases, it will generate
an error to let you know where the mistake is located in your document.
A few examples of problems that HTML Tidy can remedy:
- Missing or mismatched end tags.
- Improperly nested elements.
- Mixed up tags.
- Add a missing \"/\" to properly close tags.
- Insert missing tags into lists.
- Add missing quotes around attribute values.
- Ability to insert the correct DOCTYPE value based on your code (can
also recognize and report proprietary elements).
HTML Tidy can also be customized at runtime using a wide array of
command line arguments. It is capable of indenting code to make it more
readable as well as replacing FONT, NOBR, and CENTER tags with style
tags and rules using CSS. Tidy can also be taught new tags by declaring
them in the configuration file.
You can read more about HTML Tidy at the W3C\'s HTML
Tidy site, as well as download
the application as a binary or get the source code. There are several
sites that offer HTML Tidy as an online service including the
W3C and Site
Valet.
You can also validate your page using the validator available at
<http://validator.w3.org/>.
## When not to convert
You shouldn\'t convert your Web pages if they will always be served with
a MIME type of `text/html`. Make sure you know how to configure your
server or server-side script to perform HTTP content negotiation so that
XHTML capable browsers receive XHTML marked as `application/xhtml+xml`.
If you can\'t set up content negotiation, stick to HTML 4.01. People
viewing your Web pages with mainstream browsers will be unable to tell
the difference between a **valid** HTML 4.01 web page and a **valid**
XHTML 1.0 Web page.
Make sure the automated tests you run on your site simulate connections
from both XHTML-compatible browsers, e.g. Mozilla Firefox, and
non--XHTML-compatiable browsers, e.g. Internet Explorer 6.0. This is
particularly important if you use Javascript on your Web site. If
maintaining two copies of your test suite is too time consuming, don\'t
convert.
Bear in mind that valid HTML 4.01 Strict documents generally require
less effort to convert to XHTML 1.1 than valid XHTML 1.0 Transitional
documents. A valid HTML 4.01 Strict document can only contain elements
that are valid in XHTML 1.1, although a few attributes may need
changing. XHTML 1.0 Transitional documents on the other hand can contain
ten element types and more than a dozen attributes that are not valid in
XHTML 1.1. The XHTML 1.0 Transitional `body` element alone has six
atrributes that are not supported in XHTML 1.1.
Don\'t be pressured into using XHTML by people talking vaguely about
*bad practice*. Pin them down to what they mean by *bad practice*. If
they start talking about separation of content and presentation, they
have confused the differences between HTML and XHTML with the
differences between the Transitional and Strict doctypes. Both XHTML 1.0
Transitional and HTML 4.01 Transitional allow you to mix presentation
and content in the same document, i.e. they allow this type of bad
practice. Both HTML 4.01 Strict and XHTML 1.0 Strict force you to move
the bulk of the presentation (but not all of it) in to CSS or an
equivalent language. All four doctypes allow you to use embedded
stylesheets, whereas, true separation requires that all CSS and
Javascript be moved to external files.
## XHTML 1.1
XHTML 1.0 is a suitable markup language for most purposes. It provides
the option to separate content and presentation, which fits the needs of
most Web authors. XHTML 1.1 enforces the separation of content and
presentation. All deprecated elements and attributes have been removed.
It also removes two attributes that were retained in XHTML 1.0 purely
for backwards-compatibility. The `lang` attribute is replaced by
`xml:lang` and `name` is replaced by `id`. Finally it adds support for
ruby text found in East Asian documents.
### DOCTYPE
The DOCTYPE for XHTML 1.1 is:
``` XML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
```
### Modularization
The modularization of XHTML, or XHTML m12n, provides suggestions for
customizing XHTML, either by integrating subsets of XHTML into other XML
applications or extending the XHTML element set. The framework defines
two proceses:
- How to group elements and attributes into \"modules\"
- How to combine modules to create new markup languages
The resulting languages, which the W3C calls \"XHTML Host Languages\",
are based on the familiar XHTML structure but specialized for specific
purposes. XHTML 1.1 is an example of a host language. It was created by
grouping the different elements available to XHTML.
XHTML variations, while possible in theory, have not been widely
adopted. There is continuing work being done to develop host languages,
but their details are beyond the scope of this discussion.
## Invalid XHTML
XHTML-compliant browsers are allowed to render invalid XHTML documents
provided that the documents are well-formed. A simple example is given
below:
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Invalid XHTML</title>
</head>
<body>
<p>This sentence contains a <p>nested paragraph.</p></p>
</body>
</html>
```
Save the example as `invalid.xhtml` (the .xhtml extension is important)
and open the page with Mozilla Firefox. The page will render even though
it is invalid.
## Summary
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
XHTML stands for eXtensible HyperText Markup Language. XHTML is very similar to HTML, but it is stricter and easier to parse. XHTML documents must be well-formed just like regular XML. XHTML allows for modularization. XHTML code must be written according to an exact specification unlike with HTML, where simple errors like missing a closing tag are ignored by the browser. Adhering to these strict specifications actually allows XHTML to be more flexible than HTML. The benefits described in this summary are only gained if the MIME type of the document is `application/xhtml+xml`. XHTML documents can be validated but most browsers choose not to.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## Exercises
## Answers
es:Lenguaje XHTML
is:XHTML
|
# XML - Managing Data Exchange/XPath
+----------------------------------------------------------------------+
| `<span style="font-size:large;">`{=html}`<b>`{=html}Learning |
| objectives`</b>`{=html}`</span>`{=html} |
| |
| - `<span style="font-size:medium;">`{=html}Be able to |
| conceptualize an XML document as a node tree`</span>`{=html} |
| - `<span style="font-size:medium;">`{=html}Refer groups of |
| elements in an XML document`</span>`{=html} |
| - `<span style="font-size:medium;">`{=html}Understand the |
| differences between abbreviated and unabbreviated XPath |
| syntax`</span>`{=html} |
| - `<span style="font-size:medium;">`{=html}Understand the |
| differences between absolute and relative Paths`</span>`{=html} |
| - `<span style="font-size:medium;">`{=html}Be able to use XPath |
| predicates and functions to refine an XPath\'s |
| node-set`</span>`{=html} |
+----------------------------------------------------------------------+
## Introduction
Throughout the previous chapters you have learned the basic concepts of
XSL and how you must refer to nodes in an XML document when performing
an XSL transformation. Up to this point you have been using a
straightforward syntax for referring to nodes in an XML document.
Although the syntax you have used so far has been XPath there are many
more functions and capabilities that you will learn in this chapter. As
you begin to comprehend how path language is used for referring to nodes
in an XML document your understanding of XML as a tree structure will
begin to fall into place. This chapter contains examples that
demonstrate many of the common uses of XPath, but for the full XPath
specification, see the latest version of the standard at:
<http://www.w3.org/TR/xpath>
XSL uses XPath heavily.
## XPath
When you go to copy a file or 'cd' into a directory at a command prompt
you often type something along the lines of '/home/darnell/' to refer to
folders. This enables you to change into or refer to folders throughout
your computer's file system. XML has a similar way of referring to
elements in an XML document. This special syntax is called XPath, which
is short for XML Path Language.
XPath is a language for finding information in an XML document. XPath is
used to navigate through elements and attributes in an XML document.
XPath, although used for referring to nodes in an XML tree, is not
itself written in XML. This was a wise choice on the part of the W3C,
because trying to specify path information in XML would be a very
cumbersome task. Any characters that form XML syntax would need to be
escaped so that it is not confused with XML when being processed. XPath
is also very succinct, allowing you to call upon nodes in the XML tree
with a great degree of specificity without being unnecessarily verbose.
## XML as a tree structure
The great benefit about XML is that the document itself describes the
structure of data. If any of you have researched your family history,
you have probably come across a family tree. At the top of the tree is
some early ancestor and at the bottom of the tree are the latest
children.
With a tree structure you can see which children belong to which
parents, which grandchildren belong to which grandparents and many other
relationships.
The neat thing about XML is that it also fits nicely into this tree
structure, often referred to as an XML Tree.
## Understanding node relationships
We will use the following example to demonstrate the different node
relationships.
``` xml
<bookstore>
<book>
<title>Less Than Zero</title>
<author>Bret Easton Ellis</author>
<year>1985</year>
<price>13.95</price>
</book>
</bookstore>
```
Parent
: Each element and attribute has one parent.
: The book element is the parent of the title, author, year, and
price:
```{=html}
<!-- -->
```
Children
: Element nodes may have zero, one or more children.
: The title, author, year, and price elements are all children of the
book element:
```{=html}
<!-- -->
```
Siblings
: Nodes that have the same parent.
: The title, author, year, and price elements are all siblings:
```{=html}
<!-- -->
```
Ancestors
: A node\'s parent, parent\'s parent, etc.
: The ancestors of the title element are the book element and the
bookstore element:
```{=html}
<!-- -->
```
Descendants
: A node\'s children, children\'s children, etc.
: Descendants of the bookstore element are the book, title, author,
year, and price elements:
Also, it is still useful in some ways to think of an XML file as
simultaneously being a serialized file, like you would view it in an XML
editor. This is so you can understand the concepts of preceding and
following nodes. A node is said to **precede** another if the original
node is before the other in document order. Likewise, a node **follows**
another if it is after that node in document order. Ancestors and
descendants are not considered to be either preceding or following a
node. This concept will come in handy later when discussing the concept
of an axis.
## Abbreviated vs. Unabbreviated XPath syntax
XPath was created so that nodes can be referred to very succinctly,
while retaining the ability to search on many options. Most uses of
XPath will involve searching for child nodes, parent nodes, or attribute
nodes of a particular node. Because these uses are so common, an
abbreviated syntax can be used to refer to these commonly-searched
nodes. Following is an XML document that simulates a tree (the type that
has leaves and branches.) It will be used to demonstrate the different
types of syntax.
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<trunk name="the_trunk">
<bigBranch name="bb1" thickness="thick">
<smallBranch name="sb1">
<leaf name="leaf1" color="brown" />
<leaf name="leaf2" weight="50" />
<leaf name="leaf3" />
</smallBranch>
<smallBranch name="sb2">
<leaf name="leaf4" weight="90" />
<leaf name="leaf5" color="purple" />
</smallBranch>
</bigBranch>
<bigBranch name="bb2">
<smallBranch name="sb3">
<leaf name="leaf6" />
</smallBranch>
<smallBranch name="sb4">
<leaf name="leaf7" />
<leaf name="leaf8" />
<leaf name="leaf9" color="black" />
<leaf name="leaf10" weight="100" />
</smallBranch>
</bigBranch>
</trunk>
```
`<small>`{=html}Exhibit 9.2: tree. xml -- Example XML
page`</small>`{=html}
Following are a few examples of XPath location paths in English,
Abbreviated XPath, then Unabbreviated XPath.
**Selection 1:**
**English:** All \<leaf\> elements in this document that are children of
\<smallBranch\> elements that are children of \<bigBranch\> elements,
that are children of the trunk, which is a child of the root.\
**Abbreviated:** /trunk/bigBranch/smallBranch/leaf\
**Unabbreviated:**
/child::trunk/child::bigBranch/child::smallBranch/child::leaf
**Selection 2:**
**English:** The \<bigBranch\> elements with 'name' attribute equal to
'bb3,' that are children of the trunk element, which is a child of the
root.\
**Abbreviated:** /trunk/bigBranch\[@name='bb3'\]\
**Unabbreviated:**
/child::trunk/child::bigBranch\[attribute::name='bb3'\]
Notice how we can specify which bigBranch objects we want by using a
predicate in the previous example. This narrows the search down to only
bigBranch nodes that satisfy the **predicate**. The predicate is the
part of the XPath statement that is in square brackets. In this case,
the predicate is asking for bigBranch nodes with their 'name' attribute
set to 'bb3'.
The last two examples assume we want to specify the path from the root.
Let's now assume that we are specifying the path from a
`<smallBranch>`{=html} node.
**Selection 3:**
**English:**The parent node of the current \<smallBranch\>. (Notice that
this selection is relative to a \<smallBranch\>)\
**Abbreviated:** ..\
**Unabbreviated:** parent::node()
When using the Unabbreviated Syntax, you may notice that you are calling
a parent or child followed by two colons (::). Each of those are called
an **axis**. You will learn more about axes shortly.
Also, this may be a good time to explain the concept of a **location
path**. A location path is the series of location steps taken to reach
the node/nodes being selected. **Location steps** are the parts of XPath
statements separated by / characters. They are one step on the way to
finding the nodes you would like to select.
Location steps are comprised of three parts: an axis (child, parents,
descendant, etc.), a node test (name of a node, or a function that
retrieves one or more nodes), and a series of predicates (tests on the
retrieved nodes that narrow the results, eliminating nodes that do not
pass the predicate's test).
So, in a location path, each of its location steps returns a node-list.
If there are further steps on the path after a location step, the next
step is executed on all the nodes returned by that step.
## Relative vs. Absolute paths
When specifying a path with XPath, there are times when you will already
be 'in' a node. But other times, you will want to select nodes starting
from the root node. XPath lets you do both. If you have ever worked with
websites in HTML, it works the same way as referring to other files in
HTML hyperlinks. In HTML, you can specify an **Absolute Path** for the
hyperlink, describing where another page is with the server name,
folders, and filename all in the URL. Or, if you are referring to
another file on the same site, you need not enter the server name or all
of the path information. This is called a **Relative Path**. The concept
can be applied similarly in XPath.
You can tell the difference by whether there is a '/' character at the
beginning of the XPath expression. If so, the path is being specified
from the root, which makes it an Absolute Path. But if there is no '/'
at the beginning of the path, you are specifying a Relative Path, which
describes where the other nodes are relative to the **context node**, or
the node for which the next step is being taken.
Below is an XSL stylesheet (Exhibit 9.3) for use with our tree.xml file
above (Exhibit 9.2).
``` xml
<?xml version="1.0" encoding="UTF-8" ?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="html"/>
<!-- Example of an absolute link. The element '/child::trunk'
is being specified from the root element. -->
<xsl:template match="/child::trunk">
<html>
<head>
<title>XPath Tree Tests</title>
</head>
<body>
<!-- Example of a relative link. The <for-each> xsl statement will
execute for every <bigBranch> node in the
‘current’ node, which is the <trunk>node. -->
<xsl:for-each select="child::bigBranch">
<xsl:call-template name="print_out" />
</xsl:for-each>
</body>
</html>
</xsl:template>
<xsl:template name="print_out">
<xsl:value-of select="attribute::name" /> <br />
</xsl:template>
</xsl:stylesheet>
```
`<small>`{=html}Exhibit 9.3: xsl_tree.xsl -- Example of both a relative
and absolute path`</small>`{=html}
## Four types of XPath location paths
In the last two sections you learned about two different distinctions to
separate out different location paths: Unabbreviated vs. Abbreviated and
Relative vs. Absolute. Combining these two concepts could be helpful
when talking about XPath location paths. Not to mention, it could make
you sound really smart in front of your friends when you say things
like:
:#Abbreviated Relative Location Paths- Use of abbreviated syntax while
specifying a relative path.
:#Abbreviated Absolute Location Paths- Use of abbreviated syntax while
specifying a absolute path.
:#Unabbreviated Relative Location Paths- Use of unabbreviated syntax
while specifying a relative path.
:#Unabbreviated Absolute Location Paths- Use of unabbreviated syntax
while specifying a absolute path.
I only mention this four-way distinction now because it could come in
handy while reading the specification, or other texts on the subject.
## XPath axes
In XPath, there are some node selections whose performance requires the
Unabbreviated Syntax. In this case, you will be using an axis to specify
each location step on your way through the location path.
From any node in the tree, there are 13 axes along which you can step.
They are as follows:
Axes Meaning
---------------------- ------------------------------------------------------------------------------------
ancestor:: Parents of the current node up to the root node
ancestor-or-self:: Parents of the current node up to the root node and the current node
attribute:: Attributes of the current node
child:: Immediate children of the current node
descendant:: Children of the current node (including children\'s children)
descendant-or-self:: Children of the current node (including children\'s children) and the current node
following:: Nodes after the current node (excluding children)
following-sibling:: Nodes after the current node (excluding children) at the same level
namespace:: XML namespace of the current node
parent:: Immediate parent of the current node
preceding:: Nodes before the current node (excluding children)
preceding-sibling:: Nodes before the current node (excluding children) at the same level
self:: The current node
## XPath predicates and functions
Sometimes, you may want to use a predicate in an XPath Location Path to
further filter your selection. Normally, you would get a set of nodes
from a location path. A predicate is a small expression that gets
evaluated for each node in a set of nodes. If the expression evaluates
to 'false', then the node is not included in the selection. An example
is as follows:
//p\[@class='alert'\]
In the preceding example, every \<p\> tag in the document is checked to
see if its 'class' attribute is set to 'alert'. Only those \<p\> tags
with a 'class' attribute with value 'alert' are included in the set of
nodes for this location path.
The following example uses a function, which can be used in a predicate
to get information about the context node.
/book/chapter\[position()=3\]
This previous example selects only the chapter of the book in the third
position. So, for something to be returned, the current \<book\> element
must have at least 3 \<chapter\> elements.
Also notice that the position function returns an integer. There are
many functions in the XPath specification. For a complete list, see the
W3C specification at <http://www.w3.org/TR/xpath#corelib>
Here are a few more functions that may be helpful:
number **last**() -- last node in the current node set
number **position**() -- position of the context node being tested
number **count**(node-set) -- the number of nodes in a node-set
boolean **starts-with**(string, string) -- returns true if the first
argument starts with the second
boolean **contains**(string, string) -- returns true if the first
argument contains the second
number **sum**(node-set) -- the sum of the numeric values of the nodes
in the node-set
number **floor**(number) -- the number, rounded down to the nearest
integer
number **ceiling**(number) -- the number, rounded up to the nearest
integer
number **round**(number) -- the number, rounded to the nearest integer
## Example
The following XML document, XSD schemas, and XSL stylesheet examples are
to help you put everything you have learned in this chapter together
using real life data. As you study this example you will notice how
XPath can be used in the stylesheet to call and modify the output of
specific information from the document.
Below is an XML document (Exhibit 9.4)
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="movies.xsl" type="text/xsl" media="screen"?>
<movieCollection xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="movies.xsd">
<movie>
<movieTitle>Meet the Parents</movieTitle>
<movieSynopsis>
Greg Focker is head over heels in love with his girlfriend Pam, and is ready to
pop the big question. When his attempt to propose is thwarted by a phone call
with the news that Pam's younger sister is getting married, Greg realizes that
the key to Pam's hand in marriage lies with her formidable father.
</movieSynopsis>
<role>
<roleIDREF>bs1</roleIDREF>
<roleType>Lead Actor</roleType>
</role>
<role>
<roleIDREF>tp1</roleIDREF>
<roleType>Lead Actress</roleType>
</role>
<role>
<roleIDREF>rd1</roleIDREF>
<roleType>Lead Actor</roleType>
</role>
<role>
<roleIDREF>bd1</roleIDREF>
<roleType>Supporting Actress</roleType>
</role>
</movie>
<movie>
<movieTitle>Elf</movieTitle>
<movieSynopsis>
One Christmas Eve, a long time ago, a small baby at an orphanage crawled into
Santa’s bag of toys, only to go undetected and accidentally carried back to Santa’s
workshop in the North Pole. Though he was quickly taken under the wing of a surrogate
father and raised to be an elf, as he grows to be three sizes larger than everyone else,
it becomes clear that Buddy will never truly fit into the elf world. What he needs is
to find his real family. This holiday season, Buddy decides to find his true place in the
world and sets off for New York City to track down his roots.
</movieSynopsis>
<role>
<roleIDREF>wf1</roleIDREF>
<roleType>Lead Actor</roleType>
</role>
<role>
<roleIDREF>jc1</roleIDREF>
<roleType>Supporting Actor</roleType>
</role>
<role>
<roleIDREF>zd1</roleIDREF>
<roleType>Lead Actress</roleType>
</role>
<role>
<roleIDREF>ms1</roleIDREF>
<roleType>Supporting Actress</roleType>
</role>
</movie>
<castMember>
<castMemberID>rd1</castMemberID>
<castFirstName>Robert</castFirstName>
<castLastName>De Niro</castLastName>
<castSSN>489-32-5984</castSSN>
<castGender>male</castGender>
</castMember>
<castMember>
<castMemberID>bs1</castMemberID>
<castFirstName>Ben</castFirstName>
<castLastName>Stiller</castLastName>
<castSSN>590-59-2774</castSSN>
<castGender>male</castGender>
</castMember>
<castMember>
<castMemberID>tp1</castMemberID>
<castFirstName>Teri</castFirstName>
<castLastName>Polo</castLastName>
<castSSN>099-37-8765</castSSN>
<castGender>female</castGender>
</castMember>
<castMember>
<castMemberID>bd1</castMemberID>
<castFirstName>Blythe</castFirstName>
<castLastName>Danner</castLastName>
<castSSN>273-44-8690</castSSN>
<castGender>male</castGender>
</castMember>
<castMember>
<castMemberID>wf1</castMemberID>
<castFirstName>Will</castFirstName>
<castLastName>Ferrell</castLastName>
<castSSN>383-56-2095</castSSN>
<castGender>male</castGender>
</castMember>
<castMember>
<castMemberID>jc1</castMemberID>
<castFirstName>James</castFirstName>
<castLastName>Caan</castLastName>
<castSSN>389-49-3029</castSSN>
<castGender>male</castGender>
</castMember>
<castMember>
<castMemberID>zd1</castMemberID>
<castFirstName>Zooey</castFirstName>
<castLastName>Deschanel</castLastName>
<castSSN>309-49-4005</castSSN>
<castGender>female</castGender>
</castMember>
<castMember>
<castMemberID>ms1</castMemberID>
<castFirstName>Mary</castFirstName>
<castLastName>Steenburgen</castLastName>
<castSSN>988-43-4950</castSSN>
<castGender>female</castGender>
</castMember>
</movieCollection>
```
`<small>`{=html}Exhibit 9.4: movies_xpath.xml`</small>`{=html}
Below is the second XML document (Exhibit 9.5)
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<cities xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="cities.xsd">
<city>
<cityID>c2</cityID>
<cityName>Mandal</cityName>
<cityPopulation>13840</cityPopulation>
<cityCountry>Norway</cityCountry>
<tourismDescription>A small town with a big atmosphere. Mandal provides comfort
away from normal luxuries.
</tourismDescription>
<capitalCity>c3</capitalCity>
</city>
<city>
<cityID>c3</cityID>
<cityName>Oslo</cityName>
<cityPopulation>533050</cityPopulation>
<cityCountry>Norway</cityCountry>
<tourismDescription>Oslo is the capital of Norway for many reasons.
It is also the capital location for tourism. The culture, shopping,
and attractions can all be experienced in Oslo. Just remember
to bring your wallet.
</tourismDescription>
</city>
</cities>
```
`<small>`{=html}Exhibit 9.5: cites\_\_xpath.xml`</small>`{=html}
Below is the Movies schema (Exhibit 9.6)
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified">
<!--Movie Collection-->
<xsd:element name="movieCollection">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="movie" type="movieDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<!--This contains the movie details.-->
<xsd:complexType name="movieDetails">
<xsd:sequence>
<xsd:element name="movieTitle" type="xsd:string" minOccurs="1" maxOccurs="unbounded"/>
<xsd:element name="movieSynopsis" type="xsd:string"/>
<xsd:element name="role" type="roleDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<!--The contains the genre details.-->
<xsd:complexType name="roleDetails">
<xsd:sequence>
<xsd:element name="roleIDREF" type="xsd:IDREF"/>
<xsd:element name="roleType" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
<xsd:simpleType name="ssnType">
<xsd:restriction base="xsd:string">
<xsd:pattern value="\d{3}-\d{2}-\d{4}"/>
</xsd:restriction>
</xsd:simpleType>
<xsd:complexType name="castDetails">
<xsd:sequence>
<xsd:element name="castMemberID" type="xsd:ID"/>
<xsd:element name="castFirstName" type="xsd:string"/>
<xsd:element name="castLastName" type="xsd:string"/>
<xsd:element name="castSSN" type="ssnType"/>
<xsd:element name="castGender" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
```
`<small>`{=html}Exhibit 9.6: movies.xsd`</small>`{=html}
Below is the Cities schema (Exhibit 9.7)
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
attributeFormDefault="unqualified">
<xsd:element name="cities">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="city" type="cityType" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<xsd:complexType name="cityType">
<xsd:sequence>
<xsd:element name="cityID" type="xsd:ID"/>
<xsd:element name="cityName" type="xsd:string"/>
<xsd:element name="cityPopulation" type="xsd:integer"/>
<xsd:element name="cityCountry" type="xsd:string"/>
<xsd:element name="tourismDescription" type="xsd:string"/>
<xsd:element name="capitalCity" type="xsd:IDREF" minOccurs="0" maxOccurs="1"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
```
`<small>`{=html}Exhibit 9.7: cities.xsd`</small>`{=html}
Below is the XSL stylesheet (Exhibit 9.8)
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:key name="castList" match="castMember" use="castMemberID"/>
<xsl:output method="html"/>
<!-- example of using an abbreviated absolute path to pull info
from cities_xpath.xml for the city "Oslo" specifically -->
<!-- specify absolute path to select cityName and assign it the variable "city" -->
<xsl:variable name="city" select="document('cities_xpath.xml')
/cities/city[cityName='Oslo']/cityName" />
<!-- specify absolute path to select cityCountry and assign it the variable "country" -->
<xsl:variable name="country" select="document('cities_xpath.xml')
/cities/city[cityName='Oslo']/cityCountry" />
<!-- specify absolute path to select tourismDescription and assign it the variable "description" -->
<xsl:variable name="description" select="document('cities_xpath.xml')
/cities/city[cityName='Oslo']/tourismDescription" />
<xsl:template match="/">
<html>
<head>
<title>Movie Collection</title>
</head>
<body>
<h2>Movie Collection</h2>
<xsl:apply-templates select="movieCollection"/>
</body>
</html>
</xsl:template>
<xsl:template match="movieCollection">
<!-- let's say we just want to see the actors. -->
<!--
<xsl:for-each select="movie">
<hr />
<br />
<b><xsl:text>Movie Title: </xsl:text></b>
<xsl:value-of select="movieTitle"/>
<br />
<br />
<b><xsl:text>Movie Synopsis: </xsl:text></b>
<xsl:value-of select="movieSynopsis"/>
<br />
<br />-->
<!-- actor info begins here. -->
<b><xsl:text>Cast: </xsl:text></b>
<br />
<!-- specify an abbreviated relative path here for "role."
NOTE: there is no predicate in this one; it's just a path. -->
<xsl:for-each select="movie/role">
<xsl:sort select="key('castList',roleIDREF)/castLastName"/>
<xsl:number value="position()" format="
 0. " />
<xsl:value-of select="key('castList',roleIDREF)/castFirstName"/>
<xsl:text> </xsl:text>
<xsl:value-of select="key('castList',roleIDREF)/castLastName"/>
<xsl:text>, </xsl:text>
<xsl:value-of select="roleType"/>
<br />
<xsl:value-of select="key('castList',roleIDREF)/castGender"/>
<xsl:text>, </xsl:text>
<xsl:value-of select="key('castList',roleIDREF)/castSSN"/>
<br />
<br />
</xsl:for-each>
<!--
</xsl:for-each>-->
<hr />
<!--calling the variables -->
<span style="color:red;">
<p><b>Travel Advertisement</b></p>
<!-- reference the city, followed by a comma, and then the country -->
<p><xsl:value-of select="$city" />, <xsl:value-of select="$country" /></p>
<!-- reference the description -->
<xsl:value-of select="$description" />
</span>
</xsl:template>
</xsl:stylesheet>
```
`<small>`{=html}Exhibit 9.6: movies.xsl`</small>`{=html}
## Summary
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Throughout the chapter we have learned many of the features and capabilities of the XML Path Language. You should now have a good understanding of node relationships though the use of the XML tree structure. Using the concept of Abbreviated and Unabbreviated location paths allows us to narrow our searches down to only a particular element by satisfying the predicate in the square brackets. Relative and Absolute are used for specifying the path to your location. The Relative path gives the file location in relation to the current working directory while the Absolute path gives an exact location of a file or directory name within a computer or file system. Both of these concepts can be combined to come up with four types of XPath location paths: Abbreviated Relative, Abbreviated Absolute, Unabbreviated Relative, and lastly Unabbreviated Absolute. If further filtering is required XPath predicates and functions can be used. These allow for the predicate to be evaluated for such things as true/false and count functions. When used correctly XPath can be a very powerful tool in the XML language.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## Exercises
## Answers
fr:Programmation XML/XPath
it:XML/XPath
|
# XML - Managing Data Exchange/XLink
```{=html}
<table cellspacing=10 cellpadding=10 border=5>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<font size=4>`{=html}`<b>`{=html}Learning
objectives`</b>`{=html}`</font>`{=html}\
- `<font size=3>`{=html} Learn different techniques of implementing
XLink\'s in XML`</font>`{=html}
- `<font size=3>`{=html} create a custom XLink`</font>`{=html}
- `<font size=3>`{=html} learn the functionality behind various XLink
parameters`</font>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
sponsored by:\
\
```{=html}
<center>
```
`<font size=3>`{=html}`<b>`{=html}The University of
Georgia`</b>`{=html}`</font>`{=html}\
\
`<font size=5 color=#990000>`{=html}`<b>`{=html}Terry College of
Business`</b>`{=html}`</font>`{=html}\
\
`<font size=3>`{=html}`<b>`{=html}Department of Management Information
Systems`</b>`{=html}`</font>`{=html}
```{=html}
</center>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
\
==Introduction== Through the use of Uniform Resource Identifiers
(URI\'s), an **XLink** allows elements to be inserted into XML documents
that create links between resources such as documents, images, files and
other pages. An XLink is similar in concept to an HTML hyperlink, but is
more powerful and flexible.
This chapter will be a general overview of the XLink syntax. It will
also provide exposure to some of XLink\'s basic concepts. For the full
XLink specification, see the latest version of the standard at:
<http://www.w3.org/TR/xlink>
## XLink
XLinks create a linking relationship between two or more resources. They
allow for any XML element, image, text or markup files to be specified
in the link.
By using a method similar to the centralized formatting of XSL
stylesheets, XLinks allow a document\'s hyperlinks to be isolated and
centralized in a separate document. As a linked document\'s addresses
changes, the XLink remains functional.
The use of XLink requires the declaration of the XLink
namespace. This namespace provides the
global attributes for type, href, role, arcrole, title, show, actuate,
label, from and to. The following example would make the prefix xlink
available within the tourGuide element.
``` xml
<tourGuide
xmlns:xlink="http://www.w3.org/1999/xlink">
...
</tourGuide>
```
## XLink global attributes
The following table outlines the attributes that can be used with the
xlink namespace. The global attributes are type, href, role, arcrole,
title, show, actuate, label, from, and to. The table also includes
descriptions of how the attributes can be used.
**Exhibit 1: Table of global attributes**\
```{=html}
<table cellspacing=10 cellpadding=10 border=5>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<font size=3>`{=html}`<b>`{=html}Attributes`</b>`{=html}`</font>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
`<font size=3>`{=html}`<b>`{=html}Description and Valid
Values`</b>`{=html}`</font>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}type`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Describes the meaning of an item\
- simple - basic format similar to html linkage
- extended - more complex than simple types with multi functional
format
- resource - provides local resources
- locator - provides remote resources
- arc - provides the ability to traverse from one resource to another
- title - readable name or explanation of link
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}href`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Location of resource\
- value is URI
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}role`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Description of XLink\'s content\
- value is URI
- describes the element whose role it is
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}arcrole`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Description of XLink\'s content\
- value is URI
- describe the relationship between the two sides of the arc
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}title`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Name displayed, usually short description of link\
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}show`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Describes behavior of the browser once the XLink has been actuated and
loaded\
- new - load in a new window or frame
- replace - load in same window or frame
- embed - replace the current item
- other - look for information elsewhere
- none - not specified
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}actuate`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Specifies when resource is retrieved or link processing occurs\
- onRequest - when user requests the link
- onLoad - when page is loaded
- other - looks for information elsewhere
- none - not specified
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}label, from & to`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Specifies link direction
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
\
## XML schema
\
The following XML schema defines a tour guide that contains at least one
city. Each city contains one or more attractions. The name of each
attraction is an XLink.
**Exhibit 2: XML schema for TourGuide**
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : TourGuide.xsd
Created on : February 28, 2006
Author : Billy Timmins
-->
<!--
Declaration of usage of xlink Namespace
-->
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified"
xmlns:xlink="http://www.w3.org/1999/xlink">
<xsd:element name="tourGuide">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="city" type="cityDetails" minOccurs="1" maxOccurs="unbounded" />
</xsd:sequence>
</xsd:complexType>
</xsd:element>
<!--
This section will contain the City details
-->
<xsd:complexType name="cityDetails">
<xsd:sequence>
<xsd:element name="cityName" type="xsd:string"/>
<xsd:element name="adminUnit" type="xsd:string"/>
<xsd:element name="country" type="xsd:string"/>
<xsd:element name="continent">
<xsd:simpleType>
<xsd:restriction base="xsd:string">
<xsd:enumeration value="Asia"/>
<xsd:enumeration value="Africa"/>
<xsd:enumeration value="Australia"/>
<xsd:enumeration value="Europe"/>
<xsd:enumeration value="North America"/>
<xsd:enumeration value="South America"/>
<xsd:enumeration value="Antarctica"/>
</xsd:restriction>
</xsd:simpleType>
</xsd:element>
<xsd:element name="population" type="xsd:integer"/>
<xsd:element name="description" type="xsd:string"/>
<xsd:element name="attraction" type="attractionDetails" minOccurs="1" maxOccurs="unbounded"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="attractionDetails">
<xsd:sequence>
<!--
Note use of xlink
-->
<xsd:element name="attractionName" xlink:type="simple"/>
<xsd:element name="attractionDescription" type="xsd:string"/>
<xsd:element name="attractionRating" type="xsd:integer"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
```
## XML document
\
The following XML document shows how the XLink, attractionName, defined
in the XML schema, is used in an XML document. Note that it is necessary
to include xlink:href=\"\" within the attribute tags in order to define
the linked website.
**Exhibit 3: XML document for TourGuide.xsd (using XLink)**
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : SomeTourGuide.xml
Created on : February 28, 2006
Author : Billy Timmins
-->
<!--
Declaration of usage of XLink Namespace
-->
<?xml-stylesheet href="TourGuide.xsl" type="text/xsl"?>
<tourGuide xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xlink="http://www.w3.org/1999/xlink" xsi:noNamespaceSchemaLocation="TourGuide.xsd">
<city>
<cityName>Atlanta</cityName>
<adminUnit>Georgia</adminUnit>
<country>USA</country>
<continent>North America</continent>
<population>425000</population>
<description>Atlanta is the capital of and largest city in the U.S. state of Georgia.</description>
<attraction>
<!--
Declaration of XLink and associated link
-->
<attractionName xlink:href="http://www.georgiaaquarium.org/"> Georgia Aquarium </attractionName>
<attractionDescription>World’s Largest Aquarium</attractionDescription>
<attractionRating>5</attractionRating>
</attraction>
<attraction>
<!--
Declaration of XLink and associated link
-->
<attractionName xlink:href="http://www.high.org/"> High Museum of Art </attractionName>
<attractionDescription>The High Museum of Art, founded in 1905 as the Atlanta Art Association, is the leading art museum in the Southeastern United States.</attractionDescription>
<attractionRating>4</attractionRating>
</attraction>
<attraction>
<!--
Declaration of XLink and associated link
-->
<attractionName xlink:href="http://www.underground-atlanta.com/"> Underground Atlanta </attractionName>
<attractionDescription> Go beneath the streets of a bustling downtown, to the heart of a great American city. Underground Atlanta is at the center of it all.</attractionDescription>
<attractionRating>2</attractionRating>
</attraction>
</city>
<city>
<cityName>Tampa</cityName>
<adminUnit>Florida</adminUnit>
<country>USA</country>
<continent>North America</continent>
<population>303000</population>
<description>Tampa is a major United States city located in Hillsborough County, on the west coast of Florida.</description>
<attraction>
<!--
Declaration of XLink and associated link
-->
<attractionName xlink:href="http://www.buschgardens.com/buschgardens/fla/default.aspx"> Bush Gardens </attractionName>
<attractionDescription>The nation's fourth largest zoo, Bush Gardens is where you can see African animals roaming free and an exciting amusement park featuring its world-famous rides like Kumba and the new inverted roller-coaster, Montu.</attractionDescription>
<attractionRating>5</attractionRating>
</attraction>
<attraction>
<!--
Declaration of XLink and associated link
-->
<attractionName xlink:href="http://www.plantmuseum.com/"> Henry B. Plant Museum </attractionName>
<attractionDescription>Discover a museum which transports you to turn-of-the-century Florida.</attractionDescription>
<attractionRating>1</attractionRating>
</attraction>
</city>
</tourGuide>
```
## XML stylesheet
\
The following XML stylesheet displays the contents of the XML document.
**Exhibit 4: XML stylesheet TourGuide**
``` xml
<?xml version="1.0" encoding="UTF-8"?>
<!--
Document : TourGuide.xsl
Created on : February 28, 2006
Author : Billy Timmins
-->
<!--
Declaration of usage of XLink Namespace
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xlink="http://www.w3.org/1999/xlink" exclude-result-prefixes="xlink" version="1.0">
<xsl:output method="html"/>
<!--
Attribute XLink defined as an href of simple type
-->
<xsl:template match="*[@xlink:type = 'simple' and @xlink:href]">
<a href="{@xlink:href}">
<xsl:apply-templates/>
</a>
</xsl:template>
<xsl:template match="/">
<html>
<head>
<title>Tour Guide XLink Example</title>
</head>
<body>
<h2>Cities</h2>
<xsl:apply-templates select="tourGuide"/>
</body>
</html>
</xsl:template>
<!--
template for handling a link
-->
<xsl:template match="attractionName">
<a href="{@xlink:href}">
<xsl:value-of select="."/>
</a>
</xsl:template>
<xsl:template match="tourGuide">
<table border="1" width="100%">
<xsl:for-each select="city">
<tr>
<td>
<br/>
<xsl:text>City: </xsl:text>
<xsl:value-of select="cityName"/>
<br/>
<xsl:text>County: </xsl:text>
<xsl:value-of select="adminUnit"/>
<br/>
<xsl:text>Continent: </xsl:text>
<xsl:value-of select="continent"/>
<br/>
<xsl:text>Population: </xsl:text>
<xsl:value-of select="population"/>
<br/>
<xsl:text>Description: </xsl:text>
<xsl:value-of select="description"/>
<br/>
<br/>
</td>
</tr>
<tr>
<td>
<xsl:text>Attraction: </xsl:text>
</td>
<td>
<xsl:text>Attraction Description: </xsl:text>
</td>
<td>
<xsl:text>Attraction Rating: </xsl:text>
</td>
</tr>
<xsl:for-each select="attraction">
<tr>
<td>
<!--
application of the template
-->
<xsl:apply-templates select="attractionName"/>
</td>
<td>
<xsl:value-of select="attractionDescription"/>
</td>
<td>
<xsl:value-of select="attractionRating"/>
</td>
</tr>
</xsl:for-each>
</xsl:for-each>
</table>
</xsl:template>
</xsl:stylesheet>
```
## Summary
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
XLink is an extremely versatile specification that standardizes the process for linking to other data sources. Not only does XLink support unidirectional linking similar to an anchor tag in HTML but also can be used to create bidirectional links. Additionally, XLink allows for the linkage from any XML element. This gives great freedom to the developer.
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## Exercises
## Answers
|
# XML - Managing Data Exchange/CSS
------------------------------------------------------------------------
## Learning objectives
Upon completion of this chapter, for CSS you will be able to
- know the benefits of using CSS
- know the limitations of CSS, so you are able to find the best
solution for your document
- know how to implement and use CSS on an XML document
## Introduction
CSS (Cascading Style Sheets) is a language that describes the
presentation form of a structured document.
An XML or an HTML based document does not have a set style, but it
consists of structured text without style information. How the document
will look when printed on paper and viewed in a browser or maybe a
cellphone is determined by a style sheet. A good way of making a
document look consistent and easy to update is by using CSS, which
Wikipedia is a good example of.
## History of CSS
Style sheets have been around in one form or another since the
beginnings of HTML in the early 1990s. Various browsers included their
own style language which could be used to customize the appearance of
web documents. Originally, style sheets were targeted towards the
end-user; early revisions of HTML did not provide many facilities for
presentational attributes, so it was often up to the user to decide how
web documents would appear.
As the HTML language grew, however, it came to encompass a wider variety
of stylistic capabilities to meet the demands of web developers. With
these capabilities, style sheets became less important, and an external
language for the purposes of defining style attributes was not widely
accepted until the development of CSS.
The concept of Cascading Style Sheets was originally proposed in 1994 by
Håkon Wium Lie. Bert
Bos was at the time working on a
browser called Argo which used its own style sheets; the two decided to
work together to develop CSS.
A number of other style sheet languages had already been proposed, but
CSS was the first to incorporate the idea of \"cascading\" \-- the
capability for a document\'s style to be inherited from more than one
\"style sheet.\" This permitted a user\'s preferred style to override
the site author\'s specified style in some areas, while inheriting, or
\"cascading\" the author\'s style in other areas. The capability to
cascade in this way permits both users and site authors added
flexibility and control; it permitted a mixture of stylistic
preferences.
Håkon\'s proposal was presented at the \"Mosaic and the Web\" conference
in Chicago in 1994, and again with Bert Bos in 1995. Around this time,
the World Wide Web Consortium was being established; the W3C took an
interest in the development of CSS, and organized a workshop toward that
end. Håkon and Bert were the primary technical staff on the project,
with additional members, including Thomas Reardon of Microsoft,
participating as well. By the end of 1996, CSS was nearly ready to
become official. The CSS level 1 Recommendation was published in
December 1996.
Early in 1997, CSS was assigned its own working group within the W3C.
The group began tackling issues that had not been addressed with CSS
level 1, resulting in the creation of CSS level 2, which was published
as an official Recommendation in May 1998. CSS level 3 is still under
development as of 2005.
## Why use CSS?
### Cleaner Looking Code
A mass of HTML tags which manage design elements generally obscure the
content of a page, making the code harder to read and maintain. Using
CSS, the content of the page is separated from the design, making
content production in formats such as HTML, XHTML, and XML as easy as
possible.
### Pages Will Load Faster
Non-CSS design typically consists of more code than a CSS-designed
website.
In a non-CSS design, the information about the design is reloaded every
time a visitor accesses a new page. Additionally, the finer points of
design are executed awkwardly. For example, a common method of defining
the spacing of a web page is to use blank GIF images inside tables.
Using CSS keeps content and design separated, so much less code will be
needed. The CSS file loads only once per session, and is saved locally
in the user\'s cache. All information about dimensions is defined in
this stylesheet, rendering awkward constructions like blank GIF images
unnecessary.
Although an increasing amount of Internet users have broadband, the size
of a web page can be important to users who are limited to dial-up
connections. Suppose a dial-up user accesses a company\'s website, and
this visitor experiences lengthy loading times. It is quite possible
that the visitor would stop their visit or form an opinion of this
company as \"slow.\" In this way, a seemingly small difference could
mean added revenue.
Furthermore, bandwidth is not free and most webhosting firms limit the
amount used. In fact, many hosts charge based on bandwidth usage, so
less code could also reduce costs.
### Redesign Becomes Trivial
When used properly, CSS is a very powerful tool that gives a web
architect complete control over a site\'s presentation. It is a notation
in which the rules of a design are governed. This becomes very useful
for a large website which requires a consistent appearance for every
type of element (such as a title, a subtitle, a piece of code, or a
paragraph).
For example, suppose a company has a 1,200 page website which took many
months to complete. The company then undergoes a rebranding and thus the
font, the background, the style of hyperlinks, and so forth needs to be
updated with the new corporate design. If the site was engineered
properly using CSS, this change would be as simple as editing the
appropriate lines of a single CSS file (assuming it is an external
stylesheet). If CSS is not used, the code that manages the appearance is
stored in each of the pages. In order to update the design in this case,
each file would have to be updated *individually*.
### Graceful Degradation
{{\...}}
### Accessibility
People with lowered vision or users with special web browsers, e.g.
people that are blind, will probably like a CSS designed website better
than one not designed using CSS. Because CSS allows you to define the
reading order separately from the visual layout it makes it easier for
the special web browsers to read the page. Bear in mind that anyone who
wears glasses or contact lenses can be considered to have lower vision.
Many designers lock the font size in pixels which prevents the user
changing the font size. Good CSS design allows the user to increase or
decrease the font size at will making pages more usable. A significant
number of web surfers like to use a magnification of 300% or more.
Giving the user the opportunity to change the font size will not make
any difference for the normal user, but it can make a difference for
people that have lowered vision. Ask yourself the question: who is the
website made for? The visitors or the designer?
Websites designed with CSS tend to display better than table-based
designs in the web browsers used in PDAs and cellphones. The use of
cellphones for browsing will probably continue to increase. A
table-based design will make web pages inaccessible to these users.
Be careful with your CSS designs. Misuse of absolute positioning and
absolute rather than relative sizes can make your webpages less
accessible rather than more accessible. A good table design is better
than a bad CSS design.
### Better results in search engines
Extensive use of tables confuses the search engines, they can actually
get problems separating content from code. The search engine robots
start reading on the top of the page, and they want to find out how
relevant the webpage is as fast as possible. Again, less code will make
it easier for the search engines to find code that\'s relevant, and it
will probably give your webpage a better ranking.
## Disadvantages of CSS
The use of CSS for styling has few disadvantages. However some browsers,
especially older ones, will sometimes present the page incorrectly. When
I was gathering information for this chapter it became clear to me that
many experts think that formatting XML with CSS is not the future of the
web. The main view is that XSL will be the new standard. So make sure
you read through the previous chapter of this book one more time. The
formatting parts of XSL and CSS will be quite similar. For example, you
will be able to use all CSS1 and CSS2 properties and values in XSL with
the same meaning as in CSS.
## CSS levels
The first CSS specification to become an official W3C Recommendation is
CSS level 1, published in December 1996. Among its capabilities is
support for:
- Typeface\|Font properties such as typeface and emphasis
- Color of text, backgrounds, and other elements
- Text attributes such as spacing between words, letters, and lines of
text
- alignment (typesetting)\|Alignment of text, images, tables and other
elements
- Margin, border, padding, and positioning for most elements
- Unique identification and generic classification of groups of
attributes
The W3C maintains the CSS1
Recommendation.
CSS level 2 was developed by the W3C and published as a Recommendation
in May 1998. A superset of CSS1, CSS2 includes a number of new
capabilities, among them the absolute, relative, and fixed positioning
of elements, the concept of media types, support for aural style sheets
and bidirectional text, and new font properties such as shadows. The W3C
maintains the CSS2 Recommendation.
CSS level 2 revision 1 or CSS 2.1 fixes errors in CSS2, removes
poorly-supported features and adds already-implemented browser
extensions to the specification. It\'s currently a Candidate
Recommendation.
CSS level 3 is currently under development. The W3C maintains a CSS3
progress report.
## CSS Syntax and Properties
- The section on selectors has moved to CSS
Programming/Selectors.
- The section on color has moved to CSS
Programming/Color.
- The section on text has moved to CSS Programming/Fonts and
Text.
- The section on borders has moved to CSS Programming/Box
Model.
- The section on positioning has moved to CSS
Programming/Positioning.
The following section contains a list of some of the most common CSS
properties. A complete list can be found
here. The
syntax for the use of CSS in an XML document is the same as that for
HTML. The difference is in how you link your CSS file to the XML
document. To do this you have to write `<code>`{=html}
```{=html}
<?xml-stylesheet href="''X.css''" type="text/css"?>
```
`</code>`{=html} before the root element of your XML document, where
*X.css* of course is the name of the CSS file.
As mentioned earlier in this chapter, CSS is a set of rules that
determines how elements in a document will be shown. The rule has two
parts: a selector and a group of one or more declarations surrounded by
braces (curly brackets):
:
: selector { declaration; \...}
The selector is normally the tag you wish to style. Here is an example
of a simple rule containing a single declaration:\
::h1 { color: red; } Result: All h1-elements in the document are shown
with the text color red.
### The general syntax
Rules are usually defined like this:
:
: selector { declaration; \...}
The declaration is formed like this:
:
: property: value;
Remember that there can be several declarations in one rule. A common
mistake is to mix up colons, which separate the property and value of a
declaration, and semicolons, which separate declarations. A selector
chooses the elements for which the rule applies and the declaration sets
the value for the different properties of the elements that are chosen.
Back to our example:
:
: h1 { color: red; }
In our example:
:
: selector is the element h1
: declaration color: red
The property *color* gets the value *red*
Multiple declarations can be written either on a single line or over
several lines, because whitespace collapses:
:
: h1 { color:red; background-color:white; }
or
:
: h1 {
:
: color:red;
: background-color:white;
: }
Details of the properties defined by CSS can be found at CSS
Programming#CSS1
Properties.
## Summary
**Cascading Style Sheets** (CSS), are used with webpages to define the
view of information saved in HTML or XML. While XML and HTML create and
preserve a documents structure, CSS is used to define the appearance and
placement of objects within the document as well as its content. All of
this information is saved in a separate file, the .css file. In the CSS
file are textsize, background color, text types, e.g defined. The
placement of pictures and other animations are also defined in the css
file. If CSS is used correctly it would make a webpage a lot easier to
create and even more important, to maintain. Because you will only have
to make changes in the css file to make the whole website change.
!CSS Zen Garden without
CSS{width="200"}
!Zen Garden with
CSS{width="200"}
\
## References and useful links
- CSS Property Reference
**References:**\
\* <http://no.wikipedia.org/> - The Norwegian version of Wiki\
\* <http://en.wikipedia.org/wiki/Cascading_Style_Sheets>\
**Useful links:**\
\* W3C has a CSS validator, located at
<http://jigsaw.w3.org/css-validator/>
- w3cs pages about css
- HTMLDog CSS Beginners
Guide
- CSS Zen Garden \-- See whats possible
with CSS
- Cascading Style Sheet
References
\-- L. Carlson, University of Minnesota Duluth.
- Web Design
Update -
A a plain text email digest newsletter. It typically goes out once a
week and has a section on CSS. All web designers and developers are
invited to join.
- - Cascading Style Sheets
Books
## Exercises
### Exercise 1
Using the CSS file provided below, create a price list for books as an
XML document.
```{=html}
<?xml version="1.0"?>
```
Exercise1.css:
<book> Lord of the rings</book> book{
display: block;
background-color: transparent;
margin: 20px 10px 10px 200px;
}
<isbn>1.000.56439 </isbn> isbn{
display: block;
font: 12pt/15pt georgia, serif;
}
<title> The Two Towers </title> title {
display: block;
font: 14pt/18pt verdana, sans-serif;
}
<author> J.R.R. Tolkien </author> author {
display: block;
font: italic 12pt/15pt georgia, serif;
}
<publisher> Penguin </author> author {
display: block;
font: 12pt/15pt georgia, serif;
}
<price> 48 EUR </price> price{
display: block;
font: bold 12pt/15pt georgia, serif;
color: #ff0000;
background-color: transparent;
}
### Exercise 2
Create a personal homepage, where you introduce yourself.
The page should contain one header, one footer, and navigation as a list
of links.
### Solutions
Solutions
### CSS Challenges
Copy and paste the HTML, then take up the challenge to create a
stylesheet to match the picture!
|
# XML - Managing Data Exchange/Cocoon
------------------------------------------------------------------------
```{=html}
<table cellspacing=10 cellpadding=10 border=5>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<font size=4>`{=html}`<b>`{=html}Learning
objectives`</b>`{=html}`</font>`{=html}\
- `<font size=3>`{=html} Understand the function of
Cocoon`</font>`{=html}
- `<font size=3>`{=html} Create a working sitemap`</font>`{=html}
- `<font size=3>`{=html} Make available a stylesheet-formatted XML
document`</font>`{=html}
- `<font size=3>`{=html} Create a simple Cocoon form`</font>`{=html}
- `<font size=3>`{=html} Create a simple XSP`</font>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
sponsored by:\
\
```{=html}
<center>
```
`<font size=3>`{=html}`<b>`{=html}The University of
Georgia`</b>`{=html}`</font>`{=html}\
\
`<font size=5 color=#990000>`{=html}`<b>`{=html}Terry College of
Business`</b>`{=html}`</font>`{=html}\
\
`<font size=3>`{=html}`<b>`{=html}Department of Management Information
Systems`</b>`{=html}`</font>`{=html}
```{=html}
</center>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
\
## Introduction
Cocoon is a product of the Apache Software Foundation. It is a powerful
server heavily based on Java and XML technology. While it does have a
command line interface, most users will be able to do everything they
need to with it simply through careful editing of a few configuration
files, formatted as XML documents. If you want to see some examples of
what Cocoon can do, go to <http://MIST5730.terry.uga.edu:8080/cocoon/>.
## Assumptions
This tutorial is set up based on the user having access to an
installation of Cocoon on Terry's Blaze server. If you do not have this
access, simply replace file locations and access methods with those
provided by your server administrator. Some programs described may be
Windows-only; you will need to find out a suitable replacement if you
are a Macintosh or Linux user, although these utilities are often
included with the operating system. JEdit is a free text editor that can
read and save files on an FTP or SFTP server as easily as on a hard
disk, and properly manipulate many different types of files, with the
proper plugins. It is available for Windows, Macintosh, some Linux
distributions and as a platform-independent Java application at
<http://www.jedit.org/>.
## The Sitemap
The primary Cocoon file to be concerned with is sitemap.xmap, located in
the root Cocoon directory. It uses XML tags to define things such as
different ways to present data, the location of important files,
identification of browsers, and the most important aspect, pipelines.
The default xmap will be fine for our purposes, and we will only need to
look at the last few lines of it, where pipeline matches are defined.
This section begins at the tag `<map:pipeline>`{=html}. A pipeline match
looks like this:
``` XML
<map:match pattern=”test”>
<map:generate type=”file” src=”content/test.xml”/>
<map:transform type=”xslt” src=”stylesheets/test.xslt”/>
<map:serialize type=”html”/>
</map:match>
```
Let's look at what each line does. The first line tells Cocoon to watch
for someone browsing to
<http://blaze.terry.uga.edu:8080/cocoon/otc/test>. When this happens,
the actions on the next three lines take place. Cocoon will take the
information from the file test.xml within the content directory, and
apply the stylesheet test.xslt from the stylesheets directory. It
formats this result as an html page, as specified on the fourth line.
Cocoon can use different serializers to format data as an html or xhtml
page, flash object, pdf, or even OpenOffice document. Unlike when
working with XML for other purposes, no XSD schema is needed -- simply
create and populate fields in the XML file as necessary.
## Cocoon Forms
Cocoon forms, or CForms, are a way to use XML structure to create
validating form field objects and then arrange them in a template for
use. The primary advantage of CForms over using HTML forms is that
fields can be validated either with built-in functionality or simple XML
attributes. There are several elements required for this. A definition
XML file, which holds the fields, called \"widgets\":
``` XML
<fd:field id="email" required="true">
<fd:label>Email address:</fd:label>
<fd:datatype base="string"/>
<fd:validation>
<fd:email/>
</fd:validation>
</fd:field>
```
\
A template XML file calls on these widgets, adding HTML code to help
with look and feel:
``` html4strict
<br/>
<ft:widget-label id="email"/>
<ft:widget id="email"/>
```
A Javascript file that controls the flow of data from one file to the
next:
``` javascript
function registration() {
var form = new Form("registration_definition.xml");
form.showForm("registration-display-pipeline");
var viewData = { "username" : form.getChild("name").getValue() }
cocoon.sendPage("registration-success-pipeline", viewData);
}
```
Pipelines in the sitemap that also control flow:
``` XML
<map:match pattern="registration">
<map:call function="registration"/>
</map:match>
...
<map:match pattern="registration-display-pipeline">
<map:generate type="jx" src="registration_template.xml"/>
<map:transform type="i18n">
<map:parameter name="locale" value="en-US"/>
</map:transform>
<map:transform src="forms-samples-styling.xsl"/>
<map:serialize/>
</map:match>
...
<map:match pattern="registration-success-pipeline">
<map:generate type="jx" src="registration_success.jx"/>
<map:serialize/>
</map:match>
```
An XSP can be used in this flow in order to pass submissions to a
database.
## XSPs
XSPs function similarly to JSPs and servlets - they are server-side
applications that can support many users at once. Unlike JSPs and
servlets, XSPs can use XML tags to accomplish much of their
functionality, although they can also use Java code between
`<xsp:logic>`{=html}`</xsp:logic>`{=html} tags. One good use for XSPs is
passing information to a database or recalling and displaying stored
data. While JSPs and servlets have to either call a specific database
connector or contain all of the code for connecting within them, Cocoon
has a configuration file which holds this information, and XSPs just
call the name of the database as specified in WEB-INF/cocoon.xconf:
`<esql:pool>`{=html}`dbname``</esql:pool>`{=html}
XSP code to enter data from a form might look like this:
` ``<esql:execute-query>`{=html}\
` ``<esql:query>`{=html}\
` ``INSERT into otc_users (name,email,password,age,spam) values ('``<xsp:expr>`{=html}`esc_name``</xsp:expr>`{=html}`','``<xsp-request:get-parameter name="email"/>`{=html}`','``<xsp-request:get-parameter name="password"/>`{=html}`','``<xsp-request:get-parameter name="age"/>`{=html}`','``<xsp-request:get-parameter name="spam"/>`{=html}`')`\
` ``</esql:query>`{=html}\
` ``</esql:execute-query>`{=html}
## Exercises
1. Create a basic XML file and accompanying html stylesheet. Upload
them into the proper folders (content and stylesheets respectively)
on the Blaze server, and write a pipeline match that would enable
you to view the XML content with your stylesheet applied in a
browser. Files and match pattern should be named after your own
name, for example Bob Jones would use "bjones." It is not necessary
to upload the pipeline code - simply browse to
<http://blaze.terry.uga.edu:8080/cocoon/otc/yourname> and it should
be visible.
2. Follow along with the CForms example located at
<http://cocoon.apache.org/2.1/userdocs/basics/sample.html>. Create
and implement at least one widget of your own making. You can view
this at work by browsing to
<http://blaze.terry.uga.edu:8080/cocoon/cforms/registration>.
3. Browse to opt/tomcat5/webapps/cocoon/cforms on Blaze. Examine
sitemap-modified.xmap to see how the pipelines could be modified to
pass CForm data to an XSP. Test.xsp shows how that data could be
inserted into or called from a database.
## Appendix - Accessing the Blaze server
When you have an account set up on the Blaze server, there are several
steps you will need to take in order to be able to work with files in
the Cocoon directory. Generally, new user accounts are set up with the
user's UGA MyId as the username, and social security number as the
password. This password must be changed at the user's first login, which
requires using an SSH client to accomplish. UGA students can download
Secure Shell Utilities 3.1 at <http://sitesoft.uga.edu/>. Two programs
are installed by this download, Secure Shell Client and Secure File
Transfer Client.
Open the Secure Shell client and click the "Quick Connect" button
located near the top of the window. In the resulting window, enter
"blaze.terry.uga.edu" as the Host Name, and your specified username as
User Name. Port Number should be set to "22", and Authentication Method
should be "Passworded". Click "Connect". In the resulting window, enter
your given password and click "Ok". You may see a window asking to save
the new host key, click "Yes". You will now be presented with a text
box. It will notify you that your password has expired and must be
changed. You will need to enter your given password once, hit enter,
enter your desired new password, hit enter, and again enter your desired
new password and hit enter. Be aware that nothing you type will show up
for security purposes, and you will not be able to delete any typos -
you\'ll have to log in and start over if you mess up. This is all we
will be using the Secure Shell Client application for; you can click the
"Disconnect" button in the row of small buttons at the top of the
screen, and then exit the program.
In order to actually access files on the Blaze server, the Secure File
Transfer Client is used. Open it and click the "Quick Connect" button
located near the top of the window, entering the same Host Name as with
the Secure Shell Client, your new password, and make sure the other
settings are the same. Click "Connect." You will be presented with a
Windows Explorer-type screen where you can browse through the files on
the Blaze server. To access our Cocoon installation go to the "opt"
folder, then the "tomcat5" folder, then the "webapps" folder, then the
cocoon folder. Most of our work will be done in the "otc" folder within.
To download a file for editing, simply highlight it and click the
"Download" button in the row of small buttons at the top of the screen.
Once you select a download location and click "Download." You can then
open it in your editor of choice. To upload a file to the server, simply
do the reverse -- click the "Upload" button in the row of small buttons
as the top of the screen, select a file to upload, and click "Upload,"
which will put the file in the folder you are currently viewing on the
Blaze server.
|
# XML - Managing Data Exchange/Parsing XML files
+----------------------------------------------------------------------+
| `<font size=4>`{=html}`<b>`{=html}Learning |
| objectives`</b>`{=html}`</font>`{=html}\ |
| |
| - `<font size=3>`{=html}Understand the concept of parsing XML |
| files`</font>`{=html} |
| - `<font size=3>`{=html}Use different APIs for processing XML |
| files `</font>`{=html} |
| - `<font size=3>`{=html}Be aware of the differences between |
| different approaches for parsing XML files `</font>`{=html} |
| - `<font size=3>`{=html}Decide when to use a particular |
| technique`</font>`{=html} |
+----------------------------------------------------------------------+
In the earlier chapters we were taught how to create XML
files in
detail. This involved the development of XML
documents, Style
sheets and
Schema and their validation.
In this chapter, we will focus on different approaches for parsing XML
files and
when to use them.
But first, it is time to refresh what we have learned about parsing.
## The Process of Parsing XML files
One goal of the XML format was to enhance raw data formats like plain
text by including detailed descriptions of the meaning of the content.
Now, in order to be able to read XML files, we use a parser which
basically exposes the document's content through a so-called API
(application programming interface). In other words, a client
application accesses the content of the XML document through an
interface, instead of having to interpret the XML code on its own!
### Simple Text Parsing
One way to extract data from an XML document is simple text parsing --
browsing all characters in the document and check for a desired pattern:
``` XML
<house>
<value><int>150,000</int></value>
</house>
```
Let's say we are interested in the value of the house. Using straight
text parsing, we would scan the file for the character sequence
<int> and call it the start pattern. Then, we
would further scan the document for the end pattern (i.e.
</int></value>). Finally, we
declare the text string in between these two patterns to be the value of
the surrounding <house>...</house> tag.
### Why it doesn\'t work that way
Obviously, this approach is not suitable for extracting information from
large and complex XML documents, since we would have to know exactly
what the file looks like and where the information needed is located.
From a more general point of view, the structure and semantics of an XML
file is determined by the makeup of the document, its tags and
attributes -- hence, we need a device that is able to recognize and
understand this structure and can point out any errors in it. Moreover,
it has to provide the content of the document through an interface, so
that other applications can access it without difficulty. This device is
known as an XML parser.
### What a parser does
Almost all programs that need to process XML documents use an XML parser
to extract the information stored in the XML document in order to avoid
any of the difficulties that occur when reading and interpreting raw XML
data. The parser usually is a class library (e.g. a set of Java class
files) that reads a given document and checks if it is well-formed
according to the W3C specification. Then, any client software can use
methods of the interface provided by the parser API to access the
information the parser retrieved from the XML file.
All in all, the parser shields the user from dealing with the complex
details of XML like assembling information distributed over several XML
files, checking for well-formedness constraints, and so on.
## Parsing: an Example
To illustrate more clearly what parsing an XML file really means, the
following example was created which contains information about some
cities. It also keeps track of who is on vacation and demonstrates the
parsing process with the currently most common parsing methods.
### Example: *cities.xml*
``` XML
<?xml version="1.0" encoding="UTF-8" ?>
<cities>
<city vacation="Sam">
<cityName>Atlanta</cityName>
<cityCountry>USA</cityCountry>
</city>
<city vacation="David">
<cityName>Sydney</cityName>
<cityCountry>Australia</cityCountry>
</city>
<city vacation="Pune">
<cityName>Athens</cityName>
<cityCountry>Greece</cityCountry>
</city>
</cities>
```
Based on the information stored in this XML document, we can easily
check who is on vacation and where. The parser will read the file using
one of the various techniques presented later in this chapter.
This process is very complicated and prone to errors of all kinds.
Luckily, we will never have to write code for it, because there are
plenty of free, fully-functional parsers on the Web. All we do is
download a parser class library and access the XML document through the
interface provided by the parser software. With more recent builds of
Java, most parsers do not even have to be downloaded. In other words, we
use the functions or methods included in the class library for
extracting the information.
Basically, a parser reads the XML document and tries to recognize the
structure of the file itself while checking for errors. It simply checks
for start/end tags, attributes, namespaces, prefixes, and so on. Then,
the client software can access the information derived from this
structure using methods provided by the parser software (i.e. the
interface).
The best way to learn about the functionality of a parser is to actually
use them; therefore, the next section demonstrates the different methods
of parsing.
## Parser APIs (Application Programming Interface)
### Overview
There are two "traditional" approaches that dominate the market right
now, an event-based push-model as represented by SAX (Simple API for
XML) and a tree-based model using the DOM (document object model)
approach.
However, there is a movement towards newer approaches and techniques
that try to overcome the flaws inherent in these traditional models --
an event-based pull-model and a "cursor model", such as VTD-XML, which
allows us to browse the XML document just like in the tree-based
approach, but simpler and easier to use.
### SAX (Simple API for XML)
#### Description
The push model, typically the exemplified by SAX (www.saxproject.org) is
the "gold standard" of XML parsing, since it is probably the most
complete and accurate method so far. The SAX classes provide an
interface between the input streams from which XML documents are read
and the client software which receives the data made available by the
parser. The parser browses through the whole document and fires events
every time it recognizes an XML construct (e.g. it recognizes a start
tag and fires an event -- the client software is notified and can use
this information... or not).
#### Evaluation
The advantage of such a model is that we don't need to store the whole
XML document in memory, since we are only reading one piece of
information at a time. If you recall that the XML structure is a set of
nodes of various types (like an element node) -- parsing the document
with a SAX parser means going through each node one at a time. This
makes it possible to read even very large XML documents in a
memory-efficient way. However, the fact that the parser only provides
information about the node currently read also implies that the
programmer of the client software is in charge of saving certain
information in a separate data structure (e.g. the parents or children
of the currently processed node). Moreover, the SAX approach is pretty
much read-only, since it is hard to modify the XML structure when we do
not have some sort of global view.
In fact, the parser is in control of what is read when. The user can
only wait until a certain event has occurred and then use the
information stored in the currently processed node.
#### Example: *TGSAXParser.java*
As mentioned before, the best way to fully understand the concept of the
parsing process is to actually use it. In the following code sample, the
information about the name and country of the cities that people are
vacationing in will be displayed. The SAX API that is part of the Xerces
parser package was used for the implementation ((Xerces 2
Homepage):
``` java
// import the basic SAX API classes
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import java.io.*;
public class TGSAXParser extends DefaultHandler
{
public boolean onVacation = false;
// what to do when a start-element event was triggered
public void startElement(String uri, String name, String qName, Attributes atts)
{
// stores the string in the XML file
String vacationer = atts.getValue("vacation");
String cityName = atts.getValue("cityName");
String cityCountry = atts.getValue("cityCountry");
// if the start tag is "city" set vacationer to true
if (qName.equals("city") && (vacationer != null))
{
onVacation = true;
System.out.print("\n" + vacationer + " is on vacation in ");
}
if (qName.equals("cityName") && onVacation)
{
}
if (qName.equals("cityCountry") && onVacation)
{
}
}
/**This method is used to stop printing information once the element has
*been read. It will also reset the onVacation variable for the next
*element.
*/
public void endElement(String uri, String name, String qName)
{
//reset flag
if (qName.equals("city"))
{
onVacation = false;
}
}
/**This method is triggered to store and print the values between
*the XML tags. It will only print those values if onVacation == true.
*/
public void characters(char[] ch, int start, int length)
{
if (onVacation)
{
for (int i = start; i < start + length; i++)
System.out.print(ch[i]);
}
}
public static void main(String[] args)
{
System.out.println("People on vacation in the following cities:");
try
{
// create a SAX parser from the Xerces package
XMLReader xml = XMLReaderFactory.createXMLReader();
TGSAXParser handler = new TGSAXParser();
xml.setContentHandler(handler);
xml.setErrorHandler(handler);
FileReader r = new FileReader("cities.xml");
xml.parse(new InputSource(r));
}
catch (SAXException se)
{
System.out.println("XML Parsing Error: " + se);
}
catch (IOException io)
{
System.out.println("File I/O Error: " + io);
}
}
}
```
The `DefaultHandler`: As mentioned before, SAX is completely
event-driven. Therefore, we need a handler that "listens" to the input
stream coming from the input file (*cities.xml* in this case).
The SAX API provides interface classes, which we have to extend with our
own code to read our own specific XML document. In order to include our
code in the SAX API, we just have to extend the DefaultHandler interface
with our own class and set the content handler to our custom handler
class (which consists of three methods: startElement, endElement and
characters)
The `startElement()` and `endElement()` methods: These methods are
invoked whenever the SAX parser finds a start or end tag respectively.
The SAX API provides blank stubs for both methods and we have to fill
them with code of our own.
In this case, we want our program to do something whenever the
`vacation` attribute is set, so we set a Boolean variable to true
whenever we find such an element and process the node by printing out
the character sequence in between the start and end tag. The `character`
method is automatically called whenever a `startElement` and
`endElement` event was triggered, but prints out the character string
only if the `onVacation` attribute is set.
### DOM (Document Object Model)
#### Description
The other popular approach is the tree-based model as represented by the
DOM (document object model, see W3C
Recommendation). This method actually
works similarly to a SAX parser, since it reads the XML document from an
input stream by browsing through the file and recognizing XML
structures.
This time, instead of returning the content of the document in a series
of small fragments, the DOM method maps the XML hierarchy to a DOM tree
object that contains everything from the original XML document.
Everything from elements, comments, textual information or processing
instructions is stored in the tree object as nodes, starting with the
document itself as the root node.
Now that all the information we need is stored in memory, we access the
data by using methods provided by the parser software to read or modify
objects within the tree. This facilitates random access to the content
of the XML document and provides the possibility to modify the data it
contains or even create new XML files by transforming a DOM back to an
XML document.
#### Evaluation
However, the major downside of this approach is that it requires much
more memory and is therefore not suitable for situations where large XML
files are used. More importantly, it is somewhat more complex than the
simplistic SAX method even for small and simple problems.
#### Example: *MyDOMParser.java*
In the following code sample, a list of cities with people on vacation
is again created but this time with the tree-based approach:
``` java
// import all necessary DOM API classes
import org.apache.xerces.parsers.*;
import org.apache.xerces.dom.*;
import org.w3c.dom.*;
public class MyDOMParser{
public static void main(String[] args) {
System.out.println("People on vacation in the following cities:");
try {
// creates a DOM parser object
DOMParser parser = new DOMParser();
parser.parse("cities.xml");
// stores the tree object in a variable
org.w3c.dom.Document doc = parser.getDocument();
// returns a list of all city elements in my city list
NodeList list = doc.getElementsByTagName("city");
// now, for every element in the city list, check if the
// "vacation" attribute is set and if yes, print out the
// information about the vacationer.
for(int i = 0, length = list.getLength(); i < length; i++){
Element city = (Element)list.item(i);
Attr vacationer = city.getAttributeNode("vacation");
if(vacationer!= null){
String v = vacationer.getValue();
System.out.print(v + " is vacationing in ");
// grab information about city name and country
// directly from the DOM tree object
ParentNode cityname = (ParentNode)
doc.getElementsByTagName("cityName").item(0);
ParentNode country = (ParentNode)
doc.getElementsByTagName("cityCountry").item(0);
System.out.println(cityname.getTextContent() + ", " + country.getTextContent());
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
```
_`parser.getDocument()`:_ Once we parsed the XML
document, the tree object is temporarily stored in the parser variable.
In order to work with the DOM object, we have to create a variable
holding it (of type _`org.w3c.dom.Document`_).
Then, we create a _list of nodes holding all elements with
the tag name <city>_. The parser finds
these nodes by browsing through the DOM tree. Then, we just go through
each one of the city-elements and check if the `vacation` attribute is
set and display all the information about the vacationer if so.
Xerces provides a helpful method called
_`getTextContent()`_ that lets us directly access
the text node of an element node, avoiding all difficulties emerging
from unneeded white space and the like.
## Summary
Choosing an API at the beginning of your XML project is a very important
decision. Once you decide which one to use, it is easy to try different
vendors without having much trouble, but switching to a different API
will be a very time-consuming and costly process, since you will have to
redesign your whole program code.
The SAX API is a widely accepted and well-working parser that is easy to
implement and works especially well with streaming content (e.g. an
online XML source). Because it is a read-only API, you would not be able
to modify the underlying XML data source. Since it only reads one node
at a time, it is very memory-efficient and fast. However, this implies
that your application expects the information to be close together and
ordered.
If you want to randomly access the entire document at any point of time,
then the DOM approach might be a better choice for you. The DOM API is
more complex and harder to implement, but gives you full control over
the whole document and lets you modify the data, also. However, it reads
the whole XML document into memory, so the DOM API is not suitable for
projects with very large XML files.
```{=html}
<div style="color:#8b4513">
```
## Exercise
### Recommended optional exercise
*Use the code sample for the SAX and DOM parser from this chapter and
play around with it. You probably want to print out different nodes or
add more constraints. This absolutely optional, but will give you an
idea of the main differences between SAX and DOM.*
### Now for the exercise
- *Create a SAX parser to parse the file movies.xml. The output simply
needs to come from your IDE, it does not need to be sent onto a
webpage.*
*TO HELP YOU* download
this, it provides a
structure of the problem so that you can more easily run the app in
NetBeans 5.0.
If you're interested in using Xerces -- just download the following
file:
` ``http://www.apache.org/dist/xml/xerces-j/Xerces-J-bin.2.8.0.zip`
If the above link is dead. Go to
<http://www.apache.org/dist/xml/xerces-j/> and download the latest zip
binary file. It should be in the format of \"Xerces-J-bin.#.#.#.zip\"
Then put the content into the \\lib\\ext
subfolder of your NetBeans directory and start up NetBeans IDE. Now, the
Xerces package is successfully installed on your machine.
```{=html}
</div>
```
## Useful Links
1. <http://www.cafeconleche.org>
2. <http://www.xml.com>
3. <http://www.xmlpull.org>
4. <http://workshop.bea.com/xmlbeans/reference/com/bea/xml/XmlCursor.html>
5. <http://workshop.bea.com/xmlbeans/reference/com/bea/xml/XmlCursor.html>
{{/Answers}}
fr:Programmation XML/Parsing
|
# XML - Managing Data Exchange/XUL
+-----------------------------------------------+
| **Learning objectives** |
| |
| - Get a brief overview of what XUL is. |
| - Learn about the basic tag/widget library. |
| - Create some simple, static XUL web pages. |
| - Add event handlers to a XUL page. |
+-----------------------------------------------+
| |
+-----------------------------------------------+
## Introduction
XUL (pronounced zool and rhymes with cool), which stands for eXtensible
User interface Language, is an XML-based user interface language
originally developed for use in the Netscape browser. It is now
maintained by Mozilla. It is a part of Mozilla Firefox and many other
Mozilla applications, and is available as part of Gecko, the rendering
engine developed by Mozilla. In fact, XUL is powerful enough that the
entire user interface in the Firefox application is implemented in XUL.
Like HTML, in XUL you can create an interface using a relatively simple
markup language, define the appearance with CSS style sheets, and use
JavaScript to manipulate behavior. Unlike HTML, however, XUL provides a
rich set of user interface widgets to create, for example, menus,
toolbars and tabbed panels.
To put it in simple terms, XUL can be used to create lightweight,
cross-platform, cross-device user interfaces.
Many applications are developed using features of a specific platform
that makes building cross-platform software time-consuming and costly.
Some users may want to use an application on technologies other than
traditional computers, such as small handheld devices. To date, there
have been some cross-platform solutions already developed. Java, for
example, was created just for such a purpose. However, creating GUIs
with Java is cumbersome at best. Alternatively, XUL has been designed
for building portable user interfaces easily and quickly. It is
available on most versions of Windows, Mac OS X, Linux and Unix. Yahoo!
currently uses XUL and related technologies for its Yahoo! tool bar (a
Firefox extension) and Photomail application.
To illustrate XUL's potential, this chapter will work through a few
examples. Potential is the correct word here. The full capabilities of
XUL are beyond the scope of this chapter but it is designed to give the
reader a first look at the power of XUL. One more thing needs to be
noted: you'll need a Gecko-based browser (such as Firefox or the Mozilla
Suite) or XULRunner to
work with XUL.
## The Basics
XUL is XML, and like all good XML files, a good XUL file begins with the
standard XML version declaration. Currently, XUL is using the XML
version 1.0.
To make your XUL page look good, you must include a *global* stylesheet
in it. The URI of the default stylesheet is *href =
\"<chrome://global/skin/>\"*. While you can load as many stylesheets as
you like, it is best practice to load the global stylesheet initially.
Look at Fig.1. Notice the reference to "chrome". 'The chrome is the part
of the application window that lies outside of a window\'s content area.
Toolbars, menu bars, progress bars, and window title bars are all
examples of elements that are typically part of the chrome.'(1) Chrome
is the descriptive term used to name all of the elements in a XUL
application. Think of it like the chrome on the outside of a car. It's
what catches your eye. The elements in a XUL file are what you see in
the browser window.
All XML documents must have a namespace declaration. The developers of
XUL have provided a namespace that shows where they came up with the
name XUL. (The reference is from the movie 'Ghostbusters' for the
uninitiated)
``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window
id="window identifier"
title="XUL page"
orient="horizontal"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
. . . (add elements here)
</window>
```
The next thing to note is the tag `<window>`{=html}. This tag is
analogous to the
```{=html}
<body>
```
tag in HTML. All the elements will live inside the window tag. In Fig. 1
the window tag has three attributes that are very important. The 'id'
attribute is important in that it is the way to identify the window so
that scripts can refer to it. While the title attribute is not
necessary, it is good practice to provide a descriptive name. The value
of title will be displayed in the title bar of the window. The next
attribute is very important. This tells the browser in what direction to
lay out the elements described in the XUL file. Horizontal means just
that. Lay out in succession across the window. Vertical is the opposite;
it adds the elements in column format. Vertical is the default value so
if you do not declare this attribute you'll get vertical orientation.
As was stated earlier, a XUL document is used to create user interfaces.
UI\'s are generally full of interactive components such as text boxes,
buttons and the like. A XUL document accomplishes this with the use of
widgets, which are self-contained components with pre-defined behavior.
For example buttons will respond to mouse clicks and menu bars can hold
buttons. All the normally accepted actions of GUI components are built
in to the widgets. There is already a rich library of predefined
widgets, but because this is open source, any one can define a widget or
a set of widgets for themselves.
The widgets are 'disconnected' until they are programmed to work
together. This can be done simply with JavaScript or a more complex
application can be made using something like C++ or Java. In this
chapter we will use JavaScript to illustrate XUL's uses and potential.
Also, a XUL file should have .xul extension. The Mozilla browser will
automatically recognize it and know what to do with it when you click on
it. Optionally, an .xml extension could be used but you would have to
open the file within the browser.
One more thing needs to be mentioned. There are a few syntax rules to
follow and they are:
- All events and attributes must be written in lowercase.
- All strings must be double quoted.
- Every XUL widget must use close tags (either
`<tag>`{=html}`</tag>`{=html} or `<tag/>`{=html}) to be well-formed.
- All attributes must have a value.
## A First Example
What better way to start then with the good old 'Hello World' example.
Open up a text editor (not MS Word) like notepad or TextPad and type in:
``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window
id="Hello"
title="Hello World Example"
orient="vertical"
persist="screenX screenY width height"
xmlns= "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<description style='font-size:24pt'>Hello World</description>
<description value='Hello World' style='font-size:24pt'/>
<label value = 'Hello World' style='font-size:24pt'/>
</window>
```
Save it anywhere but be sure to give the file the .xul extension. Now
just double click on it and it should open in your Mozilla or Netscape
browser. You should get 'Hello World' three times, one on top of the
other. Notice the different ways that 'Hello World' was printed: twice
from a description tag and once from a label tag. Both
`<description>`{=html} and `<label>`{=html} are text related tags. Using
the description tag is the only way to write text that is not contents
of a 'value' attribute. This means that you can write text that isn\'t
necessarily assigned to a variable. In the second and third examples the
text is expressed as an attribute to the tag description or label,
respectively. You can see here that the orient attribute in window is
set to 'vertical'. That is why the text is output in a column.
Otherwise, if orient was set to 'horizontal', all the text would be on
one line. Try it.
Now let's start adding some more interesting elements.
## Adding Widgets
As stated earlier, XUL has an existing rich library of elements fondly
called widgets. These include buttons, text boxes, progress bars,
sliders and a host of other useful items. One good listing is the XUL
Programmer\'s Reference.
Let us take a look at some simple buttons. Enter the following code and
place it into a Notepad or other text editor that is not MS Word.
``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window
id="findfile-window"
title="Find Files"
orient="horizontal"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<button id="find-button" label="Find" default="true"/>
<button id="cancel-button" label="Cancel"/>
</window>
```
Save it and give the file the .xul extension. Open a Mozilla or Netscape
browser and open the file from the browser. You should see a \"find\"
button and a \"cancel button\". From here it is possible to add more
functionality and build up elaborate interfaces.
There has to be some place to put all of these things and like the
```{=html}
<body>
```
tag in HTML, the `<box>`{=html} tag in XUL is used to house the widgets.
In other words, boxes are containers that encapsulate other elements.
There are a number of different `<box>`{=html} types. In this example
we'll use `<hbox>`{=html}, `<vbox>`{=html}, `<toolbox>`{=html} and
`<tabbox>`{=html}.
`<hbox>`{=html} and `<vbox>`{=html} are synonymous with the attributes
\'orient = \"horizontal\"\' and \'orient = \"vertical\"\', which
respectively form the `<window>`{=html} tag. By using these two boxes,
discrete sections of the window can have their own orientation. These
two elements can hold all of the other elements and can even be nested.
The tags `<toolbox>`{=html} and `<tabbox>`{=html} serve special
purposes. `<toolbox>`{=html} is used to create tool bars at the top or
bottom of the window while `<tabbox>`{=html} sets up a series of tabbed
sheets in the window.
Take the XUL framework from Fig. 1 and replace \". . .( add elements
here)\" with a `<vbox>`{=html} tag pair (that\'s both open and close
tags). This will be the outside container for the rest of the elements.
Remember, the `<vbox>`{=html} means that elements will be positioned
vertically in order of appearance. Add the attribute \'flex=\"1\"\'.
This will make the menu bar extend all the way across the window.
``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window
id="findfile-window"
title="Find Files"
orient="horizontal"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<vbox flex="1">
(... add elements here)
</vbox>
</window>
```
The \'flex\' attribute needs some explanation since it is a primary way
of sizing and positioning the elements on a page. Flex is a dynamic way
of sizing and positioning widgets in a window. The higher the flex
number (1 being highest), the more that widget gets priority sizing and
placement over widgets with lower flex settings. All elements have size
attributes, such as width and/or height, that can be set to an exact
number of pixels but using flex insures the same relative sizing and
positioning when resizing a window occurs.
Now put a pair each of `<toolbox>`{=html} and `<tabbox>`{=html} tags
inside of the `<vbox>`{=html} tags with `<toolbox>`{=html} first. As was
said `<toolbox>`{=html} is used to create tool bars so lets add a
toolbar similar to the one at the top of the browser.
This is the code so far:
``` XML
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window
id="findfile-window"
title="Find Files"
orient="horizontal"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<vbox flex="1">
<toolbox>
<menubar id="MenuBar">
<menu id="File" label="File" accesskey="f">
<menupopup id="FileMenu">
<menuitem label="New" accesskey="n"/>
<menuitem label="Open..." accesskey="o"/>
<menuitem label="Save" accesskey="s"/>
<menuitem label="Save As..." accesskey="s"/>
<menuitem label=" ... "/>
<menuseparator/>
<menuitem label="Close" accesskey="c" />
</menupopup>
</menu>
<menu id="Edit" label="Edit" accesskey="e">
<menupopup id="EditMenu">
<menuitem label="Cut" accesskey="t" acceltext="Ctrl + X"/>
<menuitem label="Copy" accesskey="c" acceltext="Ctrl + C"/>
<menuitem label="Paste" accesskey="p" disabled="true"/>
</menupopup>
</menu>
<menu id="View" label="View" accesskey="v">
<menupopup id="ViewMenu">
<menuitem id="Tool Bar1" label="Tool Bar1"
type="checkbox" accesskey="1" checked="true"/>
<menuitem id="Tool Bar2" label="Tool Bar2"
type="checkbox" accesskey="2" checked="false"/>
</menupopup>
</menu>
</menubar>
</toolbox>
<tabbox>
</tabbox>
</vbox>
</window>
```
There should now be a menu bar with "File Edit View" in it and they
should each expand when you click on them. Let's examine the elements
and their attributes more closely to see how they work.
First the `<menubar>`{=html} holds all of the menu items (File, Edit
,View). Next there are the three different menu items. Each menu has a
set of elements and attributes. The `<menupopup>`{=html} does just it
says. It creates the popup menu that occurs when the menu label is
clicked. In the popup menu is the list of menu items. Each of these has
an \'accesskey\' attribute. This attribute underlines the letter and
provides the reference for making a hot key for that menu item. Notice
in the Edit menu, both \'Cut\' and \'Copy\' have accelerator text
labels. In the File menu there is a `<menuseperator/>`{=html} tag. This
places a line across the menu that acts as a visual separator. In the
Edit menu, notice the menu item labeled \'Paste\' has an attribute:
disabled=\"true\". This causes the Paste label to be grayed out in that
menu and finally in the View menu the menu items there are actually
checkboxes. The first one is checked by default and the second one is
not.
Now on to the `<tabbox>`{=html}. Let\'s make three different sheets with
different elements on them. Put this code in between the
`<tabbox>`{=html} tags:
``` XML
<tabbox flex="1">
<tabs>
<tab id="Tab1" label="Sheet1" selected="true"/>
<tab id="Tab2" label="Sheet2"/>
<tab id="Tab3" label="Sheet3"/>
</tabs>
<tabpanels flex="1">
<tabpanel flex="1" id="Tab1Sheet" orient="vertical" >
<description style="color:teal;">
This doesn't do much.
Just shows some of the style attributes.
</description>
</tabpanel>
<tabpanel flex="1" id="Tab2Sheet" orient="vertical">
<description class="normal">
Hey, the slider works (for free).
</description>
<scrollbar/>
</tabpanel>
<tabpanel flex="1" id="Tab3Sheet" orient="vertical">
<hbox>
<text value="Progress Meter" id="txt" style="display:visible;"/>
<progressmeter id="prgmeter" mode="undetermined"
style="display:visible;" label="Progress Bar"/>
</hbox>
<description value="Wow, XUL! I mean cool!"/>
</tabpanel>
</tabpanels>
</tabbox>
```
The tabs **are first defined** with `<tab>`{=html}. They are given an id
and label. Next, a set of associated panels is created, each with
different content. The first one is to show that like HTML style sheets
can be applied in line. The second two sheets have component type
elements in them. See how the slider works and the progress bar is
running on its own.
XUL has a number of types of elements for creating list boxes. A list
box displays items in the form of a list. Any item in such a particular
list can be selected. XUL provides two types of elements to create
lists, a listbox element to create multi-row list boxes, and a menulist
element to create drop-down list boxes, as we have already seen.
The simplest list box uses the listbox element for the box itself, and
the listitem element for each item. For example, this list box will have
four rows, one for each item.
``` XML
<listbox>
<listitem label="Butter Pecan"/>
<listitem label="Chocolate Chip"/>
<listitem label="Raspberry Ripple"/>
<listitem label="Squash Swirl"/>
</listbox>
```
Like with the HTML option element, you a value can be assigned using the
value attribute. The list box will set to a normal size, but you can
alter the size to a certain level using the row attributes. Set it to
the number of rows to display in the list box. A scroll bar will
automatically come up to let the user be able to see the rest of the
items in the list box if the box is too small.
``` XML
<listbox rows="3">
<listitem label="Butter Pecan" value="bpecan"/>
<listitem label="Chocolate Chip" value="chocchip"/>
<listitem label="Raspberry Ripple" value="raspripple"/>
<listitem label="Squash Swirl" value="squash"/>
</listbox>
```
Assigning values to each of the listitems lets the user be able to
reference them later using script. This way, other elements can be
reference this items to be used for alternative purposes.
All these elements are very nice and easy to put into a window, but by
themselves they don\'t do anything. Now we have to connect things with
some other code.
## Adding Event Handlers and Responding to Events
To make things really useful, some type of scripting or application
level coding has to be done. In our example, JavaScript will be used to
add functionality to the components. This is done in a similar fashion
as to scripting with HTML. With HTML, an event handler is associated
with an element and some action is initiated when that handler is
activated. Most of the handlers used with HTML are also found in XUL, in
addition to some unique ones. Scripting can be done in additional lines
of code, but a more efficient way is to create a separate file with the
needed scripts inside of it. This allows the page to load faster since
the rendering engine doesn't have to decide what to do with the embedded
script tags.
That being said, we'll first add a simple script, in line, as a first
example.
Let's add an 'onclick' event handler to fire an alert box when an
element is selected. Inside the `<window>`{=html} tag add the line
beginning with onclick:
``` XML
<window
onclick="alert(event.target.tagName); return false;"
id="findfile-window"
title="Find Files"
orient="horizontal"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
(... add elements here)
</window>
```
Now when you click on any element in the window, you created an alert
box that pops up telling you the name of the element. One interesting
thing to note: When you click on the text enclosed by the description
tag the response is undefined but when you click on the text wrapped by
the label tag you get the tabName label.
This implies that a description tag is not really an element. After
playing with the alert box, delete that line and add this inside the
opening tag of the 'Close' menu item in the 'File' menu:
``` XML
oncommand="window.close()"
```
Now when you click on 'Close' or use the 'C' as a hot key, the entire
window will close. The oncommand event handler is actually preferred
over onclick because oncommand can handle hot keys and other non-mouse
events.
Let's try one more thing. Add this right after the opening
`<window>`{=html} tag.
``` javascript
<script>
function show()
{
var meter=document.getElementById('prgmeter');
meter.setAttribute("style","display: visible;");
var tx=document.getElementById('txt');
tx.setAttribute("style","display: visible;");
}
function hide()
{
var meter=document.getElementById('prgmeter');
meter.setAttribute("style","display: none;");
var tx=document.getElementById('txt');
tx.setAttribute("style","display: none;");
}
</script>
```
These two functions first retrieve a reference to the progress meter and
the text element using their ids. Then both functions set the style
attributes of the progress meter and text element to have a display of
\'visible\' or 'none' which will do just that: hide or display those two
elements. (The tabpanel for the progress meter has to be displayed in
order to see these actions)
Now add two buttons that will provide the event to fire these two
methods. First, add a new box element to hold the buttons. The width
attribute of the box needs to be set otherwise the buttons will be laid
out to extend the length of the window.
``` XML
<box width="200px">
<button id="show" label="Show" default="true" oncommand="show();"/>
<button id="hide" label="Hide" default="true" oncommand="hide();"/>
</box>
```
### Style Sheets
Style sheets may be used both for creating themes, as well as modifying
elements for a more elaborate user interfaces. XUL uses CSS (Cascading
Style Sheets) for this. A style sheet is a file which contains style
information for elements. The style sheet makes it possible to apply
certain fonts, colors, borders, and size to the elements of your choice.
Mozilla applies a default style sheet to each XUL window. So far, this
is the style sheet that has been used for all the XUL documents:
``` XML
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
```
That line gives the XUL document the default <chrome://global/skin/>
style sheet. In Mozilla, this will be translated as the file global.css,
which contains default style information for XUL elements. The file will
still show is this line is left out but it will not be as aesthetically
pleasing. The style sheet applies theme-specific fonts, colors and
borders to make the elements look more suitable. Even though style
sheets can provide a better looking file, adding styles cannot always
provide a better view. Some CSS properties do not affect the appearance
of a widget, such as those that change the size or margins. In XUL, the
use of the \"flex: attribute should be used instead of using specific
sizes. There are other ways that CSS does not apply, and may be to
advanced for this tutorial.
Using a style sheet that you perhaps have already made, you just have to
insert one extra line of code pointing to the CSS file you have already
made.
``` XML
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<?xml-stylesheet href="findfile.css" type="text/css"?>
```
This second line of code references the style sheet, and will take over
as the default style sheet used for the XUL document. Sometimes it is
desired not to have the style that comes with the default CSS file.
### Answers
## Conclusion
The examples shown in this chapter merely scratch the surface of XUL's
capabilities. Even though these examples are very simple, one can see
how easy it would be to create more complex UI's with XUL. With a
complete set of the standard components such as buttons and text boxes
at the programmer's disposal, the programmer can code anything in XUL
that can be coded in HTML. The cross-platform ability of XUL is another
bonus but the fact that it doesn't work with Microsoft's Internet
Explorer may suppress XUL's widespread use. There is some hope that due
to the delay in the development of the next version of IE that XUL may
find it's way into IE, but don't hold your breath..
## References
1. \'Configurable
Chrome\' by Dave
Hyatt ([email protected]) (Last Modified 4/7/99)
2. XML User Interface Language
(XUL) - The Mozilla
Organization
3. XulPlanet
4. XUL Programmer\'s Reference Manual, Fifth Draft: Updated for XUL
1.0
fr:Programmation XML/XUL
|
# XML - Managing Data Exchange/Web Services
+----------------------------------+----------------------------------+
| `<font size=4>`{=html}**Learning | sponsored by: |
| objectives**`</font>`{=html}\ | |
| | ```{=html} |
| - `<font size=3>`{=html} To | <center> |
| understand web services, and | ``` |
| what they can | `<font size=3>`{=html}**The |
| do.`</font>`{=html} | University of |
| - `<font size=3>`{=html} To | Georgia**`</font>`{=html} |
| know what SOAP is, and what | |
| web services use it for. | `<font size |
| `</font>`{=html} | =5 color=#990000>`{=html}**Terry |
| - `<font size=3>`{=html} To | College of |
| know what Web Services | Business**`</font>`{=html} |
| Description Language is, and | |
| how to read a WSDL | `< |
| file.`</font>`{=html} | font size=3>`{=html}**Department |
| - `<font size=3>`{=html} To | of Management Information |
| know what the Universal | Systems**`</font>`{=html} |
| Description, Discovery, and | |
| Integration (UDDI) standard | ```{=html} |
| is.`</font>`{=html} | </center> |
| - `<font size=3>`{=html} To | ``` |
| understand how to use Java | |
| to connect to a web | |
| service.`</font>`{=html} | |
+----------------------------------+----------------------------------+
## Web Services Overview
**Web Services** are a new breed of Web application. They are
self-contained, self-describing, modular applications that can be
published, located, and invoked across the Web. Web services perform
functions, which can be anything from simple requests to complicated
business processes. Once a Web service is deployed, other applications
(and other Web services) can discover and invoke the deployed service.
Web services make use of XML to describe the request and response, and
HTTP as its network transport.
The primary difference between a Web Service and a **web application**
relates to collaboration. Web applications are simply business
applications which are located or invoked using web protocols.
Similarly, Web Services also perform computing functions remotely over a
network. However, Web Services use internet protocols with the specific
intent of enabling inter operable machine to machine coordination.
Web Services have emerged as a solution to problems associated with
distributed computing. **Distributed computing** is the use of multiple
systems to perform a function rather than having a single system perform
it. The previous technologies used in distributed computing, primarily
Common Object Request Broker Architecture (CORBA) and Distributed
Component Object Model (DCOM), had some limitations. For example,
neither has achieved complete platform independence or easy transport
over firewalls. Additionally, DCOM is not vendor independent, being a
Microsoft product.
Some of the primary needs for a distributed computing standard were:
- Cross-platform support for Business to Business, as well as
internal, communication.
- Concordance with existing Internet infrastructure as much as
possible.
- Scalability, both in number and complexity of nodes.
- Internalization.
- Tolerance of failure.
- Vendor independence.
- Suitability for trivial and non-trivial requests.
Over time, business information systems became highly configured and
differentiated. This inevitably made system interaction extremely costly
and time consuming. Developers began realizing the benefits of
standardizing Web Service development. Using web standards seemed to be
an intuitive and logical step toward attaining these goals. Web
standards already provided a platform independent means for system
communication and were readily accepted by information system users.
The end result was the development of Web Services. A Web Service forms
a distributed environment, in which objects can be accessed remotely via
standardized interfaces. It uses a three-tiered model, defining a
service provider, a service consumer, and a service broker. This allows
the Web Service to be a loose relationship, so that if a service
provider goes down, the broker can always direct consumers to another
one. Similarly, there are many brokers, so consumers can always find an
available one. For communication, Web Services use open Web standards:
TCP/IP, HTTP, and XML based SOAP.
At higher levels technologies such as XAML, XLANG, (transactional
support for complex web transactions involving multiple web services)
and XKMS (ongoing work by Microsoft and Verisign to support
authentication and registration) might be added.
## SOAP
!SOAP structure{width="220"}
**Simple Object Access Protocol (SOAP)** is a method for sending
information to and from Web Services in an extensible format. SOAP can
be used to send information or remote procedure calls encoded as XML.
Essentially, SOAP serves as a universally accepted method of
communication with web services. Businesses adhere to the SOAP
conventions in order to simplify the process of interacting with Web
Services.
``` XML
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Header>
<!-- SOAP header -->
</SOAP:Header>
<SOAP:Body SOAP:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<!-- SOAP body -->
</SOAP:Body>
</SOAP:Envelope>
```
A SOAP message contains either a request method for invoking a Web
Service, or contains response information to a Web Service request.
Adhering to this layout when developing independent Web Services
provides notable benefits to the businesses. Due to the fact that Web
Applications are designed to be utilized by a myriad of actors,
developers want them to be easily adoptable. Using established and
familiar standards of communication ultimately reduces the amount of
effort it takes users to effectively interact with a Web Service.
The SOAP Envelope is used for defining and organizing the content
contained in Web Service messages. Primarily, the SOAP envelope serves
to indicate that the specified document will be used for service
interaction. It contains an optional SOAP Header and a SOAP Body.
Messages are sent in the SOAP body, and the SOAP head is used for
sending other information that wouldn\'t be expected in the body. For
example, if the SOAP:actor attribute is present in the SOAP header, it
indicates who the recipient of the message should be.
A web service transaction involves a SOAP request and a SOAP response.
The example we will be using is a Web Service provided by Weather.gov.
The input is latitude, longitude, a start date, how many days of
forecast information desired, and the format of the data. The SOAP
request will look like this:
``` XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?/>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<m:NDFDgenByDayRequest xmlns:SOAPSDK1="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl">
<latitude xsi:type="xsd:decimal">33.955464</latitude>
<longitude xsi:type="xsd:decimal">-83.383245</longitude>
<startDate xsi:type="xsd:date"></startDate>
<numDays xsi:type="xsd:integer">1</numDays>
<format>24 Hourly</format>
</m:NDFDgenByDayRequest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
```
The startDate was left empty because this will automatically get the
most recent data. The format data type is not defined because it is
defined in the WSDL document.
The response SOAP looks like this.
``` XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?/>
<SOAP-ENV:Envelope
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<NDFDgenByDayResponse xmlns:SOAPSDK1="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl">
<dwmlByDayOut xsi:type="xsd:string">.....</dwmlByDayOut>
</NDFDgenByDayResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
```
SOAP handles data by encoding it on the sender side and decoding it on
the receiver side. The data types handled by SOAP are based on the W3C
XML Schema specification. Simple types include strings, integers,
floats, and doubles, while compound types are made up of primitive
types.
``` XML
<element name="name" type="xsd:string" />
<SOAP:Array SOAP:arrayType="xsd:string[2]">
<string>Web</string>
<string>Services</string>
</SOAP:Array>
```
Because they are text based, SOAP messages generally have no problem
getting through firewalls or other barriers. They are the ideal way to
pass information to and from web services.
## Service Description - WSDL
**Web Service Description Language (WSDL)** was created to provide
information about how to connect to and query a specific Web Service.
This document also adheres to strict formatting and organizational
guidelines. However, the methods, parameters, and service information
are application specific. Web Services perform different functionality
and contain independent information, however they are all organized the
same way. By creating a standard organizational architecture for these
services, developers can effectively invoke and utilize them with little
to no familiarization. To use a web service, a developer can follow the
design standards of the WSDL to easily determine all the information and
procedures associated with its usage.
Essentially, a WSDL document serves as an instruction for interacting
with a Web Service. It contains no application logic, giving the service
a level of autonomy. This enables users to effectively interact with the
service without having to understand its inner workings.
The following is an example of a WSDL file for a web service that
provides a temperature, given a U.S. zip code.
``` XML
<?xml version="1.0"?>
<definitions xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:si="http://soapinterop.org/xsd" xmlns:tns="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
xmlns:typens="http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl>
<types>
<xsd:schema targetNamespace="http://www.weather.gov/forecasts/xml/DWMLgen/schema/DWML.xsd">
<xsd:import namespace="http://schemas.xmlsoap.org/soap/encoding/" />
<xsd:import namespace="http://schemas.xmlsoap.org/wsdl/" />
<xsd:simpleType name="formatType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="24 hourly" />
<xsd:enumeration value="12 hourly" />
</xsd:restriction>
</xsd:simpleType>
<xsd:simpleType name="productType">
<xsd:restriction base="xsd:string">
<xsd:enumeration value="time-series" />
<xsd:enumeration value="glance" />
</xsd:restriction>
</xsd:simpleType>
<xsd:complexType name="weatherParametersType">
<xsd:all>
<xsd:element name="maxt" type="xsd:boolean" />
<xsd:element name="mint" type="xsd:boolean" />
<xsd:element name="temp" type="xsd:boolean" />
<xsd:element name="dew" type="xsd:boolean" />
<xsd:element name="pop12" type="xsd:boolean" />
<xsd:element name="qpf" type="xsd:boolean" />
<xsd:element name="sky" type="xsd:boolean" />
<xsd:element name="snow" type="xsd:boolean" />
<xsd:element name="wspd" type="xsd:boolean" />
<xsd:element name="wdir" type="xsd:boolean" />
<xsd:element name="wx" type="xsd:boolean" />
<xsd:element name="waveh" type="xsd:boolean" />
<xsd:element name="icons" type="xsd:boolean" />
<xsd:element name="rh" type="xsd:boolean" />
<xsd:element name="appt" type="xsd:boolean" />
</xsd:all>
</xsd:complexType>
</xsd:schema>
</types>
<message name="NDFDgenRequest">
<part name="latitude" type="xsd:decimal"/>
<part name="longitude" type="xsd:decimal" />
<part name="product" type="typens:productType" />
<part name="startTime" type="xsd:dateTime" />
<part name="endTime" type="xsd:dateTime" />
<part name="weatherParameters" type="typens:weatherParametersType" />
</message>
<message name="NDFDgenResponse">
<part name="dwmlOut" type="xsd:string" />
</message>
<message name="NDFDgenByDayRequest">
<part name="latitude" type="xsd:decimal" />
<part name="longitude" type="xsd:decimal" />
<part name="startDate" type="xsd:date" />
<part name="numDays" type="xsd:integer" />
<part name="format" type="typens:formatType" />
</message>
<message name="NDFDgenByDayResponse">
<part name="dwmlByDayOut" type="xsd:string" />
</message>
<portType name="ndfdXMLPortType">
<operation name="NDFDgen">
<documentation> Returns National Weather Service digital weather forecast data </documentation>
<input message="tns:NDFDgenRequest" />
<output message="tns:NDFDgenResponse" />
</operation>
<operation name="NDFDgenByDay">
<documentation> Returns National Weather Service digital weather forecast data summarized over either 24- or 12-hourly periods </documentation>
<input message="tns:NDFDgenByDayRequest" />
<output message="tns:NDFDgenByDayResponse" />
</operation>
</portType>
<binding name="ndfdXMLBinding" type="tns:ndfdXMLPortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="NDFDgen">
<soap:operation soapAction="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgen" style="rpc" />
<input>
<soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
<operation name="NDFDgenByDay">
<soap:operation soapAction="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgenByDay" style="rpc" />
<input>
<soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
<service name="ndfdXML">
<documentation>The service has two exposed functions, NDFDgen and NDFDgenByDay.
For the NDFDgen function, the client needs to provide a latitude and
longitude pair and the product type. The client also needs to provide
the start and end time of the period that it wants data for. For the
time-series product, the client needs to provide an array of boolean values
corresponding to which weather values should appear in the time series product.
For the NDFDgenByDay function, the client needs to provide a latitude and longitude
pair, the date it wants to start retrieving data for and the number of days worth
of data. The client also needs to provide the format that is desired.</documentation>
<port name="ndfdXMLPort" binding="tns:ndfdXMLBinding">
<soap:address location="http://www.weather.gov/forecasts/xml/SOAP_server/ndfdXMLserver.php" />
</port>
</service>
</definitions>
```
The WSDL file defines a service, made up of different endpoints, called
ports. The port is made up of a network address
` and a binding.`
``` XML
<service name="ndfdXML">
<documentation>The service has two exposed functions, NDFDgen and NDFDgenByDay.
For the NDFDgen function, the client needs to provide a latitude and
longitude pair and the product type. The client also needs to provide
the start and end time of the period that it wants data for. For the
time-series product, the client needs to provide an array of boolean values
corresponding to which weather values should appear in the time series product.
For the NDFDgenByDay function, the client needs to provide a latitude and longitude
pair, the date it wants to start retrieving data for and the number of days worth
of data. The client also needs to provide the format that is desired.</documentation>
<port name="ndfdXMLPort" binding="tns:ndfdXMLBinding">
<soap:address location="http://www.weather.gov/forecasts/xml/SOAP_server/ndfdXMLserver.php" />
</port>
</service>
```
The binding identifies the binding style and protocol for each
operation. In this case, it uses Remote Procedure Call style binding,
using SOAP.
``` XML
<binding name="ndfdXMLBinding" type="tns:ndfdXMLPortType">
<soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http" />
<operation name="NDFDgen">
<soap:operation soapAction="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgen" style="rpc" />
<input>
<soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
<operation name="NDFDgenByDay">
<soap:operation soapAction="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl#NDFDgenByDay" style="rpc" />
<input>
<soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</input>
<output>
<soap:body use="encoded" namespace="http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl"
encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" />
</output>
</operation>
</binding>
```
Port Types are abstract collections of operations. In this case, the
operation is getTemp.
``` XML
<portType name="ndfdXMLPortType">
<operation name="NDFDgen">
<documentation> Returns National Weather Service digital weather forecast data </documentation>
<input message="tns:NDFDgenRequest" />
<output message="tns:NDFDgenResponse" />
</operation>
<operation name="NDFDgenByDay">
<documentation> Returns National Weather Service digital weather forecast data summarized over either 24- or 12-hourly periods </documentation>
<input message="tns:NDFDgenByDayRequest" />
<output message="tns:NDFDgenByDayResponse" />
</operation>
</portType>
```
Finally, messages are used by the operations to communicate - in other
words, to pass parameters and return values.
``` XML
<message name="NDFDgenByDayRequest">
<part name="latitude" type="xsd:decimal" />
<part name="longitude" type="xsd:decimal" />
<part name="startDate" type="xsd:date" />
<part name="numDays" type="xsd:integer" />
<part name="format" type="typens:formatType" />
</message>
<message name="NDFDgenByDayResponse">
<part name="dwmlByDayOut" type="xsd:string" />
</message>
```
From the WSDL file, a consumer should be able to access data in a web
service.
For a more detailed analysis of how this particular web service, please
visit Weather.gov
## Service Discovery - UDDI
You\'ve seen how WSDL can be used to share interface definitions for Web
Services, but how do you go about finding a Web Service in the first
place? There are countless independent Web Services that are developed
and maintained by just as many different organizations. Upon adopting
Web Service practices and methodologies, developers sought to foster the
involvement and creative reuse of their systems. It soon became apparent
that there was a need for an enumerated record of these services and
their respective locations. This information would empower developers to
leverage the best practices and processes of Web Services quickly and
easily. Additionally, having a central reference of current Web Service
capabilities enables developers avoid developing redundant applications.
UDDI defines registries in which services can be published and found.
The UDDI specification was creaed by Microsoft, Ariba, and IBM. UDDI
defines a data structure and Application Programming Interface (API).
In the three-tier model mentioned before, UDDI is the service broker.
Its function is to enable service consumers to find appropriate service
providers.
Connecting to UDDI registries using Java can be accomplished through the
Java API for XML Registries (JAXR). JAXR creates a layer of abstraction,
so that it can be used with UDDI and other types of XML Registries, such
as the ebXML Registry and Repository standard.
## Using Java With Web Services
To execute a SOAP message, an application must be used to communicate
with the service provider. Due to its flexibility, almost any
programming language can be used to execute SOAP message. For our
purposes, however, we will be focusing on using Java to interact with
Web Services.
Using Java with web services requires some external libraries.
- Apache SOAP Toolkit
- Java Mail Framework
- JavaBeans Activation Framework
- Xerces XML parser
Let\'s go through using Java to query the Temperature Web Service we
talked about earlier.
``` java
import java.io.*;
import java.net.*;
import java.util.*;
import org.apache.soap.util.xml.*;
import org.apache.soap.*;
import org.apache.soap.rpc.*;
public class TempClient
{
public static float getTemp (URL url, String zipcode) throws Exception
{
Call call = new Call ();
// Service uses standard SOAP encoding
String encodingStyleURI = Constants.NS_URI_SOAP_ENC;
call.setEncodingStyleURI(encodingStyleURI);
// Set service locator parameters
call.setTargetObjectURI ("urn:xmethods-Temperature");
call.setMethodName ("getTemp");
// Create input parameter vector
Vector params = new Vector ();
params.addElement (new Parameter("zipcode", String.class, zipcode, null));
call.setParams (params);
// Invoke the service ....
Response resp = call.invoke (url,"");
// ... and evaluate the response
if (resp.generatedFault ())
{
throw new Exception();
}
else
{
// Call was successful. Extract response parameter and return result
Parameter result = resp.getReturnValue ();
Float rate=(Float) result.getValue();
return rate.floatValue();
}
}
// Driver to illustrate service invocation
public static void main(String[] args)
{
try
{
URL url=new URL("http://services.xmethods.net:80/soap/servlet/rpcrouter");
String zipcode= "30605";
float temp = getTemp(url,zipcode);
System.out.println(temp);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
```
This Java code effectively hides all the SOAP from the user. It invokes
the target object by name and URL, and sets the parameter *zipcode*. But
what does the underlying SOAP Request look like?
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:n="urn:xmethods-Temperature"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<n:getTemp>
<zipcode xsi:type="xs:string">30605</zipcode>
</n:getTemp>
</soap:Body>
</soap:Envelope>
```
As you see, the SOAP request uses the parameters passed in by the Java
Call to fill out the SOAP envelope and direct the message. Similarly,
the response comes back into the Java program as \'70.0\'. The response
SOAP is also hidden by the Java program.
``` XML
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope
xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SOAP-ENV:Body>
<ns1:getTempResponse xmlns:ns1="urn:xmethods-Temperature"
SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<return xsi:type="xsd:float">70.0</return>
</ns1:getTempResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
```
Here\'s an additional example of using Java and SOAP to interact with
Web Services. This particular Web Service is called the \"US Zip
Validator\" and takes a ZipCode as a parameter, which then returns a
corresponding latitude and longitude. When developing applications to
interact with Web Services, the first step should be to review the WSDL
document.
The WSDL document for this service is located here:
<http://www.webservicemart.com/uszip.asmx?WSDL>
This document will contain all the necessary instructions for
interacting with the \"US Zip Validator\" Web Service.
**SOAPClient4XG**
Modified by - Duncan McAllister From:
<http://www.ibm.com/developerworks/xml/library/x-soapcl/>
``` java
import java.io.*;
import java.net.*;
import java.util.*;
public class SOAPClient4XG {
public static void main(String[] args) throws Exception {
args = new String[2];
args[0] = "http://services.xmethods.net:80/soap/servlet/rpcrouter";
args[1] = "SOAPrequest.xml";
if (args.length < 2) {
System.err.println("Usage: java SOAPClient4XG " +
"http://soapURL soapEnvelopefile.xml" +
" [SOAPAction]");
System.err.println("SOAPAction is optional.");
System.exit(1);
}
String SOAPUrl = args[0];
String xmlFile2Send = args[1];
String SOAPAction = "";
// Create the connection where we're going to send the file.
URL url = new URL(SOAPUrl);
URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;
// Open the input file. After we copy it to a byte array, we can see
// how big it is so that we can set the HTTP Cotent-Length
// property. (See complete e-mail below for more on this.)
FileInputStream fin = new FileInputStream(xmlFile2Send);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
// Copy the SOAP file to the open connection.
copy(fin,bout);
fin.close();
byte[] b = bout.toByteArray();
// Set the appropriate HTTP parameters.
httpConn.setRequestProperty( "Content-Length",
String.valueOf( b.length ) );
httpConn.setRequestProperty("Content-Type","text/xml; charset=utf-8");
httpConn.setRequestProperty("SOAPAction",SOAPAction);
httpConn.setRequestMethod( "POST" );
httpConn.setDoOutput(true);
httpConn.setDoInput(true);
// Everything's set up; send the XML that was read in to b.
OutputStream out = httpConn.getOutputStream();
out.write( b );
out.close();
// Read the response and write it to standard out.
InputStreamReader isr =
new InputStreamReader(httpConn.getInputStream());
BufferedReader in = new BufferedReader(isr);
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
// copy method from From E.R. Harold's book "Java I/O"
public static void copy(InputStream in, OutputStream out)
throws IOException {
// do not allow other threads to read from the
// input or write to the output while copying is
// taking place
synchronized (in) {
synchronized (out) {
byte[] buffer = new byte[256];
while (true) {
int bytesRead = in.read(buffer);
if (bytesRead == -1) break;
out.write(buffer, 0, bytesRead);
}
}
}
}
}
```
This Java class refers to an XML document(SOAPRequest.xml), which is
used as the SOAP message. This document should be included in the same
project folder as the Java application invoking the service.
After reviewing the \"US Zip Validator\" WSDL document, it is clear that
we would like to invoke the \"getTemp\" method. This information is
contained within the SOAP body and includes the appropriate parameters.
**SOAPRequest.xml**
``` XML
<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:n="urn:xmethods-Temperature"
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<n:getTemp>
<zipcode xsi:type="xs:string">30605</zipcode>
</n:getTemp>
</soap:Body>
</soap:Envelope>
```
Following a successful interaction, the Web Service provider will
provide a response that is similar in format to the user request. When
developing in NetBeans, run this project and examine the subsequent SOAP
message response in the Tomcat output window.
## Web Services with Netbeans
The Netbeans version used for this explanation is 5.0.
After Netbeans is open, click on the \"Runtime\" tab on the left pane,
then right-click \"Web Services\" and select \"Add Web Service.\" In the
\"URL\" field, enter the address of the web service WSDL file, in our
example above it is
\"<http://www.weather.gov/forecasts/xml/DWMLgen/wsdl/ndfdXML.wsdl>\" and
click Get Web Service Description. This will bring up the information of
the web service.
## Summary
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Web services are applications that use XML to communicate with many different systems to perform a task. To facilitate the use of web services, protocols were developed that allow them to be flexible and scalable. SOAP is used to send and define information and WSDL was created to provide information about how to connect to and query a web service. UDDI describes where these web services can be found.
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## Exercises
## Answers
## Appendix
## References and Links
- Weather.gov
- WebServices.org
- W3C\'s Web Services Reference
- UDDI.org
- XMethods.net
- Java API for XML Registries
- Apache SOAP Toolkit
- JavaMail Framework
- Java Activation
Framework
- Xerces Java Parser
- Jasnowski, Mike. *Java, XML, and Web Services Bible*
- Microsoft Web Services
- <http://www.xml.com/>
- <http://www.w3schools.com/soap/soap_intro.asp>
- <http://en.wikibooks.org/wiki/XML_-_Managing_Data_Exchange/Web_services>
- <http://www.w3.org/TR/2007/REC-soap12-part0-20070427/>
- <http://www.eweek.com/article2/0,1895,1589730,00.asp>
- <http://www.ibm.com/developerworks/xml/library/x-soapcl/>
|
# XML - Managing Data Exchange/XMLHTTP
## History
The XMLHttpRequest object enables JavaScript to make HTTP requests to a
remote server without the need to reload the page. It was first
implemented by Microsoft as an ActiveX object but is now available as a
native object within both Mozilla and Apple\'s Safari browser.
Javascript is used to transfer information back to the server in real
time where it can be processed by the server, and then returned
instantaneously to the user.
## Purpose
The main function of the XMLHttpRequest object is that it provides an
easy way for webpages to receive updated information from servers
without having to refresh the whole webpage. As a result, the
webserver's processing load is reduced and the user receives information
faster without seeing any interruptions in service.
## Future Application
The XMLHttpRequest object has many improvements over the existing data
exchange methods. Many developers still rely on Common Gateway
Interchange (CGI) for data exchange. Since CGI has no adequate
restriction about the format of data, XML usage is relatively pointless
from a data exchange standpoint. Utilizing the inherent abilities of
XMLHttp will remove the inadequacies originating from the widespread use
of CGI. The XMLHttpRequest object provides a more adequate approach for
real-time content delivery than existing development methods.
## Tutorials
<http://developer.apple.com/library/safari/#documentation/appleapplications/Conceptual/SafariJSProgTopics/Articles/XHR.html>
|
# XML - Managing Data Exchange/Database and XML
+-----------------------------------------------------+
| **Learning objectives** |
| |
| - Learn about Native XML Databases |
| - Learn about the conversion technology available |
| - Create Table and retrieve information |
+-----------------------------------------------------+
| |
+-----------------------------------------------------+
## Native XML Database
The term **Native XML database**: has become popular since 1999, after
the company Software AG released the first version of its native XML
server Tamino, which included a native XML database. A definition of a
native databases is that it:
\"\[d\]efines a (logical) model for an XML document and stores and
retrieves documents according to that model.\" (Bourret, 2002)\"
To model data in XML, two principle approaches are used: Data-centric
documents and Document-centric documents.
- Data-centric documents (for data transport) have fairly regular
structure, order typically does not matter, and little or no mixed
content.
```{=html}
<!-- -->
```
- Document-centric documents (usually for human consumption) have less
regular or irregular structure, significant order of the elements,
and lots of mixed content.
Examples of Native databases
```{=html}
<table width="60%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<th width="15%">
```
Product
```{=html}
</th>
```
```{=html}
<th width="15%">
```
Developer
```{=html}
</th>
```
```{=html}
<th width="15%">
```
License
```{=html}
</th>
```
```{=html}
<th width="15%">
```
DB Type
```{=html}
</th>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
Tamino
```{=html}
</td>
```
```{=html}
<td>
```
Software AG
```{=html}
</td>
```
```{=html}
<td>
```
Commercial
```{=html}
</td>
```
```{=html}
<td>
```
Proprietary. Relational through ODBC.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style="text-align:center">
```
```{=html}
<td>
```
XediX Multimedia Solution
```{=html}
</td>
```
```{=html}
<td>
```
XediX Tera Solution
```{=html}
</td>
```
```{=html}
<td>
```
Commercial
```{=html}
</td>
```
```{=html}
<td>
```
Proprietary
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
eXist
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Wolfgang Meier
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Open Source
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Relational
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
dbXML
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
dbXML Group
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Open Source
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Proprietary
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td style="text-align:center">
```
Xindice
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Apache Software Foundation
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Open Source
```{=html}
</td>
```
```{=html}
<td style="text-align:center">
```
Proprietary (Model-based)
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
### eXist
eXist is an Open Source effort to
develop a native XML database system, tightly integrated with existing
XML development tools like Apache\'s Cocoon. The database may be easily
deployed, running either standalone, inside a servlet engine, or
directly embedded in an application.
Some features that are available in eXist and that can be found in most
Native XML databases are :
- Schema-less storage - Documents do not have to be associated to
schema or document type, meaning they are allowed to be well formed
only.
```{=html}
<!-- -->
```
- Collections - A collection plays a similar role to a directory in a
file system. When submitting a query the user can choose a distinct
part of the collection hierarchy or even all the documents contained
in the database.
```{=html}
<!-- -->
```
- Query languages - The most popular query languages supported by
Native XML databases are XPath (with extensions for queries over
multiple documents) and XQuery.
## Relational Databases
Database vendors such as IBM, Microsoft, Oracle, and Sybase have
developed tools to assist in converting XML documents into relational
tables.
Let us look at IBM and Oracle:
### IBM Technology
**DB2 XML Extender** provides access, storage and transformation for XML
data through user-defined functions and stored procedure. It offers 2
key storage models: **XML Colums** and **XML Collections**.
1\. XML Column: stores and retrieves entire XML documents as DB2 column
data. Use of XML Columns is recommended when XML documents already exist
and/or when there is a need to store XML documents in their entity.
2\. XML Collection: composes XML Documents from a collection of
relational tables.
A **data access definition (DAD)** file is used for both XML Column and
XML Collection approaches to define the \"mapping\" between the database
tables and the structure of the XML document.
`<Xcollection>`{=html} Specifies that the XML data is either to be
decomposed from XML documents into a collection of relational tables, or
to be composed into XML documents from a collection of relational
tables.
The DAD file defines the XML document tree structure, using the
following kinds of nodes:
- root_node - Specifies the root element of the document.
- element_node - Identifies an element, which can be the root element
or a child element.
- text_node - Represents the CDATA text of an element.
- attribute_node - Represents an attribute of an element.
``` XML
<?xml version="1.0"?>
<!DOCTYPE DAD SYSTEM ""c:\dxx\samples\db2xml\dtd\dad.dtd">
<DAD>
...
<Xcollection>
<SQL_stmt>
...
</SQL_stmt>
<prolog>?xml version="1.0"?</prolog>
<doctype>!DOCTYPE Order SYSTEM
""c:\dxx\samples\db2xml\dtd\getstart.dtd""</doctype>
<root_node>
<element_node name="Order"> --> Identifies the element <Order>
<attribute_node name="key"> --> Identifies the attribute "key"
<column name="order_key"/> --> Defines the name of the column,
"order_key", to which the
element and attribute are
mapped
</attribute_node>
<element_node name="Customer"> --> Identifies a child element of
<Order> as <Customer>
<text_node> --> Specifies the CDATA text for
the element <Customer>
<column name="customer"> --> Defines the name of the column,
"customer", to which the child
element is mapped
</text_node>
</element_node>
...
</element_node>
...
</root_node>
</Xcollection>
</DAD>
```
\
\* XML for DB2 Information Integration
Redbook.
### Oracle
Oracle\'s **XML SQL Utility (XSU)** uses a schematic mapping that
defines how to map tables and views, including object-relational
features, to XML documents. Oracle translates the chain of object
references from the database into the hierarchical structure of XML
elements.
``` SQL
CREATE TABLE Customers
{
FIRSTNAME VARCHAR,
LASTNAME VARCHAR,
PHONENO INT,
ADDRESS AddressType, // object reference
}
CREATE TYPE AddressType as OBJECT
{
ZIP VARCHAR (100),
CITY VARCHAR (100),
STREET VARCHAR (100),
}
```
\
A corresponding XML document generated from the given object-relational
model looks like:
``` XML
<?xml version="1.0"?>
<ROWSET>
<ROW num="1">
<FIRSTNAME>JOHN</FIRSTNAME>
<LASTNAME>SMITH</LASTNAME>
<PHONENO>7061234567</PHONENO>
<ADDRESS>
<ZIP>30601</ZIP>
<CITY>ATHENS</CITY>
<STREET>123 MAIN STREEET</STREET>
</ADDRESS>
</ROW>
<!-- additional rows ... -->
</ROWSET>
```
\
XSU can be used for executing queries in a Java environment and retrieve
XML from the database.
``` java
import oracle.jdbc.driver.*;
import oracle.xml.sql.query.OracleXMLQuery;
import java.lang.*;
import java.sql.*;
// class to test XML document generation as String
class testXMLSQL {
public static void main(String[] args)
{
try {
// Create the connection
Connection conn = getConnection("root","");
// Create the query class
OracleXMLQuery qry = new OracleXMLQuery(conn,
"SELECT * FROM Customers");
// Get the XML string
String str = qry.getXMLString();
// Print the XML output
System.out.println("The XML output is:\n"+str);
// Always close the query to get rid of any resources..
qry.close();
} catch(SQLException e) {
System.out.println(e.toString());
}
}
// Get the connection given the user name and password.!
private static Connection getConnection(String username,
String password)
throws SQLException
{
// register the JDBC driver..
DriverManager.registerDriver(new
oracle.jdbc.driver.OracleDriver());
// Create the connection using the OCI8 driver
Connection conn =
DriverManager.getConnection(
"jdbc:oracle:thin:@dlsun489:1521:ORCL",username,password);
return conn;
}
}
```
## Query Languages
### XPath
../XPath/ is a language for addressing parts of
an XML document, and is the common locator used by both XSLT and
XPointer. An XPath expression is a series of location steps separated by
\" / \". Each step selects a set of nodes that become the current
node(s) for the next step. The set of nodes selected by the expression
are the nodes remaining after processing each step in order.
### XQuery
../XQuery/ is a query language under
development by the World Wide Web Consortium (W3C). The ambitious task
is to develop the first world standard for querying Web documents.
XQuery is a versatile markup language, capable of labeling the
information content of diverse data sources including structured and
semi-structured documents, relational databases, and object
repositories.
- Catalog of XQuery Processors at
www.SQLSummit.com.
## MySQL 5.1
MySQL has a command line utility for executing queries against a MySQL
database; it has an option for using XML as their output format. MySQL
also allows convertion to XML; more information can be found in
../Converting MySQL to XML/
MySQL allows users to execute any SQL query. mysqldump allows users to
specify which tables to dump and to specify a where clause to restrict
the rows that are dumped. In its Beta release of MySQL 5.1, several
features have been added including new **XML functions**.
In order to understand these New functions, we will use the following
table:
``` mysql
CREATE TABLE Customers (doc VARCHAR(150));
INSERT INTO Customers VALUES
('
<person id="1">
<firstname>John</firstname>
<lastname>Smith</lastname>
<phoneno>123-5678</phoneno>
</person>
');
INSERT INTO Customers VALUES
('
<person id="2">
<firstname>Aminata</firstname>
<lastname>Cisse</lastname>
<phoneno>123-5679</phoneno>
</person>
');
INSERT INTO Customers VALUES
('
<person id="3">
<firstname>Lamine</firstname>
<lastname>Smith</lastname>
<phoneno>123-5680</phoneno>
</person>
');
```
\
### XML Functions
MySQL version 5.1 has functions for searching and changing XML
documents: **ExtractValue()** and **UpdateXML()**.
- EXTRACTVALUE (XML_document, XPath_string);
This function takes 2 string arguments: The first parameter correspond
to the XML_document string, and the 2nd Parameter XPath_string (XPath
expression / locator). This will result in the return of the string
containing a value from the document.
<nowiki>
mysql> SELECT EXTRACTVALUE(doc,'//firstname') FROM Customers;
+------------------------------------------+
| EXTRACTVALUE(doc,'//firstname') |
+------------------------------------------+
| John |
| Aminata |
| Lamine |
+------------------------------------------+
3 rows in set (0.01 sec)
</nowiki>
\
<nowiki>
mysql> SELECT ExtractValue(doc,'/person[@id="3"]/firstname') as fname FROM Customers;
+---------+
| fname |
+---------+
| |
| |
| Lamine |
+---------+
3 rows in set (0.02 sec)
</nowiki>
\
- UPDATEXML (XML_document, XPath_string, new_value);
This function takes 3 string arguments: The first two paramaters are
similar to the ones used with extractValue(), XML_document and
XPath_string. The third parameter is the new value that will replace the
one found. This function will then returns the changed XML.
<nowiki>
mysql> SELECT UpdateXML(doc,'/person[@id="3"]/phoneno', '<phoneno>111-2233<phoneno>') FROM Customers;
+-------------------------------------------------------------------------------
----------------------------------------------------+
| UpdateXML(doc,'/person[@id="3"]/phoneno','<phoneno>111-2233<phoneno>')
|
+-------------------------------------------------------------------------------
----------------------------------------------------+
|
<person id="1">
<firstname>John</firstname>
<lastname>Smith</lastname>
<phoneno>123-5678</phoneno>
</person>
|
|
<person id="2">
<firstname>Aminata</firstname>
<lastname>Cisse</lastname>
<phoneno>123-5679</phoneno>
</person>
|
|
<person id="3">
<firstname>Lamine</firstname>
<lastname>Smith</lastname>
<phoneno>111-2233<phoneno>
</person>
|
+-------------------------------------------------------------------------------
----------------------------------------------------+
3 rows in set (0.00 sec)
</nowiki>
\
### Installation
Currently (04/05/06) MySQL 5.1 does not come with the installer (Beta
Version).
Quick Windows
installation.
Details information can be found in the online Manual:
- Windows.
```{=html}
<!-- -->
```
- Mac
OS.
```{=html}
<!-- -->
```
- Linux.
```{=html}
<!-- -->
```
- and more in the
Manual.
## Summary
## Exercises
## Answers
|
# XML - Managing Data Exchange/SyncML
## Learning objectives
Upon completion of this chapter, you will be able to
- Understand SyncML fundamentals and general syntax.
- Understand how and why SyncML is implemented.
- Quickly locate and use SyncML technical specifications.
## Introduction
Mobile devices such as PDAs, pagers, mobile phones and laptops are- by
nature- not always connected to a network. Yet these devices contain
applications which require information obtained from a network in order
to be useful. While most PDAs and mobile phones contain applications
such as calendars, task lists, and address books for storing useful
information, this information is far less useful when it is static, only
available on the device itself. For example, copies of static
information will always be dissimilar when changes are made on one copy
or the other. Synchronization offers a device the ability to connect to
a network in order to update either the information on the device or the
information on the network, such that both sets of information are
identical and up-to-date.
Given the proliferation of proprietary mobile devices and protocols, as
well as the increasing consumer demand for ubiquitous mobile access of
information, leading technology companies saw the need to create a
standard, universal language for describing the synchronization actions
between devices and applications. They formed a consortium to sponsor
the SyncML initiative to create this language.
Currently, the SyncML consortium has been adopted and incorporated into
the Open Mobile Alliance, a larger
group of over 300 companies which sponsors many collaborative technology
projects and protocols.
## What is SyncML?
SyncML or *Synchronization Markup Language* is an XML-based,
industry-standard protocol for synchronizing mobile data across a
variety of multiple networks, platforms and devices. SyncML started as
an initiative in mid 2000 by major technology companies such as
Ericsson, IBM, Palm Inc., Lotus, Matsushita Ltd. (Panasonic), Motorola,
Nokia, Openwave, Starfish Software, Psion and Symbian. Their
initiative\'s goals were to create a universal language from the myriad,
proprietary, synchronization protocols used by mobile devices and
provide a complete set of synchronization functionality for future
devices. The consortium released version 1.0 in December 2000. They then
implemented new features and resolved issues with the subsequent version
releases, finalizing the protocol with version 1.1 in February 2002.
The SyncML protocol is designed with these goals in mind:
- As a common language, any device should be able to synchronize with
any SyncML service (a networked data repository).
- Any service speaking SyncML should be able to synchronize with any
SyncML-capable device.
- The protocol must address the limitations of mobile devices,
specifically with respect to memory storage.
- It must support a variety of transport protocols such as HTTP, SMTP,
Bluetooth and others.
- It must deliver common synchronization commands to all devices.
- It builds upon existing web technologies, specifically XML.
- Support asynchronous communication and error-handling, since the
Internet has latency.
SyncML consists of client and server commands enclosed within
DTD-defined\...
## SyncML Fundamentals
### Vocabulary
Let\'s begin by defining a vocabulary:
- Client - the mobile device, its application and local database.
- Server - a remote system communicating to the system database or
application.
- Modifications - data in fields in a database are changed.
- Sync - The client and server exchange SyncML messages with commands.
- Package - SyncML DTD conformant XML markup describing requests or
actions to be taken by either a SyncML client or server. A package
is a collection of actions to be performed
- Message - the smallest unit of SyncML markup. Large packages are
broken into separate messages.
- Mapping - using an intermediate identifier to tie two pieces of
information together. example: let\'s say \'green\' is \'5\', and
\'5\' is nice. What is nice? If you said \'green\' you are correct.
You\'ve just done mapping!
Abbreviations:
--------------------------------- -------------------------------------------
../IMEI/ International Mobile Equipment Identifier
GUID Global Unique Identifier
LUID Local Unique Identifier
--------------------------------- -------------------------------------------
### Messages and Packages
SyncML messages are requests from either a client or server to perform
some action. The action may be to synchronize data, perform some checks
on data, update a status, or handle any errors with these actions.
Messages are bundled together as packages, as kind of a to-do list.
Messages are a laundry list of requests, and they can be pieced together
out of order if sufficient mapping information is given to identify to
which package the message belongs.
SyncML is designed this way to accommodate for errors and dropped
messages. Should one message be dropped, a syncML client or server will
know there is a problem because the mapping cannot be completed. It will
then issue a request for the information to be resent. Once the data is
received, the updates to the information can proceed.
### Structure of a SyncML message
Like SOAP, there are two parts to the SyncML message, a Sync Header
`<SyncHdr>`{=html} and Sync Body `<SyncBody>`{=html}. The header
contains meta-information about the request, such as the target database
`<Target>`{=html} and source database \<Source\> URIs, Authentication
information `<Cred>`{=html}, the session ID `<SessionID>`{=html}, the
message ID `<MsgID>`{=html}, and SyncML version declaration
`<VerDTD>`{=html}. The body contains the actual requests, alerts and
data.
### Addressing
Addressing is done through the \<syntaxhighlight\> and `<LocURI>`{=html}
tags. A server will have a familiar URI like
http://www.chris.syncml.org/sync and a client mobile device will have an
IMEI identification number like this 30400495959596904.
### Mapping
SyncML is based on the idea that clients and servers can have their own
way of mapping information in their databases. Therefore, clients and
servers must each have their own set of unique identifiers.
- Locally Unique Identifiers (LUID) are numbers assigned by the client
to a data object in a local database (like a field or a row). They
are non-reusable numbers assigned to these objects by the SyncML
client.
- Globally Unique Identifiers (GUID) are numbers assigned to a data
object for use in a remote database. This identifier is assigned by
the server.
LUID and GUID numbers only have to be unique if they are being used in a
table between two communicating parties. In other words, these numbers
are temporary, used for mapping data to tables and only really exist for
the complete duration of transactions between client and server.
The server will create a mapping table to tie the LUID and GUID
together.
`<small>`{=html}Client-side data`</small>`{=html}
+---------------+---------------+
| <nowiki> | <nowiki> |
| LUID | Data |
| ---- | ---- |
| 5 | Green |
| | </nowiki> |
| </nowiki> | |
+---------------+---------------+
`<small>`{=html}Server-side data`</small>`{=html}
+---------------+---------------+
| <nowiki> | <nowiki> |
| GUID | Data |
| ---- | ---- |
| 5050505 | Green |
| | </nowiki> |
| </nowiki> | |
+---------------+---------------+
`<small>`{=html}Server Mapping`</small>`{=html}
+---------------+---------------+
| <nowiki> | <nowiki> |
| GUID | LUID |
| ---- | ---- |
| 5050505 | 5 |
| | </nowiki> |
| </nowiki> | |
+---------------+---------------+
### Change Logs
The Server and Client track of changes made to their databases during
synchronization through \"change logs\". SyncML doesn\'t define the
change logs, instead SyncML does require that the changes and
corrections be negotiated between client and server through messages.
Using change logs, the Client and Server know which fields need to be
updated. The implementation of change tracking in the application which
will use SyncML is not defined.
### Sync Anchors
During Synchronization, the Client and Server need to know which fields
to update. If a client/server application is checking the fields prior
to updating/modifying them, how then does the client/server keep track
of the position of current field in the database? The answer is \"by
using Sync Anchors\".
There are two kinds of Anchors : Last and Next. The \'Last\' anchor
describes which updates occurred during the last synchronization event.
The \'Next\' anchor describes the current and future synchronization
request. These anchors describe the events from the standpoint of the
sending device.
Anchors are sent back and forth from client and server to keep track of
what is happening to the database fields and what\'s going on in overall
through the lifetime of the sync operation.
By coordinating Sync Anchors and change logs with the type of Sync that
is requested, the server application can determine and track (with
change logs) which information is the most up-to-date. For example, it
is possible to overwrite \'newer\' information- that is information for
which there is the most recent time-stamp in the change log- with older
information. This could be done by choosing a sync in which the client
tells the server to overwrite it\'s information with client data. This
is called a \'refresh sync from client\'. The types of syncs are
described below.
### Syncs
There are seven types of Syncs in the SyncML 1.1 language. The following
section describes the types of syncs:
1. **Two-way Sync** - The client and server exchange information about
modified data. The client sends the modifications first.
2. **Slow sync** - a two-way sync in which all fields in the database
are checked on a field-to-field basis. This type of sync is used for
the first sync, or after a synchronization failure.
3. **One-way sync, client only** - the client sends the modified data
first. The server accepts and updates the data and does not send its
modifications.
4. **Refresh sync from client** - the client sends the entire database
to the server. The server does not sync. Rather, the server replaces
the target database with the client\'s database.
5. **One-way sync, server only** - the server sends the modified data
first. The client accepts and updates the data and does not send its
modifications.
6. **Refresh sync from server** - the server sends all its information
from a database to the client, replacing the client\'s database.
7. **Server alerted sync** - the server remotely commands the client to
initiate one of the above sync types with the server. In this way,
the server is remotely-controlling the client.
### Sync Initiation
Sync Initiation is the process the client and server must go through
prior to an actual Synchronization. The first step is for the client and
server to speak the same language, exchanging and revealing each
other\'s capabilities (as defined by device, as in amount of memory, and
protocol as defined by DTD). The second step is identification of the
databases to be synchronized. Next the two must decide on the type of
synchronization. The third and final step is authentication. Once this
step is completed successfully, the synchronization activities can
begin.
### Authentication
The SyncML server can send the client a message containing the
`<Chal>`{=html} tag in order to represent an authentication challenge to
the information the client is attempting to access. The client must then
respond, giving the username and password within the `<Cred>`{=html}
tag.
SyncML uses MD5 digest access authentication. The Client and Server
exchange credentials during the authentication process, returning error
codes if the process breaks down at some point. The `<Cred>`{=html} tag
is used in the `<SyncHdr>`{=html} for holding the credentials to be used
for authentication.
## Common SyncML implementations
Nokia was the first company to make a SyncML-enabled phone. It
synchronized the calendar database on the phone. SyncML can synchronize
to-do lists, calendars, address books, phone-books, pretty much anything
an organizer can do. SyncML is capable of much more. It would be
appropriate to use SyncML any time there are two disparate, remote
applications which need to share the same data.
## SyncML Syntax
### SyncML Example
`<small>`{=html}Abbreviated SyncML example`</small>`{=html}
+---------------+-----------------------------------------------------+
| <nowiki> | <nowiki><SyncML> |
| 1 | <SyncHdr> |
| 2 | <VerDTD>1.1</VerDTD> |
| 3 | <VerProto>SyncML/1.1</VerProto> |
| 4 | <SessionID>104050403</SessionID> |
| 5 | <MsgID>5</MsgID> |
| 6 | <Cred>...</Cred> |
| 7 | </SyncHdr> |
| 8 | <SyncBody> |
| 9 | <Status>...</Status> |
| 10 | <Sync> |
| 11 | <Target>target database URI</Target> |
| 12 | <Source>source database URI</Source> |
| 13 | <Add>datafield and data</Add> |
| 14 | <Repl |
| 15 | ace>an existing data field with some data</Replace> |
| 16 | </Sync> |
| 17 | </SyncBody> |
| 18 | </SyncML></nowiki> |
| </nowiki> | |
+---------------+-----------------------------------------------------+
Notice lines {1} and {18} start the SyncML file with the root tags.
Next, the SyncHdr is defined by lines {2} and {8}. Further, lines {3,4}
define the versioning information, line {5} defines the sessionID to
distinguish which unique dialogue is occurring between client and server
applications, line {6} shows the MsgID to uniquely identify this set of
requests (this entire markup) to be performed by the requested
application. Also in the syncHeader are credentials, on line {7}.
The SyncBody begins on line {9}. In this part of the syncML message,
device/application status {10}, target/source URIs {12,13}, and
requested actions such as the sync itself between lines {11,16}, Add and
Replace {14,15} commands are given.
### WBXML and SyncML
WAP Binary XML (WBXML) is a form of XML whereby the XML tags are
abbreviated in order to shorten the markup for transmission to mobile
devices, which commonly have bandwidth and memory limitations. The XML
tags are encoded into a binary shorthand to save space. Let\'s take a
look at an example so that this will make more sense.
The following is WBXML binary code depicting a SyncML message. Notice in
the first line there is a the document type definition, represented here
in hexadecimal tokens. Can you see what happens to the following string?
\"//SYNCML//DTD SYNCML 1.1//EN\"
!wbxml
Immediately following this string are the characters \'6D 6C 71\'. Each
of these represent a SyncML tag.
`<small>`{=html}wbxml abbreviations`</small>`{=html}
+-----------------+---------------------------+
| <nowiki> | <nowiki> |
| 6D | = "<SyncML>" |
| 6C | = "<SyncHdr>" |
| 71</nowiki> | = "<VerDTD>"</nowiki> |
+-----------------+---------------------------+
`<small>`{=html}wbxml abbreviations (cont.)`</small>`{=html}
+-----------------+---------------------------------------------------+
| <nowiki>C3 | <nowiki |
| 03 | > = represents the beginning of opaque (xml) data |
| "1" "." "1" | |
| 01</nowiki> | = this represents the length of this opaque data |
| | = The characters "1" followed by "." and "1" |
| | = represents "</VerDTD>"</nowiki> |
+-----------------+---------------------------------------------------+
tells the SyncML processor that this is the beginning of opaque (xml)
data this represents the length of this opaque data The characters \"1\"
followed by \".\" and \"1\" represents \"`</VerDTD>`{=html}\"
All together this WBXML code snippet, *6D6C71C303\"1.1\"01* represents:
`<small>`{=html}SyncML header snippet`</small>`{=html}
+---------------+-----------------------------------+
| <nowiki> | <nowiki> |
| 1 | <SyncML> |
| 2 | <SyncHdr> |
| 3 | <VerDTD>1.1</VerDTD></nowiki> |
| </nowiki> | |
+---------------+-----------------------------------+
So you can see how using WBXML shorthand would be a more compact means
of representing XML, saving bandwidth for mobile devices.
For more information please refer to Ed Dumbill\'s articles on syncML
with WBXML:
- Have Data, Will
Travel
- WBXML and
SyncML
## SyncML specifications
The best source of information on SyncML is the protocol itself. Visit
the Open Mobile Alliance for the SyncML specifications.
### Open Mobile Alliance
Download OMA SyncML Specifications and white
papers at the
Open Mobile Alliance. Or check out
the SyncML
Articles at
the Open Mobile Alliance.
## SyncML Implementations
Although the SyncML specifications are useful, you still have to
implement the protocol in your application. There are a few toolkits and
implementations out there that you can use to get a head start.
### SyncML Reference Toolkit
The Open Mobile Alliance has released a toolkit written in C to
demonstrate SyncML. You can get it
here. If you can
read German, you can get a sample application using the toolkit
here.
### Funambol
Interested in developing SyncML for Java? Check out the open source
project Funambol. It offers a Java
and C++ SDK that implements the SyncML data synchronization protocol, a
Java-based application framework for building SyncML server
applications, and a standalone SyncML server.
## Summary
Mobile Device Technology is improving and changing at a rapid pace. As
US telecommunication companies implement Third generation (3G) WCDMA
technology (wide-band code-division multiple access), or wireless
broadband, we will begin to see powerful devices emerge on the market.
These devices will be able to deliver full color, video, streaming
multimedia and a variety of data services such as Multimedia Messaging
Service (MMS) through WAP. In that infrastructure is becoming cheaper,
these telecommunication companies are starting to shift towards being
service providers and media vendors as opposed to communications
utilities. Cingular wireless, multimedia messaging and ringtones
services are a good example of the shift of their company towards being
a *media platform*. The companies that will survive will be the ones
that listen to customers needs and make easy-to-use services.
Telecommunications companies can add value to their services by creating
custom applications and services that use SyncML for synchronization.
```{=html}
<div style="color:#8b4513;">
```
## Exercises
1. Visit the Open Mobile Alliance Website, download the pdf of the
SyncML v. 1.1 protocol and review it. Reading this reference is a
valuable exercise in learning.
2. Answer these questions:
- What is WBXML and why is it used?
- How do you foresee SyncML being used in the future?
- Name a problematic situation whereby SyncML is the best \'tool\'
for the job.
`<small>`{=html}`<small>`{=html}*Answers: 2a) WBXML is Wap Binary XML,
it is a form of XML whereby the XML tags are abbreviated in order to
shorten the markup for transmission to mobile devices, which commonly
have bandwidth and memory limitations. 2b) SyncML will likely be used as
a general, standard syncing mechanism for synchronizing data sets
between systems, not just for mobile devices. 2c) A ticket-tracking
system called TNT helpdesk is a web-based open work request management
system. The staff running this system would like to have live data from
this system on their PDAs, listing open requests. Currently, the PDA
database is synced via a docking sync station attached to the staff
members\' PCs. Staff members have to download the request list as a CSV
file, convert it into a usable PDA database and upload it to the PDA,
making it this process cumbersome, prone to error, and always
out-of-date. Recommendation: Create a custom app to push live updates to
the PDAs using SyncML over
Bluetooth/Wireless*`</small>`{=html}`</small>`{=html}
```{=html}
</div>
```
## References
+----------------------------------------------------------------------+
| Dumbill, E.(2002, January 1). *XML Watch: Have data, will |
| travel.* IBM.com. Retrieved April 6, 2004 from\ |
| <http |
| ://www-106.ibm.com/developerworks/xml/library/x-synchml/index.html>\ |
+----------------------------------------------------------------------+
| Dumbill, E.(2003, March 1). *XML Watch: WBXML and basic SyncML |
| server requirements.* IBM.com. Retrieved April 6, 2004 from\ |
| <http://www-106.ibm.com/developerworks/xml/library/x-syncml2.html>\ |
+----------------------------------------------------------------------+
| *How \[SyncML\] works*(n.a). Nokia.com. Retrieved April 6, 2004 |
| from\ |
| <http://www.nokia.com/nokia/0,8764,2559,00.html>\ |
+----------------------------------------------------------------------+
| *The New SyncML Standard.* . Cellular Dot Co Dot Za |
| Website. Retrieved April 6, 2004 from\ |
| <http://www.cellular.co.za/syncml.htm>\ |
+----------------------------------------------------------------------+
| Open Mobile Alliance (2002, April 2). *SyncML version 1.0, 1.1 |
| specification, white paper, errata.* Retrieved April 6, 2004 from\ |
| <http:// |
| www.openmobilealliance.org/tech/affiliates/syncml/syncmlindex.html>\ |
+----------------------------------------------------------------------+
| Pabla, C(2002, April 1). *SyncML Intensive: A beginner\'s look at |
| the SyncML protocol and procedures.* IBM.com. Retrieved April 6, |
| 2004 from\ |
| <http://www-106.ibm.com/developerworks/xml/library/wi-syncml2/>\ |
+----------------------------------------------------------------------+
| SyncML Initiative, Ltd.(2000, December 7). *SyncML Specification |
| Protocol version 1.0.* The Open Mobile Alliance. Retrieved April 6, |
| 2004 from\ |
| <http://www.openmobileall |
| iance.org/tech/affiliates/syncml/syncml_represent_v10_20001207.pdf>\ |
+----------------------------------------------------------------------+
| SyncML Initiative, Ltd.(2002, February 15). *SyncML Device |
| Information DTD version 1.1.* . Retrieved April 6, 2004 from\ |
| <http://www.openmobile |
| alliance.org/tech/affiliates/syncml/syncml_devinf_v11_20020215.pdf>\ |
+----------------------------------------------------------------------+
| Saarilahti, A, Group SyncML, et al.(2001, April 23). *Tik-76.115 |
| Short introduction to SyncML.* . Retrieved April 6, 2004 from\ |
| <http://www.hut.fi/u/asaarila/syncml/syncml_intro.html>\ |
+----------------------------------------------------------------------+
| Stemberger, S.(2002, October). *Syncing Data: An introduction to |
| SyncML.* IBM.com. Retrieved April 6, 2004 from\ |
| <http://www-106.ibm.com/developerworks/wireless/library/wi-syncml/>\ |
+----------------------------------------------------------------------+
| Synchronica Software GmbH(n.d.). *SyncML for Microsoft |
| Exchange.* Synchronica Software Website. Retrieved May 24, 2004 |
| from\ |
| <http://www.synchronica.com/products/syncml/corporate_syncml.html>\ |
+----------------------------------------------------------------------+
| Weblicon Technologies AG (n.d.). *SyncML for SunOne.* Weblicon |
| Technologies AG Website. Retrieved April 6, 2004 from\ |
| <http://www.weblicon.net/html/products_syncml.html>\ |
+----------------------------------------------------------------------+
| XML Cover Pages (n.a., 2003, April 29). *The SyncML Initiative.* XML |
| Cover Pages Dot Org Website. Retrieved April 6, 2004 from\ |
| <http://xml.coverpages.org/syncML.html>\ |
+----------------------------------------------------------------------+
fr:Programmation XML/SyncML
|
# XML - Managing Data Exchange/SVG
+----------------------------------+----------------------------------+
| `<big>`{=html}Learning | `<small style="font- |
| objectives`</big>`{=html} | weight:normal">`{=html}Initiated |
| | by:`</small>`{=html} |
| - define SVG and its purpose | |
| - discuss differences between | ```{=html} |
| raster graphics and SVG | <div style="text-align:center"> |
| - define similarities and | ``` |
| differences between Flash | The University of Georgia |
| and SVG | |
| - create a simple SVG document | `<big |
| | style="color:#900">`{=html}Terry |
| | College of |
| | Business`</big>`{=html} |
| | |
| | Department of Management |
| | Information Systems |
| | |
| | ```{=html} |
| | </div> |
| | ``` |
+----------------------------------+----------------------------------+
## What is SVG?
Based on XML, Scalable Vector Graphics (SVG) is an open-standard vector
graphics file format and Web development language created by the W3C,
and has been designed to be compatible with other W3C standards such as
DOM, CSS, XML, XSLT, XSL, SMIL, HTML, and XHTML. SVG enables the
creation of dynamically generated, high-quality graphics from real-time
data. SVG allows you to design high-resolution graphics that can include
elements such as gradients, embedded fonts, transparency, animation, and
filter effects.
SVG files are different from raster or bitmap formats, such as GIF and
JPEG that have to include every pixel needed to display a graphic.
Because of this, GIF and JPEG files tend to be bulky, limited to a
single resolution, and consume large amounts of bandwidth. SVG files are
significantly smaller than their raster counterparts. Additionally, the
use of vectors means SVG graphics retain their resolution at any zoom
level. SVG allows you to scale your graphics, use any font, and print
your designs, all without compromising resolution. SVG is XML-based and
written in plain text, meaning SVG code can be edited with any text
editor. Additionally, SVG offers important advantages over bitmap or
raster formats such as:
- **Zooming**: Users can magnify their view of an image without
negatively affecting the resolution.
- **Text stays text**: Text remains editable and searchable.
Additionally, any font may be used.
- **Small file size**: SVG files are typically smaller than other
Web-graphic formats and can be downloaded more quickly.
- **Display independence**: SVG images always appear crisp on your
screen, no matter the resolution. You will never experience
"pixelated" images.
- **Superior color control**: SVG offers a palette of 16 million
colors.
- **Interactivity and intelligence**: Since SVG is XML-based, it
offers dynamic interactivity that can respond to user actions.
### Data-driven graphics
Because it is written in XML, SVG content can be linked to back-end
business processes, databases, and other sources of information. SVG
documents use existing standards such as Cascading Stylesheets (CSS) and
Extensible Stylesheet Language (XSL), enabling graphics to be easily
customized. This results in:
- **Reduced maintenance costs**: Because SVG allows image attributes
to be changed dynamically, it eliminates the need for numerous image
files. SVG allows you to specify rollover states and behaviors via
scriptable attributes. Complex navigation buttons, for example, can
be created using only one SVG file where normally this would require
multiple raster files.
- **Reduced development time**: SVG separates the three elements of
traditional Web workflow -- content (data), presentation (graphics),
and application logic (scripting). With raster files, entire
graphics must be completely recreated if changes are made to
content.
- **Scalable server solutions**: Both the client and the server can
render SVG graphics. Because the "client" can be utilized to render
the graphic, SVG can reduce server loads. Client-side rendering can
enhance the user-experience by allowing users to "zoom in" on an SVG
graphic. Additionally, the server can be used to render the graphic
if the client has limited processing resources, such as a PDA or
cell phone. Either way the file is rendered, the source content is
the same.
- **Easily updated**: SVG separates design from content, allowing easy
updates to either.
### Interactive graphics
SVG allows you to create Web-based applications, tools, or user
interfaces. Additionally, you can incorporate scripting and programming
languages such as JavaScript, Java, and Visual Basic. Any SVG element
can be used to modify or control any other SVG or HTML element. Because
SVG is text based, the text inside graphics can be translated for other
languages quickly, which simplifies localization efforts. Additionally,
if there is a connection to a database, SVG allows drill-down
functionality for charts and graphs. This results in:
- **Improved end user experience**: Users can input their own data,
modify data, or even generate new graphics from two or more data
sources.
- **In SVG, text is text**: As mentioned previously, SVG treats text
as text. This makes SVG-based graphics searchable by search engines.
- **SVG can create SVG**: Enterprise applications such as an online
help feature can be developed.
### Personalized graphics
SVG can be targeted to people to overcome issues of culture,
accessibility, and aesthetics, and can be customized for many audiences
and demographic groups. SVG can also be dynamically generated using
information gathered from databases or user interaction. The overall
goal is to have one source file, which transforms seamlessly in a wide
variety of situations. This results in:
- **One source, customized appearances**: SVG makes it possible to
change color and other properties based on aesthetics, culture, and
accessibility issues. SVG can use stylesheets to customize its
appearance for different situations.
- **Internationalization, localization**: SVG supports Unicode
characters in order to effectively display text in many languages
and fashions -- vertically, horizontally, and bi-directionally.
- **Utilizing existing standards**: SVG works seamlessly with
stylesheets in order to control presentation. Cascading Stylesheets
(CSS) can be used for typical font characteristics as well as for
other SVG graphic elements. For example, you can control the stroke
color, fill color, and fill opacity of an element from an external
stylesheet.
## SVG vs. Macromedia Flash
Macromedia has been the dominant force behind vector-based graphics on
the web for the last 10 years. It is apparent, however, that SVG
provides alternatives to many of the functions of Flash and incorporates
many others. The creation of vector-based graphical elements is the base
structure of both SVG and Flash. Much like Flash, SVG also includes the
ability to create time-based animations for each element and allows
scripting of elements via DOM, JavaScript, or any other scripting
language that the SVG viewer supports. Many basic elements are available
to the developer, including elements for creating circles, rectangles,
lines, ellipses, polygons, and text. Much like HTML, elements are styled
with Cascading Stylesheets (CSS2) using a style element or directly on a
particular graphical element via the style attribute. Styling properties
may also be specified with presentation attributes. For each CSS
property applicable to an element, an XML attribute specifying the same
styling property can also be used. There is an on going debate about
whether Flash or SVG is better for web development There are advantages
to both, it usually comes down to the situation.
**Flash Advantages:**
- Use Flash if you want to make a Flash-like website -- replicating
the same effect using SVG is hard.
- Use Flash if you want complex animations, or complex games (SVG\'s
built in SMIL animation engine is extremely processor intensive).
- Use Flash if your users will not be so computer literate, for
instance a children\'s site, or a site appealing to a wide audience.
- Use Flash if sound is important -- SVG/SMIL supports sound, but
it\'s pretty basic.
- Use Flash if you prefer WYSIWYG to script.
**SVG advantages:**
- It\'s fully scriptable, using a DOM1 interface and JavaScript. That
means you can start with an empty SVG image, and build it up using
JavaScript.
- SVG can easily be created by ASP, PHP, Perl, etc and extracted from
a database.
- It has a built-in ECMA-script (JavaScript) engine, so you don\'t
have to code per browser, and you don\'t need to learn Flash\'s
action-script.
- SVG is XML, meaning it can be read by anything that can read XML .
Flash can use XML, but needs to convert it before use.
- This also allows SVG to be transformed through an XSLT
stylesheet/parser.
- SVG supports standard CSS1 stylesheets.
- Text used in SVG remains selectable and searchable.
- You only need a text editor to create SVG, as opposed to buying
Flash.
- SVG is an web real standard (not just "de facto"), supported by
various different programs, some of which are free software (and
thus available for most free computer operating systems).
## Why use SVG?
SVG is emerging through the efforts of the W3C and its members. It is
open source and as such does not require the use of proprietary
languages and development tools as does Macromedia Flash. Because it is
XML-based, it looks familiar to developers and allows them to use
existing skills. SVG is text based and can be learned by leveraging the
work (or code) of others, which significantly reduces the overall
learning curve. Additionally, because SVG can incorporate JavaScript,
DOM, and other technologies, developers familiar with these languages
can create graphics in much the same way. SVG is also highly compatible
because it works with HTML, GIF, JPEG, PNG, SMIL, ASP, JSP, and
JavaScript. Finally, graphics created in SVG are scalable and do not
result in loss of quality across platforms and devices. SVG can
therefore be used for the Web, in print, as well as on portable devices
while retaining full quality.
## SVG Viewer
### The Adobe SVG Viewer
The Adobe SVG Viewer is available as a downloadable plug--in that allows
SVG to be viewed on Windows, Linux and Mac operating systems in all
major browsers including Internet Explorer (versions 4.x, 5.x, 6.x),
Netscape (versions 4.x, 6.x), and Opera in Internet Explorer and
Netscape.
The Adobe SVG Viewer is the most widely deployed SVG Viewer and it
supports almost all of the SVG Specification including support for the
SVG DOM, animation and scripting.
**Features of the Adobe SVG Viewer** Click the right mouse button
(CTRL-Key + mouse click in Mac) over your SVG image to get a context
menu. The context menu gives you several options, which can all be
accessed utilizing the menu itself or "hotkeys":
`<small>`{=html}Table 1: Features of the Adobe SVG
Viewer`</small>`{=html}
---------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Function Description
Zoom In Using the CTRL-Key (or Apple-Key) you can drag your mouse to make a rectangle that specifies the cross-section of the area you will zoom to.
Zoom Out This work just like "Zoom In" except you press the CTRL-Key and the SHIFT-Key at the same time.
Panning Pressing the ALT-Key and move the mouse cursor while a hand-icon appears.
Copy SVG The purpose of the SVG Viewers "Copy SVG" options is for users to be able to cut-and-paste graphics and/or source code into other applications. Using "Copy SVG" developers are able to make a copy of the source code, which can be pasted into any text editor. Also, after selecting "Copy SVG" and switching to a desktop application such as MS Office users are able to choose either to use the Edit/Paste option to produce a snapshot of the SVGs DOM-tree code (this contains the current structure of the dynamic SVG image) or users can use the Edit/Paste Special option to translate the SVG into a Bitmap image. These options are likely to improve and increase as support for SVG improves in other applications.
View Source The SVG Viewers "View Source" menu options allow both compressed and uncompressed SVG source code to instantly be viewed as text in a new browser window. This is a very handy option for designers and developers.
Save SVG as... This option allows for quickly saving of SVG content to your local computer by popping up a "save SVG as" form that gives you the option to input the name and location of the file. In version 3 of the Adobe SVG Viewer the option of Saving as GZip compressed SVG (.svgz) was added to the \'save as' dialog box.
---------------- --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
### SMIL
The Synchronized Multimedia Integration Language (SMIL, pronounced
"smile") enables simple authoring of interactive audiovisual
presentations. SMIL is typically used for "rich media"/multimedia
presentations which integrate streaming audio and video with images,
text or any other media type. SMIL is an easy-to-learn HTML-like
language, and many SMIL presentations are written using a simple
text-editor. SMIL can be used with XML to enable video and sound when
viewing a SVG.
### Attention Microsoft Windows Mozilla users!
The Seamonkey and Mozilla Firefox browsers have SVG support enabled
natively. If desired, the Adobe SVG Viewer plugin will work with Mozilla
Firefox, or the Seamonkey browser.
1 Webkit based browsers
also have some SVG support natively.
### Native SVG (Firefox)
The Mozilla SVG implementation is a native SVG implementation. This is
as opposed to plug-in SVG viewers such as the Adobe viewer (which is
currently the most popular SVG viewer).
Some of the implications of this are:
- Mozilla can handle documents that contain SVG, MathML, XHTML, XUL,
etc. all mixed together in the same \'compound\' document. This is
being made possible by using XML namespaces.
- Mozilla is \'aware\' of the SVG content. It can be accessed through
the SVG DOM (which is compatible with the XML DOM) and manipulated
by Mozilla\'s script engine.
- Other Mozilla technologies can be used with SVG. XBL coupled with
SVG is a particular interesting combination. It can be used to
create graphical widgets (I wonder when we\'ll see the first
SVG-based chrome!) or extend Mozilla to recognize other specialized
languages such as e.g. CML (chemical markup language). There are
samples of these kinds of more advanced usage patterns on
<http://croczilla.com/svg/>.
### rsvg-view
rsvg-view program is a part of the librsvg package[^1]. It may be used
as the default svg opener. It can resize svgs and export them to png
which is often the only thing one needs to do with an svg file.[^2]
Example : rsvg-view-3 name.svg
## Creating SVG files
### How to do it
One can use 4 groups of programs :
- general text editors, like Notepad ++ (with XML syntax highlithning)
- specialized svg editors
- programs that can exports svg (like gnuplot, Maxima CAS)
- own programs to create svg files directly thru concatenate of
strings
#### SVG editors
As you can see from the previous example of a path definition, SVG files
are written in an extremely abbreviated format to help minimize file
size. However, they can be very difficult to write depending on the
complexity of your image. There are SVG editor tools that can help make
this task easier. Some of these tools are:
`<small>`{=html}Table 3: SVG Editors`</small>`{=html}
--------------------------------------- ---------------------------------------------- --------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SVG Editor Platform Availability Description
Adobe Illustrator 10.0 Mac OS 9.1/9.2/10.1, Win98/ME, Win2000/XP Commercial product Illustrator version 9.01 had SVG export capability. Version 10, announced recently, adds SVG import and enhances SVG export, including data-driven graphics.
Sodipodi Linux / UNIX Open Source (Free, with source) Fast vector graphics WYSWIG editor.
Adobe Livemotion 2 Win98/ME, Win2000/XP Commercial product Adobe Livemotion is the authoring tool similar to Macromedia Flash. It had SVG export capability in earler version, but in Version 2, its support is withdrawn.It looks that even Adobe\'s support of the SVG is dubious.
Beez Win95/98/ME, WinNT/2000/XP Free download Beez is a WYSIWYG editor to create a single animated SVG path, consisting of multiple Bezier curves, which can then be used in an SVG file. Nice utility for hand coders. It is an open-source project, on sourceforge, and written in Delphi.
Corel Draw! Win95/98/ME, WinNT/2000, Mac OS X version 11 Commercial product Has SVG import and export capability
Gill (Gnome Illustration Application) Linux / UNIX (with Gnome) Free, with source Drawing program with SVG import and export; has a full DOM; continuously updated, can embed SVG in other Gnome programs (such as Gnumeric, the spreadsheet). See the CVS changelog for latest status
IMS Web Dwarf Win95/98/ME, WinNT/2000/XP Free download WYSIWYG editor, exports to either HTML or SVG
IMS Web Engine Win95/98/ME, WinNT/2000/XP 14-day trial downloadable IMS Web Engine is an Interactive Animation Editor and Web Top publisher for the creation of content rich interactive Dynamic HTML and SVG
Inkscape Linux, Windows, Mac Free, with source WYSIWYG editor, but allows editing the XML directly. No animation yet.
--------------------------------------- ---------------------------------------------- --------------------------------- ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#### own programs
##### C
Here is example in C :
``` c
/*
c console program based on :
cpp code by Claudio Rocchini
http://commons.wikimedia.org/wiki/File:Poincare_halfplane_eptagonal_hb.svg
http://validator.w3.org/
The uploaded document "circle.svg" was successfully checked as SVG 1.1.
This means that the resource in question identified itself as "SVG 1.1"
and that we successfully performed a formal validation using an SGML, HTML5 and/or XML
Parser(s) (depending on the markup language used).
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
const double PI = 3.1415926535897932384626433832795;
const int iXmax = 1000,
iYmax = 1000,
radius=100,
cx=200,
cy=200;
const char *black="#FFFFFF", /* hexadecimal number as a string for svg color*/
*white="#000000";
FILE * fp;
char *filename="circle.svg";
char *comment = "<!-- sample comment in SVG file \n can be multi-line -->";
void draw_circle(FILE * FileP,int radius,int cx,int cy)
{
fprintf(FileP,"<circle cx=\"%d\" cy=\"%d\" r=\"%d\" style=\"stroke:%s; stroke-width:2; fill:%s\"/>\n",
cx,cy,radius,white,black);
}
int main(){
// setup
fp = fopen(filename,"w");
fprintf(fp,
"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>\n"
"%s \n "
"<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\" \n"
"\"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n"
"<svg width=\"20cm\" height=\"20cm\" viewBox=\"0 0 %d %d \"\n"
" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
comment,iXmax,iYmax);
// draw
draw_circle(fp,radius,cx,cy);
// end
fprintf(fp,"</svg>\n");
fclose(fp);
printf(" file %s saved \n",filename );
return 0;
}
```
##### Haskell
Haskel code : lavaurs\' algorithm in Haskell with SVG output by Claude
Heiland-Allen
##### JavaScript
!SVG image with JavaScript
code
##### Matlab
Based on code by Guillaume JACQUENOT :[^3]
``` matlab
filename = [filename '.svg'];
fid = fopen(filename,'w');
fprintf(fid,'<?xml version="1.0" standalone="no"?>\n');
fprintf(fid,'"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">\n');
fprintf(fid,'<svg width="620" height="620" version="1.1"\n');
fprintf(fid,'xmlns="http://www.w3.org/2000/svg">\n');
fprintf(fid,'<circle cx="100" cy="100" r="10" stroke="black" stroke-width="1" fill="none"/>\n');
fprintf(fid,'</svg>\n');
fclose(fid);
```
##### Lisp
One can use cl-svg library or your own procedure.
##### Maxima
`BeginSVG(file_name,cm_width,cm_height,i_width,i_height):=`\
`block(`\
`destination : openw (file_name),`\
`printf(destination, "`
```{=html}
<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>
```
\~%\"),
`printf(destination,"<svg width=\"~d cm\" height=\"~d cm\" viewBox=\"0 0 ~d ~d\" xmlns=\"``http://www.w3.org/2000/svg\``" version=\"1.1\">~%",`\
`cm_width,cm_height,i_width,i_height),`\
`return(destination)`\
`);`\
`CircleSVG(dest,center_x,center_y,_radius):=printf(dest,"``<circle cx=\"~d\" cy=\"~d\" r=\"~d\" fill=\"white\" stroke=\"black\" stroke-width=\"2\"/>`{=html}`~%",`\
`center_x,center_y,_radius);`\
`CloseSVG(destination):=`\
`(`\
`printf(destination,"`
```{=html}
</svg>
```
\~%\"),
`close (destination)`\
`);`\
`/* ---------------------------------------------------- */`\
`cmWidth:10;`\
`cmHeight:10;`\
`iWidth:800;`\
`iHeight:600;`\
`radius:200;`\
`centerX:400;`\
`centerY:300;`\
`f_name:"b.svg";`\
`/* ------------------------------------------------------*/`\
`f:BeginSVG(f_name,cmWidth,cmHeight,iWidth,iHeight);`\
`CircleSVG(f,centerX,centerY,radius);`\
`CloseSVG(f);`
##### Python
One can use a prepared library, or wrap the svg code in single quotes.
def svg_page():
""" Function to write test code for a stub svg code page
The raw code that uses double-quotes is captured by single quotes
To become a python text string"""
page='<?xml version="1.0"?>\n<svg xmlns="http://www.w3.org/2000/svg" top="0in" width="5.5in" height="2in">\n <rect fill="blue" width="250" height="200"/>\n</svg>\n'
return page
def write_page(page, title):
""" Function to write the svg code to disk """
filename = title + ".svg"
f = open(filename, "w")
f.write(page)
write_page (svg_page(), "My svgstub")
!Image with python
code
### Getting started
Because it is based on XML, SVG follows standard XML conventions. Every
SVG file is contained within an
```{=html}
<svg>
```
tag as its parent element. SVG can be embedded within a parent document
or used independently. For example, the following shows an independent
SVG document:
**Exhibit 1: Creating a SVG**
``` XML
<?xml version="1.0" standalone="no"?>
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
...
</svg>
```
The first line declares that the code that follows is XML. Note the
"standalone" attribute. This denotes that this particular file does not
contain enough processing instructions to function alone. In order to
attain the required functionality it needs to display a particular
image, the SVG file must reference an external document.
The second line provides a reference to the Document Type Definition, or
DTD. As mentioned in Chapter 7: XML Schemas, the DTD is an alternate way
to define the data contained within an XML instanced document.
Developers familiar with HTML will notice the DTD declaration is similar
to that of an HTML document, but it is specific for SVG. For more
information about DTDs, visit:
<http://www.w3schools.com/dtd/dtd_intro.asp>
**Hint:** Many IDEs (ex. NetBeans) do not have SVG "templates" built in
to the tool. Therefore, it may be easier to use a simple text editor
when creating SVG documents. Once you have an SVG Viewer installed, you
should then be able to open and view your SVG document with any browser.
When creating your SVG documents, remember to:
- Declare your document as an XML file
- Make sure your SVG document elements are between
```{=html}
<svg>
```
element tags, including the SVG namespace declaration.
- Save your file with a .svg file extension.
- It is not necessary do include a DOCTYPE statement, which includes
information to identify this as an SVG document (since SVG 1.2 there
is also not more such).[^4][^5][^6]
The
```{=html}
<svg>
```
element on the second line defines the SVG document, and can specify,
among other things, the user coordinate system, and various CSS unit
specifiers. Just like with XHTML documents, the document element must
include a namespace declaration to declare the element as being a member
of the relevant namespace (in this case, the SVG namespace). Within the
```{=html}
<svg>
```
element, there can be three types of drawing elements: text, shapes, and
paths.
### Text
The following is an example of the text element: **Exhibit 2: Using text
with SVG**
``` XML
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="5.5in" xml:space="preserve" xmlns="http://www.w3.org/2000/svg" height="0.5in">
<text y="15" fill="red">This is SVG.</text>
</svg>
```
The
```{=html}
<svg>
```
element specifies: 1) that white space within text elements will be
retained, 2) the width and height of the SVG document --- particularly
important for specifying print output size. In this example, the text is
positioned in a 5.5 inches wide by .5 inches tall image area. The "y"
attribute on line 5 declares that the text element's baseline is 15
pixels down from the top of the SVG document. An omitted "x" attribute
on a text element implies an x coordinate of 0.
Because SVG documents use a W3C DTD, you can use the W3C Validator to
validate your document. Notice that the "style" attribute is used to
describe the presentation of the text element. The text could
equivalently have been given a red color by use of a presentation
attribute fill=\"red\".
### Shapes
SVG contains the following basic shape elements:
- Rectangles
- Circles
- Ellipses
- Lines
- Polylines
- Polygons
These basic shapes, along with "paths" which are covered later in the
chapter, constitute the graphic shapes of SVG. In this introduction to
SVG, we will only cover some of the shapes here.
#### Rectangles
The `<rect>`{=html} element defines a rectangle which is axis-aligned
with the current user coordinate system, the coordinate system that is
currently active and which is used to define how coordinates and lengths
are located and computed on the current canvas. Rounded rectangles can
be created by setting values for the rx and ry attributes.
The following example produces a blue rectangle with its top left corner
aligning with the top left corner of the image area. This uses the
default value of \"0\" for the x and y attributes.
**Exhibit 3: Creating a rectangle in SVG**
``` XML
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" top="0in" width="5.5in" height="2in">
<rect fill="blue" width="250" height="200"/>
</svg>
```
It will produce this result:
!Example of SVG use of rectangle
shape
#### Circles
A circle element requires three attributes: cx, cy, and r. The \'cx' and
\'cy' values specify the location of the center of the circle while the
\'r' value specifies the radius. If the \'cx' and \'cy' attributes are
not specified then the circle\'s center point is assumed to be (0, 0).
If the \'r' attribute is set to zero then the circle will not appear.
Unlike \'cx' and \'cy', the \'r' attribute is not optional and must be
specified. In addition the keyword stroke creates an outline of the
image. Both the width and the color can be changed.
**Exhibit 4: Creating a circle in SVG**
``` XML
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="350" height="300">
<circle cx="100" cy="50" r="40" stroke="darkslategrey" stroke-width="2" fill="grey"/>
</svg>
```
It will produce this result:
!Example of SVG use of circle
shape
#### Polygons
A polygon is any geometric shape consisting of three or more sides. The
\'points\' attributes describes the (x,y) coordinates that specify the
corners points of the polygon. For this specific example, there are
three points which indicate that a triangle will be produced.
**Exhibit 5: Creating a Polygon in SVG**
``` XML
<?xml version="1.0" standalone="no"?>
<svg width="100%" height="100%" version="1.1" xmlns="http://www.w3.org/2000/svg">
<polygon points="220,100 300,210 170,250" style="fill:#blue;stroke:red;stroke-width:2"/>
</svg>
```
It will produce this result:

### Paths
Paths are used to draw your own shapes in SVG, and are described using
the following data attributes:
`<small>`{=html}Table 2: SVG Paths`</small>`{=html}
---------------------------------- --------- ----------------------------------------------------- ------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Attribute Command Parameters Function Description
Moveto M x y Set a new current point Start a new sub-path at the given (x,y) coordinate.
Lineto L x y Draw a straight line Draw a line from the current point to the given (x,y) coordinate which becomes the new current point.
Horizontal lineto H x Draw a horizontal line Draws a horizontal line from the current point (cpx, cpy) to (x, cpy).
Vertical lineto V y Draw a vertical line Draws a vertical line from the current point (cpx, cpy) to (cpx, y).
Curveto C x1 y1 x2 y2 x y Draw a curve using a cubic Bezier Draws a cubic Bézier curve from the current point to (x,y) using (x1,y1) as the control point at the beginning of the curve and (x2,y2) as the control point at the end of the curve.
Smooth curveto S x2 y2 x y Draw a shorthand/smooth curve using a cubic Bezier Draws a cubic Bézier curve from the current point to (x,y). The first control point is assumed to be the reflection of the second control point on the previous command relative to the current point. (x2,y2) is the second control point (i.e., the control point at the end of the curve)
Quadratic Belzier curveto Q x1 y1 x y Draws a quadratic Bézier curve Draws a quadratic Bézier curve from the current point to (x,y) using (x1,y1) as the control point.
Smooth quadratic Belzier curveto T x y Draws a shorthand/smooth quadratic Bézier curve Draws a quadratic Bézier curve from the current point to (x,y).
Elliptical arc A rx ry x-axis-rotation large-arc-flag sweep-flag x y Draw an elliptical or circular arc Draws an elliptical arc from the current point to (x, y). The size and orientation of the ellipse are defined by two radii (rx, ry) and an x-axis-rotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. large-arc-flag and sweep-flag contribute to the automatic calculations and help determine how the arc is drawn.
Closepath Z (none) Close the current path by drawing a line to the last moveto point Close the current sub path by drawing a straight line from the current point to current sub path's initial point.
---------------------------------- --------- ----------------------------------------------------- ------------------------------------------------------------------- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The following example produces the shape of a triangle. The "M"
indicates a "moveto" to set the first point. The "L" indicates "lineto"
to draw a line from "M" to the "L" coordinates. The "Z" indicates a
"closepath", which draws a line from the last set of L coordinates back
to the M starting point.
**Exhibit 6: Creating paths in SVG**
``` XML
<?xml version="1.0"?>
<svg xmlns="http://www.w3.org/2000/svg" width="5.5in" height="2in">
<path d="M 50 10 L 350 10 L 200 120 z"/>
</svg>
```
It produces this result:
!Example of SVG use of
paths
## Validation
After creating file check its code with the W3C Validatior[^7]
## Optimisation
Even code without errors can be improved. For example grouping elements
makes code shorter.
## Including SVG in HTML
There are three methods to include SVG in an HTML document. Basically,
the SVG document is first created as a stand-alone file. It is then
referenced in the HTML document using one of the following commands:
`<small>`{=html}Table 4: Including SVG in HTML`</small>`{=html}
+------------+---------------------------+---------------------------+
| Command | Advantages | Disadvantages |
+------------+---------------------------+---------------------------+
| \<embed\> | 1. Supported in nearly | 1. Not clearly |
| | any browser | standardized within |
| | 2. Allows html2svg and | any HTML |
| | svg2html scripting | specification |
| | 3. Recommended by Adobe | |
| | for their SVG Viewer | |
+------------+---------------------------+---------------------------+
| \<object\> | 1. HTML4 and higher | 1. Works on newer |
| | standard | browsers but without |
| | 2. Supported in newer | html2svg and svg2html |
| | browser generations | scripting |
+------------+---------------------------+---------------------------+
| \<iframe\> | 1. Works in most | 1. Generates a |
| | browsers, but not | window-like border |
| | documented | without specific |
| | | styling |
+------------+---------------------------+---------------------------+
### Embed
The syntax is as follows: **Exhibit 7: Embedding SVG into HTML using
keyword embed**
``` XML
<embed src="canvas.svg" width="350" height="176" type="image/svg+xml" name="emap">
```
An additional attribute, "pluginspage", can be set to the URL where the
plug-in can be downloaded:
`pluginspage="``http://www.adobe.com/svg/viewer/install/main.html``"`
### Object
The syntax is as follows and conforms to the HTML 4 Strict
specification: **Exhibit 8: Embedding SVG into HTML using keyword
object**
``` XML
<object type="image/svg+xml" name="omap" data="canvas_norelief.svg" width="350" height="176"></object>
```
Between the opening and the closing \<object\> tags, information for
browsers that do not support objects can be added:
``` XML
<object ...>You should update your browser</object>
```
Unfortunately some browsers such as Netscape Navigator 4 do not show
this alternative content if the type attribute has been set to something
other than text/html.
### Iframe
The syntax is as follows and conforms to the HTML 4 Transitional
specification: **Exhibit 9: Embedding SVG into HTML using keyword
iframe**
``` html4strict
<iframe src="canvas_norelief.svg" width="350" height="176" name="imap"></iframe>
```
Between the opening and the closing \<iframe\> tags, information for
browsers that do not support iframes can be added:
``` XML
<iframe ...>You should update your browser</iframe>
```
### Creating 3D SVG images
*Section by Charles Gunti, UGA Master of Internet Technology Program,
Class of 2007*
Sometime we may want to view an SVG image in three dimensions. For this
we will need to change the viewpoint of the graphic. So far we have
created two dimensional graphics, such as circles and squares. Those
exist on a simple x, y plane. If we want to look at something in three
dimensions we have to add the z coordinate plane. The z plane is already
there, but we are looking at it straight on, so if data is changed on z
it doesn\'t look any different to the viewer. We need to add another
parameter to the data file, the z parameter.
``` XML
<?xml version="1.0"?>
<data>
<subject x_axis="90" y_axis="118" z_axis="0" color="red" />
<subject x_axis="113" y_axis="45" z_axis="75" color="purple" />
<subject x_axis="-30" y_axis="-59" z_axis="110" color="blue" />
<subject x_axis="60" y_axis="-50" z_axis="-25" color="yellow" />
</data>
```
Once we have the data we will use XSLT to create the SVG file. The SVG
stylesheet is the same as other stylesheets, but we need to ensure an
SVG file is created during the transformation. We call the SVG namespace
with this line in the declarations:
` xmlns="``http://www.w3.org/2000/svg`
Another change we should make from previous examples is to change the
origin of (0, 0). We change the origin in this example because some of
our data is negative. The default origin is at the upper left corner of
the SVG graphic. Negative values are not displayed because, unlike
traditional coordinate planes, negative values are above positive
values. To move the origin we simply add a line of code to the
stylesheet. Before going over that line, let\'s look at The g element.
The container element, g, is used for grouping related graphics
elements. Here, we\'ll use g to group together our graphical elements
and then we can apply the transform. Here is how we declare g and change
the origin to a point 300 pixels to the right and 300 pixels down:
` ``<g transform="translate(300,300)">`{=html}*`graphical elements`*`</g>`{=html}
SVG transformations are pretty simple, until it comes to changing the
viewpoint. SVG has features such as rotating and skewing the image in
two dimensions, but it cannot rotate the coordinate system in three
dimensions. For that we will need to use some math and a little Java.
When rotating in three dimensions two rotations need to be made, one
around the y axis, and another around the x axis. The first rotation
will be around the y axis and the formula will look like this:
$z' = z \cdot \cos(-Az) - x \cdot \sin(-Az)$ *Az is the angle the z axis
will be rotated*
$x' = z \cdot \sin(-Az) - x \cdot \cos(-Az)$
$y' = y \,$ *y will not change because we are rotating around the y
axis*
The second rotation will be around the x axis. Keep in mind that one
rotation has already been made, so instead of using x, y, and z values
we need to use x\', y\', and z\' (x-prime, y-prime and z-prime) found in
the last rotation. The formula will look like this:
z\" = z\'\*cos(Ay) -- y\'\*sin(Ay) *Ay is the angle of rotation on the y
axis*
y\" = z\'\*sin(Ay) + y\'\*cos(Ay)
x\" = x\' *Remember we are rotating around the x axis, so this does not
change*
Remember from trig class the old acronym **SOH CAH TOA**? This means
*Sin = Opposite/Hypotenuse* *Cos = Adjacent/Hypotenuse* *Tan =
Opposite/Adjacent*
And we use those functions to find the angles needed for our rotations.
Based of the previous two formulas we can make the following statements
about Az and Ay:
tan(Az) = Xv/Zv
sin(Ay) = Yv/sqrt(Xv2 + Yv2 + Zv2)
With so many steps to take to make the rotation we should drop all of
this information into a Java class, then call the class in the
stylesheet. The Java class should have methods for doing all of the
calculations for determining where the new data points will go once the
rotation is made. Creating that java class is beyond the scope of this
section, but for this example I\'ll call it ViewCalc.class.
Now that we can rotate the image, we need to integrate that capability
into the transformation. We will use parameters to pass viewpoints into
the stylesheet during the transformation. The default viewpoint will be
(0, 0, 0) and is specified on the stylesheet like so:
**Exhibit 10: 3D images with SVG**
``` XML
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
xmlns="http://www.w3.org/2000/svg"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<!-- default viewpoint in case they are not specified -->
<!-- from the command line -->
<xsl:param name="viewpoint_x">0</xsl:param>
<xsl:param name="viewpoint_y">0</xsl:param>
<xsl:param name="viewpoint_z">0</xsl:param>
<xsl:template match="/">
…
```
Java now needs to be added to the stylesheet so the processor will know
what methods to call. Two lines are added to the namespace declarations:
``` XML
<?xml version="1.0" ?>
<xsl:stylesheet version="1.0"
xmlns="http://www.w3.org/2000/svg"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
<b>xmlns:java="ViewCalc"
exclude-result-prefixes="java"</b>>
```
Notice the *exclude-result-prefixes=\"java\"* line. That line is added
so things in the stylesheet with the *java:* prefix will be processed,
not output. Be sure to have the ViewCalc class in the CLASSPATH or the
transformation will not run.
The final step is to call the methods in the ViewCalc class from the
stylesheet. For example:
``` XML
<xsl:template match="square">
<xsl:for-each select=".">
<xsl:variable name="locationx" select="@x_axis"/>
<xsl:variable name="locationy" select="@y_axis"/>
<xsl:variable name="locationz" select="@z_axis"/>
<xsl:variable name="thisx" select="java:locationX($locationx,$locationy,
$locationz, $viewpoint_x, $viewpoint_y,
$viewpoint_z)"/>
<xsl:variable name="thisy" select="java:locationY($locationx,
$locationy, $locationz, $viewpoint_x, $viewpoint_y,
$viewpoint_z)"/>
</xsl:for-each>
```
Finally we pass new parameters and run the XSL transformation to create
the SVG file with a different viewpoint.
## Summary
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
SVG stands for Scalable Vector graphics. Meaning that it creates an image that will not lose image quality when moving or changing the size. Similar to Flash in functionality, neither is better than the other, they are however better in particular situations (some of which were listed earlier.) Can create both 2D and 3D images via SVG. Supported by W3C.
---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## Demos
The following table provides a sampling of SVG documents that
demonstrate varying degrees of functionality and complexity:
`<small>`{=html}Table 5: SVG Demos`</small>`{=html}
------------------------------ ------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------
Function URL Browser Compatibility
Basic <http://www.carto.net/papers/svg/samples/canvas.svg> All
Fills <http://www.carto.net/papers/svg/samples/fill.svg> All
HTML, JS, Java Servlet <http://www.adobe.com/svg/viewer/install/main.html> -- Then follow to Inspiration, Fluent Solutions/Adobe Theater demo Does not provide full functionality in Mozilla
HTML, JS, DOM <http://www.adobe.com/svg/viewer/install/main.html> -- Then follow to Inspiration, Chart and Graph demo Does not provide full functionality in Mozilla
PHP, MySQL <http://www.carto.net/papers/svg/samples/mysql_svg_php.shtml> All
HTML5, ANGULARJS, PostGreSQL <https://vectoriole.com/> -- Then use either of the demo logins All
------------------------------ ------------------------------------------------------------------------------------------------------------------------ ------------------------------------------------
The **Basic** demo demonstrates the effects of zooming, panning, and
anti-aliasing (high quality).
The **Fills** demo demonstrates the effects of colors and transparency.
The black circle is drag-able. Simply click and drag the circle within
the square to see the changes.
The **HTML, JS, Java Servlet** demo describes an interactive,
database-driven, seating diagram, where chairs represent available seats
for a performance. If the user moves the mouse pointer over a seat, it
changes color, and the seat detail (section, row, and seat number) and
pricing are displayed. On the client side of the application, SVG
renders the seating diagram and works with JavaScript to provide user
interactivity. The SVG application is integrated with a server-side
database, which maintains ticket and event availability information and
processes ticket purchases. The Java Servlet handles form submission and
updates the database with seat purchases.
The **HTML, JS, DOM** demo shows how SVG manages and displays data,
generating SVG code from data on the fly. Although this kind of
application can be written in a variety of different ways, SVG provides
client-side processing to maintain and display the data, reducing the
load on the server as well as overall latency. Using the DOM, developers
can build documents, navigate their structure, and add, modify, or
delete elements and content.
The **PHP, MySQL** demo shows the use of database driven SVG generation
utilizing MySQL. It randomly generates a map of a European country. Each
time you reload the page you will see a different country.
The **HTML5, ANGULARJS, PostGreSQL** demo shows how to create a SVG,
then integrate variable data into the SVG & spool a variable data pdf.
## `<span style="color:#8B4513">`{=html}Exercises`</span>`{=html}
```{=html}
<div style="color:#8B4513">
```
1. Download and install the Adobe SVG Viewer. Once the Adobe SVG Viewer
has been installed, go to this page to test that the install was
successful: <http://www.adobe.com/svg/viewer/install/svgtest.html>
- If your primary browser is Internet Explorer, you can download
version 3.0 which is fully supported by Adobe and can be
accessed at <http://www.adobe.com/svg/viewer/install/main.html>
- If your primary browser is Mozilla-based, you must download the
6.0 version at
<http://download.adobe.com/pub/adobe/magic/svgviewer/win/6.x/6.0x38363/en/SVGView.exe>
- After it has been installed you must copy the NPSVG6.dll and
NPSVG6.zip files to your browser\'s plug-ins folder. These
files are normally located in C:\\Program Files\\Common
Files\\Adobe\\SVG Viewer 6.0\\Plugins\\.
2. Create your own stand-alone SVG file to produce an image containing
a circle within a rectangle.
3. Create your own stand-alone SVG file. Use 3 circles and 1 path
element to create a yellow smiley face with black eyes and a black
mouth. Use a text element so that the message "Have a nice day!"
appears below the smiley face.
- **Hint:** Because `<path>`{=html} elements can be difficult to
write, here is a sample path you can utilize:
- `<path d="M 100, 120 C 100,120 140, 140 180,120" style="fill:none;stroke:black;stroke-width:1"/>`{=html}
```{=html}
</div>
```
### References
- Collection of free SVG vectors <http://www.easyvectors.com/>
- The Adobe SVG Zone <http://www.adobe.com/svg/>
- Cartographers on the Net <http://www.carto.net/>
- Digital Web Magazine -- Tutorial: SVG: The New Flash
<http://www.digital-web.com/tutorials/tutorial_2002-04.shtml>
- Learn SVG <http://www.learnsvg.com/>
- SVG authoring and web server configuration guidelines
<http://jwatt.org/svg/authoring/>
- Mozilla Plugin Support on Microsoft Windows
<http://plugindoc.mozdev.org/en-AU/windows1.html#AdobeSVG>
- W3C SVG Tutorial <http://www.w3schools.com/svg/default.asp>
- W3C Document Structure
<http://www.w3.org/TR/2002/CR-SVG11-20020430/struct.html>
- IBM developerWorks
<http://www-128.ibm.com/developerworks/edu/x-dw-xxslt3d-i.html>
- W3C Synchronized Multimedia <http://www.w3.org/AudioVideo/>
- Mozilla SVG Project <http://www.mozilla.org/projects/svg/>
- svg.startpagina.nl <http://svg.startpagina.nl/>
cs:SVG de:SVG
ja:SVG ka:SVG nl:Scalable
Vector Graphics
pl:SVG
[^1]: libsrsvg -- free, open source SVG rendering
library
[^2]: Barry Kauler blog
[^3]: 2D Apollonian gasket with four identical circles by Guillaume
JACQUENOT
ł
[^4]: W3C SVG 1.1 Recommendation:
\[//www.w3.org/TR/SVG/single-page.html#intro-NamespaceAndDTDIdentifiers
SVG Namespace, Public Identifier and System Identifier\], see also
W3C SVG 2 Editor's Draft:
\[//svgwg.org/svg2-draft/single-page.html#intro-Namespace SVG
namespace and DTD\] (06 February 2013)
[^5]: SVG authoring and web server configuration guidelines. *Jonathan
Watt* \[//jwatt.org/svg/authoring/#doctype-declaration Don\'t
include a DOCTYPE declaration\]
[^6]: Mozilla on SVG:
\[//developer.mozilla.org/en-US/docs/SVG/Namespaces_Crash_Course
Namespaces Crash Course\],
\[//developer.mozilla.org/en-US/docs/SVG/Tutorial/Getting_Started
Getting Started\]
[^7]: validator w3.org
|
# XML - Managing Data Exchange/DocBook
------------------------------------------------------------------------
## Learning objectives
Upon completion of this chapter, you will be able to
- Learn the basics of DocBook
- Create a DocBook document by using the DocBook XML DTD
- Convert a text document to a DocBook document
- Use XSL Stylesheets to transform a DocBook XML document to multiple
formats as HTML, PDF or presentation slides.
## Introduction
DocBook is general purpose XML and SGML vocabulary particularly well
suited to books, articles, and papers. It has a large, powerful and easy
to understand Document Type Definition (DTD), and its main structures
correspond to the general concept of what constitutes a book. DocBook is
a substantial subject that we can\'t exactly cover in a few pages. Thus,
for the purposes of this chapter, we will talk about creating a simple
DocBook document with major elements in the DocBook DTD and the details
of publishing the document in order to give you a feel about DocBook. If
you would like to study the subject further, we suggest you to have a
look at the references provided at the end of the chapter.
## What is DocBook?
- DocBook enables you to author and store document content in a
presentation-neutral form that captures the logical structure of the
content.
- It has an easy-to-understand and widely used DTD. The DocBook tags
are applied so that they have a certain \"common sense\" semantic
content, at least to English speakers.
- There are no official versions of the DocBook W3C XML Schema at this
time. The DocBook Technical Committee is planning to offer an
official Schema in the DocBook V5.0 time frame. The examples
provided in this chapter will use the current official DTD.
### DTD vs. Schema:
A DTD is the XML Document Type Definition contains or points to markup
declarations that provide a grammar for a class of documents. A Schema
is a set of shared vocabularies that allow machines to carry out rules
made by people. It provides a means for defining the structure, content
and semantics of XML documents. In summary, schemas are a richer and
more powerful means of describing information than DTDs.
`<small>`{=html}Table 1: Here is a simple XML document`</small>`{=html}
``` XML
<author>
<firstname>Rusen</firstname>
<lastname>Gul</lastname>
</author>
```
`<small>`{=html}Table 2: Here is the DTD for this
document`</small>`{=html}
``` XML
<!ELEMENT author(firstname, lastname)>
<!ELEMENT firstname(#PCDATA)>
<!ELEMENT lastname(#PCDATA)>
```
`<small>`{=html}Table 3: And here is the SCHEMA `</small>`{=html}
``` XML
<xs:element name="author">
<xs:complexType>
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:element>
```
### Output formats for DocBook
XSL (Extensible Style Language) stylesheets can transform DocBook XML
into the following formats:
- HTML
- HTML Help (for Windows Help)
- Java Help
- XHTML
- XSL Formatting Objects (FO)
- PDF
DSSSL (Document Style Semantics and Specification Language) stylesheets
can transform DocBook SGML into the following formats:
- HTML
- MIF
- RTF
- TeX
### A Brief History
DocBook was created around 1991 by HaL Computer Systems and O\'Reilly &
Associates. It was developed primarily for the purpose of holding the
results of troff conversion of UNIX documentation, so that the files
could be interchanged. Now it is maintained by OASIS. The official web
site for DocBook is <http://www.oasis-open.org/docbook/>
### DocBook is used for:
1. Books for print/trade publication. Many authors are using DocBook
for writing books of all kinds, in various print and online formats,
worldwide. Some examples include:
- Processing XML with
Java
- Learning
XML
- DocBook: The Definitive Guide
- Installing and Using
DocBook
- Dive into Python
2. Articles, theses and dissertations
3. Maintaining websites
4. Producing presentation slides, printed handouts, and whitepapers
5. Documentation for commercial software and hardware
### DocBook Tools
DocBook is officially available as a DTD for both XML and SGML. You can
download both the latest DocBook XML DTD and DocBook SGML DTD from the
official DocBook site at OASIS. The examples provided in this chapter
will use DocBook XML DTD. Some experimental DocBook schemas are
available at sourceforge.net. DocBook is supported by a number of
commercial and open source tools. Easily customizable and extensible
\"standard\" DocBookStylesheets are available from the
DocBookOpenRepository along with the other free open source tools. See
DocBookTools on the
DocBook Wiki for a more complete list of commercial and open source
tools.
#### Other Free Tools:
1. **XSLTProc:** One of the most known and fast processors. Available
at <http://xmlsoft.org/XSLT/>.
2. **Apache FOP:** XSL-FO implementation. Available at
<http://xmlgraphics.apache.org/fop/>.
3. **Xt:** One of original XSLT processors. Less frequently used now.
Available at www.jclark.com.
4. **DocBook2x:** Converts DocBook to man and Texinfo pages. Available
at Sourceforge.
5. **Refdb:** Creates reference databases and bibliographies from
DocBook. Available at Sourceforge.
#### Commercial Tools:
1. **Arbortext Epic:** Comprehensive suite of both editing and
processing tools. Available at Arbortext
website.
2. **RenderX XEP:** FO to PDF rendering engine. Available at RenderX
website.
3. **Antenna House XSL Formatter:** FO to PDF rendering engine.
Available at Antenna Housewebsite.
### SGML vs XML
The syntax of SGML and XML DTD is very similar but not identical. The
biggest difference between the DocBook DTD for SGML and the one for XML
is that the SGML DTD contains SGML exclusions in some content models.
**Example:**SGML DTD excludes `<footnote>`{=html} as a descendent of
`<footnote>`{=html}, because it doesn\'t make much practical sense to
have footnotes within footnotes. XML DTDs can\'t contain exclusions, so
if you\'re authoring using the DocBook XML DTD, it\'s possible to
produce documents containing some valid-but-not-logical markup like
footnotes within footnotes.
## Creating a DocBook Document
In order to get started, you will need:
- An XML editor. Download NetBeans IDE if
you haven\'t done so yet.
- The DocBook XML DTD. Although it is optional to use one, DTD\'s are
useful when one wants to validate a document to check that it
conforms to the DTD to which one claims it conforms. Hence, the
DocBook DTD can be used to validate that a purported DocBook
document. DocBook XML 4.2 is the current version of DocBook DTD.
Download at the official DocBook
website
- The DocBook XSL stylesheets are maintained primarily by Norman
Walsh. There are two sets of stylesheets: XSL and DSSSL. Download
the latest version XSL 1.65.1 at
Sourceforge.net
- An XSLT processor (covered in the further sections)
`<small>`{=html}Table 4: A simple DocBook Book,
\"book.xml\"`</small>`{=html}
``` XML
<?xml version="1.0"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
<book>
<bookinfo>
<title>XML – Managing Data Exchange</title>
<author>
<firstname>Rusen</firstname>
<surname>Gul</surname>
</author>
</bookinfo>
<chapter>
<title>Introduction</title>
<sect1>
<title>First Section</title>
<para>This is a paragraph.</para>
</sect1>
<sect1>...</sect1>
</chapter>
<chapter>...</chapter>
<chapter>...</chapter>
<chapter>...</chapter>
<appendix>...</appendix>
<appendix>...</appendix>
</book>
```
`<small>`{=html}Table 5: A simple DocBook article,
\"article.xml\"`</small>`{=html}
``` XML
<?xml version="1.0"?>
<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd">
<article>
<articleinfo>
<title>A Simple Approach To DocBook</title>
<author>
<firstname>Rusen</firstname>
<surname>Gul</surname>
</author>
</articleinfo>
<para>This is the introductory paragraph of my article.</para>
<sect1>
<title>First Section</title>
<para>This is a paragraph in the first section.</para>
<sect2>
<title>This is the title for section2.</title>
<para>This is a paragraph in section2.</para>
</sect2>
<sect2>...</sect2>
<sect2>...</sect2>
</sect1>
<sect1>This is a high level section</sect1>
<sect1>...</sect1>
<sect1>...</sect1>
</article>
```
Let's examine the details of a typical DocBook document. Standard header
to a DocBook XML file is a **DocType declaration**:
`<small>`{=html}Standard header`</small>`{=html}
`<!DOCTYPE name FORMALID "Owner//Keyword Description//Language">`
This tells the XML manipulation tools the DTD in use. Name is the name
of the root element in the document. **FORMALID** is replaced with
either **PUBLIC** or **SYSTEM** identifier or both. **PUBLIC**
identifies the DTD to which the document conforms. **SYSTEM** explicitly
states the location of the DTD used in the document by means of a
**URI** (Uniform Resource Indicator). **PUBLIC** identifiers are
optional in XML documents although **SYSTEM** Identifiers are mandatory
in the DOCTYPE declaration.
`<small>`{=html}Header example `</small>`{=html}
```{=html}
<?xml version="1.0"?>
```
`<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"`\
`"``http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd``">`
**Owner:** Oasis\
**Keyword Description:** DTD DocBook XML V4.2\
**Language:** EN - English
`<small>`{=html}**Caution!** If you are not online, you need to change
the URL system identifier to path where DTD is
installed:`</small>`{=html}
```{=html}
<?xml version="1.0"?>
```
`<!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"`\
`"/usr/share/sgml/docbook/xml-dtd-4.2/docbookx.dtd">`
## Breaking a Document into Physical Portions
Before getting started, here is a useful tip! For the purposes of
convenience and performance, you might consider breaking a document into
physical chunks and work on each chunk separately. If you have a book
that consists of three chapters and two appendixes, you might create a
file called *book.xml*, which looks like this:
`<small>`{=html}Table 6: A physically divided book, "dividedbook.xml"
`</small>`{=html}
``` XML
<?xml version="1.0"?>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V4.2//EN"
[<!ENTITY chap1 SYSTEM "chap1.xml">
<!ENTITY chap2 SYSTEM "chap2.xml">
<!ENTITY chap3 SYSTEM "chap3.xml">
<!ENTITY appa SYSTEM "appa.xml">
<!ENTITY appb SYSTEM "appb.xml">]
<book>
<title>A Physically Divided Book</title>
&chap1;
&chap2;
&chap3;
&appa;
&appb;
</book>
```
You can then write the chapters and appendixes conveniently in separate
files. This is why DocBook is well suited to large contents. Note that
these separate files do not and must not have document type
declarations.
For example, Chapter 1 might begin like this:
`<chapter id="ch1">`{=html}\
```{=html}
<title>
```
My First Chapter
```{=html}
</title>
```
```{=html}
<para>
```
My first paragraph.
```{=html}
</para>
```
...
`……………………………………………………………`
## Breaking a Document into Logical Portions
Here is a quick reference guide for DocBook Elements:
<http://www.docbook.org/tdg/en/html/ref-elements.html>
There are--literally--hundreds of DocBook elements. This is what makes
docBook very powerful. We will try to cover the major ones here and let
you review the rest on your own. Firstly, a classification; DocBook
Elements can be divided broadly into these categories:
Sets collection of books
--------------------------- ------------------------------------------
Books books
Divisions divide books into parts
Components divide books or divisions into chapters
Sections subdivide components
Meta-information Elements contain information about other elements
Block Elements occur at paragraph level
Inline Elements used to mark up running text
## Major DocBook Elements
### Set: A collection of books
*Set* is the very top of the DocBook structural hierarchy. There\'s
nothing that contains a *Set*.
**Some children elements:** Book, SetIndex, SetInfo, Subtitle, Title,
TitleAbbrev, ToC(table of contents).
**Reference page:**
<http://www.oreilly.com/catalog/docbook/chapter/book/set.html>
`<small>`{=html}Table 7: `<set>`{=html} element,
\"lordoftherings.xml\"`</small>`{=html}
``` XML
<!DOCTYPE set PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<set>
<title>Lord of the Rings</title>
<setinfo>
<author>J.R. Tolkien</author>
</setinfo>
<book><title>The Fellowship of the Ring</title> ... </book>
<book><title>The Two Towers</title> ... </book>
<book><title>Return of the King</title> ... </book>
<set>
```
### Book: A book
A *Book* is probably the most common top-level element in a document.
The DocBook definition of a book is very loose and general. It gives you
free rein by not imposing a strict ordering of elements.
**Some children elements:** Appendix, Article, Bibliography, BookInfo,
Chapter, Colophon, Dedication, Glossary, Index, LoT, Part, Preface,
Reference, SetIndex, Subtitle, Title, TitleAbbrev, ToC.
**Reference page:**
<http://www.oreilly.com/catalog/docbook/chapter/book/book.html>
``` XML
<small>Table 8: <book> element, "xmlbook.xml"</small>
<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<book>
<title>XML – Managing Data Exchange</title>
<titleabbrev>XML</titleabbrev>
<bookinfo>
<legalnotice><para>No notice is required.</para></legalnotice>
<author><firstname>Rusen</firstname><surname>Gul</surname></author>
</bookinfo>
<dedication>
<para>This book is dedicated to MIST 7700 class of 2004 at UGA.</para>
</dedication>
<preface>
<title>Forword</title>
<para>The book aims to fulfill the need for an introductory XML
textbook. It contains the basics of XML as well as several tools
using XML.</para>
</preface>
<chapter>
<title>Introduction</title>
<para>At least one chapter, reference, part, or article is required.</para>
</chapter>
<appendix>
<title>Optional Appendix</title>
<para>Appendixes are optional but handy.</para>
</appendix>
</book>
```
### Division: A collection of parts and references (optional)
*Division*s are the first hierarchical level below Book.
**Children elements:** Part (contain components), Reference (contain
RefEntrys)
### Components: Chapter-like elements of a Book or Part
These are Preface, Chapter, Appendix, Glossary, Bibliography, and
Article. Components generally contain block elements -or sections, and
some can contain navigational components and RefEntrys.
`<small>`{=html}Table 9: `<Bibliography>`{=html} element,
\"references.xml\"`</small>`{=html}
``` XML
<!DOCTYPE bibliography PUBLIC "-//OASIS//DTD DocBook 4.2//EN">
<bibliography>
<title>References</title>
<bibliomixed>
<bibliomset relation=article>
<surname>Watson</surname>
<firstname>Richard</firstname>.
<title role=article>Managing Global Communities </title>
</bibliomset>
<bibliomset relation=journal>
<title>The World Wide Web Journal</title>
<volumenum>2</volumenum>
<issuenum>1</issuenum>.
<publishername>O'Reilly & Associates, Inc.</publishername> and
<corpname>The World Wide Web Consortium</corpname>.
<pubdate>Winter, 1996</pubdate>
</bibliomset>.
</bibliomixed>
</bibliography>
```
### Sections: Several sectioning elements
**a. Sect1...Sect5 elements** - the most common sectioning elements that
can occur in most component-level elements. These numbered section
elements must be properly nested (Sect2s can only occur inside Sect1s,
Sect3s can only occur inside Sect2s, and so on).
**b. Section element** - an alternative to numbered sections Sections
are recursive, meaning that you can nest them to any depth desired.
**c. SimpleSect element** - a terminal section that can occur at any
level SimpleSect cannot have any other sectioning element nested within
it.
**d. BridgeHead element** - a section title without any containing
section
**e. RefSect1...RefSect3 elements** - numbered section elements in
RefEntrys **f. GlossDiv, BiblioDiv, and IndexDiv elements** - do not
nest
Please see Table 4 and Table 5 for examples.
**Reference page:**
<http://www.oreilly.com/catalog/docbook/chapter/book/section.html>
### Meta-Information Elements -- contain bibliographic information
All of the elements at the section level and above include a wrapper for
meta-information about the content. Examples of meta-wrappers: BookInfo,
ArticleInfo, ChapterInfo, PrefaceInfo, SetInfo, GlossaryInfo.
`<small>`{=html}Table 10: `<bookinfo>`{=html} element`</small>`{=html}
``` XML
<!DOCTYPE bookinfo PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<bookinfo>
<title>XML – Managing Data Exchange</title>
<authorgroup>
<author>
<firstname>Richard</firstname>
<surname>Watson</surname>
</author>
<author>
<firstname>Hendrik</firstname>
<surname>Fischer</surname>
</author>
<author>
<firstname>Rusen</firstname>
<surname>Gul</surname>
<affiliation>
<orgname>University of Georgia</orgname>
</affiliation>
</author>
</authorgroup>
<edition>Introduction to XML - Version 1.0 </edition>
<pubdate>1997</pubdate>
<copyright>
<year>1999</year>
<year>2000</year>
<year>2001</year>
<year>2002</year>
<year>2003</year>
<holder> O'Reilly & Associates, Inc. </holder>
</copyright>
<legalnotice>
<para>Permission to use, copy, modify and distribute the DocBook
DTD and its accompanying documentation for any purpose and without
fee is hereby granted in perpetuity, provided that the above
copyright notice and this paragraph appear in all copies.
</para>
</legalnotice>
</bookinfo>
```
#### Block vs. Inline Elements
There are two classes of paragraph-level elements: *block* and *inline*.
Block elements are usually presented with a paragraph break before and
after them. Most can contain other block elements, and many can contain
character data and inline elements. Examples of block elements are:
Paragraphs, lists, sidebars, tables, and block quotations.
Inline elements are generally represented without any obvious breaks.
The most common distinguishing mark of inline elements is a font change,
but inline elements may present no visual distinction at all. Inline
elements contain character data and possibly other inline elements, but
they never contain block elements. They are used to mark up data. Some
examples are: cross references, filenames, commands, options, subscripts
and superscripts, and glossary terms.
### Block Elements - paragraph-level elements
The block elements occur immediately below the component and sectioning
elements.
#### Lists
---------------------------------------- ---------------------------------------------------------------------------------------------------------------------------
`<b>`{=html}CalloutList`</b>`{=html} A list of marks, frequently numbered and typically on a graphic or verbatim environment and their descriptions.
`<b>`{=html}GlossList`</b>`{=html} A list of glossary terms and their definitions.
`<b>`{=html}ItemizedList`</b>`{=html} An unordered (bulleted) list.
`<b>`{=html}OrderedList`</b>`{=html} A numbered list.
`<b>`{=html}SegmentedList`</b>`{=html} A repeating set of named items. For example, a list of states and their capitals might be represented as a SegmentedList.
`<b>`{=html}SimpleList`</b>`{=html} An unadorned list of items.
`<b>`{=html}VariableList`</b>`{=html} A list of terms and definitions or descriptions.
---------------------------------------- ---------------------------------------------------------------------------------------------------------------------------
`<small>`{=html}Table 11:
```{=html}
<segmentedlist>
```
element, \"statecapital.xml\"`</small>`{=html}
``` XML
<!DOCTYPE para PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<para>The capitals of the states of the United States of America are:
<segmentedlist>
<title>State Capitals</title>
<segtitle>State</segtitle>
<segtitle>Capital</segtitle>
<seglistitem>
<seg>Georgia</seg>
<seg>Atlanta</seg>
</seglistitem>
<seglistitem>
<seg>Alaska</seg>
<seg>Juneau</seg>
</seglistitem>
<seglistitem>
<seg>Arkansas</seg>
<seg>Little Rock</seg>
</seglistitem>
</segmentedlist>
</para>
```
`<small>`{=html}Table 12: \"statecapital.xml\" output`</small>`{=html}
------------------------------------------------------------------------
The capitals of the states of the United States of America are:
**State Capitals**
**State:** Georgia
**Capital:** Atlanta
**State:** Alaska
**Capital:** Juneau
**State:** Arkansas
**Capital:** Little Rock
------------------------------------------------------------------------
``` XML
<small>Table 13: <orderedlist> element, "mashpotatoe.xml"</small>
<!DOCTYPE para PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<para>
<orderedlist numeration="upperroman">
<listitem>
<para>Preparation</para>
<orderedlist numeration="upperalpha">
<listitem><para>Chop tomatoes</para>
</listitem>
<listitem><para>Peel onions</para>
</listitem>
<listitem><para>Mash potatoes</para>
</listitem>
</orderedlist>
</listitem>
<listitem>
<para>Cooking</para>
<orderedlist numeration="upperalpha">
<listitem><para>Boil water</para>
</listitem>
<listitem><para>Put tomatoes and onions in </para></listitem>
<listitem><para>Blanch for 5 minutes</para>
</listitem>
</orderedlist>
</listitem>
</orderedlist>
</para>
```
`<small>`{=html}Table 14: \"mashpotatoe.xml\" output`</small>`{=html}
------------------------------------------------------------------------
I.Preparation\
A.Chop tomatoes\
B.Peel onions\
C.Mash potatoes\
II.Cooking\
A.Boil water\
B.Put tomatoes and onions in\
C.Blanch for 5 minutes\
\-\-\--
#### Admonitions
There are five types of *admonition*s: Caution, Important, Note, Tip,
and Warning.
``` XML
<small>Table 15: <caution> element, "caution.xml"</small>
<!DOCTYPE caution PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<caution>
<title>This is a caution</title>
<para>Be careful while opening the box!</para>
</caution>
```
#### Line-specific environments
*Line-specific environments* preserve whitespace and line breaks.
----------------------------------------- --------------------------------------------------------------------------------------
`<b>`{=html}Address`</b>`{=html} A real-world address, generally a postal address
`<b>`{=html}LiteralLayout`</b>`{=html} A block of text in which line breaks and white space are to be reproduced faithfully
`<b>`{=html}ProgramListing`</b>`{=html} A literal listing of all or part of a program
`<b>`{=html}Screen`</b>`{=html} Text that a user sees or might see on a computer screen
`<b>`{=html}ScreenShot`</b>`{=html} A representation of what the user sees or might see on a computer screen
`<b>`{=html}Synopsis`</b>`{=html} A general-purpose element for representing the syntax of commands or functions
----------------------------------------- --------------------------------------------------------------------------------------
`<small>`{=html}Table 16:
```{=html}
<literallayout>
```
element, \"If_by_Kipling.xml\"`</small>`{=html}
``` XML
<!DOCTYPE blockquote PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<blockquote>
<attribution>Rudyard Kipling,
<citetitle>If</citetitle>
</attribution>
<literallayout>
If you can force your heart and nerve and sinew
To serve your turn long after they are gone,
And so hold on when is nothing in you
Except the Will
which says to them:
Hold on!
</literallayout>
</blockquote>
```
#### Common block-level elements
*Common block-level elements* include Examples, figures, and tables. The
distinction between formal and informal elements is that formal elements
have titles while informal ones do not.
**Example, InformalExample**
`<small>`{=html}Table 17:
```{=html}
<example>
```
element`</small>`{=html}
``` XML
<!DOCTYPE example PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<example>
<title>Sample code</title>
<programlisting>print "Hello, world!"</programlisting>
</example>
```
**Figure, InformalFigure**
`<small>`{=html}Table 18:
```{=html}
<figure>
```
element`</small>`{=html}
``` XML
<!DOCTYPE figure PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<figure>
<title>Revenues for Q1</title>
<mediaobject>
<imageobject>
<imagedata fileref="q1revenue.jpg" format="JPG"/>
</imageobject>
</mediaobject>
</figure>
```
**Table, InformalTable**
`<small>`{=html}Table 19: \<table\> element`</small>`{=html}
``` XML
<!DOCTYPE table PUBLIC "-//OASIS//DTD DocBook V4.2//EN"><br>
<table frame="frametype">
<title>frame="frametype"</title>
<tgroup cols="1">
<thead>
<row>
<entry>row 1, cell 1</entry>
<entry>row 1, cell 2</entry>
<entry>row 1, cell 3</entry>
</row>
</thead>
<tbody>
<row>
<entry>row 2, cell 1</entry>
<entry>row 2, cell 2</entry>
<entry>row 3, cell 3</entry>
</row>
</tbody>
</tgroup>
</table>
```
#### Paragraphs
*Paragraphs* are Para, SimPara (simple paragraphs may not contain other
block-level elements), and FormalPara (formal paragraphs have titles).
Paragraphs are the most commonly used high-level elements that can
contain block elements such as itemizedlist and Mediaobject and can
contain almost all inline elements.
**Reference page:** <http://www.docbook.org/tdg/en/html/para.html>
`<small>`{=html}Table 20:
```{=html}
<para>
```
element, \"Nietzsche.xml\"`</small>`{=html}
``` XML
<!DOCTYPE para PUBLIC "-//OASIS//DTD DocBook V4.2//EN">
<para>
<quote>Behold the superfluous. They are always sick. They vomit their gall and call it a newspaper.</quote>
-Friedrich Wilhelm Nietzsche,
<citetitle>Twilight of the Idols</citetitle>
</para>
```
#### Equations
Equation and InformalEquation (without titles)
`<small>`{=html}Table 21:
```{=html}
<informalequation>
```
element inside a
```{=html}
<para>
```
element`</small>`{=html}
``` XML
<!DOCTYPE para PUBLIC "-//OASIS//DTD DocBook V3.1//EN"> <para>
The equation
<informalequation>
<alt>e^(pi*i) + 1 = 0</alt>
<graphic fileref="figures/epi10"></graphic>
</informalequation>
is delightful because it joins together five of the most important mathematical constants.
</para>
```
#### Graphics
InlineGraphic, MediaObject, InlineMediaObject
These elements may contain video, audio, image, and text data. A single
media object can contain several alternative forms from which the
presentation system can select the most appropriate object.
Please see Table 18 for example.
### Inline Elements -- used to mark up running text
In published documents, inline elements often cause a font change or
other small change, but they do not cause line or paragraph breaks.
```{=html}
<table border="1" cellspacing="0" cellpadding="2">
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Abbrev `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
An abbreviation, especially one followed by a period.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Acronym`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
An often pronounceable word made from the initial (or selected) letters
of a name or phrase.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Emphasis`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Emphasized text.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Footnote `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A footnote. The location of the Footnote element identifies the location
of the first reference to the footnote. Additional references to the
same footnote can be inserted with FootnoteRef.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Phrase`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A span of text.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Quote`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
An inline quotation.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Trademark`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A trademark.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Citation`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
An inline bibliographic reference to another published work.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}GlossTerm`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A glossary term.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Link`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A hypertext link.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}ULink `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A link that addresses its target by means of a URL (Uniform Resource
Locator).
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}XRef`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A cross reference to another part of the document.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}ForeignPhrase`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A word or phrase in a language other than the primary language of the
document.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}ComputerOutput `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Data, generally text, displayed or presented by a computer.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Markup `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A string of formatting markup in text that is to be represented
literally.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Replaceable`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Content that may or must be replaced by the user.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}UserInput `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Data entered by the user.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Literal`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Inline text that is some literal value.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Command `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The name of an executable program or other software command.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}MsgText `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The actual text of a message component in a message set.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Optional `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Optional information.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Email`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
An email address.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Database `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The name of a database, or part of a database.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Filename`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The name of a file.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Token `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
A unit of information.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Type`</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The classification of a value.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html}Application `</b>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The name of a software program.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
`<b>`{=html}Entities for Special Characters`</b>`{=html}
The following entities are provided for special characters:
```{=html}
<table border="1" cellspacing="0" cellpadding="2">
```
```{=html}
<tr>
```
```{=html}
<td align="left" bgcolor="#ffff66">
```
`<span style="color:black;">`{=html}Character`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td align="left" bgcolor="#ffff66">
```
`<span style="color:black;">`{=html}Entity`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
\<
```{=html}
</td>
```
```{=html}
<td>
```
& lt;
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
\>
```{=html}
</td>
```
```{=html}
<td>
```
& gt;
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
&
```{=html}
</td>
```
```{=html}
<td>
```
& amp;
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
\"
```{=html}
</td>
```
```{=html}
<td>
```
& quot;
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
\'
```{=html}
</td>
```
```{=html}
<td>
```
\'
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## Publishing a DocBook Document
**DSSSL vs XSL Stylesheets:**
*Document Style Semantics and Specification Language (DSSSL)* is a
stylesheet language for both print and online rendering. It is mainly
intended to work with SGML.
*Extensible Stylesheet Language (XSL)* is a language for expressing
stylesheets written in XML. It includes the formatting object language,
but refers to separate documents for the transformation language and the
path language. In this chapter, we will use XSL Stylesheets because
they're more powerful, you are already familiar with them, and they are
intended to work with XML.
### Step 1: Get the Standard StyleSheets
DocBook strictly separates the content and appearance of a document. A
DocBook document only explains the semantics of the document, not its
formatting or appearance. In order to publish your DocBook Document, you
will need to use a set of DSSSL or XSL Stylesheets describing the
formatting and an XSL processor.
If you're thinking that it would be a lot of work to write your own XSL
stylesheets, you're right. The good news is that you don't need to.
There are a large number of freely available standard XSL stylesheets
for DocBook maintained primarily by Norman Walsh.
Make sure that you download the latest version of these stylesheets at
Sourceforge.net - Stylesheets
Repository.
The stylesheet distribution consists of a collection of modular XSL
files that are assembled into several complete XSL stylesheets. There is
a stylesheet for generating a single HTML file, and one for generating
multiple smaller HTML files from a single DocBook document. There are
stylesheets for print output, XHTML output, HTML Help output, and
JavaHelp output. Since there are XSL processors for all major computer
types, you can use DocBook on Unix, Linux, Windows, and Macintosh
computers. By using these default stylesheets installed on your system,
it is quite easy to create customized stylesheets. But don't forget to
note that the common approach to customize the stylesheets is creating a
customization layer rather than editing them directly.
### Step 2: Download an XSLT processor
To publish HTML from your XML documents, you will need an XSLT engine.
To print, you need an XSLT engine to produce formatting objects (FO),
which then must be processed with an FO engine to produce PostScript or
PDF output. A variety of XSLT engines are available. Here\'s a list of
some free/open-source ones you might consider. Note that xsltproc and
Saxon are currently the only recommended XSLT engines for use with
DocBook.
#### XSLT Engines
1. **Xsltproc:** A free processor written in C, available as part of
the open source libxml2 library from the Gnome development project.
It is considered the fastest of the processors, and is highly
conformant to the specification. Download at
<http://xmlsoft.org/XSLT/>
2. **Saxon:** A free processor written in Java, that can be run on any
operating system with a modern Java interpreter. It uses the Aelfred
XML parser internally, which has some bugs, so many people
substitute the Xerces parser. Download at
<http://saxon.sourceforge.net/>
3. **Xalan:** Xalan is part of the Apache XML Project. It has versions
written in both Java and C++, both of them free. The Java version is
highly portable and more fully developed. Generally Xalan is used
with the Xerces XML parser (Java or C++), also available from the
Apache XML Project. Download at <http://xml.apache.org/>
Your choice of an XSLT engine may depend a lot on the environment in
which you\'ll be running the engine. Many DocBook users who need or want
a non-Java application use xsltproc. It\'s very fast and the developers
respond very quickly to bug reports and questions. But one current
limitation xsltproc has is that it doesn\'t yet support Norm Walsh\'s
DocBook-specific XSLT extension functions.
Saxon is the most popular one for use in a Java environment. It also
supports Norm Walsh\'s DocBook-specific XSLT extension functions.
*NetBeans IDE*, the XML editor we've been using for other chapters'
exercises, has a built-in XSLT processor using the XALAN parser by
default. NetBeans IDE not only lets you validate your XML documents but
also does XSL transformations right there in the IDE. It will work for
this chapter's purpose well enough. It doesn't provide any XSLT
debugging though, so you might want to get yourself a decent XSL IDE
(e.g.,XML Spy or Xcelerator) for serious XSLT work.
#### FO Engines
For generating print/PDF output from FO files, there are two
free/open-source FO engines:
1. **PassiveTeX:** available at
<http://www.tei-c.org.uk/Software/passivetex/index.xml.ID=body.1_div.1>.
Download and installation information at
<http://www.tei-c.org.uk/Software/passivetex/index.xml.ID=body.1_div.3>.
2. **FOP:** a Java-based processor from the Apache XML Project,
available at <http://xml.apache.org/fop/>
### Step 3: Customize the XSL stylesheets
#### Output to HTML
- The main strength of standard stylesheets is that they are easily
customizable.
- Parameters found in params.xsl
- Call your customization layer instead of the standard stylesheet
`<small>`{=html}Table 22: A customized XSL stylesheet,
\"myxsl1.xsl\"`</small>`{=html}
``` XML
<?xml version="1.0"?>
<!-- Customization layer -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<nowiki><!-- Use 'chunk.xsl' in line below to chunk files. --></nowiki>
<xsl:import href="/usr/share/sgml/docbook/docbook-xsl-1.51.1/html/docbook.xsl"/>
<xsl:param name="chapter.autolabel" select="1"/>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"
doc:type="boolean"/>
<!-- Insert more parameters here. -->
</xsl:stylesheet>
```
- Beyond setting parameters, you can modify XSLT \"templates\" to
override default behavior
- You need at least a minimal knowledge of XSLT
`<small>`{=html}Table 23: A customized XSL stylesheet,
\"myxsl2.xsl\"`</small>`{=html}
``` XML
<xsl:template match="emphasis">
<xsl:choose>
<xsl:when test="(@role='strong') or (@role='bold')">
<xsl:call-template name="inline.boldseq"/>
</xsl:when>
<xsl:otherwise>
<xsl:call-template name="inline.italicseq"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
```
#### Output to PDF
It generally requires a two-stage process:
1. Generation of FO from XML
2. Generation of PDF from FO
`<small>`{=html}Table 24: An XSL stylesheet to generate FO,
\"myxsl3.xsl\"`</small>`{=html}
`xsltproc -o sample.fo $DB/fo/docbook.xsl sample.xml`\
`fop.sh -fo sample.fo -pdf sample.pdf`
#### Extensions
**a. Slides Doctype**
- Creation of presentation slides from DocBook XML
- You can create HTML (with or without frames) and FO
- Uses DocBook elements within a specific hierarchical framework
- Downloadable from DocBook Open Repository at SourceForge
`<small>`{=html}Table 25: \"slides.xml\"`</small>`{=html}
``` XML
<!DOCTYPE slides SYSTEM "/usr/share/sgml/docbook/xsl-slides-1.1/slides.dtd">
<slides>
<slidesinfo>
<title>A Simple Approach to DocBook</title>
</slidesinfo>
<foil>
<title>My first slide</title>
<itemizedlist>
<listitem><para>...</para></listitem>
<listitem><para>...</para></listitem>
<listitem><para>...</para></listitem>
</itemizedlist>
</foil>
<foil>
<title>My second slide</title>
<para>... </para>
</foil>
</slides>
```
`<b>`{=html}b. Website Doctype`</b>`{=html}
- Creation of web sites from a collection of DocBook XML files
- Uses most DocBook elements within specific framework. It has
separate files that control page navigation and hierarchy.
- Downloadable from DocBook Open Repository at SourceForge.
`<small>`{=html}Table 26: \"website.xml\"`</small>`{=html}
``` XML
<!DOCTYPE webpage SYSTEM "../website.dtd" [
<!NOTATION XML SYSTEM "xml">
<!ENTITY test1a SYSTEM "test1a.xml" NDATA XML>
<!ENTITY test3 SYSTEM "test3.xml" NDATA XML>
<!ENTITY about.xml SYSTEM "about.xml" NDATA XML>]>
<webpage id="home">
<config param="desc" value="The Test Home Page"/>
<config param="rcsdate" value="$Date: 2001/11/08 20:44:20 $"/>
<config param="footer" value="about.html" altval="About..."/>
<head>
<title>Welcome to Website</title>
<summary>Introduction</summary>
<keywords>Rusen Gul, XSL, XML, DocBook, Website</keywords>
</head>
<para> This website demonstrates the DocBook.</para>
<webtoc/>
<section>
<title>What is a Website?</title>
<para>A website is a collection of pages organized, for the purposes of navigation, into one or more hierarchies. In Website, each page is a separate XML document authored according to the Website DTD, a customization of <ulink url="http://www.oasis-open.org/docbook/">DocBook</ulink>.</para>
</section>
</webpage>
```
## Why use DocBook?
This certainly looks like too much work, doesn't it? You're not wrong.
Why do we bother to use DocBook then?
- It is portable! A document written in DocBook markup can be
converted into HTML, PostScript, PDF, RTF, DVI, plain ASCII text
easily and quickly without any expensive tools.
```{=html}
<!-- -->
```
- It is flexible! It enables output to multiple formats, including
HTML, PDF, Slides, and many others.
```{=html}
<!-- -->
```
- It separates the content from format! DocBook is only concerned with
the structure of a document. It frees the author from worrying about
the formatting and layout of a document.
```{=html}
<!-- -->
```
- It is easy to understand! Most of DocBook elements are self
explanatory.
```{=html}
<!-- -->
```
- It can handle large quantities of content. You can physically divide
the document into different files and work on them separately and
conveniently.
```{=html}
<!-- -->
```
- It is free! There a lot of freely available open source tools used
to work with DocBook.
DocBook is well suited to any collection of technical documentation that
is regularly maintained and published. Multiple authors can contribute
to a single document, and their content can easily be merged because all
the authors are using a highly structured, standard markup language.
Just one little point to keep in mind; because the formatting for
DocBook documents is strictly accomplished by stylesheets, DocBook is
not well matched to highly designed layout-driven content like
magazines.
Setting up a DocBook system will certainly take some time and effort.
The payoff will be an efficient, flexible, and inexpensive publishing
system that is iterative and that can grow with your needs. Therefore,
it is worth the effort!
## DocBook Filters - Reading and Writing DocBook XML Using OpenOffice.org
The goal of the project is to use OpenOffice.org as a WYSIWYG editor of
XML content to edit structured documents using styles. When exported,
these styles are then transformed to XML tags. This section shows you
how to enable and use DocBook filters. Below are some links to
stylesheets that can be download to use the latest transformations.
### Enabling the DocBook XSLT\'s in OpenOffice.org 1.1 Beta 2/RC
There are three different ways to enable the DocBook filters.
1. Download the DocBook XSLT Stylesheets and OpenOffice.org Style
Template
- Using this method will make certain that the most recent
stylesheets and OpenOffice.org style template will be used for
import and export. It is required to download the following to
import, export and modify DocBook documents in OpenOffice.org:
- The relevant XSLT stylesheets for the XML transformations (All
available
here)
- An OpenOffice.org style template that contains custom styles
corresponding to DocBook tags (Available
here)
The most recent stylesheets support the import and export of DocBook
documents with article or chapter as the top-level tag. The different
stylesheets required for each of these operation are listed below:
- Stylesheets required for import Article
docbooktosoffheadings.xsl
- Stylesheets required for import Chapter
docbooktosoffheadings.xsl
- Stylesheets required for export Article
sofftodocbookheadings_article.xsl
- Stylesheets required for export Chapter
sofftodocbookheadings_chapter.xsl
OpenOffice.org Template required for Article and Chapter documents:
- DocBookTemplate.stw
Creating a new DocBook filter
- Go to Tools -\> XML Filter Settings\...
- Set Filter Name and Name of File Type to DocBook (Chapter)
- Go to the Transformation tab
- Set DocType to `<chapter>`{=html}
- For XSLT for Export browse to the chapter export stylesheet
(docbooktosoffheadings.xsl).
- For XSLT for Import browse to the chapter import stylesheet
(sofftodocbookheadings_chapter.xsl).
- For Template for Import browse to the style template
(DocBookTemplate.stw).
- Click OK and close the XSLT Filter Setting dialog
To create a DocBook Article filter, the above steps can be repeated with
article replacing chapter
1. Download the DocBook XSLT Jar Packages for Article or Chapter
This method is more convenient, however there is no guarantee that the
most recent stylesheets and OpenOffice.org template will be used.
1. Download the DocBook UNO component for Article only
The DocBook UNO component adds filter support for the retention of
unresolved XML entities.
- Download the DocBookFilter
- Unzip it to the `<OOo install Dir>`{=html}/
- Run pkgchk in the `<OOo install Dir>`{=html}/program dir
- The DocBook Article filter will now import DocBook unresolved
entities as OpenOffice.org set variables
### How to Import a DocBook document
A DocBook article or chapter document can now be opened using the File
-\> Open dialog.
- Go to File -\> Open\...
- Browse to the DocBook document.
- Click OK
The DocBook XSLT filter should automatically determine the root element
of the document and import it with the matching XSLT filter.
Alternatively, it is possible to browse manually to the desired DocBook
filter in the File Type combo-box in the File -\> Open dialog.
### How to Export a DocBook document
The DocBook document can also be exported using the File -\> Save As
dialog.
- Go to File -\> Save As\...
- Browse to the location where the document is to be saved
- Click Save
Again, the DocBook XSLT filter should automatically determine the file
type and export with the matching XSLT filter. Alternatively, it is
possible to browse manually to the desired DocBook filter in the File
Type combo-box in the File -\> Save As dialog.
### Using OpenOffice.org Headings and Styles for different DocBook tags
Using OpenOffice.org styles to represent DocBook tags The style template
supplies all of the custom styles that are currently supported. Once a
DocBook document has been imported to OpenOffice.org, the available
DocBook specific styles can be viewed using the Stylist. On import, each
of the supported DocBook tags will be mapped to formatted OpenOffice.org
content. Similarly, to modify the imported DocBook document,
OpenOffice.org text styles can be used to represent the DocBook tags
marking-up the text. NOTE: A new DocBook document can be created in
OpenOffice.org by opening the DocBookTemplate.stw. The document can then
be saved as a DocBook document, and the new content will be represented
as DocBook mark-up. How to create new DocBook content:
- Press F11 to display the Stylist
- Select Custom Styles in the Stylist combo-box
- Click the Character Styles icon (second from left on the Stylist)
- Double-click the SubScript style
- Enter text in the OpenOffice.org document
- On exporting as DocBook, the text formatted as the SubScript custom
style will be marked-up with the DocBook tag `<subscript>`{=html}
How to create DocBook sections: Initially the DocBook project used
OpenOffice.org sections to enforce the nesting of DocBook sections.
Feedback has shown that authors wish to use the common word processing
styles such as Heading1, Heading2, etc. The following instructions
describe how to create a `<sect1>`{=html} that contains a
`<sect2>`{=html}
- Press F11 to display the Stylist
- Select All Styles in the Stylist combo-box
- Click the Paragraph Styles icon (first in the left on the Stylist)
- Double-click the Heading 1 style
- Enter the text to be the `<sect1>`{=html} title
- All the text below this heading will now be the content of the
DocBook `<sect1>`{=html}
- Enter other DocBook styles, tables, etc.
- Enter other DocBook styles, tables, etc. to be included in
`<sect1>`{=html}
1. Double-click the Heading 2 style
2. Enter the text to be the `<sect2>`{=html} title
3. All the text below this heading will now be the content of the
DocBook `<sect2>`{=html}
4. Enter other DocBook styles, tables, etc. to be included in
`<sect2>`{=html}
- This nesting of DocBook sect\'s using OpenOffice headings can go as
far as `<sect4>`{=html} / Heading 4
Navigating through the document: If you wish to see how DocBook sections
are nested as OpenOffice.org headings, use the F5 key to Display the
Navigator window. Expand the headings tag, to display the layout of the
headings within the document. You can skip to the start of a given
DocBook section/OpenOffice.org heading, by double-clicking on it.
## Exercises
```{=html}
<div style="color:#8b4513;">
```
1. Download the latest DocBook DTD at
<http://www.oasis-open.org/docbook/xml/>. Convert the Learning
Objectives part of Chapter 2 of this textbook into a DocBook
document. Check that it is well-formed and valid.
2. Download the DocBook XSL Stylesheets at
Sourceforge.net.
Transform the DocBook document you created in the first exercise
into an HTML file by using the *docbook.xsl* stylesheet in the
*HTML* folder.
```{=html}
</div>
```
## References and Useful Links
1. DocBook Official Website
2. DocBook: The Definitive Guide, by Norman Walsh and Leonard Muellner,
published by O\'Reilly & Associates, October 1999
<http://www.docbook.org/>
3. Sourceforge - DocBook Open
Repository
4. Installing and Using DocBook - Copyright 2002, The University Of
Birmingham
5. Using the DocBook XSL Stylesheets -
<http://www.sagehill.net/docbookxsl/index.html>
6. Setting Up A Free XML/SGML DocBook Editing Suite For Windows And
Unix
7. <http://lists.oasis-open.org/archives/docbook-apps/>
8. <http://www.dulug.duke.edu/~mark/docbookmarks/>
9. <http://www.linuxdoc.org/LDP/LDP-Author-Guide/>
10. <http://www.nwalsh.com/docs/>
11. <http://www.e-smith.org/docs/docprocess.html>
12. <http://www.lodestar2.com/people/dyork/talks/docbook/>
13. DocBook mailing list:
mailto:[email protected]
14. <http://xml.openoffice.org/xmerge/docbook/>
|
# XML - Managing Data Exchange/SMIL
`<b>`{=html}Learning objectives`</b>`{=html}
Upon completion of this chapter, you will be able to
- Understand SMIL fundamentals.
- Understand how and why SMIL is used.
- Locate and use SMIL technical specifications, tutorials and open
source SMIL tools.
- Create simple SMIL markup.
- Watch your SMIL file come to life in a SMIL viewer.
## Introduction
With the explosion of the late 90\'s popularity of the internet, The
World Wide Web Consortium (W3C) saw the need to extend the capabilities
of the web with respect to information structure and media presentation.
This is how they arrived at XML, the extensible language for describing
information structure. Furthermore, SMIL is built upon XML: it is a
specialized language to describe the presentation of media objects.
Since the W3C (and everyone else) doesn\'t know what media types will be
around in the future (virtual environments, brainwave-synch experiences,
psychic/holographic/video), XML was an appropriate choice in designing
SMIL to be extended to support these media.
In order to integrate this technology with HTML and extend the
application of media in HTML, the W3C decided to make a push towards
modularizing these languages or protocols. SMIL is one of many modular
languages which \'plug-in\' to the larger framework of XML.
### What is SMIL?
SMIL (pronounced \"smile\") is an acronym for Synchronized Multimedia
Integration Language. It is thought of as an open-standard version of
PowerPoint for the internet. SMIL is an XML-based language, similar in
appearance to HTML, that allows for the authoring of interactive
audiovisual presentations. SMIL enables the streaming of audio and video
with images, text or other media types. It is a language describing the
temporal and spacial placement of one or more media objects. Although
SMIL can be written with a simple text editor, hand-writing SMIL
documents can be a time-consuming and complicated endeavor. Therefore it
is better to use a tool for generating complicated SMIL documents.
### World Wide Web Consortium (W3C) SYMM group
Since November 1997, the W3C SYMM group has been
developing the SMIL language. It finalized SMIL 1.0 in June of 1998 and
SMIL 2.0 in August of 2001.
### Why SMIL?
Although plug-ins and media players have the ability to show many
different types of media with varying support for interaction, only SMIL
offers the ability to define the presentation in the form of text as a
script. This feature could be called media composition. This is a
powerful ability when you think about it: text presentations can be
generated from other applications. Also, SMIL offers accessibility
options and powerful features not
present in these media players.
- Macromedia products such as *Flash*, which require a plug-in to view
flash inside a web page.
- RealAudio\'s *Realplayer*
- Microsoft\'s *PowerPoint*
- OpenOffice.org\'s *Impress*
- Apple\'s *Quicktime*
- Microsoft has already created a proprietary alternative to SMIL. It
is called Microsoft\'s Synchronized Accessible Media Interchange
(SAMI), which
plays ASX files through Windows Media Player (WiMP).
Given that SMIL is extensible, the SMIL language has the ability to show
many of proprietary objects which are used by the above players. SMIL
was designed to be the overarching language for describing the
presentation of all media, all layouts and interactive controls.
Therefore, SMIL is not a substitute for flash, mpeg-4, or HTML. Rather,
it is a new standard for describing and using all of these.
### SMIL History
SMIL is still being developed. Currently, attempts are being made to
make SMIL easier to use in web browsers. Since SMIL is XML, the W3C
developed the latest standard as an addendum to the hybrid of XML and
HTML (XHTML). The following is an outline of the history of SMIL.
- The SMIL 1.0 specification defined the layout and time sequence of
multimedia elements.
- The HTML+TIME specification introduced Timing, Linking, Media, and
Content controls to HTML elements.
- The SMIL 2.0 specification brought interactivity (i.e.: HTML+TIME)
such as media linking and controls.
- BHTML proposal included transitions to be used in SMIL 2.0
- Finally, the XHTML+SMIL specification extends SMIL 2.0 capabilities
to XHTML elements.
When fully realized and implemented in the latest web browsers,
XHTML+SMIL will be able to define how media elements can be controlled.
HTML supports only static images and links. Web browsers use plug-ins to
show videos and other media objects, so the control and interaction of
the objects is left to the implementation of the plug-in. With
XHTML+SMIL, the supported objects can be placed, moved or displayed
according to a time-frame, interacted with using custom controls, and
linked to other media objects, web pages or presentations. And since XML
is extensible, support for more media objects is on the horizon. This
technology has the potential to make the WWW far more interactive,
allowing presenters far more control over presentations.
The current SMIL 2.0 is comprehensive and fairly complete. It is divided
into modules which describe different aspects of the presentation. For
example, there is a structure module to describe the structure of the
SMIL document itself, and there is a metadata module for describing what
the SMIL document is all about. Modularity is useful for extending the
SMIL schemas on a module-to-module basis when necessary, without causing
unwanted interactions with the elements in other modules.
------------------------------------------------------------------------
## Implementing SMIL
### Common SMIL implementations
- Internet or Intranet presentations.
- Slide show presentations.
- Presentations which link to other SMIL files.
- Presentations which have Control buttons (stop, start, next, \...)
- Defining sequences and duration of multimedia elements.
- Defining position and visibility of multimedia elements.
- Displaying multiple media types such as audio, video, text
- Displaying multiple files at the same time.
- Displaying files from multiple web servers.
Currently, SMIL\'s most widespread usage is with MMS. MMS (Multimedia
Messaging System) is a mobile device technology that is used as an
envelope for sending multimedia messages to cellphones. SMIL content is
placed inside the MMS message along with any associated media binaries.
In this context, MMS is a kind of transport mechanism for SMIL.
### SMIL files and MIME Types
- SMIL files have the extension \*.smil (but can also have \*.sml,
\*.smi)
- SMIL files contain tags and content necessary for showing a
presentation. This includes the layout of multimedia elements, the
timeline for the elements and the source for the multimedia files.
In order for a MIME user-agent to recognize SMIL 2.0 files, the
user-agent needs to be defined:
- application/smil \[deprecated\]
- application/smil+xml \[current MIME type\]
- application/xhtml+smil \[MIME type for embedding smil in XHTML\]
When adding this new mime-type to a web browser, the definition will
need to include the \'smil\' extension.
### SMIL Schema
The following hyperlink will direct you to the SMIL 2.0 Schemas,
provided by the W3C.org. The main schema is a general description of
SMIL 2.0 modules. It is followed by each module\'s schema. The main
schema contains the include statements for all of the module\'s schemas.
W3C.Org\'s SMIL Schema
description
### SMIL Namespace Declarations
SMIL 2.0 files need to have the following namespace declaration in the
beginning `<smil>`{=html} tag:
`<small>`{=html}SMIL 2.0 namespace`</small>`{=html}
+---------------+-----------------------------------------------------------+
| <nowiki> | <nowiki> |
| 1 | <smil xmlns="http://www.w3.org/2001/SMIL20/Language"> |
| </nowiki> | </nowiki> |
+---------------+-----------------------------------------------------------+
SMIL 1.0 files have the following namespace declaration:
`<small>`{=html}SMIL 1.0 namespace`</small>`{=html}
+---------------+--------------------------------------------------+
| <nowiki> | <nowiki> |
| 1 | <smil xmlns="http://www.w3.org/TR/REC-smil"> |
| </nowiki> | </nowiki> |
+---------------+--------------------------------------------------+
If no default namespace is declared within the
<nowiki><smil></nowiki>
root element, the document will be processed as SMIL 1.0.
------------------------------------------------------------------------
## SMIL Syntax
### Guidelines and Rules
SMIL documents look a lot like HTML. SMIL files need to be written
according to the following rules:
- SMIL documents must follow the *XML rules of well-formedness*.
- SMIL tags are *case sensitive*.
- All SMIL tags are written with *lowercase letters*.
- SMIL documents *must* start with a `<smil>`{=html} tag and end with
a `</smil>`{=html} closing tag.
- SMIL documents *must* contain a
```{=html}
<body>
```
tag for storing the contents of the presentation.
- SMIL documents can have a
```{=html}
<head>
```
element (like HTML) for storing metadata information about the
document itself, as well as presentation layout information.
### SMIL template
`<small>`{=html}SMIL 1.0 template`</small>`{=html}
+---------------+----------------------+
| <nowiki> | <nowiki> |
| 1 | <smil> |
| 2 | <head> |
| 3 | <layout> |
| 4 | ... |
| 5 | </layout> |
| 6 | </head> |
| 7 | |
| 8 | <body> |
| 9 | ... |
| 10 | </body> |
| 11 | </smil></nowiki> |
| </nowiki> | |
+---------------+----------------------+
### A Simple SMIL
`<small>`{=html}Abbreviated SMIL markup`</small>`{=html}
``` XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<smil xmlns="http://www.w3.org/SMIL20/Language">
<head>
<!-- The layout section defines regions in which to place content -->
<layout>
...
</layout>
<!-- Transitions defined in head act on content defined in body -->
<transition id="fade" type="fade" dur="1s"/>
<transition id="push" type="pushWipe" dur="0.5s"/>
</head>
<!-- The body section defines the content to be used and how it will be displayed -->
<body>
<par>
<img src="imagefile.jpg" transIn="fade"/>
<video src="soundfile.aif" transOut="push"/>
</par>
</body>
</smil>
```
### An example SMIL
`<small>`{=html}Example SMIL which has in-line text and an
image`</small>`{=html}
``` XML
<smil xmlns="http://www.w3.org/2001/SMIL20/Language">
<head>
<layout>
<root-layout width="320" height="240"/>
<region id="text1_region" left="0" top="0" width="160" height="120"/>
<region id="text2_region" left="160" top="120" width="160" height="120"/>
<region id="text3_region" left="80" top="60" width="160" height="120"/>
<region id="image_region" left="0" top="0" width="320" height="240"/>
</layout>
</head>
<body>
<seq>
<text src="data:text/plain,First%20Slide" region="text1_region" dur="2s"/>
<text src="data:text/plain,Second%20Slide" region="text2_region" dur="3s"/>
<text src="data:text/plain,Third%20Slide" region="text3_region" dur="3s"/>
<img src="sample_jpg.jpg" region="image_region" dur="3s"/>
</seq>
</body>
</smil>
```
Note that when using in-line text instead of referring to separate
plain-text files as the text source, you will have to encode the text
for any non-alphanumeric characters. This example uses \'%20\' in lines
{13,14,15} as a space character. Also note that in line {13} the source
for the text content begins with \'<data:text/plain>\'. In SMIL 2.0 this
is the default mime-type for text sources, so specifying it here is
optional. In SMIL 1.0, however, this would have to be specified in order
to use inline text.
## SMIL 2.0 Modules
SMIL 2.0 divides the language description by functionality into ten
modules. Each module contains elements to describe structure, content,
actions or attributes. The following 10 modules are associated with the
SMIL 2.0 namespace.
` 1. Timing `\
` 2. Time Manipulations`\
` 3. Animation`\
` 4. Content Control`\
` 5. Layout`\
` 6. Linking`\
` 7. Media Objects `\
` 8. Metainformation `\
` 9. Structure `\
` 10. Transitions`
The **timing** module provides a framework of elements to decide whether
elements appear concurrently, in sequence, or out of order and called by
interactive events such as clicking on a hyperlink.
The **time manipulations** module provides the ability to associate
media objects with time-related information such the as length of time a
media object should be displayed, and a description of the timeline used
as a frame of reference for the timing module.
The **animation** module allows media objects to be placed on a timeline
defined by the time manipulations module.
The **content control** module allows for choices of which content is
played, depending on such things as language and playback capabilities,
using tags such as **switch** present a test of the system\'s
capabilities.
The **layout** module contains elements that describe the spacial
placement of media objects in the presentation.
The **linking** module describes hyperlinks and linking references to
media objects.
The **media objects** module describes the pathing and typing of media
objects.
The **metainformation** module contains elements that describe meta
information about the SMIL file itself or the media objects it contains.
The **structure** module is a framework to describe the structure of the
SMIL file such as the head and body and SMIL elements.
The **transitions** module is a framework to describe transitions such
as wiping and fading between the presentation of media objects.
## Viewing a SMIL file
In order to view a SMIL presentation, a client will need to have a SMIL
player installed on his/her computer. Currently, Apple\'s Quicktime
player, Windows Media Player (WiMP) and RealNetworks RealPlayer are
among the most popular media players.
It would be convenient to be able to show these SMIL files natively in
web browser, eliminating the requirement of a separate SMIL player or
plug-in. Currently, Microsoft\'s Internet Explorer has limited support
for SMIL features. The open-source Mozilla project is slowly
incorporating SMIL and other XML-related technologies such as SVG and
MathML into their browsers, but progress is slow. It is possible they
are waiting for these XML-based languages to mature.
## Embedding SMIL files into XHTML web pages
As mentioned, SMIL is not yet native to web browsers, so in order to put
SMIL in a web page, one must embed it and open it in a plug-in.
Embedding SMIL files into web pages is somewhat beyond the scope of this
chapter. However, should you have a need to do this, the following links
are included as references to help you.
- Embedding a SMIL file is easy to do with Apple\'s
Quicktime
media player.
- Use the Windows Media Player to view SMIL files in a web page on a
non-IE browser.
- The Internet Explorer 5.5+ browser has support for SMIL.
- Visit this W3Schools
page for details on
how to use SMIL in IE-only web pages.
## SMIL for phones
As mentioned, SMIL is often used in the latest cellular phones. Phones
and vendors have varied support for MMS (multimedia messaging service),
but generally, MMS uses SMIL to define the layout of multimedia content.
If the MMS message contains a SMIL file, it will include other media
objects, which can be text or binary (text is treated here as a media
object or file to be referenced in a smil file).
Just a general note on MMS: the telecommunications industry needed a
system in order to charge for messages by throughput as well as a system
for pushing multimedia messages from phone to phone, computer to phone
or phone to computer. MMS is a standard, international system for these
purposes. SMIL was adopted because it was a well-defined, standard
language to describe the layout and timing of the content inside MMS
messages. In adhering to these (and other) standards developed by the
3GPP in partnership with the European Telecommunications Standards
Institution (ETSI) and the W3C, the industry was able to ensure
interoperability of new services between vendors, providing mutual
benefit and equal opportunity.
## SMIL tools and SMIL Info
Given that WikiBooks is a publicly-available \'open\' book, it would be
inappropriate to include information about or links to any commercial
SMIL tools. In other words, everything that is not free or open source
is not considered here.
Just a sidenote: some commercial tools cost upwards of \$800. It is
therefore in our best interest to evaluate, provide feedback for, and
contribute to opensource projects.
The following are useful links (March 18th, 2004) to free and opensource
tools, current SMIL projects, specifications, and tutorials:
- The official W3C SMIL page
- X-Smiles - a Java-based, \"an open XML
browser for exotic devices.\" Supports XSLT, XSLFO, SMIL, XForms and
SVG.
- Ambulant\'s Open SMIL Player
- W3school\'s *excellent*
tutorial on SMIL.
- PerlySMIL is a perl script
for generating SMIL files from perl.
- LimSee2 - is an
opensource, Java application for generating SMIL. It is this
author\'s experience that several media-related Java dependencies
must be properly installed before LimSee2 will work properly.
## SMIL in netbeans?
One can create a SMIL file in Netbeans just as one would create an XML
file. Just type it up and save it as a SMIL file. You can check for
well-formedness, but validation might be trickier. As mentioned
previously, SMIL 2.0 requires a namespace declaration, so don\'t forget
it.
For our simple exercises, just type up a well-formed SMIL document and
save it as .smil That\'s it!
## Summary
We\'ve seen how SMIL could be used to make standalone presentations. Yet
the future of SMIL may be in the connection of mobile devices to the
internet. As XML standards and SMIL tools reach maturity, SMIL will be
increasingly implemented in order to define interactive presentations in
the same way that Macromedia FLASH does, only this presentation will be
native to web browsers and micro browsers used in mobile devices. Since
SMIL is an open standard and it is extensible, there will likely be
other applications which will use also SMIL.
Visionaries foresee the increasing ubiquity of the internet in our homes
and work, on computers and mobile devices. This ubiquity is also called
\'pervasive computing\'. Mobile commerce would be an example of
pervasive computing as cellular phones and portable devices become more
useful for business and location-based services. SMIL is a language
which facilitates this trend by providing either a pretty face for
future business services or value-added multimedia content.
```{=html}
<div style="color:#8b4513;">
```
## SMIL Exercises
1. Create a simple SMIL file which displays the words, \'Hello World\'.
Confirm that the file works in a SMIL-conformant player.
2. Author a SMIL file which displays \'Hello World\' for 3 seconds,
then displays \'Goodbye World\' for 1 second. Confirm that the file
works in a SMIL-conformant player.
3. Take an existing Openoffice.org present (or PowerPoint) presentation
and turn it into a SMIL file. Double check it in a SMIL browser.
4. Embed one of the previously created SMIL files into an XHTML web
page and store the SMIL file and web page on a server. Confirm that
the SMIL file works for two different computers.
```{=html}
</div>
```
## SMIL Answers
## References
Ayars, J., Bulterman, D., Cohen, A., et al. (ed., 2001). Synchronized
Multimedia Integration Language (SMIL 2.0). Retrieved April 4, 2004 from
the World Wide Web Consortium Dot Org Web Site:
<http://www.w3.org/TR/smil20/smil-modules.html>
Castagno, Roberto (ed., 2003, January). Multimedia Messaging Service
(MMS); Media formats and codes. Retrieved April 4, 2004 from the Third
Generation Partnership Project (3GPP) Dot Org Web Site:
<http://www.3gpp.org/ftp/Specs/html-info/26140.htm>
Michel, T. (2004, March). Syncronized Multimedia (n.a., n.d). Retrieved
April 4, 2004 from the World Wide Web Consortium Web Dot Org Site:
<http://www.w3.org/AudioVideo/>
Newman, D., Patterson, A., Schmitz, P. (ed., 2002, January). XHTML+SMIL.
Retrieved April 4, 2004 from the World Wide Web Consortium Dot Org Web
Site: <http://www.w3.org/TR/XHTMLplusSMIL/>
SMIL Tutorial Home (n.d.). Retrieved April 4, 2004 from the W 3 Schools
Dot Com Web Site: <http://www.w3schools.com/smil/default.asp>
|
# XML - Managing Data Exchange/WDDX
## Learning objectives
Upon completion of this chapter, you will be able to answer the
following questions:
- What is WDDX?
- What are the uses of WDDX?
- What are Web Syndicate Networks?
- What are the benefits of WDDX?
## Introduction
`<b>`{=html}WDDX (Web Distributed Data eXchange)`</b>`{=html} was
created by Allaire, now known as
Macromedia, to solve the problem of
exchanging data between different web applications. It was originally
intended to be used to exchange data between
ColdFusion and other
web application languages. This XML-based technology enables complex
data to be exchanged between totally different Web programming languages
by creating \'Web Syndicate Networks.\' WDDX consists of a
language-independent representation of data based on an XML 1.0 DTD, and
a set of modules for a wide variety of languages that use WDDX.
### Features
- can be used with HTTP, SMTP, POP, FTP and other Internet protocols
that support transferring textual data
- must be using Netscape 3.0+ or Internet Explorer for Windows or any
versions for Unix and Mac platforms
- supports boolean, number, date-time, and string data types
- supports complex data types like arrays, structures, and recordsets
- not a formal standard, but is free and widely distributed and is
based on standard-base technologies like XML 1.0
## How it Works
The way that the web distributed data exchange works is by assigning a
specific module for the given programming language to translate the data
into an abstract XML format. Another specific module then translates the
XML back into another programming language for another web application.
For example, if you had an array in a ColdFusion program that you wanted
to send to an ASP program, it would first be serialized into XML and
sent to the ASP server. The ASP server would then deserialize it and
convert it to VBScript for use in the ASP program.
## Web Syndicate Networks
The term \'Web Syndicate Network\' refers to a group of websites that
share their content and transactions. This allows for economies of scale
as each site can use shared database content or even transactions and
procedures.
## References
OpenWDDX - <http://www.openwddx.org>\
WDDX Functions for PHP - <http://www.php.net/wddx>\
WDDX FAQ by Macromedia -
<http://www.macromedia.com/v1/handlers/index.cfm?id=5622&method=full>\
|
# XML - Managing Data Exchange/RPC
**Author:** Nathan Slider\
**Editor:** Nathan Slider\
UGA Master of Internet Technology
Program, 2005
## Learning Objectives
Upon completion of this chapter, you will be able to
- Discuss XML-RPC
- Create XML-RPC Code based on Examples
## RPC Defined
In order to fully understand XML-RPC, we should fist define RPC. A
**Remote Procedure Call** (**RPC**) is a protocol that allows a computer
program running on one host to cause code to be executed on another host
without the programmer needing to explicitly code for this. An RPC is
initiated by the caller (client) sending a request message to a remote
system (the server) to execute a certain procedure using arguments
supplied. A result message is returned to the caller. There are many
variations and subtleties in various implementations, resulting in a
variety of different (incompatible) RPC protocols.
In order to allow servers to be accessed by differing clients, a number
of standardized RPC systems have been created. Most of these use an
Interface Description Language (IDL) to allow various platforms to call
the RPC. Web services were the first real attempt to implement RPC
between platforms. Using Web services a .NET client can call a remote
procedure implemented in Java on a Unix server (and vice versa).
Web services use XML as the IDL, and HTTP as the
network protocol. The advantage of this system is simplicity and
standardization, the IDL is a text file that is widely understood, and
HTTP is built into almost all modern operating systems. An example of
such an RPC system is XML-RPC.
## XML-RPC Defined
**XML-RPC** (**Extensible Markup Language Remote Procedure Call**) is a
Remote Procedure Call protocol encoded in XML. It is a
very simple protocol, defining only a handful of data types and
commands, and the entire description can be printed on two pages of
paper. This is in stark contrast to most RPC systems, where the
standards documents often run into the thousands of pages and require
considerable software support in order to be used.
It was first created by in 1995 with
. However, Microsoft considered it too
simple and started adding functionality. After several rounds of this,
the standard was no longer so simple and became what is now
.
\"We wanted a clean, extensible format that\'s very simple. It should be
possible for an HTML coder to be able to look at a file containing an
XML-RPC procedure call, understand what it\'s doing, and be able to
modify it and have it work on the first or second try\... We also wanted
it to be an easy to implement protocol that could quickly be adapted to
run in other environments or on other operating systems.\"
-xmlrpc.com
## Data Types
Data Types Referenced from
+-----------+---------------------------+---------------------------+
| Name | Tag Example | Description |
+===========+===========================+===========================+
| array | ``` XML | Array of values, storing |
| | <array> | no keys |
| | <data> | |
| | <va | |
| | lue><i4>1404</i4></value> | |
| | | |
| | <value><string>Someth | |
| | ing Here</string></value> | |
| | | |
| | <value><i4>1</i4></value> | |
| | </data> | |
| | </array> | |
| | ``` | |
+-----------+---------------------------+---------------------------+
| base64 | `<base64>`{=h | \[Base 64\]-encoded |
| | tml}eW91IGNhbid0IHJlYWQgd | binary data |
| | GhpcyE=`</base64>`{=html} | |
+-----------+---------------------------+---------------------------+
| boolean | `<boolean>`{= | \[Boolean |
| | html}1`</boolean>`{=html} | datatype\|\[Boolean\] |
| | | logical value (0 or 1) |
+-----------+---------------------------+---------------------------+
| date/time | \<dateTi | Date and time |
| | me.iso8601\>19980717T14:0 | |
| | 8:55\</dateTime.iso8601\> | |
+-----------+---------------------------+---------------------------+
| double | `<double>`{=html | Double \[precision\] |
| | }-12.53`</double>`{=html} | floating number |
+-----------+---------------------------+---------------------------+
| integer | `<i4 | Whole number, \[integer\] |
| | >`{=html}42`</i4>`{=html} | |
+-----------+---------------------------+---------------------------+
| string | `<string>`{=html}Hello | String of characters. |
| | world!`</string>`{=html} | Must follow |
| | | XML |
| | | encoding. |
+-----------+---------------------------+---------------------------+
| struct | ``` XML | Array of values, storing |
| | <struct> | keys |
| | <member> | |
| | <name>foo</name> | |
| | | |
| | <value><i4>1</i4></value> | |
| | </member> | |
| | <member> | |
| | <name>bar</name> | |
| | | |
| | <value><i4>2</i4></value> | |
| | </member> | |
| | </struct> | |
| | ``` | |
+-----------+---------------------------+---------------------------+
| nil | `<nil/>`{=html} | Discriminated null value; |
| | | an XML-RPC |
| | | ext |
| | | ension |
+-----------+---------------------------+---------------------------+
### Examples
An example of a typical XML-RPC request would be:
``` XML
<?xml version="1.0"?>
<methodCall>
<methodName>examples.getStateName</methodName>
<params>
<param>
<value><i4>41</i4></value>
</param>
</params>
</methodCall>
```
An example of a typical XML-RPC response would be:
``` XML
<?xml version="1.0"?>
<methodResponse>
<params>
<param>
<value><string>South Dakota</string></value>
</param>
</params>
</methodResponse>
```
A typical XML-RPC fault would be:
``` XML
<?xml version="1.0"?>
<methodResponse>
<fault>
<value>
<struct>
<member>
<name>faultCode</name>
<value><int>4</int></value>
</member>
<member>
<name>faultString</name>
<value><string>Too many parameters.</string></value>
</member>
</struct>
</value>
</fault>
</methodResponse>
```
A final example, comparing a PHP associative array with an equivalent
XML-RPC `<struct>`{=html}. This array:
``` PHP
Array
(
[0] => 'dogs',
[1] => 'cats',
['animals'] => Array(
[0] => FALSE,
[1] => 'little_dogs',
[2] => 'little_cats',
[3] => 5,
[4] => 2.3,
[5] => 1,
),
);
```
Becomes the following XML-RPC:
``` XML
<?xml version="1.0" encoding="utf-8"?>
<methodResponse>
<params>
<param>
<value>
<struct>
<member>
<name>0
</name>
<value><string>dogs</string>
</value>
</member>
<member>
<name>1
</name>
<value><string>cats</string>
</value>
</member>
<member>
<name>animals
</name>
<value>
<array>
<data>
<value><boolean>0</boolean>
</value>
<value><string>little_dogs</string>
</value>
<value><string>little_cats</string>
</value>
<value><i4>5</i4>
</value>
<value><double>2.3</double>
</value>
<value><boolean>1</boolean>
</value>
</data>
</array>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodResponse>
```
## References
- XML-RPC Homepage
- XML-RPC Specification
- Free Online Dictionary of
Computing
- Forum
- Tutorials
- Technology Reports
- Citations from CiteSeer
|
# XML - Managing Data Exchange/JSTL
The **JavaServer Pages Standard Tag Library** (Short Form: **JSTL**) is
a collection of four custom-tag libraries which extend the JSP
specification. As a component it is allocated in the Java EE Web
application development platform. The JSTL is administrated in the
setting of the Java Community Process (JCP) 052. Within the
Jakarta-Project there are reference implementations to these
specifications.
## Components
In version 1.1 the following libraries were intended:
- core: iterative, conditional, URL-specific and general Tags
- xml: Tags from the field XML and XML-transformation
- sql: Tags for direct data base administration
- i18n: Tags for formatting and internationalization
## History
In its original Version 1.0 an „Expression Language" was intended in
comparison to Version 1.1. With JSP 2.0 JSP-EL was taken up in the
JSP-specifications itself. Therefore the primary goal of JSTL 1.1 is the
adaption of the libraries to the JSP-EL for JSP 2.0. With the libraries
in version 1.2 the JSTL is up to date concerning the unification of the
Expression Language by the JSP 2.1 and JSF-1.2-specifications.
Furthermore the JSTL in Version 1.2 is part of the Java-EE-5-Platform.
## Usage of JSTL 1.1
As for the use of JSTL 1.1 the JSP-EL is required, a servlet-container
has to be conform to at least the JSP-2.0 specifications in order to be
be used on this. The reference implementation is made up of two JAR --
archives „standard.jar" and „jstl.jar". In most containers they usually
need to be located in the lib-path of the web application only. To
ensure backwards compatibility the JSTL 1.1 is referenced by the URI
„http://java.sun.com/jsp/jstl/fmt" whereas
„http://java.sun.com/jstl/fmt" is used for JSTL 1.0.
**Example JSP-page in XML-notation (JSPX):**
``` xml
<?xml version="1.0" encoding="utf-8" ?>
<jsp:root
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:fmt="http://java.sun.com/jsp/jstl/fmt"
version="2.0">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>JSTL 1.1</title>
</head>
<body>
<h1>Iteration</h1>
<ul>
<c:forEach var="num" begin="1" end="10">
<li>Number<c:out value="${num}"/></li>
</c:forEach>
</ul>
<h1>Formatting</h1>
<p>
Currency: <fmt:formatNumber value="10000" type="currency" currencyCode="EUR" />
</p>
</body>
</html>
</jsp:root>
```
**Code-Explanations:**
In the *jsp:root* -- element the usage of the basis- und the
I18N-Taglibs (core and fmt) from the JSTL is indicated and linked to the
according XML-namespace. Under the headline *Iteration* the
*forEach-Tag* from the core-library is used: It displays the tag-body
(i.e., the content of the Tag) ten times. In this loop with *`${num}`*
you can find JSP -- Expression. With every loop cycle the current data
from *num* is displayed here. Under the headline *Formatting* the
*formatNumber*-tag from the fmt -- library of JSTL is used. Depending on
the adjusted language (this can be set by fmt:setLocale for example) the
number 10000 will be formatted (e.g. in German as „EUR 10.000,00" and in
English as „EUR 10,000.00")
## Alternatives to the JSTL
**Struts vs. JSTL:** There are in fact many instances where a Struts tag
and JSTL tag will perform equivalent functions. Unlike the
Struts-Framework the JSTL is not linked to a certain
architecture--paradigm, like the *Model--View--Controller* separation.
JSTL tags are more powerful compared to struts tags, because JSTL is a
more standard part of the J2EE specification, while at the same time
many options are available like condition checking, comparing strings,
triming white spaces, converting upper case or lower case, etc. Both
libraries own tags with identical name. So if these libraries are mixed
in applications, what is possible, it needs to be attended to use unique
prefixes(JSP) or namespaces (JSPX).
## Example Applications & Tutorials
- Using JSTL to handle
internationalization
- Examples
## Weblinks
- Suns Java JSTL Homepage
- JSTL
Reference
- Jakarta Taglibs
|
# XML - Managing Data Exchange/RDF - Resource Description Framework
Author: Sascha Meissner \| Editor: Laura Bashaw\
Editing Status: Draft\
Modification Date: Dec 6, 2004
## Learning objectives
Upon completion of this chapter, you will be able to
- understand the Resource Description Framework (RDF)
- use RDF to define metadata for web resources
- include standards like the Dublin Core for your description
- explore how Adobe is handling metadata
- create your own individual properties to expand your description
## Introduction
### Concept
The Resource Description Framework (RDF) is terminology used to encode,
exchange and reuse metadata in the World Wide Web. Metadata, structured
data about data, includes any important type of information about a
resource such as author, title, creation date or language. A
**resource** is everything that can be addressed with a Uniform Resource
Identifier (URI). For
example, a web page or a distinct type of document. RDF considers
**description** as the act of making statements about the properties
(attributes, characteristics) and inter-relationships of these
resources. A **framework** is a common model to contain or manage the
diverse information about a resource.
**Why do we not use XML to describe things?**\
\* XML is too flexible. There are too many ways to describe things. For
example, the name of a person (see code example). Each of these XML
documents would map into a different logical tree. However, a query
,like what is the name of person x, has to be independent of the choice
of the tree. RDF is different because it has a standard way of
interpreting XML-encoded descriptions of resources which converts into
one logical tree and thereby covers all possible reprensentations of a
description.
`<person name="Pete Maravich">`{=html}
or
`<person>`{=html}\
` ``<name>`{=html}`Pete Maravich``</name>`{=html}\
`</person>`{=html}
- XML documents follow a schema. The order of elements is restricted,
and documents are not extensible without changing the schema. RDF
allows to list information regardless of their order or appearence.
RDF is also openly extensible. This means if one receives a
description about something or someone, one can easily add
information without being limited to following a schema. This is a
great advantage, particularly for annotation and metadata
applications. Besides that, it is intricate to retrieve any semantic
meaning from an XML document without knowing the XML schema.
\
RDF is an application of XML that enforces the needed structural
constraints to provide unambiguous methods of expressing semantics. XML
syntax guarantees vendor independence, extensibility, validation and the
ability to represent complex structures. RDF extends the general XML
syntax and model to be specific for describing resources. Furthermore,
RDF uses XML namespaces that allow to scope and uniquely identify a set
of properties. With namespaces that point to URIs, one can generate
globally unique names for its resources. Unique names need no context to
qualify.
### Brief History
RDF is a result of several metadata communities coming together to build
a robust and flexible architecture for supporting metadata on the
existing web. The first RDF specification was released 1997 by Ora
Lassila and Ralph Swick. Based on that specification RDF interest groups
were established in the following years and RDF became a W3C
recommendation\
(W3C RDF). The potential of RDF was soon
realized and once its use is widespread the impacts will be tremendous.
Ora Lassila said the following
(W3C_NOTE_1997-11-13).
```{=html}
<center>
```
*Once the web has been sufficiently \"populated\" with rich metadata,
what can we expect? First, searching on the web will become easier as
search engines have more information available, and thus searching can
be more focused. Doors will also be opened for automated software agents
to roam the web, looking for information for us or transacting business
on our behalf. The web of today, the vast unstructured mass of
information, may in the future be transformed into something more
manageable - and thus something far more useful.*
```{=html}
</center>
```
### Purpose
Besides the human-readable display of metadata RDF is intended to enable
the exchange of information between different applications without any
loss of meaning. The effective use of metadata among applications,
however, requires common conventions about semantics syntax, and
structure. RDF imposes these conventions that make an unambiguous
transfer possible. Application areas include resource description,
site-maps, content rating, electronic commerce, collaborative services,
and privacy preferences. Earlier one of the major obstacles of metadata
interoperability has been the multiplicity of incompatible standards for
metadata syntax and schema definition languages. However since RDF is a
W3C recommendation and communities provide a standard vocabulary to
describe things application designers and developers can create
applications that allow metadata exchange in a standardized way.
## The Basic Structure
### Statements
With RDF one can make statements about resources. Below you can see an
example of a statement that can be made about a web page. The key parts
of the statement are highlighted:
`<span style="color:blue;">`{=html}http://www.example.org/index.html`</span>`{=html}
has an `<span style="color:red;">`{=html}author`</span>`{=html} whose
name is `<span style="color:darkgreen;">`{=html}Pete
Maravich`</span>`{=html}.
In general a RDF statement is a triple that contains a:
- `<span style="color:blue;">`{=html}Resource`</span>`{=html}, the
subject of a statement
- `<span style="color:red;">`{=html}Property`</span>`{=html}, the
predicate of a statement
- `<span style="color:darkgreen;">`{=html}Value`</span>`{=html}, the
object of a statement
RDF is based on the concept that every resources can have different
properties which have values. A resources, represented by an URI
reference, can be fully described by using properties and their values.
Other properties for this web page could be:
`<span style="color:blue;">`{=html}http://www.example.org/index.html`</span>`{=html}
has a `<span style="color:red;">`{=html}language`</span>`{=html} which
is `<span style="color:darkgreen;">`{=html}English`</span>`{=html}.\
or\
`<span style="color:blue;">`{=html}http://www.example.org/index.html`</span>`{=html}
has a `<span style="color:red;">`{=html}title`</span>`{=html} which is
`<span style="color:darkgreen;">`{=html} Example_Title`</span>`{=html}.
### Graphs
An RDF statement is a structured triple that contains a subject, a
predicate and an object. A set of such triples is called a graph where a
subject is always a node, a predicate is always an arc and an object is
always a node:\
\
!Abstract RDF graph\
`<small>`{=html}**Figure 1 - Abstract RDF graph**`</small>`{=html}\
The set of example statements can be represented by the following graph:
!Example graph\
`<small>`{=html}**Figure 2 - Example graph**`</small>`{=html}
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td>
```
Subject
```{=html}
</td>
```
```{=html}
<td>
```
<http://www.example.org/index.html>
```{=html}
</td>
```
```{=html}
<td>
```
is either an URI reference or a blank node
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
Predicate
```{=html}
</td>
```
```{=html}
<td>
```
<http://purl.org/dc/elements/1.1/Title>
```{=html}
</td>
```
```{=html}
<td>
```
is an URI reference
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
Object
```{=html}
</td>
```
```{=html}
<td>
```
Example_Title
```{=html}
</td>
```
```{=html}
<td>
```
can either be an URI reference, a literal or a blank node
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
### RDF/XML
Natural English sentences and graphs that represent RDF\'s concept model
are very useful pratices to understand the basics of RDF. However RDF
uses a normative XML syntax called RDF/XML to put down and exchange
graphs. Like HTML, RDF/XML is machine processable and, using URIs, can
link pieces of information. But, unlike conventional hypertext, RDF URIs
can refer to any identifiable thing, including things that may not be
directly retrievable on the Web (such as persons).
The following lines represent the graph in Figure 2 in RDF/XML:
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td style="vertical-align:top;text-align:right;">
```
`1`\
` 2`\
`3`\
`4`\
` 5`\
`6`\
`7`\
` 8`\
`9`\
`10`\
` 11`\
`12`\
`13`\
` 14`
```{=html}
</td>
```
```{=html}
<td>
```
``` XML
<?xml version="1.0"?><br>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:property="http://www.example.org/properties/"> <br>
<rdf:Description rdf:about="http://www.example.org/index.html">
<property:author>Pete Maravich</property:author>
</rdf:Description> <br>
<rdf:Description rdf:about="http://www.example.org/index.html">
<dc:language>en</dc:language>
</rdf:Description> <br>
<rdf:Description rdf:about="http://www.example.org/index.html">
<dc:title>Example_Title</dc:title>
</rdf:Description> <br>
</rdf:RDF>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
`<small>`{=html}**Figure 3 - example_rdf.rdf**`</small>`{=html}
Let\'s examine the lines of code to get a better understanding of the
syntax:
- {1} XML declaration, identifies the document as XML in the current
version 1.0
- {2} Start of an rdf:RDF element, identifies the following code as
RDF - also declares an XML namespace *rdf*, all tags starting with
the prefix rdf: are part of the namespace identified by the URIref
*http://www.w3.org/1999/02/22-rdf-syntax-ns#* which describe the RDF
vocabulary
- {3} declares an XML namespace *dc*, all tags starting with the
prefix dc: are part of the namespace identified by the URIref
*http://purl.org/dc/elements/1.1/* - the *link* defines a standard
vocabulary of terms for metadata
- {4} declares an XML namespace *property*, all tags starting with the
prefix property: are part of the namespace identified by the URIref
*http://www.example.org/properties/* - this URI is fictitious and
was chosen to indicate that one can create their own vocaburaly to
describe resources
- {5 to 7} represents a specific statement about the resource
*http://www.example.org/index.html* as seen in the examples - Line 5
declares the subject of the description - Line 6 provides a property
element, the qualified name *property* is an abbreviation that
represents the assigned namespace (line 4), property:author stands
for *http://www.example.org/properties/author* - embedded in the
property tag is the value(object) of the description as a plain
literal
```{=html}
<!-- -->
```
- {8 to 10} shows another statement - Line 8 again provides the
subject - dc:language specifies the predicate for the statement,
*http://purl.org/dc/elements/1.1/language* - the literal \'en\' is
an international standard two-letter code for English
```{=html}
<!-- -->
```
- {11 to 13} shows yet another statement - Line 10 to identify the
subject - dc:title specifies the predicate for the statement,
*http://purl.org/dc/elements/1.1/title* - the value Example_Title is
the object
- {14} ends the rdf:RDF element
Section 3 has covererd the basic structure of RDF and is intended to
provide a fundamental understanding of the topic. The next section will
cover some advanced structures and features of RDF.
## Advanced Concepts
**Structured Property Values and Blank Nodes**
As mentioned earlier the object of a statement can be a literal, a blank
node or a URI reference. The latter two give RDF more power because they
allow to create complex structures, so called **structured property
values**. For instance you consider describing the address of somebody.
An address is a structure that consists of different values such as a
street, a city, a state and a zipcode. In RDF one would identify the
adress as a resource to allow a more detailed description.
!structured RDF graph
`<small>`{=html}**Figure 4 - structured RDF graph**`</small>`{=html}
As you can see the value of the property *creator* is represented by a
reference using the URI *http://www.example.org/members/1234*. RDF
statements (additional arcs and nodes) can then be written with that
node as the subject, to represent the additional information like the
name of the creator and his address. The property *adress* itself is
represented by a URI, which allows a detailed description that is
aggregated from further statements about the address.
However the URIref *http://www.example.org/address/1234* may never need
to be referred to directly from outside a particular graph, and
therefore may not require a specific identifier. The concept above could
also be represented by using a **blank node** for the address object.
Blank nodes were called anonymous resources, they have no URIrefs and no
literals.
!structured RDF graph with a blank
node
`<small>`{=html}**Figure 5 - structured RDF graph using a blank
node**`</small>`{=html}
In RDF/XML the concept of structured property values and blank nodes are
represented like this:
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td style="vertical-align:top;text-align:right;">
```
`1`\
` 2`\
`3`\
`4`\
` 5`\
`6`\
`7`\
`8`\
`9`\
`10`\
`11`\
`12`\
` 13`\
`14`\
`15`\
`16`\
`17`\
` 18`
```{=html}
</td>
```
```{=html}
<td>
```
``` XML
<?xml version="1.0"?><br>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:property="http://www.example.org/properties/"> <br>
<rdf:Description rdf:about="http://www.example.org/index.html">
<dc:creator>
<rdf:Description rdf:about="http://www.example.org/members/1234">
<properties:name>Pete Maravich</properties:name>
<properties:address rdf:nodeID="abc"/>
</rdf:Description>
</dc:creator>
</rdf:Description><br>
<rdf:Description rdf:nodeID="abc">
<properties:street>346 Broad Street</properties:street>
<properties:city>Athens</properties:city>
<properties:state>Georgia</properties:state>
</rdf:Description> <br>
</rdf:RDF>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
`<small>`{=html}**Figure 6 - structured_rdf.xml**`</small>`{=html}
Let\'s examine the lines of code that represent the new concepts:
- {5 to 12} describes the resource *http://www.example.org/index.html*
that has the value *http://www.example.org/members/1234*
- {7 to 10} displays a way to abbreviate multiple property elements
for a resource - usually a node has multiple arcs(properties) coming
off and instead of writing one description for each property one can
abbreviate this by using multiple child property elements inside the
node element describing the subject node
- {9} shows how one can identify a blank node in RDF/XML - it is
sometimes necessary that the same blank node in a graph is referred
to in the RDF/XML in multiple places - if so, a blank node
identifier can be given to the blank node for identifying it in the
document
- {13-17} displays the properties and values for the blank node
identified in line {9}
## RDF applications
### Dublin Core Metadata Initiative
*The Dublin Core Metadata Initiative (DCMI) is
an organization dedicated to promoting the widespread adoption of
interoperable metadata standards and developing specialized metadata
vocabularies for describing resources that enable more intelligent
information discovery systems.*\
Basically the Dublin Core is a set of elements that are used to describe
a document. The goal of the Dublin Core is to provide a minimal set of
descriptive elements that support and simplify the description and the
automated indexing of document-like networked objects. Discovery tools
on the Internet, such as the \"Webcrawlers\" employed by popular World
Wide Web search engines use the metadata set. In addition, the Dublin
Core is meant to be sufficiently simple to be understood and used by the
wide range of authors and casual publishers who contribute information
to the Internet. (also see
RFC-2413)
Dublin Core Metadata Element
Set shows a description of all
current elements defined in the Dublin Core. In the following example
one can see an RDF document that uses the Dublin Core elements to
describe an article in a magazine:
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td style="vertical-align:top;text-align:right;">
```
`1`\
` 2`\
`3`\
`4`\
` 5`\
`6`\
`7`\
`8`\
`9`\
`10`\
`11`\
`12`\
`13`\
`14`\
` 15`\
`16`\
`17`\
`18`\
`19`\
`20`\
` 21`
```{=html}
</td>
```
```{=html}
<td>
```
``` XML
<?xml version="1.0"?><br>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:dcterms="http://purl.org/dc/terms/"><br>
<rdf:Description rdf:about="http://www.cio.com/archive/101504/km.html">
<dc:title>Less for Success</dc:title>
<dc:creator>Alice Dragoon</dc:creator>
<dc:subject>
<rdf:Bag>
<rdf:li>knowledge management</rdf:li>
<rdf:li>technology investments</rdf:li>
</rdf:Bag>
</dc:subject>
<dc:description>Forget the big bang approach. When it comes to demonstrating the value
of knowledge management, a piecemeal strategy works best.</dc:description>
<dc:publisher>CXO Media</dc:publisher>
<dcterms:issued>October 15, 2004</dcterms:issued>
<dc:format>text/html</dc:format>
<dc:language>en</dc:language>
<dcterms:isPartOf rdf:resource="http://www.cio.com/archive/101504/index.html"/>
</rdf:Description><br>
</rdf:RDF>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
`<small>`{=html}**Figure 7 - cio_article.rdf**`</small>`{=html}
### Adobe\'s XMP
The Extensible Metadata Platform is a specification describing RDF-based
data and storage models for metadata about documents in any format. XMP
can be included in text files such as HTML or SVG, image formats such as
JPEG or GIF and Adobe\'s own formats like Photoshop or Acrobat. Adobe is
making efforts that all of their applications will support XMP. However
Adobe claims that *XMP provides a standard format for the creation,
processing and interchange of metadata*, the specification is not a
standard.
**XMP provides the following:**
- A data model - as a useful and flexible way of describing metadata
in documents.
- A storage model - for the implementation of the data model. This
includes the serialization of the metadata as a stream of XML and
XMP Packets, a means of packaging the data in files.
- Schemas - predefined sets of metadata property definitions that are
relevant for a wide range of applications, including all of Adobe's
editing and publishing products, as well as for applications from a
wide variety of vendors. XMP also provides guidelines for the
extension and addition of schemas.
However XMP metadata vocubularly is relatively small,i.e. the ways to
describe a document are limited. To overcome this issue Adobe is using
metadata standards such as the Dublin Core and also allows users to
define their own metadata vocaburlarly.
\
The following screenshot is from Acrobat Professional 6.0 *Document
Metadata* feature. The description field allows users to define
metadata, whereas the advanced tab shows an overview of the metadata.
Under view *Source* one can see the metadata in RDF/XML.
!Abobe XMP
example{width="500"}\
`<small>`{=html}**Figure 8 - Adobe XMP example**`</small>`{=html}
The RDF/XML based representation of the document\'s metadata can be
found here. The
property funFactor expresses the hilariousness of a document. It was
included using the \'load\' functionality of Acrobat Professional to
test the addition of arbitrary metadata to the properties Acrobat
Professional already knew about.
### RSS - RDF Site Summary
RDF Site Summary (RSS) is also an application of RDF. Please have a look
at the Chapter on RSS in this Wikibook.
## Creating an RDF Vocabulary
As seen earlier in the chapter one can create its own RDF metadata
vocabulary, despite using standards like the Dublin Core. This section
is intended to show a very general approach in creating such a personal
vocabulary. For a detailed description please see *Practical RDF -
Powers 2003*.
The first step in creating a vocabulary is to define the domain elements
and their properties within the given area interest. This means one has
to outline what kind of information about the resource should be
described. Let\'s say we want to save the following facts about a
resource:
```{=html}
<table width="50%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td>
```
**Property**
```{=html}
</td>
```
```{=html}
<td>
```
**Description**
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
Title
```{=html}
</td>
```
```{=html}
<td>
```
Title of the resource
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
Created
```{=html}
</td>
```
```{=html}
<td>
```
Date of creation
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
Author
```{=html}
</td>
```
```{=html}
<td>
```
Author of the resource
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
Status
```{=html}
</td>
```
```{=html}
<td>
```
Current status of the resource
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
Subject
```{=html}
</td>
```
```{=html}
<td>
```
Subject/topic of the resource
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
Format
```{=html}
</td>
```
```{=html}
<td>
```
Format of the resource
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
FunFactor
```{=html}
</td>
```
```{=html}
<td>
```
FunFactor of the resource
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
The next step is to create a RDF Schema(RDFS) document for the new
vocabulary:
Here you can
see the definition for our desired properties. Using this RDFS one can
describe the article seen above the following way:\
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td style="vertical-align:top;text-align:right;">
```
`1`\
` 2`\
`3`\
` 4`\
`5`\
`6`\
`7`\
`8`\
`9`\
`10`\
`11`\
`12`\
`13`\
`14`\
`15`\
`16`\
`17`\
` 18`
```{=html}
</td>
```
```{=html}
<td>
```
``` XML
<?xml version="1.0"?><br>
<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:same="http://mitglied.lycos.de/virtuoso5/elements/1.0/myschema#"><br>
<rdf:Description rdf:about="http://www.cio.com/archive/101504/km.html">
<same:title>Less for Success</same:title>
<same:author>Alice Dragoon</same:author>
<same:subject>
<rdf:Bag>
<rdf:li>knowledge management</rdf:li>
<rdf:li>technology investments</rdf:li>
</rdf:Bag>
</same:subject>
<same:format>text/html</same:format>
<same:status>active</same:status>
<same:created>2004-10-19</same:created>
<same:funFactor>3</same:funFactor>
</rdf:Description><br>
</rdf:RDF>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
`<small>`{=html}**Figure 9 - cio_article2.rdf**`</small>`{=html}
To validate its RDFS and RDF files one can use the W3C RDF
Validator.
## Exercises
1. Create an RDF/XML document that describes an article of your choice
(e.g. from magazines like CIO.com or ZDNet.com). Use the Dublin Core
element set and the Dublin
Core termsas a framework for your
description. After completing the document please validate your work
with the\
W3C RDF Validator.
## References
- RDF Primer - *W3C Recommendation 10 February 2004*,
<http://www.w3.org/TR/rdf-primer/>
- Shelley Powers - *Practical RDF*, O\'Reilly 2003
- Tim Berners-Lee *Why RDF model is different from the XML model*,
September 1998, <http://www.w3.org/DesignIssues/RDF-XML.html>
- Dublin Core Metadata Initiative - <http://dublincore.org/>
- Adobe XMP - <http://www.adobe.com/products/xmp/main.html>
- XML.com - *XMP Lowdown*,
<http://www.xml.com/pub/a/2004/09/22/xmp.html>
|
# XML - Managing Data Exchange/RSS

## Learning Objectives
Upon completion of this chapter, you will
- Understand the basics of RSS
- Understand the history of RSS
- Be able to construct a RSS 2.0 document using XML
- Subscribe to an RSS aggregator/reader
## Introduction
RSS is a simple XML format used to syndicate headlines. It is now
popularly used by websites that publish new content regularly and
provide a list of headlines with links to their latest content. Content
such as news feeds, events listings, project updates, blogger and most
recently podcasting, video and image distribution can all be distributed
by RSS. RSS feeds are also used by major Internet portals such as
Google, Yahoo and AOL for people to personalize and have information
that they care about delivered to them, i.e. MyYahoo.
### What does RSS mean?
RSS is considered a name variously used to refer to three different
standards. The three separate branches are the RSS 0.9 branch, the RSS
1.0 branch (which is based on RDF) and RSS 2.0, and the initials have
been expanded into three different names: \"Really Simple Syndication\"
(RSS 0.9, 2.0), \"Rich Site Summary\" and \"RDF Site Summary\" (for RSS
1.0).
Several different versions have been developed by different developers
under different names. According to XML.com, seven versions of RSS have
been developed (see What is
RSS?). Because
RSS is understood as a term referring to many types of syndication
protocols, these various RSS protocols have sometimes been accused of
being \"incompatible\" with each other (see The myth of RSS
compatibility).
This is an important issue for RSS reader/aggregator developers.\
### History
The original version (version 0.90) of RSS was released by Netscape in
1999. Netscape developers were designing a format for making portals of
headlines for news sites. After Netscape released the simplified version
of RSS, they lost interest in developing RSS. However, another company,
UserLand Software took over with intention to use RSS with their
web-logging products and web-based writing software. While UserLand
Software continued development with version 0.91, a third non-commercial
group split off from the company and designed a new format based on
version 0.90, which was a non-simplified version. The new format
developed by this non-commercial group became known as version 1.0. In
the meantime UserLand Software grew angered at the new 1.0 version, kept
developing RSS and released version 2.0. Version 2.0 has become the
leader and most widely adopted version of RSS. The 2.0 specification was
donated to a non-commercial third party, Harvard Law School. Harvard Law
is now responsible for the future development of the RSS 2.0
specification. Below is a table that describes each version, the owner,
pros and cons, as well as its current status and recommendation for use.
```{=html}
<table border="1" summary="RSS versions and recommendations of use">
```
```{=html}
<caption>
```
RSS versions and recommendations, Table source: What is
RSS? XML.com
```{=html}
</caption>
```
```{=html}
<tr>
```
```{=html}
<th>
```
Version
```{=html}
</th>
```
```{=html}
<th>
```
Owner
```{=html}
</th>
```
```{=html}
<th>
```
Pros
```{=html}
</th>
```
```{=html}
<th>
```
Status
```{=html}
</th>
```
```{=html}
<th>
```
Recommendation
```{=html}
</th>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<th>
```
0.90
```{=html}
</th>
```
```{=html}
<td>
```
Netscape
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
Obsoleted by 1.0
```{=html}
</td>
```
```{=html}
<td>
```
Don\'t use
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<th>
```
0.91
```{=html}
</th>
```
```{=html}
<td>
```
UserLand
```{=html}
</td>
```
```{=html}
<td>
```
Drop dead simple
```{=html}
</td>
```
```{=html}
<td>
```
Officially obsoleted by 2.0, but still quite popular
```{=html}
</td>
```
```{=html}
<td>
```
Use for basic syndication. Easy migration path to 2.0 if you need more
flexibility
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<th>
```
0.92, 0.93, 0.94
```{=html}
</th>
```
```{=html}
<td>
```
UserLand
```{=html}
</td>
```
```{=html}
<td>
```
Allows richer metadata than 0.91
```{=html}
</td>
```
```{=html}
<td>
```
Obsoleted by 2.0
```{=html}
</td>
```
```{=html}
<td>
```
Use 2.0 instead
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<th>
```
1.0
```{=html}
</th>
```
```{=html}
<td>
```
RSS-DEV Working Group
```{=html}
</td>
```
```{=html}
<td>
```
RDF-based, extensibility via modules, not controlled by a single vendor
```{=html}
</td>
```
```{=html}
<td>
```
Stable core, active module development
```{=html}
</td>
```
```{=html}
<td>
```
Use for RDF-based applications or if you need advanced RDF-specific
modules
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<th>
```
2.0
```{=html}
</th>
```
```{=html}
<td>
```
UserLand
```{=html}
</td>
```
```{=html}
<td>
```
Extensibility via modules, easy migration path from 0.9x branch
```{=html}
</td>
```
```{=html}
<td>
```
Stable core, active module development
```{=html}
</td>
```
```{=html}
<td>
```
Use for general-purpose, metadata-rich syndication
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## RSS structure
A RSS document is often known as RSS feed and can have three different
types of file extensions: .RSS, .XML and .RDF. All RSS documents must
conform 100% to the XML specification begin with the XML declaration. To
identify a RSS document, the top level starts with a
`<span style="color:Red;">`{=html}`<rss>`{=html}`</span>`{=html}
element, followed by a mandatory version attribute that specifies the
RSS version. Sub-element to the
`<span style="color:Red;">`{=html}`<rss>`{=html}`</span>`{=html}
element, is the single
`<span style="color:Red;">`{=html}`<channel>`{=html}`</span>`{=html}
element which contains a brief description of the channel. Below is a
sample of RSS(2.0) from the New York Times.\
**Exhibit 1: Data model for RSS**
``` XML
<rss version="2.0">
<channel>
<title>NYT > Home Page</title>
<link> <nowiki>http //www.nytimes.com/index.html</nowiki> </link>
<description>New York Times > Breaking News, World News Multimedia</description>
<copyright>Copyright 2004 The New York Times Company</copyright>
<language>en-us</language>
<lastBuildDate>Sun, 7 Nov 2004 13 30 01 EST</lastBuildDate>
<image>
<url> <nowiki>http //www.nytimes.com/images/section/NytSectionHeader.gif</nowiki> </url>
<title>NYT > Home Page</title>
<link> <nowiki>http //www.nytimes.com/index.html</nowiki> </link>
</image>
<item>
<title>Iraq Declares State of Emergency as Insurgents Step Up Attacks</title>
<link> <nowiki>http //www.nytimes.com/2004/11/07/international/middleeast/07cnd-iraq.html</nowiki> </link>
<description> Today's attacks, including three police post raids that killed 21, came a day after insurgents killed at least 30. </description>
<author> By EDWARD WONG </author>
<pubDate> Sun, 07 Nov 2004 00 00 00 EDT </pubDate>
<guid> <nowiki>http //www.nytimes.com/2004/11/07/international/middleeast/07cnd-iraq.html</nowiki> </guid>
</item>
</channel>
</rss>
```
`<small>`{=html}**Figure 1-1: New York Times -
HomePage.xml -
RSS version 2** `</small>`{=html}\
\
The `<span style="color:Red;">`{=html}`<channel>`{=html}`</span>`{=html}
element has three mandatory elements and several optional elements.\
**Mandatory `<channel>`{=html} elements:**
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td>
```
Element
```{=html}
</td>
```
```{=html}
<td>
```
Description
```{=html}
</td>
```
```{=html}
<td>
```
Example
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
<title>
```
```{=html}
</td>
```
```{=html}
<td>
```
Name of the channel
```{=html}
</td>
```
```{=html}
<td>
```
\"The New York Times\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<description>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Brief description of the channel
```{=html}
</td>
```
```{=html}
<td>
```
New York Times \> Breaking News, World News Multimedia
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<link>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
URL to the channel associated website
```{=html}
</td>
```
```{=html}
<td>
```
http://www.nytimes.com/index.html
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
**Optional `<channel>`{=html} elements:**
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td>
```
Element
```{=html}
</td>
```
```{=html}
<td>
```
Description
```{=html}
</td>
```
```{=html}
<td>
```
Example
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<language>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Channel language
```{=html}
</td>
```
```{=html}
<td>
```
en-us
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<copyright>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Copyright notice for content in the channel
```{=html}
</td>
```
```{=html}
<td>
```
Copyright 2004 The New York Times Company
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<lastBuildDate>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The last time the content of the channel was updated/changed
```{=html}
</td>
```
```{=html}
<td>
```
Sun, 7 Nov 2004 13:30:01 EST
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
Other optional elements include: managingEditor, webMaster, pubDate,
category, generator, docs, cloud, ttl, image, rating, textInput,
skipHours, skipDates. The requirement or sub-elements of each element
please refer to the RSS specification.(see at Harvard
Law).
Below are example of image element.\
\
`<image>`{=html} elements:\
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td>
```
Element
```{=html}
</td>
```
```{=html}
<td>
```
Description
```{=html}
</td>
```
```{=html}
<td>
```
Example
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<link>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The URL to the item
```{=html}
</td>
```
```{=html}
<td>
```
http://www.nytimes.com/index.html
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
<title>
```
```{=html}
</td>
```
```{=html}
<td>
```
Picture title
```{=html}
</td>
```
```{=html}
<td>
```
NYT \> Home Page
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<url>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The URL to the picture
```{=html}
</td>
```
```{=html}
<td>
```
http://www.nytimes.com/images/section/NytSectionHeader.gif
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
A channel may contain a number of `<item>`{=html}s. An item may
represent a \"story\" - much like a story in a newspaper or magazine; if
so, its description is a synopsis of the story. The link points to the
full story. An item may also be complete in itself, if so, the
description contains the text (entity-encoded HTML is allowed; see
examples), and the link and title may be omitted.\
Each RSS channel can contain up to 15 items. All elements of an item are
optional,however, an `<item>`{=html} element must contain at least one
```{=html}
<title>
```
or `<description>`{=html} element.\
\
`<item>`{=html} elements:\
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td>
```
Element
```{=html}
</td>
```
```{=html}
<td>
```
Description
```{=html}
</td>
```
```{=html}
<td>
```
Example
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
<title>
```
```{=html}
</td>
```
```{=html}
<td>
```
Title of the item
```{=html}
</td>
```
```{=html}
<td>
```
Iraq Declares State of Emergency as Insurgents Step Up Attacks
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<link>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
The URL to the item
```{=html}
</td>
```
```{=html}
<td>
```
http://www.nytimes.com/2004/11/07/international/middleeast/07cnd-iraq.html
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<description>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Brief description of the item
```{=html}
</td>
```
```{=html}
<td>
```
Today\'s attacks, including three police post raids that killed 21, came
a day after insurgents killed at least 30.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<author>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Author\'s name and/or author\'s email address
```{=html}
</td>
```
```{=html}
<td>
```
[email protected] (Edward Wong)
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<pubDate>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Date/time the item was published
```{=html}
</td>
```
```{=html}
<td>
```
Sun, 07 Nov 2004 00:00:00 EDT
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<guid>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
Is a string that uniquely identifies the item. Can be used by the
aggregator to determine if an item is new.
```{=html}
</td>
```
```{=html}
<td>
```
http://www.nytimes.com/2004/11/07/international/middleeast/07cnd-iraq.html
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
Others include:\
source, enclosure, category, and comments.(see at Harvard
Law).\
\
An item can either be a child or a sibling of a channel.
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<tr>
```
```{=html}
<td>
```
*\"child\"*
: `<span style="color:Red;">`{=html}`<channel>`{=html}`</span>`{=html}
: \...
: `<span style="color:Blue;">`{=html}`<item>`{=html}`</span>`{=html}
: \.....
: `<span style="color:Blue;">`{=html}`</item>`{=html}`</span>`{=html}
: `<span style="color:Red;">`{=html}`</channel>`{=html}`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
*\"sibling\"*
: `<span style="color:Red;">`{=html}`<channel>`{=html}`</span>`{=html}
: \...
: `<span style="color:Red;">`{=html}`</channel>`{=html}`</span>`{=html}
: `<span style="color:Red;">`{=html}`<item>`{=html}`</span>`{=html}
: \.....
: `<span style="color:Red;">`{=html}`</item>`{=html}`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
More optional elements visit RSS 2.0
Specification
## How does it work?
RSS can be divided into two parts; the reader/ag and the feed. The
reader is the program that reads and presents the RSS feed in an
understandable format. The feed is the website with its RSS file. RSS
feeds are typically identified on webpages with an orange rectangle
icon, or an orange icon with the letters RSS written on it. To view the
XML code, you simply have to click on the icon.
### Creating an RSS feed
A website author can establish a RSS feed for itself in different ways;
either by doing it manually, by using software or by online services.
Most large websites use content management software to produce their RSS
feed. Every time a change is made on their website, the content
management software produce a RSS file of the changes with the new items
added and old items removed.
### Subscribing to an RSS feed
As a RSS subscriber you need a RSS aggregator. By feeding a RSS link,
the aggregator will search for information you subscribed and display
them. Say that you subscribe on the sport section in the New York Times;
each time the NY Times publish a new sport article the article's
headlines, description and the URL will be displayed on your computer.
Whenever you are online, the aggregator will search out and sort your
list of interests and display them.
### RSS Aggregators
RSS aggregator (aka RSS Reader) is an application that is used to
collect, update and display RSS feeds. Below is a list of some RSS
aggregators for different platforms that the aggregator will work
properly on.
- FeedReader - Windows
- Sharp
Reader -
Windows(.NET)
- NetNewsWire - Macintosh
- Straw - Linux
- Bloglines - Server-based
- NewsHutch - Server-Based
Some others include:
- AmphetaDesk - Windows,
Macintosh, Linux
- FeedDemon - Windows
- FeedReader - Windows
- NewsGator - Windows(.NET)
- RSS NewsWatcher - Windows
- Radio Userland -
Windows, Macintosh
- SlashDock -
Macintosh
- PocketFeed -
PocketPC
\
## Future of RSS
The future of RSS seems very promising as version 2.0 has become
extremely popular with the Internet industry and somewhat the standard
of the RSS versions. Yahoo recently released its new version of Yahoo
Maps and the API is based on georRSS version 2.0. This version of Yahoo
Maps allows users to edit the information on the maps, which makes the
Maps and Local Search products more effective. RSS version 2.0 is also
very popular with distributing podcasts to the subscriber base along
with distributing content Google's blogger product. Furthermore, RSS is
being utilized in an innovative way for search engine marketers to
submit time sensitive content to the engines. The Mozilla Firefox
browser already contains an internal RSS aggregator that allows users to
view RSS news and blog headlines in the bookmark toolbar or bookmark
menu. This is accomplished through the Mozilla Firefox feature named
"Live Bookmarks". RSS has quickly become a mainstream technology in a
relatively short period and has definitely become a major player in the
Internet space.
## Use RSS on Firefox
## Summary
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Now, RSS is commonly used in areas such as, websites and blogs, with version 2.0 being the most popular standard. RSS feeds are typically identified on webpages with an orange rectangle icon, or an orange icon with the letters RSS written on it. To view the XML code, you simply have to click on the icon.
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
## Exercises
## Answers
## References
Technology at Harvard Law - Internet technology hosted by Berkman
Center - RSS 2.0 Specification\
Dive-into-XML by Mark Pilgrim - What is
RSS?\
Mozilla Firefox - Live
Bookmarks\
Apple - PodCasting\
RSS INFO - RSS info\
USA Today - USA Today\
|
# XML - Managing Data Exchange/Namespace
## Learning Objectives
Upon completion of this chapter, you will:
- be able to understand what XML Namespace is and its purpose
- be able to recognize XML Namespace structure and what each part is
doing
- be able to think of organizations in which Namespace would be
necessary
## What is Namespace?
An XML namespace is a collection of names that are identified by a
Uniform Resource Identifier (URI) reference, which are used in XML
documents as element types and attribute names. URIs were used simply
because they are a well-known system for creating unique identifiers.
Namespaces consist of several parts including local names, namespace
URIs, prefixes and declarations. The combination of a local name and a
namespace is called a universal name. You might find it easier to think
of a namespace as a **dictionary** that is a source of definitions for
items that you use within an XML document.
All schemas include the namespace
<http://www.w3.org/2001/XMLSchema-instance>. You can think of this as
the master dictionary to which all schemas must refer because it defines
the fundamental items of an XML schema. The namespace\'s address looks
like a URL, but in XML we use the broader term Uniform Resource
Identifier
(URI).
Because a document can refer to multiple namespace, we need a convenient
short form for referencing the namespace. One of the common forms used
is **xsd** as illustrated in the following.
`xmlns:xsd="``http://www.w3.org/2001/XMLSchema-instance``"`
The *xlmns* informs XML that you are referencing a name space, and the
*xsd* indicates this is the short form of the namespace.
For example, you might use the following line of code in an XML schema
`<xsd:element name="item" type="xsd:string">`{=html}
The previous line of code states that the definition of element name and
string are found in \"<http://www.w3.org/2001/XMLSchema-instance>\"
Namespace enables you to use elements described in multiple schemas
within your XML document, so the short form of a namespace\'s URI is
useful for identifying the namespace to which you are referring.
## History
Namespace in XML was a new W3C recommendation in January, 1999.
Namespace was created to be a pretty simple method to distinguish names
used in XML documents. The main purpose of Namespace is to provide
programmers a method for which to grab elements and attributes that they
want, leaving behind other tags that they do not need. These
programmer-friendly names will be unique across the Internet. The XML
namespaces recommendation does not define anything except a two-part
naming system for element types and attributes.
For additional information regarding the W3C recommendation, follow this
link: <http://www.w3.org/TR/REC-xml-names/>.
## When would you use Namespace?
It would mainly be used to avoid naming conflicts. If you don't have any
duplicate elements or attributes in the XML that you use, namespaces are
not necessary. It is however beneficial if you have duplicate elements
or attributes. It basically makes two part structures that make it
unique. Instead of just defining element A, for example, you have to
define element A with some other type of identifier. That is where the
URI comes into play. The URI in combination with the element or
attribute creates your namespace and it is then a universal name.
## Namespace Structure
XML namespaces differ from the \"namespaces\" conventionally used in
computing disciplines in that the XML version has internal structure and
is not, mathematically speaking, a set.
This is an example of 2 Namespace declarations:
` ``<Organization
xmlns:addr="http://www.example.com/addresses"
xmlns="http://www.example.com/files">`{=html}` `
The first declaration associates the addr prefix with the
"www.example.com/addresses" URI. The second declaration defines
www.example.com/files as the default namespace. If there is not a prefix
defined for that element, a default namespace is applied. This default
namespace is applied to all elements without a prefix. Please note,
however, that default namespaces do not apply directly to attributes.
## How Does It Work?
When specifying a universal name in an XML document, you use an
abbreviation based on an optional prefix that\'s attached to the local
name. This abbreviation is called the qualified name or qname. To
declare an XML namespace, you use an attribute whose name has the form:
`xmlns:prefix`
These attributes are often called xmlns attributes and their value is
the name of the XML namespace being declared. This is a Uniform Resource
Identifier. The first form of the attribute (xmlns:prefix) declares a
prefix to be associated with the XML namespace. The second form (xmlns)
declares that the specified namespace is the default XML namespace.
## Namespace Best Practices
- Try to limit the number of Namespaces to about 5 per document. More
than five namespaces in a document gets unwieldy.
- Make distinctions in XML namespaces only when there are truly
distinctions between the things being named.
- Try to stick to documents in namespace normal form wherever possible
because they are simplest to read and to process.
- Avoid overriding namespaces frequently because it can cause
confusion in your documents.
## Example of Namespace Use
Let's say we are going to be pulling address values from two different
sources and address from one source pulls in a mailing address while
from the other source, it pulls in a computer IP address. We'll need to
create a Namespace so that we can distinguish the two addresses
elements.
Postal Address XML document
```{=html}
<address>
```
100 Elm St., Apt#1
```{=html}
</address>
```
IP Address XML document
```{=html}
<address>
```
172.13.5.7
```{=html}
</address>
```
How do we distinguish these Address elements in the case that they need
to be combined into the same document? We would assign each address name
to a namespace. Therefore, it becomes defined in two parts, the address
element and the XML namespace. Every time the element Address comes up,
it will have to look at two things instead of one for definition, but
this look up only has to be performed one time because the combination
is universally unique.
In this instance, we could create Namespaces for the address element:
``` xml
<Example Organization
xmlns: addr="http://www.example.com/postal_addresses"
xmlns="http://www.example.com/ip_addresses">
```
The first declaration associates the prefix \'addr\' with the URI,
\"www.example.com/postal_addresses and the second declaration sets
\"www.example.com/ip_addresses\" as the default namespace. So, where a
the prefix \'addr\' is used, it will pull the postal address and for
others, it will pull the IP address.
## Defining the location of an XML schema
Assume you have created a schema, example.xsd, that is located in the
same directory as your XML document, example.xml. In the XML document
you will indicate the location of the schema with the following code.
`<xmlns:xsi='``http://www.w3.org/2001/XMLSchema-instance``' xsi:noNamespaceSchemaLocation='example.xsd'>`
Of course, if example.xsd is stored somewhere other than the same
directory as example.xml, you specify the full path.
## Potential Problems with Namespace
- Different XML technologies are going to process namespaces
differently. Some will see namespace declarations as such and some
will just see them as attributes.
- Namespace is a compromise solution that doesn\'t meet the needs of
all users.
- XML namespaces seem simple on their face, but they can cause real
confusion and increased complexity if they are not handled or
managed correctly. To manage Namespaces correctly, you must
understand thoroughly the meaning, rules, and implications of the
various concepts that make up the XML namespaces mechanism and stick
consistently to simple conventions.
- As mentioned in Best Practices, using more than 5 namespaces can get
unwieldy. So, how do large organizations tackle this design
difficulty if there is a need for many namespaces? The basic source
of this problem is that naming convention for most information
architecture is fundamental, but with XML, it was patched together
as an afterthought. Namespaces have been very difficult to
incorporate smoothly.
fr:Programmation XML/Espace de
nom
|
# XML - Managing Data Exchange/Business Intelligence and XML
## Learning objectives
Upon completion of this chapter, for a single entity you will be able to
- create a report specification entirely in XML for Cognos ReportNet
- update a report specification in XML format.
- identify four main sections in a report specification
## Introduction
Every report created in Cognos ReportNet has a specification that is
written in XML, so you can customize it using XML editor or create a
report specification entirely in XML.
## Report Specification Flow
After you save a report and open it again, the report specification is
pulled from the content store as you can see in Figure 28.1. When you
edit it, the changes remain local on the client machine until you save
it. When you save the report, the content store is updated.
Figure 28.1 Report Specification Flow
You can see a sample of web report in figure 28.2 and this report can be
generated from XML file;
Figure 28.2 Sample of a report
## XML in Report Specification Structure
A report specification consists of four main sections.
- Report Section
- XML Tag:
- `<report>`{=html}
- `<modelConnection>`{=html}
- Query Section
- XML Tag:
- `<querySet>`{=html}
- Layout Section
- XML Tag:
- `<layoutList>`{=html}
- Variable Section
- XML Tag:
- ```{=html}
<variableList>
```
At minimum, a report specification must include the
`<report>`{=html}`</report>`{=html} tags, as well as authoring language
and schema information.
The specification header in Report Section includes information about:
- authoring language, "en-us" indicates American English. You can use
other language than English for the report
- namespace : <http://developer.sample.com/schemas/report/1>
- package name: GSR
- model version : \@name=\'model\'
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<TR>
```
```{=html}
<TD bgcolor="lightyellow">
```
`<report xml:lang="en-us" xmlns="http://developer.sample.com/schemas/report/1/">`{=html}
` ``<modelConnection name="/content/package[@name='GSR']/model[@name='model']"/>`{=html}
```{=html}
</pre>
```
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</table>
```
The query section includes information about:
- Cube elements are indicated by the `<cube>`{=html}`</cube>`{=html}
tags which can contain:
- facts (`<factList>`{=html}`</factList>`{=html}. Country, First
Name and Last Name are the facts.
- dimensions (`<dimension>`{=html}`</dimension>`{=html})
consisting of levels(`<level>`{=html}`</level>`{=html})
- filters (`<filter>`{=html}`</filters>`{=html} consiting of
conditions(`<condition>`{=html}`</conditions>`{=html}). Country
is the filter for this report, which is equal to Germany.
- Tabular model is contained in the
`<tabularModel>`{=html}`</tabularModel>`{=html} tags.
- Each tabular model contains data items
(`<dataItem>`{=html}`</dataItem>`{=html}) consisting of fully
qualified expressions
(`<expression>`{=html}`</expression>`{=html})
- The query section of a report is contained in the
`<querySet>`{=html}`</querySet>`{=html}tags.
- The query section can include multiple queries, each of which is
contained in the `<BIQuery>`{=html}`</BIQuery>`{=html}tags.
Add pages to a report specification:
- You can add many pages to a report. Each page is outlined between
the `<pageSet>`{=html} `</pageSet>`{=html}tags.
- Each page can consist of :
- a body ( mandatory)
- a header
- a footer
Add layout objects to a report:
- Once you have added one or more pages to the report layout, you can
add a variety of layout objects, such as :
- Text items
- Blocks
- Lists
- Charts
- Crosstabs
- Tables
Specify styles for layout objects:
- You can use Cascading Style Sheets (CSS) attributes to determine the
look and feel of objects in the layout.
- CSS values are specified between the
```{=html}
<style>
```
```{=html}
</style>
```
tags.
- CSS values can apply to things like font sizes, background colors,
and so forth.
Add Variables to a Report:
- You can specify variables between the
```{=html}
<variableList>
```
```{=html}
</variableList>
```
tags of the report specification., and each of variable includes an
expression between the `<expression>`{=html}`</expression>`{=html}
tags.
- We can use Variable 1 that contains a list of possible values,
example value: fr for using French language;
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<TR>
```
```{=html}
<TD bgcolor="lightyellow">
```
```{=html}
<variableList>
```
` ``<variable name=”Variable1” type=”locale”>`{=html}\
` ``<expression>`{=html}`ReportLocale()``</expression>`{=html}\
` ``<variableValueList>`{=html}\
` ``<variableValue value=”fr”/>`{=html}\
` ``</varialeValueList>`{=html}\
` ``</variable>`{=html}\
` `
```{=html}
</variableList>
```
```{=html}
</pre>
```
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
Below is the complete XML file for the report in Figure 28.3
```{=html}
<table width="100%" border="1" cellspacing="0" cellpadding="0">
```
```{=html}
<TR>
```
```{=html}
<TD bgcolor="lightyellow">
```
<report xml:lang="en-us" xmlns="http://developer.sample.com/schemas/report/1/">
<!--RS:1.1-->
<modelConnection name="/content/package[@name='GSR']/model[@name='model']"/>
<querySet xml:lang="en-us">
<BIQuery name="Query1">
<cube>
<factList>
<item refItem="Country" aggregate="none"/>
<item refItem="First name" aggregate="none"/>
<item refItem="Last name" aggregate="none"/>
</factList>
</cube>
<tabularModel>
<dataItem name="Country" aggregate="none">
<expression>[gsrs].[addr].[Country]</expression>
</dataItem>
<dataItem name="First name" aggregate="none">
<expression>[gsrs].[Person].[First name]</expression>
</dataItem>
<dataItem name="Last name" aggregate="none">
<expression>[gsrs].[Person].[Last name]</expression>
</dataItem>
<filter>
<condition>[gsrs].[addr].[Country]='Germany'</condition>
</filter>
</tabularModel>
</BIQuery>
</querySet>
<layoutList>
<layout>
<pageSet>
<page name="Page1">
<pageBody>
<list refQuery="Query1">
<listColumnTitles>
<listColumnTitle>
<textItem>
<queryItemRef refItem="Country" content="label"/>
</textItem>
</listColumnTitle>
<listColumnTitle>
<textItem>
<queryItemRef refItem="First name" content="label"/>
</textItem>
</listColumnTitle>
<listColumnTitle>
<textItem>
<queryItemRef refItem="Last name" content="label"/>
</textItem>
</listColumnTitle>
</listColumnTitles>
<listColumns>
<listColumn>
<textItem>
<queryItemRef refItem="Country"/>
</textItem>
</listColumn>
<listColumn>
<textItem>
<queryItemRef refItem="First name"/>
</textItem>
</listColumn>
<listColumn>
<textItem>
<queryItemRef refItem="Last name"/>
</textItem>
</listColumn>
</listColumns>
<style>
<CSS value="border-collapse:collapse"/>
</style>
<XMLAttribute name="RS_ListGroupInfo" value=""/>
</list>
</pageBody>
<pageHeader>
<block class="reportTitle">
<textItem class="reportTitleText">
<text/>
</textItem>
</block>
<style>
<CSS value="padding-bottom:10px"/>
</style>
</pageHeader>
<pageFooter>
<table>
<tableRow>
<tableCell>
<textItem>
<expression>AsOfDate()</expression>
</textItem>
<style>
<CSS value="vertical-align:top;text-align:left;width:25%"/>
</style>
</tableCell>
<tableCell>
<textItem>
<text>- </text>
</textItem>
<textItem>
<expression>PageNumber()</expression>
</textItem>
<textItem>
<text> -</text>
</textItem>
<style>
<CSS value="vertical-align:top;text-align:center;width:50%"/>
</style>
</tableCell>
<tableCell>
<textItem>
<expression>AsOfTime()</expression>
</textItem>
<style>
<CSS value="vertical-align:top;text-align:right;width:25%"/>
</style>
</tableCell>
</tableRow>
<style>
<CSS value="border-collapse:collapse;width:100%"/>
</style>
</table>
<style>
<CSS value="padding-top:10px"/>
</style>
</pageFooter>
</page>
</pageSet>
</layout>
</layoutList>
</report>
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
```{=html}
<table width="100%" border="1" bgcolor="lightgreen">
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<b>`{=html} `<span style="color:SaddleBrown;">`{=html}Section summary:
As Report Specification sticks to XML Rules it is favored for creating
and updating a markup file`</span>`{=html} `</b>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
### Exercise
The end user wants to read the report in Japanese language, so you have
to add a variable for Japanese language.
### Answers
|
# XML - Managing Data Exchange/Handling XML with MySQL
**Author:** Shayla S. Lee 01:39, 15 November
2005 (UTC)
## Introduction
**MySQL** is an open source relational database that supports XML. You
can use the MySQL command line or a programming language of your choice
to convert your MySQL databases and or tables to a well formed XML
document.
### Supported Versions
XML is supported in MySQL version 3.23.48 and higher. A free version of
MySQL can be downloaded from MySQL.com.
### Using the MySQL Command Line
Use the \--xml or -X option with either the mysqldump or mysql command
to produce XML output.
**mysqldump Syntax:**
`mysqldump --xml -u username -p databasename [tablename] > filename.xml`
**mysql Syntax:**
`\T "filename.xml"`\
`mysql -X -u username -p databasename [tablename]`
**OR**
`\T "filename.xml"`\
`mysql -X -u username -p databasename tablename -e`\
`'select columnname, columnname`\
` from tablename'`
In the latter mysql syntax example, you can also specify a where
condition as well as restrict the where condition just as you would in a
regular sql select statement.
**Explanation of commands and options:**
**mysqldump** is a mysql output command.
**\\T** is a mysql output command.
**-e** is a mysql option that tells mysql to execute the following
select statement.
**\--xml** is the mysql option for producing XML output.
**-u** is a mysql option which tells mysql that the next command line
item is your username.
**username** is your mysql username. It will be used to authenticate you
to the mysql database.
**-p** is a mysqldump option that tells mysql that the next command line
item is your password. If do not want your password to be visible on the
command line, then do not supply your password after the -p option and
mysql will prompt you for it later.
**databasename** is the name of the database that you want to output to
xml.
**tablename** is the name of the table that you want to output to xml.
Supplying the tablename is optional.
The **\>** symbol is the output symbol that tells mysql to output the
results to the following filename.
**filename.xml** is the filename that you want to output the XML
results.
|
# XML - Managing Data Exchange/XML Encryption
**Author**: Shayla S. Lee 02:38, 15 November
2005 (UTC)
## Introduction
XML encryption was developed to address two common areas not addressed
by the Transport Layer Security and Secure Socket Layer protocol
(TLS/SSL). TLS/SSL is a very secure and reliable protocol that provides
end-to-end security sessions between two parties. XML adds an extra
layer of security to TLS/SSL by encrypting part or all of the data being
exchanged and by allowing for secure sessions between more than two
parties. In other words, each party can maintain secure or insecure
sessions with any of the communicating parties, and both secure and
non-secure data can be exchanged in the same document. Furthermore, XML
encryption can handle both XML and non-XML (e.g. binary) data.
## Encryption Syntax
All XML encrypted files must start with the following XML preamble,
declaration, internal entity, and import.
`Schema Definition:`\
` `
```{=html}
<?xml version="1.0" encoding="utf-8"?>
```
` <!DOCTYPE schema PUBLIC "-//W3C//DTD XMLSchema 200102//EN"`\
` "``http://www.w3.org/2001/XMLSchema.dtd``"`\
` `\
` <!ATTLIST schema`\
` xmlns:xenc CDATA #FIXED '`[`http://www.w3.org/2001/04/xmlenc#``'`\
` xmlns:ds CDATA #FIXED '``http://www.w3.org/2000/09/xmldsig#``'>`\
` <!ENTITY xenc '``http://www.w3.org/2001/04/xmlenc#``'>`\
` <!ENTITY % p ''>`\
` <!ENTITY % s ''>`\
` ]>`\
` `\
` ``<schema xmlns='http://www.w3.org/2001/XMLSchema' version='1.0'
xmlns:ds='http://www.w3.org/2000/09/xmldsig#'
xmlns:xenc='http://www.w3.org/2001/04/xmlenc#'
targetNamespace='http://www.w3.org/2001/04/xmlenc#'
elementFormDefault='qualified'>`{=html}\
` ``<import namespace='http://www.w3.org/2000/09/xmldsig#'
schemaLocation='http://www.w3.org/TR/2002/REC-xmldsig-core-20020212/xmldsig-core- schema.xsd'/>`{=html}
### EncryptedType Element
**EncryptedType** is the abstract type from which EncryptedData and
EncryptedKey are derived.
` Schema Definition:`\
` ``<complexType name='EncryptedType' abstract='true'>`{=html}\
` ``<sequence>`{=html}\
` ``<element name='EncryptionMethod' type='xenc:EncryptionMethodType'
minOccurs='0'/>`{=html}\
` ``<element ref='ds:KeyInfo' minOccurs='0'/>`{=html}\
` ``<element ref='xenc:CipherData'/>`{=html}\
` ``<element ref='xenc:EncryptionProperties' minOccurs='0'/>`{=html}\
` ``</sequence>`{=html}\
` ``<attribute name='Id' type='ID' use='optional'/>`{=html}\
` ``<attribute name='Type' type='anyURI' use='optional'/>`{=html}\
` ``<attribute name='MimeType' type='string' use='optional'/>`{=html}\
` ``<attribute name='Encoding' type='anyURI' use='optional'/>`{=html}` `\
` ``</complexType>`{=html}
**Syntax Explanation**
**EncryptionMethod** is an optional element that describes the
encryption algorithm applied to the cipher data. If the element is
absent, the encryption algorithm must be known by the recipient or the
decryption will fail.
`<element name='EncryptionMethod' type='xenc:EncryptionMethodType'
minOccurs='0'/>`{=html}
**ds:KeyInfo** is an optional element that carries information about the
key used to encrypt the data. Subsequent sections of this specification
define new elements that may appear as children of ds:KeyInfo.
`<element ref='ds:KeyInfo' minOccurs='0'/>`{=html}
**CipherData** is a mandatory element that contains the CipherValue or
CipherReference with the encrypted data.
`<element ref='xenc:CipherData'/>`{=html}
**EncryptionProperties** can contain additional information concerning
the generation of the EncryptedType (e.g., date/time stamp).
`<element ref='xenc:EncryptionProperties' minOccurs='0'/>`{=html}
**Id** is an optional attribute providing for the standard method of
assigning a string id to the element within the document context.
`<attribute name='Id' type='ID' use='optional'/>`{=html}
**Type** is an optional attribute identifying type information about the
plaintext form of the encrypted content. While optional, this
specification takes advantage of it for mandatory processing in
dycryption. If the EncryptedData element contains data of Type
\'element\' or element \'content\', and replaces that data in an XML
document context, it is strongly recommended the Type attribute be
provided. Without this information, the decryptor will be unable to
automatically restore the XML document to its original cleartext form.
`<attribute name='Type' type='anyURI' use='optional'/>`{=html}
**MimeType** is an optional (advisory) attribute which describes the
media type of the data which has been encrypted. The value of this
attribute is a string with values defined by \[MIME\]. For example, if
the data that is encrypted is a base64 encoded PNG, the transfer
Encoding may be specified as
\'<http://www.w3.org/2000/09/xmldsig#base64>\' and the MimeType as
\'image/png\'. This attribute is purely advisory; no validation of the
MimeType information is required and it does not indicate the encryption
application must do any additional processing. Note, this information
may not be necessary if it is already bound to the identifier in the
Type attribute. For example, the Element and Content types defined in
this specification are always UTF-8 encoded text.
`<attribute name='MimeType' type='string' use='optional'/>`{=html}
### EncryptionMethod Element
**EncryptionMethod** is an optional element that describes the
encryption algorithm applied to the cipher data. If the element is
absent, the encryption algorithm must be known by the recipient or the
decryption will fail. The permitted child elements of the
EncryptionMethod are determined by the specific value of the Algorithm
attribute URI.
`Schema Definition:`\
` ``<complexType name='EncryptionMethodType' mixed='true'>`{=html}\
` ``<sequence>`{=html}\
` ``<element name='KeySize' minOccurs='0' type='xenc:KeySizeType'/>`{=html}\
` ``<element name='OAEPparams' minOccurs='0' type='base64Binary'/>`{=html}\
` ``<any namespace='##other' minOccurs='0' maxOccurs='unbounded'/>`{=html}\
` ``</sequence>`{=html}\
` ``<attribute name='Algorithm' type='anyURI' use='required'/>`{=html}\
` ``</complexType>`{=html}
### CipherData Element
**CipherData** is a mandatory element that provides the encrypted data.
It must either contain the encrypted octet sequence as base64 encoded
text of the CipherValue element, or provide a reference to an external
location containing the encrypted octet sequence via the CipherReference
element.
`Schema Definition:`\
` ``<element name='CipherData' type='xenc:CipherDataType'/>`{=html}\
` ``<complexType name='CipherDataType'>`{=html}\
` ``<choice>`{=html}\
` ``<element name='CipherValue' type='base64Binary'/>`{=html}\
` ``<element ref='xenc:CipherReference'/>`{=html}\
` ``</choice>`{=html}\
` ``</complexType>`{=html}
### CipherReference Element
**CipherReference** identifies a source which, when processed, yields
the encrypted octet sequence CipherReference is used when CipherValue is
not supplied directly. The actual value is obtained as follows. The
CipherReference URI contains an identifier that is dereferenced. Should
the CipherReference element contain an OPTIONAL sequence of Transforms,
the data resulting from dereferencing the URI is transformed as
specified so as to yield the intended cipher value. For example, if the
value is base64 encoded within an XML document; the transforms could
specify an XPath expression followed by a base64 decoding so as to
extract the octets.
`Schema Definition:`\
` ``<element name='CipherReference' type='xenc:CipherReferenceType'/>`{=html}\
` ``<complexType name='CipherReferenceType'>`{=html}\
` ``<sequence>`{=html}\
` ``<element name='Transforms' type='xenc:TransformsType' minOccurs='0'/>`{=html}\
` ``</sequence>`{=html}\
` ``<attribute name='URI' type='anyURI' use='required'/>`{=html}\
` ``</complexType>`{=html}
` ``<complexType name='TransformsType'>`{=html}\
` ``<sequence>`{=html}\
` ``<element ref='ds:Transform' maxOccurs='unbounded'/>`{=html}` `\
` ``</sequence>`{=html}\
` ``</complexType>`{=html}
**Cipher Reference with Optional Tranform feature and Tranform
Algorithm:**
`<CipherReference URI="http://www.example.com/CipherValues.xml">`{=html}\
` ``<Transforms>`{=html}\
` ``<ds:Transform
Algorithm="http://www.w3.org/TR/1999/REC-xpath-19991116">`{=html}\
` ``<ds:XPath xmlns:rep="http://www.example.org/repository">`{=html}\
` self::text()[parent::rep:CipherValue[@Id="example1"]]`\
` ``</ds:XPath>`{=html}\
` ``</ds:Transform>`{=html}\
` ``<ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#base64"/>`{=html}\
` ``</Transforms>`{=html}\
` ``</CipherReference>`{=html}
### EncryptedData Element
**EncryptedData** is the core element in the syntax. Not only does its
CipherData child contain the encrypted data, but it\'s also the element
that replaces the encrypted element, or serves as the new document root.
`Schema Definition:`\
` ``<element name='EncryptedData' type='xenc:EncryptedDataType'/>`{=html}\
` ``<complexType name='EncryptedDataType'>`{=html}\
` ``<complexContent>`{=html}\
` ``<extension base='xenc:EncryptedType'>`{=html}\
` ``</extension>`{=html}\
` ``</complexContent>`{=html}\
` ``</complexType>`{=html}
## Resources
The information above was obtained from W3C and IBM. For more
information, please visit the following links:
`http://www.w3.org/TR/2002/CR-xmlenc-core-20020802/#sec-Encryption-Syntax`\
`http://www-128.ibm.com/developerworks/xml/library/x-encrypt/`
|
# XML - Managing Data Exchange/XQL
## Learning Objectives
- What is XQL?
- What is an XQL Query?
- Tutorial
- What are the different components of XQL?
## Introduction
As more and more information is either stored in XML, exchanged in
` XML, or presented as XML through various interfaces, the ability to`\
` intelligently query our XML data sources becomes increasingly important. XML`\
` documents are structured documents – they blur the distinction between`\
` data and documents, allowing documents to be treated as data sources, and`\
` traditional data sources to be treated as documents.`
XQL is a query language designed specifically for XML. In the same
` sense that SQL is a query language for relational tables and OQL is a query`\
` language for objects stored in an object database, XQL is a query language for`\
` XML documents. The basic constructs of XQL correspond directly to the basic`\
` structures of XML, and XQL is closely related to XPath, the common locator`\
` syntax used by XSL and XPointers. Since queries, transformation patterns, and`\
` links are all based on patterns in structures found in possible XML documents,`\
` a common model for the pattern language used in these three applications is`\
` both possible and desirable, and a common syntax to express the patterns`\
` expressed by that model simplifies the task of the user who must master a`\
` variety of XML-related technologies. Although XQL originated before XSL`\
` Patterns, there were strong similarities between the two languages, and we have`\
` adopted XPath syntax for the constructs which differed. Not all constructs`\
` found in XPath were needed for queries, and some constructs used in XQL are not`\
` found in XPath, but the two languages share a common subset. `
The XQL language described in this chapter contains several features not
` found in previously published versions of the language, including joins, links,`\
` text containment, and extensible functions. These new features are inspired in`\
` large part by discussions stemming from the W3C QL '98 Workshop, and make it`\
` possible to combine information from heterogeneous data sources in powerful`\
` ways. Great care has been made to maintain the fundamental simplicity of XQL`\
` while adding these features.`
This chapter is intended as input for the upcoming W3C Query Language
` Activity, and for the further development of XPath.`
## XML Query Language
Traditionally, structured queries have been used primarily for
` relational or object oriented databases, and documents were queried with`\
` relatively unstructured full-text queries. Although quite sophisticated query`\
` engines for structured documents have existed for some time, they have not been`\
` a mainstream application. In the last year, a number of very different`\
` approaches to querying XML have been proposed, with several distinct`\
` perspectives on what constitutes a query. Several particularly interesting`\
` proposals have come from the semi-structured database community, including`\
` XML-QL and Lorel, and adopt semi-structured approaches to XML. This proposal`\
` incorporates several ideas from those languages into XQL.`
XQL was designed to be used in a number of different XML environments,
` using a syntax that may be used in XML attributes, embedded in programming`\
` languages, or incorporated in URIs. From the beginning, we have endeavored to`\
` keep the language simple and small, and we have been careful not to add`\
` functionality that would make it difficult to implement XQL. During the last`\
` year, we have been persuaded to add several powerful new features that allow`\
` users to combine information from multiple sources, use the relationships`\
` expressed in links as part of a query, and search based on text containment.`\
` Queries that can make use of information in multiple documents allow the`\
` information contained in those documents to be reused in ways not foreseen by`\
` the people who created the original documents. This is extremely useful when`\
` many documents or data sources may each contain part of the information needed`\
` on a given topic. For instance, suppose one document contains a set of`\
` recommended books for a given course of study, another lists books and prices`\
` for a store, and third contains a set of reviews of books. A query can be`\
` constructed to list recommended books, their prices, and the reviews they have`\
` received. `
XQL is closely related to XPath, and we hope to be able to maintain
` compatibility with XPath as it evolves. We see XQL as complementary to XSLT,`\
` which may be used for sophisticated reshaping and formatting of query results.`\
` `
## XML as a Data Model
An important motivation for the design of XQL is the realization
` that XML has its own implied data model, which is neither that of traditional`\
` relational databases nor that of object oriented or object-relational`\
` databases. In XQL, a document is an ordered, labelled tree, with nodes to`\
` represent the document entity, elements, attributes, processing instructions,`\
` and comments. The model is compatible with the `\
` XML Information Set `\
` (http://www.w3.org/XML/Group/1999/04/WD-xml-infoset-19990428.html).`\
` `
It is important to note that the relationships among data contain a
` large proportion of the information contained in a document, which is one of`\
` the reasons that structured document formats like XML are useful in the first`\
` place. The original formulation of XQL was based completely on the tree`\
` structure of XML documents:`
1. Hierarchy
1. parent/child
2. ancestor/descendant
2. Sequence (within a sibling list or in document order)
3. Position (within a sibling list or in document order)
1. absolute
2. relative
3. ranges
These relationships have long been basic to the XPointer model, and
` are now reflected in XPath in the form of axes. In XQL, all queries use the`\
` child axis, so we will speak in terms of parent/child and ancestor/descendant`\
` relationships rather than use the term ``<b>`{=html}`Locator Path``</b>`{=html}` from the XPath`\
` Working Draft.`
The current draft extends this model to support the following:
1. Ad-hoc relationships established via joins
2. Dereferencing of links
Joins allow subtrees of documents to be combined in queries; links
` allow queries to support references as well as tree structure.`
## What is an XML Query?
In XQL, a query returns XML document nodes from one or more XML
` documents. To examine the characteristics of an XQL query, it is useful to`\
` consider four basic questions about the environment in which a query takes`\
` place: `\
` `
1. ` What is a database? `\
` `
2. ` What is the query language? `\
` `
3. ` What is the input to a query? `
4. ` What is the result of a query? `\
` `
The following table provides a brief answer to each of these
` questions, including a comparison with the SQL query language, which is widely`\
` used for querying relational databases:`
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
SQL
```{=html}
</td>
```
```{=html}
<td>
```
XQL
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
The database is a set of tables.
```{=html}
</td>
```
```{=html}
<td>
```
The database is a set of one or more XML documents.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Queries are done in SQL, a query language that uses the
` structure of tables as a basic model.`
```{=html}
</td>
```
```{=html}
<td>
```
Queries are done in XQL, a query language that uses the
` structure of XML documents as a basic model.`
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
The FROM clause determines the tables which are examined by
` the query.`
```{=html}
</td>
```
```{=html}
<td>
```
A query is given a list of input nodes from one or more
` documents. `
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
The result of a query is a table containing a set of rows;
` this table may serve as the basis for further queries. `
```{=html}
</td>
```
```{=html}
<td>
```
The result of a query is a list of XML document nodes, which
` may serve as the basis for further queries. `
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
From the preceding table, it should be clear that document nodes
` play a central role in XQL queries. These nodes are an abstraction. Any real`\
` XQL implementation will find some concrete way to implement the nodes used in`\
` queries. For instance, XQL engines may represent the input to a query via DOM`\
` nodes, XSL nodes, index structures, or XML text. Any of these might also be`\
` used to represent the results of queries; in addition, hyperlinks or other`\
` references into the original document might be used, a new virtual document`\
` might be created, or DOM Level Two TreeWalkers or Iterators might be used.`
The nodes which form the input to a query may come from a variety of
` different sources. They may be the result of a prior query, the contents of a`\
` document repository, the nodes from a Document Object Model Nodelist, or any`\
` other source that identifies nodes from one or more documents. XQL does not`\
` specify how these nodes are brought to the query. Current XQL implementations`\
` take a variety of approaches, including the following: using Document Object`\
` Model subtrees as the basis for a query, querying whole documents supplied as`\
` the input to a Unix-style pipe, reading a document from the command line, using`\
` data dictionaries or repository directory structures to identify nodes to be`\
` queried, and identifying documents using a URL. This proposal adds support for`\
` merging information from heterogeneous data sources using joins.`
In XQL, nodes have identity, and they retain their identity,
` containment relationships, and sequence in query results. Grouping operators`\
` allow levels of a tree to be omitted, while still retaining the relative`\
` sequence and containment of the nodes which are returned by a query. Joins`\
` allow subtrees from one data source to be inserted into another document`\
` subtree, subject to the join conditions. Link functions are similar to joins,`\
` allowing a hypertext link in a document to be replaced by the node or nodes to`\
` which it refers. Some functions in XQL return values, which may be boolean,`\
` integer, or string. These values are also treated as nodes in the query model.`\
` `
## XQL Tutorial
Before going into further detail, we feel it would be helpful to
` present some typical XQL queries to help convey a feeling for the language.`\
` This tutorial discusses the simplest XQL queries, which are also likely to be`\
` the most common. In this tutorial, we will present a quick overview of XQL`\
` without taking the time to be precise. `
A simple string is interpreted as an element name. For instance,
` this query specification returns all <table> elements:`
` ``table`
The child operator (\"/\") indicates hierarchy. This query
` specification returns <author> elements that are children of`\
` <front> elements: `
` ``front/author`
The root of a document may be indicated by a leading \"/\"
` operator: `
` ``/novel/front/author`
> `<b>`{=html}Ed. Note: `</b>`{=html}
>
> ` In XQL, the root of a document refers to the document entity, in`\
> ` the technical XML sense, which is basically equivalent to the document itself.`\
> ` It is not the same as the root element, which is the element that contains the`\
> ` rest of the elements in the document. The document root always contains the`\
> ` root element, but it may also contain a doctype, processing instructions, and`\
> ` comments. In this example,<novel> would be the root element. `\
> ` `
Paths are always described from the top down, and unless otherwise
` specified, the right-most element on the path is returned. For instance, in the`\
` above example, <author> elements would be returned. `
The content of an element or the value of an attribute may be specified
` using the equals operator ("="). The following returns all authors`\
` with the name "Theodore Seuss Geisel" that are children of the`\
` <front> element:`
` ``front/author='Theodore Seuss Geisel'`
Attribute names begin with \"@\". They are treated as children of
` the elements to which they belong:`
` ``front/author/address/@type='email'`
The descendant operator (\"//\") indicates any number of intervening
levels. The following shows addresses anywhere within \<front\>:
`front//address`
When the descendant operator is found at the start of a path, it means
all nodes descended from the document. This query will find any address
in the document:
`//address`
The filter operator (\"\[ \]\") filters the set of nodes to its left
based on the conditions inside the brackets. The following query returns
addresses; each of these addresses must have a nattribute called
\"type\" with the value \"email\":
`front/author/address[@type='email']`
Note that\"address\[@type=\'email\'\]\" returns addresses,
but\"address/@type=\'email\'\" returns type attributes.
Multiple conditions may be combined using Boolean operators.
`front/author='Theodore Seuss Geisel'[@gender='male' and @shoesize='9EEEE']`
Brackets are also used for subscripts, which indicate position within a
document. The following refers to sections 1, 3, 4, 5, and 8, plus the
last section:
`section[1,3 to 5, 8, -1]`
Conditions and subscripts may not both occur in the same brackets, but
both uses of brackets may occur in the same query. The following refers
to the first three sections whose level attributes have the value \"3\";
in other words, it returns the first three \"level3\" sections:
`section[@level='3'][1 to 2]`
Now that we know the basics, let\'s take a look at a document and try
some XQL queries on it. The following is an invoice document.
Traditionally, invoices are often stored in databases, but invoices are
both documents and data. XQL is designed to work on both documents and
data, provided they are represented via XML through some interface. This
document will be the basis for the sample queries that follow:
<?xml version="1.0"?>
<invoicecollection>
<invoice>
<customer>
Wile E. Coyote, Death Valley, CA
</customer>
<annotation>
Customer asked that we guarantee return rights
if these items should fail in desert conditions.
This was approved by Marty Melliore, general
manager.
</annotation>
<entries n="2">
<entry quantity="2" total_price="134.00">
<product maker="ACME" prod_name="screwdriver" price="80.00"/>
</entry>
<entry quantity="1" total_price="20.00">
<product maker="ACME" prod_name="power wrench" price="20.00"/>
</entry>
</entries>
</invoice>
<invoice>
<customer> Camp Mertz </customer>
<entries n="2">
<entry quantity="2" total_price="32.00">
<product maker="BSA" prod_name="left-handed smoke shifter" price="16.00"/>
</entry>
<entry quantity="1" total_price="13.00">
<product maker="BSA" prod_name="snipe call" price="13.00"/>
</entry>
</entries>
</invoice>
</invoicecollection>
Now let\'s look at some sample queries. For these examples, we will
present query results as text, using a serialization approach described
in the section \"Query Results and Serialization\". In general, XQL
queries return lists of nodes, which may be represented in any way
convenient to the environment in which the query is performed, e.g. as
DOM nodes, serialized XML text, XPointers, hyperlinks, or by creating an
iterator to navigate the results. Since XML text is easily read, we find
it suitable as a way of representing results in our examples.
Suppose we wanted to see just the customers from the database. We could
do the following query:
Query:
`//customer`
Result:
<xql:result>
<customer> Wile E. Coyote, Death Valley, CA </customer>
<customer> Camp Mertz </customer>
</xql:result>
We might want to look at all the products manufactured by BSA. This
query would do the trick:
Query:
`//product[@maker='BSA']`
Result:
<xql:result>
<product maker="BSA" prod_name="left-handed smoke shifter" price="16.00"/>
<product maker="BSA" prod_name="snipe call" price="13.00"/>
</xql:result>
Filters are particularly useful when specifying conditions on paths that
are not the same as what is returned. For instance, the following query
returns the products ordered by Camp Mertz:
Query:
`//invoice[customer='Wile E. Coyote, Death Valley, CA']//product`
Result:
<xql:result>
<product maker="ACME" prod_name="screwdriver" price="80.00"/>
<product maker="ACME" prod_name="power wrench" price="20.00"/>
</xql:result>
This is the end of the tutorial, which covers only the most basic
features of XQL. For examples illustrating newer or more advanced
features, such as return operators, sequence, joins, references, and
user-defined functions, see the appropriate parts of the next section.
## XQLExpressions
An XQL query is always evaluated for a `<b>`{=html}context`</b>`{=html},
which is a list of document nodes. The initial context for a query is
known as the `<b>`{=html}start context`</b>`{=html}. In XQL, the nodes
in a start context may come from different documents, and even if they
are in the same document, there is no assumption that they come from
contiguous portions of the document. Some XQL operators establish a new
context in which a subexpression will be evaluated; for instance, in the
expression \"author/name\", \"author\" is evaluated in the start
context. For each author, the \"/\" operator establishes a new context
consisting of the children of that author, and \"name\" is evaluated in
that context. The operators that establish a new context are /, //, and
\[\].
> `<b>`{=html}Ed. Note: `</b>`{=html} In XSL, expressions are evaluated
> with respect to a node which is called the context node. Our use of
> the term \"context\" is intended to allow semantic consistency with
> XSL Patterns without imposing unecessary restrictions on the query
> language. As a consequence, XSL Patterns are defined in terms of
> children of the context node, and XQL queries are defined in terms of
> the context node directly. We maintain the correspondence of XSL
> Pattern definitions and XQL definitions by constructing an imaginary
> context node that contains the nodes of the context, and allowing the
> XSL term \".\" to map to this context node.
## Terms
The following expressions are `<b>`{=html}terms`</b>`{=html}, which
select particular nodes from the context based on the type or name of
the node:
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
n
```{=html}
</td>
```
```{=html}
<td>
```
element name
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context where the node type is element and the node
name is \"n\".
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\*
```{=html}
</td>
```
```{=html}
<td>
```
element name with wildcards
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context where the node type is element.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\@n
```{=html}
</td>
```
```{=html}
<td>
```
attribute name
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context where the node type is attribute and the node
name is \"n\".
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
@\*
```{=html}
</td>
```
```{=html}
<td>
```
attribute name with wildcards
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context where the node type is attribute.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
text()
```{=html}
</td>
```
```{=html}
<td>
```
text node
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context where the node type is text.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
comment()
```{=html}
</td>
```
```{=html}
<td>
```
comment
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context where the node type is comment.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
pi()
```{=html}
</td>
```
```{=html}
<td>
```
processing instruction
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context where the node type is processing instruction.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
pi(\"v\")
```{=html}
</td>
```
```{=html}
<td>
```
processing instruction with target
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context where the node type is processing instruction
and the target is \"v\".
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
.
```{=html}
</td>
```
```{=html}
<td>
```
context node
```{=html}
</td>
```
```{=html}
<td>
```
The node which is the parent to the nodes in the context - this node may
be real or imaginary.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## Namespaces and names
In XML expressions, names may be associated with namespace prefixes. A
namespace prefix can be declared using a variable declaration. In the
following query, the first line declares \"b\" to be a variable
equivalent to the namespace URL \"<http://www.TwiceSoldTales.com>\". The
second line of the query searches for all \<book\> elements belonging to
this namespace:
b := "http://www.TwiceSoldTales.com";
//b:book
An XML document may well use a different namespace prefix for the same
namespace URI. Matching is done on the basis of the namespace URI, not
the prefix associated with it in the document or in the XQL query.
XQL expressions can explicitly state whether namespaces should be taken
into account when matching node names:
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
table
```{=html}
</td>
```
```{=html}
<td>
```
Any element named \<table\>, regardless of the namespace to which it
belongs.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
html:table
```{=html}
</td>
```
```{=html}
<td>
```
Any element named \<table\> that belongs to the namespace indicated by
the prefix \"html\".
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\*
```{=html}
</td>
```
```{=html}
<td>
```
Any element, regardless of the namespace to which it belongs.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
:table
```{=html}
</td>
```
```{=html}
<td>
```
Any element named \<table\> for which no namespace has been declared.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\*:table
```{=html}
</td>
```
```{=html}
<td>
```
Any element named \<table\> for which a namespace has been declared.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
html:\*
```{=html}
</td>
```
```{=html}
<td>
```
Any element belonging to the namespace associated with the prefix
\"html\".
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
:\*
```{=html}
</td>
```
```{=html}
<td>
```
Any element for which no namespace has been declared.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\*:\*
```{=html}
</td>
```
```{=html}
<td>
```
Any element for which a namespace has been declared.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
The same conventions apply to attribute names. In attribute names, the
attribute prefix comes before the namespace prefix:
@lib:isbn
Namespaces are preserved in the output of a query. To change the
namespaces of nodes in the output, use the Renaming Operator.
## Comparisons
Comparisons add constraints based on the content or value of nodes.
Consider the following examples:
`author="Washington Irving"`
`@id="id-sec-0203"`
`text() = "Whan that Aprille with his shoures soughte"`
Regardless of the node type on the left hand of the comparison, it is
compared to the value on the right. For systems that use a schema that
supports data types, they are used in comparisons:
`books[pub_date < date("1990-01-01")]`
Since some environments in which XQL is used have restricted character
sets, e.g. URIs or queries stored in attribute values, many comparisons
have an alternative syntax that meets the syntactic constraints of these
environments. For instance, the following two queries are equivalent:
`books[pub_date < date("1990-01-01")]`
`books[pub_date lt date("1990-01-01")]`
The following comparison operators are available in XQL:
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Equality
```{=html}
</td>
```
```{=html}
<td>
```
n=\"value\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
n eq \"value\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Case insensitive comparison
```{=html}
</td>
```
```{=html}
<td>
```
n ieq \"value\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Inequality
```{=html}
</td>
```
```{=html}
<td>
```
n !=\"value\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
n ne \"value\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Text containment
```{=html}
</td>
```
```{=html}
<td>
```
n contains \"value\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Case insensitive text containment
```{=html}
</td>
```
```{=html}
<td>
```
n icontains \"value\"
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
Text comparisons support the wildcard characters \"\*\" and \"?\".
Consider the following example:
Data:
<editor>
<name>
<first> Ramesh </first>
<last> Lekshmynarayanan </last>
</name>
</editor></customer>
Query:
`//(editor contains "Leksh*")`
The value \"Leksh\*\" matches the name \"Lekshmynarayanan\", and the
\<editor\> element is returned.
The following operators may be defined in XQL environments that support
data types:
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Less than
```{=html}
</td>
```
```{=html}
<td>
```
n \< value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
n lt value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Less than or equals
```{=html}
</td>
```
```{=html}
<td>
```
n \<=value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
n lte value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Greater than
```{=html}
</td>
```
```{=html}
<td>
```
n \> value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
n gt value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Greater than or equals
```{=html}
</td>
```
```{=html}
<td>
```
n \>=value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
<td>
```
n gte value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## Hierarchy and Filters
These operators establish a new search context and evaluate a
subexpression within that context. In this table, Q1 and Q2 are used to
denote arbitrary XQL expressions.
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Q1/Q2
```{=html}
</td>
```
```{=html}
<td>
```
parent/child
```{=html}
</td>
```
```{=html}
<td>
```
Children of nodes that satisfy Q1, evaluated in the current context,
such that the children satisfy Q2. Q2 is evaluated separately for the
child list of each node in Q1; the nodes to which each child list
evaluates are unioned together.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Q1//Q2
```{=html}
</td>
```
```{=html}
<td>
```
ancestor/descendant
```{=html}
</td>
```
```{=html}
<td>
```
Descendants of nodes that satisfy Q1, evaluated in the current context,
such that the descendants satisfy Q2. Q2 is evaluated separately for
each child list of each node in Q1, and recursively for each node in the
child list; the nodes to which each child list evaluates are unioned
together.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Q1\[Q2\]
```{=html}
</td>
```
```{=html}
<td>
```
filter
```{=html}
</td>
```
```{=html}
<td>
```
Nodes that satisfy Q1, evaluated in the current context, containing
children that satisfy Q2. Q2 is evaluated separately for the child list
of each node in Q1; the nodes to which each child list evaluates are
unioned together.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Q1\[poslist\]
```{=html}
</td>
```
```{=html}
<td>
```
subscript
```{=html}
</td>
```
```{=html}
<td>
```
Nodes that satisfy Q1, evaluated in the current context, whose position
in the evaluation list is contained in the poslist.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## Boolean and Set Operators
Terms or other XQL expressions may be combined using `<b>`{=html}boolean
operators`</b>`{=html} and `<b>`{=html}set operators`</b>`{=html}:
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
not(q)
```{=html}
</td>
```
```{=html}
<td>
```
negation
```{=html}
</td>
```
```{=html}
<td>
```
All nodes in the context for which the expression q evaluates to null.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
q1 union q2
```{=html}
</td>
```
```{=html}
<td>
```
union
```{=html}
</td>
```
```{=html}
<td>
```
The union of q1 and q2, evaluated in the context.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
q1 intersect q2
```{=html}
</td>
```
```{=html}
<td>
```
intersection
```{=html}
</td>
```
```{=html}
<td>
```
The intersection of q1 and q2, evaluated in the context.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
q1 \| q2
```{=html}
</td>
```
```{=html}
<td>
```
union
```{=html}
</td>
```
```{=html}
<td>
```
The union of q1 and q2, evaluated in the context.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
q1 \~ q2
```{=html}
</td>
```
```{=html}
<td>
```
both
```{=html}
</td>
```
```{=html}
<td>
```
If both q1 and q2 are non-empty, returns q1 union q2; if either is
empty, returns the empty list.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
q1 or q2
```{=html}
</td>
```
```{=html}
<td>
```
or
```{=html}
</td>
```
```{=html}
<td>
```
(Boolean) If the union of q1 and q2, evaluated in the context, is
non-empty, returns true; else, returns false.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
q1 and q2
```{=html}
</td>
```
```{=html}
<td>
```
and
```{=html}
</td>
```
```{=html}
<td>
```
(Boolean) If the intersection of q1 and q2, evaluated in the context, is
non-empty, returns true; else, returns false.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
The \"both\" operator was introduced because we found that many queries
use filters to express constraints on the same data that is returned
outside the filter, resulting in expressions that are rather redundant.
For instance, the following query uses filters to express that only
invoices for the customer named \"Wile E. Coyote\"that also contain
products are of interest, and both the customer name and the set of
products should be returned:
//invoice[customer[name='Wile E. Coyote'] and .//product]/(customer | .//product)
Using the \"both\" operator, this same query can be expressed more
concisely:
//invoice/(customer[name='Wile E. Coyote'] ~ .//product)
Note that the \"both\" operator is neither the boolean \"or\" operator
nor the set intersection operator. The expression \"customer intersect
product\" always returns an empty result since no element is ever
simultaneously a \<customer\> element and a \<product\> element. The
\"both\" operator is used to specify conditions which must
simultaneously be satisfied for the context.
## Grouping Operator
It is often useful to group results using the structure of the original
document. For instance, a query that lists the products on invoices
might want to group products by invoice, placing each group of products
within an invoice tag. XQL provides a grouping operator that provides
exactly this functionality. In the following query, the element to the
left of the curly braces (the Grouping Element) is used to group the
results of the query within the braces:
`//invoice { .//product }`
For each grouping element matched by the query, the grouping operator
creates an empty element with the same name. The results of the query
contained within the curly braces are then appended to this new node as
children. If we apply this query to the invoice data presented in the
tutorial, we obtain these results:
<xql:result>
<invoice>
<product maker="ACME" prod_name="screwdriver" price="80.00"/>
<product maker="ACME" prod_name="power wrench" price="20.00"/>
</invoice>
<invoice>
<product maker="BSA" prod_name="left-handed smoke shifter" price="16.00"/>
<product maker="BSA" prod_name="snipe call" price="13.00"/>
</invoice>
</xql:result>
Complex queries that use the grouping operator can be made more readable
by the appropriate use of whitespace, eg:
invoice {
.//customer[name contains "Coyote"] {
name | address
} ~
entries {
.//product[@maker="ACME"]
}
}
## Sequence
XQL defines the following operators for sequence:
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
before
```{=html}
</td>
```
```{=html}
<td>
```
a before b
```{=html}
</td>
```
```{=html}
<td>
```
Returns a list of all \"a\"s that precede a \"b\".
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
after
```{=html}
</td>
```
```{=html}
<td>
```
a after b
```{=html}
</td>
```
```{=html}
<td>
```
Returns a list of all \"a\"s that occur after a \"b\".
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
list concatenation
```{=html}
</td>
```
```{=html}
<td>
```
a, b
```{=html}
</td>
```
```{=html}
<td>
```
Returns a list containing all \"a\"s, followed by all \"b\"s. Useful for
specifying order in return lists.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
The list concatenation operator is used to specify order in return
lists. In general, XQL operators maintain document order; the
concatenation operator allows an order to be specified within a return
list. For instance, the following query specifies that the order of the
returned results should be author, then title, then isbn:
//book//(author, title, isbn)
If there is more than one author, all authors will be listed before the
title.
In systems where XML is used mainly to represent data from object
oriented systems or relational databases, sequence may not be
particularly important. However, sequence is important in documents, and
it also can be useful in data-oriented applications where the markup
does not clearly indicate the role of each element. Consider the
following table, which lists the latest scores for some fictitious
sport:
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
`<i>`{=html}Western League`</i>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Aardvarks 12
```{=html}
</td>
```
```{=html}
<td>
```
Weasels 10
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Mosquitos 17
```{=html}
</td>
```
```{=html}
<td>
```
Slugs 2
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
`<i>`{=html}Southern League`</i>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Tortoises 25
```{=html}
</td>
```
```{=html}
<td>
```
Hares 0
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Platypii 17
```{=html}
</td>
```
```{=html}
<td>
```
Amoebae 16
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
The markup for this table looks like this:
<table width="50%" border="1">
<tbody>
<tr>
<td colspan="2"><emph>Western League</emph> </td>
</tr>
<tr>
<td Aardvarks 12</td>
<td>Weasels 10</td>
</tr>
<tr>
<td Mosquitos 17</td>
<td>Bulls 2</td>
</tr>
<tr>
<td colspan="2"><emph>Southern League</emph></td>
</tr>
<tr>
<td Tortoises 25</td>
<td>Hares 0</td>
</tr>
<tr>
<td Platypii 17</td>
<td>Amoebae 16</td>
</tr>
</tbody>
</table>
Purists may object that this is not particularly good markup, since it
does not clearly distinguish the leagues from the scores. We agree, and
when we write our own documents, we would write them differently;
however, there is a lot of mediocre markup in the real world, and when
querying documents, we do not have the luxury of rewriting them first.
Therefore, we feel that a query language should be able to manage data
like that shown above.
To find all the latest scores for the Western League, we can use the
following query:
table//((tr after (tr contains "Western League")) before (tr contains "Southern League"))
> `<b>`{=html}Ed. Note: `</b>`{=html} Sequence is handled by axes in
> XPath. We believe that an XML query language should provide some means
> for allowing sequence in queries, and that various approaches should
> be considered. The approach discussed here has advantages in
> expressing relationships among multiple nodes, especially when
> comparisons are to be made only within the descendants of a particular
> node.
## Functions
Most of the functions of XQL have been taken directly from XSL Pattern
Language. A few functions have been added, many more have been omitted
because we found them to be less relevant in a pure query environment
than in a general purpose transformation environment.
```{=html}
<h5>
```
Collection functions
```{=html}
</h5>
```
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
attribute(), attribute(\'name\')
```{=html}
</td>
```
```{=html}
<td>
```
Returns the attributes in the context. If a name argument is supplied,
returns the attribute with the given name.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
comment()
```{=html}
</td>
```
```{=html}
<td>
```
Returns the comments in the context.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
element(), element(\'name\')
```{=html}
</td>
```
```{=html}
<td>
```
Returns the elements in the context. If a name argument is supplied,
returns the elements with the given name.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
entity-ref()
```{=html}
</td>
```
```{=html}
<td>
```
Returns the entity references in the context. XQL operates on a view of
the document in which all entity references are expanded; this function
is the only way to locate entity references in XQL.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
node()
```{=html}
</td>
```
```{=html}
<td>
```
Returns all nodes in the context.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
pi(), pi(\'target\')
```{=html}
</td>
```
```{=html}
<td>
```
Returns the processing instructions in the context. If a target argument
is supplied, returns the processing instructions with the given target.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
text()
```{=html}
</td>
```
```{=html}
<td>
```
Returns the text nodes in the context. For the sake of text nodes, XQL
assumes that CDATA sections are treated as text, adjacent text nodes are
merged, and entity references are expanded.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
count()
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
id()
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
idref()
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
position()
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## Extensible Functions
Many XQL implementations are part of a programming environment. In these
environments, it is helpful to allow users to write their own functions,
which may be used in queries. This must be done in a
language-independent manner, since XQL implementations have been done in
a variety of languages, including C++, Java, Haskell, and Perl. To allow
user-defined functions to be written, XQL provides a function called
\"function()\".
Suppose a user wanted to add a function that computes the average for a
list of values. The user could write a function called \"average\" and
call it in an XQL query like this:
`average(property//price)`
User-defined functions are typically written in the language environment
of the XQL implementation; for instance, if the XQL implementation is
written in Java, user-defined functions are generally written as Java
functions. All XQL functions are passed the list of nodes in the current
context. If the function has parameters, these are passed as strings to
the XQL function. Typically, the function will evaluate these parameters
as queries against the current context; for instance, the user code that
implements the \"average\" function might first execute the query
\"property//price\" for the current context to obtain a set of \<price\>
elements, then compute the average of these elements.
The result of a function call is also a nodelist. If a single value is
to be returned, such as a string or a number, it should be returned as
an element node of that type:
`<xql:number> 112,000.47 </xql:number>`
The available set of types that may be returned by functions is
described in the section \"Query Results and Serialization\", which
follows the current section. If a function is called with the wrong
parameters, this may be communicated by returning an \<xql:warning\>
element in the result:
`<xql:warning> "average" requires numeric values for the nodes to be averaged </xql:warning>`
> `<b>`{=html}Ed. Note: `</b>`{=html} Some vendors have asked that
> extensible operators be provided as well. This would be a useful
> feature; so far, we have not found a clean design for extensible
> operators in XQL.
>
> `<b>`{=html}Issue (function-namespace): `</b>`{=html} There are
> differing opinions as to whether namespaces add significant value as
> vendors and users add functions to XQL.
## References
> `<b>`{=html}Ed. Note: `</b>`{=html} The ideas in this section are
> exploratory, and have not yet been incorporated into XQL.
There is currently no syntax for dereferencing links in XQL, but this is
clearly needed in many applications. XSL provides the \"id()\" function,
which returns the element containing a given id. For instance, the
following would evaluate to the node pointed to by an HREF attribute in
an \<A\> element:
`A/id(@HREF)`
From an XQL perspective, this is actually a kind of join. However, the
above syntax is less complex than the equivalent join syntax:
`A/id[$h = @HREF]/(//*[id=$h])`
We need functionality similar to id(), extending this functionality to
incorporate any kind of link, not just ID/IDREF. Let\'s create a
function called ref() which returns the node or nodes to which an
XPointer or HTML HREF points
`A/ref(@HREF)`
One advantage of the join syntax is that it allows the type of the
referenced node to be specified. It may be useful to be able to specify
this as a further parameter to the function. Let\'s allow the type of
the referenced node to be specified as a second parameter to the
function. For instance, the following will return the referenced node
only if it is a \'table\" element; otherwise, it will return null:
`A/ref(@HREF, "table")`
It may also be helpful to specify further parameters, e.g. to limit the
scope of the reference to the current document, the local repository, or
some other identifiable scope.
It is frequently useful to be able to identify the references to a
particular node from other nodes. For instance, if we are thinking of
deleting something from a document, we may want to know if it is
referenced. For this purpose, it may be useful to introduce another
function that returns all nodes that reference a particular node. If we
call this function \"backref()\", it might look like this:
`A/backref(table[0])`
> `<b>`{=html}Issue (ref-scope): `</b>`{=html} Backwards references will
> also need to be scoped somehow, and not all systems will want to
> support them, due to implementation overhead.
References can also be used to specify the URLs of documents used in
queries:
`ref("``http://www.amazon.com``")//book[.//title contains "Alhambra"]`
## Joins
> `<b>`{=html}Ed. Note: `</b>`{=html} Joins are a new feature in XQL.
> The approach to joins discussed in this section comes largely from
> Peter Fankhauser of the GMD-IPSI and Harald Schöning of Software AG.
> Gerald Huck of the GMD-IPSI has been particularly helpful in refining
> the initial model. There is some preliminary implementation experience
> with this approach.
In many environments, it is useful to be able to combine information
from multiple sources to create one unified view. For instance, suppose
we have a source of books and a source of reviews:
<book>
<isbn> 84-7169-020-9 </isbn>
<title> Tales of the Alhambra </title>
<author> Washington Irving </author>
</book>
<review>
<isbn> 84-7169-020-9 </isbn>
<title> Tales of the Alhambra </title>
<reviewer> Ricardo Sanchez </reviewer>
<comments>
A romantic and humorous account of the time that
the author of "The Legend of Sleepy Hollow" lived
in an Arabian palace in Spain.
</comments>
</review>
We may want to combine these to create a view of the book that includes
the comments found in reviews:
<book>
<isbn> 84-7169-020-9 </isbn>
<title> Tales of the Alhambra </title>
<author> Washington Irving </author>
<review>
<reviewer> Ricardo Sanchez </reviewer>
<comments>
A romantic and humorous account of the time that
the author of "The Legend of Sleepy Hollow" lived
in an Arabian palace in Spain.
</comments>
</review>
</book>
This amounts to inserting information from the review into the book. If
we had a database that consisted only of this one book and this one
review, we could obtain the desired result with this query:
/book {
isbn | title | author | //review { reviewer | comments }
}
If we are using a database with many books and many reviews, the above
query would include the whole list of reviews in every single book, not
just the reviews for the book in question. We need some way to restrict
our reviews to those that have the same ISBN number as the book. We will
do this by introducing correlation variables. In the following example,
\"\$i := isbn\" assigns the variable \"\$i\" to the evaluation of isbn
in the context of each book. The expression \"//review\[isbn=\$i\]\"
restricts the reviews to those that match \"\$i\":
/book[$i:=isbn] {
isbn | title | author | //review[isbn=$i] { reviewer | comments }
}
> `<b>`{=html}Ed. Note: `</b>`{=html} Although filters and variable
> bindings both use square bracket notation, variable bindings do not
> filter results. For instance, the expressions \"/book\" and
> \"/book\[\$i:=isbn\]\" will always return the same set of books,
> whether or not any \<isbn\> elements are present.
Variable bindings propogate as new search contexts are created; when a
new context is created, e.g. as the result of a child or descendant
operator, it inherits all variable bindings that are active. This allows
bindings declared high in the document hierarchy to be used for joins
performed lower down.
If a correlation variable is bound to a subexpression that evaluates to
more than one result, any value in the list of results will be used as
the basis for a join. To be precise, \"list1 relop list2\" evaluates to
\"all e1 in list1 such that for some e2 in list2, e1 relop e2 is
satisfied\".
The following query returns books whether or not they have an isbn;
reviews are returned only if they have a matching isbn:
/book[$i:=isbn] {
$i | title | author
| //review[isbn=$i] { reviewer | comments }
}
> `<b>`{=html}Ed. Note: `</b>`{=html} In this example, it seems
> intuitive to say that you can\'t join on null - a book with no isbn
> does not match all reviews that have no isbn. On the XQL mailing list,
> there is some difference of opinion as to whether it should be
> possible to join on null.
In XQL, square brackets are used for three distinct things that can not
be mixed: subscripts, filters, and variable bindings. If you want both a
filter and a variable binding, you must use separate sets of brackets:
/book[isbn][$i:=isbn] {
$i | title | author
| //review[isbn=$i] { reviewer | comments }
}
## RenamingOperator
The nodes in a list may be renamed using the renaming operator \"-\>\".
In joins, this can be used to reflect a meaningful name that describes
the synthesized result:
/book[isbn][$i:=isbn] -> BookWithReviews {
$i | title | author
| //review[isbn=$i] { reviewer | comments }
}
The renaming operator may also be used to adjust namespaces in query
results. Since renaming changes the name of a node, it also changes the
namespace. For instance, suppose \<book\> is in the namespace of
\"<http://www.TwiceSoldTales.com>\", and we rename the \<book\> element
to \<livre\>:
//book->livre
We can assume that \<livre\> is not defined in the namespace associated
with \"<http://www.TwiceSoldTales.com>\". Since renaming often creates
element names that do not exist in the original namespace, renaming in
XQL does not keep the namespace of the original node name. This property
of the renaming operator can be used to remove namespaces; for instance,
the following query places \<book\> elements in the default namespace,
regardless of their original namespace:
//book->book
New namespace prefixes may be explicitly applied with the rename
operator:
//book->a:book
## Precedence of Operators
XQL expressions are evaluated from left to right. The following table
shows the precedence of operators in XQL:
```{=html}
<table border="" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
`<i>`{=html}Query Operators by Decreasing Precedence`</i>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Grouping
```{=html}
</td>
```
```{=html}
<td>
```
()
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Filter
```{=html}
</td>
```
```{=html}
<td>
```
\[\]
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Renaming
```{=html}
</td>
```
```{=html}
<td>
```
-\>
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Grouping
```{=html}
</td>
```
```{=html}
<td>
```
{ }
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Path
```{=html}
</td>
```
```{=html}
<td>
```
/ //
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Comparison, Assignment
```{=html}
</td>
```
```{=html}
<td>
```
= != \< \<= \> \>= eq ne lt le gt ge contains ieq ine ilt ile igt ige
icontains :=
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Intersection
```{=html}
</td>
```
```{=html}
<td>
```
intersect
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Union
```{=html}
</td>
```
```{=html}
<td>
```
union \|
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Negation
```{=html}
</td>
```
```{=html}
<td>
```
not()
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Conjunction
```{=html}
</td>
```
```{=html}
<td>
```
and
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Disjunction
```{=html}
</td>
```
```{=html}
<td>
```
or
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
Sequence
```{=html}
</td>
```
```{=html}
<td>
```
before after
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
End of Statement
```{=html}
</td>
```
```{=html}
<td>
```
;
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
Parentheses may be used for grouping:
(author | editor)/name
author | (editor/name)
## Query Results and Serialization
In some environments, the results of a query are returned as XML text.
XQL defines a serialization format to allow the results of queries to be
returned as well-formed XML documents. Namespaces are used to
distinguish tags belonging to the serialization format from tags
returned by the query. When query results are serialized, they are
wrapped in an \<xql:result\> element:
<xql:result xmlns:xql="http://www.metalab.unc/xql/serialization">
<customer> Wile E. Coyote, Death Valley, CA </customer>
<customer> Camp Mertz </customer>
</xql:result>
The reason for this is that a well-formed XML document may have only one
root element, and queries may return any number of results. Other XQL
serialization elements are used to return values from functions, provide
additional information about a query, or indicate errors or warnings.
The following elements are defined in the XQL serialization namespace:
```{=html}
<table border="1" cellpadding="" align="">
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:result\>
```{=html}
</td>
```
```{=html}
<td>
```
Surrounds the serialized results of the query.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:query\>
```{=html}
</td>
```
```{=html}
<td>
```
Optional. Contains the original query string. Useful for debugging.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:true\>
```{=html}
</td>
```
```{=html}
<td>
```
Returned by boolean functions.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:false\>
```{=html}
</td>
```
```{=html}
<td>
```
Returned by boolean functions.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:number\>
```{=html}
</td>
```
```{=html}
<td>
```
Returned by numeric functions.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:text\>
```{=html}
</td>
```
```{=html}
<td>
```
Returned by text functions.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:attribute name=\"attributeName\" value=\"attributeValue\"\>
```{=html}
</td>
```
```{=html}
<td>
```
Used to return attributes when they are returned outside of the
attribute list of an element.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:declaration\>
```{=html}
</td>
```
```{=html}
<td>
```
Used to return the XML declaration when it is returned in a query.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:error\>
```{=html}
</td>
```
```{=html}
<td>
```
Used to indicate an error in the query. The content of this element
explains the error.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr align="" valign="">
```
```{=html}
<td>
```
\<xql:warning\>
```{=html}
</td>
```
```{=html}
<td>
```
Used to indicate a warning. The content of this element explains the
warning.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
```{=html}
<hr title="Separator from footer">
```
|
# XML - Managing Data Exchange/XQuery
## **1. Definition of XQuery**
XQuery is a query language under development by the World Wide Web
Consortium (W3C) and makes possible to efficiently and easily extract
information from native XML databases and relational databases that
store XML data.
Every query consists of an introduction and a body. The introduction
establishes the compile-time environment such as schema and module
imports, namespace and function declarations, and user-defined
functions. The body generates the value of the entire query. The
structure of XQuery shows in Figure 1.
```{=html}
<table class=MsoTableGrid border=0 cellspacing=0 cellpadding=0
style='margin-left:5.4pt;border-collapse:collapse;mso-yfti-tbllook:480;
mso-padding-alt:0in 5.4pt 0in 5.4pt;mso-border-insidev:.5pt solid windowtext'>
```
```{=html}
<tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes'>
```
```{=html}
<td width=624 colspan=3 style='width:6.5in;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}Figure 1.
Structure of `<span
class=SpellE>`{=html}XQuery`</span>`{=html}`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:1'>
```
```{=html}
<td width=66 rowspan=8 style='width:49.5pt;border:none;border-right:solid windowtext 1.0pt;
mso-border-right-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-fareast-language:KO;mso-bidi-language:#0400'>`{=html}Introduction`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}Comment:`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}(:
Sample version 1.0
` :)``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:2'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}Namespace
Declaration:`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}declare
namespace my =
` “``<span class=SpellE>`{=html}`urn:foo``</span>`{=html}`”;``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:3'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}Function
Declaration:`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}declare
function `<span
class=SpellE>`{=html}my:fact`</span>`{=html}(\$n) {`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:4'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}if (\$n \< 2)`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:5'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}then 1`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:6'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}else \$n \*
`<span class=SpellE>`{=html}my:fact`</span>`{=html}(\$n --
1)`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:7'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}};`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:8'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}Global
Variable:`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}declare
variable \$`<span
class=SpellE>`{=html}my:ten`</span>`{=html}
{`<span class=SpellE>`{=html}my:fact`</span>`{=html}(10)};`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:9'>
```
```{=html}
<td width=624 colspan=3 style='width:6.5in;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:10'>
```
```{=html}
<td width=66 rowspan=7 style='width:49.5pt;border:none;border-right:solid windowtext 1.0pt;
mso-border-right-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}Body`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}Constructed
XML:`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}\<table\>{`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:11'>
```
```{=html}
<td width=162 rowspan=2 style='width:121.5pt;border:none;mso-border-left-alt:
solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}FLWOR
Expression:`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}for \$`<span class=SpellE>`{=html}i`</span>`{=html} in
1 to 10`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:12'>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}return`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:13'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}\<`<span class=SpellE>`{=html}tr`</span>`{=html}\>`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:14'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}Enclosed
Expression:`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}\<`<span class=GramE>`{=html}td\>`</span>`{=html}10!/{\$`<span class=SpellE>`{=html}i`</span>`{=html}}!
` = {$``<span class=SpellE>`{=html}`my:ten``</span>`{=html}` div ``<span class=SpellE>`{=html}`my:fact``</span>`{=html}`($``<span
class=SpellE>`{=html}`i``</span>`{=html}`)} </td>``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:15'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}\</`<span
class=SpellE>`{=html}tr`</span>`{=html}\>`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:16;mso-yfti-lastrow:yes'>
```
```{=html}
<td width=162 style='width:121.5pt;border:none;mso-border-left-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 style='width:297.0pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}}
\</table\>`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## **2. XQuery versus Other Query Languages**
**2.1 XQuery versus XPath and XSLT**
XQuery, XPath, XSLT, and SQL are good query languages. Each of these
languages has their own advantages in diverse situations, so XQuery
cannot substitute for them at every task. XQuery is built on XPath
expressions. XQuery 1.0 and XPath 2.0 shares the same data model, the
same functions, and the same syntax. Table 1 shows the advantages and
the drawbacks of each query language.
Table 1. XQuery versus XPath and XSLT
```{=html}
<table class=MsoTableGrid border=1 cellspacing=0 cellpadding=0
style='margin-left:5.4pt;border-collapse:collapse;border:none;mso-border-alt:
solid windowtext .5pt;mso-yfti-tbllook:480;mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-border-insideh:.5pt solid windowtext;mso-border-insidev:.5pt solid windowtext'>
```
```{=html}
<tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes;height:22.9pt'>
```
```{=html}
<td width=84 style='width:63.0pt;border:solid windowtext 1.0pt;mso-border-alt:
solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt;height:22.9pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html} `</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=270 style='width:202.5pt;border:solid windowtext 1.0pt;border-left:
none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt;height:22.9pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Advantage`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=270 style='width:202.5pt;border:solid windowtext 1.0pt;border-left:
none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt;height:22.9pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Drawback`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:1'>
```
```{=html}
<td width=84 style='width:63.0pt;border:solid windowtext 1.0pt;border-top:
none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span class=SpellE>`{=html}`<span lang=EN-US
style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}XQuery`</span>`{=html}`</span>`{=html}`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=270 valign=top style='width:202.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}1.expressing
joins and
` sorts``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}2.manipulating
` sequences of values and nodes in arbitrary order``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}3.easy
to write
` user-defined functions including recursive ones``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}4.allows
users to
` construct temporary XML results in the middle of a query, and then navigate`\
` into that``</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=270 valign=top style='width:202.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}1.XQuery
implementations
` are less mature than XSLT ones``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:2'>
```
```{=html}
<td width=84 style='width:63.0pt;border:solid windowtext 1.0pt;border-top:
none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span class=SpellE>`{=html}`<span lang=EN-US
style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}XPath`</span>`{=html}`</span>`{=html}`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html} 1.0`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=270 valign=top style='width:202.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}1.convenient
syntax for
` addressing parts of an XML document``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}2.selecting
a node out
` of an existing XML document or database``</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=270 valign=top style='width:202.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}1.cannot
create new XML`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}2.cannot
select only
` part of an XML node``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}3.cannot
introduce
` variables or namespace bindings``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}4.cannot
work with date
` values, calculate the maximum of a set of numbers, or sort a list of strings``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:3;mso-yfti-lastrow:yes'>
```
```{=html}
<td width=84 style='width:63.0pt;border:solid windowtext 1.0pt;border-top:
none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}XSLT
1.0`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=270 valign=top style='width:202.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}1.recursively
` processing an XML document or translating XML into HTML and text``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}2.creating
new XML or
` part of existing nodes``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}3.introducing
variables
` and namespaces``</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=270 valign=top style='width:202.5pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}1.cannot
be addressed
` without effectively creating a language like ``<span class=SpellE>`{=html}`XQuery``</span>`{=html}`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}2.cannot
work with
` sequences of values``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
**2.2 XQuery versus SQL**
XQuery has similarities to SQL in both style and syntax. The main
difference between XQuery and SQL is that SQL focuses on unordered sets
of "flat" rows, while XQuery focuses on ordered sequences of values and
hierarchical nodes.
## **3. XQuery Expressions**
**3.1 FLWOR expressions**
FLWOR expressions are important part of XQuery. FLWOR is pronounced
\"flower\". This name comes from the **F**OR, **L**ET, **W**HERE,
**O**RDER BY, and **R**ETURN clauses that organize the expressions. The
FOR and LET clauses can come out any number of times in any order. The
WHERE and ORDER BY clauses are optional. However, these clauses must be
shown in the order given if they are used. The RETURN clause should
exist.
XQuery permits you to use join queries in a similar way to SQL. This
example is depicted in Example 1 as a join between the videos table and
the actors table.
Example 1.
` let $doc := .`\
` for $v in $doc//video,`\
` $a in $doc//actors/actor`\
` where ends-with($a, 'Lisa')`\
` and $v/actorRef = $a/@id`\
` order by $v/year`\
` return $v/title `
The **LET** clause states a variable assignment. In this case, the query
initializes it to doc (\'videos.xml\'), or a query's result places a
document in a database. The **FOR** clause describes a mechanism for
iteration: one variable processes all the videos in turn, another
variable processes all the actors in turn. In this case, the query
processes the pairs of videos and actors. The **WHERE** clause selects
tables in which you are interested. In this case, you want to know that
the actor shows in video table with the name ending with "Lisa". The
**ORDER BY** clause obtains the results in sorted order. In this case,
you desire to have a result with the videos in order of their release
date. The **RETURN** clause at the end of an expression informs the
system what information you want to get back. In this case, you want the
video's title.
------------------------------------------------------------------------
**3.2 Conditional expression**
XQuery offers IF, THEN, and ELSE clause, conditional expression. The
ELSE clause is obligatory. The reason is that each expression in XQuery
should return a value. A query is showed at example 2 to retrieve all
books and their authors. You desire to return additional authors as
"et-al" after the first two authors.
Example 2.
` for $b in document("books.xml")/bib/book`\
` return`\
` if (count($b/author) <= 2) then $b`\
` else ``<book>`{=html}` { $b/@*, $b/title, $b/author[position() <= 2], ``<et-al/>`{=html}`,`\
` ...... $b/publisher, $b/price } ``</book>`{=html}
This query reads book data from a books.xml. If the author count is less
than 2 or equal to 2 for each book, then the query returns the book
straightly. Otherwise the query makes a new book element including all
the original data, excepting that the query contains only the first two
authors and attaches an et-al element. Position() function is returned
only the first two authors. \$b/@\*, XPath expression, refers to all the
attributes on \$b.
------------------------------------------------------------------------
**3.3 XQuery functions and operators**
XQuery contains a huge set of functions and operators. Table 2 shows
frequently used built-in functions. You are able to describe your own
and many engines provide custom extensions as well.
Table 2. Commonly used built-in functions
```{=html}
<table class=MsoTableGrid border=1 cellspacing=0 cellpadding=0
style='margin-left:5.4pt;border-collapse:collapse;border:none;mso-border-alt:
solid windowtext .5pt;mso-yfti-tbllook:480;mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-border-insideh:.5pt solid windowtext;mso-border-insidev:.5pt solid windowtext'>
```
```{=html}
<tr style='mso-yfti-irow:0;mso-yfti-firstrow:yes'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Function`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border:solid windowtext 1.0pt;
border-left:none;mso-border-left-alt:solid windowtext .5pt;mso-border-alt:
solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Commentary`</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:1'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Math:`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}+, -, \*, div,
`<span class=SpellE>`{=html}idiv`</span>`{=html},
` mod, =, !=, <, >, <=, >= floor(), ceiling(), round(), count(),`\
` min(), max(), ``<span class=SpellE>`{=html}`avg``</span>`{=html}`(), sum()``</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Division is done using
div rather than a
` slash because a slash indicates an ``<span class=SpellE>`{=html}`XPath``</span>`{=html}` step`\
` expression. ``<span class=SpellE>`{=html}`<span class=GramE>`{=html}`idiv``</span>`{=html}`</span>`{=html}` is a`\
` special operator for integer-only division that returns an integer and`\
` ignores any remainder.``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:2'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Strings and Regular
Expressions:`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}compare(),
`<span class=SpellE>`{=html}concat`</span>`{=html}(),
` starts-with(), ends-with(), contains(), substring(), string-length(),`\
` substring-before(), substring-after(), normalize-space(), upper-case(),`\
` lower-case(), translate(), matches(), replace(), tokenize()``</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span class=GramE>`{=html}`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}compare(`</span>`{=html}`</span>`{=html}`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}) dictates string ordering.
`<span class=GramE>`{=html}translate(`</span>`{=html})
` performs a special mapping of characters. ``<span class=GramE>`{=html}`matches(``</span>`{=html}`),`\
` replace(), and tokenize() use regular expressions to find, manipulate, and`\
` split string values.``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:3'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Date and
Time:`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}current-date(),
current-time(), current-`<span
class=SpellE>`{=html}dateTime`</span>`{=html}() +, -, div
`<span class=SpellE>`{=html}eq`</span>`{=html}, `<span
class=SpellE>`{=html}ne`</span>`{=html},
`<span class=SpellE>`{=html}lt`</span>`{=html},
`<span class=SpellE>`{=html}gt`</span>`{=html},
` le, ``<span class=SpellE>`{=html}`gt``</span>`{=html}`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span class=SpellE>`{=html}`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}XQuery`</span>`{=html}`</span>`{=html}`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html} has many special types for date and time values such
as duration, `<span
class=SpellE>`{=html}dateTime`</span>`{=html}, date, and time. On most
you can do arithmetic
` and comparison operators as if they were numeric. The two-letter`\
` abbreviations stand for equal, not equal, less than, greater than, less than`\
` or equal, and greater than or equal.``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:4'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}XML node and
`<span class=SpellE>`{=html}QNames`</span>`{=html}:`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}node-kind(), node-name(),
base-`<span
class=SpellE>`{=html}uri`</span>`{=html}()
`<span class=SpellE>`{=html}eq`</span>`{=html},
`<span class=SpellE>`{=html}ne`</span>`{=html},
` is, ``<span class=SpellE>`{=html}`isnot``</span>`{=html}`, get-local-name-from-``<span class=SpellE>`{=html}`QName``</span>`{=html}`(),`\
` get-namespace-from-``<span class=SpellE>`{=html}`QName``</span>`{=html}`() deep-equal() >>,`\
` <<``</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}node-`<span class=GramE>`{=html}kind(`</span>`{=html})
` returns the type of a node (i.e. "element"). node-``<span
class=GramE>`{=html}`name(``</span>`{=html}`) returns the ``<span class=SpellE>`{=html}`QName``</span>`{=html}` of the`\
` node, if it exists. base-``<span class=SpellE>`{=html}`<span class=GramE>`{=html}`uri``</span>`{=html}`</span>`{=html}`<span
class=GramE>`{=html}`(``</span>`{=html}`) returns the URI this node is from. ``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Nodes and
`<span class=SpellE>`{=html}QName`</span>`{=html}
` values can also be compared using ``<span class=SpellE>`{=html}`eq``</span>`{=html}` and ``<span
class=SpellE>`{=html}`ne``</span>`{=html}` (for value comparison), or is and ``<span class=SpellE>`{=html}`isnot``</span>`{=html}\
` (for identity comparison). deep-``<span class=GramE>`{=html}`equal(``</span>`{=html}`) compares two`\
` nodes based on their full recursive content. ``</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}The \<\< operator returns
true if
` the left operand ``<span class=SpellE>`{=html}`preceeds``</span>`{=html}` the right operand in`\
` document order. The >> operator is a following comparison.``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:5'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Sequences:`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}item-at(), index-of(),
empty(),
` exists(), distinct-nodes(), distinct-values(), insert(), remove(),`\
` subsequence(), unordered().position(), last()``</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}item-`<span class=GramE>`{=html}at(`</span>`{=html})
returns
` an item at a given position while index-of() attempts to find a position for`\
` a given item. ``<span class=GramE>`{=html}`empty(``</span>`{=html}`) returns true if the sequence`\
` is empty and exists() returns true if it's not. ``<span class=SpellE>`{=html}`dictinct``</span>`{=html}`-``<span
class=GramE>`{=html}`nodes(``</span>`{=html}`) returns a sequence with exactly identical nodes`\
` removed and distinct-values() returns a sequence with any duplicate atomic`\
` values removed. ``<span class=GramE>`{=html}`unordered(``</span>`{=html}`) allows the query engine`\
` to optimize without preserving order. ``<span class=GramE>`{=html}`position(``</span>`{=html}`)`\
` returns the position of the context item currently being processed. ``<span
class=GramE>`{=html}`last(``</span>`{=html}`) returns the index of the last item.``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:6'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Type
Conversion:`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}string(), data(),
decimal(), `<span
class=SpellE>`{=html}boolean`</span>`{=html}()`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}These functions return
the node as the
` given type, where possible. ``<span class=GramE>`{=html}`data(``</span>`{=html}`) returns the`\
` "typed value" of the node.``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:7'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Booleans:`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}true(), false(),
not()`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}There\'s no \"true\" or
` "false" keywords in ``<span class=SpellE>`{=html}`XQuery``</span>`{=html}` but rather ``<span
class=GramE>`{=html}`true(``</span>`{=html}`) and false() functions. ``<span class=GramE>`{=html}`not(``</span>`{=html}`)`\
` returns the ``<span class=SpellE>`{=html}`boolean``</span>`{=html}` negation of its argument.``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr style='mso-yfti-irow:8;mso-yfti-lastrow:yes'>
```
```{=html}
<td width=228 valign=top style='width:171.0pt;border:solid windowtext 1.0pt;
border-top:none;mso-border-top-alt:solid windowtext .5pt;mso-border-alt:solid windowtext .5pt;
padding:0in 5.4pt 0in 5.4pt'>
```
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}Input:`</span>`{=html}
`<span lang=EN-US style='font-size:10.0pt;line-height:150%;
color:black;mso-bidi-language:#0400'>`{=html}document(), input(),
collection()`</span>`{=html}
```{=html}
</td>
```
```{=html}
<td width=396 valign=top style='width:297.0pt;border-top:none;border-left:
none;border-bottom:solid windowtext 1.0pt;border-right:solid windowtext 1.0pt;
mso-border-top-alt:solid windowtext .5pt;mso-border-left-alt:solid windowtext .5pt;
mso-border-alt:solid windowtext .5pt;padding:0in 5.4pt 0in 5.4pt'>
```
`<span class=GramE>`{=html}`<span lang=EN-US style='font-size:10.0pt;
line-height:150%;color:black;mso-bidi-language:#0400'>`{=html}document(`</span>`{=html}`</span>`{=html}`<span
lang=EN-US style='font-size:10.0pt;line-height:150%;color:black;mso-bidi-language:
#0400'>`{=html}) returns a document of nodes based on a URI parameter.
`<span
class=GramE>`{=html}collection(`</span>`{=html}) returns a collection
based on a string
` parameter (perhaps multiple documents). ``<span class=GramE>`{=html}`input(``</span>`{=html}`)`\
` returns s general engine-provided set of input nodes.``</span>`{=html}
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
## **4. References**
The contents of this chapter were quoted from the following lists.
\- *X Is for XQuery*, Jason Hunter:
<http://www.oracle.com/technology/oramag/oracle/03-may/o33devxml.html>
\- *An Introduction to the XQuery FLWOR Expression*, Michael Kay:
<http://www.stylusstudio.com/xquery_flwor.html>
\- *Learn XQuery in 10 Minutes*, Michael Kay:
<http://www.stylusstudio.com/xquery_primer.html>
\- *XQuery: The XML Query Language*, Michael Brundage, Addison-Wesley
2004
## **5. Useful Links and Books**
\- W3C XML Query (XQuery): <http://www.w3.org/XML/Query>
\- XQuery Latest version: <http://www.w3.org/TR/xquery/>
\- XQuery 1.0 and XPath 2.0 Functions and Operators:
<http://www.w3.org/TR/xpath-functions/>
\- XQuery 1.0 and XPath 2.0 Data Model (XDM):
<http://www.w3.org/TR/xpath-datamodel/>
\- XSLT 2.0 and XQuery 1.0 Serialization:
<http://www.w3.org/TR/xslt-xquery-serialization/>
\- XML Query Use Cases: <http://www.w3.org/TR/xquery-use-cases/>
\- XML Query (XQuery) Requirements:
<http://www.w3.org/TR/xquery-requirements/>
\- XQuery: The XML Query Language, Michael Brundage, Addison-Wesley 2004
## See Also
- XQuery Tutorial and Cookbook Wikibook This
Wikibook has many small XQuery examples with links to working XQuery
applications.
|
# XML - Managing Data Exchange/Exchanger XML Lite
## Exchanger XML Lite
Cladonia offers an xml editor at <http://www.exchangerxml.com/> for free
noncommercial use, and can be downloaded without registration.
This is a Java-based product that runs on all platforms including
Windows, Linux, Mac OSX and UNIX.
(NOTE: If you need an XML editor for commercial use, you can get a free
30-day trial of Exchanger XML Professional at
<http://www.exchangerxml.com>)
## Single Entity in Exchanger XML Lite
The following directions will lead you step-by-step through doing the
same project that is found in the ../A single
entity chapter.
## Part One: Creating the Project Folder
1\) Open Exchanger XML Lite
2\) Click on:
` -Project`\
` -New Project : a "New Project" folder will appear `\
` in the project folder window`
3\) Type \"TourGuide\" over the \"New Project\" title to change the name
of the new project to TourGuide.

## Part Two: Creating the Schema File
1\) Click on:
` -File`\
` -New `\
` -For Type`\
` -Scroll to "XML Schema Definition" and highlight it`\
` -OK`
2)Exchanger automatically puts the beginning and ending tags in the file
for you, however, for our example, delete those automatic tags, and copy
and paste the following code into the file:
`<?xml version="1.0" encoding="UTF-8"?>`\
` <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="unqualified"> `\
` <!-- Tour Guide -->`\
` <!--The tourGuide element is defined as a complex element type, i.e. `\
` it has embedded elements.--> `\
` <xsd:element name="tourGuide">`\
` <xsd:complexType>`\
` <xsd:sequence>`\
` <!--The minimum number of times an element can occur is `\
` set using minOccurs (default is 1) and an unlimited `\
` number of times an element can occur maxOccurs=”unbounded”.-->`\
` <xsd:element name="city" type="cityDetails" minOccurs = "1" maxOccurs="unbounded" />`\
` </xsd:sequence>`\
` </xsd:complexType>`\
` </xsd:element>`\
` <!-- City -->`\
` <!--City is declared an element of named complex type -->`\
` <!--<xsd:complexType begins the declaration of a complex `\
`type, ”cityDetails” identifies the complex type. `\
` This is NOT the name of the element. This complex type `\
` definition may be used in the declarations of more than one element.-->`\
` <xsd:complexType name="cityDetails">`\
` <!--Schema element sequence {13} specifies that the child elements `\
` must appear in the order specified.-->`\
` <xsd:sequence>`\
` <!--<xsd:element begins the declaration of an element of simple `\
` type. ”cityName” is the name of the element being declared (in `\
` the XML document it will look something like: <cityName> ) `\
` and ”xsd:string” is the data type of the element.--> `\
` <xsd:element name="cityName" type="xsd:string"/>`\
` <xsd:element name="adminUnit" type="xsd:string"/>`\
` <xsd:element name="country" type="xsd:string"/>`\
` <xsd:element name="population" type="xsd:integer"/>`\
` <xsd:element name="area" type="xsd:integer"/>`\
` <xsd:element name="elevation" type="xsd:integer"/>`\
` <xsd:element name="longitude" type="xsd:decimal"/>`\
` <xsd:element name="latitude" type="xsd:decimal"/>`\
` <xsd:element name="description" type="xsd:string"/>`\
` <xsd:element name="history" type="xsd:string"/>`\
` <!--Closing of tags. Note: these should not overlap.--> `\
` </xsd:sequence>`\
` </xsd:complexType>`\
` </xsd:schema>`
3\) Click on the GREEN CHECK to Validate, and the BROWN CHECK to check
for Well-Formedness. These can be found on the toolbar:

(NOTE: Be sure to eliminate any \"white space\" before the text that you
paste, or you may have an error when validating.)
4)Click on:
` -File`\
` -Save`\
` -"city.xsd"`
5)Right Click on:
` -"TourGuide" project folder`\
` -Add File`\
` -click on "city.xsd"`\
` -open`\
` `\
` (Note: Now the project "TourGuide" should contain one file,`\
` "city.xsd".)`
## Part Three: Creating the Style Sheet
1)Click on:
` -File`\
` -New`\
` -For Type`\
` -Scroll to "XML StyleSheet Language" and highlight it`\
` -OK`
2)Delete any automatic tags that appear, and cut and paste the following
code into the file:
`<?xml version="1.0" encoding="UTF-8"?>`\
` <!--<xsl:stylesheet> declares start of stylesheet and identifies the version `\
` number and the official W3C namespace.-->`\
`<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">`\
` <xsl:output method="html"/>`\
` <!--<xsl:template> defines the start of a template and contains `\
` rules to apply when a specified node is matched. The match attribute is `\
` used to associate (match) the template with an XML element, in this case `\
` the root (/), or whole branch, of the XML source document. The XSL looks `\
` for the root match and then outputs the HTML.--> `\
` <xsl:template match="/">`\
` <!--The contents of the template element are placed in the output `\
` stream of HTML that the browser will be able to interpret.-->`\
` <html>`\
` <head>`\
` <title>Tour Guide</title>`\
` </head>`\
` <body>`\
` <h2>Cities</h2>`\
` <xsl:apply-templates select="tourGuide"/>`\
` </body>`\
` </html>`\
` </xsl:template>`\
` <xsl:template match="tourGuide">`\
` <xsl:for-each select="city">`\
` <xsl:text>City: </xsl:text>`\
` <!--<xsl:value-of> extracts the value of the selected `\
` node/XML element and adds it to the output stream-->`\
` <xsl:value-of select="cityName"/>`\
` <br/>`\
` <xsl:text>Population: </xsl:text>`\
` <xsl:value-of select="population"/>`\
` <br/>`\
` <xsl:text>Country: </xsl:text>`\
` <xsl:value-of select="country"/>`\
` <br/>`\
` <br/>`\
` </xsl:for-each>`\
` <!--<xsl:for-each> can be used to loop through each node in a specified `\
` node set and add them to the output--> `\
` </xsl:template>`\
` </xsl:stylesheet>`
3\) Click on the GREEN CHECK to Validate, and the BROWN CHECK to check
for Well-Formedness. (NOTE: Be sure to eliminate any \"white space\"
before the text that you paste, or you may have an error when
validating.)
4)Click on:
` -File`\
` -Save As`\
` -"city.xsl"`
5)Right Click on:
` -"TourGuide" project folder`\
` -Add File`\
` -"city.xsl"`\
` -open`
` (Note: Now the project "TourGuide" contains two files, `\
` "city.xsd", and "city.xsl".)`
!thumhttp://xpressvds.blogspot.com/bnail
## Part Four: Creating the XML File
1\) Click on:
` -File`\
` -New`\
` -Default XML Document`\
` -OK`
2\) Delete any automatic tags that appear and copy and paste the
following code:
`<?xml version="1.0" encoding="UTF-8"?>`\
`<?xml-stylesheet href="city.xsl" type="text/xsl"?>`\
``\
`<!--The following declaration identifies the root element of the document `\
`(tourGuide) and the schema file (city.xsd) using xsi=schemaLocation-->`\
`<tourGuide>`\
` xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'`\
` xsi:noNamespaceSchemaLocation='city.xsd'>`\
` <!--The definition of the first city-->`\
` <city>`\
` <cityName>Belmopan</cityName>`\
` <adminUnit>Cayo</adminUnit>`\
` <country>Belize</country>`\
` <population>11100</population>`\
` <area>5</area>`\
` <elevation>130</elevation>`\
` <longitude>88.44</longitude>`\
` <latitude>17.27</latitude>`\
` <description>Belmopan is the capital of Belize</description>`\
` <history>Belmopan was established following the devastation of the`\
` former capitol, Belize City, by Hurricane Hattie in 1965. High `\
` ground and open space influenced the choice and ground-breaking `\
` began in 1966. By 1970 most government offices and operations had `\
` already moved to the new location.`\
` </history>`\
` </city>`\
` <!--the definition of the second city-->`\
` <city>`\
` <cityName>Kuala Lumpur</cityName>`\
` <adminUnit>Selangor</adminUnit>`\
` <country>Malaysia</country>`\
` <population>1448600</population>`\
` <area>243</area>`\
` <elevation>111</elevation>`\
` <longitude>101.71</longitude>`\
` <latitude>3.16</latitude>`\
` <description>Kuala Lumpur is the capital of Malaysia and the largest `\
` city in the nation</description>`\
` <history>The city was founded in 1857 by Chinese tin miners and `\
` perseded Klang. In 1880 the British government transferred their `\
` headquarters from Klang to Kuala Lumpur, and in 1896 it became the `\
` capital of Malaysia. `\
` </history>`\
` </city>`\
`<!--The closing of the root element tag--> `\
`</tourGuide>`
3\) Click on the GREEN CHECK to Validate, and the BROWN CHECK to check
for Well-Formedness. (NOTE: Be sure to eliminate any \"white space\"
before the text that you paste, or you may have an error when
validating.)
`(Also NOTE: You may need to select `\
` -Schema`\
` -Infer XML Schema`\
` -then choose city.xsd`\
`in order to validate the xml file.)`
4)Click on:
` -File`\
` -Save As`\
` -city.xml`
5\) Right click on:
` -TourGuide`\
` -Add File`\
` -"city.xml"`\
` -open`\
`(Note: Now project "TourGuide" should contain three files, `\
`"city.xsd","city.xsl", and "city.xml".)`
## Part Five: Executing your code
1\) Open the city.xml file.
2\) Click on:
` -Transform`\
` -Execute Simple XSLT`\
` -Current Document`\
` -OK`
` -XSL input`\
` -From URl`\
` -pick city.xsl`\
` -open`\
` -OK`
` -Use Default Processor`\
` -OK`\
`Note: the window should say "Transformation Complete"`
`Now you may close this window and follow step 3 to get the results.`
3)Click on:
` -Tools`\
` -Start Browser`\
` `\
`Note: Results should look like this:`

|
# XML - Managing Data Exchange/XML and JDBC
## Overview
ODBC is the acronym for the oft used API Open Database Connectivity.
Many applications and application programmers use ODBC in order to
access relational databases, such as SQL and Microsoft Access, and to
manipulate the data within the databases. Specifically, JDBC (Java
Database Connectivity), which is based on ODBC, is the API used by
applications developed in Java to perform these various tasks. Moreover,
JDBC is now capable of handling advanced datatypes in SQL which in turn
becomes useful when dealing with XML. Also, JDBC has within it the
ability to actually create XML data. Furthermore, the use of JAXP (Java
API for XML Processing) along with JDBC provides yet another way of
manipulating and using relational databases and XML. In any event, there
are multiple ways to use the JDBC API with XML.
## JDBC and XML Documents
Many Java Applications written today will more than likely interact with
an SQL database (or a relational database, but for the sake of
uniformity, we will work with SQL.) Depending on the intent of the
application, there may be the case of actually storing an XML document
for display or for manipulation. Whatever the case, JDBC now supports
all datatypes defined in the SQL:1999 specification. One of theses
datatypes is the CLOB (character large object) datatype. This datatype
is perfect for storing XML documents. This is one way XML and the JDBC
API works with each other.
## JDBC and XML Production
One of the more interesting things about JDBC is that it can be used to
gather MetaData. Meta-data is nothing more than data about data. From an
XML standpoint, this is very useful because we can create XML data on
the fly with nothing more than a table name. The class that makes this
possible is java.sql.ResultSetMetaData. Consequently this class is a
part of the JDBC API.
## JDBC and JAXP
Another intriguing way of dealing with XML objects is within the JAXP
(Java API for XML Processing). JAXP and JDBC together provide an
infrastructure for developing applications using XML and SQL.
Whenever XML instances in applications are dealt with, an XML parser is
a good tool to use. The XML parser turns the XML document into an object
or something the application can uses. Specifically, Document Object
Model (DOM) takes and XML instance and converts it into a tree. This
specific parser can be found in the JAXP API. You may then store the
parsed object in an SQL database for future use. This may open up many
ideas of how one may use JAXP and JDBC together when an issue presents
itself of dealing with XML and SQL.
## References
- <http://www.xml.com>
- <http://java.sun.com/xml>
- Stels XML JDBC
driver - JDBC driver
for XML files.
|
# XML - Managing Data Exchange/XForms
## What Is XForms?
Forms are an important part of many web applications today. An HTML form
makes it possible for web applications to accept input from a user. Web
users now do complex transactions that are starting to exceed the
limitations of standard HTML forms. XForms is the next generation of
HTML forms and is richer and more flexible than HTML forms.\
\
XForms uses XML for data definition and HTML or XHTML for data display.
XForms separates the data logic of a form from its presentation.
Separating data from presentation makes XForms device independent,
because the data model can be used for all devices. The presentation can
be customized for different user interfaces, like mobile phones and
handheld devices and can provide interactivity between such devices. It
is also possible to add XForms elements directly into other XML
applications like VoiceXML (speaking web data), WML (Wireless Markup
Language), and SVG (Scalable Vector Graphics).\
\
## The Purpose of XForms
XForms is the separation of purpose from presentation. For example, the
purpose of a questionnaire application is to collect information about
the user. This is done by creating a presentation that allows the user
to provide the required information. Web applications typically render
such a presentation as an interactive document that is continuously
updated during user interaction. By separating the purpose from its
presentation, XForms enables the binding of different interactions to a
single model.\
## The Main Aspects of XForms
The **XForms model** defines what the form is, what data it contains,
and what it should do. The **XForms user interface** defines the input
fields and how they should be displayed. The **XForms Submit Protocol**
defines how XForms send and receive data, including the ability to
suspend and resume the completion of a form. **XForms is \"instance
data\"**, an internal representation of the data mapped to the familiar
\"form controls\". Instance data is based on XML and defined in terms of
XPath's internal tree representation and processing of XML\
## The XForms Framework
With XForms, input data is described in two different parts:
1. XForm model\
2. XForm user interface\
\
### The XForms Model
The XForm model defines what the form is, what data it contains, and
what it should do.\
The data model is an instance (a template) of an XML document. The
XForms model defines a data model inside a `<model>`{=html} element:\
` ``<model>`{=html}\
` ``<instance>`{=html}\
` ``<person>`{=html}\
` ``<fname/>`{=html}\
` ``<lname/>`{=html}\
` ``</person>`{=html}\
` ``</instance>`{=html}\
` ``<submission id="form1" action="submit.asp" method="get"/>`{=html}\
` ``</model>`{=html}
\
From the example above, you can see that the XForms model uses an
`<instance>`{=html} element to define the XML template for data to be
collected, and a `<submission>`{=html} element to describe how to submit
the data.\
The XForms model does not say anything about the visual part of the form
(the user interface).\
\
====The `<instance>`{=html} Element==== The data collected by XForms is
expressed as XML instance data. XForms is always collecting data for an
XML document. The `<instance>`{=html} element in the XForms model
defines the XML document.\
In the example above the \"data instance\" (the XML document) the form
is collecting data for looks like this:
` ``<person>`{=html}\
` ``<fname/>`{=html}\
` ``<lname/>`{=html}\
` ``</person>`{=html}
After collecting the data, the XML document might look like this:
` ``<person>`{=html}\
` ``<fname>`{=html}`Jim``</fname>`{=html}\
` ``<lname>`{=html}`Jones``</lname>`{=html}\
` ``</person>`{=html}
\
#### The `<submission>`{=html} Element
The XForms model uses a `<submission>`{=html} element to describe how to
submit the data. The `<submission>`{=html} element defines a form and
how it should be submitted. In the example above, the id=\"form1\"
attribute identifies the form, the action=\"submit.asp\" attribute
defines the URL to where the form should be submitted, and the
method=\"get\" attribute defines the method to use when submitting the
data.\
\
The following diagram shows how the XForm model has the capability to
work with a variety of user interfaces.
### The XForms User Interface
The XForms user interface is used to display and input the data. The
user interface elements of XForms are called controls (or input
controls):
` ``<input ref="fname">`{=html}`<label>`{=html}`First Name``</label>`{=html}`</input>`{=html}\
` ``<input ref="lname">`{=html}`<label>`{=html}`Last Name``</label>`{=html}`</input>`{=html}\
` ``<submit submission="form1">`{=html}`<label>`{=html}`Submit``</label>`{=html}`</submit>`{=html}
In the example above the two `<input>`{=html} elements define two input
fields. The ref=\"fname\" and ref=\"lname\" attributes point to the
`<fname>`{=html} and `<lname>`{=html} elements in the XForms model. The
`<submit>`{=html} element has a submission=\"form1\" attribute which
refers to the `<submission>`{=html} element in the XForms model. A
submit element is usually displayed as a button. Notice the
`<label>`{=html} elements in the example. With XForms every input
control element has a required `<label>`{=html} element.\
==Putting Everything Together== XForms has to run inside another XML
document. It could run inside XHTML 1.0, and it will run inside XHTML
2.0. If we put it all together, the document will look like this:
` ``<xforms>`{=html}\
` ``<model>`{=html}\
` ``<instance>`{=html}\
` ``<person>`{=html}\
` ``<fname/>`{=html}\
` ``<lname/>`{=html}\
` ``</person>`{=html}\
` ``</instance>`{=html}\
` ``<submission id="form1" action="submit.asp" method="get"/>`{=html}\
` ``</model>`{=html}\
` ``<input ref="fname">`{=html}`<label>`{=html}`First Name``</label>`{=html}`</input>`{=html}\
` ``<input ref="lname">`{=html}`<label>`{=html}`Last Name``</label>`{=html}`</input>`{=html}\
` ``<submit submission="form1">`{=html}`<label>`{=html}`Submit``</label>`{=html}`</submit>`{=html}\
` ``</xforms>`{=html}
\
## The XForms Processor
An XForms Processor built into the browser will be responsible for
submitting the XForms data to a target. The data can be submitted as XML
and could look something like this:
` ``<person>`{=html}\
` ``<fname>`{=html}`Jim``</fname>`{=html}\
` ``<lname>`{=html}`Jones``</lname>`{=html}\
` ``</person>`{=html}
Or it can be submitted as text, looking something like this:
` fname=Jim;lname=Jones`
\
## The XForms Namespace
The official namespace for XForms is: <http://www.w3.org/2002/xforms>.
If you want to use XForms in HTML (or XHTML 1.0), you should declare all
XForms elements with an XForms namespace. XForms is expected to be a
standard part of XHTML 2.0, eliminating the need for the XForms
namespace.
## An XForms Example
Take a look at this document using XForms:
` ``<xforms>`{=html}\
` ``<model>`{=html}\
` ``<instance>`{=html}\
` ``<person>`{=html}\
` ``<fname/>`{=html}\
` ``<lname/>`{=html}\
` ``</person>`{=html}\
` ``</instance>`{=html}\
` ``<submission id="form1" method="get" action="submit.asp"/>`{=html}\
` ``</model>`{=html}\
` ``<input ref="fname">`{=html}\
` ``<label>`{=html}`First Name``</label>`{=html}`</input>`{=html}\
` ``<input ref="lname">`{=html}\
` ``<label>`{=html}`Last Name``</label>`{=html}`</input>`{=html}\
\
` ``<submit submission="form1">`{=html}\
` ``<label>`{=html}`Submit``</label>`{=html}`</submit>`{=html}\
` ``</xforms>`{=html}
## The Form Controls
The components of the form that deal with data entry and display are
referred to as the form controls or user interface controls. XForms
defines a comprehensive set of device-neutral, platform-independent form
controls. For each element of data defined in the model, a form control
defines its appearance via the client. These controls can be combined
with stylesheets to provide sophisticated form displays.
```{=html}
<table border="1">
```
```{=html}
<tr>
```
```{=html}
<td>
```
**XForms form control**
```{=html}
</td>
```
```{=html}
<td>
```
**Closest XHTML equivalent**
```{=html}
</td>
```
```{=html}
<td>
```
**Description**
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<input>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
`<input type="text">`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
For entry of small amounts of text
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
<textarea>
```
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
<textarea>
```
```{=html}
</td>
```
```{=html}
<td>
```
For entry of large amounts of text
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<secret>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
```{=html}
<textarea>
```
```{=html}
</td>
```
```{=html}
<td>
```
For entry of large amounts of text
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<secret>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
`<input type="password">`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
For entry of sensitive information
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
```{=html}
<output>
```
```{=html}
</td>
```
```{=html}
<td>
```
N/A
```{=html}
</td>
```
```{=html}
<td>
```
For inline display of any instance data
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<range>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
N/A
```{=html}
</td>
```
```{=html}
<td>
```
For smooth \"volume control\" selection of a value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<upload>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
`<input type="file">`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
For upload of file or device data
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<trigger>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
`<button>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
For activation of form events
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<submit>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
`<input type="submit">`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
For submission of form data
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<select>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
`<select multiple="multiple">`{=html} or multiple
`<input type="checkbox">`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
For selection of zero, one, or many options
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
`<select1>`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
`<select>`{=html} or multiple `<input type="radio">`{=html}
```{=html}
</td>
```
```{=html}
<td>
```
For selection of just one option among several
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
## XForms Action
In the course of form processing, often some particular action needs to
happen.
```{=html}
<table border="1">
```
```{=html}
<tr>
```
```{=html}
<td>
```
**XForms Action**
```{=html}
</td>
```
```{=html}
<td>
```
**Description**
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
setfocus
```{=html}
</td>
```
```{=html}
<td>
```
Gives focus to a particular form control.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
setvalue
```{=html}
</td>
```
```{=html}
<td>
```
Sets the value of a particular node.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
message
```{=html}
</td>
```
```{=html}
<td>
```
Displays a message to the user.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
send
```{=html}
</td>
```
```{=html}
<td>
```
Submits all or part of the instance data.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
reset
```{=html}
</td>
```
```{=html}
<td>
```
Resets all or part of the instance data.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
load
```{=html}
</td>
```
```{=html}
<td>
```
Opens a document in the same or a new window.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
refresh
```{=html}
</td>
```
```{=html}
<td>
```
Refreshes the view of the instance data.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
recalculate
```{=html}
</td>
```
```{=html}
<td>
```
Recalculates the instance data.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
revalidate
```{=html}
</td>
```
```{=html}
<td>
```
Revalidates the instance data.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
setindex
```{=html}
</td>
```
```{=html}
<td>
```
Navigates through a repeating sequence.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
insert
```{=html}
</td>
```
```{=html}
<td>
```
Inserts a node from a repeating sequence.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
delete
```{=html}
</td>
```
```{=html}
<td>
```
Removes a node from a repeating sequence.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
toggle
```{=html}
</td>
```
```{=html}
<td>
```
Selects a case of a switch
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
dispatch
```{=html}
</td>
```
```{=html}
<td>
```
Dispatch an event.
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
## XForms Methods
The XForms specification uses and builds upon XPath, which includes
adding some method calls useful for forms: These can be called at any
point where XPath is allowed. Additionally, implementations can support
"extension functions" to provide additional functionality.
```{=html}
<table border="1">
```
```{=html}
<tr>
```
```{=html}
<td>
```
**Method**
```{=html}
</td>
```
```{=html}
<td>
```
**Description**
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
avg()
```{=html}
</td>
```
```{=html}
<td>
```
Returns the arithmetic mean of the indicated nodes
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
min() and max()
```{=html}
</td>
```
```{=html}
<td>
```
Returns the minimum or maximum value of the indicated nodes
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
count-non-empty()
```{=html}
</td>
```
```{=html}
<td>
```
Returns the number of non-empty nodes
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
if()
```{=html}
</td>
```
```{=html}
<td>
```
Returns one of two strings depending on a Boolean value
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
index()
```{=html}
</td>
```
```{=html}
<td>
```
Indicates the current position in a repeating sequence
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
days-from-date()
```{=html}
</td>
```
```{=html}
<td>
```
Converts an XML Schema datatype into a number of days
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
seconds-from-dateTime()
```{=html}
</td>
```
```{=html}
<td>
```
Converts an XML Schema datatype into a number of seconds
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
seconds()
```{=html}
</td>
```
```{=html}
<td>
```
Converts an XML Schema duration into a number of seconds
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
months()
```{=html}
</td>
```
```{=html}
<td>
```
Converts an XML Schema duration into a number of months
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td>
```
now()
```{=html}
</td>
```
```{=html}
<td>
```
Returns the current date/time
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
\
## See Also
- XForms Tutorial and Cookbook Wikibook This wiki
book has over 75 XForms examples with links to working XForms
applications.
|
# XML - Managing Data Exchange/XMLWebAudio
## Learning Objectives
Upon completion of this chapter, you will
- understand the potential of XML based web delivery of audio text
files
- understand the use of SSML (Synthetic Speech Markup Language), the
XML subset of tags
### The Problem:
How can text files of any content a user chooses be transferred to the
user in such a form that the end user can listen to them on a piece of
hardware that has mobile internet capability? An example would be
someone listening to a news report of any topic or from any region just
by converting text files which already exist on the internet to a
sythesized voice for playing on a mobile device in an automobile.
Existing Technology: There are several technologies available that work
with voice data. Voice XML provides a framework for transferring voice
data between entities. It is used for interactive voice triggered tools.
This technology is used extensively for phone menus and automated help
by companies with customer service or other areas of high call volume
needs.
Internet radio exists and provides a user with music or other
programming that is broadcast throughout the internet. This programming
is not up to the choice of the end user other than to select the
internet station to listen to.
Software exists that can convert any text file into an audio file. Text
files can be converted to audio files using software provided in the
Windows or Mac operating systems or very inexpensive stand-alone
software (an example is TextAloud). TextAloud allows a user to modify
the voice, the pace of reading and other features. Free versions of it
are available online. These systems can modify the voice in multiple
ways to the personal taste of a user. These systems do not make the
files available over the internet for users to search and listen to.
### The Potential:
With the right combination of XML technology, mobile communication
services and software/hardware that already exists the idea of internet
radio could be opened to a much larger volume of content than currently
exists. Most internet radio is in the form of music files and programed
radio content. The choices of internet radio could be extended to
include any existing text file which would include news reports,
government documents, educational materials and many forms of official
records. A business example would be a travelling salesman briefing
himself on a client's buying history by listening to a file in his car
on the way to a sales call with the customer. Another example includes
language conversion software that already exists that could enable a
person in a distant county to listen and learn about technology that is
being developed somewhere else.
### Requirements:
The technology would require three areas to come together to make the
process work. 1. The XML technology must include a set of agreed upon
XML tags for transferring files between content generators/distrubutors
and users. 2. The mobile communications services must be able to deliver
the data in a usable format to an end user system. 3. Hardware and
software must be able to make use of the documents sent and play them
for a user. Included in this is the further development of a voice
processing browser.
The second and third requirements are outside the scope of this chapter
on XML. However, work is being done on them. The W3C (World Wide Web
Consortium) is currently working on the Mobile Web Initiative which
would set some standards for software vendors, content providers,
hardware (handset) manufacturers, browser developers and mobile service
operators. One suggestion being considered is a maximum page weight of
10K (a typical magazine article fits within that range). The
availability of advertising being embedded and what form it would take
is under debate. Delivery protocol is expected to be http. The
connection for a mobile device can be slow but the audio files do not
have to stream. Current vendors involved include Nokia, Ericsson, HP,
France Telecom and Opera.
The first requirement would include a set of XML tags that all text file
content generators (such as news services, governments, educational
institutions and official records generators) could use to generate
files of their content. Thus their content could be accessed and stored
in a searchable database and requested for downloading and playback at
any time from anywhere that supports a mobile browser device.\
\

\
\
### The Existing Tag Set:
There is an existing set of XML tags called SSML (Synthesized Speech
Markup Language). This set enables control of enough aspects of speech
generation that a personable voice can be generated and manipulated by a
user. A Text-to-Speech system uses the tags to take a text file and
generate audible text in a voice.
**Document Structure, Text Processing and Pronunciation Elements and
Attributes:**
*speak - Root Element*
` `*`xml:lang - Attribute`*` `\
` Language (indicates the natural language of the file, such as “en-US”); this `\
` is preferred to be indicated only on the voice element so as to eliminate `\
` changes in a voice in the midst of a voice file.`\
` `*`xml:base - Attribute`*` `\
` base URI Attribute (optional)`
**EXAMPLE:**
`<speak version="1.0"
xmlns="http://www.w3.org/2001/10/synthesis"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/2001/10/synthesis
http://www.w3.org/TR/speech-synthesis/synthesis.xsd"
xml:lang="en-US">`{=html}
` ... the body ...`
`</speak>`{=html}
*lexicon - Element*
` for pronunciation, (an empty element)`
*meta - Element*
` (an empty element); includes a string that contains some information about the `\
` ensuing data; it can declare a content type of “http” in the case of a file that `\
` doesn’t have generated header fields from the originating server.`
*metadata - Element*
` can provide broader information about data as it accesses a metadata schema.`
*p - Element*
` text structure, represents a paragraph. It can only contain the following elements: `\
` audio, break, emphasis, mark, phoneme, prosody, say-as, sub, s, voice.`
*s - Element*
` text structure, Element; represents a sentence. It can only contain the following `\
` elements: audio, break, emphasis, mark, phoneme, prosody, say-as, sub, voice.`
*say-as - Element*
` available attributes: interpret-as, format, and detail phoneme with interpret-as being `\
` the only required one. The tag set may only contain text to be rendered by a voice `\
` synthesizer. This tag helps a browser to know more about the manner in which the `\
` enclosed text is to be voiced.`\
` `*`format - Attribute`*` `\
` this attribute gives additional hints as to the rendering of voiced text. `*`detail - Attribute`*\
` this attribute is for indicating the level of detail to be applied to voiced `\
` text. An example would be a special form of emphasis such as the reading of `\
` computer code in a block of text.`
*Phoneme - Element*
` a pronunciation indicator for the text to speech engine. The engine does not render `\
` the contents of the tag, thus the tag can be empty. The attributes for the tag provide `\
` what the engine will use to help with language specific pronunciation factors. `\
` However, any text between the tag set will be rendered on screen in a visual browser `\
` for hearing impaired users. This tag can only contain text, no elements.`\
` `*`alphabet - attribute`*` `\
` for Phoneme, used to specify a particular version of an alphabet, optional`\
` `*`ph - Attribute`*\
` a required attribute for phoneme, used to specify the string to be pronounced.`
*EXAMPLE:*
`<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.w3.org/2001/10/synthesis
http://www.w3.org/TR/speech-synthesis/synthesis.xsd"
xml:lang="en-US">`{=html}
` ``<phoneme alphabet="ipa" ph="təmei̥ɾou̥">`{=html}` pomegranate ``</phoneme>`{=html}\
` `\
` `
`</speak>`{=html}
*sub - Element*
` an element used to specify within its “alias” attribute the pronounced version of some `\
` written text that is between the tag set. Example:`\
` <sub alias=”American Association of Retired Persons”>AARP``</sub>`{=html}` `
Prosody and Style - prosody covers such things as tone, intonation,
conversational pacing, pitch of voice, loudness, duration of sound,
chunking (units of words, not necessarily sentences).
*voice - Element*
` indicates the type of voice to use, all the attributes are optional, however, not `\
` indicating any attributes at all is considered an error. The “lang” attribute takes `\
` precedence; all other attributes are equal.`\
` `*`lang - attribute`*` `\
` for voice element, indicates the language for the voice.`\
` `*`gender - Attribute`*\
` `*`age - Attributte`*`''`\
` `*`variant - Attributte`*\
` `*`name - Attribute`*
*EXAMPLE:*
`<voice gender="male">`{=html}Show me a person without a
goal`</voice>`{=html}
` ``<voice gender="male" variant="2">`{=html}\
` and I'll show you a stock clerk.`\
` ``</voice>`{=html}\
` `\
` ``<voice name="James">`{=html}`Show me a stock clerk with a goal and I'll show you someone who will change the world.``</voice>`{=html}
*emphasis - Element*
` contains text to be emphasized by the speech processor (with stress or intensity). It `\
` has one attribute:`\
` `*`level - Attribute`*\
` indicating the degree of emphasis.`
*EXAMPLE:*
Geniuses themselves don\'t talk about the gift of genius, they just talk
about
`<emphasis level="strong">`{=html}` hard work and long hours. ``</emphasis>`{=html}
The \"emphasis\" element can contain text and the following elements:
` `*`audio - Element`*\
` `*`desc - Element`*\
` if the content is not speech then the “desc” tag should be used to describe `\
` the content. This description can be used in a text output for the hearing `\
` impaired.`\
` `*`break - Element`*\
` `*`emphasis - Element`*` `\
` `*`mark - Element`*\
` `*`phoneme - Element`*\
` `*`prosody - Element`*\
` `*`say-as - Element`*\
` `*`sub - Element`*\
` `*`voice - Element`*
*break - Element*
` wherever the element is used between words it indicates a pause in the reading of the `\
` text; attributes are: “strength” with values of: none (meaning no pause even if the `\
` system would normally put one there), x-weak, weak, medium, strong, x-strong; “time” `\
` with values of either milliseconds: 250ms or seconds: 2s. `
*prosody - Element*
` controls the pitch, speaking rate and volume of a generated voice. Attributes `\
` are optional but it is considered an error if no attributes are set. `\
` pitch - Attribute`\
` contour - Attribute`\
` range - Attribute`\
` rate - Attribute`\
` duration - Attribute`\
` volume - Attribute`
Other elements that allow the insertion of audio files in addition to
generated voice content.
*audio - Element*
` may be empty but if it contains anything it should be the text that the speech `\
` generator could convert to a voice in place of the audio file. `
*EXAMPLE:*
```{=html}
<audio src="JCPennyQuote.au">
```
Every business is built on friendship.
```{=html}
</audio>
```
*mark - Element*
` an empty tag that places a named marker into the content. When the processor `\
` reaches a “mark” element one of two things happens. One, the processor is provided `\
` with the info to retrieve the desired position in the content, two, an event is issued `\
` that includes the content at the desired position. It has one attribute which is:`\
` `*`name - Attribute`*\
` `
*desc - Element*
### Potential Future of XML Web Audio:
Additional tags could be introduced to contain dates, titles of files,
authors, originating language and other metadata about the files.
Expanding the set of existing tags would enable the files to be stored
and searched in databases using multiple methods. They would enable
storing of data related to the actual text/audio files that would be
valuable to potential users. A user could search based on originating
date of the file, the originating country of the file and subject or
title of files.
### Conclusion
Using SSML, a subset of XML, audio files can be generated from any text
file such as news reports, government documents, educational materials
or official records. This content could be delivered via mobile
communication services and over the web. The files could be played on
mobile browser devices. This could constitute a much larger market for
internet radio than the strictly music or programmed content form it
exists in today. This could generate many uses for on-demand access to
many sources of information for travelling users.
|
# XML - Managing Data Exchange/OpenOffice.org & OpenDocument Format
+------------------------------------------------------------+
| **Learning objectives** |
| |
| - Learn how OpenOffice.org uses OpenDocument Format |
| - Learn about the zip archive |
| - Learn about OpenOffice capabilites and how to download |
| - Learn about the future of OpenDocument Format |
+------------------------------------------------------------+
| |
+------------------------------------------------------------+
## Introduction
OpenOffice.org is exactly what its title suggests: an open source office
applications suite. It is based on the source of Sun Microsystems\'
StarOffice, which was donated to the open source community in 2000.
OpenOffice.org will read and save files in several formats used by other
office applications, but its default format is OpenDocument, which is an
XML format standardized by OASIS (Organization for the Advancement of
Structured Information Standards). Because of these two factors, an open
source editor and XML-based files, OpenOffice.org is poised to be of
great importance in the very near future as the trend continues for
national governments, particularly in the European Union, to require
that all electronic government documents be saved in an open source
format.
## OpenDocument Format
As stated in the introduction, OpenDocument is an XML format
standardized by OASIS. An OpenDocument file takes the form of a
compressed zip archive with one of the following extensions:
- .odt (text)
- .ott (text template)
- .odm (master document)
- .oth (HTML template)
- .ods (spreadsheet)
- .ots (spreadsheet template)
- .odg (drawing)
- .otg (drawing template)
- .odp (presentation)
- .otp (presentation template)
- .odf (formula)
- .odb (database)
(Note that all of these extensions are version 2.0 only)
The zip archive contains the following files and directories (from
OpenOffice.org Help documentation):
- The actual text of the document is stored in
`<b>`{=html}content.xml`</b>`{=html}. By default this is a
stripped-down version of the document that leaves out formatting
elements such as indentation or line breaks in order to streamline
saving and opening the document.
**content.xml Example**
+-------------------------------------------------+
| ``` xml |
| <office:document-content namespace declarations |
| office:version="1.0" |
| office:class="document type"> |
| |
| <office:scripts/> |
| |
| <office:font-face-decls> |
| <!-- font specifications --> |
| </office:font-decls> |
| |
| <office:styles> |
| <office:automatic-styles> |
| <!-- style information --> |
| </office:automatic-styles> |
| </office:styles> |
| |
| <office:body> |
| <office:documentType> |
| <!-- actual content here --> |
| </office:documentType> |
| </office:body> |
| </office:document-content> |
| ``` |
+-------------------------------------------------+
| |
+-------------------------------------------------+
- **meta.xml** contains the meta information of the document, which
can be edited in File -- Properties. If a document is saved with a
password, meta.xml will not be encrypted.
**meta.xml Example**
+----------------------------------------------------------------------+
| ``` xml |
| <?xml version="1.0" encoding="UTF-8" ?> |
| <office:document-meta xmlns: |
| office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:xlin |
| k="http://www.w3.org/1999/xlink" xmlns:dc="http://purl.org/dc/elemen |
| ts/1.1/" xmlns:meta="urn:oasis:names:tc:opendocument:xmlns:meta:1.0" |
| xmlns:ooo="http://openoffice.org/2004/office" office:version="1.0"> |
| <office:meta> |
| <meta:generator>OpenOffice.org |
| /2.0$Win32 OpenOffice.org_project/680m1$Build-8990</meta:generator> |
| <meta:initial-creator>Creator Name</meta:initial-creator> |
| <meta:creation-date>2006-03-27T19:17:57</meta:creation-date> |
| <dc:creator>Creator Name</dc:creator> |
| <dc:date>2006-03-27T20:58:06</dc:date> |
| <dc:language>en-US</dc:language> |
| <meta:editing-cycles>2</meta:editing-cycles> |
| <meta:editing-duration>PT1H40M37S</meta:editing-duration> |
| <meta:user-defined meta:name="Info 1" /> |
| <meta:user-defined meta:name="Info 2" /> |
| <meta:user-defined meta:name="Info 3" /> |
| <meta:user-defined meta:name="Info 4" /> |
| <meta:document-statistic meta:table-count="0" meta: |
| image-count="0" meta:object-count="0" meta:page-count="2" meta:parag |
| raph-count="6" meta:word-count="567" meta:character-count="3550" /> |
| </office:meta> |
| </office:document-meta> |
| ``` |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
- **settings.xml** contains further information about the settings for
this document.
**settings.xml Example**
+----------------------------------------------------------------------+
| ``` xml |
| <?xml version="1.0" encoding="UTF-8" ?> |
| - <office:document-settings xmlns:office="urn:oasis:names:tc:o |
| pendocument:xmlns:office:1.0" xmlns:xlink="http://www.w3.org/1999/xl |
| ink" xmlns:config="urn:oasis:names:tc:opendocument:xmlns:config:1.0" |
| xmlns:ooo="http://openoffice.org/2004/office" office:version="1.0"> |
| - <office:settings> |
| - <config:config-item-set config:name="ooo:view-settings"> |
| <config:config-item c |
| onfig:name="ViewAreaTop" config:type="int">635</config:config-item> |
| <config:config-item |
| config:name="ViewAreaLeft" config:type="int">0</config:config-item> |
| <config:config-item confi |
| g:name="ViewAreaWidth" config:type="int">25852</config:config-item> |
| <config:config-item config |
| :name="ViewAreaHeight" config:type="int">14818</config:config-item> |
| <config:config-item config:name=" |
| ShowRedlineChanges" config:type="boolean">true</config:config-item> |
| <config:config-item config:n |
| ame="InBrowseMode" config:type="boolean">false</config:config-item> |
| - <config:config-item-map-indexed config:name="Views"> |
| - <config:config-item-map-entry> |
| <config:config-item c |
| onfig:name="ViewId" config:type="string">view2</config:config-item> |
| <config:config-item |
| config:name="ViewLeft" config:type="int">17549</config:config-item> |
| <config:config-ite |
| m config:name="ViewTop" config:type="int">4949</config:config-item> |
| <config:config-item |
| config:name="VisibleLeft" config:type="int">0</config:config-item> |
| <config:config-item |
| config:name="VisibleTop" config:type="int">635</config:config-item> |
| <config:config-item conf |
| ig:name="VisibleRight" config:type="int">25850</config:config-item> |
| <config:config-item confi |
| g:name="VisibleBottom" config:type="int">15452</config:config-item> |
| <config:config-ite |
| m config:name="ZoomType" config:type="short">0</config:config-item> |
| <config:config-item co |
| nfig:name="ZoomFactor" config:type="short">100</config:config-item> |
| <config:config-item config:name |
| ="IsSelectedFrame" config:type="boolean">false</config:config-item> |
| </config:config-item-map-entry> |
| </config:config-item-map-indexed> |
| </config:config-item-set> |
| - <config:config-item-set config:name="ooo:configuration-settings"> |
| <config:config-item config:name="A |
| ddParaTableSpacing" config:type="boolean">true</config:config-item> |
| <config:config-item config:na |
| me="PrintReversed" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="OutlineLev |
| elYieldsNumbering" config:type="boolean">false</config:config-item> |
| <config:config-item conf |
| ig:name="LinkUpdateMode" config:type="short">1</config:config-item> |
| <config:config-item config:name="IgnoreFirstLine |
| IndentInNumbering" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="C |
| haracterCompressionType" config:type="short">0</config:config-item> |
| <config:config-item config:name |
| ="PrintSingleJobs" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="U |
| pdateFromTemplate" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="Pr |
| intPaperFromSetup" config:type="boolean">false</config:config-item> |
| <config:config-item config:name |
| ="AddFrameOffsets" config:type="boolean">false</config:config-item> |
| <config:config-item config:na |
| me="PrintLeftPages" config:type="boolean">true</config:config-item> |
| <config:config-it |
| em config:name="RedlineProtectionKey" config:type="base64Binary" /> |
| <config:config-item config |
| :name="PrintTables" config:type="boolean">true</config:config-item> |
| <config:config-item config:nam |
| e="ChartAutoUpdate" config:type="boolean">true</config:config-item> |
| <config:config-item config:n |
| ame="PrintControls" config:type="boolean">true</config:config-item> |
| <config:c |
| onfig-item config:name="PrinterSetup" config:type="base64Binary" /> |
| <config:config-item config:na |
| me="PrintAnnotationMode" config:type="short">0</config:config-item> |
| <config:config-item config:n |
| ame="LoadReadonly" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="AddParaS |
| pacingToTableCells" config:type="boolean">true</config:config-item> |
| <config:config-item config:name=" |
| AddExternalLeading" config:type="boolean">true</config:config-item> |
| <config:config-item config:n |
| ame="ApplyUserData" config:type="boolean">true</config:config-item> |
| <config:config-item config:nam |
| e="FieldAutoUpdate" config:type="boolean">true</config:config-item> |
| <config:config-item config:name="S |
| aveVersionOnClose" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="SaveGl |
| obalDocumentLinks" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="IsKer |
| nAsianPunctuation" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="Al |
| ignTabStopPosition" config:type="boolean">true</config:config-item> |
| <config:config-i |
| tem config:name="CurrentDatabaseDataSource" config:type="string" /> |
| <c |
| onfig:config-item config:name="PrinterName" config:type="string" /> |
| <co |
| nfig:config-item config:name="PrintFaxName" config:type="string" /> |
| <config:config-item config:name="Conside |
| rTextWrapOnObjPos" config:type="boolean">false</config:config-item> |
| <config:config-item config:nam |
| e="PrintRightPages" config:type="boolean">true</config:config-item> |
| <config:config-item config:name |
| ="IsLabelDocument" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="Use |
| FormerLineSpacing" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="AddParaT |
| ableSpacingAtStart" config:type="boolean">true</config:config-item> |
| <config:config-item config:name="UseF |
| ormerTextWrapping" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="DoNotResetPa |
| raAttrsForNumFont" config:type="boolean">false</config:config-item> |
| <config:config-item config:na |
| me="PrintProspect" config:type="boolean">false</config:config-item> |
| <config:config-item config:n |
| ame="PrintGraphics" config:type="boolean">true</config:config-item> |
| <config:config-item config:name="A |
| llowPrintJobCancel" config:type="boolean">true</config:config-item> |
| <config:config-item config:name="C |
| urrentDatabaseCommandType" config:type="int">0</config:config-item> |
| <config:config-item config:name="DoNotJustifyLin |
| esWithManualBreak" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="UseFormer |
| ObjectPositioning" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="PrinterIndepende |
| ntLayout" config:type="string">high-resolution</config:config-item> |
| <config:config-item config:name |
| ="UseOldNumbering" config:type="boolean">false</config:config-item> |
| <config:config-item config:name="P |
| rintPageBackground" config:type="boolean">true</config:config-item> |
| <config:confi |
| g-item config:name="CurrentDatabaseCommand" config:type="string" /> |
| <config:config-item config:n |
| ame="PrintDrawings" config:type="boolean">true</config:config-item> |
| <config:config-item config:name |
| ="PrintBlackFonts" config:type="boolean">false</config:config-item> |
| </config:config-item-set> |
| </office:settings> |
| </office:document-settings> |
| ``` |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
- **styles.xml** contains the styles applied to the document that can
be seen in the Styles and Formatting window.
**styles.xml Example**
+----------------------------------------------------------------------+
| ``` xml |
| |
| <?xml version="1.0" encoding="UTF-8" ?> |
| <office:document-styles xmlns:of |
| fice="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:style= |
| "urn:oasis:names:tc:opendocument:xmlns:style:1.0" xmlns:text="urn:oa |
| sis:names:tc:opendocument:xmlns:text:1.0" xmlns:table="urn:oasis:nam |
| es:tc:opendocument:xmlns:table:1.0" xmlns:draw="urn:oasis:names:tc:o |
| pendocument:xmlns:drawing:1.0" xmlns:fo="urn:oasis:names:tc:opendocu |
| ment:xmlns:xsl-fo-compatible:1.0" xmlns:xlink="http://www.w3.org/199 |
| 9/xlink" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:meta="urn |
| :oasis:names:tc:opendocument:xmlns:meta:1.0" xmlns:number="urn:oasis |
| :names:tc:opendocument:xmlns:datastyle:1.0" xmlns:svg="urn:oasis:nam |
| es:tc:opendocument:xmlns:svg-compatible:1.0" xmlns:chart="urn:oasis: |
| names:tc:opendocument:xmlns:chart:1.0" xmlns:dr3d="urn:oasis:names:t |
| c:opendocument:xmlns:dr3d:1.0" xmlns:math="http://www.w3.org/1998/Ma |
| th/MathML" xmlns:form="urn:oasis:names:tc:opendocument:xmlns:form:1. |
| 0" xmlns:script="urn:oasis:names:tc:opendocument:xmlns:script:1.0" x |
| mlns:ooo="http://openoffice.org/2004/office" xmlns:ooow="http://open |
| office.org/2004/writer" xmlns:oooc="http://openoffice.org/2004/calc" |
| xmlns:dom="http://www.w3.org/2001/xml-events" office:version="1.0"> |
| - <office:font-face-decls> |
| <style:font-face style:name="Tahoma1" svg:font-family="Tahoma" /> |
| <style:font-face style:name="Arial Unicode MS" |
| svg:font-family="'Arial Unicode MS'" style:font-pitch="variable" /> |
| <style:font-face style:na |
| me="Tahoma" svg:font-family="Tahoma" style:font-pitch="variable" /> |
| <style:font |
| -face style:name="Times New Roman" svg:font-family="'Times New Roman |
| '" style:font-family-generic="roman" style:font-pitch="variable" /> |
| <style:font-face style:name="Arial" svg:font-family="Aria |
| l" style:font-family-generic="swiss" style:font-pitch="variable" /> |
| </office:font-face-decls> |
| - <office:styles> |
| - <style:default-style style:family="graphic"> |
| <style:graphic-properties |
| draw:shadow-offset-x="0.1181in" draw:shadow-offset-y="0.1181in" draw |
| :start-line-spacing-horizontal="0.1114in" draw:start-line-spacing-ve |
| rtical="0.1114in" draw:end-line-spacing-horizontal="0.1114in" draw:e |
| nd-line-spacing-vertical="0.1114in" style:flow-with-text="false" /> |
| - <style:paragraph-properties |
| style:text-autospace="ideograph-alpha" style:line-break="strict" sty |
| le:writing-mode="lr-tb" style:font-independent-line-spacing="false"> |
| <style:tab-stops /> |
| </style:paragraph-properties> |
| <style:text-prop |
| erties style:use-window-font-color="true" fo:font-size="12pt" fo:lan |
| guage="en" fo:country="US" style:font-size-asian="12pt" style:langua |
| ge-asian="none" style:country-asian="none" style:font-size-complex=" |
| 12pt" style:language-complex="none" style:country-complex="none" /> |
| </style:default-style> |
| - <style:default-style style:family="paragraph"> |
| <style:paragraph-properti |
| es fo:hyphenation-ladder-count="no-limit" style:text-autospace="ideo |
| graph-alpha" style:punctuation-wrap="hanging" style:line-break="stri |
| ct" style:tab-stop-distance="0.4925in" style:writing-mode="page" /> |
| <style:text-p |
| roperties style:use-window-font-color="true" style:font-name="Times |
| New Roman" fo:font-size="12pt" fo:language="en" fo:country="US" styl |
| e:font-name-asian="Arial Unicode MS" style:font-size-asian="12pt" st |
| yle:language-asian="none" style:country-asian="none" style:font-name |
| -complex="Tahoma" style:font-size-complex="12pt" style:language-comp |
| lex="none" style:country-complex="none" fo:hyphenate="false" fo:hyph |
| enation-remain-char-count="2" fo:hyphenation-push-char-count="2" /> |
| </style:default-style> |
| - <style:default-style style:family="table"> |
| <style:table-properties table:border-model="collapsing" /> |
| </style:default-style> |
| - <style:default-style style:family="table-row"> |
| <style:table-row-properties fo:keep-together="auto" /> |
| </style:default-style> |
| <style:style s |
| tyle:name="Standard" style:family="paragraph" style:class="text" /> |
| - <style:style |
| style:name="Text_20_body" style:display-name="Text body" style:famil |
| y="paragraph" style:parent-style-name="Standard" style:class="text"> |
| <style:para |
| graph-properties fo:margin-top="0in" fo:margin-bottom="0.0835in" /> |
| </style:style> |
| - <style:style s |
| tyle:name="Heading" style:family="paragraph" style:parent-style-name |
| ="Standard" style:next-style-name="Text_20_body" style:class="text"> |
| <style:paragraph-properties fo:margin-top=" |
| 0.1665in" fo:margin-bottom="0.0835in" fo:keep-with-next="always" /> |
| |
| <style:text-properties style:font-name="Arial" fo:font-size="14pt" s |
| tyle:font-name-asian="Arial Unicode MS" style:font-size-asian="14pt" |
| style:font-name-complex="Tahoma" style:font-size-complex="14pt" /> |
| </style:style> |
| - <style:style style:name="List" style:family="p |
| aragraph" style:parent-style-name="Text_20_body" style:class="list"> |
| <style:text-properties style:font-name-complex="Tahoma1" /> |
| </style:style> |
| - <style:style style:name="Caption" style:family |
| ="paragraph" style:parent-style-name="Standard" style:class="extra"> |
| <style:paragraph-properties fo:margin-top="0.0835in" fo:margin- |
| bottom="0.0835in" text:number-lines="false" text:line-number="0" /> |
| <style:text-properties fo |
| :font-size="12pt" fo:font-style="italic" style:font-size-asian="12pt |
| " style:font-style-asian="italic" style:font-name-complex="Tahoma1" |
| style:font-size-complex="12pt" style:font-style-complex="italic" /> |
| </style:style> |
| - <style:style style:name="Index" style:family |
| ="paragraph" style:parent-style-name="Standard" style:class="index"> |
| <style:par |
| agraph-properties text:number-lines="false" text:line-number="0" /> |
| <style:text-properties style:font-name-complex="Tahoma1" /> |
| </style:style> |
| - <text:outline-style> |
| - <text:outline-level-style text:level="1" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="2" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="3" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="4" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="5" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="6" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="7" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="8" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="9" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| - <text:outline-level-style text:level="10" style:num-format=""> |
| <style:list-level-properties text:min-label-distance="0.15in" /> |
| </text:outline-level-style> |
| </text:outline-style> |
| <text:notes-configuration te |
| xt:note-class="footnote" style:num-format="1" text:start-value="0" t |
| ext:footnotes-position="page" text:start-numbering-at="document" /> |
| <text:notes-configuration tex |
| t:note-class="endnote" style:num-format="i" text:start-value="0" /> |
| <text:linenumberin |
| g-configuration text:number-lines="false" text:offset="0.1965in" sty |
| le:num-format="1" text:number-position="left" text:increment="5" /> |
| </office:styles> |
| - <office:automatic-styles> |
| - <style:page-layout style:name="pm1"> |
| - <style:page-layout-prop |
| erties fo:page-width="8.5in" fo:page-height="11in" style:num-format= |
| "1" style:print-orientation="portrait" fo:margin-top="0.7874in" fo:m |
| argin-bottom="0.7874in" fo:margin-left="0.7874in" fo:margin-right="0 |
| .7874in" style:writing-mode="lr-tb" style:footnote-max-height="0in"> |
| <style:footnote-sep style:width="0.0071in" style:di |
| stance-before-sep="0.0398in" style:distance-after-sep="0.0398in" sty |
| le:adjustment="left" style:rel-width="25%" style:color="#000000" /> |
| </style:page-layout-properties> |
| <style:header-style /> |
| <style:footer-style /> |
| </style:page-layout> |
| </office:automatic-styles> |
| - <office:master-styles> |
| <styl |
| e:master-page style:name="Standard" style:page-layout-name="pm1" /> |
| </office:master-styles> |
| </office:document-styles> |
| ``` |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
- **manifest.xml** in the meta-inf directory describes the structure
of the XML file.
**manifest.xml Example**
+--------------------------------------------------------------------------+
| ``` xml |
| <?xml version="1.0" encoding="UTF-8"?> |
| <!DOCTYPE manifest:manifest |
| PUBLIC "-//OpenOffice.org//DTD Manifest 1.0//EN" "Manifest.dtd"> |
| <manifest:manifest |
| xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0"> |
| <manifest:file-entry |
| manifest:media-type="application/vnd.oasis.opendocument.text" |
| manifest:full-path="/"/> |
| <manifest:file-entry |
| manifest:media-type="application/vnd.sun.xml.ui.configuration" |
| manifest:full-path="Configurations2/"/> |
| <manifest:file-entry |
| manifest:media-type="" manifest:full-path="Pictures/"/> |
| <manifest:file-entry |
| manifest:media-type="text/xml" manifest:full-path="content.xml"/> |
| <manifest:file-entry |
| manifest:media-type="text/xml" manifest:full-path="styles.xml"/> |
| <manifest:file-entry |
| manifest:media-type="text/xml" manifest:full-path="meta.xml"/> |
| <manifest:file-entry |
| manifest:media-type="" |
| manifest:full-path="Thumbnails/thumbnail.png"/> |
| <manifest:file-entry |
| manifest:media-type="" manifest:full-path="Thumbnails/"/> |
| <manifest:file-entry |
| manifest:media-type="text/xml" manifest:full-path="settings.xml"/> |
| </manifest:manifest> |
| ``` |
+--------------------------------------------------------------------------+
| |
+--------------------------------------------------------------------------+
- Other files and folders may be included in the archive if necessary.
The schema for the OpenDocument formats may be found at
<http://www.oasis-open.org/committees/download.php/12572/OpenDocument-v1.0-os.pdf>
(caution: 706 pages).
## Open Office Capabilites
OpenOffice contains WRITER which is OpenOffice.org's word processor.
CALC is a powerful spreadsheet that has all the tools needed to
calculate, analyze, summarize, and present data. IMPRESS is a fast and
powerful way to create effective multimedia presentations. DRAW will
produce everything from simple diagrams to dynamic 3D illustrations and
special effects. New to Version 2, BASE enables you to manipulate
database data seamlessly within OpenOffice.org. It allows the creation
and modification of tables, forms, queries, and reports.
Download at <http://download.openoffice.org/>
## The Future of OpenDocument
Government and business leaders alike are beginning to realize the
importance of open source document formats and to act upon this
realization. In July 2005, Norway\'s Minister of Modernization, Morton
A. Meyer, presented a plan for information technology in Norway called
"eNorge---the digital leap," in which open standards and open source are
addressed. Meyer\'s objectives for open standards and open source are as
follows:
- Within 2009 all new ICT- and information systems in the public
sector shall use open standards.
- Within 2006 a set of management/administrative standards for data
and document exchange should be established.
- Within 2006 all operations in the public sector should have
introduced plans for how they will use open standards, service
oriented architecture and open source.
- Within 2008 all data and document exchange in the public sector
shall satisfy the management/administrative standards.
- Within 2008 all public forms shall be built on a common interface.
Also, Meyer said "Proprietary formats will no longer be acceptable in
communication between citizens and government."
In the US, IBM\'s Vice President of Standards and Open Source, Bob
Sutor, made the following recommendations to users in his blog as part
of an "Open Document Commitment to Action":
- Insist today that the provider of your office applications (word
processor, spreadsheet, presentation software) is committed to
support the OASIS OpenDocument Format for Office Applications
standard in their products by January 1, 2007.
- Insist today that the office applications you deploy allow users to
easily set the OASIS OpenDocument standard as the default \"save\"
format for your documents. That is, you should not have to go to a
lot of trouble to avoid using proprietary formats.
- Get a commitment from your office applications provider to join and
contribute to the OASIS OpenDocument standard technical committee.
- Ask your CIO when you will be able to use office applications that
support the OASIS OpenDocument standard.
- Ask your local and federal governments when they will be supporting
the OASIS OpenDocument standard.
- Insist that any XML document format you use is not encumbered by
proprietary extensions, and that the format is freely available for
anyone to implement without restrictions, including open source
communities that use a GPL license. Ensure that if implementers must
accept a license covering the format, the license is clear and
unambiguous on these important issues.
- **\"They are your documents: you should be able to do whatever you
want with them, whenever you want, with whatever application you
wish to use\"**
The implications are clear. The computing world is moving toward open
source software and file types for information exchange, especially in
business and government, and OpenOffice.org, with its XML-based format,
stands to be at the front of the pack.
## Additional Links
<http://www.oasis-open.org/committees/tc_home.php?wg_abbrev=office>
<http://www.sun.com/software/star/staroffice/index.jsp>
<http://www.koffice.org/>
## Works Cited
"Norwegian Minister says that all public sectors need to make a plan for
the use of Open Source by 2005." Europa---IDABC. July 6, 2005.
<http://ec.europa.eu/idabc/en/document/4403/469>.
Bob Sutor. "Open standards, open source, open minds, open
opportunities." IBM developerWorks. October 11, 2005.
<http://www-128.ibm.com/developerworks/blogs/dw_blog_comments.jspa?blog=384&entry=97126>.
"XML File Formats." Help documentation, Sun Microsystems, Inc.,
OpenOffice.org version 2.0, 2000-2005.
|
# XML - Managing Data Exchange/Google earth
## KML Introduction
(most content here is directly quoted from the KML wikipedia
article)
**KML** (**K**eyhole **M**arkup **L**anguage) is an XML-based Markup
language for managing the display of three-dimensional geospatial data
in the programs Google Earth, Google Maps, Google Mobile, ArcGIS
Explorer and World Wind. (The word *Keyhole* is an earlier name for the
software that became Google Earth; the software was produced in turn by
Keyhole, Inc, which was acquired by Google in 2004. The term \"Keyhole\"
actually honors the KH-11\|KH reconnaissance satellites, the original
eye-in-the-sky military reconnaissance system now some 30 years old.)
The KML file specifies a set of features (placemarks, images, polygons,
3D models, textual descriptions, etc.) for display in Google Earth, Maps
and Mobile. Each place always has a longitude and a latitude. Other data
can make the view more specific, such as tilt, heading, altitude, which
together define a \"camera view\". KML shares some of the same
structural grammar as Geography Markup
Language\|GML1. Some KML information
cannot be viewed in Google Maps or Mobile
2.
KML files are very often distributed as **KMZ** files, which are Data
compression\|zipped KML files with a .kmz extension. When a KMZ file is
unzipped, a single \"doc.kml\" is found along with any overlay and icon
images referenced in the KML.
Example KML document:
``\
` <?xml version="1.0" encoding="UTF-8"?>`\
` <kml xmlns="http://earth.google.com/kml/2.0">`\
` <Placemark>`\
` <description>New York City</description>`\
` <name>New York City</name>`\
` <Point>`\
` <coordinates>-74.006393,40.714172,0</coordinates>`\
` </Point>`\
` </Placemark>`\
` </kml>`
The MIME type associated to KML is
*application/vnd.google-earth.kml+xml*.\
The MIME type associated to KMZ is *application/vnd.google-earth.kmz* .
## Basic KML Document Types
For an XML document to recognize KML specific tags you must declare the
KML namespace (listed below).
`<kml xmlns="http://earth.google.com/kml/2.0">`{=html}
You will see this declaration in all the example files listed.
In order to see use the examples provided in this chapter you will need
to copy and paste the text into any text editor. Next you will save the
file as a .kml. This can be done by choosing \"save as\" and naming the
file with a .kml extension (You might have to surround the name in
quotes ie \"test.kml\").
### Placemarks
Placemarks simply make a clickable pinpoint inside Google Earth at an
exact location based on coordinates. This can be useful for marking a
point of interest or a beginning and ending destination to a trip.
The example KML document in the introduction uses the Placemark tag. If
you want to move the placemark to a different location all you would
change are the coordinates.
### Paths
Paths are a series of connected coordinates that can be edited with line
styles for a more bold appearance inside Google Earth. The height and
color can be adjusted for a more exaggerated appearance and better
clarity.
The following example is a path from Atlanta, Georgia to Nashville,
Tennessee. The code may look a bit complicated but it is mostly just
styling/formatting tags with the 4 actual coordinates at near the end.
So if you wanted to use the same style wall but just make a different
path, all you would do is change the coordinates.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Document>
<name>Paths</name>
<description>Path from Atlanta to Nashville</description>
<Style id="yellowLineGreenPoly">
<LineStyle>
<color>7f00ffff</color>
<width>4</width>
</LineStyle>
<PolyStyle>
<color>7f00ff00</color>
</PolyStyle>
</Style>
<Placemark>
<name>Atlanta to Nashville</name>
<description>Wall structured path</description>
<styleUrl>#yellowLineGreenPoly</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
<altitudeMode>absolute</altitudeMode>
<coordinates>
-84.40204442007513,33.75488573910702,83269
-84.37837132006098,33.82567285375923,83269
-84.79700041857893,35.30711817667424,83269
-86.79210094043326,36.15389499208452,83269
</coordinates>
</LineString>
</Placemark>
</Document>
</kml>
### Overlays
Overlays are graphics that can be placed over an area in Google Earth
marked by coordinates. These graphics can show how an area looked at a
different point in time or during a special event (like a volcanic
eruption).
This overlay example comes from Google\'s KML samples webpage and shows
what Mt. Etna looked like during an actual eruption.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Folder>
<name>Ground Overlays</name>
<description>Examples of ground overlays</description>
<GroundOverlay>
<name>Large-scale overlay on terrain</name>
<description>Overlay shows Mount Etna erupting
on July 13th, 2001.</description>
<Icon>
<href>http://code.google.com/apis/kml/documentation/etna.jpg</href>
</Icon>
<LatLonBox>
<north>37.91904192681665</north>
<south>37.46543388598137</south>
<east>15.35832653742206</east>
<west>14.60128369746704</west>
<rotation>-0.1556640799496235</rotation>
</LatLonBox>
</GroundOverlay>
</Folder>
</kml>
You can see from the code that it takes the image etna.jpg and places it
over the coordinates listed.
### Polygons
Polygons are a neat feature of Google Earth that allow 3-D shapes to be
molded anywhere in Google Earth. These shapes can be useful for making
neat presentations or just showing the world a structure actually looks.
This example is a polygon of Turner Field (The Atlanta Braves\' home
stadium) in Georgia. There is no styling on the polygon to keep the code
simple.
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://earth.google.com/kml/2.1">
<Placemark>
<name>Turner Field</name>
<Polygon>
<extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode>
<outerBoundaryIs>
<LinearRing>
<coordinates>
-84.39024224888713,33.73459764262901,28
-84.38961532726215,33.73451197628319,28
-84.38830478530726,33.7350571795205,28
-84.38811742696677,33.73579651137399,28
-84.38856034410841,33.73618350237595,28
-84.38930790023139,33.73647497375488,28
-84.38997872537549,33.73655338302832,28
-84.39051294303495,33.73605785090994,28
-84.39056804786146,33.73528763589146,28
-84.39024224888713,33.73459764262901,28
</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
</Placemark>
</kml>
As you can see from the code, the polygon\'s 3-D shape is made up from
the latitude and longitude coordinates with the height being determined
by the 3rd column value inside the coordinates tag (28 in this case).
## Google Earth
Google Earth is the name of Google\'s free software that is responsible
for handling these KML documents. It is a virtual world created by a
collage of satellite images where a user can manipulate the Earth in any
way to see its landscapes, oceans, and cities.
You can find more information and download the software
here.
### Basic Interface Navigation
The user interface is fairly straight forward and is extremely easy for
computer illiterate users to just jump right in and start exploring. You
can completely ignore the toolbars and buttons if you want and just
click and grab on the Earth to shake, spin, or roll it as you please. To
zoom in, simply right-click and pull down or up depending on the speed
which you prefer to \"fall\" toward the surface.
If you would like help finding a location you can type in the location
(in the form of City, State) in the \"Fly to..\" search box. Google
Earth will then spin around and zoom in to the location entered. If you
want to take a virtual vacation, Google has some preset locations saved
in the window below \"Fly to\...\" labeled \"Sightseeing.\" Simply click
on one of these locations and be taken to the location where pictures,
articles, and comments can be all be viewed.
### Points of Interest
Points of interest that Google has already marked for users are marked
with different color dots and icons. These can be clicked on for a
variety of information ranging from a simple comment, to a panoramic
photograph of that exact location. Advanced users, interested in the
code make-up of such a feature, can right click on any of Google\'s
marks and choose \"Copy.\" This will copy all the code for that feature
where you can just paste it into a text document to see all of the tags
and references.
## More References
### External links
- KML Documentation
- Developer Knowledge Base: KML in Google
Earth
- KML Developer Support
group
- KMLImporter
importing placemarks into NASA World
Wind
- Use hierarchical maps (Mindmaps) to create
and manage KML files and convert Excel
data to KML.
- Google Earth Connectivity
Add-on
for ArchiCAD 9
### Other notes
- Point of Interest
- Geography Markup
Language
### Wikipedia in other languages
- w:ar:كيه إم إل (Arabian)
- w:de:Keyhole Markup
Language (German)
- w:es:KML (Spanish)
- w:it:Keyhole Markup
Language (Italian)
- w:hu:Keyhole Markup
Language (Hungarian)
- w:nl:Keyhole Markup
Language (Dutch)
- w:pl:Keyhole Markup
Language (Polish)
- w:ru:KML (Russian)
: /Exercises/
|
# XML - Managing Data Exchange/acord
+--------------------------------------------------------------------+
| **Learning objectives** |
| |
| - get to know insurance industry\'s standardization organization |
| - understand how XML is used in the insurance industry |
| - realize why industry standards are so important |
| - comprehend the main aspects of the ACORD XML standard |
| - learn about the advantages of using ACORD XML |
+--------------------------------------------------------------------+
| |
+--------------------------------------------------------------------+
## Introduction
ACORD is the **A**ssociation for **C**ooperative
**O**perations **R**esearch and **D**evelopment.
### Organization
## ACORD
ACORD was founded in 1970 as a standards-setting organization for the
insurance industry. As a global non-profit organization, they develop
and provide cost saving digital standards for data interchange to reduce
paperwork. The goals of their standards are to minimize redundant work
and maximize data accuracy; making life far easier for all companies,
agents and policyholders \[1\].
### Work
The standards are the result of the work of all members, synchronized by
ACORD working groups. Finally the ACORD Steering Committees will decide,
which results would end up as public standards, in coordination with
other standardization organizations and governments.
One of the recent standards incorporates the use of XML as a frame for
flexible data transmission and interchange. In 2001 XML for P&C and
Surety Version 1.0 was approved, in 2002 Version 1.2 was approved
\[1\].
### XML
XML provides an open standard, with easy to be
made connectivity between
ERP
systems, managment systems, web services, web applications and other
related systems. It can be used in business-to-business,
customer-to-business and business-to-customer applications.
## Benefits of ACORD XML
Usually the benefits of XML are across all industries and domains of
similar type, but that does not apply to the insurance industry. There
you can find unique benefits like \[6\]:
### Partner to Partner Integration
Common data elements and definitions are necessary to deal with external
business partners in this industry. So you need a common language to
share data with all actors from the value chain, e.g. reinsurers or
intermediaries. By involving this actors in the process of development
ACORD designed this common language and data standards.
### Internal Integration
The Insurance industry requires the separation of communication systems
to complete a business process. Furthermore a claim adjuster, who wants
to verify coverage or to ensure that the claim\'s code is correct, needs
a system that offers accurate transfer of the claim or policy number.
ACORD XML standards are essential to transfer such items from system to
system.
### Electronic Data Sharing
Moreover the data should have a high quality and transparency. Without
that it is not possible for carriers to get exposure information in
disparate and incompatible formats in order to identify aggregation of
exposure across customers and lines of business in an effective way.
Reinsurers need high visibility into cedent risk portfolios for
extensive exposure analyses. ACORD data standards support a format that
captures and analyzes information and data in multiple formats across
partners.
### Web Services
By reason of Web Services are required for real time integration
througout the transaction processing cycle, ACORD standards realise
processes like the integration of back-end systems with an agent portal.
### Document Repository Standards
A single repository for all risk related information is in general not
possible. Due to the fact that consistency across data repositories is
very important, ACORD XML standards were established to allow trading
partners to share structured and unstructured documents and data also in
a variety of third party systems. Therefore Document Repository
Interface Standards exist to guarantee access to free format
documentation for improving decisions.
### Improved Cash Flow
By using ACORD XML standards transaction processing is accelerated.
Consequently there is a faster access to money or other types of
payments.
## Standards
Following standards allows different companies along the value chain of
a market to exchange data with less \"frictional losses\" that are
usually generated by the usage of incompatible data formats. A standard
serves as a common communication method to increase efficiency - a
lowest common denominator. It is a set of rules and guidelines that
provide a common framework for
communication.1 The set of ACORD
standards consists of subsets for the 3 main segments of insurance
industry. These are:
- Life, Annuity and Health
- Property and Casualty
- Reinsurance and Large Commercial
By implementing and following ACORD\'s standard definitions, member
companies can achieve \...
- competitive advantages
- end-to-end process support
- easier access to markets
- lower costs, which lead to more profit
- better market acceptance
- higher performance and enhanced credibility.
As seen in the previous chapters (esp. in \"Introduction to
XML\")
using XML as a means of data exchange is a suitable base for a standard
like ACORD. It\'s flexible enough to be tailored for the usage within
different insurance segments but it also offers methods to ensure data
quality and the stability of the standard.
## Technical Standardization
The ACORD standard describes different concepts that can be implemented
by a member. The access to the standard\'s descriptions is partly free,
partly limited to ACORD members. It can be found here: ACORD Standard
Descriptions.
### XML structures
To ensure the correct form of the transferred data, ACORD provides XML
schemas and DTDs for its members. Companies implementing the standard
can validate their data against those definitions. The ACORD XML
standard is strongly based upon the United Nations
EDIFACT standard and expands the standard XML
data types with the financial data types used by the **I**nteractive
**F**inancial
**E**xchange (IFX).
ACORD\'s data types consist partly of those definitions but also expand
them with own data types. The data types are used as building blocks for
larger entities within the specification:
**Exhibit 1: XML entities used within the ACORD XML standard**
Entity Description
----------- ------------------------------------------------------------------
Element a base element, based on one or more of the described data types
Aggregate a collection of corresponding elements, entities or aggregates
Entity aggregate with the same structure
Message an aggregate that is used as one entity for communication
Service a collection of corresponding messages
Document a collection of messages that are sent together at the same time
A detailed description of the technical XML related aspects of the ACORD
standard can be obtained for Property &
Casualty and for
Life, Annuity & Health.
### XML messages
The before mentioned data types and structures are used to define
messages that can be interchanged between companies implementing the
ACORD standard. Different message types are defined within the data
model for each insurance segment. The following example shows the
messages used within the Reinsurance & Large Commercial segment:
**Exhibit 2: ACORD XML message types for RLC business**
Message Description
----------------- -----------------------------------------------------------------------------------------------
Placing message for placing obligatory or facultative business
Bordereau message between primary insurance and reinsurance company with information about signed risks
ClaimMovement message for a claim notification
TechAccount message to exchange accounting data for a treaty
Settlement message to exchange settlements
Acknowledgement message to confirm other messages or to request information
### ACORD message service
ACORD messages can be exchanged between implementing companies as plain
XML files. Additionally the ACORD standard defines a specialized message
exchange service. It is based on the **W**eb **S**ervice
**D**escription
**L**anguage (WSDL)
to implement the concepts of web services. The messages are send using
the **S**imple **O**bject **A**ccess
**P**rotocol (SOAP) standard. Following this
protocol a message consists of an envelope with the XML root element, a
header and a body which both are direct child elements of the envelope.
The SOAP envelope only contains structural information, not the message
itself. The actual SOAP messages are send as attachments with the
message and are referenced within the message body.
Therefore it\'s possible to enrich the ACORD messages with additional
information in PDF or DOC format.
**Exhibit 3: ACORD message service structure**

### Examples
To provide an impression of the complexity of ACORD\'s XML standard
definitions, following a small excerpt (only some lines of more than
5.000 per XML schema file / DTD) of the Reinsurance & Large Commercial
segment\'s XML schema and DTD files are presented:
**Exhibit 4: Excerpt from the RLC XML schema**
<nowiki>
<?xml version="1.0" encoding="UTF-8"?>
<!--
This is the ACORD Reinsurance and Large Commercial Business Message specification's
**** version 2007-1 Schema ****
Generated: May 10, 2007
COPYRIGHT NOTICE:
(c) 2001-2007 ACORD. All Rights Reserved.
IMPORTANT NOTE: Please be advised that this document and your use of it is governed, and
you are bound, by the Terms and Conditions of Use accessible at [http://legal.acord.org/terms.pdf].
-->
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://www.ACORD.org/standards/Jv-Ins-Reinsurance/2007-1"
xmlns:ac="http://www.ACORD.org/Standards/AcordMsgSvc/1" targetNamespace="http://www.ACORD.org/standards/Jv-Ins-Reinsurance/2007-1"
elementFormDefault="qualified" attributeFormDefault="unqualified" version="2007-1">
<xs:import namespace="http://www.ACORD.org/Standards/AcordMsgSvc/1" schemaLocation="Acord-Repository_v-1-3-0-RLC-Slice.xsd"/>
<!--******************-->
<!--2007-1 MRs applied-->
<!--******************-->
<!--MR1: Add CedentBuildReference, BrokerBuildReference, ReinsurerBuildReference, InsurerBuildReference,
ServiceProviderBuildReference and PlacingExchangeBuildReference elements to Contract -->
<!--MR10: Change DeductibleNumberOfLines, CoverageNumberOfLines, ReinsurerShareNumberOfLines, InsurerShareNumberOfLines,
ReinsurerWrittenNumberOfLines, InsurerWrittenNumberOfLines to become decimal numbers instead of integers-->
<!--MR11: Add ExpenseIndicator element to IndividualClaimAmtItem-->
<!--MR20: Add ProcessingInstructions/SettlementChannel to ContractMarket-->
<!---->
<!--******************************************************-->
<!--Start of Jv-Ins-Reinsurance base data types -->
<!--******************************************************-->
<!--Character is equated to the xs:string Schema base type-->
<!--URL is equated to the xs:anyURI Schema base type-->
<!--Attributes are validated against the xs:NMTOKEN Schema base type-->
<xs:simpleType name="FlexibleDate_Type">
<xs:annotation>
<xs:documentation>JAG type</xs:documentation>
</xs:annotation>
<xs:union memberTypes="xs:date xs:gYearMonth xs:gYear"/>
</xs:simpleType>
<xs:simpleType name="FlexibleDate1_Type">
<xs:annotation>
<xs:documentation>JAG type restriction 1 : Year only not admitted - Default in RLC</xs:documentation>
</xs:annotation>
<xs:union memberTypes="xs:date xs:gYearMonth"/>
</xs:simpleType>
<xs:simpleType name="FlexibleDateTime_Type">
<xs:annotation>
<xs:documentation>JAG type</xs:documentation>
</xs:annotation>
<xs:union memberTypes="xs:date xs:dateTime xs:gYearMonth xs:gYear"/>
</xs:simpleType>
<xs:simpleType name="FlexibleDateTime1_Type">
<xs:annotation>
<xs:documentation>JAG type restriction 1 : Year only not admitted</xs:documentation>
</xs:annotation>
<xs:union memberTypes="xs:date xs:dateTime xs:gYearMonth"/>
</xs:simpleType>
<xs:simpleType name="FlexibleDateTime2_Type">
<xs:annotation>
<xs:documentation>JAG type restriction 2 : Year only and YearMonth only not admitted</xs:documentation>
</xs:annotation>
<xs:union memberTypes="xs:date xs:dateTime"/>
</xs:simpleType>
<xs:complexType name="StartDateType">
<xs:simpleContent>
<xs:extension base="FlexibleDate1_Type">
<xs:attribute name="DateIndicator" type="xs:NMTOKEN"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="EndDateType">
<xs:simpleContent>
<xs:extension base="FlexibleDate1_Type">
<xs:attribute name="DateIndicator" type="xs:NMTOKEN"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="StartDateTimeType">
<xs:simpleContent>
<xs:extension base="FlexibleDateTime2_Type">
<xs:attribute name="DateIndicator" type="xs:NMTOKEN"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
<xs:complexType name="EndDateTimeType">
<xs:simpleContent>
<xs:extension base="FlexibleDateTime2_Type">
<xs:attribute name="DateIndicator" type="xs:NMTOKEN"/>
</xs:extension>
</xs:simpleContent>
</xs:complexType>
.
.
.
<xs:element name="WrittenDateTime" type="FlexibleDateTime2_Type"/>
<xs:element name="XplClauseIndicator" type="XplClauseIndicatorType"/>
<!--**************************************************************-->
<!--End of Jv-Ins-Reinsurance elements-->
<!--**************************************************************-->
<!--The Message aggregates included in this schema are generic and contain the child elements allowed in each message.
Where a child element is itself an aggregate, this does NOT mean that ALL elements of that child aggregate are
available for use in a particular message.
The ACORD RLC Data dictionary and Implementation guides give details of the restrictions placed on the use of all
elements and further information can also be found in the individual templates for each message. These templates are
XML files listing all tags available for each message and can be viewed with any XML editor or viewer.
The respective message aggregates are as shown in the section "Jv-Ins-Reinsurance root and transaction elements"
table below. The templates themselves can be downloaded from the ACORD web site www.ACORD.org along with the standard
documentation.-->
<!--
*****************************************************************
* Jv-Ins-Reinsurance root and Message elements *
*****************************************************************
-->
<xs:element name="Jv-Ins-Reinsurance" type="Jv-Ins-ReinsuranceType"/>
<xs:element name="Acknowledgement" type="AcknowledgementType"/>
<xs:element name="Bordereau" type="BordereauType"/>
<xs:element name="ClaimMovement" type="ClaimMovementType"/>
<xs:element name="Codes" type="CodesType"/>
<xs:element name="Placing" type="PlacingType"/>
<xs:element name="Settlement" type="SettlementType"/>
<xs:element name="TechAccount" type="TechAccountType"/>
<!--End of Jv-Ins-Reinsurance root and transaction elements-->
</xs:schema>
</nowiki>
**Exhibit 5: Excerpt from the RLC DTD**
<nowiki>
<?xml version="1.0" encoding="UTF-8"?>
<!-- edited with XMLSpy v2006 rel. 3 sp2 (http://www.altova.com) by Serge Cayron (ACORD Corp.) -->
<!--
This is the ACORD Reinsurance and Large Commercial Business Message specification's
**** version 2007-1 DTD ****
Generated: May 10, 2007
COPYRIGHT NOTICE:
(c) 2001-2007 ACORD. All Rights Reserved.
IMPORTANT NOTE: Please be advised that this document and your use of it is governed, and you are bound, by the Terms
and Conditions of Use accessible at [http://legal.acord.org/terms.pdf].
*******************************************************************************************
* Formal Public Identifier
*
* "-//ACORD//DTD JV Ins-Reinsurance Version 2007-1//EN"
********************************************************************************************
IMPORTANT NOTE: From the 2005-2 release, the RLC XML Schema is able to validate messages that include custom extensions,
using a standard method. The DTD file does NOT support the same functionality. The user of a DTD should be aware that
it will not be possible to use the DTD to validate messages that use the standard extension method. -->
<!--******************-->
<!--2007-1 MRs applied-->
<!--******************-->
<!--MR1: Add CedentBuildReference, BrokerBuildReference, ReinsurerBuildReference, InsurerBuildReference,
ServiceProviderBuildReference and PlacingExchangeBuildReference elements to Contract -->
<!--MR10: Change DeductibleNumberOfLines, CoverageNumberOfLines, ReinsurerShareNumberOfLines, InsurerShareNumberOfLines,
ReinsurerWrittenNumberOfLines, InsurerWrittenNumberOfLines to become decimal numbers instead of integers-->
<!--MR11: Add ExpenseIndicator element to IndividualClaimAmtItem-->
<!--MR20: Add ProcessingInstructions/SettlementChannel to ContractMarket-->
<!--
************************************************
* Common Entities in alphabetical order *
************************************************
-->
<!ENTITY % PARTY "Party, Contact?, Address?">
<!ENTITY % PARTYXT "((Party, FullNameAndAddress?) | FullNameAndAddress), Contact?, Address?, OperationsDescription?">
<!ENTITY % PERILS "Peril+">
<!ENTITY % PERIOD "StartDate?, EndDate?, TimeDuration?">
<!ENTITY % REPORTING "Description?, ReportDue?, ProvisionFrequency?, AnnualAsOfDate?">
<!--
*****************************
* Data typing elements *
*****************************
-->
<!-- Currency amount -->
<!ELEMENT Amt (#PCDATA)>
<!ATTLIST Amt
Ccy NMTOKEN #REQUIRED
Share (cedent_share | contract_ceded | hundred_percent | receiver_share | reinsurer_share) #IMPLIED
CcyIndic (reference_currency | target_currency | original_currency) #IMPLIED
>
<!-- Integer -->
<!ELEMENT Count (#PCDATA)>
<!ELEMENT StartDate (#PCDATA)>
<!ATTLIST StartDate
DateIndicator NMTOKEN #IMPLIED
>
<!ELEMENT EndDate (#PCDATA)>
<!ATTLIST EndDate
DateIndicator NMTOKEN #IMPLIED
>
<!-- Date and time -->
<!ELEMENT StartDateTime (#PCDATA)>
<!ATTLIST StartDateTime
DateIndicator NMTOKEN #IMPLIED
>
<!ELEMENT EndDateTime (#PCDATA)>
<!ATTLIST EndDateTime
DateIndicator NMTOKEN #IMPLIED
>
<!-- Decimal -->
<!ELEMENT Dec (#PCDATA)>
<!-- Period identification - Integer-->
<!ELEMENT PeriodNbr (#PCDATA)>
<!ATTLIST PeriodNbr
PeriodIndicator NMTOKEN #REQUIRED
>
<!-- Rate -->
<!ELEMENT Rate (#PCDATA)>
<!ATTLIST Rate
RateUnit NMTOKEN #REQUIRED
>
<!-- Time duration -->
<!ATTLIST TimeDuration
PeriodType NMTOKEN #IMPLIED
PeriodIndicator NMTOKEN #IMPLIED
>
.
.
.
<!ATTLIST TimeDuration
PeriodType NMTOKEN #IMPLIED
PeriodIndicator NMTOKEN #IMPLIED
>
<!ELEMENT TimeRelation (#PCDATA)>
<!ELEMENT TimeZone (#PCDATA)>
<!ELEMENT TotalLossIndicator (#PCDATA)>
<!ELEMENT Townclass (#PCDATA)>
<!ATTLIST Townclass
Agency NMTOKEN #IMPLIED
>
<!ELEMENT TransactionReasonDescription (#PCDATA)>
<!ELEMENT TransactionResponseReason (#PCDATA)>
<!ELEMENT TreatyFac (#PCDATA)>
<!ELEMENT URL (#PCDATA)>
<!ELEMENT UUId (#PCDATA)>
<!ELEMENT UnderwritingManager (%PARTY;)>
<!ELEMENT UnderwritingManagerRiskReference (#PCDATA)>
<!ELEMENT UnderwritingYear (#PCDATA)>
<!ELEMENT UnearnedPremiumCalculationPeriod (%PERIOD;)>
<!ELEMENT UnearnedPremiumReserveProfitCommissionPercentage (Rate)>
<!ELEMENT USARiskClassification ((RiskClass, RiskClassDescription?) | RiskClassDescription)>
<!ELEMENT UserId (#PCDATA)>
<!ELEMENT ValueAddedTaxRating (#PCDATA)>
<!ELEMENT ValueDate (#PCDATA)>
<!ELEMENT VesselName (#PCDATA)>
<!ELEMENT VesselOrConveyanceDescription (#PCDATA)>
<!ELEMENT Voyage (DepartureDateTime?, LoadingOrEmbarkationDate?, DepartureLocation?, DestinationLocation?)>
<!ELEMENT WebApplication (URL?, UserId?)>
<!ELEMENT WebSiteURL (#PCDATA)>
<!ELEMENT WholesaleBrokerageAmount (Amt+)>
<!ELEMENT WholesaleBrokeragePercentage (Rate)>
<!ELEMENT WithdrawalDate (#PCDATA)>
<!ELEMENT WithdrawalPercentage (Rate)>
<!ELEMENT WorkersCompensationState (Subentity)>
<!ELEMENT WorkersCompensationStateDescription (#PCDATA)>
<!ELEMENT WrittenDateTime (#PCDATA)>
<!ELEMENT XplClauseIndicator (#PCDATA)>
</nowiki>
### Certification
To ensure data quality and member\'s compliance with the proposed
standards ACORD offers a special certification program. ACORD members
can send their XML messages to ACORD. There the messages are validated
in 2 steps:
1. Automatic Validation against the standard\'s XML schema and DTD
files
2. Validation of the sent data by a human for plausibility which goes
beyond the automatical, technical consistency check
## Members
World\'s largest insurance companies and insurance related businesses
are ACORD members: \"Over 70% of the top 10 and 60% of the top 25 Life &
Annuity carriers; Over 75% of the top 50 Property & Casualty carriers;
and 70% of the top 10 Reinsurers, as well as the Top 5 reinsurance
brokers representing 80% of the top 20\'s gross
revenue.\"2 The following list
shows just some of them:
- Allianz Insurance
- Allstate
- Hannover Re
- AXA
- Benfield
- ING Group
- MetLife
- Munich Re
- Zurich Insurance Group
For a complete list have a look at the ACORD
Memberlist.
## References
Sources:
- \[1\] ACORD Website
- \[2\] Market Reform Group
- \[3\] IFX Forum
- \[4\] University of
Leipzig
- \[5\] SAP
INFO
- \[6\] ACORD White
Paper
## Summary
+----------------------------------------------------------------------+
| In the previous chapter you have learned about the insurance |
| industry\'s standard for electronical data exchange. It\'s |
| maintained by a nonprofit organization called ACORD and defines data |
| models for the main insurance segments. The main concepts of the |
| ACORD XML standard are: |
| |
| - a set of XML schemas and DTDs to ensure the content, structure |
| and \"quality\" of the sent XML streams |
| - a set of XML messages for different business cases |
| - the ACORD message service for exchanging enriched XML data based |
| on WSDL and SOAP |
+----------------------------------------------------------------------+
| |
+----------------------------------------------------------------------+
|
# XML - Managing Data Exchange/Glossary
```{=html}
<h2 style="background-color:#CEE0F2; border-bottom:0px; border: 1px solid #A3B1BF; text-align:center; padding-top:4px;">
```
Glossary
```{=html}
</h2>
```
```{=html}
<div align="center">
```
```{=html}
</div>
```
## 0--9
`<span id=1RR style="font-weight: bold">`{=html}.NET`</span>`{=html}
: Microsoft **.NET** Framework
: Microsoft .NET Framework is a software component that is part of
several Microsoft Windows operating systems. It has a large library
of pre-coded solutions to common programming problems and manages
the execution of programs written specifically for the framework.
## A
`<span id=3RR style="font-weight: bold">`{=html}ACORD`</span>`{=html}
: **A**ssociation for **C**ooperative **O**perations **R**esearch and
**D**evelopment
: ACORD is the insurance industry\'s nonprofit standards developer, a
resource for information about object technology, EDI, XML and
electronic commerce in the United States and abroad.
: Among other things, ACORD governs an XML based data model to provide
an easy way to exchange data between insurance companies, insurance
brokers, other insurance related firms and governments.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}AJAX`</span>`{=html}
: **A**synchronous **J**ava**S**cript **a**nd **X**ML
: AJAX is a group of inter-related web development techniques used for
creating interactive web applications.
: A primary characteristic is the increased responsiveness and
interactivity of web pages achieved by exchanging small amounts of
data with the server \"behind the scenes\" so that entire web pages
do not have to be reloaded each time there is a need to get data
from the server. This is intended to increase the web page\'s
interactivity, speed, functionality and usability.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}ANSI`</span>`{=html}
: **A**merican **N**ational **S**tandards **I**nstitute
: ANSI is a private non-profit organization that oversees the
development of voluntary consensus standards for products, services,
processes, systems, and personnel in the United States. The
organization also coordinates U.S. standards with international
standards so that American products can be used worldwide. For
example, standards make sure that people who own cameras can find
the film they need for them anywhere around the globe.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}API`</span>`{=html}
: **A**pplication **P**rogramming **I**nterface
: API is a source code interface that an operating system, library or
service provides to support requests made by computer programs.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}ASCII`</span>`{=html}
: **A**merican **S**tandard **C**ode **I**nformation**I**nterchange
: ASCII is a character encoding based on the English alphabet. ASCII
codes represent text in computers, communications equipment, and
other devices that work with text. Most modern character encodings
--- which support many more characters than did the original ---
have a historical basis in ASCII.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}ASP`</span>`{=html}
: **A**nalog **S**ignal **P**rocessing
: ASP means processing electronic signals that represent continuous
variables by use of analog circuitry.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}ASX`</span>`{=html}
: **A**dvanced **S**tream Redirector
: ASX format is a type of XML metafile designed to store a list of
Windows Media files to play during a multimedia presentation.
: It is used frequently on streaming video servers where multiple ASF
files are to be played in succession. Both RTSP and MMS streaming
protocols are supported, as well as HTTP.
## B
`<span id=3RR style="font-weight: bold">`{=html}BHTML`</span>`{=html}
: **B**roadcast **H**yper**T**ext **M**arkup **L**anguage
: BHTML extends HTML by adding attributes for standardizing multimedia
object descriptions within HTML OBJECT elements, using the SMIL
SWITCH option and introducing an EVENT element to manage the actions
to be taken when certain conditions are encountered.
## C
`<span id=3RR style="font-weight: bold">`{=html}CGI`</span>`{=html}
: **C**ommon **G**ateway **I**nterface
: CGI is a standard protocol for interfacing external application
software with an information server, commonly a web server. The task
of such an information server is to respond to requests (in the case
of web servers, requests from client web browsers) by returning
output. Each time a request is received, the server analyzes what
the request asks for, and returns the appropriate output.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}CML`</span>`{=html}
: **C**hemical **M**arkup **L**anguage
: CML is a new approach to managing molecular information using tools
such as XML and Java. It was the first domain specific
implementation based strictly on XML, the most robust and widely
used system for precise information management in many areas.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}CORBA`</span>`{=html}
: **C**ommon **O**bject **R**equest **B**roker **A**rchitecture
: CORBA is a standard defined by the Object Management Group (OMG)
that enables software components written in multiple computer
languages and running on multiple computers to work together.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}../CSS/`</span>`{=html}
: **C**ascading **S**tyle **S**heets
: CSS is a language that describes the presentation form of a
structured document. An XML or an HTML based document does not have
a set style, but it consists of structured text without style
information. How the document will look when printed on paper and
viewed in a browser or maybe a cellphone is determined by a style
sheet.
## D
`<span id=3RR style="font-weight: bold">`{=html}DAD`</span>`{=html}
: **D**ata **A**ccess **D**efinition
: A data access definition (DAD) file is used for both XML Column and
XML Collection approaches to define the \"mapping\" between the
database tables and the structure of the XML document.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DB2`</span>`{=html}
: DB2 is one of IBM\'s families of relational database management
system (or, as IBM now calls it, data server) software products
within IBM\'s broader Information Management Software line.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DCMI`</span>`{=html}
: **D**ublin **C**ore **M**etadata **I**nitiative
: The Dublin Core Metadata Initiative is an open organization engaged
in the development of interoperable online metadata standards that
support a broad range of purposes and business models. DCMI\'s
activities include work on architecture and modeling, discussions
and collaborative work in DCMI Communities and DCMI Task Groups,
annual conferences and workshops, standards liaison, and educational
efforts to promote widespread acceptance of metadata standards and
practices.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DCOM`</span>`{=html}
: **D**istributed **C**omponent **O**bject **M**odel
: DCOM is a proprietary Microsoft technology for communication among
software components distributed across networked computers. DCOM,
which originally was called \"Network OLE\", extends Microsoft\'s
COM, and provides the communication substrate under Microsoft\'s
COM+ application server infrastructure. It has been deprecated in
favor of Microsoft .NET.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DHTML`</span>`{=html}
: **D**ynamic **H**yper**T**ext **M**arkup **L**anguage
: DHTML is a collection of technologies used together to create
interactive and animated web sites by using a combination of a
static markup language (such as HTML), a client-side scripting
language (such as JavaScript), a presentation definition language
(Cascading Style Sheets, CSS), and the Document Object Model.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DOM`</span>`{=html}
: **D**ocument **O**bject **M**odel
: DOM is a platform- and language-independent standard object model
for representing HTML or XML and related formats.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DSSSL`</span>`{=html}
: **D**ocument **S**tyle **S**emantics and **S**pecification
**L**anguage
: DSSSL is a stylesheet language for both print and online rendering.
It is mainly intended to work with SGML.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DTD`</span>`{=html}
: **D**ocument **T**ype **D**efinition
: A DTD is the XML Document Type Definition contains or points to
markup declarations that provide a grammar for a class of documents.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DTMF`</span>`{=html}
: **D**ual **T**one **M**ulti **F**requency
: Dual-tone multi-frequency signaling is used for telephone signaling
over the line in the voice-frequency band to the call switching
center. The version of DTMF used for telephone tone dialing is known
by the trademarked term Touch-Tone (canceled March 13, 1984), and is
standardized by ITU-T Recommendation Q.23. Other multi-frequency
systems are used for signaling internal to the telephone network.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}DVI`</span>`{=html}
: **D**igital **V**isual **I**nterface
## E
`<span id=3RR style="font-weight: bold">`{=html}ECMAScript`</span>`{=html}
: **E**uropean **C**omputer **M**anufacturers **A**ssociation
**Script**
: ECMAScript is a scripting language, standardized by Ecma
International in the ECMA-262 specification. The language is widely
used on the web, and is often referred to as JavaScript or JScript,
after the two primary dialects of the specification.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}EDI`</span>`{=html}
: **E**lectronic **D**ata **I**nterchange
: EDI is traditional data exchange standard for large organizations.
It supports the electronic exchange of standard business documents
and is currently the major data format for electronic commerce.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}ETSI`</span>`{=html}
: **E**uropean **T**elecommunications **S**tandards **I**nstitution
: ETSI is an independent, non-for-profit, standardization organization
of the telecommunications industry (equipment makers and network
operators) in Europe, with worldwide projection. It has been
successful in standardizing the GSM cell phone system and the TETRA
professional mobile radio system.
## F
`<span id=3RR style="font-weight: bold">`{=html}FO`</span>`{=html}
: **F**ormatting **O**bjects
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}FTP`</span>`{=html}
: **F**ile **T**ransfer **P**rotocol
: FTP is a file transfer protocol for exchanging files over any TCP/IP
based network to manipulate files on another computer on that
network regardless of which operating systems are involved (if the
computers permit FTP access). There are many existing FTP client and
server programs. FTP servers can be set up anywhere between game
servers, voice servers, internet hosts, and other physical servers.
## G
`<span id=3RR style="font-weight: bold">`{=html}GIF`</span>`{=html}
: **G**raphics **I**nterchange **F**ormat
: GIF is an 8-bit-per-pixel bitmap image format that was introduced by
CompuServe in 1987 and has since come into widespread usage on the
World Wide Web due to its wide support and portability.
: The format uses a palette of up to 256 distinct colors from the
24-bit RGB color space.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}GML`</span>`{=html}
: **G**eography **M**arkup **L**anguage
: GML is the XML grammar defined by the Open Geospatial Consortium
(OGC) to express geographical features.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}GUID`</span>`{=html}
: **G**lobal **U**nique **Id**entifier
: Globally Unique Identifiers are numbers assigned to a data object
for use in a remote database. This identifier is assigned by the
server.
## H
`<span id=3RR style="font-weight: bold">`{=html}HTML`</span>`{=html}
: **H**yper**t**ext **M**arkup **L**anguage
: HTML is the predominant markup language for web pages. It provides a
means to describe the structure of text-based information in a
document --- by denoting certain text as links, headings,
paragraphs, lists, and so on --- and to supplement that text with
interactive forms, embedded images, and other objects. HTML is
written in the form of tags, surrounded by angle brackets. HTML can
also describe, to some degree, the appearance and semantics of a
document, and can include embedded scripting language code (such as
JavaScript) which can affect the behavior of Web browsers and other
HTML processors.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}HTTP`</span>`{=html}
: **H**ypertext **T**ransfer **P**rotocol
: HTML is a communications protocol for the transfer of information on
the intranet and the World Wide Web. Its original purpose was to
provide a way to publish and retrieve hypertext pages over the
Internet.
## I
`<span id=3RR style="font-weight: bold">`{=html}IDE`</span>`{=html}
: **I**ntegrated **D**evelopment **E**nvironment
: IDE is a software application that provides comprehensive facilities
to computer programmers for software development. An IDE normally
consists of a source code editor, a compiler and/or interpreter,
build automation tools, and (usually) a debugger. IDEs are designed
to maximise programmer productivity by providing tightly-knit
components with similar user interfaces, thus minimising the amount
of mode switching the programmer must do comparing to loose,
discrete collections of disparate development programs.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}IDL`</span>`{=html}
: **I**nterface **D**escription **L**anguage
: IDL is a specification language used to describe a software
component\'s interface. IDLs describe an interface in a
language-neutral way, enabling communication between software
components that do not share a language -- for example, between
components written in C++ and components written in Java.
: IDLs are commonly used in remote procedure call software. In these
cases the machines at either end of the \"\"link\"\" may be using
different operating systems and computer languages. IDLs offer a
bridge between the two different systems.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}IDREF`</span>`{=html}
: **Id**entifier **REF**erence
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}IFX`</span>`{=html}
: **I**nteractive **F**inancial **E**xchange
: IFX is an XML specification for financial transactions such as bill
presentment and payment, business to business and consumer to
business banking (e.g.: balances, financial transaction
information), payments and automated teller machine (ATM)
communications.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}IMEI`</span>`{=html}
: **I**nternational **M**obile **E**quipment **I**dentifier
: ../IMEI/ is a number unique to every GSM and
UMTS mobile phone. It is usually found printed on the phone
underneath the battery.
: The IMEI number is used by the GSM network to identify valid devices
and therefore can be used to stop a stolen phone from accessing the
network. For example, if a mobile phone is stolen, the owner can
call his or her network provider and instruct them to \"\"ban\"\"
the phone using its IMEI number. This renders the phone useless,
regardless of whether the phone\'s SIM is changed.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}ISO`</span>`{=html}
: **I**nternational **O**rganization for **S**tandardization
: ISO is an international-standard-setting body composed of
representatives from various national standards organizations.
Founded on 23 February 1947, the organization promulgates world-wide
proprietary industrial and commercial standards. It is headquartered
in Geneva, Switzerland.
## J
`<span id=3RR style="font-weight: bold">`{=html}Java EE`</span>`{=html}
: **Java** Platform **E**nterprise **E**dition
: Java EE is a widely used platform for server programming in the Java
programming language. The Java EE Platform differs from the Standard
Edition (SE) of Java in that it adds libraries which provide
functionality to deploy fault-tolerant, distributed, multi-tier Java
software, based largely on modular components running on an
application server.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JAR`</span>`{=html}
: **J**ava **AR**chive
: In computing, a JAR file is used for aggregating many files into
one. It is generally used to distribute Java classes and associated
metadata.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JAVA`</span>`{=html}
: Java is a programming language originally developed by Sun
Microsystems and released in 1995 as a core component of Sun
Microsystems\' Java platform. The language derives much of its
syntax from C and C++ but has a simpler object model and fewer
low-level facilities. Java applications are typically compiled to
bytecode that can run on any Java virtual machine (JVM) regardless
of computer architecture.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JAXP`</span>`{=html}
: **J**ava **A**PI for **X**ML **P**rocessing
: Java API for XML Processing is one of the Java XML programming APIs.
It provides the capability of validating and parsing XML documents.
The three basic parsing interfaces are the Document Object Model
parsing interface (DOM interface), the Simple API for XML parsing
interface (SAX interface) and the Streaming API for XML (StAX
interface).
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JAXR`</span>`{=html}
: **J**ava **A**PI for **X**ML **R**egistries (pronounced \"jaks-p\")
: JAXR creates a layer of abstraction, so that it can be used with
UDDI and other types of XML Registries, such as the ebXML Registry
and Repository standard.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JCP`</span>`{=html}
: **J**ava **C**ommunity **P**rocess
: JCP is a formalized process which allows interested parties to be
involved in the definition of future versions and features of the
Java platform.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JDBC`</span>`{=html}
: **J**ava **D**ata**B**ase **C**onnectivity
: JDBC is an API for the Java programming language that defines how a
client may access a database. It provides methods for querying and
updating data in a database. JDBC is oriented towards relational
databases.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JDNC`</span>`{=html}
: **JD**esktop **N**etwork **C**omponents
: JDNC is a SwingLab subproject concerning contained components that
allow to build easily Swing-based rich-client Java applications. The
project is no more actively maintained. It has been replaced by
Swing Application Framework (JSR 296)
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JPEG`</span>`{=html}
: **J**oint **P**hotographic **E**xperts **G**roup
: JPEG is a commonly used method of compression for photographic
images. The degree of compression can be adjusted, allowing a
selectable tradeoff between storage size and image quality. JPEG
typically achieves 10 to 1 compression with little perceivable loss
in image quality.
: JPEG is the most common image format used by digital cameras and
other photographic image capture devices, and is the most common
format for storing and transmitting photographic images on the World
Wide Web.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JSP`</span>`{=html}
: **J**ava**S**erver **P**ages
: JSP is a Java technology that allows software developers to
dynamically generate HTML, XML or other types of documents in
response to a Web client request. The technology allows Java code
and certain pre-defined actions to be embedded into static content.
: The JSP syntax adds additional XML-like tags, called JSP actions, to
be used to invoke built-in functionality. Additionally, the
technology allows for the creation of JSP tag libraries that act as
extensions to the standard HTML or XML tags. Tag libraries provide a
platform independent way of extending the capabilities of a Web
server.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JSPX`</span>`{=html}
: JSP-page in XML-notation
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}JSTL`</span>`{=html}
: **J**avaServer Pages **S**tandard **T**ag **L**ibrary
: A collection of four custom-tag libraries which extend the JSP
specification. As a component it is allocated in the Java EE Web
application development platform.
## K
`<span id=3RR style="font-weight: bold">`{=html}KML`</span>`{=html}
: **K**eyhole **M**arkup **L**anguage
: KML is an XML-based Markup language for managing the display of
three-dimensional geospatial data in the programs Google Earth,
Google Maps, Google Mobile, ArcGIS Explorer and World Wind.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}KMZ files`</span>`{=html}
: Data compression / zipped KML file
## L
`<span id=3RR style="font-weight: bold">`{=html}LUID`</span>`{=html}
: **L**ocal **U**nique **Id**entifier
: Locally Unique Identifiers (LUID) are numbers assigned by the client
to a data object in a local database (like a field or a row). They
are non-reusable numbers assigned to these objects by the SyncML
client.
## M
`<span id=3RR style="font-weight: bold">`{=html}MD5`</span>`{=html}
: **M**essage-**D**igest algorithm **5**
: In cryptography, MD5 is a widely used, partially insecure
cryptographic hash function with a 128-bit hash value. As an
Internet standard, MD5 has been employed in a wide variety of
security applications, and is also commonly used to check the
integrity of files. An MD5 hash is typically expressed as a 32 digit
hexadecimal number.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}MIF`</span>`{=html}
: **M**aker **I**nterchange **F**ormat
: MIF is a proprietary markup language associated with Adobe Systems\'
FrameMaker product for technical document preparation.
: While MIF is essentially specific to a single program (FrameMaker),
it was widely used in the complex document workflows of small
enterprises, especially in the industrial and manufacturing sector.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}MIME type`</span>`{=html}
: An Internet media type, originally called a MIME type after MIME and
sometimes a Content-type after the name of a header in several
protocols whose value is such a type, is a two-part identifier for
file formats on the Internet. The identifiers were originally
defined in RFC 2046 for use in e-mail sent through SMTP, but their
use has expanded to other protocols such as HTTP and SIP.
: A media type is composed of at least two parts: a type, a subtype,
and one or more optional parameters. For example, subtypes of text
type have an optional charset parameter that can be included to
indicate the character encoding, and subtypes of multipart type
often define a boundary between parts.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}ML`</span>`{=html}
: **M**arkup **L**anguage
: A markup language is an artificial language using a set of
annotations to text that describe how text is to be structured, laid
out, or formatted.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}MMS`</span>`{=html}
: **M**ultimedia **M**essaging **S**ervice
: MMS is a standard for telephone messaging systems that allows
sending messages that include multimedia objects (images, audio,
video, rich text) and not just text as in Short Message Service
(SMS). It is mainly deployed in cellular networks along with other
messaging systems like SMS, Mobile Instant Messaging and Mobile
E-mail.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}MPEG`</span>`{=html}
: **M**oving **P**icture **E**xperts **G**roup
: Moving Picture Experts Group, commonly referred to as simply MPEG,
is a working group of ISO/IEC charged with the development of video
and audio encoding standards. MPEG has standardized a variety of
compression formats and ancillary standards.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html} MySQL`</span>`{=html}
: MySQL is an open source relational database that supports XML. You
can use the MySQL command line or a programming language of your
choice to convert your MySQL databases and or tables to a well
formed XML document.
## O
`<span id=3RR style="font-weight: bold">`{=html}ODBC`</span>`{=html}
: API **O**pen **D**ata**B**ase **C**onnectivity
: In computing, Open Database Connectivity provides a standard
software API method for using database management systems (DBMS).
The designers of ODBC aimed to make it independent of programming
languages, database systems, and operating systems.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}OpenGIS Consortium`</span>`{=html}
: **Open** **G**eo**s**patial **Consortium**
: The Open Geospatial Consortium, Inc. is a non-profit, international,
voluntary consensus standards organization that is leading the
development of standards for geospatial and location based services.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}OpenOffice`</span>`{=html}
: OpenOffice.org is exactly what its title suggests: an open source
office applications suite. It is based on the source of Sun
Microsystems\' StarOffice, which was donated to the open source
community in 2000. OpenOffice.org will read and save files in
several formats used by other office applications, but its default
format is OpenDocument, which is an XML format standardized by OASIS
(Organization for the Advancement of Structured Information
Standards).
## P
`<span id=3RR style="font-weight: bold">`{=html}PDA`</span>`{=html}
: **P**ersonal **D**igital **A**ssistants
: PDA a handheld computer, also known as small or palmtop computers.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}PDF`</span>`{=html}
: **P**ortable **D**ocument **F**ormat
: PDF is a fixed-layout format used for representing two-dimensional
documents in a manner independent of the application software,
hardware, and operating system. Each PDF file encapsulates a
complete description of a 2-D document (and, with Acrobat 3-D,
embedded 3-D documents) that includes the text, fonts, images, and
2-D vector graphics that compose the documents.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}PHP`</span>`{=html}
: **H**ypertext **P**re**p**rocessor
: PHP is a computer scripting language, originally designed for
producing dynamic web pages. It is for server-side scripting, but
can be used from a command line interface or in standalone graphical
applications.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}PML`</span>`{=html}
: Phone Markup Language
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}PNG`</span>`{=html}
: **P**ortable **N**etwork **G**raphics
: PNG is a bitmapped image format that employs lossless data
compression. PNG was created to improve upon and replace the GIF
format, as an image-file format not requiring a patent license.
## R
`<span id=3RR style="font-weight: bold">`{=html}RDF`</span>`{=html}
: **R**esource **D**escription **F**ramework
: RDF is an international-standard-setting body composed of
representatives from various national standards organizations.
Founded on 23 February 1947, the organization promulgates world-wide
proprietary industrial and commercial standards. It is headquarter
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}RDFS`</span>`{=html}
: **R**esource **D**escription **F**ramework **S**chema
: RDFS is an international-standard-setting body composed of
representatives from various national standards organizations.
Founded on 23 February 1947, the organization promulgates world-wide
proprietary industrial and commercial standards.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}RPC`</span>`{=html}
: **R**emote **P**rocedure **C**all
: RPC is a protocol that allows a computer program running on one host
to cause code to be executed on another host without the programmer
needing to explicitly code for this. An RPC is initiated by the
caller (client) sending a request message to a remote system (the
server) to execute a certain procedure using arguments supplied. A
result message is returned to the caller. There are many variations
and subtleties in various implementations, resulting in a variety of
different (incompatible) RPC protocols.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}RSS`</span>`{=html}
: **R**DF **S**ite **S**ummary
: RSS is a simple XML format used to syndicate headlines. It is now
popularly used by websites that publish new content regularly and
provide a list of headlines with links to their latest content.
Content such as news feeds, events listings, project updates,
blogger and most recently podcasting, video and image distribution
can all be distributed by RSS.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}RTF`</span>`{=html}
: **R**ich **T**ext **F**ormat
: RTF is a free document file format developed by Microsoft in 1987
for cross-platform document interchange. Most word processors are
able to read and write RTF documents.
## S
`<span id=3RR style="font-weight: bold">`{=html}SAMI`</span>`{=html}
: **S**ynchronized **A**ccessible **M**edia **I**nterchange
: Microsoft\'s proprietary alternative to SMIL.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SAX`</span>`{=html}
: **S**imple **A**PI for **X**ML
: The SAX classes provide an interface between the input streams from
which XML documents are read and the client software which receives
the data made available by the parser. The parser browses through
the whole document and fires events every time it recognizes an XML
construct.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SFTP`</span>`{=html}
: **S**ecure **F**ile **T**ransfer **P**rotocol
: SFTP is a program that uses SSH to transfer files. Unlike standard
FTP, it encrypts both commands and data, preventing passwords and
sensitive information from being transmitted in the clear over the
network.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SGML`</span>`{=html}
: **S**tandard **G**eneralized **M**arkup **L**anguage
: The Standard Generalized Markup Language is a metalanguage in which
one can define markup languages for documents.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SMIL`</span>`{=html}
: **S**ynchronized **M**ultimedia **I**ntegration **L**anguage
(pronounced \"smile\")
: SMIL is a specialized language to describe the presentation of media
objects. It enables simple authoring of interactive audiovisual
presentations. SMIL is a XML based language and typically used for
\"rich media\"/multimedia presentations which integrate streaming
audio and video with images, text or any other media type.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SOAP`</span>`{=html}
: **S**imple **O**bject **A**ccess **P**rotocol
: SOAP is a method for sending information to and from Web Services in
an extensible format. SOAP can be used to send information or remote
procedure calls encoded as XML. Essentially, SOAP serves as a
universally accepted method of communication with web services.
Businesses adhere to the SOAP conventions in order to simplify the
process of interacting with Web Services.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SQL`</span>`{=html}
: **S**tandard **Q**uery **L**anguage
: SQL is a database computer language designed for the retrieval and
management of data in relational database management systems,
database schema creation and modification, and database object
access and control management.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SRGS`</span>`{=html}
: **S**peech **R**ecognition **G**rammar **S**pecification
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SSML`</span>`{=html}
: **S**ynthesized **S**peech **M**arkup **L**anguage
: There is an existing set of XML tags for Voice XML, called SSML.
This set enables control of enough aspects of speech generation that
a personable voice can be generated and manipulated by a user. A
Text-to-Speech system uses the tags to take a text file and generate
audible text in a voice.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SVG`</span>`{=html}
: **S**calable **V**ector **G**raphics
: SVG is a XML based, open-standard vector graphics file format and
Web development language created by the W3C, and has been designed
to be compatible with other W3C standards such as DOM, CSS, XML,
XSLT, XSL, SMIL, HTML, and XHTML. It enables the creation of
dynamically generated, high-quality graphics from real-time data.
SVG allows you to design high-resolution graphics that can include
elements such as gradients, embedded fonts, transparency, animation,
and filter effects.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}Sync4i`</span>`{=html}
: SyncML for Java
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}SyncML`</span>`{=html}
: **S**ynthesized **S**peech **M**arkup **L**anguage
: There is an existing set of XML tags for Voice XML, called SSML.
This set enables control of enough aspects of speech generation that
a personable voice can be generated and manipulated by a user. A
Text-to-Speech system uses the tags to take a text file and generate
audible text in a voice.
## T
`<span id=3RR style="font-weight: bold">`{=html}TLS / SSL`</span>`{=html}
: **T**ransport **L**ayer **S**ecurity and **S**ecure **S**ocket
**L**ayer
: TLS/SSL is a very secure and reliable protocol that provides
end-to-end security sessions between two parties. XML adds an extra
layer of security to TLS/SSL by encrypting part or all of the data
being exchanged and by allowing for secure sessions between more
than two parties.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}TTS`</span>`{=html}
: **T**ext-**T**o-**S**peech
## U
`<span id=3RR style="font-weight: bold">`{=html}UDDI`</span>`{=html}
: **U**niversal **D**escription, **D**iscovery and **I**ntegration
: UDDI defines registries in which services can be published and
found. The UDDI specification was creaed by Microsoft, Ariba, and
IBM and defines a data structure and Application Programming
Interface (API).
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}UN/EDIFACT`</span>`{=html}
: **U**nited **N**ations/**E**lectronic **D**ata **I**nterchange
**F**or **A**dministration, **C**ommerce, and **T**ransport
: UN/EDIFACT is the international EDI standard developed under the
United Nations.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}URI`</span>`{=html}
: **U**niform **R**esource **I**dentifier
: URI is a compact string of characters used to identify or name a
resource. The main purpose of this identification is to enable
interaction with representations of the resource over a network,
typically the World Wide Web, using specific protocols. URIs are
defined in schemes defining a specific syntax and associated
protocols.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}URL`</span>`{=html}
: **U**niform **R**esource **L**ocator
: URL is a technical, web-related term used in two distinct meanings:
In popular usage and many technical documents, it is a synonym for
URI. In popular usage, it means a web page address. Strictly it is a
compact string of characters for a resource available via the
Internet.
## V
`<span id=3RR style="font-weight: bold">`{=html}VoiceXML`</span>`{=html}
: Speaking web data
: VoiceXML is created to generate audio dialogs that allows the use of
synthesized speech, digitized audio, recognition of spoken and
DTMF(Dual Tone Multi-Frequency Touch-tone or push-button dialing.)
In other words, VoiceXML allows the use of computer speech, recorded
audio, human speech, and telephones as input and output devices.
## W
`<span id=3RR style="font-weight: bold">`{=html}W3C`</span>`{=html}
: **W**orld **W**ide **W**eb **C**onsortium
: W3C is the main international standards organization for the World
Wide Web (abbreviated WWW or W3).
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}WAP`</span>`{=html}
: **W**ireless **A**pplication **P**rotocol
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}WBXML`</span>`{=html}
: **W**AP **B**inary **XML**
: WAP Binary XML (WBXML) is a form of XML whereby the XML tags are
abbreviated in order to shorten the markup for transmission to
mobile devices, which commonly have bandwidth and memory
limitations. The XML tags are encoded into a binary shorthand to
save space.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}WCDMA`</span>`{=html}
: **W**ide-band **C**ode-**D**ivision **M**ultiple **A**ccess
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}WDDX`</span>`{=html}
: **W**eb **D**istributed **D**ata e**X**change
: WDDX was created by Allaire, now known as Macromedia, to solve the
problem of exchanging data between different web applications. This
XML-based technology enables complex data to be exchanged between
totally different Web programming languages by creating \'Web
Syndicate Networks.\'
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}WiMP`</span>`{=html}
: **Wi**ndows **M**edia **P**layer
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}WML`</span>`{=html}
: **W**ireless **M**arkup **L**anguage
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}WSDL`</span>`{=html}
: **W**eb **S**ervice **D**escription **L**anguage (pronounced
\"wiz-dal\")
: WSDL is an XML-based language that provides a model for describing
Web services.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}WWW`</span>`{=html}
: **W**orld **W**ide **W**eb (also W3)
## X
`<span id=3RR style="font-weight: bold">`{=html}X.12`</span>`{=html}
: ASC **X12** (also known as ANSI ASC X12)
: X.12 the official designation of the U.S. national standards body
for the development and maintenance of Electronic Data Interchange
(EDI) standards.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XALAN`</span>`{=html}
: XALAN is a XSLT processor for transforming XML documents into HTML.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XBL`</span>`{=html}
: **X**ML **B**inding **L**anguage
: XBL describes the ability to associate elements in a document with
script, event handlers, CSS and more complex content models, which
can be stored in another document.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XBRL`</span>`{=html}
: e**X**tensible **B**usiness **R**eporting **L**anguage
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XForms`</span>`{=html}
: XForms are the next generation of HTML forms and is richer and more
flexible than HTML forms.
: XForms uses XML for data definition and HTML or XHTML for data
display. XForms separates the data logic of a form from its
presentation. Separating data from presentation makes XForms device
independent, because the data model can be used for all devices.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XHTML`</span>`{=html}
: e**X**tensible **H**yper**T**ext **M**arkup **L**anguage
: XHTML is a cross between HTML and XML.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XLink`</span>`{=html}
: A XLink allows elements to be inserted into XML documents that
create links between resources such as documents, images, files and
other pages. It is similar in concept to an HTML hyperlink, but is
more powerful and flexible.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XML`</span>`{=html}
: e**X**tensible **M**arkup **L**anguage
: XML is a technology for managing data exchange.
: XML is a general-purpose specification for creating custom markup
languages. It is classified as an extensible language because it
allows its users to define their own elements. Its primary purpose
is to facilitate the sharing of structured data across different
information systems, particularly via the Internet, and it is used
both to encode documents and to serialize data.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XML document`</span>`{=html}
: A XML document is a XML file containing XML code.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XML schema`</span>`{=html}
: A XML Schema is a XML file that describes the structure of a
document and its tags.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XML stylesheet`</span>`{=html}
: An XML file containing formatting instructions for an XML file.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XML-RPC`</span>`{=html}
: XML-RPC is a *r*emote *p*rocedure *c*all protocol, which uses XML to
encode its calls and HTTP as a transport mechanism. It is a very
simple protocol, defining only a handful of data types and commands,
and the entire description can be printed on two pages of paper.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XMP `</span>`{=html}
: e**X**tensible **M**etadata **P**latform
: The XMP is a specification describing RDF-based data and storage
models for metadata about documents in any format. XMP can be
included in text files such as HTML or SVG, image formats such as
JPEG or GIF and Adobe\'s own formats like Photoshop or Acrobat.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XPath`</span>`{=html}
: XPath is a language for finding information in an XML document.
XPath is used to navigate through elements and attributes in an XML
document.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XQL`</span>`{=html}
: e**X**tensible **Q**uery **L**anguage
: XQL is a query language designed specifically for XML. In the same
sense that SQL is a query language for relational tables and OQL is
a query language for objects stored in an object database, XQL is a
query language for XML documents.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XQuery`</span>`{=html}
: XQuery is a query language under development by the World Wide Web
Consortium (W3C). The ambitious task is to develop the first world
standard for querying Web documents. XQuery is a versatile markup
language, capable of labeling the information content of diverse
data sources including structured and semi-structured documents,
relational databases, and object repositories.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XSL`</span>`{=html}
: **X**ML **S**tylesheet **L**anguage
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XSLT`</span>`{=html}
: e**X**tensible **S**tylesheet **L**anguage **T**ransformations
: XSLT is an XML-based language used for the transformation of XML
documents into other XML or \"human-readable\" documents.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XSP`</span>`{=html}
: e**X**tensible **S**erver **P**ages
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XSU`</span>`{=html}
: **X**ML **S**QL **U**tility
: Oracle\'s XML SQL Utility uses a schematic mapping that defines how
to map tables and views, including object-relational features, to
XML documents. Oracle translates the chain of object references from
the database into the hierarchical structure of XML elements.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XUL`</span>`{=html}
: e**X**tensible **U**ser Interface **L**anguage
: XUL is an XML-based user interface language originally developed for
use in the Netscape browser. It is now maintained by Mozilla. Like
HTML, in XUL you can create an interface using a relatively simple
markup language, define the appearance with CSS style sheets, and
use JavaScript to manipulate behavior. Unlike HTML, however, XUL
provides a rich set of user interface widgets to create, for
example, menus, toolbars and tabbed panels.
```{=html}
<!-- -->
```
`<span id=3RR style="font-weight: bold">`{=html}XULRunner`</span>`{=html}
: The XULRunner is a Mozilla runtime package that can be used to
bootstrap XUL+XPCOM applications that are as rich as Firefox and
Thunderbird. It will provide mechanisms for installing, upgrading,
and uninstalling these applications. XULRunner will also provide
libxul, a solution, which allows the embedding of Mozilla
technologies in other projects and products.
|
# XML - Managing Data Exchange/Author guidelines
## Editing Chapters
You simply click on the \"edit this page\" tab at the top of any page
you want to edit. You can also just edit a section or subsection - any
place you see a little \'edit\' to the far right above a line, click on
it to edit that section. The thoughts behind the editing process of the
chapters will be documented in the \"discussion\" tab of each chapter -
go there to record your intentions for your assigned chapter.
If you would like to make any suggestions to the editorial board, we
welcome them. At the top of the XML: Managing Data Exchange contents
page is a tab to \"discussion\" follow that link and edit the page with
your comments, be sure to follow the directions for entries.
- **Use wiki code, not HTML code** when you edit a page.
```{=html}
<!-- -->
```
- how to make a link : \[\[XML: Managing Data
Exchange/NameOfThePage(on the page)\|NameOfThePage(displayed as the
link)\]\]
```{=html}
<!-- -->
```
- no plagiarism : please use citations and references to books,
articles, and websites that have helped you contribute to the book.
```{=html}
<!-- -->
```
- All figures and graphics should be prefixed with \'xml\' to avoid
accidentally overwriting another file (e.g., xmldmcity defines the
data model for city).
```{=html}
<!-- -->
```
- Where possible use Portable Network Graphics
(PNG) for graphics because of its
superiority to GIF and JPEG. Also, PNG is Open Source.
OpenOffice.org Draw can be used to
create PNG files.
## Consistency guidelines
**- developed to create a consistent look and feel to the book**
### Layout
- **Chapter summary required**
The bottom of each chapter should include a chapter summary highlighting
the key points of the chapter. Follow the formatting guideline detailed
later on this page.
- **Bold new words**
As new concepts and terminology are introduced in each chapter, make
sure that they are defined first before using them; so that the reader
understands what the words and ideas represent. **Bold** the first
occurrence of the word (or preceding the definition).
- **Use the sentence format for titles**
Capitalize the first letter of a title and allow the rest of the letters
to be lower case, as in this title.
- **Avoid the use of underline and all capital words**
```{=html}
<!-- -->
```
- **Tables, figures, and code references**
For consistency, label all tables, figures (e.g. charts and photos), and
code examples as \"exhibits.\" Place the label for exhibits at the top
of the exhibit, flush left, and enumerate the exhibits, followed by a
brief caption. Examples: \"Exhibit 1: XML data types\" and \"Exhibit 2:
Schema code example\"
- **Concept capsules and breathing room**
Think of your chapter as a data model or a large steak. A useful data
model is broken down into its smallest attributes that require recording
and maintaining for future analysis. A large steak is best eaten in bite
size pieces to prevent choking and promote good digestion. As you revise
your chapter consider the basic elements of your topic; break your topic
down and present each element in a section - so that it is easy for the
reader to follow and understand each part. Feel free to use bullets to
represent lists.
To continue with the steak analogy, it is also good to eat slowly,
taking breaths between each bite. Allow for spaces between each
subsection and greater spaces between each section. This opens up the
text so that it does not appear to dense and compact - and therefore
intimidating.
- **NetBeans (or other XML editor) Examples**
Scroll down the contents page to \"Appendices\". You will see a link to
the chapter \"Using an XML editor\". When you open this link - go to the
edit this page tab and insert a link under the NetBeans heading with the
name of your chapter. This is the format for the link: \[\[XML: Managing
Data Exchange/ChapterName(NetBeans)\|ChapterName\]\] After you save your
edit, the XML Editor page will contain a link to your new NetBeans page.
It will appear red because no information has been posted to that page
yet. Click on the link and paste all the NetBeans information from your
chapter into the edit box. In your assigned chapter, at the places where
there were NetBeans information (that you just cut and paste into the
XML editor page) - put a link to the XML editor - your Chapter page.
- **Help:Wikibooks** \<= this link will
provide several wiki guidelines - this page is also accessible from
the \'help\' link in the navigation box on the left bar of every one
of these Wikibook pages. It contains information on inserting
pictures, creating tables using wiki language (which is much easier
to write and read).
This help page also has a link to a \"sandbox.\" This is a blank page
that allows you to experiment with wiki without affecting a real page.
### Code examples
- Make all code examples a uniform color (black)---some are all black;
some are multicolored. Please change the ones that are multicolored
to all black.
```{=html}
<!-- -->
```
- HTML code is lower case.
```{=html}
<!-- -->
```
- Keep the comments in the code, but put a space above and bellow each
comment.
```{=html}
<!-- -->
```
- Include the file name of the code in a comments tag. If you are the
author of the code, include your name and the date you authored the
code in the comments. See example:
```{=html}
<!-- -->
```
<nowiki>
<!--
Document : city.xsd
Created on : March 1, 2005
Author : Tim Jones
-->
</nowiki>
- Keep all the example codes in the chapter on the same topic---the
TOURGUIDE. If there are examples in your chapter that deviate from
this theme, please change them to show examples from TOURGUIDE.
```{=html}
<!-- -->
```
- If your code contains HTML or the XML declaration then you will want
to put the tags \<pre\> \... \</pre\>
```{=html}
<!-- -->
```
- In order to get those \'pre\' tags to show up I had to use the tags
\<nowiki\> \... `</nowiki>`{=html}
If you run into trouble while inserting code, one of the two tags
mentioned above might be able to get you out.
- You do **not** have to create a table around samples of a code
example; usually just putting a few spaces in front of each line
will create the dashed blue lined box
### Spelling
- Use the spelling \"stylesheet\" instead of \"style sheet.\"
```{=html}
<!-- -->
```
- Use the spelling \"opening tag\" instead of \"opening-tag.\"
```{=html}
<!-- -->
```
- **Check your wiki text with a spellchecker** (e.g. copy and paste in
a text editor that supports spell checking).
### Exercises & Answers
Create two links at the bottom of your chapter, one to an Exercises page
and one to the Answers page already made (you can find this answer page
link at the bottom of the contents page).
In the Exercises page, cut and paste your chapter exercises into a **new
page**. An easy way to create a new page is simply to go to your main
chapter page, type \"exercises\" at the end of the URL, and hit enter.
If the page does not exist, Wikipedia will ask you to create the page by
going to \"edit this page.\"
At the top and bottom of the Exercises page, provide a link to the
chapter and the Answers page---and vice versa with the Answers page.
### Elements of Style - Principles of Composition
**taken from *the Elements of Style* - by William Strunk and E.B.
White**
- **Make the paragraph the unit of composition** - The subject will
need to be broken down into topics, and topics will need to be
broken down into concepts and subconcepts. Each concept should be
explored within its own paragraph.
```{=html}
<!-- -->
```
- **Put statements in positive form** - \"Make definitive assertions.
Avoid tame, hesitating, noncommittal language. Use the word \'not\'
as a means of denial or in antithesis, never as means of evasion.\"
```{=html}
<!-- -->
```
- **Use definite, specific, concrete language** - \"Prefer the
specific to the general, the definite to the vague, the concrete to
the abstract.\"
```{=html}
<!-- -->
```
- **Omit needless words** - \"A sentence should contain no unnecessary
words, a paragraph no unnecessary sentences\...Many expressions
violate this principle: \'the fact that,\' he is a man who \... - he
\...\"
```{=html}
<!-- -->
```
- **Avoid a succession of loose sentences**
```{=html}
<!-- -->
```
- **Express coordinate ideas in similar form**
```{=html}
<!-- -->
```
- **Keep related words together**
```{=html}
<!-- -->
```
- **Place the emphatic words of a sentence at the end**
## Source code
For inserting source code (e.g., XML or Java) into the book, use the
following format:
<nowiki>
<country>
<code>au</code>
<country>Australia</country>
<flag>au.gif</flag>
</country>
</nowiki>
Use the following wiki code:
<pre><nowiki>
<country>
<code>au</code>
<country>Australia</country>
<flag>au.gif</flag>
</country>
</nowiki></pre>
## Section summary
Section summaries should appear in the following format:
-------------------
A chapter summary
-------------------
Use the following wiki code:
{| style="background:linen; border: 1px solid black; padding: 1em; width: 100%;"
|-
| A chapter summary
|-
|}
## Story
Stories/case studies should appear in the following format:
---------
A story
---------
Use the following wiki code:
{| style="background: lightyellow; border: 1px solid black; padding: 1em; width: 100%;"
|-
| A story
|-
|}
## References
- A guide to Wiki
editing
is online
- HTML tables can be converted to Wiki format using an online
tool.
|
# XML - Managing Data Exchange/XML Colors
For use in your stylesheet: these colors can be used for both background
and fonts.
```{=html}
<table class="wikitable" style="margin:0px auto; text-align:center;">
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#000000" width="25" style="color:#FFF;">
```
000000
```{=html}
</td>
```
```{=html}
<td bgcolor="#000033" width="25" style="color:#FFF;">
```
000033
```{=html}
</td>
```
```{=html}
<td bgcolor="#000066" width="25" style="color:#FFF;">
```
000066
```{=html}
</td>
```
```{=html}
<td bgcolor="#000099" width="25" style="color:#FFF;">
```
000099
```{=html}
</td>
```
```{=html}
<td bgcolor="#0000CC" width="25" style="color:#FFF;">
```
0000CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#0000FF" width="25" style="color:#FFF;">
```
0000FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#003300" width="25" style="color:#FFF;">
```
003300
```{=html}
</td>
```
```{=html}
<td bgcolor="#003333" width="25" style="color:#FFF;">
```
003333
```{=html}
</td>
```
```{=html}
<td bgcolor="#003366" width="25" style="color:#FFF;">
```
003366
```{=html}
</td>
```
```{=html}
<td bgcolor="#003399" width="25" style="color:#FFF;">
```
003399
```{=html}
</td>
```
```{=html}
<td bgcolor="#0033CC" width="25" style="color:#FFF;">
```
0033CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#0033FF" width="25" style="color:#FFF;">
```
0033FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#006600" width="25" style="color:#FFF;">
```
006600
```{=html}
</td>
```
```{=html}
<td bgcolor="#006633" width="25" style="color:#FFF;">
```
006633
```{=html}
</td>
```
```{=html}
<td bgcolor="#006666" width="25" style="color:#FFF;">
```
006666
```{=html}
</td>
```
```{=html}
<td bgcolor="#006699" width="25" style="color:#FFF;">
```
006699
```{=html}
</td>
```
```{=html}
<td bgcolor="#0066CC" width="25" style="color:#FFF;">
```
0066CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#0066FF" width="25" style="color:#FFF;">
```
0066FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#009900" width="25" style="color:#FFF;">
```
009900
```{=html}
</td>
```
```{=html}
<td bgcolor="#009933" width="25" style="color:#FFF;">
```
009933
```{=html}
</td>
```
```{=html}
<td bgcolor="#009966" width="25" style="color:#FFF;">
```
009966
```{=html}
</td>
```
```{=html}
<td bgcolor="#009999" width="25" style="color:#FFF;">
```
009999
```{=html}
</td>
```
```{=html}
<td bgcolor="#0099CC" width="25" style="color:#FFF;">
```
0099CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#0099FF" width="25" style="color:#FFF;">
```
0099FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#00CC00" width="25" style="color:#FFF;">
```
00CC00
```{=html}
</td>
```
```{=html}
<td bgcolor="#00CC33" width="25" style="color:#FFF;">
```
00CC33
```{=html}
</td>
```
```{=html}
<td bgcolor="#00CC66" width="25" style="color:#FFF;">
```
00CC66
```{=html}
</td>
```
```{=html}
<td bgcolor="#00CC99" width="25" style="color:#FFF;">
```
00CC99
```{=html}
</td>
```
```{=html}
<td bgcolor="#00CCCC" width="25" style="color:#FFF;">
```
00CCCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#00CCFF" width="25" style="color:#FFF;">
```
00CCFF
```{=html}
</td>
```
```{=html}
<td bgcolor="#00FF00" width="25" style="color:#FFF;">
```
00FF00
```{=html}
</td>
```
```{=html}
<td bgcolor="#00FF33" width="25" style="color:#FFF;">
```
00FF33
```{=html}
</td>
```
```{=html}
<td bgcolor="#00FF66" width="25" style="color:#FFF;">
```
00FF66
```{=html}
</td>
```
```{=html}
<td bgcolor="#00FF99" width="25" style="color:#FFF;">
```
00FF99
```{=html}
</td>
```
```{=html}
<td bgcolor="#00FFCC" width="25" style="color:#FFF;">
```
00FFCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#00FFFF" width="25" style="color:#FFF;">
```
00FFFF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#330000" width="25" style="color:#FFF;">
```
330000
```{=html}
</td>
```
```{=html}
<td bgcolor="#330033" width="25" style="color:#FFF;">
```
330033
```{=html}
</td>
```
```{=html}
<td bgcolor="#330066" width="25" style="color:#FFF;">
```
330066
```{=html}
</td>
```
```{=html}
<td bgcolor="#330099" width="25" style="color:#FFF;">
```
330099
```{=html}
</td>
```
```{=html}
<td bgcolor="#3300CC" width="25" style="color:#FFF;">
```
3300CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#3300FF" width="25" style="color:#FFF;">
```
3300FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#333300" width="25" style="color:#FFF;">
```
333300
```{=html}
</td>
```
```{=html}
<td bgcolor="#333333" width="25" style="color:#FFF;">
```
333333
```{=html}
</td>
```
```{=html}
<td bgcolor="#333366" width="25" style="color:#FFF;">
```
333366
```{=html}
</td>
```
```{=html}
<td bgcolor="#333399" width="25" style="color:#FFF;">
```
333399
```{=html}
</td>
```
```{=html}
<td bgcolor="#3333CC" width="25" style="color:#FFF;">
```
3333CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#3333FF" width="25" style="color:#FFF;">
```
3333FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#336600" width="25" style="color:#FFF;">
```
336600
```{=html}
</td>
```
```{=html}
<td bgcolor="#336633" width="25" style="color:#FFF;">
```
336633
```{=html}
</td>
```
```{=html}
<td bgcolor="#336666" width="25" style="color:#FFF;">
```
336666
```{=html}
</td>
```
```{=html}
<td bgcolor="#336699" width="25" style="color:#FFF;">
```
336699
```{=html}
</td>
```
```{=html}
<td bgcolor="#3366CC" width="25" style="color:#FFF;">
```
3366CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#3366FF" width="25" style="color:#FFF;">
```
3366FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#339900" width="25" style="color:#FFF;">
```
339900
```{=html}
</td>
```
```{=html}
<td bgcolor="#339933" width="25" style="color:#FFF;">
```
339933
```{=html}
</td>
```
```{=html}
<td bgcolor="#339966" width="25" style="color:#FFF;">
```
339966
```{=html}
</td>
```
```{=html}
<td bgcolor="#339999" width="25" style="color:#FFF;">
```
339999
```{=html}
</td>
```
```{=html}
<td bgcolor="#3399CC" width="25" style="color:#FFF;">
```
3399CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#3399FF" width="25" style="color:#FFF;">
```
3399FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#33CC00" width="25" style="color:#000;">
```
33CC00
```{=html}
</td>
```
```{=html}
<td bgcolor="#33CC33" width="25" style="color:#000;">
```
33CC33
```{=html}
</td>
```
```{=html}
<td bgcolor="#33CC66" width="25" style="color:#000;">
```
33CC66
```{=html}
</td>
```
```{=html}
<td bgcolor="#33CC99" width="25" style="color:#000;">
```
33CC99
```{=html}
</td>
```
```{=html}
<td bgcolor="#33CCCC" width="25" style="color:#000;">
```
33CCCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#33CCFF" width="25" style="color:#000;">
```
33CCFF
```{=html}
</td>
```
```{=html}
<td bgcolor="#33FF00" width="25" style="color:#000;">
```
33FF00
```{=html}
</td>
```
```{=html}
<td bgcolor="#33FF33" width="25" style="color:#000;">
```
33FF33
```{=html}
</td>
```
```{=html}
<td bgcolor="#33FF66" width="25" style="color:#000;">
```
33FF66
```{=html}
</td>
```
```{=html}
<td bgcolor="#33FF99" width="25" style="color:#000;">
```
33FF99
```{=html}
</td>
```
```{=html}
<td bgcolor="#33FFCC" width="25" style="color:#000;">
```
33FFCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#33FFFF" width="25" style="color:#000;">
```
33FFFF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#660000" width="25" style="color:#FFF;">
```
660000
```{=html}
</td>
```
```{=html}
<td bgcolor="#660033" width="25" style="color:#FFF;">
```
660033
```{=html}
</td>
```
```{=html}
<td bgcolor="#660066" width="25" style="color:#FFF;">
```
660066
```{=html}
</td>
```
```{=html}
<td bgcolor="#660099" width="25" style="color:#FFF;">
```
660099
```{=html}
</td>
```
```{=html}
<td bgcolor="#6600CC" width="25" style="color:#FFF;">
```
6600CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#6600FF" width="25" style="color:#FFF;">
```
6600FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#663300" width="25" style="color:#FFF;">
```
663300
```{=html}
</td>
```
```{=html}
<td bgcolor="#663333" width="25" style="color:#FFF;">
```
663333
```{=html}
</td>
```
```{=html}
<td bgcolor="#663366" width="25" style="color:#FFF;">
```
663366
```{=html}
</td>
```
```{=html}
<td bgcolor="#663399" width="25" style="color:#FFF;">
```
663399
```{=html}
</td>
```
```{=html}
<td bgcolor="#6633CC" width="25" style="color:#FFF;">
```
6633CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#6633FF" width="25" style="color:#FFF;">
```
6633FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#666600" width="25" style="color:#FFF;">
```
666600
```{=html}
</td>
```
```{=html}
<td bgcolor="#666633" width="25" style="color:#FFF;">
```
666633
```{=html}
</td>
```
```{=html}
<td bgcolor="#666666" width="25" style="color:#FFF;">
```
666666
```{=html}
</td>
```
```{=html}
<td bgcolor="#666699" width="25" style="color:#FFF;">
```
666699
```{=html}
</td>
```
```{=html}
<td bgcolor="#6666CC" width="25" style="color:#FFF;">
```
6666CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#6666FF" width="25" style="color:#FFF;">
```
6666FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#669900" width="25" style="color:#FFF;">
```
669900
```{=html}
</td>
```
```{=html}
<td bgcolor="#669933" width="25" style="color:#FFF;">
```
669933
```{=html}
</td>
```
```{=html}
<td bgcolor="#669966" width="25" style="color:#FFF;">
```
669966
```{=html}
</td>
```
```{=html}
<td bgcolor="#669999" width="25" style="color:#FFF;">
```
669999
```{=html}
</td>
```
```{=html}
<td bgcolor="#6699CC" width="25" style="color:#FFF;">
```
6699CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#6699FF" width="25" style="color:#FFF;">
```
6699FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#66CC00" width="25" style="color:#000;">
```
66CC00
```{=html}
</td>
```
```{=html}
<td bgcolor="#66CC33" width="25" style="color:#000;">
```
66CC33
```{=html}
</td>
```
```{=html}
<td bgcolor="#66CC66" width="25" style="color:#000;">
```
66CC66
```{=html}
</td>
```
```{=html}
<td bgcolor="#66CC99" width="25" style="color:#000;">
```
66CC99
```{=html}
</td>
```
```{=html}
<td bgcolor="#66CCCC" width="25" style="color:#000;">
```
66CCCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#66CCFF" width="25" style="color:#000;">
```
66CCFF
```{=html}
</td>
```
```{=html}
<td bgcolor="#66FF00" width="25" style="color:#000;">
```
66FF00
```{=html}
</td>
```
```{=html}
<td bgcolor="#66FF33" width="25" style="color:#000;">
```
66FF33
```{=html}
</td>
```
```{=html}
<td bgcolor="#66FF66" width="25" style="color:#000;">
```
66FF66
```{=html}
</td>
```
```{=html}
<td bgcolor="#66FF99" width="25" style="color:#000;">
```
66FF99
```{=html}
</td>
```
```{=html}
<td bgcolor="#66FFCC" width="25" style="color:#000;">
```
66FFCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#66FFFF" width="25" style="color:#000;">
```
66FFFF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#990000" width="25" style="color:#FFF;">
```
990000
```{=html}
</td>
```
```{=html}
<td bgcolor="#990033" width="25" style="color:#FFF;">
```
990033
```{=html}
</td>
```
```{=html}
<td bgcolor="#990066" width="25" style="color:#FFF;">
```
990066
```{=html}
</td>
```
```{=html}
<td bgcolor="#990099" width="25" style="color:#FFF;">
```
990099
```{=html}
</td>
```
```{=html}
<td bgcolor="#9900CC" width="25" style="color:#FFF;">
```
9900CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#9900FF" width="25" style="color:#FFF;">
```
9900FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#993300" width="25" style="color:#FFF;">
```
993300
```{=html}
</td>
```
```{=html}
<td bgcolor="#993333" width="25" style="color:#FFF;">
```
993333
```{=html}
</td>
```
```{=html}
<td bgcolor="#993366" width="25" style="color:#FFF;">
```
993366
```{=html}
</td>
```
```{=html}
<td bgcolor="#993399" width="25" style="color:#FFF;">
```
993399
```{=html}
</td>
```
```{=html}
<td bgcolor="#9933CC" width="25" style="color:#FFF;">
```
9933CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#9933FF" width="25" style="color:#FFF;">
```
9933FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#996600" width="25" style="color:#FFF;">
```
996600
```{=html}
</td>
```
```{=html}
<td bgcolor="#996633" width="25" style="color:#FFF;">
```
996633
```{=html}
</td>
```
```{=html}
<td bgcolor="#996666" width="25" style="color:#FFF;">
```
996666
```{=html}
</td>
```
```{=html}
<td bgcolor="#996699" width="25" style="color:#FFF;">
```
996699
```{=html}
</td>
```
```{=html}
<td bgcolor="#9966CC" width="25" style="color:#FFF;">
```
9966CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#9966FF" width="25" style="color:#FFF;">
```
9966FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#999900" width="25" style="color:#FFF;">
```
999900
```{=html}
</td>
```
```{=html}
<td bgcolor="#999933" width="25" style="color:#FFF;">
```
999933
```{=html}
</td>
```
```{=html}
<td bgcolor="#999966" width="25" style="color:#FFF;">
```
999966
```{=html}
</td>
```
```{=html}
<td bgcolor="#999999" width="25" style="color:#FFF;">
```
999999
```{=html}
</td>
```
```{=html}
<td bgcolor="#9999CC" width="25" style="color:#FFF;">
```
9999CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#9999FF" width="25" style="color:#FFF;">
```
9999FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#99CC00" width="25" style="color:#000;">
```
99CC00
```{=html}
</td>
```
```{=html}
<td bgcolor="#99CC33" width="25" style="color:#000;">
```
99CC33
```{=html}
</td>
```
```{=html}
<td bgcolor="#99CC66" width="25" style="color:#000;">
```
99CC66
```{=html}
</td>
```
```{=html}
<td bgcolor="#99CC99" width="25" style="color:#000;">
```
99CC99
```{=html}
</td>
```
```{=html}
<td bgcolor="#99CCCC" width="25" style="color:#000;">
```
99CCCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#99CCFF" width="25" style="color:#000;">
```
99CCFF
```{=html}
</td>
```
```{=html}
<td bgcolor="#99FF00" width="25" style="color:#000;">
```
99FF00
```{=html}
</td>
```
```{=html}
<td bgcolor="#99FF33" width="25" style="color:#000;">
```
99FF33
```{=html}
</td>
```
```{=html}
<td bgcolor="#99FF66" width="25" style="color:#000;">
```
99FF66
```{=html}
</td>
```
```{=html}
<td bgcolor="#99FF99" width="25" style="color:#000;">
```
99FF99
```{=html}
</td>
```
```{=html}
<td bgcolor="#99FFCC" width="25" style="color:#000;">
```
99FFCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#99FFFF" width="25" style="color:#000;">
```
99FFFF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#CC0000" width="25" style="color:#FFF;">
```
CC0000
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC0033" width="25" style="color:#FFF;">
```
CC0033
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC0066" width="25" style="color:#FFF;">
```
CC0066
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC0099" width="25" style="color:#FFF;">
```
CC0099
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC00CC" width="25" style="color:#FFF;">
```
CC00CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC00FF" width="25" style="color:#FFF;">
```
CC00FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC3300" width="25" style="color:#FFF;">
```
CC3300
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC3333" width="25" style="color:#FFF;">
```
CC3333
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC3366" width="25" style="color:#FFF;">
```
CC3366
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC3399" width="25" style="color:#FFF;">
```
CC3399
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC33CC" width="25" style="color:#FFF;">
```
CC33CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC33FF" width="25" style="color:#FFF;">
```
CC33FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#CC6600" width="25" style="color:#FFF;">
```
CC6600
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC6633" width="25" style="color:#FFF;">
```
CC6633
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC6666" width="25" style="color:#FFF;">
```
CC6666
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC6699" width="25" style="color:#FFF;">
```
CC6699
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC66CC" width="25" style="color:#FFF;">
```
CC66CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC66FF" width="25" style="color:#FFF;">
```
CC66FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC9900" width="25" style="color:#FFF;">
```
CC9900
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC9933" width="25" style="color:#FFF;">
```
CC9933
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC9966" width="25" style="color:#FFF;">
```
CC9966
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC9999" width="25" style="color:#FFF;">
```
CC9999
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC99CC" width="25" style="color:#FFF;">
```
CC99CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#CC99FF" width="25" style="color:#FFF;">
```
CC99FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#CCCC00" width="25" style="color:#000;">
```
CCCC00
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCCC33" width="25" style="color:#000;">
```
CCCC33
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCCC66" width="25" style="color:#000;">
```
CCCC66
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCCC99" width="25" style="color:#000;">
```
CCCC99
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCCCCC" width="25" style="color:#000;">
```
CCCCCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCCCFF" width="25" style="color:#000;">
```
CCCCFF
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCFF00" width="25" style="color:#000;">
```
CCFF00
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCFF33" width="25" style="color:#000;">
```
CCFF33
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCFF66" width="25" style="color:#000;">
```
CCFF66
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCFF99" width="25" style="color:#000;">
```
CCFF99
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCFFCC" width="25" style="color:#000;">
```
CCFFCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#CCFFFF" width="25" style="color:#000;">
```
CCFFFF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#FF0000" width="25" style="color:#FFF;">
```
FF0000
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF0033" width="25" style="color:#FFF;">
```
FF0033
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF0066" width="25" style="color:#FFF;">
```
FF0066
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF0099" width="25" style="color:#FFF;">
```
FF0099
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF00CC" width="25" style="color:#FFF;">
```
FF00CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF00FF" width="25" style="color:#FFF;">
```
FF00FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF3300" width="25" style="color:#FFF;">
```
FF3300
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF3333" width="25" style="color:#FFF;">
```
FF3333
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF3366" width="25" style="color:#FFF;">
```
FF3366
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF3399" width="25" style="color:#FFF;">
```
FF3399
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF33CC" width="25" style="color:#FFF;">
```
FF33CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF33FF" width="25" style="color:#FFF;">
```
FF33FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#FF6600" width="25" style="color:#FFF;">
```
FF6600
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF6633" width="25" style="color:#FFF;">
```
FF6633
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF6666" width="25" style="color:#FFF;">
```
FF6666
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF6699" width="25" style="color:#FFF;">
```
FF6699
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF66CC" width="25" style="color:#FFF;">
```
FF66CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF66FF" width="25" style="color:#FFF;">
```
FF66FF
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF9900" width="25" style="color:#FFF;">
```
FF9900
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF9933" width="25" style="color:#FFF;">
```
FF9933
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF9966" width="25" style="color:#FFF;">
```
FF9966
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF9999" width="25" style="color:#FFF;">
```
FF999
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF99CC" width="25" style="color:#FFF;">
```
FF99CC
```{=html}
</td>
```
```{=html}
<td bgcolor="#FF99FF" width="25" style="color:#FFF;">
```
FF99FF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
<tr>
```
```{=html}
<td bgcolor="#FFCC00" width="25" style="color:#000;">
```
FFCC00
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFCC33" width="25" style="color:#000;">
```
FFCC33
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFCC66" width="25" style="color:#000;">
```
FFCC66
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFCC99" width="25" style="color:#000;">
```
FFCC99
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFCCCC" width="25" style="color:#000;">
```
FFCCCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFCCFF" width="25" style="color:#000;">
```
FFCCFF
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFFF00" width="25" style="color:#000;">
```
FFFF00
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFFF33" width="25" style="color:#000;">
```
FFFF33
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFFF66" width="25" style="color:#000;">
```
FFFF66
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFFF99" width="25" style="color:#000;">
```
FFFF99
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFFFCC" width="25" style="color:#000;">
```
FFFFCC
```{=html}
</td>
```
```{=html}
<td bgcolor="#FFFFFF" width="25" style="color:#000;">
```
FFFFFF
```{=html}
</td>
```
```{=html}
</tr>
```
```{=html}
</table>
```
|
# English in Use/Introduction
------------------------------------------------------------------------
## Welcome
Welcome to the English language Wikibook on the English language!
To learn about chapter format and whether this is the right book for
you, continue reading this page. Most of this material is not dependent
on other sections, so you can also use this book as a reference by
clicking on any subject you would like to learn more about on the
contents page. If you don\'t want to bother looking
through chapters for a specific piece of information, click
here
to ask a question on any subject covered in this book. To learn more
about this book and view a list of authors, see the
../About/ page.
Additionally, those knowledgeable about the English language are welcome
and highly encouraged to contribute. See the
../About/ page to learn more about contributing
and add your name to the authors listing.
## Introduction to the English language
English has become one of the most popular languages in the world.
Proper English skills are becoming a valuable asset in business around
the world. Do not put off learning English because of the great variety
of word orders available (even for simple things). Have a go and keep
trying. Practice.
It is well worth remembering that English is not a fixed language - it
is shifting like sand and so these \"rules\" are in the process of
change and are often ignored or bent - much to the disdain of erudite
scholars. This may be one reason why English can be tricky to learn.
## Purpose and structure - What will this book cover?
This book will function as:
1. A guide to structure and grammar,
2. A usage guide, and
3. A manual of style
It is divided into six units: Words and usage, Sentences, Punctuation,
Other key topics, Appendices, and Topics in detail. The eventual goal is
to be usable in English classrooms around the world. This book will not
include English vocabulary and pronunciation (covered in English as an
Additional Language).
Advanced writing topics (covered in
) will also be excluded.
## Intended audience - Who is this book for?
This book is written for native English speakers and those who wish to
learn the finer grammar and mechanics points of the language and improve
their writing and speech, including ESL speakers. It is meant to be both
a structured textbook read chapter by chapter and a reference book.
English as an Additional
Language and Business
English present English in the manner of a
traditional foreign language course.
covers advanced writing
techniques not covered in this book. See /External
resources for other pages to read.
## Chapter format
All pages of this book should be about the same length and difficulty,
in order to provide consistency and allow readers to plan ahead how much
they want to read each session. Each chapter will try to not be
dependent on previous chapters as much as possible. Each chapter should
be accompanied by exercises using .
## Contributing - What can I do to help?
Both experts and beginners can help to improve this book. If you would
like to help, the about page should tell you
everything you want to know to help. If you don\'t have a lot of time to
work on this book, there are two simple things you can do. Firstly, you
can make sure that is on every
page. Type
on the bottom of the page to include the template. Secondly, you are
encouraged to comment on each chapter on its talk page. Don\'t
understand something? Please say so so others don\'t experience the same
problem! If you feel you understand the material on a page pretty well,
## Brief language history
Modern English has evolved out of old Anglo-Saxon, a language much like
modern German. In the process, it has borrowed many Latin words, and
completely changed its grammar.
The story starts when the Romans left Britain, leaving the Celtic
Britons in chaos. One Celtic king asked the Angles, Saxons, and Jutes to
come and fight for him, but they decided to take over England instead,
since the Celts couldn\'t put up a decent fight.
Soon, there were no Celts left in England, and hardly any trace of the
Celtic languages. There are a few river names inherited from the Celts,
or earlier, and maybe a dozen words, but no more. This complete
obliteration of the Celts was unusually thorough for the times.
A few generations later the English converted to Christianity. The new
religion brought with it a flood of new words, borrowed from Latin and
Greek; religious terms such as *Angel*, *priest*, and *nun*, but also
names of un-English things such *lion*, *pepper*, and *oyster*.
Around this time, the English began slurring the ends of words. This was
the start of the process that created modern English grammar.
After a few centuries of peace the Vikings invaded. They spoke Old
Norse, a language related to English. After much fighting, they settled
down in North East England, and introduced many Norse words into
English, including the pronouns *them*, *they*, and *their*.
Just as the Viking invasions stopped, the French-speaking Normans
invaded. Commoners continued speaking English, but for the next two
centuries the noblemen spoke French.
A few French words trickled into English during the period, but the
number stayed pretty low until the nobles stopped speaking French, in
the mid thirteenth century. This precipitated a large influx of words of
French origin into the English language as an entire class migrated from
French to English. Many of the French words were Anglicized, but some of
the spelling of the words remained roughly intact. It should be noted
that the Normans spoke an older version of French known as *Old French*
that may sometimes actually seem to be closer to English than current
French, because English took some words from Old French wholesale, such
as *mansion*. Around the same time the universities of Oxford and
Cambridge were founded.
During the Renaissance, the scholars of England added many more Greek
and Latin words to the English language. As a result, much of the
technical vocabulary in English consists of Greek or Latin words.
Since then, English has also borrowed many words from the major European
languages, such as French, as well as a few words from almost every
other language. It is still changing and developing.
hi:अंग्रेज़ी भाषा/परिचय
|
# English in Use/Articles
An **article** is the word *the*, *an*, or *a*, which we put before
nouns to limit their signification: as, *the air, the stars, an island,
a ship*.
The articles can seldom be put one for the other, without gross
impropriety; and of course either is to be preferred to the other, as it
better suits the sense: as,
- \"The violation of this rule never fails to hurt and displease a
reader.\"---Blair\'s Lectures, p. 107.
- Say, \"A violation of this rule never fails to displease the
reader.\"
## Nouns without any article
A common noun, when taken in its widest sense, usually admits no
article: as,
- \"A candid temper is proper for man; that is, for all
mankind.\"---Murray.
Nouns without any article, or other definitive, are often used in a
sense indefinitely partitive: as,
- \"He took bread, and gave thanks.\"---Acts.
- That is, \"Some bread.\"
- \"To buy food are your servants come.\"---Genesis.
- That is, \"Some food.\"
- \"There are fishes that have wings, and are not strangers to the
airy region.\"---Locke\'s Essay, p. 322.
- That is, \"Some fishes.\"
- Words in which nothing but the mere being of anything is implied,
are used without articles: as, \'This is not beer, but water;\'
\'This is not brass, but steel.\'---Dr. Johnson\'s Gram., p. 5.
## Indefinite articles
The indefinite article is *an* or *a*, which denotes one thing of a
kind, but not any particular one: as, *a boy, an orange*.
*An* is used in preference to a, whenever the following word begins with
a vowel sound: as, *an art, an end, an heir, an inch, an ounce, an hour,
an urn*.
*A* is used in preference to *an*, whenever the following word begins
with a consonant sound: as, *a man, a house, a wonder, a one, a yew, a
use, a ewer, a European car*.
The consonant sounds of *w* and *y*, even when expressed by other
letters, require *a* and not *an* before them: as,
- \"In an epic poem, or a poem upon an elevated subject, a writer
ought to avoid raising a simile on a low image.\"---Ld. Kames.
*An* or *a* before the genus, may refer to a whole species; and the
before the species, may denote that whole species emphatically: as,
- \"A certain bird is termed the cuckoo, from the sound which it
emits.\"---Blair.
But *an* or *a* is commonly used to denote individuals as unknown, or as
not specially distinguished from others: as,
- \"I see an object pass by, which I never saw till now; and I say,
\'There goes a beggar with a long beard.\'\"---Harris.
The article *an* or *a* implies unity, or one, and of course belongs to
nouns of the singular number only: as, *a man, an old man, a good boy*.
*An* or *a* sometimes gives a collective meaning to a numeral, when the
noun following is plural: as, *a few days, a hundred men, one hundred
pounds sterling*.
## Definite articles
The definite article is *the*, which denotes some particular thing or
things: as, *the boy, the oranges*.
The definite article is commonly used to denote individuals as known, or
as specially distinguished from others: as,
- \"The man departs, and returns a week after; and I say, \'There goes
the beggar with the long beard.\'\"---Id.
The article *the* is applied to nouns of either number: as, *the man,
the men; the good boy, the good boys*.
The is commonly required before adjectives that are used by ellipsis as
nouns: as,
- \"The young are slaves to novelty; the old, to custom.\"---Ld.
Kames.
Pronunciation of \"the\" all depends on the word it\'s referring to and
whether that word starts with a vowel sound or a consonant sound. When
the word begins with a vowel sound we use the long \"the\" (thee). For
example: The (thee) Apple, the (thee hOur). When the word begins with a
consonant sound we use the short \"the\" (thuh). For example: The (thuh)
Banana, the (thuh) University.
Sometime\'s \"the\" is used to emphasize a noun, especially when that
noun is unique. When writing this particular use of \"the\" it is almost
always written in Italics *\"the\"*.
For Example: \"I saw the Queen last week.\" \"What?! *The* (thee) Queen?
As in Queen Elizabeth the 2nd?\" \"Yes, Queen Elizabeth.\"
## General rules
Articles should be inserted as often as the sense requires them: as,
- \"Repeat the preterit and \[the\] past participle of the verb to
abide.\"---Merchant\'s American School Grammar, p. 66.
Needless articles should be omitted; they seldom fail to pervert the
sense: as,
- \"The Rhine, the Danube, the Tanais, the Po, the Volga, the Ganges,
like many hundreds of similar names, rose not from any obscure
jargon or irrational dialect.\"---Dr. Murray\'s Hist. of Europ.
Lang., Vol. i, p. 327.
## A short syntax
Articles relate to the nouns which they limit, as \"The blind beggar,\"
except the following cases: the comparative or the superlative degree,
as \"The mightiest,\" and an unstressed numeral, as \"A hundred men.\"
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
|
# English in Use/Nouns
------------------------------------------------------------------------
: *This page is written in English, and therefore needs to be
translated at a later date to other languages for it to become more
useful.*
+----------------------------------------------------------------------+
| **Examples** |
+======================================================================+
| - **Janet** is the **name** of a **girl**. |
| - **Apple** is a **fruit** and a computer **company**. |
| |
| In the above sentence, \"computer\" is an adjective because it is |
| describing \"company\". |
| |
| - **Cleanliness** is next to **Godliness**. |
| - The **World Wide Web** has become the least expensive **way** to |
| publish **information**. |
+----------------------------------------------------------------------+
A **noun**, or **noun substantive**, is a part of speech (a word or
phrase) which functions as the head of a noun phrase. The word \"noun\"
derives from the Latin *nomen* meaning \"name\", and a traditional
definition of nouns is that they are only those expressions that refer
to a person, place, thing, event, substance, quality, or idea. They
serve as the subject or object of a verb and as the governed term of a
preposition, and can co-occur with articles and attributive adjectives.
There are different groups of nouns:
- **Common nouns**---\"*chair*\",
- **Proper nouns**---\"*Fred*\",
- **Abstract nouns**---\"*love*\",
- **Collective nouns**---\"*gaggle*\",
- **Compound nouns**---\"*butterfly*\",
- **Verbal nouns**---\"*triumphing*\".
Each of these different groups of nouns have different properties, each
making them different in how we use them.
Thus, nouns are names of objects, places, people and things. They are
used with adjectives to describe something, and with verbs to show an
action.
## Concrete nouns
Concrete nouns are proper nouns and common nouns.
### Proper nouns
**Proper nouns** are the names of people, places, groups or dates: as,
*Adam*, *Boston*, *the Hudson*, *the Romans*, *the Azores*, *the Alps*.
They almost always have a capital letter as their first letter. Example:
- \"*Timmy* is not someone to be toyed with.\"No one likes to hear
other people boast their talents
### Common nouns
**Common nouns** are the names of a sort, kind, or class, of beings or
things: as, *beast*, *bird*, *fish*, *insect*, *creatures*, *persons*,
*children*. They often refer to objects or things which we can see,
touch and feel, like the word *chair*. Example:
- \"I sat at the *table*.\"
#### Individual nouns
Their refer to only one thing of the same kind, for eg: man, player,
cow, chicken, minister.
#### Collective nouns
**Collective nouns** are the names of a groups of objects or many
individuals together: as, *council*, *meeting*, *committee*, *flock*.
Example:
- \"They are a *group*.\"
## Abstract nouns
**Abstract nouns** are the names of some particular qualities considered
apart from its substance: as, *goodness*, *hardness*, *pride*,
*frailty*. They are often names of the things that we cannot touch or
see, but are there all the same. Example:
- \"I think I\'ve fallen in *love*!\"
### Attribute
### Verbal nouns
**Verbal nouns** or **participial nouns** are the names of some actions,
or states of being; and are formed from a verb, like a participle, but
employed as a noun: as,
- \"The *triumphing* of the wicked is short.\"---Job, XX, 5.
### Sui generis
A thing **sui generis**, (i.e., of its own peculiar kind,) is something
which is distinguished, not as an individual of a species, but as a sort
by itself, without plurality in either the noun or the sort of thing:
as, *galvanism*, *music*, *geometry*.
## Words and word groups used as nouns
### Adjectives made nouns
- \"The Ancient of days did sit.\"---*Bible*.
- \"Of the ancients.\"---*Swift*.
- \"For such impertinents.\"---*Steele*.
- \"He is an ignorant in it.\"---*Id*.
- \"In the luxuriance of an unbounded picturesque.\"---*Jamieson*.
- \"A source of the sublime;\"---*Burke*.
- \"The vast immense of space:\"---*Murray*.
- \"There is none his like.\"---*Job, XLI, 33*.
- \"A little more than a little, is by much too
much.\"---*Shakespeare*.
- \"And gladly make much of that entertainment.\"---*Sidney*.
- \"A covetous man makes the most of what he has.\"---*L\'Estrange*.
- \"It has done enough for me.\"---*Pope*.
- \"He had enough to do.\"---*Bacon*.
- \"All withers here; who most possess, are losers by their gain,
stung by full proof, that bad at best, life\'s idle all is
vain.\"---*Young*.
- \"Nor grudge I you the much the Grecians give, nor murmuring take
the little I receive.\"---*Dryden*.
### Pronouns made nouns
- \"A love of seeing the what and how of all about him.\"---Story\'s
Life of Flaxman: Pioneer, Vol. i, p. 133.
- \"The nameless he, whose nod is Nature\'s birth.\"---Young, Night
iv.
- \"I was wont to load my she with knacks.\"---Shak. Winter\'s Tale.
- \"Or any he, the proudest of your sort.\"---Shak.
- \"I am the happiest she in Kent.\"---Steele.
- \"The shes of Italy.\"---Shak.
- \"The hes in birds.\"---Bacon.
- \"We should soon have as many hes and shes as the
French.\"---Cobbet\'s E. Gram., Para. 42.
- \"If, for instance, we call a nation a she, or the sun a
he.\"---Ib., Para. 198.
- \"When I see many its in a page, I always tremble for the
writer.\"---Ib., Para. 196.
- \"Let those two questionary petitioners try to do this with their
whos and their whiches.\"---Spect: Ash\'s Gr., p. 131.
- \"Such mortal drugs I have; but Mantua\'s law is death to any he
that utters them.\"---Shak.
### Verbs made nouns
- \"Avaunt all attitude, and stare, and start theatric.\"---Cowper.
- \"A may-be of mercy is sufficient.\"---Bridge.
- \"Which cuts are reckoned among the fractures.\"---Wiseman.
- \"The officer erred in granting a permit.\"
- \"Feel darts and charms, attracts and flames.\"---Hudibras.
- \"You may know by the falling off of the come, or
sprout.\"---Mortimer.
- \"And you have talked of sallies and retires.\"---Shak.
- \"For all that else did come, were sure to fail; yet would he
further none, but for avail.\"---Spenser.
### Participles made nouns (gerunds)
- \"For the producing of real happiness.\"---Crabb.
- \"For the crying of the poor and the sighing of the needy, I will
arise.\"---Bible.
- \"Surely the churning of milk brings forth butter, and the wringing
of the nose brings forth blood; so the forcing of wrath brings forth
strife.\"---Prov., xxx, 33.
- \"Reading, writing, and ciphering, are indispensable to civilized
man.\"
- \"Hence was invented the distinction between doing and
permitting.\"---Calvin\'s Inst., p. 131.
- \"Knowledge of the past comes next.\"---Hermes, p. 113.
- \"I am my beloved\'s, and his desire is toward me.\"---Sol. Song,
vii, 10.
- \"Here\'s---a simple coming-in for one man.\"---Shak.
- \"What are your rents? What are your comings-in? O Ceremony, show me
but your worth.\"---Id.
### Adverbs made nouns
- \"In these cases we examine the why, the what, and the how of
things.\"---L\'Estrange.
- \"If a point or now were extended, each of them would contain within
itself infinite other points or nows.\"---Hermes, p. 101.
- \"The why is plain as way to parish church.\"---Shak.
- \"It is heaven itself that points out an hereafter.\"---Addison.
- \"The dread of a hereafter.\"---Fuller.
- \"The murmur of the deep amen.\"---Sir W. Scott.
- \"For their whereabouts lies in a mystery.\"---Book of Thoughts,
p. 14. Better.
- \"Bid them farewell, Cordelia, though unkind; you lose here, a
better where to find.\"---Shak.
### Conjunctions made nouns
- \"The if, which is here employed, converts the sentence into a
supposition.\"---Blair\'s Rhet.
- \"Your if is the only peacemaker; much virtue is in if.\"---Shak.
- \"So his lordship decreed with a grave solemn tone, decisive and
clear, without one if or but---that whenever the nose put his
spectacles on, by daylight or candlelight---eyes should be
shut.\"---Cowper.
### Prepositions made nouns
- \"O, not like me; for mine\'s beyond beyond.\"---Shakspeare: Cymb.,
iii, 2.
- \"I.e., her longing is further than beyond; beyond anything that
desire can be said to be beyond.\"---Singer\'s Notes.
- \"You whirled them to the back of beyont to look at the auld Roman
camp.\"---Antiquary, i. 37.
### Interjections or phrases made nouns
- \"Come away from all the lo-heres! and lo-theres!\"---Sermon.
- \"Will cuts him short with a \'What then?\'\"---Sermon.
- \"With hark and whoop, and wild halloo.\"---Scott.
- \"And made a pish at chance and sufferance.\"---Shak.
- \"A single look more marks the internal wo, than all the windings of
the lengthened oh.\"---Lloyd.
## Countable and uncountable nouns
## Inflections of Nouns
Nouns have modifications of genders, numbers, and cases.
### Genders
Genders, in grammar, are modifications that distinguish objects in
regard to sex.
There are three genders; the masculine, the feminine, and the neuter:
1. The **masculine** gender is that which denotes persons or animals of
the male kind: as, *man, father, king*.
2. The **feminine** gender is that which denotes persons or animals of
the female kind: as, *woman, mother, queen*.
3. The **neuter** gender is that which denotes things that are neither
male nor female: as, *pen, ink, paper*.
Hence, names of males are masculine; names of females, feminine; and
names of things inanimate, literally, neuter.
- Masculine nouns make regular feminines, when their termination is
changed to *ess*: as,
: *Hunter, huntress; prince, princess; lion, lioness*.
- In some instances the syllable *ess* is simply added: as,
: *Accuser, accuseress; advocate, advocatess; archer, archeress;
author, authoress; avenger, avengeress; barber, barberess; baron,
baroness; canon, canoness; cit, cittess; coheir, coheiress; count,
countess; deacon, deaconess; demon, demoness; diviner, divineress;
doctor, doctoress; giant, giantess; god, goddess; guardian,
guardianess; Hebrew, Hebrewess; heir, heiress; herd, herdess;
hermit, hermitess; host, hostess; Jesuit, Jesuitess; Jew, Jewess;
mayor, mayoress; Moabite, Moabitess; monarch, monarchess; pape,
papess; or, pope, popess; patron, patroness; peer, peeress; poet,
poetess; priest, priestess; prior, prioress; prophet, prophetess;
regent, regentess; saint, saintess; shepherd, shepherdess; soldier,
soldieress; tailor, tailoress; viscount, viscountess; warrior,
warrioress*.
- In other instances, the termination is changed, and there is no
increase of syllables: as,
: *Abbot, abbess; actor, actress; adulator, adulatress; adulterer,
adulteress; adventurer, adventuress; advoutrer, advoutress;
ambassador, ambassadress; anchorite, anchoress; or, anachoret,
anachoress; arbiter, arbitress; auditor, auditress; benefactor,
benefactress; caterer, cateress; chanter, chantress; cloisterer,
cloisteress; commander, commandress; conductor, conductress;
creator, creatress; demander, demandress; detractor, detractress;
eagle, eagless; editor, editress; elector, electress; emperor,
emperess, or empress; emulator, emulatress; enchanter, enchantress;
exactor, exactress; fautor, fautress; fornicator, fornicatress;
fosterer, fosteress, or fostress; founder, foundress; governor,
governess; huckster, huckstress; or, hucksterer, hucksteress;
idolater, idolatress; inhabiter, inhabitress; instructor,
instructress; inventor, inventress; launderer, launderess, or
laundress; minister, ministress; monitor, monitress; murderer,
murderess; negro, negress; offender, offendress; ogre, ogress;
porter, portress; progenitor, progenitress; protector, protectress;
proprietor, proprietress; pythonist, pythoness; seamster,
seamstress; solicitor, solicitress; songster, songstress; sorcerer,
sorceress; suitor, suitress; tiger, tigress; traitor, traitress;
victor, victress; votary, votaress*.
- In a few instances the feminine is formed as in Latin, by changing
*or* to *rix*; but some of these have also the regular form, which
ought to be preferred: as,
: *Adjutor, adjutrix; administrator, administratrix; arbitrator,
arbitratrix; coadjutor, coadjutrix; competitor, competitress, or
competitrix; creditor, creditrix; director, directress, or
directrix; executor, executress, or executrix; inheritor,
inheritress, or inheritrix; mediator, mediatress, or mediatrix;
orator, oratress, or oratrix; rector, rectress, or rectrix;
spectator, spectatress, or spectatrix; testator, testatrix; tutor,
tutoress, or tutress, or tutrix; deserter, desertress, or
desertrice, or desertrix*.
- The following are irregular words, in which the distinction of sex
is chiefly made by the termination:
: *Amoroso, amorosa: archduke, archduchess; chamberlain, chambermaid;
duke, duchess; gaffer, gammer; goodman, goody, or goodwife; hero,
heroine; landgrave, landgravine; margrave, margravine; marquis,
marchioness; palsgrave, palsgravine; sakeret, sakerhawk; sewer,
sewster; sultan, sultana; tzar, tzarina; tyrant, tyranness; widower,
widow*.
### Numbers
Numbers, in grammar, are modifications that distinguish unity and
plurality.
There are two numbers; the **singular** and the **plural**.
The singular number is that which denotes but one: as,
- \"The boy learns.\"
The plural number is that which denotes more than one: as,
- \"The boys learn.\"
- Plurals in meaning and form:
: *Analects, annals, archives, ashes, assets, billiards, bowels,
breeches, calends, cates, chops, clothes, compasses, crants, eaves,
embers, estovers, forceps, giblets, goggles, greaves, hards or
hurds, hemorrhoids, ides, matins, nippers, nones, obsequies, orgies,
piles, pincers or pinchers, pliers, reins, scissors, shears,
skittles, snuffers, spectacles, teens, tongs, trowsers, tweezers,
umbles, vespers, victuals*.
- Plurals by formation, derived chiefly from adjectives:
: *Acoustics, aeronautics, analytics, bitters, catoptrics, commons,
conics, credentials, delicates, dioptrics, economics, ethics,
extraordinaries, filings, fives, freshes, glanders, gnomonics,
goods, hermeneutics, hustings, hydrodynamics, hydrostatics,
hydraulics, hysterics, inwards, leavings, magnetics, mathematics,
measles, mechanics, mnemonics, merils, metaphysics, middlings,
movables, mumps, nuptials, optics, phonics, phonetics, physics,
pneumatics, poetics, politics, riches, rickets, settlings, shatters,
skimmings, spherics, staggers, statics, statistics, stays,
strangles, sundries, sweepings, tactics, thanks, tidings, trappings,
vives, vitals, wages, withers, yellows*.
- Plurals by composition:
: *Backstairs, cocklestairs, firearms, headquarters, hotcockles,
spatterdashes, self-affairs. To these may be added the Latin words,
aborigines, antipodes, antes, antoeci, amphiscii, anthropophagi,
antiscii, ascii, literati, fauces, regalia, and credenda, with the
Italian vermicelli, and the French belles-lettres and entremets*.
#### Regular plurals
The plural form is usually represented orthographically by adding *s* to
the singular form. The phonetic form of the plural morpheme is
by default. When the preceding sound is a
voiceless consonant, it is pronounced .
Examples: *boy* makes *boys*; *girl*, *girls*; *chair*, *chairs*; *cat*,
*cats*.
Where a noun ends in a sibilant sound, the plural is formed by adding
*es* (pronounced ), which is spelled *es* if
the word does not already end with *e*: *glass* makes *glasses*; *dish,
dishes; witch, witches; phase, phases; judge, judges*.
Most nouns ending in *o* preceded by a consonant also form their plurals
by adding *es* (pronounced ): *hero* makes
*heroes*; *potato, potatoes; volcano, volcanoes*.
Nouns ending in a *y* preceded by a consonant drop the *y* and add *ies*
(pronounced ): *cherry* makes *cherries*;
*lady, ladies*.
Proper nouns (particularly those for people or places) ending in a *y*
preceded by a consonant form their plurals regularly: *Harry* makes
*Harrys*; *Germany, Germanys*.
This does not apply to words that are merely capitalised common nouns:
as, *P&O Ferries*.
A few common nouns ending in a *y* preceded by a consonant form their
plurals regularly: *henry* makes *henrys*; *zloty, zlotys*.
Words ending in *ey* form their plurals regularly, in order to avoid the
unpleasant-appearing vowel sequence *eie*: *monkey, monkeys*.
#### Almost-regular plurals
Many nouns of Italian or Spanish origin are exceptions to the **oes
rule**: *canto* makes *cantos*; *piano, pianos; portico, porticos;
quarto, quartos; solo, solos*.
Many nouns ending in a voiceless fricative mutate that sound to a voiced
fricative before adding the plural ending. In the case of
changing to the
mutation is indicated in the orthography as well: *calf* makes *calves*;
*bath, baths; mouth, mouths; house, houses*.
Some retain the voiceless consonant: *proof* makes *proofs*; *moth,
moths; place, places; dwarf, dwarfs or dwarves; hoof, hoofs or hooves;
staff, staffs or staves; turf, turfs or turves; roof, roofs or rooves*.
#### Irregular plurals
There are many other less regular ways of forming plurals. While they
may seem quirky, they usually stem from older forms of English or from
foreign borrowings.
#### Irregular Germanic plurals
The plural of a few Germanic nouns can also be formed from the singular
by adding *n* or *en*, stemming from the obsolete weak declension: *ox*
makes *oxen*; *child, children*.
The plural is sometimes formed by simply changing the vowel sound of the
singular, in a process called umlaut (these are sometimes called
*mutated plurals*): *foot* makes *feet*; *goose, geese; louse, lice;
man, men; mouse, mice; tooth, teeth; woman, women*.
Some nouns have singular and plural alike, although they are sometimes
seen as regular plurals: as, *aircraft, sheep, deer, fish, cod, trout,
head, cannon*.
Generally, plurals refer to several species or kinds of animal, while
the unmarked plural is used to describe multiple individual animals; one
would say *the classification of fishes*, but *five fish in an
aquarium*.
#### Irregular plurals of foreign origin
Such nouns often retain their original plurals. In some cases both forms
are still vying: for a librarian, the plural of *appendix* is
*appendices*; for physicians, the plural of *appendix* is *appendixes*.
A radio engineer works with *antennas* and an entomologist deals with
*antennae*. The \"correct\" form is the one that sounds better in
context. Correctly formed Latin plurals are the most acceptable, in
academic and scientific contexts. In common usage, plurals with *s* are
sometimes preferred.
- Final *a* becomes *ae* (also *æ*) or just adds *s*:
: *Formula* makes *formulae*, *lamina*, *laminae*; *macula*,
*maculae*; minutia, *minutiae*; *nebula*, *nebulae*; *siliqua*,
*siliqiuae*; *dogma*, *dogmas* or *dogmata*; *exanthema*,
*exanthemas* or *exanthemata*; *miasm* or *miasma*, *miasms* or
*miasmata*; *stigma*, *stigmas* or *stigmata*.
```{=html}
<!-- -->
```
: *Saliva* and *scoria* have no occasion for the plural.
- Final *ex* or *ix* becomes *ices* (pronounced
or ) or
just adds *es*. Of nouns in *x*, there are few, if any, which ought
not to form the plural regularly, when used as English words; though
the Latins changed *x* to *ces*, and *ex* to *ices*, making the *i*
sometimes long and sometimes short: as,
: *Apex, apices, for apexes; appendix, appendices, for appendixes;
calix, calices, for calixes; calx, calces, for calxes; calyx,
calyces, for calyxes; caudex, caudices, for caudexes; cicatrix,
cicatrices, for cicatrixes; helix, helices, for helixes; index,
indices, for indexes; matrix, matrices, for matrixes; quincunx,
quincunces, for quincunxes; radix, radices, for radixes; varix,
varices, for varixes; vertex, vertices, for vertexes; vortex,
vortices, for vortexes*.
```{=html}
<!-- -->
```
: Some Greek words in *x* change that letter to *ges*: as, *larynx,
larynges, for larinxes; phalanx, phalanges, for phalanxes*.
*Billet-doux*, from the French, is *billets-doux* in the plural.
- Final *is* becomes *es* (pronounced . Of
nouns in *is*, some are regular: as, *trellis, trellises: so,
annolis, butteris, caddis, dervis, iris, marquis, metropolis,
portcullis, proboscis*.
: Some seem to have no need of the plural: as, *ambergris,
aqua-fortis, arthritis, brewis, crasis, elephantiasis, genesis,
orris, siriasis, tennis*.
```{=html}
<!-- -->
```
: But most nouns of this ending follow the Greek or Latin form, which
simply changes *is* to *es*: as, *amanuensis, amanuenses; analysis,
analyses; antithesis, antitheses; axis, axes; basis, bases; crisis,
crises; diaeresis, diaereses; diesis, dieses; ellipsis, ellipses;
emphasis, emphases; fascis, fasces; hypothesis, hypotheses;
metamorphosis, metamorphoses; oasis, oases; parenthesis,
parentheses; phasis, phases; praxis, praxes; synopsis, synopses;
synthesis, syntheses; syrtis, syrtes; thesis, theses*.
```{=html}
<!-- -->
```
: In some, however, the original plural is not so formed; but is made
by changing *is* to *ides*: as, *aphis, aphides; apsis, apsides;
ascaris, ascarides; bolis, bolides; cantharis, cantharides;
chrysalis, chrysalides; ephemeris, ephemerides; epidermis,
epidermides*.
```{=html}
<!-- -->
```
: So *iris* and *proboscis*, which we make regular; and perhaps some
of the foregoing may be made so too.
- Final *ies* remains unchanged: as, *series, species*.
- Final *on* becomes *a*. Of nouns in *on*, derived from Greek, the
greater part always form the plural regularly: as, *etymons,
gnomons, ichneumons, myrmidons, phlegmons, trigons, tetragons,
pentagons, hexagons, heptagons, octagons, enneagons, decagons,
hendecagons, dodecagons, polygons*.
: So *trihedrons, tetrahedrons, pentahedrons*, etc., though some say,
these last may end in *dra*.
```{=html}
<!-- -->
```
: For a few words of this class, however, there are double plurals in
use; as, *automata* or *atomatons*, *criteria* or *criterions*,
*parhelia* or *parhelions*; and the plural of *phenomenon* appears
to be always *phenomena*.
```{=html}
<!-- -->
```
: The plural of *legumen* is *legumens* or *legumina*; of *stamen*,
*stamens* or *stamina*: of *cherub*, *cherubs* or *cherubim*; of
*seraph*, *seraphs* or *seraphim*; of *beau*, *beaus* or *beaux*; of
*bandit*, *bandits* or *banditti*.
- Final *um* becomes *a* or just adds *s*: as, *addendum* makes
*addenda*, *medium* makes *media* or *mediums*. Of nouns in *um*,
some have no need of the plural: as,
: *Bdellium, decorum, elysium, equilibrium, guaiacum, laudanum, odium,
opium, petroleum, serum, viaticum. Some form it regularly; as,
asylums, compendiums, craniums, emporiums, encomiums, forums,
frustums, lustrums, mausoleums, museums, pendulums, nostrums,
rostrums, residuums, vacuums. Others take either the English or the
Latin plural; as, desideratums or desiderata, mediums or media,
menstruums or menstrua, memorandums or memoranda, spectrums or
spectra, speculums or specula, stratums or strata, succedaneums or
succedanea, trapeziums or trapezia, vinculums or vincula. A few seem
to have the Latin plural only: as, arcanum, arcana; datum, data;
effluvium, effluvia; erratum, errata; scholium, scholia*.
- Final *us* becomes *i* (second declension), *era*, *ora* (third
declension), or just adds *es* (especially in fourth declension,
where it would otherwise be the same as the singular): as, *alumnus*
makes *alumni*, *viscus viscera, corpus corpora, prospectus
prospectuses*.
: But such as have properly become English words, may form the plural
regularly in *es*; as, *chorus, choruses*: so, *apparatus, bolus,
callus, circus, fetus, focus, fucus, fungus, hiatus, ignoramus,
impetus, incubus, isthmus, nautilus, nucleus, prospectus, rebus,
sinus, surplus*.
```{=html}
<!-- -->
```
: *Radius* makes *radii* or *radiuses*. *Genius* has *genii*, for
imaginary spirits, and *geniuses*, for men of wit. *Genus*, a sort,
becomes *genera* in Latin, and *genuses* in English. *Denarius*
makes *denarii* or *denariuses*.
```{=html}
<!-- -->
```
: Of nouns in *us*, a few have no plural: as, *asparagus*, *calamus*,
*mucus*.
```{=html}
<!-- -->
```
: Some have only the Latin plural, which usually changes *us* to *i*:
as, *alumnus, alumni; androgynus, androgyni; calculus, calculi;
dracunculus, dracunculi; echinus, echini; magus, magi*.
```{=html}
<!-- -->
```
: Final *us* in nouns of Greek origin \"properly\" add *es*. These
words are also heard with the Latin *i* instead, which is sometimes
considered \"over-correct\", but this is so common as to be
acceptable in most circumstances, even technical ones: *cactus*
makes *cactuses* or *cacti*; *hippopotamus, hippopotamuses or
hippopotami, octopus, octopuses, octopi, or octopodes; platypus,
platypuses, rhinoceros, rhinoceroses or rhinoceri, uterus, uteruses
or uteri*.
- Final *as* in one case of a noun of Greek origin changes to *antes*:
*Atlas* makes *Atlantes*; *atles, atlases*.
- Final *ma* in nouns of Greek origin add *ta*: *stigma* makes
*stigmata*; *stoma, stomata; zeugma, zeugmata*.
: Though some take *s* more commonly: *schema* makes *schemata* or
*schemas*; *dogma*, *dogmata* or *dogmas*; *lemma*, *lemmata* or
*lemmas*.
- Some nouns of French origin add *x*: *beau* makes *beaux*; *chateau,
chateaux; bureau, bureaus or bureaux*.
- Nouns from Slavic languages: *kniazhestvo* makes *kniazhestvos* or
*kniazhestva*; *kobzar*, *kobzars* or *kobzari*, *oblast*, *oblasts*
or *oblasti*.
- Nouns of Hebrew language origin add *im*, *ot* (generally m/f), or
just *s*: *cherub* makes *cherubim* or *cherubs*; *seraph, seraphim
or seraphs; matzoh, matzot or matzos*.
: The Hebrew plurals *cherubim* and *seraphim*, being sometimes
mistaken for singulars, other plurals have been formed from them.
- Some nouns of Japanese origin have no plural and do not change: as,
*samurai, otaku*.
: However, other nouns such as *kimonos*, *futons* and *tsunamis* are
more often seen with a regular English plural.
- In New Zealand English, nouns of Maori origin can either take an *s*
or have no separate plural form: as, *waka* makes *waka*; *marae,
marae; kohwai, kohwai or kohwais; tui, tuis or tui, kiwi, kiwi or
kiwis*.
- Nouns from languages that have donated few words to English, and
that are spoken by relatively few English-speakers, generally form
plurals as if they were native English words: *canoe* makes
*canoes*; *kayak, kayaks; igloo, igloos; kangoroo, kangoroos; sauna,
saunas; cwm, cwms; pizza, pizzas; kindergarten, kindergartens*.
: In Canada and Alaska, some words borrowed from Inuktitut retain
traditional plurals: *Inuk* makes *Inuit*; *inukshuk, inukshuit*.
- Some words of foreign origin are much better known in the plural. In
common usage, the proper plural is considered the singular form.
Back-formation has usually resulted in a regularized plural:
*candelabra* makes *candelabras*; *data, data; agenda, agendas or
agendae; graffiti, graffiti; insignia, insignias; algae, algae or
algaes; opera, operas; viscera, viscera; panini, paninis; phalanx,
phalanges; magazine, magazines*.
### Cases
Cases, in grammar, are modifications that distinguish the relations of
nouns or pronouns to other words.
There are three cases; the nominative, the possessive, and the
objective.
#### The nominative case
The nominative case is that form or state of a noun or pronoun, which
usually denotes the subject of a finite verb: as,
- \"The boy runs;\"
- \"I run.\"
The subject of a finite verb is that which answers to who or what before
it: as,
- \"The boy runs.\"
- Who runs? \"The boy.\"
Boy is therefore here a noun in the nominative case, or **nominative**.
For example:
- I eat an orange
- I buy a chocolate
- I love my family
- I love yellow
#### The possessive case
The possessive case is that form or state of a noun or pronoun, which
usually denotes the relation of property: as,
- \"My hat;\"
- \"The boy\'s hat.\"
Boy is here a noun in the possessive case, or **possessive**.
The possessive case of nouns is formed, in the singular number, by
adding to the nominative *s* preceded by an apostrophe; and, in the
plural, when the nominative ends in *s*, by adding an apostrophe only:
as, singular, boy\'s; plural, boys\'; sounded alike, but written
differently.
#### The objective case
The objective case is that form or state of a noun or pronoun which
usually tells the object of a verb, participle, or preposition: as,
- \"I know the boy, having seen him at school; and he knows me.\"
The object of a verb, participle, or preposition, is that which answers
to whom or what after it: as,
- \"I know the boy.\"
- I know whom? \"The boy.\"
Boy is therefore here a noun in the objective case, or **objective**.
The nominative and the objective of nouns, are always alike in form,
being distinguishable from each other only by their place in a sentence,
or by their simple dependence according to the sense.
For example:
- I am playing with my football.
- I take her bag.
- Anoud\'s room is dirty.
#### The declension of nouns
The declension of a noun is a regular arrangement of its numbers and
cases. Thus:
Sing. Nom. friend, Plur. Nom. friends,
Poss. friend's, Poss. friends',
Obj. friend; Obj. friends.
Sing. Nom. man, Plur. Nom. men,
Poss. man's, Poss. men's,
Obj. man; Obj. men.
Sing. Nom. fox, Plur. Nom. foxes,
Poss. fox's, Poss. foxes',
Obj. fox; Obj. foxes.
Sing. Nom. fly, Plur. Nom. flies,
Poss. fly's, Poss. flies',
Obj. fly; Obj. flies.
## The noun as a modifier
## A short syntax
The subject must be in the nominative case, as \"You say it.\"
The subject is placed before the attribute, as \"Peace dawned on his
mind,\" except the following cases: a question, as \"How many loaves
have you?\" imperative mood, as \"Go you,\" strong feeling, as \"May she
be happy!\" a supposition, as \"Were it true,\" *neither* or *nor*, as
\"Neither shall you touch it,\" emphasis, as \"Here am I,\" no regimen,
as \"Echo the mountains round,\" dialogue, as \"My name is Hassan,\" and
the adverb *there*, as \"There lived a man.\"
A noun in apposition is put in the same case as the noun it explains, as
\"But he, our gracious master, knows us.\"
A possessive is governed by the name of the thing possessed, as \"Man\'s
life.\"
A possessive comes immediately before the governing noun, as \"Nature\'s
peace,\" except the following cases: an intervening adjective, as
\"Flora\'s earliest smells,\" affirmation or denial, as \"The book is
not John\'s,\" a possessive without sign, as \"Brother Absalom\'s
house,\" or \"David and Jonathan\'s friendship.\"
The predicate is governed by attribute in objective case, as \"I found
her.\"
A noun or a pronoun put after a non-transitive verb or participle,
agrees in case with a preceding noun or pronoun referring to the same
thing, as \"The child was named John.\"
The case of absolute noun or pronoun depends on no other word, as \"Your
fathers, where are they?\"
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold
Brown, 1851.
- An English
Grammar
by W. M. Baskervill and
J. W. Sewell, 1895.
- The Wikipedia article on Collective
noun.
- The Wikipedia article on Count noun.
- The Wikipedia article on English
plural.
- The Wikipedia article on Mass noun.
- The Wikipedia article on Noun.
|
# English in Use/Pronouns
------------------------------------------------------------------------
A **pronoun** is a word used instead of a noun: as,
- \"The boy loves his book; he has long lessons, and he learns them
well.\"
Pronouns are not a requirement of a sentence, and it is possible for
them to never to be used in sentences. However, many sentences become
unwieldy without them:
- \"Alistair is doing what Alistair thinks is best according to
Alistair\'s rights as a human being.\"
- Better, \"Alistair is doing what he thinks is best according to his
rights as a human being.\"
The pronouns in English language are twenty-four; and their variations
are thirty-two: so that the number of words of this class, is fifty-six.
Pronouns are divided into three classes; personal, relative, and
interrogative.
Pronouns also change depending on whether they refer to one person or
thing (singular) or a group of people or things (plural).
## Personal pronouns
A personal pronoun or **personal** is a pronoun that shows, by its form,
of what person it is: as,
- \"Whether it were I or they, so we preach, and so you
believed.\"---1 Cor., xv, 11.
The simple personal pronouns are five: namely, *I*, of the first person;
*you (thou)*, of the second person; *he, she*, and *it*, of the third
person.
The compound personal pronouns are also five: namely, *myself*, of the
first person; *yourself (thyself)*, of the second person; *himself,
herself*, and *itself*, of the third person.
First person pronouns are used when referring to oneself:
- \"*I* think *I* am not silly.\"
Second person pronouns are used to refer to someone who you are
conversing with, the person the sentence is intended to be heard by:
- \"*You* are not very silly.\"
(\"*Thou* art not very silly.\")
Third person pronouns are used when referring to something else that is
outside the conversation, either some other person, or an object not
capable of understanding or communicating:
- \"I like the tree because *it* is beautiful.\"
- \"I don\'t like the RIAA because *they* sued me.\"
Third person singular pronouns are the only pronouns marked for gender.
If gender is unknown, use *he or she* or use a plural.
## Relative pronouns
A relative pronoun or **relative** is a pronoun that represents an
antecedent word or phrase, and connects different clauses of a sentence:
as,
- \"No people can be great, who have ceased to be virtuous.\"---Dr.
Johnson.
The relative pronouns are *who, which, what, that, as*, and the
compounds *whoever or whosoever, whichever or whichsoever, whatever or
whatsoever*.
*What* is a kind of double relative, equivalent to \"that which\" or
\"those which\"; and is to be parsed first as antecedent, and then as
relative: as,
- \"This is what I wanted; that is to say, the thing which I
wanted.\"---L. Murray. III.
## Interrogative pronouns
An interrogative pronoun or **interrogative** is a pronoun with which a
question is asked: as,
- \"Who touched my clothes?\"---Mark, v, 30.
The interrogative pronouns are *who, which*, and *what*; being the same
in form as relatives.
*Who* demands a person\'s name; *which*, that a person or thing be
distinguished from others; *what*, the name of a thing, or a person\'s
occupation and character.
Pronouns have the same modifications as nouns; namely, persons, numbers,
genders, and cases. Definitions universally applicable have already been
given of all these things; it is therefore unnecessary to define them
again in this place.
The declension of a pronoun is a regular arrangement of its numbers and
cases.
## Simple personals
The simple personal pronouns are thus declined:
I, of the first person, any of the genders.
Sing. Nom. I, Plur. Nom. we,
Poss. my, or mine, Poss. our, or ours,
Obj. me; Obj. us.
You, of the second person, any of the genders.
Nom. you,
Poss. your, or yours,
Obj. you.
He, of the third person, masculine gender.
Sing. Nom. he, Plur. Nom. they,
Poss. his, Poss. their, or theirs,
Obj. him; Obj. them.
She, of the third person, feminine gender.
Sing. Nom. she, Plur. Nom. they,
Poss. her, or hers, Poss. their, or theirs,
Obj. her; Obj. them.
It, of the third person, neuter gender.
Sing. Nom, it, Plur. Nom. they,
Poss. its, Poss. their, or theirs,
Obj. it; Obj. them.
## Compound personals
The word *self*, added to the simple personal pronouns, forms the class
of compound personal pronouns; which are used when an action reverts
upon the agent, and also when some persons are to be distinguished from
others. They all want the possessive case, and are alike in the
nominative and objective. Thus:
Myself, of the first person, any of the genders
Sing. Nom. myself, Plur. Nom. ourselves
Poss. ------, Poss. ---------,
Obj. myself; Obj. ourselves.
Yourself, of the second person, any of the genders.
Sing. Nom. yourself,
Poss. --------,
Obj. yourself.
Plur. Nom. yourselves,
Poss. ----------,
Obj. yourselves.
Himself, of the third person, masculine gender.
Sing. Nom. himself, Plur. Nom. themselves,
Poss. -------, Poss. ----------,
Obj. himself; Obj. themselves.
Herself, of the third person, feminine gender.
Sing. Nom. herself Plur. Nom. themselves,
Poss. -------, Poss. ----------,
Obj. herself; Obj. themselves.
Itself, of the third person, neuter gender.
Sing. Nom. itself, Plur. Nom. themselves,
Poss. ------, Poss. ----------,
Obj. itself; Obj. themselves.
## Relatives and interrogatives
The relative and the interrogative pronouns are thus declined:
Who, literally applied to persons only.
Sing. Nom. who, Plur. Nom. who,
Poss. whose, Poss. whose,
Obj. whom; Obj. whom.
Which, applied to animals and things.
Sing. Nom. which, Plur. Nom. which,
Poss. ----, Poss. -----,
Obj. which; Obj. which.
What, applied ordinarily to things only.
Sing. Nom. what, Plur. Nom. what,
Poss. ----, Poss. ----,
Obj. what; Obj. what.
That, applied to persons, animals, and things.
Sing. Nom. that, Plur. Nom. that,
Poss. ----, Poss. ----,
Obj. that; Obj. that.
As, applied to persons, animals, and things.
Sing. Nom. as, Plur. Nom. as,
Poss. ----, Poss. ----,
Obj. as; Obj. as.
## Compound relatives
The compound relative pronouns, *whoever or whosoever, whichever or
whichsoever*, and *whatever or whatsoever* are declined in the same
manner as the simples. Thus:
Whoever or whosoever, applied only to persons.
Sing. Nom. whoever, Plur. Nom. whoever,
Poss.whosever, Poss. whosever,
Obj. whomever; Obj. whomever.
Sing. Nom. whosoever, Plur. Nom. whosoever,
Poss. whosesoever, Poss. whosesoever,
Obj. whomsoever; Obj. whomsoever.
Whichever or whichsoever, applied to persons,
animals, and things.
Sing. Nom. whichever, Plur. Nom. whichever,
Poss. ---------, Poss. --------,
Obj. whichever; Obj. whichever.
Sing. Nom. whichsoever, Plur. Nom. whichsoever,
Poss. ---------, Poss. --------,
Obj. whichsoever; Obj. whichsoever.
Whatever or whatsoever, applied ordinarily to things only.
Sing. Nom. whatever, Plur. Nom. whatever,
Poss. --------, Poss. --------,
Obj. whatever; Obj. whatever.
Sing. Nom. whatsoever, Plur. Nom. whatsoever,
Poss. ---------, Poss. --------,
Obj. whatsoever; Obj. whatsoever.
## Unclear Usage of Pronouns
Although helpful to eliminate repetitiveness of nouns, pronouns, when
used too much, can make a sentence extremely vague: as,
- \"Pictures on walls make *it* look pretty.\"
The reader does not know what *it* is.
- \"The teachers prepared the food. The students ate it. *They* had
fun.\"
The reader does not know who *they* are.
## Y\'all
The pronoun *y\'all* is a contraction of \"You all\". It is
traditionally used in the south of the United States, where in the north
you all is more common. *Y\'all* follows the same conjugation rules as
*they*. Very often it is incorrectly spelled *ya\'ll*.
## A short syntax
A pronoun must agree with its antecedent, as \"This is the book; it is
excellent,\" except the following cases: something indefinite, as \"Tell
me who it was,\" a neuter pronoun, as \"I cannot view it,\" the pronoun
*it*, as \"It is not for kings,\" the adjective *many*, as \"Many a
great genius, they have no friends,\" enallage, as \"We shall close our
remarks,\" another sense, as \"Lamps is of the plural number,\"
nominatives, as \"Who are you?\", absolute nominatives, as \"It need not
be any wonder,\" possessives, as \"Him whose yoke is easy,\" objectives,
as \"Those whom she persuaded,\" neuter verbs, as \"Whom did you suppose
me to be?\", familiar language, as \"The man \[whom\] I trust,\"
omission of the relative, as \"The worst thing \[that\] could happen,\"
a collective noun, as \"The council were divided,\" the conjunction
*or*, as \"James or John will favour us with his company,\" the
conjunction *and*, as \"Saul and Jonathan were pleasant in their
lives,\" one person or thing, as \"This great philosopher and
statesman,\" empathy, as \"The good man, and the sinner too, shall have
his reward,\" and *each*, *every*, or *no*, as \"Every plant and every
tree produces others after its kind.\"
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
## See also
- The Wikipedia article on Ain\'t
- The Wikipedia article on Generic you
- The Wikipedia article on Personal
pronouns
- The Wikipedia article on Possessive
pronouns
- The Wikipedia article on Relative
pronouns
- The Wikipedia article on Singular they
- The Wikipedia article on Y\'all
- The Wikipedia article on You
- The Wikipedia article on Who "wikilink")
de:Englisch: Pronomina
fr:Anglais:Pronoms
|
# English in Use/Adjectives
------------------------------------------------------------------------
An **adjective** is a word added to a noun or pronoun, and generally
expresses quality: as, A wise man; a new book; you two are diligent.
Adjectives may be divided into six classes; namely, common, proper,
numeral, pronominal, participial, and compound.
A **common** adjective is any ordinary epithet, or adjective denoting
quality or situation: as, *good, bad, peaceful, warlike, eastern,
western, outer, inner*.
A **proper** adjective is an adjective formed from a proper name: as,
*American, English, Platonic, Genoese*.
A **numeral** adjective is an adjective that expresses a definite
number: as, *one, two, three, four, five, six*, etc.
A **pronominal** adjective is a definitive word which may either
accompany its noun, or represent it understood: as,
- \"All join to guard what each desires to gain.\"---Pope.
That is,
- \"All men join to guard what each man desires to gain.\"
A **participial** adjective is one that has the form of a participle,
but differs from it by rejecting the idea of time: as,
- \"An amusing story,\"
- \"A lying divination.\"
A **compound** adjective is one that consists of two or more words
joined together, either by the hyphen or solidly: as, *nut-brown,
laughter-loving, four-footed; threefold, lordlike, lovesick*.
**Cardinal**: *one, two, three, four, five, six, seven, eight, nine,
ten, eleven, twelve, thirteen, fourteen, fifteen, sixteen, seventeen,
eighteen, nineteen, twenty, twenty-one, twenty-two*, etc.
**Ordinal**: *first, second, third, fourth, fifth, sixth, seventh,
eighth, ninth, tenth, eleventh, twelfth, thirteenth, fourteenth,
fifteenth, sixteenth, seventeenth, eighteenth, nineteenth, twentieth,
twenty-first, twenty-second*, etc.
**Multiplicative**: *single or alone, double or twofold, triple or
threefold, quadruple or fourfold, quintuple or fivefold, sextuple or
sixfold, septuple or sevenfold, octuple or eightfold*, etc.
All that occur above decuple or tenfold, are written with a hyphen, and
are usually of round numbers only: as, *thirty-fold, sixty-fold,
hundred-fold*.
## Adjectives ending in ing and ed
## Adjectives word order
In English, multiple adjectives should follow a certain pattern as
follows:
1. opinion (e.g. lovely, fantastic)
2. size (e.g. tiny, large)
3. most other qualities (e.g. warm, tight)
4. age (e.g. new, young)
5. colour (e.g. red, beige)
6. pattern (e.g. stripy, plain)
7. nationality (e.g. Spanish, foreign)
8. material (e.g. silk, cotton)
Although you generally shouldn\'t use more than 2 or 3 adjectives
together it is possible to make a sentence like this:
- \"I just bought a lovely, large, warm, new, red, stripey, foreign,
cotton sweater.\"
## Modifications
Adjectives have, commonly, no modifications but the forms of comparison.
Comparison is a variation of the adjective, to express quality in
different degrees: as, *hard, harder, hardest; soft, softer, softest*.
There are three degrees of comparison; the positive, the comparative,
and the superlative.
The *\'positive degree* is that which is expressed by the adjective in
its simple form: as,
- \"An elephant is large; a mouse, small; a lion, fierce, active,
bold, and strong.\"
The **comparative degree** is that which is more or less than something
contrasted with it: as,
- \"A whale is larger than an elephant; a mouse is a much smaller
animal than a rat.\"
The **superlative degree** is that which is most or least of all
included with it: as,
- \"The whale is the largest of the animals that inhabit this globe;
the mouse is the smallest of all beasts.\"---Dr. Johnson.
Those adjectives whose signification does not admit of different
degrees, cannot be compared: as, *two, second, all, every, immortal,
infinite*.
Those adjectives which may be varied in sense, but not in form, are
compared by means of adverbs: as, *fruitful, more fruitful, most
fruitful; fruitful, less fruitful, least fruitful*.
## Regular comparison
Adjectives are regularly compared, when the comparative degree is
expressed by adding *er*, and the superlative, by adding *est* to them:
as, *great, greater, greatest; mild, milder, mildest*.
In the variation of adjectives, final consonants are doubled, final *e*
is omitted, and final *y* is changed to *i*, agreeably to the rules for
spelling: as, *hot, hotter, hottest; wide, wider, widest; happy,
happier, happiest*.
The regular method of comparison belongs almost exclusively to
monosyllables, with dissyllables ending in *w* or *y*, and such others
as receive it and still have but one syllable after the accent: as,
*fierce, fiercer, fiercest; narrow, narrower, narrowest; gloomy,
gloomier, gloomiest; serene, serener, serenest; noble, nobler, noblest;
gentle, gentler, gentlest*.
## Comparison by adverbs
The two degrees of superiority may also be expressed with precisely the
same import as above, by prefixing to the adjective the adverbs *more*
and *most*: as, *wise, more wise, most wise; famous, more famous, most
famous; amiable, more amiable, most amiable*.
The degrees of inferiority are expressed, in like manner, by the adverbs
*less* and *least*: as, *wise, less wise, least wise; famous, less
famous, least famous; amiable, less amiable, least amiable*. The regular
method of comparison has, properly speaking, no degrees of this kind.
Nearly all adjectives that admit of different degrees, may be compared
by means of the adverbs; but, for short words, the regular method is
generally preferable: as, *quick, quicker, quickest*; rather than,
*quick, more quick, most quick*.
## Irregular comparison
The following adjectives are compared irregularly: *good, better, best;
bad, evil, or ill, worse, worst; little, less, least; much, more, most;
many, more, most*.
## A short syntax
Adjectives relate to nouns or pronouns, as \"Worldly enjoyments,\"
except the following cases: an intervening verb, as \"To err is human,\"
arithmetical numbers, as \"Four hundred and fifty-six men,\" an abstract
adjective, as \"Being sublime,\" and an adjective as abstract noun, as
\"Sensations of sublime.\"
An adjective is placed immediately before noun, as \"Vain man,\" except
the following cases: pronouns, as \"They left me weary,\" other words,
as \"A mind conscious of right,\" an action, as \"Virtue renders life
happy,\" admiration, as \"Goodness infinite,\" a verb, as \"Truth stands
independent,\" a prefix *a*, as afraid, the nature of a participle, as
\"The time then present,\" poetry, as \"Isles atlantic,\" technical
usage, as \"Notary public,\" an adjective, as \"A being infinitely
wise,\" several adjectives, as \"A woman, modest, sensible, and
virtuous,\" empathy, as \"Weighty is the anger,\" an adjective in
predicate, as \"We call the boy good,\" and an adjective as adverb, as
\"Particularly\".
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
## See also
- The Wikipedia article on Adjective
fr:Enseignement de
l\'anglais/Adjectifs
|
# English in Use/Adverbs
------------------------------------------------------------------------
An **adverb** is a word added to a verb, a participle, an adjective, or
another adverb; and generally expresses time, place, degree, or manner:
as,
- \"They are now here, studying very diligently.\"
Adverbs can modify a verb, a clause, adjective or a phrase.
## Form
Adjectives are generally turned into adverbs with the addition of a *ly*
suffix. *Ly* is a contraction of like, and is the most common
termination of adverbs. When added to nouns, it forms adjectives; but a
few of these are also used adverbially: as, *daily, weekly, monthly*.
Examples of adverbs are:
- \"Jack is swimming *quickly*.\"
- \"*Unfortunately*, he lost the race.\"
- \"We told him to run *much* faster.\"
In the first sentence, the adverb modifies the verb swimming. The
adjective *quick* has had a *ly* added to it to make an adverb. In the
second sentence, it modifies the entire sentence and in the final
example, the adverb *much* modifies the adverb *faster*.
## Comparative forms of adverbs
Adverbs have no modifications, except that a few are compared, after the
manner of adjectives: as, *soon, sooner, soonest; long, longer, longest;
fast, faster, fastest*.
The following are irregularly compared: *well, better, best; badly or
ill, worse, worst; little, less, least; much, more, most; far, farther,
farthest; forth, further, furthest*.
## Kinds of adverbs
Adverbs may be reduced to four general classes; namely, adverbs of time,
of place, of degree, and of manner. Besides these, it is proper to
distinguish the particular class of conjunctive adverbs.
### Adverbs of time
Adverbs of time are those which answer to the question, when? how long?
how soon? or how often?
Of time **present**: as, *now, yet, today, nowadays, presently,
instantly, immediately, straightway, directly, forthwith*.
Of time **past**: as, *already, just now, lately, recently, yesterday,
formerly, anciently, once, heretofore, hitherto, since, till now, long
ago, erewhile, erst*.
Of time **to come**: as, *tomorrow, hereafter, henceforth, henceforward,
by-and-by, soon, erelong, shortly*.
Of time **relative**: as, *when, then, first, just, before, after,
while, whilst, meanwhile, as, till, until, seasonably, betimes, early,
late, whenever, afterward, afterwards, otherwhile, otherwhiles*.
Of time **absolute**: as, *always, ever, never, aye, eternally, forever,
perpetually, continually, incessantly, endlessly, evermore,
everlastingly*.
Of time **repeated**: as, *often, oft, again, occasionally, frequently,
sometimes, seldom, rarely, daily, weekly, monthly, yearly, annually,
once, twice, thrice, or three times*.
Above thrice, we use only the phrases four times, five times, six times,
etc. Times, for repetitions, or instances, may be supposed a noun; but
such phrases often appear to be used adverbially.
### Adverbs of degree
Adverbs of degree are those which answer to the question, how much? how
little? or to the idea of more or less.
Of **excess** or abundance: as, *much, more, most, too, very, greatly,
far, besides; chiefly, principally, mainly, mostly, generally; entirely,
full, fully, completely, perfectly, wholly, totally, altogether, all,
quite, clear, stark; exceedingly, excessively, extravagantly,
intolerably; immeasurably, inconceivably, infinitely*.
Of equality or **sufficiency**: as, *enough, sufficiently, competently,
adequately, proportionally, equally, so, as, even, just, exactly,
precisely*.
Of **deficiency** or abatement: as, *little, less, least, scarcely,
hardly, scantly, scantily merely, barely, only, but, partly, partially,
nearly, almost, well-nigh, not quite*.
Of quantity in the **abstract**: as, *how, however, howsoever, everso,
something, anything, nothing, a groat, a sixpence*, and other nouns of
quantity used adverbially.
### Adverbs of manner
Adverbs of manner are those which answer to the question, how? or, by
affirming, denying, or doubting, show how a subject is regarded.
Of manner from **quality**: as, *well, ill, wisely, foolishly, justly,
wickedly*, and many others formed by adding *ly* to adjectives of
quality.
Of affirmation or **assent**: as, *yes, yea, ay, verily, truly, indeed,
surely, certainly, doubtless, undoubtedly, assuredly, certes, forsooth,
amen*.
Of **negation**: as, *no, nay, not, nowise, noway, noways, nohow*.
Of doubt or **uncertainty**: as, *perhaps, haply, possibly, perchance,
peradventure, maybe*.
Of **mode** or way: as, *thus, so, how, somehow, nohow, anyhow, however,
howsoever, like, else, otherwise, across, together, apart, asunder,
namely, particularly, necessarily, hesitatingly, trippingly, extempore,
headlong, lengthwise*.
### Adverbs of place
Of place **in** which: as, *where, here, there, yonder, above, below,
about, around, somewhere, anywhere, elsewhere, otherwhere, everywhere,
nowhere, wherever, wheresoever, within, without, whereabout,
whereabouts, hereabout, hereabouts, thereabout, thereabouts*.
Of place **to** which: as, *whither, hither, thither, in, up, down,
back, forth, aside, ashore, abroad, aloft, home, homewards, inwards,
upwards, downwards, backwards, forwards*.
Of place **from** which: as, *whence, hence, thence, away, out, off,
far, remotely*.
Of the **order** of place: as, *first, secondly, thirdly, fourthly*,
etc.
Thus, secondly means in the second place; *thirdly, in the third place*;
etc.
### Conjunctive adverbs
The conjunctive adverbs are those which perform the office of
conjunctions. The following words are the most frequently used as
conjunctive adverbs: *after, again, also, as, before, besides,
consequently, else, ere, even, furthermore, hence, how, however,
moreover, nevertheless, as well, otherwise, since, so, still, till,
then, thence, therefore, too, until, when, where, wherefore, whither,
while*.
The **adverbs of cause**: *why, wherefore, therefore*; but the last two
of these are often called conjunctions.
The **pronominal compounds**: *herein, therein, wherein*, etc.
## A short syntax
Adverbs relate to verbs, participles, adjectives, or other adverbs: as,
\"How blessed,\" except the following cases: independent adverbs, as
\"No,\" the word *amen*, as \"These things say the amen,\" an adverb
before preposition, as \"All along\", and *much*, *little*, *far*, and
*all*, as \"Thus far is right.\"
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
- The Wikipedia article on Adverb
|
# English in Use/Prepositions, Conjunctions, and Interjections
------------------------------------------------------------------------
## Preposition
A **preposition** is a word used to express some relation of different
things or thoughts to each other, and is generally placed before a noun
or a pronoun: as,
- \"The paper lies before me on the desk.\"
In that sentence, *before* is the preposition, *me* is the **governed
term** of a preposition, \"before me\" is a **prepositional phrase**,
and the verb *lies* is the **prior term** of a preposition. \"On the
desk\" is the other prepositional phrase, and *lies* is its prior term.
To a preposition, the prior term may be a noun, an adjective, a pronoun,
a verb, a participle, or an adverb; and the governed term may be a noun,
a pronoun, a pronominal adjective, an infinitive verb, or a participle.
Although overlooked in common speech, prepositional phrases should not
be placed at the end of a question: as,
- \"Who do I give this *to*?\"
- Say, \"*To whom* do I give this?\"
Prepositional phrases can be placed at the end of a sentence: as,
- \"She did not sign up *for tennis*.\"
**See also:** List of English
prepositions
Some words are linked with their prepositions, e.g. *compared* *with*,
*similar* *to*, and *different* *from* (possibly *different* *than* in
USA).
Commonly used prepositions include:
- **About**---In concern with; engaged in; intent on; on the point or
verge of; in act of; concerning; with regard to; on account of.
- **Above**---In or to a higher place; on or over; superior to;
surpassing; beyond; higher in measure or degree.
- **Across**---From side to side; athwart; crosswise; quite over.
- **After**---Behind in place; below in rank; later in time;
subsequent to; following; in search of; in pursuit of; concerning;
in relation to; in imitation of; in conformity with; after the
manner of; according to; in accordance with; in proportion to.
- **Against**---Abreast; opposite to; facing; towards; in opposition
to; counter to; in contrariety to; adverse to; by of before the
time; in preparation for.
- **Along**---By the length.
- **Amid(st)**---In the midst or middle of; surrounded or encompassed
by; among.
- **Among**---Conjoined; associated with; making part of.
- **Around**---On all sides of; encircling; encompassing; at random
through; about; on another side of.
- **As**---Similar of like. It can be used as conjunction and
preposition.
- **At**---Expresses the relations of presence, proximity to, nearness
in place or time, age or order, state or condition, employment or
action, point or position, rate or value, source, occasion, reason,
consequence or effect, direction toward an object or end; occupied
with.
- **Before**---In front of; preceding in space, order, rank, right,
worth, or time; ahead of; earlier than; previously to; anterior to;
an advance of; farther onward; in presence or sight of; face to face
with; under the jurisdiction of; open for; free of access to; in the
power of.
- **Behind**---At the back part; in the rear; toward the back part or
rear; backward; out of sight; remaining.
- **Below**---Under, or lower in place; beneath; inferior to; unworthy
of; unbefitting.
- **Beneath**---Lower in place; under; underneath; lower in rank,
dignity, or excellence.
- **Beside(s)**---Over and above; separate or distinct from; in
addition to; other than; else than.
- **Between**---In the space which separates; betwixt; from one place
to another; shared by both; affecting mutual relation; with relation
to two.
- **Beyond**---On the further side of; further on or away than; at a
place or time not yet reached; out of the reach or sphere of;
further than; greater than; exceeding or surpassing.
- **During**---In the time of; as long as the action or existence of.
- **Except**---With exclusion of; leaving or left out; excepting.
- **For**---In consideration of; in view of; with reference to; the
cause, occasion, motive or inducement of; the reason of; in favor
of; in promoting which; on account of which; indicating the object
of an act; toward which; in the character of; instead of which;
during; in or through the space or time of; in prevention of which.
- **From**---Lessening or losing proximity to; leaving behind; by
reason of; out of; by aid of; indicates the point of space or time
at which the action or state is regarded as setting out or
beginning; the source; the cause; the correlative of to.
- **In**---With reference to space or place, circumstances or
conditions, a whole, physical surrounding, personal states, reach,
scope, movement or tendency, limit of time.
- **Into**---To the inside of; expressing penetration beyond the
outside or surface; indicating insertion, inclusion, or passing to
another form or condition.
- **Like**---Similar of as. It can be used as conjunction and
preposition.
- **Of**---Out from; proceeding from; belonging to; relating to;
concerning; about; belonging to; connected with; indicating origin,
source, descent, possession or ownership, relation of subject to
attribute, material, part, source of a purpose or action, distance
in space or time, identity or equivalence, agent, or passage from
one state to another.
- **Off**---Not on; away from.
- **On**---At, to or against the surface; by means of; with; adjacent
to; in addition to; besides; indicating dependence or reliance; at
or in the time of; during; in consequence of; toward; for; at the
peril of; for the safety of; by virtue of; with the pledge of; to
the account of; in reference or relation to; occupied with; in the
performance of; in the service of; connected with; of the number of;
forward; onward; in continuance; without interruption or ceasing;
adhering; not off; attached to the body; in progress; proceeding.
- **Over**---Above, or higher than; across; from side to side of; on
the whole surface of; throughout the whole extent of; superiority in
excellence, dignity, condition, value or authority; across or during
the time of; from beginning to end of; beyond; in excess of; in
addition to; more than; across; crosswise.
- **Past**---Beyond, in position, degree or time; further than; beyond
the reach or influence of; above; exceeding; more than; by.
- **Through**---From one end to the opposite; between the sides or
walls of; by means of; by the agency of; over the whole extent of;
among or in the midst of; to the end; to a conclusion; to the
ultimate purpose.
- **To**---Indicates motion, course, or tendency toward a limit;
connects adjectives, nouns and verbs with their governed terms and
contains less the idea of appropriation than for; a sign of the
infinitive; extent; limit; degree of comprehension; inclusion as far
as; effect; end; consequence; apposition; connection; antithesis;
opposition; accord; adaptation; comparison; addition; union;
accompaniment; character; condition of being.
- **Toward(s)**---In the direction of; with respect or reference to;
regarding; concerning; tending to; in behalf of; near; about;
approaching to.
- **Under**---Below or lower; lower than; beneath; denoting relation
to some thing, condition or person that is superior, or to something
that comprehends, includes or furnishes a cover.
- **Underneath**---Under; beneath; below.
- **Until**---To; unto; towards; up to; till; before.
- **With**---Denotes relation of nearness, proximity, association,
connection, opposition or hostility, connection of friendship,
support, alliance, assistance, countenance, accomplishment of cause,
means, instrument, simultaneous happening, immediate succession,
consequence, possession or appendage; among; in the company of.
- **Without**---On or at the outside of; out of; not within; out of
the limits of; out of reach of; in absence of, separation from, or
destitution of; not with use or employment of; independently of;
exclusively of; with omission; unless; except.
### A short syntax
A noun or a pronoun made the object of a preposition, is governed by it
in the objective case, as \"From whom.\"
Prepositions show the relations of words, and of the things or thoughts
expressed by them, as \"He came from Rome,\" except the following cases:
the preposition *to*, as \"To learn to die,\" and the preposition *for*,
as \"For us to learn.\"
## Conjunction
A **conjunction** is a word used to connect words or sentences in
construction, and to show the dependence of the terms so connected: as,
- \"You and he are happy, because you are good.\"---Murray.
Conjunctions are divided into two general classes, copulative and
disjunctive; and a few of each class are particularly distinguished from
the rest, as being corresponsive.
A **copulative** conjunction is a conjunction that denotes an addition,
a cause, a consequence, or a supposition: as,
- \"He and I shall not dispute; for, if he has any choice, I shall
readily grant it.\"
The copulatives: *and, as, both, because, even, for, if, that, then,
since, seeing, so*.
A **disjunctive** conjunction is a conjunction that denotes opposition
of meaning: as,
- \"Though he were dead, yet shall he live.\"---St. John\'s Gospel.
- \"Be not faithless, but believing.\"---Id.
The disjunctives: *or, nor, either, neither, than, though, although,
yet, but, except, whether, lest, unless, save, provided,
notwithstanding, whereas*.
The **corresponsive** conjunctions are those which are used in pairs, so
that one refers or answers to the other: as,
- \"John came neither eating nor drinking.\"---Matt., xi, 18.
- \"But if I cast out devils by the spirit of God, then the kingdom of
God is come to you.\"---Ib., xii, 28.
The corresponsives: *both, and; as, as; as, so; if, then; either, or;
neither, nor; whether, or; though, yet; although, yet*.
### A short syntax
Conjunctions connect words, sentences, or parts of sentences, as
\"Between me and you,\" except the following cases: introducing a
sentence, as \"That you have wronged me,\" corresponding conjunctions,
as \"Neither sun nor stars,\" and *either* and *neither*, as \"It is not
dangerous neither.\"
## Interjection
An **interjection** is a word that is uttered to indicate a strong or
sudden emotion. The following are the principal interjections, arranged
according to the emotions which they are intended to indicate:
- Of joy; yoo! hey! oi! yeah!
- Of sorrow; oh! ah! hoo! alas! alack! lackaday! welladay! or welaway!
- Of wonder; gotit! ha! strange! indeed!
- Of wishing, earnestness, or vocative address; (often with a noun or
pronoun in the nominative absolute;) O!
- Of praise; well-done! good! bravo!
- Of surprise with disapproval; whew! hoity-toity! really! no-way!
what!
- Of pain or fear; oh! ooh! ah! eh! O dear! Oh, no!
- Of contempt; fudge! pugh! poh! pshaw! pish! tush! tut! humph! fine!
- Of aversion; foh! faugh! fie! fy! foy!
- Of expulsion; out! off! shoo! whew! begone! avaunt! aroynt!
- Of calling aloud; oi! yo! dude! hollo! holla! hallo! halloo! hoy!
ahoy! hey!
- Of exultation; ah! aha! hazza! hey! heyday! harrah!
- Of laughter; ha, ha, ha; he, he, he; te-hee, te-hee.(lol)
- Of salutation; welcome! hail! all-hail!
- Of calling to attention; ho! lo! la! law! look! see! behold! hark!
- Of calling to silence; hush! hist! whist! \'st! aw! pst! shhh! zip
it!
- Of dread or horror; oh! ha! hah! what!
- Of languor or weariness; heigh-ho! heigh-ho-hum!
- Of stopping; hold! soft! avast! whoh! halt! stop! hold-on! calm!
- Of parting; farewell! adieu! good-bye! good-day! see ya!
- Of knowing or detecting; oho! ahah! ay-ay!
- Of interrogating; eh? ha? hey? no?
### A short syntax
Interjections are put absolute, either alone, or with other words, as
\"Ah Dennis!\"
## References
- A part of the text in this article was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
- The Public Domain portion of \"The Gutenberg Webster\'s Unabridged
Dictionary\"
|
# English in Use/Verbals
## Overview
## Infinitives
See the verbs infinitive mood.
### A short syntax
An infinitive can be joined to every part of speech: a noun, as \"Obtain
felicity,\" an adjective, as \"Desirous to speak,\" a pronoun, as \"What
to accuse,\" a finite verb, as \"Come to seek,\" an infinitive, as \"To
wait to consider,\" a participle, as \"Bent to unhoard,\" an adverb, as
\"How to act,\" a conjunction, as \"More than praise it,\" a
preposition, as \"About to write,\" and an interjection, as \"O to
forget her!\".
An infinitive may stand for the following: a supplement to verb, as \"Go
to seek,\" purpose, as \"Labour not to be rich,\" an object of passion,
as \"He loves to ride,\" a cause of passion, as \"I rejoice to hear
it,\" the subject of proposition, as \"To steal is sinful,\" the object
of proposition, as \"To enjoy is to obey,\" a coming event, as \"Things
to come,\" a necessary event, as \"It is to be remembered,\" something
previously suggested, as \"The gift to know it,\" and measure, as
\"Enough to show.\"
## Gerunds
Gerunds are nouns built from a verb with an *ing* suffix. They can be
used as the subject of a sentence, an object, or an object of
preposition. They can also be used to complement a subject. Often,
gerunds exist side-by-side with nouns that come from the same root but
the gerund and the common noun have different shades of meaning.
Examples: breath and *breathing*, knowledge and *knowing*. Yet,
distinguishing between a gerund, and a verb can sometimes cause trouble.
For example:
- \"*Swimming* has to be the best sport ever.\" (*Swimming* is
gerund.)
- \"I went swimming today.\" (Not a Gerund, because it is not an
idea.)
Examples of gerunds as the subject of a sentence are:
- \"*Backpacking* is a rewarding pastime.\"
- \"*Stretching* can loosen up muscles.\"
- \"No *smoking*.\" (I.e., no smoking is allowed / you may not smoke
here.)
As an object:
- \"We all love to go *bowling* on the weekend.\"
- \"He loves *eating* chips.\"
An object of preposition:
- \"They complained of *hearing* strange sounds from the next cabin.\"
- \"They sang about *being* eaten by bears to allay their fears.\"
And as a complement to a subject:
- \"One of the most dangerous things to do on the lake is
*ice-skating*.\"
## Participles
**Participles** are forms of verbs which are used as adjectives. A
participle is a word derived from a verb, participating the properties
of a verb, and of an adjective or a noun; and is generally formed by
adding *ing*, *d*, or *ed*, to the verb: thus, from the verb rule, are
formed three participles, two simple and one compound; as, *ruling,
ruled, having ruled*.
English verbs, not defective, have severally three participles; which
have been very variously denominated, perhaps the most accurately thus:
the present, the past, and the past perfect. Or, as their order is
undisputed, they may be conveniently called the first, the second, and
the third.
The **present participle** is that which ends commonly in *ing*, and
implies a continuance of the being, action, or passion: as, *being,
acting, ruling, loving, defending, terminating*. Therefore:
- *Talk* becomes *talking*
- *Jump* becomes *jumping*
- *Open* becomes *opening*
- *See* becomes *seeing*
The present participle, when simple, is always formed by adding *ing*,
or it is formed by prefixing being to some other simple participle; as,
*being reading, being read, being completed*.
The **past participle** is that which ends commonly in *ed* or *en*, and
implies a completion of the being, action, or passion: as, *been, acted,
ruled, loved, defended, terminated*. Therefore:
- *Talk* becomes *talked*
- *Jump* becomes *jumped*
- *Open* becomes *opened*
- However, *See* becomes *seen*
The past participle is always simple, and is regularly formed by adding
*d* or *ed* to the radical verb: those verbs from which it is formed
otherwise, are either irregular or redundant.
The irregular verb *see* also did not have a regular past participle. As
with most irregular words, there is no good \"general rule\" which
applies, but often *ed* is replaced by \'en\'. More irregular verbs with
irregular past participles are:
- *Be*, *been*
- *Break*, *broken*
- *Eat*, *eaten*
- *Slide*, *slid*
The **past perfect participle** is that which takes the sign having, and
implies a previous completion of the being, action, or passion: as,
*having loved, having seen, having written; having been loved, having
been writing, having been written*.
The past perfect participle is always compound, and is formed by
prefixing having to the past participle, when the compound is double,
and having been to the past or the present participle, when the compound
is triple: as, having spoken, having been spoken, having been speaking.
### A short syntax
Participles relate to nouns or pronouns, as \"Reading Plato,\" except
the following cases: the preceding phrase, as \"To leave them, appearing
a duty,\" an abstract action or being, as \"To seem compelled, is
disagreeable,\" substitute for infinitive, as \"Afraid of trying,\" and
substitute for a noun, as \"This is talking.\"
## Examples
- He is **talking** to her.
- They are **jumping** into the pool.
- We had **eaten** the pie.
Each of these cases has a verb acting as an adjective, describing the
subject.
In case you were wondering, *had* plus a past participle is called a
**past perfect**, or in the United Kingdom, the **pluperfect**.
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
|
# English in Use/Sentences Overview
This section will serve as a basic overview of sentences. Each topic
will be discussed in more detail in subsequent chapters.
### Phrases
A **phrase** is a group of words which contains neither a subject nor a
verb. (It may, however, contain a verbal form such as an infinitive, a
participle, or a
gerund.)1
### Clauses
A **clause** is a group of words containing at least a subject and a
verb (the baby ate), and frequently it lets its hair down by containing
some kind of a complement as well (the baby ate the goldfish). There are
two kinds of clauses: independent and
dependent.2
## Forms
There are three forms of a sentence: simple, compound, and complex, and
one combined form: compound-complex.
### Simple
### Compound
### Complex
### Compound-complex
It is a sentence which is made to by joining two or more simple
sentences.
## Purposes
Sentences are created for four main reasons: to declare, to command, to
question, and to exclaim.
### Declarative
### Imperative
### Interrogative
### Exclamatory
## Sentence diagrams
|
# English in Use/Clauses
Clause can be defined as a group of words that carries a finite verb but
do not act as a sentence. It acts like a part of a sentence that can not
express its meaning without being depended on the other part. as in
\'Rahul, who lives in London, is my friend. In the above sentence \'who
lives in London\' is the part that has to be depended on the part
\"Rahul is my friend\' to expresses its proper meaning. Clauses can be
divided into two parts;
1. Principal Clause
2. Sub-ordinate Clause
Sub-Ordinate Clauses are divided into three parts:
1. Noun Clause
2. Adjective Clause
3. Adverb Clause
|
# English in Use/Adjective and Adverb Usage
An adjective is simply a word which modifies the noun it is related to.
Adjectives usually come before the modified noun. An adjective could
also be a phrase or a clause instead of being a single word. John bought
a *blue* shirt. (single word) Last night, a man *in a blue coat* stole
my wallet. (phrase) I love the car *which just crossed the street*.
(clause)
Adverbs are like adjectives, but they modify the verb. Ordinarily, there
are three types of adverbs (see above examples).
He *carefully* left the room. He left the room *with a scared face*. He
left the room *which was located on the seventh floor.*
Most single word adverbs are made simply by adding -ly to the end of the
respective adjective: Careful-ly = in a careful manner Usually = in a
usual manner (often) Simply = in a simple way
|
# English in Use/Pronoun Usage
Pronoun Usage
A pronoun comes from a Latin word that means \'for a noun\'. It is a
word that stands in for a noun. The English language has lots of
different kinds of pronouns.
Pronouns are often divided into first, second and third person, singular
and plural. First person refers to the speaker, second person refers to
the person or thing being spoken to, and third person refers to a person
or thing neither speaking nor being spoken to.
The first person pronoun (referring to the speaker) is \'I\' or \'me\'
in the singular, and \'we\' or \'us\' in the plural. The first of each
set, \"I/we\", is used as the subject of a verb; the second, \'me/us\',
is used as the object of a verb or preposition. There are also reflexive
pronouns which can be made (i.e. they are the same person as the
subject) by adding the suffix \'-self\' to the possessive
(myself/ourselves).
The second person pronoun (referring to the person being spoken to) is
\'you\' in singular and plural, as subject or object. The reflexive is
\"yourself\" in the singular and \"yourselves\" in the plural.
|
# English in Use/Subject-verb Agreement
English features a loose conjugation and declension pattern. For this
reason, subject-verb agreement is of paramount importance.
Subject-Verb agreement is a rule which states that the number present in
a noun must agree with the number shown in the conjugated form of the
verb that is being used, and that the person of the noun must agree with
the person of the conjugated form of the verb that you are using.
Proper Subject-Verb agreement:
- **TO BE**: I am - you are - he is - we are - you are - they are
- **TO WORK**: I work - you work - he works - we work - you work -
they work
Where the subject is a pronoun or complex or modified as part of an
adjectival phrase, or modified by parenthetic expressions, or clarified
in meaning by common knowledge or something that occurs later in the
sentence, then subject-verb agreement can become a little more
complicated. Some grammar rules say that the complex part of the subject
closest to verb in the sentence should determine the verbal agreement.
However, many examples can be found that make this sound funny. A better
rule is to consider the entire complex subject phrase as one subject,
and then think about what kind of thing it represents.
The basic idea in idiomatic English is to make the verb agree with the
idea that the subject REPRESENTS, which could have different plurality
than the actual subject as a word. This is actually helpful in
understanding meaning since it gives subject-verb agreement a role that
is not simply redundant (in echoing the pluarity of the subject).
Whatever the subject represents can be considered singular or plural,
and that is what the verb should agree with.
- The president and the children (plural) are at the party.
- Neither the president nor the children (plural) are at the party.
- Either the president or the children (plural) are at the party.
- Neither the children nor the president (singular) is at the party.
- Somebody (singular) is at the party.
- Nobody (singular) is at the party.
- We (plural 1st person) are at the party.
- I (singular 1st person) am at the party.
- The Three Musketeers (singular-book) is a good book.
- Ten dollars (singular) is enough to buy the book.
- Ten dollars (plural) are in my pocket.
- Economics (singular subject of study) is an interesting subject.
- Bryans and Hastings (singular supermarket) is a great place to shop.
- The idea of serving frankfurters (singular idea) is a good one.
- My sister is (singular) with my friend, Roberta, at the party.
- My sister and my friend are (both) at the party.
In many cases, the author decides whether the subject represents
something singular or plural, depending upon which idea is desired to be
expressed. For example, a group can act as a whole (singular) or as a
group of individuals (plural), and despite many attempts at making rules
for this, there is no simple rule that covers all cases:
- All of my family is going camping.
- Most of my family is at the party.
- All of my family are fans.
- Some of my family are fans.
- Most of my family is at the party.
- Most of my family are at the party.
- Some of my family are in their homes.
- The sounds the car makes, the ways they irritate (singular idea
stated with 2 phrases)\--it is all the same idea no matter how you
say it.
Another needed example is one in which the noun that is clearly singular
until the entire sentence is read, and something near the end changes
the meaning of the noun so that it clearly represents a plural thing.
|
# English in Use/Verb Usage
A verb is a part of speech that usually denotes action (\"bring\",
\"read\"), occurrence (\"to decompose\" (itself), \"to glitter\"), or a
state of being (\"exist\", \"live\", \"soak\", \"stand\"). Depending on
the language, a verb may vary in form according to many factors,
possibly including its tense, aspect, mood and voice. It may also agree
with the person, gender, and/or number of some of its arguments (what we
usually call subject, object, etc.).
Verbs can be conveyed in many ways. Lets look in particular at the word
\"wear\"
She wears a pink dress - This sentence is made up of three main parts,
she, being the noun. Wears, being an action or \'doing\' word. Pink,
describing the noun about to be added to the sentence and, Dress, the
noun which pulls all these words together (giving them all one key
point) to complete the sentence.
|
# English in Use/End Marks
## Period
The period, or full stop, is used to mark an entire and independent
sentence, whether simple or compound.
### Distinct sentences
When a sentence, whether long or short, is complete in respect to sense,
and independent in respect to construction, it should be marked with the
period: as,
- \"Every deviation from truth is criminal. Abhor a falsehood. Let
your words be ingenuous. Sincerity possesses the most powerful
charm.\"
- \"The force of a true individual is felt through every clause and
part of a right book; the commas and dashes are alive with
it.\"---R. W. Emerson.
- \"By frequent trying, Troy was won. All things, by trying, may be
done.\"---Lloyd, p. 184.
### Allied sentences
The period is often employed between two sentences which have a general
connection, expressed by a personal pronoun, a conjunction, or a
conjunctive adverb: as,
- \"The selfish man languishes in his narrow circle of pleasures. They
are confined to what affects his own interests. He is obliged to
repeat the same gratifications, till they become insipid. But the
man of virtuous sensibility moves in a wider sphere of
felicity.\"---Blair.
- \"And whether we shall meet again, I know not. Therefore our
everlasting farewell take.\"---Shak., J. C.
### Abbreviations
The period is generally used after abbreviations, and very often to the
exclusion of other points; but, as in this case it is not a constant
sign of pause, other points may properly follow it, if the words written
in full would demand them: as, A. D. for Anno Domini; Pro tem. for pro
tempore; Ult. for ultimo; i.e. for id est, that is;
- \"Add., Spect, No. 285.\"
- For \"Addison, in the Spectator, Number 285th.\"
- \"Consult the statute; \'Quart.\' I think, it is, \'Edwardi sext.,\'
or \'prim. et quint. Eliz.\'\"---Pope, p. 399.
## Note of interrogation
The eroteme, or note of interrogation, is used to designate a question.
### Questions direct
Questions expressed directly as such, if finished, should always be
followed by the note of interrogation: as,
- \"Was it possible that virtue so exalted should be erected upon
injustice? that the proudest and the most ambitious of mankind
should be the great master and accomplished pattern of humility?
that a doctrine so pure as the Gospel should be the work of an
uncommissioned pretender? that so perfect a system of morals should
be established on blasphemy?\"---Jerningham\'s Essay, p. 81.
- \"In life, can love be bought with gold? Are friendship\'s pleasures
to be sold?\"---Johnson.
### Questions united
When two or more questions are united in one compound sentence, the
comma, semicolon, or dash, is sometimes used to separate them, and the
eroteme occurs after the last only: as,
- \"When---under what administration---under what exigencies of war or
peace---did the Senate ever before deal with such a measure in such
a manner? Never, sir, never.\"---D. Webster, in Congress, 1846.
- \"Cannot you, and honoured with a christian name, buy what is
woman-born, and feel no shame; trade in the blood of innocence, and
plead expedience as a warrant for the deed?\"---Cowper.
- \"Truths would you teach, or save a sinking land? All fear, none aid
you, and few understand.\"---Pope.
### Questions indirect
When a question is mentioned, but not put directly as a question, it
loses both the quality and the sign of interrogation: as,
- \"The Cyprians asked me why I wept.\"---Murray.
## Note of exclamation
The ecphoneme, or note of exclamation, is used to denote a pause with
some strong emotion of admiration, joy, grief, or other feeling; and, as
a sign of great wonder, it is sometimes, though not very elegantly,
repeated: as,
- \"Grammatical consistency!!! What a gem!\"---Peirce\'s Gram.,
p. 352.
### Interjections
Emphatic interjections, and other expressions of great emotion, are
generally followed by the note of exclamation: as,
- \"Hold! hold! Is the devil in you? Oh! I am bruised all
over.\"---Molière: Burgh\'s Speaker, p. 250.
- \"And O! till earth, and seas, and heaven decay, never may that fair
creation fade away!\"---Dr. Lowth.
### Invocations
After an earnest address or solemn invocation, the note of exclamation
is now generally preferred to any other point: as,
- \"Whereupon, O king Agrippa! I was not disobedient to the heavenly
vision.\"---Acts, xxvi, 19.
- \"Be witness you, immortal Lord of all! Whose thunder shakes the
dark aerial hall.\"---Pope.
### Exclamatory questions
Words uttered with vehemence in the form of a question, but without
reference to an answer, should be followed by the note of exclamation:
as,
- \"How madly have I talked!\"---Young.
- \"An Author! It is a venerable name! How few deserve it, and what
numbers claim!\"---Id., Br. Po., viii, 401.
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
|
# English in Use/Commas
The **comma** is used to separate those parts of a sentence, which are
so nearly connected in sense, as to be only one degree removed from that
close connection which admits no point.
## Introductory phrases
## Appositives
Appositives are always separated from the main body of the sentence by
punctuation, usually commas, but sometimes---when greater separation is
desired---dashes are used.
Words in **apposition**, especially if they have adjuncts, are generally
set off by the comma: as,
- \"He that now calls upon you, is Theodore, the hermit of
Teneriffe.\"---Johnson.
- \"Lowth, Dr. Robert, bishop of London, born in 1710, died in
1787.\"---Biog. Dict.
- \"Home, Henry, lord Kames.\"---Ib.
- \"What next I bring shall please you, be assured, your likeness,
your fit help, your other self, your wish exactly to your heart\'s
desire.\"---Milton, P. L., viii, 450.
- \"And he, their prince, shall rank among my peers.\"---Byron.
## Parenthetical expressions
### Adjectives
Adjectives, when something depends on them, or when they have the import
of a dependent clause, should, with their **adjuncts**, be set off by
the comma: as,
- \"Among the roots of hazel, pendent over the plaintive stream, they
frame the first foundation of their domes.\"---Thomson.
- \"Up springs the lark, shrill-voiced and loud, the messenger of
morn.\"---Id.
### Adjective which follows its noun
When an adjective immediately follows its noun, and is taken in a
restrictive sense, the comma should not be used before it: as,
- \"And on the coast averse from entrance or cherubic
watch.\"---Milton, P. L., B. ix, l. 68.
### Finite verbs
Where a finite verb is understood, a comma is generally required: as,
- \"From law arises security; from security, curiosity; from
curiosity, knowledge.\"---Murray.
- \"Else all my prose and verse were much the same; this, prose on
stilts; that, poetry fallen lame.\"---Pope.
### A pause for the omitted verb
As the semicolon must separate the clauses when the comma is inserted by
this rule, if the pause for the omitted verb be very slight, it may be
left unmarked, and the comma be used for the clauses: as,
- \"When the profligate speaks of piety, the miser of generosity, the
coward of valour, and the corrupt of integrity, they are only the
more despised by those who know them.\"---Comstock\'s Elocution,
p. 132.
### Infinitives
The infinitive, when it follows a verb from which it must be separated,
or when it depends on something remote or understood, is generally, with
its adjuncts, set off by the comma: as,
- \"One of the greatest secrets in composition is, to know when to be
simple.\"---Jamieson\'s Rhet., p. 151. \[?\]
- \"To confess the truth, I was much in fault.\"---Murray\'s Gram.,
p. 271.
- \"The Governor of all---has interposed, not seldom, his avenging
arm, to smite the injurious trampler upon nature\'s law.\"---Cowper.
### Participles
Participles, when something depends on them, when they have the import
of a dependent clause, or when they relate to something understood,
should, with their adjuncts, be set off by the comma: as,
- \"Law is a rule of civil conduct, prescribed by the supreme power in
a state, commanding what is right, and prohibiting what is
wrong.\"---Blackstone: Beattie\'s Moral Science, p. 346.
- \"Young Edwin, lighted by the evening star, lingering and listening
wandered down the vale.\"---Beattie.
- \"United, we stand; divided, we fall.\"---Motto.
- \"Properly speaking, there is no such thing as chance.\"
### Participle which follows its noun
When a participle immediately follows its noun, and is taken in a
restrictive sense, the comma should not be used before it: as,
- \"A man renowned for repartee, will seldom scruple to make free with
friendship\'s finest feeling.\"---Cowper.
### Adverbs
Adverbs, when they **break the connection** of a simple sentence, or
when they have not a close dependence on some particular word in the
context, should, with their adjuncts, be set off by the comma: as,
- \"We must not, however, confound this gentleness with the artificial
courtesy of the world.\"
- \"Besides, the mind must be employed.\"---Gilpin.
- \"Most unquestionably, no fraud was equal to all
this.\"---Lyttelton.
- \"But, unfortunately for us, the tide was ebbing already.\"
- \"When buttress and buttress, alternately, seem framed of ebon and
ivory.\"---Scott\'s Lay, p. 33.
### Conjunctions
Conjunctions, when they are separated from the principal clauses that
depend on them, or when they introduce examples, are generally set off
by the comma: as,
- \"But, by a timely call upon religion, the force of habit was
eluded.\"---Johnson.
- \"They know the neck that joins the shore and sea, or, ah! how
changed that fearless laugh would be.\"---Crabbe.
### Prepositions
Prepositions and their objects, when they break the connection of a
simple sentence, or when they do not closely follow the words on which
they depend, are generally set off by the comma: as,
- \"Fashion is, for the most part, nothing but the ostentation of
riches.\"
- \"By reading, we add the experience of others to our own.\"
- \"In vain the sage, with retrospective eye, would from the apparent
what conclude the why.\"---Pope.
### Interjections
Interjections that require a pause, though more commonly emphatic and
followed by the ecphoneme, are sometimes set off by the comma: as,
- \"For, lo, I will call all the families of the kingdoms of the
north.\"---Jeremiah, i, 15.
- \"O, it was about something you would not understand.\"---Columbian
Orator, p. 221.
- \"Ha, ha! you were finely taken in, then!\"---Aikin.
- \"Ha, ha, ha! A facetious gentleman, truly!\"---Id.
- \"Oh, when shall Britain, conscious of her claim, stand emulous of
Greek and Roman fame?\"---Pope.
### Words emphatically repeated
A word emphatically repeated, is generally set off by the comma: as,
- \"Happy, happy, happy pair!\"---Dryden.
- \"Ay, ay, there is some comfort in that.\"---Shak.
- \"Ah! no, no, no.\"---Dryden.
- \"The old oaken bucket, the iron-bound bucket, the moss-covered
bucket, which hung in the well!\"---Woodworth.
### Dependent quotations
A quotation, observation, or description, when it is introduced in close
dependence on a verb, (as, say, reply, cry, or the like,) is generally
separated from the rest of the sentence by the comma: as,
- \"\'The book of nature,\' said he, \'is before
you.\'\"---Hawkesworth.
- \"I say to all, watch.\"---Mark.
- \"\'The boy has become a man,\' means, \'He has grown to be a man.\'
\'Such conduct becomes a man,\' means, \'Such conduct befits
him.\'\"---Hart\'s Gram., p. 116.
- \"While man exclaims, \'See all things for my use!\' \'See man for
mine!\' replies a pampered goose.\"---Pope.
### Words put absolute
Nouns or pronouns put **absolute**, should, with their adjuncts, be set
off by the comma: as,
- \"The prince, his father being dead, succeeded.\"
- \"This done, we parted.\"
- \"Zaccheus, make haste and come down.\"
- \"His proctorship in Sicily, what did it produce?\"---Cicero.
- \"Winged with his fears, on foot he strove to fly, his steeds too
distant, and the foe too nigh.\"---Pope, Iliad, xi, 440.
## Series
### More than two words
When more than two words or terms are connected in the same
construction, or in a **joint dependence** on some other term, by
conjunctions expressed or understood, the comma should be inserted after
every one of them but the last; and, if they are nominatives before a
verb, the comma should follow the last also: as,
- \"Who, to the enraptured heart, and ear, and eye, teach beauty,
virtue, truth, and love, and melody.\"---Beattie.
- \"Ah! what avails\... all that art, fortune, enterprise, can bring,
if envy, scorn, remorse, or pride, the bosom wring?\"---Id.
- \"Women are soft, mild, pitiful, and flexible; you, stern, obdurate,
flinty, rough, remorseless.\"---Shak.
- \"She plans, provides, expatiates, triumphs there.\"---Young.
- \"So eagerly the fiend over bog, or steep, through strait, rough,
dense, or rare, with head, hands, wings, or feet, pursues his way,
and swims, or sinks, or wades, or creeps, or flies.\"---Milton.
### Only two words
When only two words or terms are connected by a conjunction, they should
not be separated by the comma: as,
- \"It is a stupid and barbarous way to extend dominion by arms; for
true power is to be got by arts and industry\"---Spectator, No. 2.
- \"Despair and anguish fled the struggling soul.\"---Goldsmith.
### Two words with several adjuncts
When the **two words** connected have several **adjuncts**, or when one
of them has an adjunct that relates not to both, the comma is inserted:
as,
- \"I shall spare no pains to make their instruction agreeable, and
their diversion useful.\"---Spectator, No. 10.
- \"Who is applied to persons, or things personified.\"---Bullions.
- \"With listless eyes the dotard views the store, he views, and
wonders that they please no more.\"---Johnson.
### Contrasted words or phrases
When two connected words or phrases are **contrasted**, or emphatically
distinguished, the comma is inserted: as,
- \"The vain are easily obliged, and easily disobliged.\"---Kames.
- \"Liberal, not lavish, is kind nature\'s hand.\"---Beattie.
- \"It is certain he could write, and cipher too.\"---Goldsmith.
### Alternative of names
When there is merely an alternative of names, or an explanatory change
of terms, the comma is usually inserted: as,
- \"We saw a large opening, or inlet.\"---W. Allen.
- \"Have we not power to lead about a sister, a wife, as well as other
apostles?\"---Cor., ix, 5.
### Understood conjunction
When the conjunction is understood, the comma is inserted; and, if two
separated words or terms refer alike to a third term, the second
requires a second comma: as,
- \"Reason, virtue, answer one great aim.\"---L. Murray, Gram.,
p. 269.
- \"To him the church, the realm, their powers consign.\"---Johnson.
- \"She thought the isle that gave her birth. The sweetest, wildest
land on earth.\"---Hogg.
### Words in pairs
When successive words are joined in **pairs** by conjunctions, they
should be separated in pairs by the comma: as,
- \"Interest and ambition, honour and shame, friendship and enmity,
gratitude and revenge, are the prime movers in public
transactions.\"---W. Allen.
- \"But, whether ingenious or dull, learned or ignorant, clownish or
polite, every innocent man, without exception, has as good a right
to liberty as to life.\"---Beattie\'s Moral Science, p. 313.
- \"Then say how hope and fear, desire and hate, overspread with
snares the crowded maze of fate.\"---Dr. Johnson.
### A compound name
When several words, in their common order, are used as one compound
name, the comma is not inserted: as,
- \"Dr. Samuel Johnson,\"
- \"Publius Gavius Cosanus.\"
### United common and proper name
When a common and a proper name are closely united, the comma is not
inserted: as,
- \"The brook Kidron,\"
- \"The river Don,\"
- \"The empress Catharine,\"
- \"Paul the Apostle.\"
### A mere emphasis and distinction
When a pronoun is added to an other word merely for emphasis and
distinction, the comma is not inserted: as,
- \"You men of Athens,\"
- \"I myself,\"
- \"You flaming minister,\"
- \"You princes.\"
### Name acquired by action or relation
When a name acquired by some action or relation, is put in apposition
with a preceding noun or pronoun, the comma is not inserted: as,
- \"I made the ground my bed;\"
- \"To make him king;\"
- \"Whom they revered as God;\"
- \"With modesty your guide.\"---Pope.
## Clarity
### Simple sentences
A **simple sentence** does not, in general, admit the comma: as,
- \"The weakest reasoners are the most positive.\"---W. Allen\'s
Gram., p. 202.
- \"Theology has not hesitated to make or support a doctrine by the
position of a comma.\"---Tract on Tone, p. 4.
- \"Then pain compels the impatient soul to seize on promised hopes of
instantaneous ease.\"---Crabbe.
### Nominative accompanied by adjuncts
When the **nominative** in a long simple sentence is accompanied by
inseparable **adjuncts**, or when several words together are used
instead of a nominative, a comma should be placed immediately before the
verb: as,
- \"Confession of sin without amendment, obtains no
pardon.\"---Dillwyn\'s Reflections, p. 6.
- \"To be totally indifferent to praise or censure, is a real defect
in character.\"---Murray\'s Gram., p. 268.
- \"O that the tenor of my just complaint, were sculpt with steel in
rocks of adamant!\"---Sandys.
### Simple members
The **simple members** of a compound sentence, whether successive or
involved, elliptical or complete, are generally divided by the comma:
as,
- \"Here stand we both, and aim we at the best.\"---Shak.
- \"I, that did never weep, now melt in woe.\"---Id.
- \"Tide life, tide death, I come without delay.\"---Id.
- \"I am their mother, who shall bar me from them?\"---Id.
- \"How wretched, were I mortal, were my state!\"---Pope.
- \"Go; while you may, avoid the dreadful fate.\"---Id.
- \"Grief aids disease, remembered folly stings, and his last sighs
reproach the faith of kings.\"---Johnson.
### Relative that follows its antecedent
When a relative immediately follows its antecedent, and is taken in a
restrictive sense, the comma should not be introduced before it: as,
- \"For the things which are seen, are temporal; but the things which
are not seen, are eternal.\"---2 Cor., iv, 18.
- \"A letter is a character that expresses a sound without any
meaning.\"---St. Quentin\'s General Gram., p. 3.
### Closely connected simple members
When the simple members are short, and **closely connected** by a
**conjunction** or a **conjunctive adverb**, the comma is generally
omitted: as,
- \"Honest poverty is better than wealthy fraud.\"---Dillwyn\'s Ref.,
p. 11.
- \"Let him tell me whether the number of the stars be even or
odd.\"---Taylor: Joh. Dict., w.
- \"It is impossible that our knowledge of words should outstrip our
knowledge of things.\"---Campbell: Murray\'s Gram., p 359.
## Omissions
### Simple immediately united members
When two simple members are immediately united, through **ellipsis** of
the relative, the antecedent, or the conjunction that, the comma is not
inserted: as,
- \"Make an experiment on the first man you meet.\"---Berkley\'s
Alciphron, p. 125.
- \"Our philosophers do infinitely despise and pity whoever shall
propose or accept any other motive to virtue.\"---Ib., p. 126.
- \"It is certain we imagine before we reflect.\"---Ib., p. 359.
- \"The same good sense that makes a man excel, still makes him doubt
he never has written well.\"---Young.
## References
- The organization of this chapter was adapted from the 1977 edition
of *Building English Skills Handbook* by McDougal, Litell & Company.
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
|
# English in Use/Apostrophes
An **apostrophe** can be used to form possessives for nouns, indicate
the omission of letters in a word for stylistic purposes or as a
colloquial form of a word, and be used to indicate plurality.
The term is derived from the Latin word **apostrophus** itself derived
from the Greek words **αποστροφος** meaning *accident of elision*
**αποστρεφειν** meaning *a turning away.*
The apostrophe usually denotes either the possessive case of a noun, or
the elision of one or more letters of a word: as,
- \"The girl\'s regard to her parents\' advice;\"
\'Gan, lov\'d, e\'en, thro\'; for *began, loved, even, through*.
It is sometimes used in pluralizing a mere letter or sign: as,
- \"Two a\'s---three 6\'s.\"
**Apostrophe** is also a figure of speech in which an absent person, a
personified inanimate being, or an abstraction, is addressed as though
present.
This sense is maintained when a narrative or dramatic thread is broken
in order to digress by speaking directly to someone not there, e.g.,
- "Envy, be silent and attend!"---Alexander Pope.
- "On a Certain Lady at Court."
|
# English in Use/Quotations
The **quotation points** distinguish words that are exhibited as those
of an other author or speaker. A quotation within a quotation, is
usually marked with single points; which, when both are employed, are
placed within the others: as,
- \"And again he said, \'Rejoice, you gentiles, with his
people.\'\"---Rom., xv, 10.
## English Quotations
In English quotations and direct speech is donated using quotation
marks:
- **\"** is used as an opening quotation mark,
- **\"** is also used as a closing quotation mark.
Converting direct speech follows a pattern in English which may differ
to reported speech in other languages. This pattern concerns statements
(there are different rules for imperatives and questions).
Tense Changes
-------------------------
Direct Speech
\"I am from England\"
\"I am going to Italy\"
\"I have read it\"
Note that when converting from direct speech to indirect speech you
usually have to move the tense backwards:
Tense Changes
-------------------
Direct Speech
Present Simple
Present Perfect
Past Simple
Will + Infinitive
Be + Going to
Similarly there are some changes to be made to other words in the
sentence. Because we are reporting what someone said in the past we must
use other words to talk about the past, e.g. \"today\" becomes \"that
day\", \"here\" becomes \"there\", \"next week\" becomes \"the following
week\" and \"last week\" becomes \"the previous week\". There are other
similar changes too.
Examples
----------------------------------------
\"I am here\"
\"I am from England\"
\"I will return next week\"
\"I have worked here since last week\"
|
# English in Use/Other Common Punctuation Marks
## Semicolon
The semicolon is used to separate those parts of a compound sentence,
which are neither so closely connected as those which are distinguished
by the comma, nor so little dependent as those which require the colon.
### Complex members
When two or more **complex members**, or such clauses as require the
comma in themselves, are constructed into a period, they are generally
separated by the semicolon: as,
- \"In the regions inhabited by angelic natures, unmingled felicity
forever blooms; joy flows there with a perpetual and abundant
stream, nor needs any mound to check its course.\"---Carter.
- \"When the voice rises, the gesture naturally ascends; and when the
voice makes the falling inflection, or lowers its pitch, the gesture
follows it by a corresponding descent; and, in the level and
monotonous pronunciation of the voice, the gesture seems to observe
a similar limitation, by moving rather in the horizontal direction,
without much varying its elevation.\"---Comstock\'s Elocution,
p. 107.
- \"The wide, the unbounded prospect lies before me; but shadows,
clouds, and darkness, rest upon it.\"---Addison.
### Simple members
When two or more simple members, or such clauses as **complete** their
sense without subdivision, are constructed into a period; if they
require a pause greater than that of the comma, they are usually
separated by the semicolon: as,
- \"Straws swim on the surface; but pearls lie at the
bottom.\"---Murray\'s Gram., p. 276.
- \"Everything grows old; everything passes away; everything
disappears.\"---Hiley\'s Gram., p. 115.
- \"Alexander asked them the distance of the Persian capital; what
forces the king of Persia could bring into the field; what the
Persian government was; what was the character of the king; how he
treated his enemies; what were the most direct ways into
Persia.\"---Whelpley\'s Lectures, p. 175.
- \"A longer care man\'s helpless kind demands; that longer care
contracts more lasting bands.\"---Pope.
### Apposition
Words in apposition, in **disjunct pairs**, or in any other
construction, if they require a pause greater than that of the comma,
and less than that of the colon, may be separated by the semicolon: as,
- \"Pronouns have three cases; the nominative, the possessive, and the
objective.\"---Murray\'s Gram., p. 51.
- \"Judge, judgement; lodge, lodgement; acknowledge,
acknowledgement.\"---Butler\'s Gram., p. 11.
- \"Do not the eyes discover humility, pride; cruelty, compassion;
reflection, dissipation; kindness, resentment?\"---Sheridan\'s
Elocution, p. 159.
- \"This rule forbids parents to lie to children, and children to
parents; instructors to pupils, and pupils to instructors; the old
to the young, and the young to the old; attorneys to jurors, and
jurors to attorneys; buyers to sellers, and sellers to
buyers.\"---Wayland\'s Moral Science, p. 304.
- \"Make, made; have, had; pay, paid; say, said; leave, left; dream,
dreamt; mean, meant; reave and bereave have reft.\" ---Ward\'s Gr.,
p. 66.
## Colon
The colon is used to separate those parts of a compound sentence, which
are neither so closely connected as those which are distinguished by the
semicolon, nor so little dependent as those which require the period.
### Additional remarks
When the preceding clause is complete in itself, but is followed by some
additional remark or **illustration**, especially if no conjunction is
used, the colon is generally and properly inserted: as,
- \"Avoid evil doers: in such society, an honest man may become
ashamed of himself.\"
- \"See that moth fluttering incessantly round the candle: man of
pleasure, behold your image!\"---Art of Thinking, p. 94.
- \"Some things we can, and others we cannot do: we can walk, but we
cannot fly.\"---Beanie\'s Moral Science, p. 112.
- \"Remember heaven has an avenging rod: to smite the poor, is treason
against God.\"---Cowper.
### Greater pauses
When the semicolon has been introduced, or when it must be used in a
subsequent member, and a still greater pause is required within the
period, the colon should be employed: as,
- \"Princes have courtiers, and merchants have partners; the
voluptuous have companions, and the wicked have accomplices: none
but the virtuous can have friends.\"
- \"Unless the truth of our religion be granted, a christian must be
the greatest monster in nature: he must at the same time be
eminently wise, and notoriously foolish; a wise man in his practice,
and a fool in his belief: his reasoning powers must be deranged by a
constant delirium, while his conduct never swerves from the path of
propriety.\"---Principles of Eloquence, p. 80
- \"A decent competence we fully taste; it strikes our sense, and
gives a constant feast: more we perceive by dint of thought alone;
the rich must labour to possess their own.\"---Young.
### Independent quotations
A quotation introduced without a close dependence on a verb or a
conjunction, is generally preceded by the colon: as,
- \"In his last moments, he uttered these words: \'I fall a sacrifice
to sloth and luxury.\'\"
- \"At this the king hastily retorted: \'No put-offs, my lord; answer
me presently.\'\"---Churchill\'s Gram., p. 367.
- \"The father addressed himself to them to this effect: \'O my sons,
behold the power of unity!\'\"--- Rippingham\'s Art of Speaking,
p. 85.
## Dash
The dash is mostly used to denote an unexpected or emphatic pause, of
variable length; but sometimes it is a sign of faltering, or of the
irregular stops of one who hesitates in speaking: as,
- \"Then, after many pauses, and inarticulate sounds, he said: \'He
was very sorry for it, was extremely concerned it should happen
so---but---a---it was necessary---a---\' Here lord E--- stopped him
short, and bluntly demanded, if his post were destined for
another.\"---Churchill\'s Gram., p. 170.
### Abrupt pauses
A sudden interruption, break, or transition, should be marked with the
dash: as,
- \"\'I must inquire into the affair; and if\'---\'And if!\'
interrupted the farmer.\"
- \"Whom I---But first it is fit the billows to restrain.\"---Dryd.
Virg. 3.
- \"Here lies the great---False marble! where? Nothing but sordid dust
lies here.\"---Young.
### Emphatic pauses
To mark a considerable pause, greater than the structure or the sentence
or the points inserted would seem to require, the dash may be employed:
as,
- \"I pause for a reply.---None?---Then none have I offended.---I have
done no more to Caesar, than you should do to
Brutus.\"---Shakspeare: Enfields Speaker, p. 182.
- \"Tarry a little. There is something else.---This bond---doesn\'t
give you here---no jot of blood.\" ---ID.: Burgh\'s Sp., p. 167.
- \"It thunders;---but it thunders to preserve.\"---Young.
- \"Behold the picture!---Is it like?---Like whom?\"---Cowper.
### Faulty dashes
Dashes needlessly inserted, or substituted for other stops more
definite, are in general to be treated as errors in punctuation: as,
- \"Here Greece stands by itself as opposed to the other nations of
antiquity---She was none of the other nations---She was more
polished than they.\"---Lennie\'s Gram., p. 78.
- \"Here Greece stands by herself, as opposed to the other nations of
antiquity. She was none of the other nations: she was more polished
than they.\"---Bullions, E. Gram., p. 114.
If this colon is sufficient, the capital after it is needless: a period
would, perhaps, be better.
## Curves
The curves, or marks of parenthesis, are used to distinguish a clause or
hint that is hastily thrown in between the parts of a sentence to which
it does not properly belong: as,
- \"Their enemies (and enemies they will always have) would have a
handle for exposing their measures.\"---Walpole.
- \"To others do (the law is not severe) what to yourself you wish to
be done.\"---Beattie.
The incidental clause should be uttered in a lower tone, and faster than
the principal sentence. It always requires a pause as great as that of a
comma, or greater.
### Parenthesis
A clause that breaks the unity of a sentence or passage too much to be
incorporated with it, and only such, should be inclosed within curves,
as a parenthesis: as,
- \"For I know that in me, (that is, in my flesh,) dwells no good
thing.\"---Rom., vii, 18.
- \"Know then this truth, (enough for man to know,) virtue alone is
happiness below.\"---Pope.
### Included points
The curves do not supersede other stops; and, as the parenthesis
terminates with a pause equal to that which precedes it, the same point
should be included, except when the sentences differ in form: as,
- \"Now for a recompense in the same, (I speak as to my children,) be
you also enlarged.\"---2 Cor., vi, 13.
- \"Man\'s thirst of happiness declares it is: (for nature never
gravitates to nought:) that thirst unquenched, declares it is not
here.\"---Young.
- \"Night visions may befriend: (as sung above:) our waking dreams are
fatal. How I dreamt of things impossible! (could sleep do more?) of
joys perpetual in perpetual change!\"---Young.
## Hyphen
The hyphen connects the parts of many compound words, especially such as
have two accents: as, ever-living. It is also frequently inserted where
a word is divided into syllables: as, con-tem-plate. Placed at the end
of a line, it shows that one or more syllables of a word are can led
forward to the next line.
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
|
# English in Use/Less Common Typographical Marks
- the **Acute accent** \[**´**\]
- the **Asterisk** \[**\***\]
- the **Asterism** \[**⁂**\]
- the **Brace**, or **Curly Brackets** \[**{}**\]
- the **Breve** \[**˘**\]
- the **Caret** \[**\^**\]
- the **Cedilla** \[**¸**\]
- the **Circumflex** \[**ˆ**\]
- the **Crotchets**, or **Brackets** \[**\[\]**\],
- the **Diaeresis** \[**¨**\]
- the **Diesis**, or **Double Dagger** \[**‡**\]
- the **Ellipsis** \'\'\'...\'\'\'
- the **Grave accent** \[**\`**\]
- the **Guillements**, or **Angle Quotes** \[**«»**\]
- the **Index** \[**☞**\]
- the **Macron** \[**¯**\]
- the **Obelisk**, or **Dagger** \[**†**\]
- the **Paragraph** \[**¶**\]
- the **Quotation Marks** \[**""**\]
- the **Parallels** \[**\|\|**\]
- the **Section** \[**§**\]
## Acute accent \[ **´** \]
The acute accent marks the syllable which requires the principal stress
in pronunciation: as, e\'qual, equal\'ity. It is sometimes used in
opposition to the grave accent, to distinguish a close or short vowel:
as, *Fancy*; or to denote the rising inflection of the voice: as,
- \"Is it he?\"
## Asterisk ( **\*** )
The asterisk, or star, the obelisk, or dagger, the diesis, or double
dagger, the section, the parallels, and the paragraph, refer to marginal
notes. Where many references are to be made, the small letters of the
alphabet, or the numerical figures, in their order, may be conveniently
used for the same purpose.
## Asterism \[**⁂**\]
The asterism, or three stars, a sign not very often used, is placed
before a long or general note, to mark it as a note, without giving it a
particular reference.
## At sign at sign ( @ )
The *at sign* is variously used in various conventions. Originally it
was an accountancy abbreviation for \"at\", as:
- \"One load of erunam @ \$7.50 per bucket\"
and still used informally to represent \'at\'\
On the Internet it commomly indicates the start of an email address
## Brace or Curly Brackets \[**{}**\]
The brace serves to unite a triplet; or, more frequently, to connect
several terms with something to which they are all related.
## Brackets of various types ( **( ) \[ \] { }〈 〉**)
The crotchets, parentheses or brackets generally enclose a parenthetic
correction or remark, but sometimes the sign or subject to be explained:
as,
- \"He \[Mr. Maurice\] was of a different opinion.\"---Allen\'s Gram.,
p. 213.
In formal notation it can delimit an expression to be used as a term or
logical unit in a larger expression, to be evaluated out of the lexical
sequence before being included in the encompassing expression. eg, in
the following expression, the addition must be performed before the
multiplication or division:
- \"The assessment is to be calculated as: Contribution \* (age +
diameter) / mean weighting\"
## Breve \[ **˘** \]
The breve, or stenotone, is used to denote either the close, short, shut
sound of a vowel, or a syllable of short quantity: as, l˘ive, to have
life; r˘av\'en, to devour; c˘al˘am˘us, a reed.
## Caret \[**\^**\]
The caret, used only in writing, shows where to insert words or letters
that have been accidentally omitted.
## Cedilla \[**¸**\]
The cedilla is borrowed from the French. It is placed under the letter
*c*, to give it the sound of *s*, before *a* or *o*: as, *Façade*,
*Alençon*. It is sometimes attached to other letters, to denote their
soft sounds: Ģ as *J*; Ş as *Z*.
## Circumflex**ˆ**
The circumflex generally denotes either the broad sound of a or an
unusual sound given to some other vowel: as in *all, heir, machine*.
Some use it to mark a peculiar wave of the voice, and when occasion
requires, reverse it: as,
- \"If you said s\^o, then I said so.\"
## Degree sign
The degree sign ( **`<big>`{=html}°`</big>`{=html}** ) : marks several
different units: arc degrees, temperature degrees, and (rarely) hours of
time. Different from the masculine ordinal indicator, used to abbreviate
ordinal numbers in some languages
## Diaeresis \[**¨**\]
The diaeresis, or dialysis, placed over either of two contiguous vowels,
shows that they are not a diphthong: as, *Danaee, aerial*.
## Ellipsis (**...**)
The ellipsis, or suppression, denotes the omission of some letters or
words: as, K...g, for King; c...d, for coward; d...d, for damned.
## Grave accent \[**\`**\]
The grave accent is used in opposition to the acute, to distinguish an
open or long vowel: as, *Favour*; or to denote the falling inflection of
the voice: as,
- \"Yes; it is he.\"
It is sometimes placed over a vowel to show that it is not to be
suppressed in pronunciation: as,
- \"Let me, though in humble speech, your refined maxims
teach.\"---Amer. Review, May, 1848.
## Index \[**☞**\]
The index, or hand, points out something remarkable, or what the reader
should particularly observe: as,
- \"**`<big>`{=html}☞`</big>`{=html}** On odd dates it is a criminal
offence to bring a wheeled vehicle into the controlled area
## Macron \[**¯**\]
The macron, or macrotone, is used to denote either the open, long,
primal sound of a vowel, or a syllable of long quantity: as, l¯ive,
having life; r¯a\'ven, a bird; ¯e\'qu¯ine, of a horse.
## Number sign, octothorpe, pound sign, or hash ( **\#** )
The number sign is variously used in different conventions. Commonly
means \"number\" when preceding ordinal numbers, but weight when
following numbers
## Paragraph mark or pilcrow \[**¶**\]
The paragraph denotes the commencement of a new subject. Those parts of
discourse that usually are called paragraphs, generally are sufficiently
distinguished by beginning a new line, often with the first word or the
body text indented. However, when referring to numbered paragraphs in
books, the pilcrow may be used as an abbreviation for the word
\"paragraph\".
## Section \[**§**\]
The section marks the smaller divisions of a book or chapter; and, with
the help of numbers, serves to abridge references.
## Slash/Solidus (**/**) and backslash (**\\**)
Forward slashes are used to indicate alternatives, connect words, and
form abbreviations. For example, black/white, either/or, w/o (without).\
Slashes also are used variously in technical notation, for example to
denote division, rates or fractions, or to denote files within different
folders on an Internet server.
## Other marks
ampersand ( & ) : a substitute for the word \'and\'. Most common in signs, titles, and informal writing.
```{=html}
<!-- -->
```
bullet ( •, more ) : used to mark items in lists
```{=html}
<!-- -->
```
currency ( ¤ ) :
```{=html}
<!-- -->
```
dagger ( † ‡ ) : commonly used to mark footnotes (along with the asterisk)
```{=html}
<!-- -->
```
interrobang ( ‽ ) : A superimposed exclamation point and question mark, sometimes used in place of !? to denote a surprised question.
```{=html}
<!-- -->
```
percent and related signs ( % ) ( ‰ ) ( ‱ ) :
```{=html}
<!-- -->
```
prime ( ′ ) :
```{=html}
<!-- -->
```
spaces ( ) ( ) ( ) :
```{=html}
<!-- -->
```
tilde ( \~ ) :
```{=html}
<!-- -->
```
umlaut/diaresis ( ¨ ) :
```{=html}
<!-- -->
```
underscore/understrike ( \_ ) :
```{=html}
<!-- -->
```
vertical line/pipe/broken bar ( \| ) ( ¦ ) :
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
|
# English in Use/Time and Date
Here are some hints on **how to express the date and time in
English**:
## Date
- The day of the month, the month, and the year:
- Use *on* + ordinal of the day. *On the 1st of June*.
- Use *in + only* and the month. *In June*.
- Use *about the* + date (for approximate dates). *About the 25th
of December*.
- Day of the week: precedes *on*. Example: *open on Sundays*.
- Ask the date: *what\'s the date* and *what day is it (or today)?*.
- Answer a date asking: *today\'s the* + ordinal. *Today\'s the 16th.*
- Century: *in the* + the ordinal of the century. Example: *in the
20th century*.
- Decade:
- Precedes *in* with the number in plural: *in the 1990s*.
- Follows *something* for undetermined year of the decade, in
other words: *in 1980 something*.
- Era:
- A.D. = *Anno Domini*, Latin for *in the year
of the Lord*, in other words the Christian Era.
- B.C. = *Before Christ*, in other words *before Christian Era*.
## Time
- Ask the time: *What time is it?* and *What is the time?*
- Answer: *It is* and the part of the hour or the minutes, seconds:
*It is five o\'clock*.
- Parts of the day:
- morning: *in the morning*
- afternoon: *in the afternoon*
- evening: *in the evening*
- night: *at night*
- Halves:
- AM
- PM
- Parts of the hour:
- O\'clock, for example: *It is
one o\'clock* (1:00).
- Past and
to:
- *It is 4 minutes past 5 (5:04)* (or *4 minutes after 5* in
USA).
- *It is 20 to 5 (4:40)* (or *20 before 5* in USA).
- Quarter:
- A quarter past, for example: *It is a quarter past 9 (9:15)*
(or *a quarter after 9* in USA).
- A quarter to, for example: *It is a quarter to 12 (11:45)*
(or *a quarter before 12* in USA).
- Half past, for example: *It is
half past 9 (9:30)*.
- Answer to *when?*:
- Certain time: *At*, for example: *At 5 p.m.*.
- Proximity:
- Nearly, about : *It is about 10 o\'clock*.
- Just after: *It is just after 10* (a few minutes past 10).
- Synonyms for times:
- *Noon*, *Midday*: 12:00 in the 24 hour clock. *It is 5 past
noon* (12:05).
- *Midnight*: 0:00 in the 24 hour clock. *Half past midnight*
(00:30).
|
# English in Use/Capitalization
The use of capital letters in English is generally similar to in other
Germanic and Romance languages with a few exceptions. The following list
shows when you should use a capital letter:
## Capitalization
Capitalize the first word in every sentence.\
EXAMPLE: **S**he said, \"It will be hard to go home after this fun
vacation.\"
Capitalize the pronoun I.\
EXAMPLE: Ira said that **I** was the best dancer in the show.
Capitalize the interjection O.\
EXAMPLE: Guide and direct us,**O** Lord.
Capitalize the first word in both the salutation and the closing of a
letter.\
EXAMPLES: **D**ear Mr. Novato: **S**incerely
Capitalize the names of persons and animals.\
EXAMPLES: **F**ranklin **D.** **R**oosevelt **W**illem **d**e Kooning
Capitalize geographical names
EXAMPLES: the **G**ulf of Mexico the **S**outhwest **P**rince
**W**illiam **F**orest
Capitalize the names of planets, stars, constellations, and other
heavenly bodies.
EXAMPLES: **N**eptune **P**olaris **G**reat Nebula
Capitalize the names of teams, organizations, institutions, and
government bodies.
EXAMPLES: **K**ansas **C**ity **C**hiefs **F**uture **T**eachers of
**A**merica
Capitalize the names of historical events and periods, special events,
holidays, and other calendar items.
EXAMPLES: the **E**ighties the **C**ivil **W**ar **H**annukah my
**B**irthday
Capitalize the names of nationalities, races, and peoples
EXAMPLES: **I**ndian **C**hinese **B**edouin
Capitalize the names of religions and their followers, holy days and
celebrations, sacred writings, and specific deities.
EXAMPLES: **A**llah **H**indus **C**hristmas **K**oran
Capitalize the names of buildings and other structures.
EXAMPLES: **C**olleyville **H**eritage **H**igh **S**chool **W**orld
**T**rade **C**enter
Capitalize the names of monuments, memorials, and awards
EXAMPLES: **L**incoln **M**emorial **N**obel **P**eace **P**rize
Capitalize the names of trains, ships, aircraft, and spacecraft
EXAMPLES: **E**nola **G**ay **U**.**S**.**S**. **E**nterprise
**C**hallenger
Capitalize the names of businesses and the brand names of business
products
EXAMPLES: **C**ontinental **A**irlines **M**icrosoft **W**indows
## Notes
The use of medial capitals (those in the middle of words)is generally
considered poor English, although this is quite common on the Internet
and in advertisements. It\'s not necessary to capitalize styles of music
(e.g. \"indie\"), adjectives, or the name of companies if they
themselves don\'t use a capital letter (e.g. eBay) although the first
letter will sometimes be capitalized on the Internet due to technical
reasons.
|
# English in Use/Figures of Syntax
A **figure of syntax** is an intentional deviation from the ordinary
construction of words. The principal figures of syntax are five; namely,
el-lip\'-sis, ple\'-o-nasm, syl-lep\'-sis, en-al\'-la-ge, and
hy-per\'-ba-ton.
## Ellipsis
Ellipsis is the omission of some word or words which are necessary to
complete the construction, but not necessary to convey the meaning. Such
words are said, in technical phrase, to be understood.
Of compound sentences, a vast many are more or less elliptical.
Sometimes, for brevity\'s sake, even the most essential parts of a
simple sentence, are suppressed: as,
- \"But more of this hereafter.\"---Harris\'s Hermes, p. 77.
- This means, \"But I shall say more of this hereafter.\"
- \"Prythee, peace.\"---Shak.
- That is, \"I pray you, hold you your peace.\"
There may be an omission of any of the parts of speech, or even of a
whole clause, when this repeats what precedes. But the omission of mere
articles or interjections can scarcely constitute a proper ellipsis,
because these parts of speech ought to be expressed.
### Of the article
- \"A man and \[a\] woman.\"
- \"The day, \[the\] month, and \[the\] year.\"
- \"She gave me an apple and \[a\] pear, for a fig and \[an\]
orange.\"---Jaudon\'s Gram., p. 170.
### Of the noun
- \"The common \[law\] and the statute law.\"
- \"The twelve \[apostles\].\"
- \"The same \[man\] is he.\"
- \"One \[book\] of my books.\"
- \"A dozen \[bottles\] of wine.\"
- \"Conscience, I say; not your own \[conscience\], but \[the
conscience\] of the other.\"---1 Cor., x, 29.
- \"Every moment subtracts from \[our lives\] what it adds to our
lives.\"---Dillwyn\'s Ref., p. 8.
- \"Bad actions mostly lead to worse\" \[actions\].---Ib., p. 5.
### Of the adjective
- \"There are subjects proper for the one, and not \[proper\] for the
other.\"---Kames.
- \"A just weight and \[a just\] balance are the Lord\'s.\"---Prov.,
xvi, 11.
True ellipses of the adjective alone, are but seldom met with.
### Of the pronoun
- \"Leave \[you\] there your gift before the altar, and go \[you\]
your way; first be \[you\] reconciled to your brother, and then come
\[you\] and offer \[you\] your gift,\"---Matt., v, 24.
- \"Love \[you\] your enemies, bless \[you\] them that curse you, do
\[you\] good to them that hate you.\"---Ib., v. 44.
- \"Chastisement does not always immediately follow error, but \[it\]
sometimes comes when \[it is\] least expected.\"--- Dillwyn, Ref.,
p. 31.
- \"Men generally put a greater value upon the favours \[which\] they
bestow, than upon those \[which\] they receive.\"---Art of Thinking,
p. 48.
- \"Wisdom and worth were all \[that\] he had.\"---Allen\'s Gram.,
p. 294.
### Of the verb
- \"The world is crucified to me, and I \[am crucified\] to the
world.\"---Gal., vi, 14.
- \"Hearts should not \[differ\], though heads may,
differ.\"---Dillwyn, p. 11.
- \"Are you not much better than they\" \[are\]?---Matt., vi, 26.
- \"Tribulation works patience; and patience \[works\] experience; and
experience \[works\] hope.\"---Romans, v, 4.
- \"Wrongs are engraved on marble; benefits \[are engraved\] on
sand.\"---Art of Thinking, p. 41.
- \"To whom thus Eve, yet sinless\" \[spoke\].---Milton.
### Of the participle
- \"That \[being\] over, they part.\"
- \"Animals of various natures, some adapted to the wood, and some
\[adapted\] to the wave.\"---Melmoth, on Scripture, p. 13.
- \"His knowledge \[being\] measured to his state and place, His time
\[being\] a moment, and a point \[being\] his space.\"---Pope.
### Of the adverb
- \"He can do this independently of me, if not \[independently\] of
you.\"
- \"She shows a body rather than a life; a statue, \[rather\] than a
breather.\"---Shak., Ant. and Cleo., iii, 3.
### Of the conjunction
- \"But the fruit of the Spirit is love, \[and\] joy, \[and\] peace,
\[and\] long suffering, \[and\] gentleness, \[and\] goodness,
\[and\] faith, \[and\] meekness, \[and\] temperance.\"---Gal., v,
22.
The repetition of the conjunction is called polysyndeton; and the
omission of it, asyndeton.
### Of the preposition
- \"It shall be done \[on\] this very day.\"
- \"We shall set off \[at\] some time \[in\] next month.\"
- \"He departed \[from\] this life.\"
- \"He gave \[to\] me a book.\"
- \"We walked \[through\] a mile.\"
- \"He was banished \[from\] the kingdom.\"---W. Allen.
- \"He lived like \[to\] a prince.\"---Wells.
### Of the interjection
- \"Oh! the frailty, \[oh!\] the wickedness of men.\"
- \"Alas for Mexico! and \[alas\] for many of her invaders!\"
### Of phrases or clauses
- \"The active commonly do more than they are bound to do; the
indolent \[commonly do\] less\" \[than they are bound to do\].
- \"Young men, angry, mean less than they say; old men, \[angry,
mean\] more\" \[than they say\].
- \"It is the duty of justice, not to injure men; \[it is the duty\]
of modesty, not to offend them.\"---W. Allen.
## Pleonasm
Pleonasm is the introduction of superfluous words: as,
- \"But of the tree of the knowledge of good and evil, you shall not
eat of it.\"---Gen., ii, 17.
This figure is allowable only, when it abruptly introduces an emphatic
word, or repeats an idea to impress it more strongly: as,
- \"He that has ears to hear, let him hear.\"---Bible.
- \"All you inhabitants of the world, and dwellers on the
earth.\"---Id.
- \"There shall not be left one stone upon another that shall not be
thrown down.\"---Id.
- \"I know you who you are.\"---Id.
A pleonasm is sometimes impressive and elegant; but an unemphatic
repetition of the same idea, is one of the worst faults of bad writing.
## Syllepsis
Syllepsis is agreement formed according to the figurative sense of a
word, or the mental conception of the thing spoken of, and not according
to the literal or common use of the term: as,
- \"The Word was made flesh, and dwelt amongst us, and we beheld his
glory.\"---John, i, 14.
- \"Then Philip went down to the city of Samaria, and preached Christ
unto them.\"---Acts, viii, 5.
- \"The city of London have expressed their sentiments with freedom
and firmness.\"---Junius, p. 159.
- \"And I said \[to backsliding Israel,\] after she had done all these
things, turn you to me; but she returned not: and her treacherous
sister Judah saw it.\"---Jer., iii, 7.
- \"And he surnamed them Boanerges, which is, The sons of
thunder.\"---Mark, iii, 17.
- \"While Evening draws her crimson curtains round.\"---Thomson,
p. 63.
- \"The Thunder raises his tremendous voice.\"---Id., p. 113.
## Enallage
Enallage is the use of one part of speech, or of one modification, for
another. This figure borders closely on solecism. There are, however,
several forms of it which can appeal to good authority: as,
- \"You know that you are Brutus, that say this.\"---Shak.
- \"They fall successive\[ly\], and successive\[ly\] rise.\"---Pope.
- \"Than whom \[who\] a fiend more fell is nowhere found.\"---Thomson.
- \"Sure some disaster has befell\" \[befallen\].---Gay.
- \"So furious was that onset\'s shock, destruction\'s gates at once
unlock\" \[unlocked\].---Hogg.
## Hyperbaton
Hyperbaton is the transposition of words: as,
- \"He wanders earth around.\"---Cowper
- \"Rings the world with the vain stir.\"---Id.
- \"Whom therefore you ignorantly worship, him declare I to
you.\"---Acts, xvii, 23.
- \"\'Happy\', says Montesquieu, \'is that nation whose annals are
tiresome.\'\"---Corwin, in Congress, 1847.
This figure is much employed in poetry, but care should be taken lest it
produce ambiguity or solecism.
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
|
# English in Use/Syntax
------------------------------------------------------------------------
**Syntax** treats of the relation, agreement, government, and
arrangement, of words in sentences.
The **relation** of words is their reference to other words, or their
dependence according to the sense.
The **agreement** of words is their similarity in person, number,
gender, case, mood, tense, or form.
The **government** of words is that power which one word has over
another, to cause it to assume some particular modification.
The **arrangement** of words is their collocation, or relative position,
in a sentence.
A **sentence** is an assemblage of words, making complete sense, and
always containing a nominative and a verb: as,
- \"Reward sweetens labour.\"
The principal parts of a sentence are usually three; namely, the
**subject**, or **nominative**; the **finite verb**; and the **object**
governed by the verb: as,
- \"Crimes deserve punishment.\"
A **predicate** is the part of the sentence (or clause) which states
something about the subject.
The other or subordinate parts depend on these, either as primary or as
secondary **adjuncts**: as,
- \"High crimes justly deserve very severe punishments.\"
Sentences are usually said to be of two kinds, simple and compound.
A **simple sentence** is a sentence which consists of one single
assertion, supposition, command, question, or exclamation: as,
- \"David and Jonathan loved each other.\"
- \"If your enemy hunger.\"
- \"Do violence to no man.\"
- \"Am I not an apostle?\"---1 Cor., ix, 1.
- \"What immortal glory shall I have acquired!\"---Hooke: Mur. Seq.,
p. 71.
A **compound sentence** is a sentence which consists of two or more
simple ones either expressly or tacitly connected: as,
- \"Send men to Joppa, and call for Simon, whose surname is Peter; who
shall tell you words, whereby you and all your house shall be
saved.\"---Acts, xi, 13.
- \"The more the works of Cowper are read, the more his readers will
find reason to admire the variety and the extent, the graces and the
energy, of his literary talents.\"---Hayley: Mur. Seq., p. 250.
A **clause**, or **member**, is a subdivision of a compound sentence;
and is itself a sentence, either simple or compound: as,
- \"If your enemy be hungry, give him bread to eat; if he be thirsty,
give him water to drink.\"---Prov., xxv, 21.
A **phrase** is two or more words which express some relation of
different ideas, but no entire proposition: as,
- \"By the means appointed.\"
- \"To be plain with you.\"
- \"Having loved his own.\"
Words that are omitted by **ellipsis**, and that are necessarily
understood in order to complete the construction, must be supplied in
**parsing**.
The leading principles to be observed in the construction of sentences,
are embraced in the following rules, which are arranged, as nearly as
possible, in the order of the **parts of speech**.
## Articles
Articles relate to the nouns which they limit: as,
- \"At a little distance from the ruins of the abbey, stands an aged
elm.\"
- \"See the blind beggar dance, the cripple sing, the sot a hero,
lunatic a king.\"---Pope\'s Essay, Ep. ii, l. 268.
### The comparative or superlative degree
The definite article may relate to an adjective or adverb of the
comparative or the superlative degree: as,
- \"A land which was the mightiest.\"---Byron.
- \"The farther they proceeded, the greater appeared their
alacrity.\"---Dr. Johnson.
- \"He chooses it the rather.\"---Cowper.
### An unstressed numeral
The indefinite article is sometimes used to give a collective meaning to
an unstressed numeral (a plural adjective of number): as,
- \"You have a few names even in Sardis.\"---Rev., iii, 4.
- \"There are a thousand things which crowd into my
memory.\"---Spectator, No. 468.
- \"The centurion commanded a hundred men.\"---Webster.
## Nouns
### The subject or nominative
A noun or a pronoun which is the subject of a finite verb, must be in
the nominative case: as,
- \"The Pharisees also, who were covetous, heard all these things; and
they derided him.\"---Luke, xvi, 14.
- \"But where the meekness of self-knowledge veils the front of
self-respect, there look you for the man whom none can know but they
will honour.\"---Book of Thoughts, p. 66.
- \"Do you mourn Philander\'s fate? I know you say it: says your life
the same?\"---Young, N. ii, l. 22.
The subject, or nominative, is generally placed before the verb: as,
- \"Peace dawned on his mind.\"---Johnson.
- \"What is written in the law?\"---Bible.
But, in the following nine cases, the subject of the verb is usually
placed after it, or after the first auxiliary:
#### A question
When a question is asked without an interrogative pronoun in the
nominative case: as,
- \"Shall mortals be implacable?\"---Hooke.
- \"What are you doing?\"---Id.
- \"How many loaves have you?\"---Bible.
- \"Are they Israelites? So am I.\"---Ib.
#### The imperative mood
When the verb is in the imperative mood: as,
- \"Go you,\"
- \"Come you.\"
But, with this mood, the pronoun is very often omitted and understood:
as,
- \"Philip said to him, Come and see.\"---John, i, 46.
- \"And he said to them, Be not afraid.\"---Mark, xvi, 5.
#### An earnest wish or strong feeling
When an earnest wish, or other strong feeling, is expressed: as,
- \"May she be happy!\"
- \"How were we struck!\"---Young.
- \"Not as the world gives, give I to you.\"---Bible.
#### A supposition without if
When a supposition is made without the conjunction if: as,
- \"Had they known it;\" for, \"If they had known it.\"
- \"Were it true;\" for, \"If it were true.\"
- \"Could we draw by the covering of the grave;\" for, \"If we could
draw,\" etc.
#### Neither or nor
When neither or nor, signifying and not, precedes the verb: as,
- \"This was his fear; nor was his apprehension groundless.\"
- \"You shall not eat of it, neither shall you touch it.\"---Gen.,
iii, 3.
#### Emphasis
When, for the sake of emphasis, some word or words are placed before the
verb, which more naturally come after it: as,
- \"Here am I,\"
- \"Narrow is the way,\"
- \"Silver and gold have I none; but such as I have, give I
you.\"---Bible.
#### No regimen
When the verb has no regimen, and is itself emphatical: as,
- \"Echo the mountains round.\"---Thomson.
- \"After the light infantry marched the grenadiers, then followed the
horse.\"---Buchanan\'s Syntax, p. 71.
#### A dialogue
When the verbs, say, answer, reply, and the like, introduce the parts of
a dialogue: as,
- \"\'Son of affliction,\' said Omar, \'who are you?\' \'My name,\'
replied the stranger, \'is Hassan.\'\"---Dr. Johnson.
#### The adverb there
When the adverb *there* precedes the verb: as,
- \"There lived a man.\"---Montgomery.
- \"In all worldly joys, there is a secret wound.\"---Owen.
This use of *there*, is idiomatic, and somewhat different from the use
of the same word in reference to a particular locality: as,
- \"Because there was not much water there.\"---John, iii, 23.
### Apposition or appositive
A noun or a personal pronoun used to explain a preceding noun or
pronoun, is put, by **apposition**, in the same case: as,
- \"But it is really I, your old friend and neighbour, Piso, late a
dweller on the Coelian hill, who am now basking in the warm skies of
Palmyra.\"---Zenobia.
- \"But he, our gracious Master, kind as just, knowing our frame,
remembers we are dust.\"---Barbauld.
An apposition or **appositive** is an interjection into a sentence.
Appositive renames, or adds to the description of another noun. The
thought expressed by the sentence will stand fully on its own without
the appositive. In the following sentence, \"My best friend\'s collie\"
is an appositive:
- \"The dog, my best friend\'s collie, caught the frisbee every
time.\"
### A possessive noun
A noun or a pronoun in the possessive case, is governed by the name of
the thing possessed: as,
- \"God\'s mercy prolongs man\'s life.\"---Allen.
- \"Theirs is the vanity, the learning yours; touched by your hand,
again Rome\'s glories shine.\"---Pope.
The possessive case generally comes immediately before the governing
noun, expressed or understood: as,
- \"All nature\'s difference keeps all nature\'s peace.\"---Pope.
- \"Lady! be yours (i. e., your walk) the Christian\'s walk.\"---Chr.
Observer.
- \"Some of Aeschylus\'s \[plays\] and Euripides\'s plays are opened
in this manner.\"---Blair\'s Rhet., p. 459.
And in this order one possessive sometimes governs another: as,
- \"Peter\'s wife\'s mother,\"
- \"Paul\'s sister\'s son.\"---Bible.
But, to this general principle of arrangement, there are some
exceptions: as,
#### An adjective
When the governing noun has an adjective, this may intervene: as,
- \"Flora\'s earliest smells.\"---Milton.
- \"Of man\'s first disobedience.\"---Id.
In the following phrase from the Spectator,
- \"Of Will\'s last night\'s lecture,\"
it is not very clear, whether Will\'s is governed by night\'s or by
lecture; yet it violates a general principle of our grammar, to suppose
the latter; because, on this supposition, two possessives, each having
the sign, will be governed by one noun.
#### The affirmed or denied possessive
When the possessive is affirmed or denied: as,
- \"The book is mine, and not John\'s.\"
But here the governing noun may be supplied in its proper place; else a
pronoun or the verb will be the only governing word: as,
- \"You are Christ\'s \[disciples, or people\]; and Christ is God\'s
\[son\].\"---St. Paul.
Whether this phraseology is thus elliptical or not, is questionable.
#### The case without the sign
When the case occurs without the sign, either by apposition or by
connection: as,
- \"In her brother Absalom\'s house.\"---Bible.
- \"David and Jonathan\'s friendship.\"---Allen.
- \"Adam and Eve\'s morning hymn.\"---Dr. Ash.
- \"Behold the heaven, and the heaven of heavens, is the Lord\'s your
God.\"---Deut., x, 14.
- \"For peace and quiet\'s sake.\"---Cowper.
- \"To the beginning of King James the First\'s
reign.\"---Bolingbroke, on Hist., p. 32.
### The object of predicate
A noun or a pronoun made the object of an active **transitive** verb or
participle, is governed by it in the objective case: as,
- \"I found her assisting him,\"
- \"Having finished the work, I submit it,\"
- \"Preventing fame, misfortune lends him wings, and Pompey\'s self
his own sad story brings.\" ---Rowe\'s Lucan, B. viii, l. 66.
### An intransitive verb
A noun or a pronoun put after an **intransitive** verb or participle,
agrees in case with a preceding noun or pronoun referring to the same
thing: as,
- \"It is I,\"
- \"These are they,\"
- \"The child was named John,\"
- \"It could not be he,\"
- \"The Lord sits King forever.\"---Psalms, xxix, 10.
- \"What war could ravish, commerce could bestow, and he returned a
friend, who came a foe.\"---Pope, Ep. iii, l. 206.
### An absolute noun
A noun or a pronoun is put **absolute** in the nominative, when its case
depends on no other word: as,
- \"He failing, who shall meet success?\"
- \"Your fathers, where are they? and the prophets, do they live
forever?\"---Zech., i, 5.
- \"Or I only and Barnabas, have not we power to forbear
working?\"---1 Cor., ix, 6.
- \"Nay but, O man, who are you that replies against God?\"---Rom.,
ix, 20.
- \"O rare we!\"---Cowper.
- \"Miserable they!\"---Thomson.
## Adjectives
### An adjective relates to nouns
Adjectives relate to nouns or pronouns: as,
- \"Miserable comforters are you all.\"---Job, xvi, 2.
- \"No worldly enjoyments are adequate to the high desires and powers
of an immortal spirit.\"---Blair.
- \"Whatever faction\'s partial notions are, no hand is wholly
innocent in war.\"---Rowe\'s Lucan, B. vii, l. 191.
#### An intervening verb
An adjective sometimes relates to a phrase or sentence which is made the
subject of an intervening verb: as,
- \"To insult the afflicted, is impious.\"---Dillwyn.
- \"That he should refuse, is not strange.\"
- \"To err is human.\"
#### Combined arithmetical numbers
In combined arithmetical numbers, one adjective often relates to
another, and the whole phrase, to a subsequent noun: as,
- \"One thousand four hundred and fifty-six men,\"
- \"Six dollars and eighty-seven and a half cents for every five
days\' service,\"
- \"In the one hundred and twenty-second year,\"
- \"One seven times more than it was wont to be heated.\"---Daniel,
iii, 19.
#### A being or action in the abstract
With an infinitive or a participle denoting being or action in the
abstract, an adjective is sometimes also taken abstractly; that is,
without reference to any particular noun, pronoun, or other subject: as,
- \"To be sincere, is to be wise, innocent, and safe.\"---Hawkesworth.
- \"Capacity marks the abstract quality of being able to receive or
hold.\"---Crabb\'s Synonymes.
- \"Indeed, the main secret of being sublime, is to say great things
in few and plain words.\"---Hiley\'s Gram., p. 215.
- \"Concerning being free from sin in heaven, there is no
question.\"---Barclay\'s Works, iii, 437.
- Better, \"Concerning freedom from sin,\" etc.
#### Abstract nouns
Adjectives are sometimes substituted for their corresponding abstract
nouns; perhaps, in most instances, elliptically: as,
- \"The sensations of sublime and beautiful are not always
distinguished by very distant boundaries.\"---Blair\'s Rhet., p. 47.
- \"The faults opposite to the sublime are chiefly two: the frigid,
and the bombast.\"---Ib., p. 44.
- Better, \"The faults opposite to sublimity, are chiefly two;
frigidity and bombast.\"
- \"Yet the ruling character of the nation was that of barbarous and
cruel.\"---Brown\'s Estimate, ii, 26.
- \"In a word, agreeable and disagreeable are qualities of the objects
we perceive.\"---Kames, El. of Crit., i, 99.
- \"Polished, or refined, was the idea which the author had in
view.\"---Blair\'s Rhet., p. 219.
### An adjective placed before noun
The adjective is generally placed immediately before its noun: as,
- \"Vain man! is grandeur given to gay attire?\"---Beattie.
Adjectives can also come before the subject:
- \"The red dog likes chocolate.\"
- \"The tiny man had a height problem.\"
In the following instances the adjective is placed after the word to
which it relates:
#### Pronouns
Those adjectives which relate to pronouns, most commonly follow them:
as,
- \"They left me weary on a grassy turf.\"---Milton.
But to both these general rules there are many exceptions; for the
position of an adjective may be varied by a variety of circumstances,
not excepting the mere convenience of emphasis: as,
- \"And Jehu said, to which of all us?\"---2 Kings, ix, 5.
#### Words which depend on the adjective
When other words depend on the adjective, or stand before it to qualify
it: as,
- \"A mind conscious of right,\"
- \"A wall three feet thick,\"
- \"A body of troops fifty thousand strong.\"
#### The quality which results from action
When the quality results from an action, or receives its application
through a verb or participle: as,
- \"Virtue renders life happy.\"
- \"He was in Tirzah, drinking himself drunk in the house of
Arza.\"---1 Kings, xvi, 9.
- \"All men agree to call vinegar sour, honey sweet, and aloes
bitter.\"---Burke, on Taste, p. 38.
- \"God made you perfect, not immutable.\"---Milton.
#### The quality which excites admiration
When the quality excites admiration, and the adjective would thus be
more clearly distinctive: as,
- \"Goodness infinite,\"
- \"Wisdom unsearchable.\"---Murray.
#### A verb
When a verb comes between the adjective and the noun: as,
- \"Truth stands independent of all external things.\"---Burgh.
- \"Honour is not seemly for a fool.\"---Solomon.
#### The adjective formed by prefix
When the adjective is formed by means of the prefix a: as, afraid,
alert, alike, alive, alone, asleep, awake, aware, averse, ashamed,
askew. To these may be added a few other words: as, else, enough,
extant, extinct, fraught, pursuant.
#### The nature of a participle
When the adjective has the nature, but not the form, of a participle:
as,
- \"A queen regnant,\"
- \"The prince regent,\"
- \"The heir apparent,\"
- \"A lion, not rampant, but couchant or dormant,\"
- \"For the time then present.\"
#### Poetry
In some instances, the adjective may either precede or follow its noun;
as, in poetry, provided the sense be obvious: as,
- \"Will you to the isles atlantic, to the rich hesperian clime, fly
in the train of Autumn?\"---Akenside, P. of I., Book i, p. 27.
- \"Will you fly with laughing Autumn to the atlantic isles, and range
with him the hesperian field?\"---Id. Bucke\'s Gram., p. 120.
#### Technical usage
When technical usage favours one order, and common usage another: as,
- \"A notary public,\" or, \"A public notary;\"
- \"The heir presumptive,\" or, \"The presumptive heir.\"
#### An adverb
When an adverb precedes the adjective: as,
- \"A Being infinitely wise,\" or,
- \"An infinitely wise Being.\"
Murray, Comly, and others, here approve only the former order; but the
latter is certainly not ungrammatical.
#### Belonging to the same noun
When several adjectives belong to the same noun: as,
- \"The red, hungry dog ate the chocolate.\"
- \"The car is red, slow and very old.\"
- \"A woman, modest, sensible, and virtuous,\" or, \"A modest,
sensible, and virtuous woman.\"
#### An emphatic adjective
When the adjective is emphatic, it may be foremost in the sentence,
though the natural order of the words would bring it last: as,
- \"Weighty is the anger of the righteous.\"---Bible.
- \"Blessed are the pure in heart.\"---Ib.
- \"Great is the earth, high is the heaven, swift is the sun in his
course.\"---1 Esdras, iv, 34.
- \"The more laborious the life is, the less populous is the
country.\"---Goldsmith\'s Essays, p. 151.
#### A part of the object or predicate
When the adjective and its noun both follow a verb as parts of the
predicate, either may possibly come before the other, yet the
arrangement is fixed by the sense intended. Thus, there is a great
difference between the following assertions:
- \"We call the boy good,\"
- \"We call the good boy.\"
#### An equivalent to an adverb
By an ellipsis of the noun, an adjective with a preposition before it,
is sometimes equivalent to an adverb: as,
- \"In particular;\" that is, \"In a particular manner;\" equivalent
to \"Particularly\".
- So \"In general\" is equivalent to \"Generally\".
## Pronoun antecedents
A pronoun must agree with its **antecedent**, or the noun or pronoun
which it represents, in person, number, and gender: as,
- \"This is the friend of whom I spoke; he has just arrived.\"
- \"This is the book which I bought; it is an excellent work.\"
- \"You, therefore, who love mercy, teach your sons to love it
too.\"---Cowper.
- \"Speak you, whose thoughts at humble peace repine, shall Wolsey\'s
wealth with Wolsey\'s end be yours?\"---Dr. Johnson.
### Something indefinite
When a pronoun stands for some person or thing **indefinite**, or
unknown to the speaker, the person, number, and gender, are rather
assumed in the pronoun, than regulated by an antecedent: as,
- \"I do not care who knows it.\"---Steele.
- \"Who touched me? Tell me who it was.\"
- \"We have no knowledge how, or by whom, it is inhabited.\"---Abbot:
Joh. Dict.
### The neuter pronoun
The neuter pronoun may be applied to a young child, or to other
creatures masculine or feminine by nature, when they are not obviously
distinguishable with regard to sex: as,
- \"Which is the real friend to the child, the person who gives it the
sweetmeats, or the person who, considering only its health, resists
its importunities?\"---Opis.
- \"He loads the animal he is showing me, with so many trappings and
collars, that I cannot distinctly view it.\"---Murray\'s Gram.,
p. 301.
- \"The nightingale sings most sweetly when it sings in the
night.\"---Bucke\'s Gram., p. 52.
### The pronoun it
The pronoun it is often used without a definite reference to any
antecedent, and is sometimes a mere expletive, and sometimes the
representative of an action expressed afterwards by a verb: as,
- \"Whether she grapple it with the pride of philosophy.\"---Chalmers.
- \"Seeking to lord it over God\'s heritage.\"---The Friend, vii, 253.
- \"It is not for kings, O Lemuel, it is not for kings to drink wine,
nor for princes strong drink.\"---Prov., xxxi, 4.
- \"Having no temptation to it, God cannot act unjustly without
defiling his nature.\"---Brown\'s Divinity, p. 11.
- \"Come, and trip it as you go, on the light fantastic
toe.\"---Milton.
### The adjective many
A singular antecedent with the adjective many, sometimes admits a plural
pronoun, but never in the same clause: as,
- \"Hard has been the fate of many a great genius, that while they
have conferred immortality on others, they have wanted themselves
some friend to embalm their names to posterity.\"---Welwood\'s Pref.
to Rowe\'s Lucan.
- \"In Hawick twinkled many a light, behind him soon they set in
night.\"---W. Scott.
### Enallage
When a plural pronoun is put by **enallage** for the singular, it does
not agree with its noun in number, because it still requires a plural
verb: as,
- \"We \[Lindley Murray\] have followed those authors, who appear to
have given them the most natural and intelligible
distribution.\"---Murray\'s Gram., 8vo, p. 29.
- \"We shall close our remarks on this subject, by introducing the
sentiments of Dr. Johnson respecting it.\"---Ib.
- \"My lord, you know I love you.\"---Shakespeare.
### The antecedent taken in another sense
The pronoun sometimes disagrees with its antecedent in one sense,
because it takes it in another: as,
- \"I have perused Mr. Johnson\'s Grammatical Commentaries, and find
it a very laborious, learned, and useful work.\"---Tho. Knipe, D. D.
- \"Lamps is of the plural number, because it means more than
one.\"---Smith\'s New Gram., p. 8.
- \"Man is of the masculine gender, because it is the name of a
male.\"---Ib.
- \"The Utica Sentinel says it has not heard whether the wounds are
dangerous.\"---Evening Post.
- Better, \"The editor of the Utica Sentinel says, he has not heard,\"
etc.
- \"There is little Benjamin with their ruler.\"---Psalms, lxviii, 27.
- \"Her end when emulation misses, she turns to envy, stings, and
hisses.\"---Swift\'s Poems, p. 415.
### Nominatives
Nominatives: (i.e., words parsed as nominatives after the verbs, though
mostly transposed:)
- \"Who are you?\"---Bible.
- \"What were we?\"---Ib.
- \"Do not tell them who I am.\"
- \"Let him be who he may, he is not the honest fellow that he
seemed.\"
- \"The general conduct of mankind is neither what it was designed,
nor what it ought to be.\"
### Absolute nominatives
This construction of the relative is a latinism, and very seldom used by
the best writers.
- \"There are certain bounds to imprudence, which being transgressed,
there remains no place for repentance in the natural course of
things.\"---Bp. Butler.
- \"Which being so, it need not be any wonder, why I
should.\"---Walker\'s Particles, Pref., p. xiv.
- \"He offered an apology, which not being admitted, he became
submissive.\"---Murray\'s Key, p. 202.
### Possessives
- \"The chief man of the island, whose name was Publius.\"---Acts.
- \"Despair, a cruel tyrant, from whose prisons none can
escape.\"---Dr. Johnson.
- \"To contemplate on Him whose yoke is easy and whose burden is
light.\"---Steele.
### Objectives
- \"Those whom she persuaded.\"---Dr. Johnson.
- \"The cloak that I left at Troas.\"---St. Paul.
- \"By the things which he suffered.\"---Id.
- \"A man whom there is reason to suspect.\"
- \"What are we to do?\"---Burke.
- \"Love refuses nothing that love sends.\"---Gurnall.
- \"The first thing, says he, is, to choose some maxim or point of
morality; to inculcate which, is to be the design of his
work.\"---Blair\'s Rhet., p. 421.
- \"Whomsoever you please to appoint.\"---Lowth.
- \"Whatsoever he does, shall prosper.\"---Bible.
- \"What we are afraid to do before men, we should be afraid to think
before God.\"---Sibs.
- \"Shall I hide from Abraham that thing which I do?\"---Gen., xviii,
32.
- \"Shall I hide from Abraham what I am going to do?\"
- \"Call imperfection what you fancy such.\"---Pope.
### Neuter verbs
Pronouns parsed as objectives after **neuter verbs**, though they stand
before them:
- \"He is not the man that I took him to be.\"
- \"Whom did you suppose me to be?\"
- \"If the lad ever become what you wish him to be.\"
- \"To whom shall we go?\"---Bible.
- \"The laws by which the world is governed, are general.\"---Bp.
Butler.
- \"Whom he looks on as his defender.\"---Addison.
- \"That secret heaviness of heart which unthinking men are subject
to.\"---Id.
- \"I cannot but think the loss of such talents as the man of whom I
am speaking was master of, a more melancholy instance.\"---Steele.
- \"Grammar is the solid foundation on which all other science
rests.\"---Buchanan\'s Eng. Synt., p. xx.
### Familiar language
In familiar language, the relative of the objective case is frequently
understood: as,
- \"The man \[whom\] I trust.\"---Cowper.
- \"Here is the letter \[which\] I received.\"
- \"This is the man they hate. These are the goods they bought. Are
these the Gods they worship? Is this the woman you saw?\"---Ash\'s
Gram., p. 96.
In grave writing, or deliberate discourse, it is much better to express
the relative. The omission of it is often attended with some obscurity:
as,
- \"The next error \[that\] I shall mention \[,\] is a capital
one.\"---Kames, El. of Crit., ii, 157.
- \"It is little \[that\] we know of the divine
perfections.\"---Scougal, p. 94.
- \"The faith \[which\] we give to memory, may be thought, on a
superficial view, to be resolvable into consciousness, as well as
that \[which\] we give to the immediate impressions of
sense.\"---Campbell\'s Rhet., p. 53.
- \"We speak that \[which\] we do know, and testify that \[which\] we
have seen.\"---John, iii, 11.
### A relative in the nominative case
The omission of a relative in the nominative case, is almost always
inelegant: as,
- \"This is the worst thing \[that\] could happen.\"
- \"There were several things \[which\] brought it on
me.\"---Pilgrim\'s Progress, p. 162.
This ellipsis may occur after but or than, and it is sometimes allowed
in poetry: as,
- \"\[There is\] No person of reflection but \[who\] must be sensible,
that an incident makes a stronger impression on an eyewitness, than
when heard at second hand.\"---Kames, El. of Crit., ii, 257.
- \"In this it is God directs, in that it is man.\"---Pope, on Man.
- \"Abuse on all he loved, or loved him, spread.\"---Id., to
Arbuthnot.
- \"There\'s nothing blackens like the ink of fools.\"---Id., to
Augustus.
### A collective noun
When the antecedent is a collective noun conveying the idea of
plurality, the pronoun must agree with it in the plural number: as,
- \"The council were divided in their sentiments.\"
- \"The Christian world are beginning to awake out of their
slumber.\"---C. Simeon.
- \"Whatever Adam\'s posterity lost through him, that and more they
gain in Christ.\"---J. Phipps.
- \"To this, one pathway gently-winding leads, where march a train
with baskets on their heads.\"---Pope, Iliad, B. xviii, l. 657.
### Antecedents connected by or
When a pronoun has two or more antecedents connected by or or nor, it
must agree with them singly, and not as if taken together: as,
- \"James or John will favour us with his company.\"
- \"Neither wealth nor honour can secure the happiness of its
votaries.\"
- \"What virtue or what mental grace, but men unqualified and base
will boast it their possession?\"---Cowper, on Friendship.
### Antecedents connected by and
When a pronoun has two or more antecedents connected by and, it must
agree with them jointly in the plural, because they are taken together:
as,
- \"Minos and Thales sung to the lyre the laws which they
composed.\"---Strabo: Blair\'s Rhet., p. 379.
- \"Saul and Jonathan were lovely and pleasant in their lives, and in
their death they were not divided.\"---2 Sam., i, 23.
- \"Rhesus and Rhodius then unite their rills, Caresus roaring down
the stony hills.\"---Pope, Il., B. xii, l. 17.
#### One person or thing
When two or more antecedents connected by and serve merely to describe
one person or thing, they are either in apposition or equivalent to one
name, and do not require a plural pronoun: as,
- \"This great philosopher and statesman continued in public life till
his eighty-second year.\"
- \"The same Spirit, light, and life, which enlightens, also
sanctifies, and there is not another.\"---Penington.
- \"My Constantius and Philetus confesses me two years older when I
wrote it.\"---Cowley\'s Preface.
- \"Remember these, O Jacob and Israel! for you are my
servant.\"---Isaiah, xliv, 21.
- \"In that strength and cogency which renders eloquence
powerful.\"---Blair\'s Rhet., p. 252.
#### Emphatically distinguished
When two antecedents connected by and are emphatically distinguished,
they belong to different propositions, and, if singular, do not require
a plural pronoun: as,
- \"The butler, and not the baker, was restored to his office.\"
- \"The good man, and the sinner too, shall have his reward.\"
- \"Truth, and truth only, is worth seeking for its own sake.\"
- \"It is the sense in which the word is used, and not the letters of
which it is composed, that determines what is the part of speech to
which it belongs.\"---Cobbett\'s Gram., 130.
#### Each, every, or no
When two or more antecedents connected by and are preceded by the
adjective each, every, or no, they are taken separately, and do not
require a plural pronoun: as,
- \"Every plant and every tree produces others after its own kind.\"
- \"It is the cause of every reproach and distress which has attended
your government.\"---Junius, Let. xxxv.
But if the latter be a collective noun, the pronoun may be plural: as,
- \"Each minister and each church act according to their own
impressions.\"---Dr. M\'Cartee.
## The finite verb
Every finite verb must agree with its subject, or nominative, in person
and number: as,
- \"I know; You know; He knows;\"
- \"The bird flies; The birds fly.\"
- \"Our fathers\' fertile fields by slaves are tilled, and Rome with
dregs of foreign lands is filled.\"---Rowe\'s Lucan, B. vii, l. 600.
When the nominative is a collective noun conveying the idea of
plurality, the verb must agree with it in the plural number: as,
- \"The council were divided.\"
- \"The college of cardinals are the electors of the
pope.\"---Murray\'s Key, p. 176.
- \"Quintus Curtius relates, that a number of them were drowned in the
river Lycus.\"---Home\'s Art of Thinking, p. 125.
- \"Yon host come learned in academic rules.\"---Rowe\'s Lucan, vii,
401.
- \"While heaven\'s high host on hallelujahs live.\"---Young\'s N.
Th., iv, 378.
### Nominatives connected by and
When a verb has two or more nominatives connected by and, it must agree
with them jointly in the plural, because they are taken together: as,
- \"True rhetoric and sound logic are very nearly allied.\"---Blair\'s
Rhet., p. 11.
- \"Aggression and injury in no case justify
retaliation.\"---Wayland\'s Moral Science, p. 406.
- \"Judges and senates have been bought for gold, esteem and love were
never to be sold.\"---Pope.
#### One person or thing
When two nominatives connected by and serve merely to describe one
person or thing, they are either in apposition or equivalent to one
name, and do not require a plural verb: as,
- \"Immediately comes a hue and cry after a gang of
thieves.\"---L\'Estrange.
- \"The hue and cry of the country pursues him.\"---Junius, Letter
xxiii.
- \"Flesh and blood \[i.e. man, or man\'s nature,\] has not revealed
it to you.\"---Matt., xvi, 17.
- \"Descent and fall to us is adverse.\"---Milton, P. L., ii, 76.
- \"This philosopher and poet was banished from his country.\"
- \"Such a Saviour and Redeemer is actually provided for
us.\"---Gurney\'s Essays, p. 386.
- \"Let us then declare what great things our God and Saviour has done
for us.\"---Dr. Scott, on Luke viii.
- \"Toll, tribute, and custom, was paid to them.\"---Ezra, iv, 20.
- \"Whose icy current and compulsive course never feels retiring ebb,
but keeps due on.\"---Shakespeare.
#### Emphatically distinguished
When two nominatives connected by and, are emphatically distinguished,
they belong to different propositions, and, if singular, do not require
a plural verb: as,
- \"Ambition, and not the safety of the state, was
concerned.\"---Goldsmith.
- \"Consanguinity, and not affinity, is the ground of the
prohibition.\"---Webster\'s Essays, p. 324.
- \"But a modification, and oftentimes a total change, takes
place.\"---Maunder.
- \"Somewhat, and, in many circumstances, a great deal too, is put on
us.\"---Butler\'s Analogy, p. 108.
- \"Disgrace, and perhaps ruin, was the certain consequence of
attempting the latter.\"---Robertson\'s America, i, 434.
- \"Ay, and no too, was no good divinity.\"---Shakespeare.
- \"Love, and love only, is the loan for love.\"---Young.
#### Each, every, or no
When two or more nominatives connected by and are preceded by the
adjective each, every, or no, they are taken separately, and do not
require a plural verb: as,
- \"When no part of their substance, and no one of their properties,
is the same.\"---Bp. Butler.
- \"Every limb and feature appears with its respective
grace.\"---Steele.
- \"Every person, and every occurrence, is beheld in the most
favourable light.\"---Murray\'s Key, p. 190.
- \"Each worm, and each insect, is a marvel of creative power.\"
- \"Whose every look and gesture was a joke to clapping theatres and
shouting crowds.\"---Young.
When the verb separates its nominatives, it agrees with that which
precedes it, and is understood to the rest: as,
- \"The earth is the Lord\'s, and the fullness thereof.\"---Murray\'s
Exercises, p. 36.
- \"Disdain forbids me, and my dread of shame.\"---Milton.
- \"Forth in the pleasing spring, your beauty walks, your tenderness,
and love.\"---Thomson.
### Nominatives connected by or
When a verb has two or more nominatives connected by or or nor, it must
agree with them singly, and not as if taken together: as,
- \"Fear or jealousy affects him.\"---W. Allen\'s Gram., p. 133.
- \"Nor eye, nor listening ear, an object finds: creation
sleeps.\"---Young.
- \"Neither character nor dialogue was yet understood.\"---L.
Murray\'s Gram., p. 151.
- \"The wife, where danger or dishonour lurks, safest and seemliest by
her husband stays.\"---Milton, P. L., ix, 267.
## Infinitives
### The infinitive mood
The infinitive mood is governed in general by the preposition to, which
commonly connects it to a finite verb: as,
- \"I desire to learn.\"---Dr. Adam.
- \"Of me the Roman people have many pledges, which I must strive,
with my utmost endeavours, to preserve, to defend, to confirm, and
to redeem.\"---Duncan\'s Cicero, p. 41.
- \"What if the foot, ordained the dust to tread, or hand to toil,
aspired to be the head?\"---Pope.
The active verbs, bid, dare, feel, hear, let, make, need, see, and their
participles, usually take the infinitive after them without the
preposition to: as,
- \"If he bade you depart, how dare you stay?\"
- \"I dare not let my mind be idle as I walk in the
streets.\"---Cotton Mather.
- \"Your Hector, wrapt in everlasting sleep, shall neither hear you
sigh, nor see you weep.\" ---Pope\'s Homer.
Though the infinitive is commonly made an adjunct to some finite verb,
yet it may be connected to almost all the other parts of speech. The
preposition to being its only and almost universal index; unless the
word about, in such a situation, is a preposition.
Anciently, the infinitive was sometimes preceded by for as well as to:
as,
- \"I went up to Jerusalem for to worship.\"---Acts, xxiv, 11.
- \"What went you out for to see?\"---Luke, vii, 26.
- \"And stood up for to read.\"---Luke, iv, 16.
It seems practicable to subjoin the infinitive to every one of the ten
parts of speech, except the article: as,
#### Noun
- \"If there is any precept to obtain felicity.\"---Hawkesworth.
- \"It is high time to awake out of sleep.\"---Rom., xiii, 11.
- \"To flee from the wrath to come.\"---Matt., iii, 7.
#### Adjective
- \"He seemed desirous to speak, yet unwilling to
offend.\"---Hawkesworth.
- \"He who is the slowest to promise, is the quickest to
perform.\"---Art of Thinking, p. 35.
#### Pronoun
- \"I discovered him to be a scholar.\"---W. Allen\'s Gram., p. 166.
- \"Is it lawful for us to give tribute to Caesar?\"---Luke, xx, 22.
- \"Let me desire you to reflect impartially.\"---Blair: Murray\'s
Eng. Reader, p. 77.
- \"Whom have you then or what to accuse?\"---Milton, P. L., iv, 67.
#### Finite verb
- \"Then Peter began to rebuke him.\"---Matt., xvi, 22.
- \"The Son of man is come to seek and to save that which was
lost.\"---Luke, xix, 10.
#### Another infinitive
- \"To go to enter into Egypt.\"---Jer., xli, 17.
- \"We are not often willing to wait to consider.\"---J. Abbott.
- \"For what had he to do to chide at me?\"---Shak.
#### Participle
- \"Still threatening to devour me.\"---Milton.
- \"Or as a thief bent to unhoard the cash of some rich
burgher.\"---Id.
#### Adverb
- \"She is old enough to go to school.\"
- \"I know not how to act.\"---Nutting\'s Gram., p. 106.
- \"Tell me when to come, and where to meet you.\"
- \"He has not where to lay his head.\"
#### Conjunction
- \"He knows better than to trust you.\"
- \"It was so hot as to melt these ornaments.\"
- \"Many who praise virtue, do no more than praise it.\"---Dr.
Johnson.
#### Preposition
- \"I was about to write.\"---Rev., x, 4.
- \"Not for to hide it in a hedge.\"---Burns\'s Poems, p. 42.
- \"Amatum iri, to be about to be loved.\"---Adam\'s Gram., p. 95.
#### Interjection
- \"O to forget her!\"---Young\'s Night Thoughts.
### The uses of the infinitive
The infinitive is a verb, without affirmation, without person or number,
and therefore without the agreement peculiar to a finite verb. But, in
most instances, it is not without limitation of the being, action, or
passion, to some persons or things, that are said, supposed, or denied,
to be, to act, or to be acted on. Whenever it is not thus limited, it is
taken abstractly, and has some resemblance to a noun. Even then, the
active infinitive may govern the objective case. The uses of the
infinitive are many and various. The following are the chief of the
things for which it may stand:
#### Supplement to another verb
For the supplement to another verb, to complete the sense: as,
- \"Loose him, and let him go.\"---John, xi, 44.
- \"They that go to seek mixed wine.\"---Prov., xxiii, 30.
- \"His hands refuse to labour.\"---Ib., xxi, 25.
- \"If you choose to have those terms.\"---Tooke\'s D. P., ii, 374.
- \"How our old translators first struggled to express this.\"---Ib.,
ii, 456.
- \"To any one who will please to examine our language.\"---Ib., ii,
444.
- \"They are forced to give up at last.\"---Ib., ii, 375.
- \"Which ought to be done.\"---Ib., ii, 451.
- \"Which came to pass.\"---Acts, xi, 28.
- \"I dare engage to make it out.\"---Swift.
#### A purpose
For the purpose, or end, of that to which it is added: as,
- \"Each has employed his time and pains to establish a
criterion.\"---Tooke\'s D. P., ii, 374.
- \"I shall not stop now, to assist in their elucidation.\"---Ib., ii,
75.
- \"Our purposes are not endowed with words to make them
known.\"---Ib., ii, 74.
- \"A tool is some instrument taken up to work with.\"---Ib., ii, 145.
- \"Labour not to be rich.\"---Prov., xxiii, 4.
- \"I flee to you to hide me.\"---Ps., cxliii, 9.
- \"Evil shall hunt the violent man to overthrow him.\"---Ib., cxl,
11.
#### Object of an affection or passion
For the object of an affection or passion: as,
- \"He loves to ride.\"
- \"I desire to hear her speak again.\"---Shale.
- \"If we wish to avoid important error.\"---Tooke\'s D. P., ii, 3.
- \"Who rejoice to do evil.\"---Prov., ii, 14.
- \"All agreeing in earnestness to see him.\"---Shak.
- \"Our curiosity is raised to know what lies beyond.\"---Kames, El.
of Crit., ii, 335.
#### Cause of an affection or passion
For the cause of an affection or passion: as,
- \"I rejoice to hear it.\"
- \"By which I hope to have laid a foundation.\"---Blair\'s Rhet.,
p. 34.
- \"For he made me mad, to see him shine so brisk, and smell so
sweet.\"---Beauties of Shak., p. 118.
- \"You did eat strange flesh, which some did die to look on.\"---Ib.,
p. 182.
- \"They grieved to see their best allies at variance.\"---Rev. W.
Allen\'s Gram., p. 165.
#### Subject of a proposition
For the subject of a proposition, or the chief term in such subject: as,
- \"To steal is sinful.\"
- \"To do justice and judgement, is more acceptable to the Lord than
sacrifice.\"---Prov., xxi, 3.
- \"To do right, is, to do that which is ordered to be
done.\"---Tooke\'s D. P., ii, 7.
- \"To go to law to plague a neighbour, has in it more of malice, than
of love to justice.\"---Seattle\'s Mor. Sci., i, 177.
#### Predicate or object of a proposition
For the predicate of a proposition, or the chief term in such predicate:
as,
- \"To enjoy is to obey.\"---Pope.
- \"The property of rain is to wet, and fire, to burn.\"---Beauties of
Shak., p. 15.
- \"To die is to be banished from myself.\"---Ib., p. 82.
- \"The best way is, to slander Valentine.\"---Ib., p. 83.
- \"The highway of the upright is to depart from evil.\"---Prov., xvi,
17.
#### A coming event
For a coming event, or what will be: as,
- \"A mutilated structure soon to fall.\"---Cowper.
- \"He being dead, and I speedily to follow him.\"---Tooke\'s D. P.,
ii, 111.
- \"She shall rejoice in time to come.\"---Prov., xxxi, 25.
- \"Things present, or things to come.\"---1 Cor., iii, 22.
#### A necessary event
For a necessary event, or what ought to be: as,
- \"It is to be remembered.\"
- \"It is never to be forgotten.\"---Tooke\'s D. P., ii, 2.
- \"An oversight much to be deplored.\"---Ib., ii, 460.
- \"The sign is not to be used by itself, or to stand alone; but is to
be joined to some other term.\"---Ib., ii, 372.
- \"The Lord\'s name is to be praised.\"---Ps., cxiii, 3.
#### Something previously suggested
For what is previously suggested by another word: as,
- \"I have faith to believe.\"
- \"The glossarist did well here not to yield to his
inclination.\"---Tooke\'s D. P., ii, 329.
- \"It is a good thing to give thanks to the Lord.\"---Ps., xcii, 1.
- \"It is as sport to a fool to do mischief.\"---Prov., x, 23.
- \"They have the gift to know it.\"---Shak.
- \"We have no remaining occupation but to take care of the
public.\"---Art of Thinking, p. 52.
#### Term of comparison or measure
For a term of comparison or measure: as,
- \"He was so much affected as to weep.\"
- \"Who could do no less than furnish him.\"---Tooke\'s D. P., ii,
408.
- \"I shall venture no farther than to explain the nature and
convenience of these abbreviations.\"---Ib., ii, 439.
- \"I have already said enough to show what sort of operation that
is.\"---Ib., ii, 358.
## Participles
The regular syntax of the participle, is twofold; being sometimes that
of simple relation to a noun or a pronoun that precedes it, and
sometimes that of government, or the state of being governed by a
preposition. In the former construction, the participle resembles an
adjective; in the latter, it is more like a noun, or like the infinitive
mood. To these constructions, some add others less regular: using the
participle as the subject of a finite verb, as the object of a
transitive verb, or as a nominative after a neuter verb.
Participles relate to nouns or pronouns, or else are governed by
prepositions: as,
- \"Elizabeth\'s tutor, at one time paying her a visit, found her
employed in reading Plato.\"---Hume.
- \"I have no more pleasure in hearing a man attempting wit and
failing, than in seeing a man trying to leap over a ditch and
tumbling into it.\"---Dr. Johnson.
- \"Now, raised on Tyre\'s sad ruins, Pharaoh\'s pride soared high,
his legions threatening far and wide.\"---Dryden.
### A preceding phrase
A participle sometimes relates to a preceding phrase or sentence, of
which it forms no part: as,
- \"I then quit the society; to withdraw and leave them to themselves,
appearing to me a duty.\"
- \"It is almost exclusively on the ground we have mentioned, that we
have heard his being continued in office defended.\"---Professors\'
Reasons, p. 23.
- Better, \"His continuance in office,\" or, \"The continuing of him
in office.\"
- \"But ever to do ill our sole delight, as being the contrary to his
high will.\"---Milton.
### A being or action in the abstract
With an infinitive denoting being or action in the abstract, a
participle is sometimes also taken abstractly; that is, without
reference to any particular noun, pronoun, or other subject: as,
- \"To seem compelled, is disagreeable.\"
- \"To keep always praying aloud, is plainly impossible.\"
- \"It must be disagreeable to be left pausing on a word which does
not, by itself, produce any idea.\"---Murray\'s Gram., 8vo, p. 323.
- \"To praise him is to serve him, and fulfill, doing and suffering,
his unquestioned will.\"---Cowper, Vol. i, p. 88.
### Substitute for the infinitive mood
The participle is often used irregularly, as a substitute for the
infinitive mood, to which it is sometimes equivalent without
irregularity: as,
- \"I saw him enter, or entering.\"---Grant\'s Lat. Gram., p. 230.
- \"He is afraid of trying, or to try.\"---Ibid.
- \"Sir, said I, if the case stands thus, it is dangerous
drinking.\"---Collier\'s Tablet of Cebes.
- \"It will be but ill venturing your soul on that.\"---Bunyan\'s Law
and Grace, p. 27.
- \"Describing a past event as present, has a fine effect in
language.\"---Kames, El. of Crit., i, 93.
- \"In English likewise it deserves remarking.\"---Harris\'s Hermes,
p. 232.
- \"Bishop Atterbury deserves being particularly
mentioned.\"---Blair\'s Rhet., p. 291.
- \"This, however, is in effect no more than enjoying the sweet that
predominates.\"---Campbell\'s Rhet., p. 43.
- \"Habits are soon assumed; but when we strive to strip them off, it
is being flayed alive.\"---Cowper, Vol. i, p. 44
### A participle which is treated as a noun
Another frequent irregularity in the construction of participles, is the
practice of treating them essentially as nouns, without taking from them
the regimen and adjuncts of participles: as,
- \"Your having been well educated will be a great
recommendation.\"---W. Allen\'s Gram., p. 171.
- Better, \"Your excellent education,\" or \"That you have been well
educated, will be,\" etc.
- \"It arises from sublimity\'s expressing grandeur in its highest
degree.\"---Blair\'s Rhet., p. 29.
- \"Concerning the separating by a circumstance, words intimately
connected.\"---Kames, El. of Crit., Vol. ii, p. 104.
- \"As long as there is any hope of their keeping pace with
them.\"---Literary Convention, p. 114.
- \"Which could only arise from his knowing the secrets of all
hearts.\"---West\'s Letters to a Young Lady, p. 180.
- \"But this again is talking quite at random.\"---Butler\'s Analogy,
p. 146.
- \"My being here it is, that holds you hence.\"---Shak.
- \"Such, but by foils, the clearest lustre see, and deem aspersing
others, praising you.\"---Savage, to Walpole.
## Adverbs
The syntax of an adverb consists in its simple relation to a verb, a
participle, an adjective, or whatever else it qualifies.
Adverbs relate to verbs, participles, adjectives, or other adverbs: as,
- \"Any passion that habitually discomposes our temper, or unfits us
for properly discharging the duties of life, has most certainly
gained a very dangerous ascendency.\"---Blair.
- \"How blessed this happy hour, should he appear, dear to us all, to
me supremely dear!\"---Pope\'s Homer.
### Independent adverbs
The adverbs yes, ay, and yea, expressing a simple affirmation, and the
adverbs no and nay, expressing a simple negation, are always
independent. They generally answer a question, and are equivalent to a
whole sentence. Is it clear, that they ought to be called adverbs? No.
- \"Can honour set to a leg? No. Or an arm? No. Or take away the grief
of a wound? No. Honour has no skill in surgery then? No.\"---Shak.:
First Part of Hen. IV, Act v, 1.
### The word amen
The word amen, which is commonly called an adverb, is often used
independently at the beginning or end of a declaration or a prayer: as,
- \"Surely, I come quickly. Amen: even so, come Lord Jesus.\"---Rev.,
xxii, 20.
When it does not stand thus alone, it seems in general to be used
substantively: as,
- \"The strangers among them stood on Gerizim, and echoed amen to the
blessings.\"---Wood\'s Dict.
- \"These things say the amen.\"---Rev., iii, 14
### An adverb before a preposition
An adverb before a preposition seems sometimes to relate to the latter,
rather than to the verb or participle to which the preposition connects
its object: as,
- \"This mode of pronunciation runs considerably beyond ordinary
discourse.\"---Blair\'s Rhet., p. 334.
- \"Yea, all along the times of the apostasy, this was the thing that
preserved the witnesses.\"---Penington\'s Works, Vol. iv, p. 12.
- \"Right against the eastern gate, where the great sun begins his
state.\"---Milton, L\'Allegro.
### Much, little, far, and all
The words much, little, far, and all, being originally adjectives, are
sometimes preceded by the negative not, or (except the last) by such an
adverb as too, how, thus, so, or as, when they are taken substantively:
as,
- \"Not all that glitters, is gold.\"
- \"Too much should not be offered at once.\"---Murray\'s Gram.,
p. 140.
- \"Thus far is consistent.\"---Ib., p. 161.
- \"Thus far is right.\"---Lowth\'s Gram., p. 101.
## Conjunctions
The syntax of conjunctions consists in the simple fact, that they link
together such and such terms, and thus \"Mark the connections of human
thought.\"---Beattie.
Conjunctions connect words, sentences, or parts of sentences: as,
- \"Let there be no strife, I pray you, between me and you, and
between my herdmen and your herdmen; for we are brethren.\"---Gen.,
xiii, 8.
- \"Ah! if she lend not arms as well as rules. What can she more than
tell us we are fools?\"---Pope.
### Introducing a sentence
The conjunction that sometimes serves merely to introduce a sentence
which is made the subject or the object of a finite verb: as,
- \"That mind is not matter, is certain.\"
- \"That you have wronged me, does appear in this.\"---Shak.
- \"That time is mine, O Mead! to you, I owe.\"---Young.
### Two corresponding conjunctions
When two corresponding conjunctions occur, in their usual order, the
former should generally be parsed as referring to the latter, which is
more properly the connecting word: as,
- \"Neither sun nor stars in many days appeared.\"---Acts, xxvii, 20.
- \"Whether that evidence has been afforded \[or not,\] is a matter of
investigation.\"---Keith\'s Evidences, p. 18.
### Either and neither
Either, corresponding to or, and neither, corresponding to nor or not,
are sometimes transposed, so as to repeat the disjunction or negation at
the end of the sentence: as,
- \"Where then was their capacity of standing, or his
either?\"---Barclay\'s Works, iii, 359.
- \"It is not dangerous neither.\"---Bolingbroke, on Hist., p. 135.
- \"He is very tall, but not too tall neither.\"---Spect., No. 475.
## Prepositions
The syntax of prepositions consists, not solely or mainly in their power
of governing the objective case, but in their adaptation to the other
terms between which they express certain relations.
Prepositions show the relations of words, and of the things or thoughts
expressed by them: as,
- \"He came from Rome to Paris, in the company of many eminent men,
and passed with them through many cities.\"---Analectic Magazine.
- \"Ah! who can tell the triumphs of the mind, by truth illumined, and
by taste refined?\"---Rogers.
### The object
A noun or a pronoun made the object of a preposition, is governed by it
in the objective case: as,
- \"The temple of fame stands on the grave: the flame that burns on
its altars, is kindled from the ashes of great men.\"---Hazlitt.
- \"Life is his gift, from whom whatever life needs, with every good
and perfect gift, proceeds.\"---Cowper, Vol. i, p. 95.
### The preposition to
The preposition to, before an abstract infinitive, and at the head of a
phrase which is made the subject of a verb, has no proper antecedent
term of relation: as,
- \"To learn to die, is the great business of life.\"---Dillwyn.
- \"Nevertheless, to abide in the flesh, is more needful for
you.\"---St. Paul: Phil., i, 24.
- \"To be reduced to poverty, is a great affliction.\"
- \"Too much to know, is, to know nought but fame; and every godfather
can give a name.\"---Shakespeare.
### The preposition for
The preposition for, when it introduces its object before an infinitive,
and the whole phrase is made the subject of a verb, has properly no
antecedent term of relation: as,
- \"For us to learn to die, is the great business of life.\"
- \"Nevertheless, for me to abide in the flesh, is more needful for
you.\"
- \"For an old man to be reduced to poverty is a very great
affliction.\"
- \"For man to tell how human life began, is hard; for who himself
beginning knew?\"---Milton.
## Interjections
Interjections have no dependent construction; they are put absolute,
either alone, or with other words: as,
- \"O! let not your heart despise me.\"---Dr. Johnson.
- \"O cruel you!\"---Pope, Odys., B. xii, l. 333.
- \"Ah wretched we, poets of earth!\"---Cowley,
- \"Ah Dennis! Gildon ah! what ill-starred rage divides a friendship
long confirmed by age?\"---Pope, Dunciad, B. iii,
## General rules
In the formation of sentences, the **consistency** and adaptation of all
the words should be observed; and a regular, clear, and correspondent
construction should be preserved throughout.
Words that may constitute different **parts of speech**, must not be
left doubtful as to their classification.
The **reference** of words to other words, or their syntactical relation
according to the sense, should never be left doubtful.
A **definition** must include the whole class of things, which it
pretends to define, and exclude everything which comes not under the
name.
A **comparison** is a form of speech which requires some similarity or
common property in the things compared; without which, it becomes a
solecism.
Sentences that convey a meaning manifestly **false**, should be changed,
rejected, or contradicted. They distort language from its only worthy
use; which is, to state facts, and to tell the truth.
Every writer should be careful not to **contradict** himself; for what
is self-contradictory, is both null in argument, and bad in style.
Words that are entirely **needless**, and especially such as encumber
the expression, ought in general to be omitted.
Words **necessary** to the sense, or even to the melody or beauty of a
sentence, ought seldom, if ever, to be omitted.
## References
- A part of the text in this article, was taken from the public domain
English grammar \"The Grammar of English
Grammars\" by Goold Brown,
1851.
- Wiktionary, the free
dictionary
|
# English in Use/Conversation Pieces
## Apologizing
- Excuse me, \...
- Sorry!
- Sorry to interrupt.
- I\'m sorry!
- I\'m so sorry!
- I\'m afraid so.
- I\'m afraid not.
- I apologize.
- I do apologize.
- Please forgive me!
## Expressing Surprise
- Wow!
- You\'ve got to be kidding me!
- I don't believe it!
- That\'s incredible!
- Is that right?
- You\'re joking!
- Really?
- Seriously?
- My goodness!
- Oh my!
- Gosh!
- What a surprise!
- Good heavens! (Use sparingly)
- Well, well, well! (Use sparingly)
## Goodbyes
- Good-bye!
- So long!
- See you!
- See you later!
- See you soon!
- See you tomorrow!
- Cheerio!
- Ta-ta!
- Ta-ra!
- I\'ll be seeing you.
- Good evening.
- Good night.
- Have a good evening!
- Have a good afternoon!
- Come back soon!
- Keep safe!
- Have a safe trip.
- Bye bye
- Toodles!
## Meeting People
- Hello there!
- Pleased to meet you. *informal*
- Pleased to meet you, {sir **or** madam}. *formal*
- It\'s nice meeting you.
- Finally, we meet!
**The following greetings are typically used in formal environments,
however, they can also be used for informal environments but be sure not
to use sir or ma\'am if you know the person well or else it makes the
conversation seem a bit too impersonal.**
- Good afternoon, {name **or** sir **or** madam}
- Good morning, {name **or** sir **or** madam}
- Good evening, {name **or** sir **or** madam}
## Responding to News or Information
- Good for you!
- I'm sorry to hear that.
- Oh, how lovely!
- Sounds great.
- Yes, I suppose you must be.
- Wow! That sounds exciting.
## Responding to Thanks
- You are welcome
- Don\'t mention it
- No problem
- It\'s okay
- It\'s a pleasure
## Saying: That\'s Life
- It was just one of those things.
- That's the way it goes.
- These things happen.
- You know how it is.
## Telephoning
**To ask about someone on the telephone**
- *May I speak to \... , please? (formal)*
- *Is \... there? (informal)*
**To leave a message**
- *Can I leave a message?* (informal)
- *May I leave a message?* (formal)
- *Can you ask \... to call me?*
**To ask someone to repeat something**
- *Could you repeat that, please?* (formal)
- *Would you repeat that, please?* (formal)
- *Pardon?*
- *Excuse me?*
- *I\'m sorry, I didn\'t catch that.*
**Some alternative forms to say \"yes\"**
- *Of course.*
- *Sure.*
- *Yep.*
- *Yup.*
- *Yeah.* (informal)
- *Uh-huh.* (informal)
## Thanking
- Thank you!
- Thanks! (informal)
- Thank you so much!
- Thanks a lot! (if not said with a rising tone, it will often come
across as sarcastic, so be careful with this phrase)
- I don\'t know how to thank you. (extremely thankful, almost always
used after a large gift or favor is given)
{{English in Use/Navigation}}
|
# English in Use/Glossary
------------------------------------------------------------------------
Absolute --- Not immediately dependent on the other parts of the
sentence in government.
Abstract --- Considered apart from any application to a particular
object.
Abstract noun --- A noun that denotes an idea, emotion, feeling, quality
or other abstract or intangible concept.
Active verb --- A verb that expresses action as distinct from mere
existence or state.
Adjective --- A word that modifies a noun or describes a noun's
referent.
Adjunct --- A clause in a sentence that amplifies its meaning.
Adverb --- A word that modifies a verb, adjective, or various other
types of words, phrases, and clauses.
Adverb of cause --- Adverbs of cause are *why, wherefore* and
*therefore*.
Adverb of degree --- Adverbs of degree are those which answer to the
question, how much? how little? or to the idea of more or less.
Adverb of manner --- Adverbs of manner are those which answer to the
question, how? or, by affirming, denying, or doubting, show how a
subject is regarded.
Adverb of place --- Adverbs of place indicate where something happens.
Adverb of time --- Adverbs of time are those which answer to the
question, when? how long? how soon? or how often?
Affirmative --- An answer that shows agreement or acceptance.
Agreement --- Rules that exist in many languages that force some parts
of a sentence to be used or inflected differently depending on certain
attributes of other parts.
Antecedent --- A word, phrase or clause referred to by a pronoun.
Aorist --- A temporal feature of the verb which denotes the speaker\'s
standpoint of the event described by the verb, as from outside of the
event and seeing it as a completed whole.
Aphaeresis --- The loss of letters or sounds from the beginning of a
word, such as the development of special from especial.
Apocope --- The loss or omission of a sound or syllable from the end of
a word.
Apposition --- A construction in which one noun or noun phrase is placed
with another as an explanatory equivalent, both having the same
syntactic function in the sentence.
Appositive --- Of or being in apposition.
Archaism --- The adoption or imitation of archaic words or style.
Arrangement --- Relative position of words in a sentence.
Article --- A part of speech that indicates, specifies and limits a noun
(*a*, *an*, or *the* in English).
Attribute --- A word that qualifies a noun.
Auxiliary --- A verb that accompanies the main verb in a clause in order
to make distinctions in tense, mood, voice or aspect.
Capital --- An uppercase letter.
Cardinal adjective --- A cardinal number used as an adjective.
Case --- A category of nouns, pronouns, or adjectives, specialized
(usually by inflection) to indicate a particular syntactic relation to
other words in a sentence.
Clause --- A word or group of words ordinarily consisting of a subject
and a predicate.
Collective noun --- A noun which, though singular, refers to a group of
things or animals.
Common adjective --- A common adjective is any ordinary epithet, or
adjective denoting quality or situation: as, *good, bad, peaceful,
warlike, eastern, western, outer, inner*.
Common noun --- A noun that can be preceded by an indefinite article,
and denotes any member, or all members of a class; an ordinary noun such
as *dog* or *city*.
Comparative degree --- Adverbial or adjectival forms modified by *more*
or ending in *er*, used when comparing two things.
Comparison --- The ability of adjectives and adverbs to form three
degrees.
Compound --- A lexeme that consists of more than one stem; for example
*laptop*, formed from *lap* and *top*.
Compound adjective --- A compound adjective is one that consists of two
or more words joined together, either by the hyphen or solidly: as,
*nut-brown, laughter-loving, four-footed; threefold, lordlike,
lovesick*.
Compound personal --- A compound personal pronoun. compound personal
pronouns are *myself, yourself, himself, herself, itself*.
Compound relative --- Compound relatives are *whoever, whosoever,
whichever, whichsoever, whatever, whatsoever*.
Compound sentence --- A compound sentence is a sentence which is
composed of at least two independent clauses.
Conjugation --- In some languages, one of several classifications of
verbs according to what inflections they take.
Conjunction --- A word used to join other words or phrases together into
sentences.
Conjunctive adverb --- An adverb that connects two clauses.
Consonant --- A sound that results from the passage of air through
restrictions of the oral cavity; any sound that is not the dominant
sound of a syllable, the dominant sound generally being a vowel.
Continuous tense --- Expressing an ongoing action or state.
Declension --- A way of categorizing nouns, pronouns, or adjectives
according to the inflections they receive.
Defective verb --- A verb with an incomplete conjugation; for example,
one that can only be conjugated in certain persons and numbers.
Definite article --- An article that introduces a noun and specifies it
as the particular noun that is being considered; in English, the only
definite article is the.
Diaeresis --- A diacritic placed over a vowel letter indicating that it
is sounded separately, usually forming a distinct syllable, as in
*naïve, Noël, Brontë*.
Ellipsis --- The omission of a grammatically required word or phrase
that can be implied.
Enallage --- The substitution of one grammatical form for another one.
Finite verb --- A verb that is inflected for person and for tense
according to the rules and categories of the languages in which it
occurs.
First-future tense --- The first-future tense is that which expresses
what will take place hereafter.
Gender --- A division of nouns and pronouns (and sometimes of other
parts of speech), such as masculine, feminine, neuter or common.
Gerund --- A verbal form that functions as a verbal noun. In English, a
gerund has the same spelling as a present participle, but functions
differently.
Government --- That power which one word has over another, to cause it
to assume some particular modification.
Grammar --- A system of rules and principles for speaking and writing a
language.
Hyperbaton --- An inversion of the usual or logical order of words or
phrases, for emphasis or poetic effect.
Imperative mood --- The grammatical mood expressing an order.
Indefinite article --- A word preceding a noun to indicate that the noun
is new or unknown. In English it can be a (before a consonant sound) or
an (before a vowel sound) in the singular; in the plural an article
isn\'t used at all, or the pronoun some is used instead.
Independent clause --- A clause that can stand by itself as a
grammatically viable simple sentence.
Indicative mood --- The mood of a verb used in ordinary factual or
objective statements.
Infinitive --- The uninflected form of a verb. In English, this is
usually formed with the verb stem preceded by \'to\'.
Infinitive mood --- The infinitive of a verb is its basic form with or
without the particle *to*.
Inflection --- A change in the form of a word that reflects a change in
grammatical function.
Interjection --- An exclamation or filled pause; a word or phrase with
no particular grammatical relation to a sentence, often an expression of
emotion.
Interrogative --- A word (pronoun, pronominal adjective, or adverb)
implying interrogation, or used for asking a question: *why, who, when*,
etc.
Introductory phrase --- A phrase or clause that introduces a sentence.
Irregular comparison --- Comparison of adjectives which cannot be
compared regularly.
Irregular verb --- A verb that does not follow the normal rules for its
conjugation.
Italic characters --- A typeface in which the letters slant to the
right.
Letter --- A symbol in an alphabet.
Liquid --- An *l* or *r* sound.
Mimesis --- The representation of aspects of the real world, especially
human actions, in literature and art.
Mood --- A verb form that depends on how its containing clause relates
to the speaker's or writer's wish, intent, or assertion about reality.
Morphology --- The forms of word formation.
Multiplicative adjective --- An adjective which expresses the
multiplicity.
Mute --- A letter that, in a particular word, does not correspond to any
sound in the word\'s pronunciation.
Neuter verb --- A verb that expresses neither action nor passion, but
simply being, or a state of being.
Nominative --- Giving a name; naming; designating; said of that case or
form of a noun which stands as the subject of a finite verb.
Non-finite verb --- A verb form that is not limited by a subject and,
more generally, is not fully inflected by categories that are marked
inflectionally in language, such as tense, aspect, mood, number, gender,
and person.
Note of exclamation --- Punctuation used to denote excitement, surprise
or shock; exclamation point.
Note of interrogation --- The punctuation mark \"?\", used at the end of
a sentence to indicate a question.
Noun --- A word that can be used to refer to a person, place, thing,
quality, or idea; one of the basic parts of speech in many languages,
including English.
Number --- Of a word or phrase, the state of being singular, dual or
plural, shown by inflection.
Numeral --- A numeral adjective.
Numeral adjective --- An adjective that expresses a definite number: as,
*one, two, three, four, five, six*.
Object --- The noun phrase which is an internal complement of a verb
phrase or a prepositional phrase. In a verb phrase with a transitive
action verb, it is typically the receiver of the action.
Objective --- Of, or relating to a noun or pronoun used as the object of
a verb.
Ordinal adjective --- An ordinal number used as an adjective.
Paragoge --- The addition of a sound, syllable or letter to the end of a
word, either through natural development or as a grammatical function.
Parenthetical phrase --- A phrase in the sentence which is not essential
to the meaning of the sentence.
Parsing --- To resolve into its elements, as a sentence, pointing out
the several parts of speech, and their relation to each other by
government or agreement; to analyze and describe grammatically.
Participial adjective --- A participle used as an adjective, such as
drowning in the drowning man and drowned in the drowned man.
Participle --- A form of a verb that may function as an adjective or
noun.
Part of speech --- The function a word or phrase performs in a sentence
or phrase.
Passive voice --- A grammatical voice in which the subject receives the
action of a transitive verb.
Past participle --- A past participle is usually identical to the
verb\'s past tense form, though in irregular verbs the two usually
differ.
Past perfect tense --- Tense of verb conjugated by adding had before the
past participle of a verb.
Perfect tense --- A tense that expresses action completed at the present
time; in English it is formed by using the present tense of have with a
past participle.
Period --- The punctuation mark (".") indicating the end of a sentence
or marking an abbreviation.
Person --- A linguistic category used to distinguish between the speaker
of an utterance and those to whom or about whom he is referring;
implemented in most languages by a variety of pronouns.
Personal --- Denoting person; as, a personal pronoun.
Personification --- A figure of speech, prosopopeia, in which an
inanimate object or an abstraction is given human qualities.
Phrase --- A word or group of words that functions as a single unit in
the syntax of a sentence, usually consisting of a head, or central word,
and elaborating words.
Pleonasm --- A phrase in which one or more words are redundant as their
meaning is expressed elsewhere in the phrase.
Plural --- A word in the form in which it potentially refers to
something other than one person or thing; and other than two things if
the language has a dual form.
Possessive --- A pronoun in the possessive case.
Potential mood --- A verbal construction or form stating something is
possible or probable.
Predicate --- The part of the sentence (or clause) which states
something about the subject.
Prefix --- That which is prefixed; especially one or more letters or
syllables added to the beginning of a word to modify its meaning; as,
*pre* in *prefix*, *con* in *conjure*.
Preposition --- A closed class of non-inflecting words typically
employed to connect a noun or a pronoun, in an adjectival or adverbial
sense, with some other word.
Propositional phrase --- A phrase that has both a preposition and its
object or complement; may be used as an adjunct or a modifier.
Present participle --- The present participle is identical in form to
the gerund.
Present tense --- The form of language used to refer to an event,
transaction, or occurrence which is happening now (or at the present
time), or an object that currently exists.
Preterit --- The preterite tense, simple past tense: the grammatical
tense that determines the specific initiation or termination of an
action in the past.
Progressive form --- A form of a verb in which its gerund (or present
participle) is used with any form of the verb *to be*. Examples: I am
defining. It had been snowing.
Pronominal --- Of, pertaining to, resembling, or functioning as a
pronoun.
Pronominal compound --- An adjective *herein, therein, wherein*.
Pronoun --- A type of noun that refers anaphorically to another noun or
noun phrase, but which cannot ordinarily be preceded by a determiner and
rarely takes an attributive adjective.
Proper adjective --- An adjective derived from a proper noun, such as
*British* derived from *Britain*.
Proper noun --- The name of a particular person, place, organization or
other individual entity.
Prosthesis --- The prepending of phonemes at the beginning of a word
without changing its morphological structure, as in *nother* from
*other*.
Quotation --- A fragment of a human expression that is being referred to
by somebody else.
Radical --- Of or pertaining to the root of a word.
Redundant verb --- A verb which has two forms for past tense.
Regimen --- A syntactical relation between words, as when one depends on
another and is regulated by it in respect to case or mood; government.
Regular comparison --- Adjectives are regularly compared, when the
comparative degree is expressed by adding *er*, and the superlative, by
adding *est* to them.
Regular verb --- A verb which conjugates regularly. In English, a verb
which uses an *ed* suffix to form its past participle.
Relation --- Reference of word to other words.
Relative --- A relative pronoun. Relative pronouns are *who, which,
what, that, whoever, whosoever, whichever, whichsoever, whatever,
whatsoever*.
Remote --- Not directly related.
Roman characters --- A serifed style of typeface. Upright, as opposed to
italic.
Second-future tense --- The second-future tense is that which expresses
what will have taken place at some future time mentioned.
Semivowel --- A sound in speech which has some qualities of a consonant
and some qualities of a vowel. A letter which represents a semivowel
sound, such as *w* or *y* in English.
Sentence --- A grammatically complete series of words consisting of a
subject and predicate, even if one or the other is implied, and
typically beginning with a capital letter and ending with a full stop.
Sign --- An auxiliary, suffix, etc. that modifies a word.
Small letters --- The minuscule or small letters (*a*, *b*, *c*, as
opposed to the uppercase or capital letters, *A*, *B*, *C*).
Subject --- The word or word group (usually a noun phrase) that is dealt
with. In active clauses with verbs denoting an action, the subject and
the actor are usually the same.
Subjunctive mood --- A verb inflected to indicate that an act or state
of being is possible, contingent or hypothetical, and not a fact.
Superlative degree --- The form of an adjective that expresses which of
more than two items has the highest degree of the quality expressed by
the adjective; in English, formed by appending *est* to the end of the
adjective (for some short adjectives only) or putting *most* before it.
Supposition --- An assumption, conjecture, speculation or something
supposed.
Syllepsis --- A figure of speech in which one word simultaneously
modifies two or more other words such that the modification must be
understood differently with respect to each modified word; often causing
humorous incongruity.
Synaeresis --- The contraction of two vowels into a diphthong or a long
vowel.
Syncope --- A missing sound from the interior of a word, for example by
changing *cannot* to *can\'t* or *Hawai\'i* from the root name
*Hawaiki*.
Syntax --- A set of rules that govern how words are combined to form
phrases and sentences.
Tense --- Any of the forms of a verb which distinguish when an action or
state of being occurs or exists.
Thing sui generis --- In a class of its own; one of a kind.
Tmesis --- The insertion of one or more words between the components of
a compound word.
Understood words --- Words that are omitted by ellipsis.
Unstressed numeral --- A numeral in which *one* is replaced with
indefinite article.
Verb --- A word that indicates an action, an event, or a state.
Verbal --- A verb form which does not function as a predicate, or a word
derived from a verb.
Voice --- A particular mode of inflecting or conjugating verbs, or a
particular form of a verb, by means of which is indicated the relation
of the subject of the verb to the action which the verb expresses.
Vowel --- A sound produced by the vocal cords with relatively little
restriction of the oral cavity, forming the prominent sound of a
syllable. A letter representing the sound of vowel; in English, the
vowels are *a*, *e*, *i*, *o*, *u*, and sometimes *y*.
## References
- Wiktionary, the free
dictionary
- Wikipedia, the free
encyclopedia
- \"The Grammar of English
Grammars\"
|
# English in Use/Q&A
```{=html}
<div style="border: 2px solid SlateBlue; background: #F7F7FF; margin: 0em 1em 0em 1em; text-align: center; padding:5px; clear: both">
```
Welcome to the English questions and answers page.\
Feel free to post any questions you have while learning or encountering
English. Please sign and date your entries by inserting **\-- \~\~\~\~**
at the end.\
If you have questions about this book, post them on the English
discussion page.
------------------------------------------------------------------------
`<big>`{=html} **Ask a
question!**
`</big>`{=html}
```{=html}
</div>
```
## Open or Opened
When do you use \'open\' and when do you use \'opened\'?
For example in sentences like : The door was open. The door was opened.
` The box is open or The box is opened.`
: Following is/am/are, etc., \'open\' is used as an adjective,
describing the state of the object. \'To be opened\' is always a
passive verb, which means someone performed an action on the object.
For example, \"The store is opened at 7AM (by the owner); the store
is open from 7:00-10:00. Depending on the characteristics of the
object, \"is opened\" can be replaced by the active form \"opens\"
(\"The store opens (itself) at 7:00.\"). This can also be done with
another object: \"The owner opens the store. I open the box.\" \"The
door was opened.\" means that someone performed the action of
opening the door in the past. \"The door was open.\" means that the
door was in that open state in the past, but was not necessarily
opened or closed by anybody. \--hagindaz
15:26, 3 August 2006 (UTC)
```{=html}
<!-- -->
```
:
: A good example of the difference is that if the store opens at
7AM and closes at 10PM, then it is *open* at 8AM, but it isn\'t
*opened* at 8AM. NeonMerlin
(discuss •
contribs) 20:12,
6 August 2014 (UTC)
## Unanswered
how to make sentence with 2 noun and a pronoun and 2 adjective and a
verb and a adverb and a conjunction and a preposition?
grammar based sentences
I HAVE TO KNOW THAT WHAT IS FUTUTRE TIME REFERENCE
Hi, can you tell me how you would describe the phrase \"in common
with\"? Is it an adjective phrase, a comparative or what? thanks -
Analysis of this sentence depends on how one sees it. Lets begin with
the word common, there are many uses to the word common, and as well,
there many definitions. The problem with the word is it can be used to
describe \"common decency - something all should follow, or share\", or
it can be used to define the way \"people share one thing, be it an
object, an interest\". To answer your question, I truthfully would agree
it is a comparative, because you are comparing two \'things\' but, also
stating that these two things share one common purpose.
## The use of the gerund : \"being\"
Is the following correct or incorrect technically and why. (It does not
sound right to me)
A. \"The design margin is one metre, assuming the liquid being at
boiling point.\"
compared to
B. \"The design margin is one metre, assuming the liquid is at boiling
point.\" Is the following correct or incorrect technically and why.
be: verb and auxiliary verb, is: present singular 3rd person being:
present participle
Thank-you
Douglas Murray
## The use of the gerund : \"being\"
Is the following correct or incorrect technically and why. (It does not
sound right to me).
A. \"The design margin is one metre, assuming the liquid being at
boiling point.\"
compared to
B. \"The design margin is one metre, assuming the liquid is at boiling
point.\" Is the following correct or incorrect technically and why.
be: verb and auxiliary verb, is: present singular 3rd person being:
present participle
Thanks
Douglas Murray
11 January 2007
## a list of good interesting phrases for english composition.
could i have a list of good interesting phrases for English
compositions?
## Language
` "No language, no society".Justify the truism or otherwise of this assertion.`
## What is the difference between revise and review?
They are two different usages.
The author \"revises\" the document. - making changes to the document
The reviewer \"reviews\" the author\'s document. - read and comment the
document

## verbs.
what are the types of verbs in the following sentence? It\'s beginning
to look a lot like Christmas.
|
# English in Use/Hard C and soft C guide
The letter \"C\" can make two different sounds based on the rules of
English pronunciation. It can make the \"hard\" sound, as in \"cake\"
and \"cut\", and it can make the \"soft\" sound as in \"cell\" and
\"cinder\". This is going to be your guide, an in-depth guide, for how
to tell when to use the hard sound, and when to use the soft sound.
Despite being a multi-sound letter, the letter \"C\" is typically quite
well-behaved. Much of this information should be quite familiar to you.
We as educated, sane, rational adults don\'t, in the right mind, see a
word like \"Congress\" and expect it to have a soft C, because that\'s
not how CO words are pronounced. \"Congress\", like billions of other
words with a \"C\" followed by \"O\", has a hard C, just like the \"C\"
in \"cat\". In many dictionaries, \"C\" is the second most common letter
for a word to begin with, behind only the letter \"S\".
## Rules
- The sound of the letter \"C\" depends on the letter that follows it.
- If the letter \"C\" is followed by \"E\", \"I\", or \"Y\", it makes
the soft sound. The soft C sounds like the letter \"S\" as in
\"salad\". Examples include \"cell\", \"cider\", and \"Cynthia\".
- If the letter \"C\" is followed by H, then this consonant cluster
makes its own sound, as in \"chair\" and \"chill\".
- In some words, \"CH\" makes the hard C sound. Examples include
\"chorus\", \"chord\", \"chasm\", and all words starting with
\"Christ\", including the name of a very popular day of the year,
Christmas.
- If the letter \"C\" is followed by \"A\", \"L\", \"O\", \"R\", or
\"U\", it makes the hard sound. The hard C sounds like the letter
\"K\" as in \"king\". Examples include \"card\", \"clam\", \"coat\",
\"crate\", and \"cut\".
- If a word has a \"double C\", it helps to view this word as a
composite. The first \"C\" is hard, and the second \"C\" is hard or
soft based on the above rules. Words like \"accuse\" have two hard
C\'s back-to-back, so they have the hard C sound. In the word
\"accident\", the second C is soft because it is followed by \"I\",
and the hard and soft C\'s together form the \"X\" sound.
|
# Special Relativity/Mathematical approach2
## Four vectors
A four vector represents a displacement in spacetime.

If the spacetime has a metric given by:
$ds^2 = dt^2 - dx^2 - dy^2 - dz^2$
and if the space-time is flat the magnitude of the four vector is
calculated from:
$\mathbf{S}^2 = A^2 - B^2 - C^2 - D^2$
Where A, B, C, D are the projections of the vector on the corresponding
coordinate axes (t,x,y,z). The magnitude of a four vector is given by:
$S = | \mathbf{S}^2 |^{1/2} = \sqrt{A^2 - B^2 - C^2 - D^2}$
The scalar product of a four vector (also known as the \"dot product\"
or \"inner product\") can be derived in the same way as the scalar
product for an ordinary vector (a three vector, see scalar
product).
So the scalar product of two four vectors, $\mathbf{A.B}$ is:
$\mathbf{A.B} = A_tB_t - A_xB_x - A_yB_y - A_zB_z$
This can also be derived easily from the metric tensor of Minkowski
spacetime. The scalar product of two four-vectors *x* and *y* is defined
(using indicial notation) as:
$$x \cdot y
= x^a \eta_{ab} y^b
= \left( \begin{matrix}x^0 & x^1 & x^2 & x^3 \end{matrix} \right)
\left( \begin{matrix} -1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & 1 \end{matrix} \right)
\left( \begin{matrix}y^0 \\ y^1 \\ y^2 \\ y^3 \end{matrix} \right)
= - x^0 y^0 + x^1 y^1 + x^2 y^2 + x^3 y^3$$
The scalar product of four vectors is independent of the coordinate
system:
$$\begin{matrix}
A'_x & = & \gamma \left( A_x - \frac{v}{c} A_t \right)
\\ A'_y & = & A_y \\ A'_z & = & A_z \\
A'_t & = & \gamma \left( -\frac{v}{c} A_x + A_t \right)
\end{matrix}$$
The scalar product in this frame is:
$$\underline{A'} \cdot \underline{B'} =
A'_x B'_x + A'_y B'_y + A'_z B'_z - A'_t B'_t$$
Simplifying, we get:
$$\begin{matrix}
\underline{A'} \cdot \underline{B'} & = &
\gamma^2 \left( A_x B_x -\frac{v}{c} (A_x B_t + A_t B_x) + \frac{v^2}{c^2} A_t B_t \right) \\
& & + A_y B_y + A_z B_z &\\
& & - \gamma^2 \left( \frac{v^2}{c^2}A_x B_x -\frac{v}{c} (A_x B_t + A_t B_x) + A_t B_t \right) \\
& = & \left(1- \frac{v^2}{c^2} \right)^{-1} \left( A_x B_x + \frac{v^2}{c^2} A_t B_t \right) \\
& & + A_y B_y + A_z B_z \\
& & - \left(1- \frac{v^2}{c^2} \right)^{-1} \left( \frac{v^2}{c^2} A_x B_x - A_t B_t \right) \\
& = & A_x B_x + A_y B_y + A_z B_z - A_t B_t
\end{matrix}$$
Which is the same as the scalar product in the original frame of
reference.
Properties:
1\. Distributivity for vector addition
$\mathbf{A}.(\mathbf{B}+\mathbf{C})$
2\. Symmetry $\mathbf{A.B} = \mathbf{B.A}$
3\. Leibniz rule of differentiation applies ie:
$d (\mathbf{A.B}) = d\mathbf{A}.\mathbf{B} + \mathbf{A}.d\mathbf{B}$
4\. Orthogonality $\mathbf{A.B} = 0$ if $\mathbf{A}$ is perpendicular to
$\mathbf{B}$
5\. $\mathbf{A.A} = \mathbf{A}^2$
We now know that the dot product of two four-vectors is a
`<i>`{=html}scalar`</i>`{=html} result, i. e., its value is independent
of coordinate system. This can be used to advantage on occasion.
In the odd geometry of spacetime it is not obvious what *perpendicular*
means. We therefore `<i>`{=html}define`</i>`{=html} two four-vectors
$\underline{A}$ and $\underline{B}$ to be perpendicular if their dot
product is zero, in the same way as with three-vectors.
$$\underline{A} \cdot \underline{B} = 0$$
Because the dot product is a scalar, if vectors are perpendicular in one
frame, they will be perpendicular in all frames.
We can also consider the dot product of a four-vector $\underline{A}$
which resolves into $(A_x , A_t )$ in the unprimed frame. Let us further
suppose that the spacelike component is zero in some primed frame, so
that the components in this frame are (0, *A*~t\'~ ) The fact that the
dot product is independent of coordinate system means that
$$\underline{A} \cdot \underline{A} = A_x^2 - A_t^2 = - A_t'^2$$
This constitutes an extension of the spacetime Pythagorean theorem to
four-vectors other then the position four-vector. Thus, for instance,
the wavenumber for some wave may be zero in the primed frame, which
means that the wavenumber and frequency in the unprimed frame are
related to the frequency in the primed frame by
$k^2 - \omega^2 / c^2 = - \omega'^2 / c^2$.
We indicate a four-vector by underlining and write the components in the
following way: $\underline{k} = (k , \omega /c )$, where $\underline{k}$
is the wave four-vector, $k$ is its spacelike component, and $\omega /c$
is its timelike component. For three space dimensions, where we have a
wave vector rather than just a wavenumber, we write
$\underline{k} = (k , \omega /c )$.
Another example of a four-vector is simply the position vector in
spacetime, $\underline{x} = ( x, ct )$, or
$\underline{x} = ( \mathbf{x}, ct )$ in three space dimensions. The $c$
*multiplies* the timelike component in this case, because that is what
is needed to give it the same dimensions as the spacelike component.
### Proper time
Classically, the temporal derivative, *d*/*dt* acts like a scalar so we
can multiply a vector by it, and get another vector.
In relativity *t* is part of a four-vector, which means *d*/*dt* also
is, so we can\'t simply differentiate vectors with respect to *t* and
expect to get vectors.
For example, the position of a stationary particle is (0, *ct*).
Viewed from a frame moving at *v* to the right, its position becomes
(-*v*τ, *c*τ), where τ=γ*t* is the time as measured in the moving frame.
If we differentiate with respect to τ the velocity would be (-*v*, *c*)
If we differentiate with respect to *t*, we get (0, *c*) in the
stationary frame, which would be (using the Lorentz transform) (-γ*v*,
-γ*c*) in the moving frame, if this were a four vector.
These two expressions differ by a factor of γ, when measured in the same
frame, so this can not be a four vector.
However, if the moving observer divides by γ, which is the time
dilation, they will get the same vector as the stationary observer.
Doing this is equivalent to differentiating by the time *in the
particles own rest frame*. Since this works for the position vector, we
can expect it to work for all vectors.
The time measured in a particle\'s rest frame is called its *proper
time*.
Differentiating a vector with respect to proper time gives another
vector, which is the relativistic equivalent of the temporal derivative.
|
# Special Relativity/Mathematical Appendix#Mathematics of the Lorentz Transformation Equations
## Mathematics of the Lorentz Transformation Equations
Consider two observers $O$ and $O^'$, moving at velocity $v \,$ relative
to each other who synchronise their clocks so that $t=t^'=0$ as they
pass each other. They both observe the same event as a flash of light.
How will the coordinates recorded by the observers of the event that
produced the light be interrelated?
The relationship between the coordinates can be derived using linear
algebra on the basis of the postulates of relativity and an extra
homogeneity and isotropy assumption.
**The homogeneity and isotropy assumption**: space is uniform and
homogeneous in all directions. If this were not the case then when
comparing lengths between coordinate systems the lengths would depend
upon the position of the measurement. For instance, if $x^' = a x^2 \,$
the distance between two points would depend upon position.
The linear equations relating coordinates in the primed and unprimed
frames are:
: $x^' = a_{11} x + a_{12} y + a_{13} z + a_{14} t \,$
: $y^' = a_{21} x + a_{22} y + a_{23} z + a_{24} t \,$
: $z^' = a_{31} x + a_{32} y + a_{33} z + a_{34} t \,$
: $t^' = a_{41} x + a_{42} y + a_{43} z + a_{44} t \,$
There is no relative motion in the $y$ or $z$ directions so, according
to the \'relativity\' postulate:
: $z^' = z \,$
: $y^' = y \,$
Hence:
: $a_{22} = 1 \,$ and $a_{21} = a_{23} = a_{24} = 0 \,$
: $a_{33} = 1 \,$ and $a_{31} = a_{32} = a_{34} = 0 \,$
So the following equations remain to be solved:
: $x^' = a_{11} x + a_{12} y + a_{13} z + a_{14} t \,$
: $t^' = a_{41} x + a_{42} y + a_{43} z + a_{44} t \,$
If space is isotropic (the same in all directions) then the motion of
clocks should be independent of the y and z axes (otherwise clocks
placed symmetrically around the x-axis would appear to disagree). Hence:
: $a_{42} = a_{43} = 0 \,$
so:
: $t^' = a_{41} x + a_{44} t \,$
Events satisfying $x^' = 0 \,$ must also satisfy $x = vt \,$. So:
: $0 = a_{11} vt + a_{12} y + a_{13} z + a_{14} t \,$
and
: $-a_{11} vt = a_{12} y + a_{13} z + a_{14} t \,$
Given that the equations are linear then $a_{12} y + a_{13} z = 0 \,$
and:
: $-a_{11} vt = a_{14} t \,$
and
: $-a_{11} v = a_{14} \,$
Therefore the correct transformation equation for $x^' \,$ is:
: $x^' = a_{11} (x - vt) \,$
The analysis to date gives the following equations:
: $x^' = a_{11} (x - vt) \,$
: $y^' = y \,$
: $z^' = z \,$
: $t^' = a_{41} x + a_{44} t \,$
Assuming that the speed of light is constant, the coordinates of a flash
of light that expands as a sphere will satisfy the following equations
in each coordinate system:
: $x^2 + y^2 + z^2 = c^2t^2 \,$
: $x^{'2} + y^{'2} + z^{'2} = c^2t^{'2} \,$
Substituting the coordinate transformation equations into the second
equation gives:
: $a_{11}^2(x - vt)^2 + y^2 + z^2 = c^2(a_{41}x + a_{44}t)^2 \,$
rearranging:
: $(a_{11}^2 - c^2 a_{41}^2)x^2 + y^2 + z^2 - 2(va_{11}^2 + c^2a_{41} a_{44}) xt = (c^2 a_{44}^2 - v^2 a_{11}^2)t^2 \,$
We demand that this is equivalent with
: $x^2 + y^2 + z^2 = c^2t^2 \,$
So we get:
: $c^2 a_{44}^2 - v^2 a_{11}^2 = c^2 \,$
: $a_{11}^2 - c^2 a_{41}^2 = 1 \,$
: $va_{11}^2 + c^2a_{41} a_{44} = 0 \,$
Solving these 3 simultaneous equations gives:
: $a_{44} = \frac{1}{\sqrt{(1 - v^2/c^2)}} \,$
: $a_{11} = \frac{1}{\sqrt{(1 - v^2/c^2)}} \,$
: $a_{41} = -\frac{v/c^2}{\sqrt{(1 - v^2/c^2)}} \,$
Substituting these values into:
: $x^' = a_{11} (x - vt) \,$
: $y^' = y \,$
: $z^' = z \,$
: $t^' = a_{41} x + a_{44} t \,$
gives:
: $x^' = \frac{x - vt}{\sqrt{(1 - v^2/c^2)}} \,$
: $y^' = y \,$
: $z^' = z \,$
: $t^' = \frac{t - (v/c^2)x}{\sqrt{(1 - v^2/c^2)}} \,$
The inverse transformation is:
: $x = \frac{x^' + vt^'}{\sqrt{(1 - v^2/c^2)}} \,$
: $y = y^' \,$
: $z = z^' \,$
: $t = \frac{t^' + (v/c^2)x^'}{\sqrt{(1 - v^2/c^2)}} \,$
### Einstein\'s original approach
How would two observers measure the position and timing of an event by
using light rays if the speed of light were constant? The modern
analysis of this problem, exposing the assumptions involved, is given
above but Einstein\'s original reasoning (Einstein 1905,1920) is as
follows.
Light is transmitted along the positive x axis according to the equation
$x = ct$ where $c$ is the velocity of light. This can be rewritten as:
$$x - ct = 0$$
Another observer, moving relatively to the first may find different
values for x and t but the same equation will apply:
$$x^' - ct^' = 0$$
A simple relationship between these formulae, which apply to the same
event is:
$$(x^' - ct^') = \lambda (x - ct)$$
Light is transmitted along the negative x axis according to the equation
$x = -ct$ where $c$ is the velocity of light. This can be rewritten as:
$$x + ct = 0$$
$$x^' + ct^' = 0$$
And:
$$(x^' + ct^') = \mu (x + ct)$$
Adding the equations and substituting $a = \frac{\lambda + \mu}{2}$ and
$b = \frac{\lambda - \mu}{2}$:
: \(1\) $x' = ax - bct$
: \(2\) $ct' = act - bx$
The origin of one set of coordinates can be set so that $x^' = 0$ hence:
$$x = \frac{bc}{a} t$$
If $v$ is the velocity of one observer relative to the other then
$v = \frac{x}{t}$ and:
: \(3\) $v = \frac{bc}{a}$
At $t = 0$:
: \(4\) $x^' = ax$
Therefore two points separated by unit distance in the primed frame of
reference ie: when $x^' = 1$ have the following separation in the
unprimed frame:
: \(5\) $\Delta x = \frac{1}{a}$
Now $t$ can be eliminated from equations (1) and (2) and combined with
$v = \frac{bc}{a}$ and (4) to give in the case where $x=1$ and
$t^' = 0$:
: \(6\) $x^' = a (1 -\frac{v^2}{c^2}) x$
And, if $\Delta x = 1$:
: \(7\) $\Delta x^' = a (1 -\frac{v^2}{c^2})$
Now if the two moving systems are identical and the situation is
symmetrical a measurement in the unprimed system of a division showing
one metre on a measuring rod in the primed system is going to be
identical to a measurement in the primed system of a division showing
one metre on a measuring rod in the unprimed system. Thus (5) and (7)
can be combined so that:
$$\frac {1}{a} = a (1 -\frac{v^2}{c^2})$$
So:
$$a^2 = \frac {1}{(1 -\frac{v^2}{c^2})}$$
Inserting this value for $a$ into equations (1) and (2) and solving for
$b$ gives:
$$x^' = \frac {x - vt}{\sqrt {1 -\frac{v^2}{c^2}}}$$
$$t^' = \frac {t - (v/c^2)x}{\sqrt {1 -\frac{v^2}{c^2}}}$$
These are the **Lorentz Transformation Equations** for events on the x
axis.
Einstein, A. (1920). Relativity. The Special and General Theory. Methuen
& Co Ltd 1920. Written December, 1916. Robert W. Lawson (Authorised
translation). <http://www.bartleby.com/173/>
|
# Think Python/The way of the program
The goal of this book is to teach you to think like a computer
scientist. This way of thinking combines some of the best features of
mathematics, engineering, and natural science. Like mathematicians,
computer scientists use formal languages to denote ideas (specifically
computations). Like engineers, they design things, assembling components
into systems and evaluating tradeoffs among alternatives. Like
scientists, they observe the behavior of complex systems, form
hypotheses, and test predictions.
The single most important skill for a computer scientist is **problem
solving**. Problem solving means the ability to formulate problems,
think creatively about solutions, and express a solution clearly and
accurately. As it turns out, the process of learning to program is an
excellent opportunity to practice problem-solving skills. That's why
this chapter is called, "The way of the program."
On one level, you will be learning to program, a useful skill by itself.
On another level, you will use programming as a means to an end. As we
go along, that end will become clearer.
## The Python programming language
The programming language you will learn is Python. Python is an example
of a **high-level language**; other high-level languages you might have
heard of are C, C++, Perl, and Java.
There are also **low-level languages**, sometimes referred to as
"machine languages" or "assembly languages." Loosely speaking, computers
can only execute programs written in low-level languages. So programs
written in a high-level language have to be processed before they can
run. This extra processing takes some time, which is a small
disadvantage of high-level languages.
The advantages are enormous. First, it is much easier to program in a
high-level language. Programs written in a high-level language take less
time to write, they are shorter and easier to read, and they are more
likely to be correct. Second, high-level languages are **portable**,
meaning that they can run on different kinds of computers with few or no
modifications. Low-level programs can run on only one kind of computer
and have to be rewritten to run on another.
Due to these advantages, almost all programs are written in high-level
languages. Low-level languages are used only for a few specialized
applications.
Two kinds of programs process high-level languages into low-level
languages: **interpreters** and **compilers**. An interpreter reads a
high-level program and executes it, meaning that it does what the
program says. It processes the program a little at a time, alternately
reading lines and performing computations.

A compiler reads the program and translates it completely before the
program starts running. In this context, the high-level program is
called the **source code**, and the translated program is called the
**object code** or the **executable**. Once a program is compiled, you
can execute it repeatedly without further translation.

Python is considered an interpreted language because Python programs are
executed by an interpreter. There are two ways to use the interpreter:
**interactive mode** and **script mode**. In interactive mode, you type
Python programs and the interpreter prints the result:
``` python
>>> 1 + 1
2
```
The chevron, `>>>`, is the **prompt** the interpreter uses to indicate
that it is ready. If you type `1 + 1`, and then press the Enter key, the
interpreter replies `2`.
Alternatively, you can store code in a file and use the interpreter to
execute the contents of the file, which is called a **script**. By
convention, Python scripts have names that end with `.py`.
To execute the script, you have to tell the interpreter the name of the
file. In a UNIX command window, you would type `python dinsdale.py`. In
other development environments, the details of executing scripts are
different. You can find instructions for your environment at the Python
Website `python.org`.
Working in interactive mode is convenient for testing small pieces of
code because you can type and execute them immediately. But for anything
more than a few lines, you should save your code as a script so you can
modify and execute it in the future.
## What is a program?
A **program** is a sequence of instructions that specifies how to
perform a computation. The computation might be something mathematical,
such as solving a system of equations or finding the roots of a
polynomial, but it can also be a symbolic computation, such as searching
and replacing text in a document or (strangely enough) compiling a
program.
The details look different in different languages, but a few basic
instructions appear in just about every language:
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**input:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Get data from the keyboard, a file, or some other device.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**output:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Display data on the screen or send data to a file or other device.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**math:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Perform basic mathematical operations like addition and multiplication.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**conditional execution:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Check for certain conditions and execute the appropriate sequence of
statements.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**repetition:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Perform some action repeatedly, usually with some variation.
```{=html}
</DD>
```
```{=html}
</DL>
```
Believe it or not, that\'s pretty much all there is to it. Every program
you\'ve ever used, no matter how complicated, is made up of instructions
that look pretty much like these. So you can think of programming as the
process of breaking a large, complex task into smaller and smaller
subtasks until the subtasks are simple enough to be performed with one
of these basic instructions.
That may be a little vague, but we will come back to this topic when we
talk about **algorithms**.
## What is debugging?
Programming is error-prone. For whimsical reasons, programming errors
are called **bugs** and the process of tracking them down is called
**debugging**.
Three kinds of errors can occur in a program: syntax errors, runtime
errors, and semantic errors. It is useful to distinguish between them in
order to track them down more quickly.
### Syntax errors
Python can only execute a program if the syntax is correct; otherwise,
the interpreter displays an error message. **Syntax** refers to the
structure of a program and the rules about that structure. For example,
parentheses have to come in matching pairs, so `(1 + 2)` is legal, but
`8)` is a **syntax error**.
In English readers can tolerate most syntax errors, which is why we can
read the poetry of E. E. Cummings without spewing error messages. Python
is not so forgiving. If there is a single syntax error anywhere in your
program, Python will display an error message and quit, and you will not
be able to run your program. During the first few weeks of your
programming career, you will probably spend a lot of time tracking down
syntax errors. As you gain experience, you will make fewer errors and
find them faster.
### Runtime errors
The second type of error is a runtime error, so called because the error
does not appear until after the program has started running. These
errors are also called **exceptions** because they usually indicate that
something exceptional (and bad) has happened.
Runtime errors are rare in the simple programs you will see in the first
few chapters, so it might be a while before you encounter one.
### Semantic errors
The third type of error is the **semantic error**. If there is a
semantic error in your program, it will run successfully in the sense
that the computer will not generate any error messages, but it will not
do the right thing. It will do something else. Specifically, it will do
what you told it to do.
The problem is that the program you wrote is not the program you wanted
to write. The meaning of the program (its semantics) is wrong.
Identifying semantic errors can be tricky because it requires you to
work backward by looking at the output of the program and trying to
figure out what it is doing.
### Experimental debugging
One of the most important skills you will acquire is debugging. Although
it can be frustrating, debugging is one of the most intellectually rich,
challenging, and interesting parts of programming.
In some ways, debugging is like detective work. You are confronted with
clues, and you have to infer the processes and events that led to the
results you see.
Debugging is also like an experimental science. Once you have an idea
about what is going wrong, you modify your program and try again. If
your hypothesis was correct, then you can predict the result of the
modification, and you take a step closer to a working program. If your
hypothesis was wrong, you have to come up with a new one. As Sherlock
Holmes pointed out, "When you have eliminated the impossible, whatever
remains, however improbable, must be the truth." (A. Conan Doyle, *The
Sign of Four*)
For some people, programming and debugging are the same thing. That is,
programming is the process of gradually debugging a program until it
does what you want. The idea is that you should start with a program
that does *something* and make small modifications, debugging them as
you go, so that you always have a working program.
For example, Linux is an operating system that contains thousands of
lines of code, but it started out as a simple program Linus Torvalds
used to explore the Intel 80386 chip. According to Larry Greenfield,
"One of Linus's earlier projects was a program that would switch between
printing AAAA and BBBB. This later evolved to Linux." (*The Linux Users'
Guide* Beta Version 1).
Later chapters will make more suggestions about debugging and other
programming practices.
## Formal and natural languages
**Natural languages** are the languages people speak, such as English,
Spanish, and French. They were not designed by people (although people
try to impose some order on them); they evolved naturally.
**Formal languages** are languages that are designed by people for
specific applications. For example, the notation that mathematicians use
is a formal language that is particularly good at denoting relationships
among numbers and symbols. Chemists use a formal language to represent
the chemical structure of molecules. And most importantly:
> **Programming languages are formal languages that have been designed
> to express computations.**
Formal languages tend to have strict rules about syntax. For example,
3 + 3 = 6 is a syntactically correct mathematical statement, but 3 + = 3
\$6 is not. *H*~2~*O* is a syntactically correct chemical formula, but
~2~*Zz* is not.
Syntax rules come in two flavors, pertaining to **tokens** and
structure. Tokens are the basic elements of the language, such as words,
numbers, and chemical elements. One of the problems with 3 + = 3 \$6 is
that `$` is not a legal token in mathematics (at least as far as I
know). Similarly, ~2~*Zz* is not legal because there is no element with
the abbreviation *Zz*.
The second type of syntax error pertains to the structure of a
statement; that is, the way the tokens are arranged. The statement 3 + =
3 \$6 is illegal because even though + and = are legal tokens, you
can\'t have one right after the other. Similarly, in a chemical formula
the subscript comes after the element name, not before.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 1** *Write a well-structured English sentence with invalid
tokens in it. Then write another sentence with all valid tokens but with
invalid structure.*
```{=html}
</DIV>
```
When you read a sentence in English or a statement in a formal language,
you have to figure out what the structure of the sentence is (although
in a natural language you do this subconsciously). This process is
called **parsing**.
For example, when you hear the sentence, "The penny dropped," you
understand that "the penny" is the subject and "dropped" is the
predicate. Once you have parsed a sentence, you can figure out what it
means, or the semantics of the sentence. Assuming that you know what a
penny is and what it means to drop, you will understand the general
implication of this sentence.
Although formal and natural languages have many features in
common---tokens, structure, syntax, and semantics---there are some
differences:
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**ambiguity:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Natural languages are full of ambiguity, which people deal with by using
contextual clues and other information. Formal languages are designed to
be nearly or completely unambiguous, which means that any statement has
exactly one meaning, regardless of context.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**redundancy:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
In order to make up for ambiguity and reduce misunderstandings, natural
languages employ lots of redundancy. As a result, they are often
verbose. Formal languages are less redundant and more concise.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**literalness:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Natural languages are full of idiom and metaphor. If I say, "The penny
dropped," there is probably no penny and nothing dropping.[^1] Formal
languages mean exactly what they say.
```{=html}
</DD>
```
```{=html}
</DL>
```
People who grow up speaking a natural language---everyone---often have a
hard time adjusting to formal languages. In some ways, the difference
between formal and natural language is like the difference between
poetry and prose, but more so:
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**Poetry:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Words are used for their sounds as well as for their meaning, and the
whole poem together creates an effect or emotional response. Ambiguity
is not only common but often deliberate.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Prose:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The literal meaning of words is more important, and the structure
contributes more meaning. Prose is more amenable to analysis than poetry
but still often ambiguous.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Programs:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The meaning of a computer program is unambiguous and literal, and can be
understood entirely by analysis of the tokens and structure.
```{=html}
</DD>
```
```{=html}
</DL>
```
Here are some suggestions for reading programs (and other formal
languages). First, remember that formal languages are much more dense
than natural languages, so it takes longer to read them. Also, the
structure is very important, so it is usually not a good idea to read
from top to bottom, left to right. Instead, learn to parse the program
in your head, identifying the tokens and interpreting the structure.
Finally, the details matter. Small errors in spelling and punctuation,
which you can get away with in natural languages, can make a big
difference in a formal language.
## The first program
Traditionally, the first program you write in a new language is called
"Hello, World!" because all it does is display the words, "Hello,
World!" In Python, it looks like this:
``` python
print 'Hello, World!'
```
This is an example of a **print statement**,[^2] which doesn\'t actually
print anything on paper. It displays a value on the screen. In this
case, the result is the words
``` python
Hello, World!
```
The quotation marks in the program mark the beginning and end of the
text to be displayed; they don\'t appear in the result.
Some people judge the quality of a programming language by the
simplicity of the "Hello, World!" program. By this standard, Python does
about as well as possible.
## Debugging
It is a good idea to read this book in front of a computer so you can
try out the examples as you go. You can run most of the examples in
interactive mode, but if you put the code into a script, it is easier to
try out variations.
Whenever you are experimenting with a new feature, you should try to
make mistakes. For example, in the "Hello, world!" program, what happens
if you leave out one of the quotation marks? What if you leave out both?
What if you spell `print` wrong?
This kind of experiment helps you remember what you read; it also helps
with debugging, because you get to know what the error messages mean. It
is better to make mistakes now and on purpose than later and
accidentally.
Programming, and especially debugging, sometimes brings out strong
emotions. If you are struggling with a difficult bug, you might feel
angry, despondent or embarrassed.
There is evidence that people naturally respond to computers as if they
were people.[^3] When they work well, we think of them as teammates, and
when they are obstinate or rude, we respond to them the same way we
respond to rude, obstinate people.
Preparing for these reactions might help you deal with them. One
approach is to think of the computer as an employee with certain
strengths, like speed and precision, and particular weaknesses, like
lack of empathy and inability to grasp the big picture.
Your job is to be a good manager: find ways to take advantage of the
strengths and mitigate the weaknesses. And find ways to use your
emotions to engage with the problem, without letting your reactions
interfere with your ability to work effectively.
Learning to debug can be frustrating, but it is a valuable skill that is
useful for many activities beyond programming. At the end of each
chapter there is a debugging section, like this one, with my thoughts
about debugging. I hope they help!
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**problem solving:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of formulating a problem, finding a solution, and expressing
the solution.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**high-level language:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A programming language like Python that is designed to be easy for
humans to read and write.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**low-level language:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A programming language that is designed to be easy for a computer to
execute; also called "machine language" or "assembly language."
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**portability:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A property of a program that can run on more than one kind of computer.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**interpret:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To execute a program in a high-level language by translating it one line
at a time.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**compile:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To translate a program written in a high-level language into a low-level
language all at once, in preparation for later execution.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**source code:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A program in a high-level language before being compiled.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**object code:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The output of the compiler after it translates the program.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**executable:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Another name for object code that is ready to be executed.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**prompt:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Characters displayed by the interpreter to indicate that it is ready to
take input from the user.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**script:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A program stored in a file (usually one that will be interpreted).
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**interactive mode:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A way of using the Python interpreter by typing commands and expressions
at the prompt.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**script mode:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A way of using the Python interpreter to read and execute statements in
a script.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**program:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A set of instructions that specifies a computation.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**algorithm:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A general process for solving a category of problems.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**bug:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An error in a program.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**debugging:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of finding and removing any of the three kinds of
programming errors.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**syntax:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The structure of a program.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**syntax error:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An error in a program that makes it impossible to parse (and therefore
impossible to interpret).
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**exception:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An error that is detected while the program is running.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**semantics:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The meaning of a program.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**semantic error:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An error in a program that makes it do something other than what the
programmer intended.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**natural language:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Any one of the languages that people speak that evolved naturally.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**formal language:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Any one of the languages that people have designed for specific
purposes, such as representing mathematical ideas or computer programs;
all programming languages are formal languages.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**token:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the basic elements of the syntactic structure of a program,
analogous to a word in a natural language.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**parse:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To examine a program and analyze the syntactic structure.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**print statement:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An instruction that causes the Python interpreter to display a value on
the screen.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 2
Use a web browser to go to the Python website, <http://python.org/>.
This page contains information about Python and links to Python-related
pages, and it gives you the ability to search the Python documentation.
For example, if you enter `print` in the search window, the first link
that appears is the documentation of the `print` statement. At this
point, not all of it will make sense to you, but it is good to know
where it is.
### Exercise 3
Start the Python interpreter and type **\'`help()`**\' to start the
online help utility. Or you can type **`help('print')`** to get
information about the **\'`print`**\' statement.If this example doesn\'t
work, you may need to install additional Python documentation or set an
environment variable; the details depend on your operating system and
version of Python.
### Exercise 4
Start the Python interpreter and use it as a calculator. Python\'s
syntax for math operations is almost the same as standard mathematical
notation. For example, the symbols **\'`+`**\', **\'`-`**\' and
**\'`/`**\' denote addition, subtraction and division, as you would
expect. The symbol for multiplication is **\'`*`**\'.If you run a 10
kilometer race in 43 minutes 30 seconds, what is your average time per
mile? What is your average speed in miles per hour? (Hint: there are
1.61 kilometers in a mile).\'\'
## References
```{=html}
<references/>
```
[^1]: This idiom means that someone realized something after a period of
confusion.
[^2]: In Python 3.0, `print` is a function, not a statement, so the
syntax is `print(’Hello, World!’)`. We will get to functions soon!
[^3]: See Reeves and Nass, `<I>`{=html}The Media Equation: How People
Treat Computers, Television, and New Media Like Real People and
Places`</I>`{=html}.
|
# Think Python/Variables, expressions and statements
### Values and types
A **value** is one of the basic things a program works with, like a
letter or a number. The values we have seen so far are `1`, `2`, and
`'Hello, World!'`.
These values belong to different **types**: `2` is an integer, and
`'Hello, World!'` is a **string**, so-called because it contains a
"string" of letters. You (and the interpreter) can identify strings
because they are enclosed in quotation marks.
The print statement also works for integers.
``` python
>>> print (4)
4
```
If you are not sure what type a value has, the interpreter can tell you.
``` python
>>> type('Hello, World!')
<type 'str'>
>>> type(17)
<type 'int'>
```
Not surprisingly, strings belong to the type `str` and integers belong
to the type `int`. Less obviously, numbers with a decimal point belong
to a type called `float`, because these numbers are represented in a
format called **floating-point**.
``` python
>>> type(3.2)
<type 'float'>
```
What about values like `'17'` and `'3.2'`? They look like numbers, but
they are in quotation marks like strings.
``` python
>>> type('17')
<type 'str'>
>>> type('3.2')
<type 'str'>
```
They\'re strings.
When you type a large integer, you might be tempted to use commas
between groups of three digits, as in `1,000,000`. This is not a legal
integer in Python, but it is legal:
``` python
>>> print 1,000,000
1 0 0
```
Well, that's not what we expected at all! Python interprets `1,000,000`
as a comma-separated sequence of integers, which it prints with spaces
between.
This is the first example we have seen of a semantic error: the code
runs without producing an error message, but it doesn\'t do the "right"
thing.
### Variables
One of the most powerful features of a programming language is the
ability to manipulate **variables**. A variable is a name that refers to
a value.
An **assignment statement** creates new variables and gives them values:
``` python
>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931
```
This example makes three assignments. The first assigns a string to a
new variable named `message`; the second gives the integer `17` to `n`;
the third assigns the (approximate) value of π to `pi`.
A common way to represent variables on paper is to write the name with
an arrow pointing to the variable's value. This kind of figure is called
a **state diagram** because it shows what state each of the variables is
in (think of it as the variable's state of mind). This diagram shows the
result of the previous example:
----------- --------------- ------------------------------------------------
`message` $\rightarrow$ `'And now for something completely different'`
`n` $\rightarrow$ `17`
`pi` $\rightarrow$ `3.1415926535897931`
----------- --------------- ------------------------------------------------
To display the value of a variable, you can use a print statement:
``` python
>>> print n
17
>>> print pi
3.14159265359
```
The type of a variable is the type of the value it refers to.
``` python
>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>
```
#### Exercise 1
If you type an integer with a leading zero, you might get a confusing
error:
``` python
>>> zipcode = 02492
^
SyntaxError: invalid token
```
Other numbers seem to work, but the results are bizarre:
``` python
>>> zipcode = 02132
>>> print zipcode
1114
```
Can you figure out what is going on? Hint: print the values `01`, `010`,
`0100` and `01000`.
### Variable names and keywords
Programmers generally choose names for their variables that are
meaningful---they document what the variable is used for.
Variable names can be arbitrarily long. They can contain both letters
and numbers, but they have to begin with a letter. It is legal to use
uppercase letters, but it is a good idea to begin variable names with a
lowercase letter (you\'ll see why later).
The underscore character (`_`) can appear in a name. It is often used in
names with multiple words, such as `my_name` or
`airspeed_of_unladen_swallow`.
If you give a variable an illegal name, you get a syntax error:
``` python
>>> 76trombones = 'big parade'
SyntaxError: invalid syntax
>>> more@ = 1000000
SyntaxError: invalid syntax
>>> class = 'Advanced Theoretical Zymurgy'
SyntaxError: invalid syntax
```
`76trombones` is illegal because it does not begin with a letter.
`more@` is illegal because it contains an illegal character, `@`. But
what\'s wrong with `class`?
It turns out that `class` is one of Python\'s **keywords**. The
interpreter uses keywords to recognize the structure of the program, and
they cannot be used as variable names.
Python has 31 keywords:
------------ ----------- ---------- ---------- ---------
`and` `del` `from` `not` `while`
`as` `elif` `global` `or` `with`
`assert` `else` `if` `pass` `yield`
`break` `except` `import` `print`
`class` `exec` `in` `raise`
`continue` `finally` `is` `return`
`def` `for` `lambda` `try`
------------ ----------- ---------- ---------- ---------
You might want to keep this list handy. If the interpreter complains
about one of your variable names and you don\'t know why, see if it is
on this list.
If you write your code in a text editor that understands Python, you may
find that it makes it easy for you to spot such keyword clashes by
displaying keywords in a different color to ordinary variables. This
feature is called *syntax highlighting*, and most programmers find it
indispensable. This book uses syntax highlighting for its example code,
so in the following example:
``` python
ok_variable = 42
yield = 42
```
you can see that `yield` has been recognized as a keyword and not as an
ordinary variable, since it is colored green.
### Statements
A statement is a unit of code that the Python interpreter can execute.
We have seen two kinds of statements: print and assignment.
When you type a statement in interactive mode, the interpreter executes
it and displays the result, if there is one.
A script usually contains a sequence of statements. If there is more
than one statement, the results appear one at a time as the statements
execute.
For example, the script
``` python
print 1
x = 2
print x
```
produces the output
``` python
1
2
```
The assignment statement produces no output.
### Operators and operands
**Operators** are special symbols that represent computations like
addition and multiplication. The values the operator is applied to are
called **operands**.
The operators `+`, `-`, `*`, `/` and `**` perform addition, subtraction,
multiplication, division and exponentiation, as in the following
examples:
``` python
20+32 hour-1 hour*60+minute minute/60 5**2 (5+9)*(15-7)
```
In some other languages, `^` is used for exponentiation, but in Python
it is a bitwise operator called XOR. I won't cover bitwise operators in
this book, but you can read about them at
`wiki.python.org/moin/BitwiseOperators`.
The division operator might not do what you expect:
``` python
>>> minute = 59
>>> minute/60
0
```
The value of `minute` is 59, and in conventional arithmetic 59 divided
by 60 is 0.98333, not 0. The reason for the discrepancy is that Python
is performing **floor division**.[^1]
When both of the operands are integers, the result is also an integer;
floor division chops off the fraction part, so in this example it rounds
down to zero.
If either of the operands is a floating-point number, Python performs
floating-point division, and the result is a `float`:
``` python
>>> minute/60.0
0.98333333333333328
```
### Expressions
An **expression** is a combination of values, variables, and operators.
A value all by itself is considered an expression, and so is a variable,
so the following are all legal expressions (assuming that the variable
`x` has been assigned a value):
``` python
17
x
x + 17
```
If you type an expression in interactive mode, the interpreter
**evaluates** it and displays the result:
``` python
>>> 1 + 1
2
```
But in a script, an expression all by itself doesn't do anything! This
is a common source of confusion for beginners.
#### Exercise 2
Type the following statements in the Python interpreter to see what they
do:
``` python
5
x = 5
x + 1
```
Now put the same statements into a script and run it. What is the
output? Modify the script by transforming each expression into a print
statement and then run it again.
### Order of operations
When more than one operator appears in an expression, the order of
evaluation depends on the **rules of precedence**. For mathematical
operators, Python follows mathematical convention. The acronym
**PEMDAS** is a useful way to remember the rules:
- **P**arentheses have the highest precedence and can be used to force
an expression to evaluate in the order you want. Since expressions
in parentheses are evaluated first, `2 * (3-1)` is 4, and
`(1+1)**(5-2)` is 8. You can also use parentheses to make an
expression easier to read, as in `(minute * 100) / 60`, even if it
doesn\'t change the result.
- **E**xponentiation has the next highest precedence, so `2**1+1` is
3, not 4, and `3*1**3` is 3, not 27.
- **M**ultiplication and **D**ivision have the same precedence, which
is higher than **A**ddition and **S**ubtraction, which also have the
same precedence. So `2*3-1` is 5, not 4, and `6+4/2` is 8, not 5.
- Operators with the same precedence are evaluated from left to right.
So in the expression `degrees / 2 * pi`, the division happens first
and the result is multiplied by `pi`. To divide by 2 π, you can
reorder the operands or use parentheses.
### String operations
In general, you cannot perform mathematical operations on strings, even
if the strings look like numbers, so the following are illegal:
``` python
'2'-'1' 'eggs'/'easy' 'third'*'a charm'
```
The `+` operator works with strings, but it might not do what you
expect: it performs **concatenation**, which means joining the strings
by linking them end-to-end. For example:
``` python
first = 'throat'
second = 'warbler'
print first + second
```
The output of this program is `throatwarbler`.
The `*` operator also works on strings; it performs repetition. For
example, `’Spam’*3` is `'SpamSpamSpam'`. If one of the operands is a
string, the other has to be an integer.
This use of `+` and `*` makes sense by analogy with addition and
multiplication. Just as `4*3` is equivalent to `4+4+4`, we expect
`'Spam'*3` to be the same as `'Spam'+'Spam'+'Spam'`, and it is. On the
other hand, there is a significant way in which string concatenation and
repetition are different from integer addition and multiplication. Can
you think of a property that addition has that string concatenation does
not?
### Comments
As programs get bigger and more complicated, they get more difficult to
read. Formal languages are dense, and it is often difficult to look at a
piece of code and figure out what it is doing, or why.
For this reason, it is a good idea to add notes to your programs to
explain in natural language what the program is doing. These notes are
called **comments**, and they start with the `#` symbol:
``` python
# compute the percentage of the hour that has elapsed
percentage = (minute * 100) / 60
```
In this case, the comment appears on a line by itself. You can also put
comments at the end of a line:
``` python
percentage = (minute * 100) / 60 # percentage of an hour
```
Everything from the `#` to the end of the line is ignored---it has no
effect on the program.
Comments are most useful when they document non-obvious features of the
code. It is reasonable to assume that the reader can figure out *what*
the code does; it is much more useful to explain *why*.
This comment is redundant with the code and useless:
``` python
v = 5 # assign 5 to v
```
This comment contains useful information that is not in the code:
``` python
v = 5 # velocity in meters/second.
```
Good variable names can reduce the need for comments, but long names can
make complex expressions hard to read, so there is a tradeoff.
### Debugging
At this point the syntax error you are most likely to make is an illegal
variable name, like `class` and `yield`, which are keywords, or
`odd~job` and `US$`, which contain illegal characters.
If you put a space in a variable name, Python thinks it is two operands
without an operator:
``` python
>>> bad name = 5
SyntaxError: invalid syntax
```
For syntax errors, the error messages don't help much. The most common
messages are `SyntaxError: invalid syntax` and
`SyntaxError: invalid token`, neither of which is very informative.
The runtime error you are most likely to make is a "use before def;"
that is, trying to use a variable before you have assigned a value. This
can happen if you spell a variable name wrong:
``` python
>>> principal = 327.68
>>> interest = principle * rate
NameError: name 'principle' is not defined
```
Variables names are case sensitive, so `LaTeX` is not the same as
`latex`.
At this point the most likely cause of a semantic error is the order of
operations. For example, to evaluate 1/2 π, you might be tempted to
write
``` python
>>> 1.0 / 2.0 * pi
```
But the division happens first, so you would get π / 2, which is not the
same thing! There is no way for Python to know what you meant to write,
so in this case you don't get an error message; you just get the wrong
answer.
### Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**value:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the basic units of data, like a number or string, that a program
manipulates.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**type:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A category of values. The types we have seen so far are integers (type
`int`), floating-point numbers (type `float`), and strings (type `str`).
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**integer:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A type that represents whole numbers.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**floating-point:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A type that represents numbers with fractional parts.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**string:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A type that represents sequences of characters.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**variable:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A name that refers to a value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**statement:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A section of code that represents a command or action. So far, the
statements we have seen are assignments and print statements.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**assignment:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A statement that assigns a value to a variable.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**state diagram:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A graphical representation of a set of variables and the values they
refer to.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**keyword:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A reserved word that is used by the compiler to parse a program; you
cannot use keywords like `if`, `def`, and `while` as variable names.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**operator:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A special symbol that represents a simple computation like addition,
multiplication, or string concatenation.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**operand:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the values on which an operator operates.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**floor division:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The operation that divides two numbers and chops off the fraction part.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**expression:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A combination of variables, operators, and values that represents a
single result value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**evaluate:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To simplify an expression by performing the operations in order to yield
a single value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**rules of precedence:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The set of rules governing the order in which expressions involving
multiple operators and operands are evaluated.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**concatenate:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To join two operands end-to-end.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**comment:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Information in a program that is meant for other programmers (or anyone
reading the source code) and has no effect on the execution of the
program.
```{=html}
</DD>
```
```{=html}
</DL>
```
### Exercises
#### Exercise 3
Assume that we execute the following assignment statements:
``` python
width = 17
height = 12.0
delimiter = '.'
```
For each of the following expressions, write the value of the expression
and the type (of the value of the expression).
``` python
width/2
width/2.0
height/3
1 + 2 * 5
delimiter * 5
```
Use the Python interpreter to check your answers.
#### Exercise 4
Practice using the Python interpreter as a calculator:
- *The volume of a sphere with radius
**\'`<I>`{=html}r`</I>`{=html}**\' is **\'4/3**\' π
`<I>`{=html}r`</I>`{=html}*^*3*^\'\'.
What is the volume of a sphere with radius 5? Hint: 392.6 is wrong!\'\'
- \'\'Suppose the cover price of a book is \$24.95, but bookstores get
a
40% discount. Shipping costs \$3 for the first copy and 75 cents for
each additional copy. What is the total wholesale cost for 60
copies?\'\'
- \'\'If I leave my house at 6:52 am and run 1 mile at an easy pace
(8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at
easy pace again, what time do I get home for breakfast?\'\'
### Notes
[^1]: In Python 3.0, the result of this division is a `float`. The new
operator `//` performs integer division.
|
# Think Python/Case study: interface design
### TurtleWorld
To accompany this book, I have written a suite of modules called Swampy.
One of these modules is TurtleWorld, which provides a set of functions
for drawing lines by steering turtles around the screen.
You can download Swampy from
`thinkpython.com/swampy`; follow the
instructions there to install Swampy on your system.
Move into the directory that contains `TurtleWorld.py`, create a file
named `polygon.py` and type in the following code:
``` python
from TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print bob
wait_for_user()
```
The first line is a variation of the `import` statement we saw before;
instead of creating a module object, it imports the functions from the
module directly, so you can access them without using dot notation.
The next lines create a TurtleWorld assigned to `world` and a Turtle
assigned to `bob`. Printing `bob` yields something like:
``` python
<TurtleWorld.Turtle instance at 0xb7bfbf4c>
```
This means that `bob` refers to an **instance** of a Turtle as defined
in module `TurtleWorld`. In this context, \"instance\" means a member of
a set; this Turtle is one of the set of possible Turtles.
`wait_for_user` tells TurtleWorld to wait for the user to do something,
although in this case there\'s not much for the user to do except close
the window.
TurtleWorld provides several turtle-steering functions: `fd` and `bk`
for forward and backward, and `lt` and `rt` for left and right turns.
Also, each Turtle is holding a pen, which is either down or up; if the
pen is down, the Turtle leaves a trail when it moves. The functions `pu`
and `pd` stand for "pen up" and "pen down."
To draw a right angle, add these lines to the program (after creating
`bob` and before calling `wait_for_user`):
``` python
fd(bob, 100)
rt(bob)
fd(bob, 100)
```
The first line tells `bob` to take 100 steps forward. The second line
tells him to turn right.
When you run this program, you should see `bob` move east and then
south, leaving two line segments behind.
Now modify the program to draw a square. Don't turn the page until
you\'ve got it working!
### Simple repetition
Chances are you wrote something like this (leaving out the code that
creates TurtleWorld and waits for the user):
``` python
fd(bob, 100)
lt(bob)
fd(bob, 100)
lt(bob)
fd(bob, 100)
lt(bob)
fd(bob, 100)
```
We can do the same thing more concisely with a `for` statement. Add this
example to `polygon.py` and run it again:
``` python
for i in range(4):
print 'Hello!'
```
You should see something like this:
``` python
Hello!
Hello!
Hello!
Hello!
```
This is the simplest use of the `for` statement; we will see more later.
But that should be enough to let you rewrite your square-drawing
program. Don't turn the page until you do.
Here is a `for` statement that draws a square:
``` python
for i in range(4):
fd(bob, 100)
lt(bob)
```
The syntax of a `for` statement is similar to a function definition. It
has a header that ends with a colon and an indented body. The body can
contain any number of statements.
A `for` statement is sometimes called a **loop** because the flow of
execution runs through the body and then loops back to the top. In this
case, it runs the body four times.
This version is actually a little different from the previous
square-drawing code because it makes another left turn after drawing the
last side of the square. The extra turn takes a little more time, but it
simplifies the code if we do the same thing every time through the loop.
This version also has the effect of leaving the turtle back in the
starting position, facing in the starting direction.
### Exercises
The following is a series of exercises using TurtleWorld. They are meant
to be fun, but they have a point, too. While you are working on them,
think about what the point is.
The following sections have solutions to the exercises, so don't look
until you have finished (or at least tried).
- Write a function called `square` that takes a parameter
named `t`, which is a turtle. It should use the turtle to draw a square.
Write a function call that passes `bob` as an argument to `square`, and
then run the program again.
- Add another parameter, named `length`, to `square`.
Modify the body so length of the sides is `length`, and then modify the
function call to provide a second argument. Run the program again. Test
your program with a range of values for `length`.
- The functions `lt` and `rt` make 90-degree turns by
default, but you can provide a second argument that specifies the number
of degrees. For example, `lt(bob, 45)` turns `bob` 45 degrees to the
left. Make a copy of `square` and change the name to `polygon`. Add
another parameter named `n` and modify the body so it draws an n-sided
regular polygon. Hint: The angles of an n-sided regular polygon are
360.0 / `<I>`{=html}n`</I>`{=html} degrees.
- Write a function called `circle` that takes a turtle, `t`,
and radius, `r`, as parameters and that draws an approximate circle by
invoking `polygon` with an appropriate length and number of sides. Test
your function with a range of values of `r`.
Hint: figure out the circumference of the circle and make sure that
`length * n = circumference`.
Another hint: if `bob` is too slow for you, you can speed him up by
changing `bob.delay`, which is the time between moves, in seconds.
`bob.delay = 0.01` ought to get him moving.
- Make a more general version of `circle` called `arc`
that takes an additional parameter `angle`, which determines what
fraction of a circle to draw. `angle` is in units of degrees, so when
`angle=360`, `arc` should draw a complete circle.
### Encapsulation
The first exercise asks you to put your square-drawing code into a
function definition and then call the function, passing the turtle as a
parameter. Here is a solution:
``` python
def square(t):
for i in range(4):
fd(t, 100)
lt(t)
square(bob)
```
The innermost statements, `fd` and `lt` are indented twice to show that
they are inside the `for` loop, which is inside the function definition.
The next line, `square(bob)`, is flush with the left margin, so that is
the end of both the `for` loop and the function definition.
Inside the function, `t` refers to the same turtle `bob` refers to, so
`lt(t)` has the same effect as `lt(bob)`. So why not call the parameter
`bob`? The idea is that `t` can be any turtle, not just `bob`, so you
could create a second turtle and pass it as an argument to `square`:
``` python
ray = Turtle()
square(ray)
```
Wrapping a piece of code up in a function is called **encapsulation**.
One of the benefits of encapsulation is that it attaches a name to the
code, which serves as a kind of documentation. Another advantage is that
if you re-use the code, it is more concise to call a function twice than
to copy and paste the body!
### Generalization
The next step is to add a `length` parameter to `square`. Here is a
solution:
``` python
def square(t, length):
for i in range(4):
fd(t, length)
lt(t)
square(bob, 100)
```
Adding a parameter to a function is called **generalization** because it
makes the function more general: in the previous version, the square is
always the same size; in this version it can be any size.
The next step is also a generalization. Instead of drawing squares,
`polygon` draws regular polygons with any number of sides. Here is a
solution:
``` python
def polygon(t, n, length):
angle = 360.0 / n
for i in range(n):
fd(t, length)
lt(t, angle)
polygon(bob, 7, 70)
```
This draws a 7-sided polygon with side length 70. If you have more than
a few numeric arguments, it is easy to forget what they are, or what
order they should be in. It is legal, and sometimes helpful, to include
the names of the parameters in the argument list:
``` python
polygon(bob, n=7, length=70)
```
These are called **keyword arguments** because they include the
parameter names as "keywords" (not to be confused with Python keywords
like `while` and `def`).
This syntax makes the program more readable. It is also a reminder about
how arguments and parameters work: when you call a function, the
arguments are assigned to the parameters.
### Interface design
The next step is to write `circle`, which takes a radius, `r`, as a
parameter. Here is a simple solution that uses `polygon` to draw a
50-sided polygon:
``` python
def circle(t, r):
circumference = 2 * math.pi * r
n = 50
length = circumference / n
polygon(t, n, length)
```
The first line computes the circumference of a circle with radius `r`
using the formula 2 π `<I>`{=html}r`</I>`{=html}. Since we use
`math.pi`, we have to import `math`. By convention, `import` statements
are usually at the beginning of the script.
`n` is the number of line segments in our approximation of a circle, so
`length` is the length of each segment. Thus, `polygon` draws a 50-sides
polygon that approximates a circle with radius `r`.
One limitation of this solution is that `n` is a constant, which means
that for very big circles, the line segments are too long, and for small
circles, we waste time drawing very small segments. One solution would
be to generalize the function by taking `n` as a parameter. This would
give the user (whoever calls `circle`) more control, but the interface
would be less clean.
The **interface** of a function is a summary of how it is used: what are
the parameters? What does the function do? And what is the return value?
An interface is "clean" if it is "as simple as possible, but not
simpler. (Einstein)"
In this example, `r` belongs in the interface because it specifies the
circle to be drawn. `n` is less appropriate because it pertains to the
details of *how* the circle should be rendered.
Rather than clutter up the interface, it is better to choose an
appropriate value of `n` depending on `circumference`:
``` python
def circle(t, r):
circumference = 2 * math.pi * r
n = int(circumference / 3) + 1
length = circumference / n
polygon(t, n, length)
```
Now the number of segments is (approximately) `circumference/3`, so the
length of each segment is (approximately) 3, which is small enough that
the circles look good, but big enough to be efficient, and appropriate
for any size circle.
### Refactoring
When I wrote `circle`, I was able to re-use `polygon` because a
many-sided polygon is a good approximation of a circle. But `arc` is not
as cooperative; we can't use `polygon` or `circle` to draw an arc.
One alternative is to start with a copy of `polygon` and transform it
into `arc`. The result might look like this:
``` python
def arc(t, r, angle):
arc_length = r * math.radians(angle)
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n
for i in range(n):
fd(t, step_length)
lt(t, step_angle)
```
The second half of this function looks like `polygon`, but we can't
re-use `polygon` without changing the interface. We could generalize
`polygon` to take an angle as a third argument, but then `polygon` would
no longer be an appropriate name! Instead, let's call the more general
function `polyline`:
``` python
def polyline(t, n, length, angle):
for i in range(n):
fd(t, length)
lt(t, angle)
```
Now we can rewrite `polygon` and `arc` to use `polyline`:
``` python
def polygon(t, n, length):
angle = 360.0 / n
polyline(t, n, length, angle)
def arc(t, r, angle):
arc_length = r * math.radians(angle)
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
```
Finally, we can rewrite `circle` to use `arc`:
``` python
def circle(t, r):
arc(t, r, 360)
```
This process---rearranging a program to improve function interfaces and
facilitate code re-use---is called **refactoring**. In this case, we
noticed that there was similar code in `arc` and `polygon`, so we
"factored it out" into `polyline`.
If we had planned ahead, we might have written `polyline` first and
avoided refactoring, but often you don't know enough at the beginning of
a project to design all the interfaces. Once you start coding, you
understand the problem better. Sometimes refactoring is a sign that you
have learned something.
### A development plan
A **development plan** is a process for writing programs. The process we
used in this case study is "encapsulation and generalization." The steps
of this process are:
- Start by writing a small program with no function definitions.
```{=html}
<!-- -->
```
- Once you get the program working, encapsulate it in a function
and give it a name.
- Generalize the function by adding appropriate parameters.
```{=html}
<!-- -->
```
- Repeat steps 1--3 until you have a set of working functions.
Copy and paste working code to avoid retyping (and re-debugging).
- Look for opportunities to improve the program by refactoring.
For example, if you have similar code in several places, consider
factoring it into an appropriately general function.
This process has some drawbacks---we will see alternatives later---but
it can be useful if you don't know ahead of time how to divide the
program into functions. This approach lets you design as you go along.
### docstring
A **docstring** is a string at the beginning of a function that explains
the interface ("doc" is short for "documentation"). Here is an example:
``` python
def polyline(t, length, n, angle):
"""Draw n line segments with the given length and
angle (in degrees) between them. t is a turtle.
"""
for i in range(n):
fd(t, length)
lt(t, angle)
```
This docstring is a triple-quoted string, also known as a multiline
string because the triple quotes allow the string to span more than one
line.
It is terse, but it contains the essential information someone would
need to use this function. It explains concisely what the function does
(without getting into the details of how it does it). It explains what
effect each parameter has on the behavior of the function and what type
each parameter should be (if it is not obvious).
Writing this kind of documentation is an important part of interface
design. A well-designed interface should be simple to explain; if you
are having a hard time explaining one of your functions, that might be a
sign that the interface could be improved.
### Debugging
An interface is like a contract between a function and a caller. The
caller agrees to provide certain parameters and the function agrees to
do certain work.
For example, `polyline` requires four arguments. The first has to be a
Turtle (or some other object that works with `fd` and `lt`). The second
has to be a number, and it should probably be positive, although it
turns out that the function works even if it isn't. The third argument
should be an integer; `range` complains otherwise (depending on which
version of Python you are running). The fourth has to be a number, which
is understood to be in degrees.
These requirements are called **preconditions** because they are
supposed to be true before the function starts executing. Conversely,
conditions at the end of the function are **postconditions**.
Postconditions include the intended effect of the function (like drawing
line segments) and any side effects (like moving the Turtle or making
other changes in the World).
Preconditions are the responsibility of the caller. If the caller
violates a (properly documented!) precondition and the function doesn't
work correctly, the bug is in the caller, not the function. However, for
purposes of debugging it is often a good idea for functions to check
their preconditions rather than assume they are true. If every function
checks its preconditions before starting, then if something goes wrong,
you will know which function to blame.
### Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**instance:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A member of a set. The TurtleWorld in this chapter is a member of the
set of TurtleWorlds.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**loop:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A part of a program that can execute repeatedly.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**encapsulation:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of transforming a sequence of statements into a function
definition.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**generalization:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of replacing something unnecessarily specific (like a
number) with something appropriately general (like a variable or
parameter).
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**keyword argument:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An argument that includes the name of the parameter as a "keyword."
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**interface:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A description of how to use a function, including the name and
descriptions of the arguments and return value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**development plan:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A process for writing programs.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**docstring:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A string that appears in a function definition to document the
function's interface.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**precondition:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A requirement that should be satisfied by the caller before a function
starts.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**postcondition:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A requirement that should be satisfied by the function before it ends.
```{=html}
</DD>
```
```{=html}
</DL>
```
### Exercises
**Exercise 1** *Download the code in this chapter from
**\'`thinkpython.com/code/polygon.py`**\'.*
- \'\'Write appropriate docstrings for **\'`polygon`**\',
**\'`arc`**\' and
**\'`circle`**\'.\'\'
- \'\'Draw a stack diagram that shows the state of the program
while executing **\'`circle(bob, radius)`**\'. You can do the arithmetic
by hand or add **\'`print`**\' statements to the code.\'\'
- \'\'The version of **\'`arc`**\' in Section **\'4.7**\' is not
very accurate because the linear approximation of the circle is always
outside the true circle. As a result, the turtle ends up a few units
away from the correct destination. My solution shows a way to reduce the
effect of this error. Read the code and see if it makes sense to you. If
you draw a diagram, you might see how it works.\'\'
**Exercise 2** *Write an appropriately general set of functions that
can draw flowers like this:*
```{=html}
<DIV CLASS="center">
```
*`<IMG SRC="book005.png">`{=html}*
```{=html}
</DIV>
```
*You can download a solution from
**\'`thinkpython.com/code/flower.py`**\'.*
**Exercise 3** *Write an appropriately general set of functions that
can draw shapes like this:*
```{=html}
<DIV CLASS="center">
```
*`<IMG SRC="book006.png">`{=html}*
```{=html}
</DIV>
```
*You can download a solution from
**\'`thinkpython.com/code/pie.py`**\'.*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 4** ***\'**\'* *The letters of the alphabet can be
constructed from a moderate number of basic elements, like vertical and
horizontal lines and a few curves. Design a font that can be drawn with
a minimal number of basic elements and then write functions that draw
letters of the alphabet.*
*You should write one function for each letter, with
names`draw_a`,`draw_b`, etc., and put your functions in a file named
**\'`letters.py`**\'. You can download a "turtle typewriter" from
**\'`thinkpython.com/code/typewriter.py`**\' to help you test your
code.*
*You can download a solution from
**\'`thinkpython.com/code/letters.py`**\'.*
|
# Think Python/Conditional and recursion
## Modulus operator
The **modulus operator** works on
integers and yields the remainder when the first operand is divided by
the second. In Python, the modulus operator is a percent sign (`%`). The
syntax is the same as for other operators:
``` python
>>> quotient = 7 // 3
>>> print(quotient)
2
>>> remainder = 7 % 3
>>> print(remainder)
1
```
So 7 divided by 3 is 2 with 1 left over.
The modulus operator turns out to be surprisingly useful. For example,
you can check whether one number is divisible by another---if `x % y` is
zero, then `x` is divisible by `y`.
Also, you can extract the right-most digit or digits from a number. For
example, `x % 10` yields the right-most digit of `x` (in base 10).
Similarly `x % 100` yields the last two digits.
## Boolean expressions
A **boolean expression** is an expression that is either true or false.
The following examples use the operator `==`, which compares two
operands and produces `True` if they are equal and `False` otherwise:
``` python
>>> 5 == 5
True
>>> 5 == 6
False
```
`True` and `False` are special values that belong to the type `bool`;
they are not strings:
``` python
>>> type(True)
<type 'bool'>
>>> type(False)
<type 'bool'>
```
The `==` operator is one of the **comparison operators**; the others
are:
``` python
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
```
Although these operations are probably familiar to you, the Python
symbols are different from the mathematical symbols. A common error is
to use a single equal sign (`=`) instead of a double equal sign (`==`).
Remember that `=` is an assignment operator and `==` is a comparison
operator. There is no such thing as `=<` or `=>`.
## Logical operators
There are three **logical operators**: `and`, `or`, and `not`. The
semantics (meaning) of these operators is similar to their meaning in
English. For example, `x > 0 and x < 10` is true only if `x` is greater
than 0 *and* less than 10.
`n%2 == 0 or n%3 == 0` is true if *either* of the conditions is true,
that is, if the number is divisible by 2 *or* 3.
Finally, the `not` operator negates a boolean expression, so
`not (x > y)` is true if `x > y` is false, that is, if `x` is less than
or equal to `y`.
Strictly speaking, the operands of the logical operators should be
boolean expressions, but Python is not very strict. Any nonzero number
is interpreted as "true."
``` python
>>> 17 and True
True
```
This flexibility can be useful, but there are some subtleties to it that
might be confusing. You might want to avoid it (unless you know what you
are doing).
## Conditional execution
In order to write useful programs, we almost always need the ability to
check conditions and change the behavior of the program accordingly.
**Conditional statements** give us this ability. The simplest form is
the `if` statement:
``` python
if x > 0:
print 'x is positive'
```
The boolean expression after the `if` statement is called the
**condition**. If it is true, then the indented statement gets executed.
If not, nothing happens.
`if` statements have the same structure as function definitions: a
header followed by an indented block. Statements like this are called
**compound statements**.
There is no limit on the number of statements that can appear in the
body, but there has to be at least one. Occasionally, it is useful to
have a body with no statements (usually as a place keeper for code you
haven\'t written yet). In that case, you can use the `pass` statement,
which does nothing.
``` python
if x < 0:
pass # need to handle negative values!
```
## Alternative execution
A second form of the `if` statement is **alternative execution**, in
which there are two possibilities and the condition determines which one
gets executed. The syntax looks like this:
``` python
if x % 2 == 0:
print 'x is even'
else:
print 'x is odd'
```
If the remainder when `x` is divided by 2 is 0, then we know that `x` is
even, and the program displays a message to that effect. If the
condition is false, the second set of statements is executed. Since the
condition must be true or false, exactly one of the alternatives will be
executed. The alternatives are called **branches**, because they are
branches in the flow of execution.
## Chained conditionals
Sometimes there are more than two possibilities and we need more than
two branches. One way to express a computation like that is a **chained
conditional**:
``` python
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
```
`elif` is an abbreviation of "else if." Again, exactly one branch will
be executed. There is no limit on the number of `elif` statements. If
there is an `else` clause, it has to be at the end, but there doesn\'t
have to be one.
``` python
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()
```
Each condition is checked in order. If the first is false, the next is
checked, and so on. If one of them is true, the corresponding branch
executes, and the statement ends. Even if more than one condition is
true, only the first true branch executes.
## Nested conditionals
One conditional can also be nested within another. We could have written
the trichotomy example like this:
``` python
if x == y:
print 'x and y are equal'
else:
if x < y:
print 'x is less than y'
else:
print 'x is greater than y'
```
The outer conditional contains two branches. The first branch contains a
simple statement. The second branch contains another `if` statement,
which has two branches of its own. Those two branches are both simple
statements, although they could have been conditional statements as
well.
Although the indentation of the statements makes the structure apparent,
**nested conditionals** become difficult to read very quickly. In
general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional
statements. For example, we can rewrite the following code using a
single conditional:
``` python
if 0 < x:
if x < 10:
print 'x is a positive single-digit number.'
```
The `print` statement is executed only if we make it past both
conditionals, so we can get the same effect with the `and` operator:
``` python
if 0 < x and x < 10:
print 'x is a positive single-digit number.'
```
## Recursion
It is legal for one function to call another; it is also legal for a
function to call itself. It may not be obvious why that is a good thing,
but it turns out to be one of the most magical things a program can do.
For example, look at the following function:
``` python
def countdown(n):
if n <= 0:
print 'Blastoff!'
else:
print n
countdown(n-1)
```
If `n` is 0 or negative, it outputs the word, "Blastoff!" Otherwise, it
outputs `n` and then calls a function named
`countdown`---itself---passing `n-1` as an argument.
What happens if we call this function like this?
``` python
>>> countdown(3)
```
The execution of `countdown` begins with `n=3`, and since `n` is greater
than 0, it outputs the value 3, and then calls itself\...
> The execution of `countdown` begins with `n=2`, and since `n` is
> greater than 0, it outputs the value 2, and then calls itself\...
>
> > The execution of `countdown` begins with `n=1`, and since `n` is
> > greater than 0, it outputs the value 1, and then calls itself\...
> >
> > > The execution of `countdown` begins with `n=0`, and since `n` is
> > > not greater than 0, it outputs the word, "Blastoff!" and then
> > > returns.
> >
> > The `countdown` that got `n=1` returns.
>
> The `countdown` that got `n=2` returns.
The `countdown` that got `n=3` returns.
And then you\'re back in `__main__`. So, the total output looks like
this:
``` python
3
2
1
Blastoff!
```
A function that calls itself is **recursive**; the process is called
**recursion**.
As another example, we can write a function that prints a string `n`
times.
``` python
def print_n(s, n):
if n <= 0:
return
print s
print_n(s, n-1)
```
If `n <= 0` the `return` statement exits the function. The flow of
execution immediately returns to the caller, and the remaining lines of
the function are not executed.
The rest of the function is similar to `countdown`: if `n` is greater
than 0, it displays `s` and then calls itself to display `s` *n*−1
additional times. So the number of lines of output is `1 + (n - 1)`,
which adds up to `n`.
For simple examples like this, it is probably easier to use a `for`
loop. But we will see examples later that are hard to write with a `for`
loop and easy to write with recursion, so it is good to start early.
## Stack diagrams for recursive functions
In Section 3.10, we used a stack diagram to represent the state of a
program during a function call. The same kind of diagram can help
interpret a recursive function.
Every time a function gets called, Python creates a new function frame,
which contains the function\'s local variables and parameters. For a
recursive function, there might be more than one frame on the stack at
the same time.
This figure shows a stack diagram for `countdown` called with `n = 3`:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book007.png">`{=html}
```{=html}
</DIV>
```
As usual, the top of the stack is the frame for `__main__`. It is empty
because we did not create any variables in `__main__` or pass any
arguments to it.
The four `countdown` frames have different values for the parameter `n`.
The bottom of the stack, where `n=0`, is called the **base case**. It
does not make a recursive call, so there are no more frames.
> Draw a stack diagram for `print_n` called with `s = 'Hello'` and
> `n=2`.
> Write a function called `do_n` that takes a function object and a
> number, `n` as arguments, and that calls the given function `n` times.
## Infinite recursion
If a recursion never reaches a base case, it goes on making recursive
calls forever, and the program never terminates. This is known as
**infinite recursion**, and it is generally not a good idea. Here is a
minimal program with an infinite recursion:
``` python
def recurse():
recurse()
```
In most programming environments, a program with infinite recursion does
not really run forever. Python reports an error message when the maximum
recursion depth is reached:
``` python
File "<stdin>", line 2, in recurse
File "<stdin>", line 2, in recurse
File "<stdin>", line 2, in recurse
.
.
.
File "<stdin>", line 2, in recurse
RuntimeError: Maximum recursion depth exceeded
```
This traceback is a little bigger than the one we saw in the previous
chapter. When the error occurs, there are 1000 `recurse` frames on the
stack!
## Keyboard input
The programs we have written so far are a bit rude in the sense that
they accept no input from the user. They just do the same thing every
time.
Python provides a built-in function called `raw_input` that gets input
from the keyboard.[^1] When this function is called, the program stops
and waits for the user to type something. When the user presses Return
or Enter, the program resumes and `raw_input` returns what the user
typed as a string.
``` python
>>> input = raw_input()
What are you waiting for?
>>> print input
What are you waiting for?
```
Before getting input from the user, it is a good idea to print a prompt
telling the user what to input. `raw_input` can take a prompt as an
argument:
``` python
>>> name = raw_input('What...is your name?\n')
What...is your name?
Arthur, King of the Britons!
>>> print name
Arthur, King of the Britons!
```
The sequence `\n` at the end of the prompt represents a **newline**,
which is a special character that causes a line break. That\'s why the
user\'s input appears below the prompt.
If you expect the user to type an integer, you can try to convert the
return value to `int`:
``` python
>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
17
>>> int(speed)
17
```
But if the user types something other than a string of digits, you get
an error:
``` python
>>> speed = raw_input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int()
```
We will see how to handle this kind of error later.
## Debugging
The traceback Python displays when an error occurs contains a lot of
information, but it can be overwhelming, especially when there are many
frames on the stack. The most useful parts are usually:
- What kind of error it was, and
```{=html}
<!-- -->
```
- Where it occurred.
Syntax errors are usually easy to find, but there are a few gotchas.
Whitespace errors can be tricky because spaces and tabs are invisible
and we are used to ignoring them.
``` python
>>> x = 5
>>> y = 6
File "<stdin>", line 1
y = 6
^
SyntaxError: invalid syntax
```
In this example, the problem is that the second line is indented by one
space. But the error message points to `y`, which is misleading. In
general, error messages indicate where the problem was discovered, but
the actual error might be earlier in the code, sometimes on a previous
line.
The same is true of runtime errors. Suppose you are trying to compute a
signal-to-noise ratio in decibels. The formula is *SNR*~*db*~ = 10
log~10~ (*P*~*signal*~ / *P*~*noise*~). In Python, you might write
something like this:
``` python
import math
signal_power = 9
noise_power = 10
ratio = signal_power / noise_power
decibels = 10 * math.log10(ratio)
print decibels
```
But when you run it, you get an error message:
``` python
Traceback (most recent call last):
File "snr.py", line 5, in ?
decibels = 10 * math.log10(ratio)
OverflowError: math range error
```
The error message indicates line 5, but there is nothing wrong with that
line. To find the real error, it might be useful to print the value of
`ratio`, which turns out to be 0. The problem is in line 4, because
dividing two integers does floor division. The solution is to represent
signal power and noise power with floating-point values.
In general, error messages tell you where the problem was discovered,
but that is often not where it was caused.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**modulus operator:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An operator, denoted with a percent sign (`%`), that works on integers
and yields the remainder when one number is divided by another.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**boolean expression:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An expression whose value is either `True` or `False`.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**comparison operator:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the operators that compares its operands: `==`, `!=`, `>`, `<`,
`>=`, and `<=`.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**logical operator:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the operators that combines boolean expressions: `and`, `or`, and
`not`.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**conditional statement:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A statement that controls the flow of execution depending on some
condition.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**condition:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The boolean expression in a conditional statement that determines which
branch is executed.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**compound statement:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A statement that consists of a header and a body. The header ends with a
colon (:). The body is indented relative to the header.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**body:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The sequence of statements within a compound statement.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**branch:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the alternative sequences of statements in a conditional
statement.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**chained conditional:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A conditional statement with a series of alternative branches.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**nested conditional:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A conditional statement that appears in one of the branches of another
conditional statement.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**recursion:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of calling the function that is currently executing.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**base case:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A conditional branch in a recursive function that does not make a
recursive call.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**infinite recursion:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A function that calls itself recursively without ever reaching the base
case. Eventually, an infinite recursion causes a runtime error.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
**Exercise 1** \'\'\'
*Fermat\'s Last Theorem says that there are no integers***\'a,b,
andc***\' such that*
```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
**\'a**\'^**\'n**\'^* + *b**\'^**\'n**\'^* = *c**\'^**\'n**\'^* *
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
for any values of ***\'n***\' greater than 2.\'\'
- *Write a function named`check_fermat`*\'\' that takes four
parameters---**\'`a`**\', **\'`b`**\', **\'`c`**\' and **\'`n`**\'---and
that checks to see if Fermat\'s theorem holds. If ***\'n***\' is greater
than 2 and it turns out to be true that \'\'
```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
***\'a`<SUP>`{=html}n`</SUP>`{=html}**\' + *b***\'`<SUP>`{=html}n`</SUP>`{=html}**\' = *c***\'`<SUP>`{=html}n`</SUP>`{=html}**\' *\'\'
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
**\' the program should print, "Holy smokes, Fermat was wrong!"
Otherwise the program should print, "No, that doesn't work."**\'
- \'\'\'\'Write a function that prompts the user to input values
for \'\'***\'`a`*,*`b`*,*`c`*and*`n`*****, converts them to integers,
and uses**\'**`'check_fermat`**`'`**\' to check whether they violate
Fermat\'s theorem.**\'
**Exercise 2** *If you are given three sticks, you may or may not be
able to arrange them in a triangle. For example, if one of the sticks is
12 inches long and the other two are one inch long, it is clear that you
will not be able to get the short sticks to meet in the middle. For any
three lengths, there is a simple test to see if it is possible to form a
triangle:*
> *"If any of the three lengths is greater than the sum of the other
> two, then you cannot form a triangle. Otherwise, you can.[^2]"*
- *Write a function named`is_triangle`*\'\' that takes three
integers as arguments, and that prints either "Yes" or "No," depending
on whether you can or cannot form a triangle from sticks with the given
lengths.\'\'
- \'\'Write a function that prompts the user to input three stick
lengths, converts them to integers, and uses **`is_triangle`** to check
whether sticks with the given lengths can form a triangle.\'\'
The following exercises use TurtleWorld from Chapter 4:
**Exercise 3** *Read the following function and see if you can figure
out what it does. Then run it (see the examples in Chapter **\'4**\').*
``` python
''def draw(t, length, n):
if n == 0:
return
angle = 50
fd(t, length*n)
lt(t, angle)
draw(t, length, n-1)
rt(t, 2*angle)
draw(t, length, n-1)
lt(t, angle)
bk(t, length*n)
''
```
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 4**
*The Koch curve is a fractal that looks something like this:*
```{=html}
<DIV CLASS="center">
```
*`<IMG SRC="book008.png">`{=html}*
```{=html}
</DIV>
```
*To draw a Koch curve with length***\'x***\', all you have to do is*
- *Draw a Koch curve with length*\'*\'x*/3\'*\'.*
```{=html}
<!-- -->
```
- *Turn left 60 degrees.*
```{=html}
<!-- -->
```
- *Draw a Koch curve with length*\'*\'x*/3\'*\'.*
```{=html}
<!-- -->
```
- *Turn right 120 degrees.*
```{=html}
<!-- -->
```
- *Draw a Koch curve with length*\'*\'x*/3\'*\'.*
```{=html}
<!-- -->
```
- *Turn left 60 degrees.*
```{=html}
<!-- -->
```
- *Draw a Koch curve with length*\'*\'x*/3\'*\'.*
*The only exception is if***\'xis less than 3. In that case, you can
just draw a straight line with lengthx***\'.*
- \'\'Write a function called **\'`koch`**\' that takes a turtle and
a length as parameters, and that uses the turtle to draw a Koch curve
with the given length.\'\'
- \'\'Write a function called **\'`snowflake`**\' that draws three
Koch curves to make the outline of a snowflake.You can see my solution
at **\'`thinkpython.com/code/koch.py`**\'.\'\'
- \'\'The Koch curve can be generalized in several ways. See
**\'`wikipedia.org/wiki/Koch_snowflake`**\' for examples and implement
your favorite.\'\'
## Notes
[^1]: In Python 3.0, this function is named `input`
[^2]: If the sum of two lengths equals the third, they form what is
called a "degenerate" triangle.
|
# Think Python/Fruitful functions
## Return values
Some of the built-in functions we have used, such as the math functions,
produce results. Calling the function generates a value, which we
usually assign to a variable or use as part of an expression.
``` python
e = math.exp(1.0)
height = radius * math.sin(radians)
```
All of the functions we have written so far are void; they print
something or move turtles around, but their return value is `None`.
In this chapter, we are (finally) going to write fruitful functions. The
first example is `area`, which returns the area of a circle with the
given radius:
``` python
def area(radius):
temp = math.pi * radius**2
return temp
```
We have seen the `return` statement before, but in a fruitful function
the `return` statement includes an expression. This statement means:
"Return immediately from this function and use the following expression
as a return value." The expression can be arbitrarily complicated, so we
could have written this function more concisely:
``` python
def area(radius):
return math.pi * radius**2
```
On the other hand, **temporary variables** like `temp` often make
debugging easier.
Sometimes it is useful to have multiple return statements, one in each
branch of a conditional:
``` python
def absolute_value(x):
if x < 0:
return -x
else:
return x
```
Since these `return` statements are in an alternative conditional, only
one will be executed.
As soon as a return statement executes, the function terminates without
executing any subsequent statements. Code that appears after a `return`
statement, or any other place the flow of execution can never reach, is
called **dead code**.
In a fruitful function, it is a good idea to ensure that every possible
path through the program hits a `return` statement. For example:
``` python
def absolute_value(x):
if x < 0:
return -x
if x > 0:
return x
```
This function is incorrect because if `x` happens to be 0, neither
condition is true, and the function ends without hitting a `return`
statement. If the flow of execution gets to the end of a function, the
return value is `None`, which is not the absolute value of 0.
``` python
>>> print absolute_value(0)
None
```
By the way, Python provides a built-in function called `abs` that
computes absolute values.
### Exercise 1
\'\'Write a **\'`compare`**\' function that returns **\'`1`**\' if
**\'`x > y`**\', **\'`0`**\' if **\'`x == y`**\', and **\'`-1`**\' if
**\'`x < y`**\'.
## Incremental development
As you write larger functions, you might find yourself spending more
time debugging.
To deal with increasingly complex programs, you might want to try a
process called **incremental development**. The goal of incremental
development is to avoid long debugging sessions by adding and testing
only a small amount of code at a time.
As an example, suppose you want to find the distance between two points,
given by the coordinates (`<I>`{=html}x`</I>`{=html}~1~,
`<I>`{=html}y`</I>`{=html}~1~) and (`<I>`{=html}x`</I>`{=html}~2~,
`<I>`{=html}y`</I>`{=html}~2~). By the Pythagorean theorem, the distance
is:
$\text{distance} = \sqrt{ (x_2 - x_1)^2 + (y_2 - y_1)^2}$
The first step is to consider what a `distance` function should look
like in Python. In other words, what are the inputs (parameters) and
what is the output (return value)?
In this case, the inputs are two points, which you can represent using
four numbers. The return value is the distance, which is a
floating-point value.
Already you can write an outline of the function:
``` python
def distance(x1, y1, x2, y2):
return 0.0
```
Obviously, this version doesn\'t compute distances; it always returns
zero. But it is syntactically correct, and it runs, which means that you
can test it before you make it more complicated.
To test the new function, call it with sample arguments:
``` python
>>> distance(1, 2, 4, 6)
0.0
```
I chose these values so that the horizontal distance is 3 and the
vertical distance is 4; that way, the result is 5 (the hypotenuse of a
3-4-5 triangle). When testing a function, it is useful to know the right
answer.
At this point we have confirmed that the function is syntactically
correct, and we can start adding code to the body. A reasonable next
step is to find the differences `<I>`{=html}x`</I>`{=html}~2~ −
`<I>`{=html}x`</I>`{=html}~1~ and `<I>`{=html}y`</I>`{=html}~2~ −
`<I>`{=html}y`</I>`{=html}~1~. The next version stores those values in
temporary variables and prints them.
``` python
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
print 'dx is', dx
print 'dy is', dy
return 0.0
```
If the function is working, it should display `'dx is 3'` and
`’dy is 4’`. If so, we know that the function is getting the right
arguments and performing the first computation correctly. If not, there
are only a few lines to check.
Next we compute the sum of squares of `dx` and `dy`:
``` python
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
print 'dsquared is: ', dsquared
return 0.0
```
Again, you would run the program at this stage and check the output
(which should be 25). Finally, you can use `math.sqrt` to compute and
return the result:
``` python
def distance(x1, y1, x2, y2):
dx = x2 - x1
dy = y2 - y1
dsquared = dx**2 + dy**2
result = math.sqrt(dsquared)
return result
```
If that works correctly, you are done. Otherwise, you might want to
print the value of `result` before the return statement.
The final version of the function doesn't display anything when it runs;
it only returns a value. The `print` statements we wrote are useful for
debugging, but once you get the function working, you should remove
them. Code like that is called **scaffolding** because it is helpful for
building the program but is not part of the final product.
When you start out, you should add only a line or two of code at a time.
As you gain more experience, you might find yourself writing and
debugging bigger chunks. Either way, incremental development can save
you a lot of debugging time.
The key aspects of the process are:
- Start with a working program and make small incremental changes. At
any point, if there is an error, you should have a good idea where
it is.
- Use temporary variables to hold intermediate values so you can
display and check them.
- Once the program is working, you might want to remove some of the
scaffolding or consolidate multiple statements into compound
expressions, but only if it does not make the program difficult to
read.
### Exercise 2
*Use incremental development to write a function called
**\'`hypotenuse`**\' that returns the length of the hypotenuse of a
right triangle given the lengths of the two legs as arguments. Record
each stage of the development process as you go.*
## Composition
As you should expect by now, you can call one function from within
another. This ability is called **composition**.
As an example, we'll write a function that takes two points, the center
of the circle and a point on the perimeter, and computes the area of the
circle.
Assume that the center point is stored in the variables `xc` and `yc`,
and the perimeter point is in `xp` and `yp`. The first step is to find
the radius of the circle, which is the distance between the two points.
We just wrote a function, `distance`, that does that:
``` python
radius = distance(xc, yc, xp, yp)
```
The next step is to find the area of a circle with that radius; we just
wrote that, too:
``` python
result = area(radius)
```
Encapsulating these steps in a function, we get:
``` python
def circle_area(xc, yc, xp, yp):
radius = distance(xc, yc, xp, yp)
result = area(radius)
return result
```
The temporary variables `radius` and `result` are useful for development
and debugging, but once the program is working, we can make it more
concise by composing the function calls:
``` python
def circle_area(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp))
```
## Boolean functions
Functions can return booleans, which is often convenient for hiding
complicated tests inside functions. For example:
``` python
def is_divisible(x, y):
if x % y == 0:
return True
else:
return False
```
It is common to give boolean functions names that sound like yes/no
questions; `is_divisible` returns either `True` or `False` to indicate
whether `x` is divisible by `y`.
Here is an example:
``` python
>>> is_divisible(6, 4)
False
>>> is_divisible(6, 3)
True
```
The result of the `==` operator is a boolean, so we can write the
function more concisely by returning it directly:
``` python
def is_divisible(x, y):
return x % y == 0
```
Boolean functions are often used in conditional statements:
``` python
if is_divisible(x, y):
print 'x is divisible by y'
```
It might be tempting to write something like:
``` python
if is_divisible(x, y) == True:
print 'x is divisible by y'
```
But the extra comparison is unnecessary.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 3** *Write a function`is_between(x, y, z)`that returns
**\'`True`**\' if **\'`<I>`{=html}x`</I>`{=html} ≤
`<I>`{=html}y`</I>`{=html} ≤ `<I>`{=html}z`</I>`{=html}**\' or
**\'`False`**\' otherwise.*
```{=html}
</DIV>
```
## More recursion
We have only covered a small subset of Python, but you might be
interested to know that this subset is a *complete* programming
language, which means that anything that can be computed can be
expressed in this language. Any program ever written could be rewritten
using only the language features you have learned so far (actually, you
would need a few commands to control devices like the keyboard, mouse,
disks, etc., but that's all).
Proving that claim is a nontrivial exercise first accomplished by Alan
Turing, one of the first computer scientists (some would argue that he
was a mathematician, but a lot of early computer scientists started as
mathematicians). Accordingly, it is known as the Turing Thesis. For a
more complete (and accurate) discussion of the Turing Thesis, I
recommend Michael Sipser's book *Introduction to the Theory of
Computation*.
To give you an idea of what you can do with the tools you have learned
so far, we'll evaluate a few recursively defined mathematical functions.
A recursive definition is similar to a circular definition, in the sense
that the definition contains a reference to the thing being defined. A
truly circular definition is not very useful:
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**frabjuous:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An adjective used to describe something that is frabjuous.
```{=html}
</DD>
```
```{=html}
</DL>
```
If you saw that definition in the dictionary, you might be annoyed. On
the other hand, if you looked up the definition of the factorial
function, denoted with the symbol !, you might get something like this:
```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
```{=html}
<TABLE CELLSPACING=6 CELLPADDING=0>
```
```{=html}
<TR>
```
```{=html}
<TD ALIGN=right NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=center NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=left NOWRAP>
```
0! = 1
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
<TR>
```
```{=html}
<TD ALIGN=right NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=center NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=left NOWRAP>
```
`<I>`{=html}n`</I>`{=html}! = `<I>`{=html}n`</I>`{=html} (`<I>`{=html}n`</I>`{=html}−1)!
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
This definition says that the factorial of 0 is 1, and the factorial of
any other value, `<I>`{=html}n`</I>`{=html}, is
`<I>`{=html}n`</I>`{=html} multiplied by the factorial of
`<I>`{=html}n`</I>`{=html}−1.
So 3! is 3 times 2!, which is 2 times 1!, which is 1 times 0!. Putting
it all together, 3! equals 3 times 2 times 1 times 1, which is 6.
If you can write a recursive definition of something, you can usually
write a Python program to evaluate it. The first step is to decide what
the parameters should be. In this case it should be clear that
`factorial` takes an integer:
``` python
def factorial(n):
```
If the argument happens to be 0, all we have to do is return 1:
``` python
def factorial(n):
if n == 0:
return 1
```
Otherwise, and this is the interesting part, we have to make a recursive
call to find the factorial of `<I>`{=html}n`</I>`{=html}−1 and then
multiply it by `<I>`{=html}n`</I>`{=html}:
``` python
def factorial(n):
if n == 0:
return 1
else:
recurse = factorial(n-1)
result = n * recurse
return result
```
The flow of execution for this program is similar to the flow of
`countdown` in Section 5.8. If we call `factorial` with the value 3:
Since 3 is not 0, we take the second branch and calculate the factorial
of `n-1`\...
> Since 2 is not 0, we take the second branch and calculate the
> factorial of `n-1`\...
>
> > Since 1 is not 0, we take the second branch and calculate the
> > factorial of `n-1`\...
> >
> > > Since 0 *is* 0, we take the first branch and return 1 without
> > > making any more recursive calls.
> >
> > The return value (1) is multiplied by `<I>`{=html}n`</I>`{=html},
> > which is 1, and the result is returned.
>
> The return value (1) is multiplied by `<I>`{=html}n`</I>`{=html},
> which is 2, and the result is returned.
The return value (2) is multiplied by `<I>`{=html}n`</I>`{=html}, which
is 3, and the result, 6, becomes the return value of the function call
that started the whole process.
Here is what the stack diagram looks like for this sequence of function
calls:
\
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book009.png">`{=html}
```{=html}
</DIV>
```
\
The return values are shown being passed back up the stack. In each
frame, the return value is the value of `result`, which is the product
of `n` and `recurse`.
In the last frame, the local variables `recurse` and `result` do not
exist, because the branch that creates them does not execute.
## Leap of faith
Following the flow of execution is one way to read programs, but it can
quickly become labyrinthine. An alternative is what I call the "leap of
faith." When you come to a function call, instead of following the flow
of execution, you *assume* that the function works correctly and returns
the right result.
In fact, you are already practicing this leap of faith when you use
built-in functions. When you call `math.cos` or `math.exp`, you don't
examine the bodies of those functions. You just assume that they work
because the people who wrote the built-in functions were good
programmers.
The same is true when you call one of your own functions. For example,
in Section 6.4, we wrote a function called `is_divisible` that
determines whether one number is divisible by another. Once we have
convinced ourselves that this function is correct---by examining the
code and testing---we can use the function without looking at the body
again.
The same is true of recursive programs. When you get to the recursive
call, instead of following the flow of execution, you should assume that
the recursive call works (yields the correct result) and then ask
yourself, "Assuming that I can find the factorial of
`<I>`{=html}n`</I>`{=html}−1, can I compute the factorial of
`<I>`{=html}n`</I>`{=html}?" In this case, it is clear that you can, by
multiplying by `<I>`{=html}n`</I>`{=html}.
Of course, it\'s a bit strange to assume that the function works
correctly when you haven\'t finished writing it, but that\'s why it\'s
called a leap of faith!
## One more example
After `factorial`, the most common example of a recursively defined
mathematical function is `fibonacci`, which has the following
definition[^1]:
```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
```{=html}
<TABLE CELLSPACING=6 CELLPADDING=0>
```
```{=html}
<TR>
```
```{=html}
<TD ALIGN=right NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=center NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=left NOWRAP>
```
`<I>`{=html}fibonacci`</I>`{=html}(0) = 0
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
<TR>
```
```{=html}
<TD ALIGN=right NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=center NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=left NOWRAP>
```
`<I>`{=html}fibonacci`</I>`{=html}(1) = 1
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
<TR>
```
```{=html}
<TD ALIGN=right NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=center NOWRAP>
```
```{=html}
</TD>
```
```{=html}
<TD ALIGN=left NOWRAP>
```
`<I>`{=html}fibonacci`</I>`{=html}(`<I>`{=html}n`</I>`{=html}) = `<I>`{=html}fibonacci`</I>`{=html}(`<I>`{=html}n`</I>`{=html}−1) + `<I>`{=html}fibonacci`</I>`{=html}(`<I>`{=html}n`</I>`{=html}−2);
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
Translated into Python, it looks like this:
``` python
def fibonacci (n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
```
If you try to follow the flow of execution here, even for fairly small
values of `<I>`{=html}n`</I>`{=html}, your head explodes. But according
to the leap of faith, if you assume that the two recursive calls work
correctly, then it is clear that you get the right result by adding them
together.
## Checking types
What happens if we call `factorial` and give it 1.5 as an argument?
``` python
>>> factorial(1.5)
RuntimeError: Maximum recursion depth exceeded
```
It looks like an infinite recursion. But how can that be? There is a
base case---when `n == 0`. But if `n` is not an integer, we can *miss*
the base case and recurse forever.
In the first recursive call, the value of `n` is 0.5. In the next, it is
-0.5. From there, it gets smaller (more negative), but it will never be
0.
We have two choices. We can try to generalize the `factorial` function
to work with floating-point numbers, or we can make `factorial` check
the type of its argument. The first option is called the gamma
function[^2] and it's a little beyond the scope of this book. So we'll
go for the second.
We can use the built-in function `isinstance` to verify the type of the
argument. While we're at it, we can also make sure the argument is
positive:
``` python
def factorial (n):
if not isinstance(n, int):
print 'Factorial is only defined for integers.'
return None
elif n < 0:
print 'Factorial is only defined for positive integers.'
return None
elif n == 0:
return 1
else:
return n * factorial(n-1)
```
The first base case handles nonintegers; the second catches negative
integers. In both cases, the program prints an error message and returns
`None` to indicate that something went wrong:
``` python
>>> factorial('fred')
Factorial is only defined for integers.
None
>>> factorial(-2)
Factorial is only defined for positive integers.
None
```
If we get past both checks, then we know that `<I>`{=html}n`</I>`{=html}
is a positive integer, and we can prove that the recursion terminates.
This program demonstrates a pattern sometimes called a **guardian**. The
first two conditionals act as guardians, protecting the code that
follows from values that might cause an error. The guardians make it
possible to prove the correctness of the code.
## Debugging
Breaking a large program into smaller functions creates natural
checkpoints for debugging. If a function is not working, there are three
possibilities to consider:
- There is something wrong with the arguments the function
is getting; a precondition is violated.
- There is something wrong with the function; a postcondition
is violated.
- There is something wrong with the return value or the
way it is being used.
To rule out the first possibility, you can add a `print` statement at
the beginning of the function and display the values of the parameters
(and maybe their types). Or you can write code that checks the
preconditions explicitly.
If the parameters look good, add a `print` statement before each
`return` statement that displays the return value. If possible, check
the result by hand. Consider calling the function with values that make
it easy to check the result (as in Section 6.2).
If the function seems to be working, look at the function call to make
sure the return value is being used correctly (or used at all!).
Adding print statements at the beginning and end of a function can help
make the flow of execution more visible. For example, here is a version
of `factorial` with print statements:
``` python
def factorial(n):
space = ' ' * (4 * n)
print space, 'factorial', n
if n == 0:
print space, 'returning 1'
return 1
else:
recurse = factorial(n-1)
result = n * recurse
print space, 'returning', result
return result
```
`space` is a string of space characters that controls the indentation of
the output. Here is the result of `factorial(5)` :
``` python
factorial 5
factorial 4
factorial 3
factorial 2
factorial 1
factorial 0
returning 1
returning 1
returning 2
returning 6
returning 24
returning 120
```
If you are confused about the flow of execution, this kind of output can
be helpful. It takes some time to develop effective scaffolding, but a
little bit of scaffolding can save a lot of debugging.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**temporary variable:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A variable used to store an intermediate value in a complex calculation.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**dead code:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Part of a program that can never be executed, often because it appears
after a `return` statement.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**`None`:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A special value returned by functions that have no return statement or a
return statement without an argument.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**incremental development:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A program development plan intended to avoid debugging by adding and
testing only a small amount of code at a time.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**scaffolding:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Code that is used during program development but is not part of the
final version.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**guardian:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A programming pattern that uses a conditional statement to check for and
handle circumstances that might cause an error.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 4
*Draw a stack diagram for the following program. What does the program
print?*
``` python
def b(z):
prod = a(z, z)
print z, prod
return prod
def a(x, y):
x = x + 1
return x * y
def c(x, y, z):
sum = x + y + z
pow = b(sum)**2
return pow
x = 1
y = x + 1
print c(x, y+3, x+y)
```
### Exercise 5
*The Ackermann function,
**\'`<I>`{=html}A`</I>`{=html}(`<I>`{=html}m`</I>`{=html},
`<I>`{=html}n`</I>`{=html})**\' is defined[^3]:*
```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
\'\'
$A(M, N) =
\begin{cases}
n + 1 & \mbox{if }m = 0 \\
A(m-1, 1) & \mbox{if } m > 0 \mbox{ and } n = 0 \\
A(m-1, A(m, n-1)) & \mbox{if } m > 0 \mbox{ and } n > 0
\end{cases}$
Write a function named **\'`ack`**\' that evaluates Ackerman's function.
Use your function to evaluate **\'`ack(3, 4)`**\', which should be 125.
What happens for larger values of **\'`m`**\' and **\'`n`**\'?\'\'
### Exercise 6
*A palindrome is a word that is spelled the same backward and forward,
like "noon" and "redivider". Recursively, a word is a palindrome if the
first and last letters are the same and the middle is a palindrome.*
*The following are functions that take a string argument and return the
first, last, and middle letters:*
``` python
def first(word):
return word[0]
def last(word):
return word[-1]
def middle(word):
return word[1:-1]
```
*We'll see how they work in Chapter **\'8**\'.*
- \'\'Type these functions into a file named **\'`palindrome.py`**\'
and test them out. What happens if you call **\'`middle`**\' with a
string with two letters? One letter? What about the empty string, which
is written *`<CODE>`{=html}*\'*\'`</CODE>`{=html}* and contains no
letters?\'\'
- *Write a function called`is_palindrome`*\'\' that takes
a string argument and returns **\'`True`**\' if it is a palindrome and
**\'`False`**\' otherwise. Remember that you can use the built-in
function **\'`len`**\' to check the length of a string.\'\'
### Exercise 7
A number, **\'`<I>`{=html}a`</I>`{=html}**\', is a power of
**\'`<I>`{=html}b`</I>`{=html}**\' if it is divisible by
**\'`<I>`{=html}b`</I>`{=html}**\' and
**\'`<I>`{=html}a`</I>`{=html}/`<I>`{=html}b`</I>`{=html}**\' is a power
of **\'`<I>`{=html}b`</I>`{=html}**\'. Write a function called
**`is_power`** that takes parameters **\'`a`**\' and **\'`b`**\' and
returns **\'`True`**\' if **\'`a`**\' is a power of **\'`b`**\'.
### Exercise 8
*The greatest common divisor (GCD) of **\'`<I>`{=html}a`</I>`{=html}**\'
and **\'`<I>`{=html}b`</I>`{=html}**\' is the largest number that
divides both of them with no remainder*[^4]*.*
*One way to find the GCD of two numbers is Euclid's algorithm, which is
based on the observation that if **\'`<I>`{=html}r`</I>`{=html}**\' is
the remainder when **\'`<I>`{=html}a`</I>`{=html}**\' is divided by
**\'`<I>`{=html}b`</I>`{=html}**\', then
**\'`<I>`{=html}gcd`</I>`{=html}(`<I>`{=html}a`</I>`{=html},
`<I>`{=html}b`</I>`{=html}) =
`<I>`{=html}gcd`</I>`{=html}(`<I>`{=html}b`</I>`{=html},
`<I>`{=html}r`</I>`{=html})**\'. As a base case, we can consider
**\'`<I>`{=html}gcd`</I>`{=html}(`<I>`{=html}a`</I>`{=html}, 0) =
`<I>`{=html}a`</I>`{=html}**\'.*
*Write a function called`gcd`that takes parameters **\'`a`**\' and
**\'`b`**\' and returns their greatest common divisor. If you need help,
see **\'`wikipedia.org/wiki/Euclidean_algorithm`**\'.*
## Notes
[^1]: See `wikipedia.org/wiki/Fibonacci_number`.
[^2]: See `wikipedia.org/wiki/Gamma_function`.
[^3]: See `wikipedia.org/wiki/Ackermann_function`
[^4]: This exercise is based on an example from Abelson and Sussman's
*Structure and Interpretation of Computer Programs*.
|
# Think Python/Iteration
## Multiple assignment
As you may have discovered, it is legal to make more than one assignment
to the same variable. A new assignment makes an existing variable refer
to a new value (and stop referring to the old value).
``` python
bruce = 5
print bruce,
bruce = 7
print bruce
```
The output of this program is `5 7`, because the first time `bruce` is
printed, its value is 5, and the second time, its value is 7. The comma
at the end of the first `print` statement suppresses the newline, which
is why both outputs appear on the same line.
Here is what **multiple assignment** looks like in a state diagram:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book010.png">`{=html}
```{=html}
</DIV>
```
With multiple assignment it is especially important to distinguish
between an assignment operation and a statement of equality. Because
Python uses the equal sign (`=`) for assignment, it is tempting to
interpret a statement like `a = b` as a statement of equality. It is
not!
First, equality is a symmetric relation and assignment is not. For
example, in mathematics, if `<I>`{=html}a`</I>`{=html} = 7 then 7 =
`<I>`{=html}a`</I>`{=html}. But in Python, the statement `a = 7` is
legal and `7 = a` is not.
Furthermore, in mathematics, a statement of equality is either true or
false, for all time. If `<I>`{=html}a`</I>`{=html} =
`<I>`{=html}b`</I>`{=html} now, then `<I>`{=html}a`</I>`{=html} will
always equal `<I>`{=html}b`</I>`{=html}. In Python, an assignment
statement can make two variables equal, but they don't have to stay that
way:
``` python
a = 5
b = a # a and b are now equal
a = 3 # a and b are no longer equal
```
The third line changes the value of `a` but does not change the value of
`b`, so they are no longer equal.
Although multiple assignment is frequently helpful, you should use it
with caution. If the values of variables change frequently, it can make
the code difficult to read and debug.
## Updating variables
One of the most common forms of multiple assignment is an **update**,
where the new value of the variable depends on the old.
``` python
x = x+1
```
This means "get the current value of `x`, add one, and then update `x`
with the new value."
If you try to update a variable that doesn't exist, you get an error,
because Python evaluates the right side before it assigns a value to
`x`:
``` python
>>> x = x+1
NameError: name 'x' is not defined
```
Before you can update a variable, you have to **initialize** it, usually
with a simple assignment:
``` python
>>> x = 0
>>> x = x+1
```
Updating a variable by adding 1 is called an **increment**; subtracting
1 is called a **decrement**.
## The `while` statement
Computers are often used to automate repetitive tasks. Repeating
identical or similar tasks without making errors is something that
computers do well and people do poorly.
We have seen two programs, `countdown` and `print_n`, that use recursion
to perform repetition, which is also called **iteration**. Because
iteration is so common, Python provides several language features to
make it easier. One is the `for` statement we saw in Section 4.2. We'll
get back to that later.
Another is the `while` statement. Here is a version of `countdown` that
uses a `while` statement:
``` python
def countdown(n):
while n > 0:
print n
n = n-1
print 'Blastoff!'
```
You can almost read the `while` statement as if it were English. It
means, "While `n` is greater than 0, display the value of `n` and then
reduce the value of `n` by 1. When you get to 0, display the word
`Blastoff!`"
More formally, here is the flow of execution for a `while` statement:
- Evaluate the condition, yielding `True` or `False`.
- If the condition is false, exit the `while` statement and continue
execution at the next statement.
- If the condition is true, execute the body and then go back to step
1.
This type of flow is called a **loop** because the third step loops back
around to the top.
The body of the loop should change the value of one or more variables so
that eventually the condition becomes false and the loop terminates.
Otherwise the loop will repeat forever, which is called an **infinite
loop**. An endless source of amusement for computer scientists is the
observation that the directions on shampoo, "Lather, rinse, repeat," are
an infinite loop.
In the case of `countdown`, we can prove that the loop terminates
because we know that the value of `n` is finite, and we can see that the
value of `n` gets smaller each time through the loop, so eventually we
have to get to 0. In other cases, it is not so easy to tell:
``` python
def sequence(n):
while n != 1:
print n,
if n%2 == 0: # n is even
n = n/2
else: # n is odd
n = n*3+1
```
The condition for this loop is `n != 1`, so the loop will continue until
`n` is `1`, which makes the condition false.
Each time through the loop, the program outputs the value of `n` and
then checks whether it is even or odd. If it is even, `n` is divided by
2. If it is odd, the value of `n` is replaced with `n*3+1`. For example,
if the argument passed to `sequence` is 3, the resulting sequence is 3,
10, 5, 16, 8, 4, 2, 1.
Since `n` sometimes increases and sometimes decreases, there is no
obvious proof that `n` will ever reach 1, or that the program
terminates. For some particular values of `n`, we can prove termination.
For example, if the starting value is a power of two, then the value of
`n` will be even each time through the loop until it reaches 1. The
previous example ends with such a sequence, starting with 16.
The hard question is whether we can prove that this program terminates
for *all positive values* of `n`. So far^1^, no one has been able to
prove it *or* disprove it!
```{=html}
<DIV CLASS="theorem">
```
**Exercise 1** *Rewrite the function`print_n`from Section **\'5.8**\'
using iteration instead of recursion.*
```{=html}
</DIV>
```
## `break`
Sometimes you don't know it's time to end a loop until you get half way
through the body. In that case you can use the `break` statement to jump
out of the loop.
For example, suppose you want to take input from the user until they
type `done`. You could write:
``` python
while True:
line = raw_input('> ')
if line == 'done':
break
print line
print 'Done!'
```
The loop condition is `True`, which is always true, so the loop runs
until it hits the break statement.
Each time through, it prompts the user with an angle bracket. If the
user types `done`, the `break` statement exits the loop. Otherwise the
program echoes whatever the user types and goes back to the top of the
loop. Here's a sample run:
``` python
> not done
not done
> done
Done!
```
This way of writing `while` loops is common because you can check the
condition anywhere in the loop (not just at the top) and you can express
the stop condition affirmatively ("stop when this happens") rather than
negatively ("keep going until that happens.").
## Square roots
Loops are often used in programs that compute numerical results by
starting with an approximate answer and iteratively improving it.
For example, one way of computing square roots is Newton's method.
Suppose that you want to know the square root of
`<I>`{=html}a`</I>`{=html}. If you start with almost any estimate,
`<I>`{=html}x`</I>`{=html}, you can compute a better estimate with the
following formula:
```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
`<I>`{=html}y`</I>`{=html} =
```{=html}
</TD>
```
```{=html}
<TD CLASS="dcell">
```
```{=html}
<TABLE CLASS="display">
```
```{=html}
<TR>
```
```{=html}
<TD CLASS="dcell" ALIGN="center">
```
`<I>`{=html}x`</I>`{=html} + `<I>`{=html}a`</I>`{=html}/`<I>`{=html}x`</I>`{=html}
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
<TR>
```
```{=html}
<TD CLASS="hbar">
```
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
<TR>
```
```{=html}
<TD CLASS="dcell" ALIGN="center">
```
2
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
```{=html}
</TD>
```
```{=html}
<TD CLASS="dcell">
```
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
For example, if `<I>`{=html}a`</I>`{=html} is 4 and
`<I>`{=html}x`</I>`{=html} is 3:
``` python
>>> a = 4.0
>>> x = 3.0
>>> y = (x + a/x) / 2
>>> print y
2.16666666667
```
Which is closer to the correct answer
(√`<SPAN style="text-decoration:overline">`{=html}4`</SPAN>`{=html} =
2). If we repeat the process with the new estimate, it gets even closer:
``` python
>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.00641025641
```
After a few more updates, the estimate is almost exact:
``` python
>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.00001024003
>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.00000000003
```
In general we don't know ahead of time how many steps it takes to get to
the right answer, but we know when we get there because the estimate
stops changing:
``` python
>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.0
>>> x = y
>>> y = (x + a/x) / 2
>>> print y
2.0
```
When `y == x`, we can stop. Here is a loop that starts with an initial
estimate, `x`, and improves it until it stops changing:
``` python
while True:
print x
y = (x + a/x) / 2
if y == x:
break
x = y
```
For most values of `a` this works fine, but in general it is dangerous
to test `float` equality. Floating-point values are only approximately
right: most rational numbers, like 1/3, and irrational numbers, like
√`<SPAN style="text-decoration:overline">`{=html}2`</SPAN>`{=html},
can't be represented exactly with a `float`.
Rather than checking whether `x` and `y` are exactly equal, it is safer
to use the built-in function `abs` to compute the absolute value, or
magnitude, of the difference between them:
``` python
if abs(y-x) < epsilon:
break
```
Where `epsilon` has a value like `0.0000001` that determines how close
is close enough.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 2** ***\' Encapsulate this loop in a function called
**`square_root`** that takes**\'`a`**\' as a parameter, chooses a
reasonable value of**\'`x`**\', and returns an estimate of the square
root of**\'`a`.*
```{=html}
</DIV>
```
## Algorithms
Newton's method is an example of an **algorithm**: it is a mechanical
process for solving a category of problems (in this case, computing
square roots).
It is not easy to define an algorithm. It might help to start with
something that is not an algorithm. When you learned to multiply
single-digit numbers, you probably memorized the multiplication table.
In effect, you memorized 100 specific solutions. That kind of knowledge
is not algorithmic.
But if you were "lazy," you probably cheated by learning a few tricks.
For example, to find the product of `<I>`{=html}n`</I>`{=html} and 9,
you can write `<I>`{=html}n`</I>`{=html}−1 as the first digit and
10−`<I>`{=html}n`</I>`{=html} as the second digit. This trick is a
general solution for multiplying any single-digit number by 9. That's an
algorithm!
Similarly, the techniques you learned for addition with carrying,
subtraction with borrowing, and long division are all algorithms. One of
the characteristics of algorithms is that they do not require any
intelligence to carry out. They are mechanical processes in which each
step follows from the last according to a simple set of rules.
In my opinion, it is embarrassing that humans spend so much time in
school learning to execute algorithms that, quite literally, require no
intelligence.
On the other hand, the process of designing algorithms is interesting,
intellectually challenging, and a central part of what we call
programming.
Some of the things that people do naturally, without difficulty or
conscious thought, are the hardest to express algorithmically.
Understanding natural language is a good example. We all do it, but so
far no one has been able to explain *how* we do it, at least not in the
form of an algorithm.
## Debugging
As you start writing bigger programs, you might find yourself spending
more time debugging. More code means more chances to make an error and
more place for bugs to hide.
One way to cut your debugging time is "debugging by bisection." For
example, if there are 100 lines in your program and you check them one
at a time, it would take 100 steps.
Instead, try to break the problem in half. Look at the middle of the
program, or near it, for an intermediate value you can check. Add a
`print` statement (or something else that has a verifiable effect) and
run the program.
If the mid-point check is incorrect, the problem must be in the first
half of the program. If it is correct, the problem is in the second
half.
Every time you perform a check like this, you halve the number of lines
you have to search. After six steps (which is much less than 100), you
would be down to one or two lines of code, at least in theory.
In practice it is not always clear what the "middle of the program" is
and not always possible to check it. It doesn't make sense to count
lines and find the exact midpoint. Instead, think about places in the
program where there might be errors and places where it is easy to put a
check. Then choose a spot where you think the chances are about the same
that the bug is before or after the check.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**multiple assignment:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Making more than one assignment to the same variable during the
execution of a program.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**update:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An assignment where the new value of the variable depends on the old.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**initialize:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An assignment that gives an initial value to a variable that will be
updated.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**increment:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An update that increases the value of a variable (often by one).
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**decrement:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An update that decreases the value of a variable.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**iteration:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Repeated execution of a set of statements using either a recursive
function call or a loop.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**infinite loop:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A loop in which the terminating condition is never satisfied.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 3
*To test the square root algorithm in this chapter, you could compare it
with **\'`math.sqrt`**\'. Write a function named`test_square_root`that
prints a table like this:*
``` python
''1.0 1.0 1.0 0.0
2.0 1.41421356237 1.41421356237 2.22044604925e-16
3.0 1.73205080757 1.73205080757 0.0
4.0 2.0 2.0 0.0
5.0 2.2360679775 2.2360679775 0.0
6.0 2.44948974278 2.44948974278 0.0
7.0 2.64575131106 2.64575131106 0.0
8.0 2.82842712475 2.82842712475 4.4408920985e-16
9.0 3.0 3.0 0.0
''
```
\'\'The first column is a number, **\'`<I>`{=html}a`</I>`{=html}**\';
the second column is the square root of
**\'`<I>`{=html}a`</I>`{=html}**\' computed with the function from
Exercise **\'7.2**\'; the third column is the square root computed by
**\'`math.sqrt`**\'; the fourth column is the absolute value of the
difference between the two estimates.
### Exercise 4
*The built-in function **\'`eval`**\' takes a string and evaluates it
using the Python interpreter. For example:*
``` python
''>>> eval('1 + 2 * 3')
7
>>> import math
>>> eval('math.sqrt(5)')
2.2360679774997898
>>> eval('type(math.pi)')
<type 'float'>
''
```
*Write a function called`eval_loop`that iteratively prompts the user,
takes the resulting input and evaluates it using **\'`eval`**\', and
prints the result.*
*It should continue until the user enters***`done`***, and then return
the value of the last expression it evaluated.*
### Exercise 5
*The brilliant mathematician Srinivasa Ramanujan found an infinite
series*^*2*^ that can be used to generate a numerical approximation of
$\pi$:\'\'
$\frac{1}{\pi} = \frac{2 \sqrt{2}} {9801} \sum_{k=0}^{\infty}
\frac{ (4k)! (1103 + 26390k)}{(k!)^4 396^{4k}}$
*Write a function called`estimate_pi`that uses this formula to compute
and return an estimate of **\'π**\'. It should use a **\'`while`**\'
loop to compute terms of the summation until the last term is smaller
than **\'`1e-15`**\' (which is Python notation for **\'10*^*−15*^*). You
can check the result by comparing it to**\'`math.pi`.*
*You can see my solution at **\'`thinkpython.com/code/pi.py`**\'.*
```{=html}
</DIV>
```
```{=html}
<HR CLASS="footnoterule">
```
```{=html}
<DL CLASS="thefootnotes">
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
1
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
See `wikipedia.org/wiki/Collatz_conjecture`.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
2
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
See `wikipedia.org/wiki/Pi`.
```{=html}
</DD>
```
```{=html}
</DL>
```
|
# Think Python/Strings
## A string is a sequence
A string is a **sequence** of characters. You can access the characters
one at a time with the bracket operator:
``` python
>>> fruit = 'banana'
>>> letter = fruit[1]
```
The second statement selects character number 1 from `fruit` and assigns
it to `letter`.
The expression in brackets is called an **index**. The index indicates
which character in the sequence you want (hence the name).
But you might not get what you expect:
``` python
>>> print letter
a
```
For most people, the first letter of `'banana'` is `b`, not `a`. But for
computer scientists, the index is an offset from the beginning of the
string, and the offset of the first letter is zero.
``` python
>>> letter = fruit[0]
>>> print letter
b
```
So `b` is the 0th letter ("zero-eth") of `'banana'`, `a` is the 1th
letter ("one-eth"), and `n` is the 2th ("two-eth") letter.
You can use any expression, including variables and operators, as an
index, but the value of the index has to be an integer. Otherwise you
get:
``` python
>>> letter = fruit[1.5]
TypeError: string indices must be integers
```
## `len`
`len` is a built-in function that returns the number of characters in a
string:
``` python
>>> fruit = 'banana'
>>> len(fruit)
6
```
To get the last letter of a string, you might be tempted to try
something like this:
>>> length = len(fruit)
>>> last = fruit[length]
IndexError: string index out of range
The reason for the `IndexError` is that there is no letter in `’banana’`
with the index 6. Since we started counting at zero, the six letters are
numbered 0 to 5. To get the last character, you have to subtract 1 from
`length`:
``` python
>>> last = fruit[length-1]
>>> print last
a
```
Alternatively, you can use negative indices, which count backward from
the end of the string. The expression `fruit[-1]` yields the last
letter, `fruit[-2]` yields the second to last, and so on.
## Traversal with a `for` loop
A lot of computations involve processing a string one character at a
time. Often they start at the beginning, select each character in turn,
do something to it, and continue until the end. This pattern of
processing is called a **traversal**. One way to write a traversal is
with a `while` loop:
``` python
index = 0
while index < len(fruit):
letter = fruit[index]
print letter
index = index + 1
```
This loop traverses the string and displays each letter on a line by
itself. The loop condition is `index < len(fruit)`, so when `index` is
equal to the length of the string, the condition is false, and the body
of the loop is not executed. The last character accessed is the one with
the index `len(fruit)-1`, which is the last character in the string.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 1** *Write a function that takes a string as an argument and
displays the letters backward, one per line.*
```{=html}
</DIV>
```
Another way to write a traversal is with a `for` loop:
``` python
for char in fruit:
print char
```
Each time through the loop, the next character in the string is assigned
to the variable `char`. The loop continues until no characters are left.
The following example shows how to use concatenation (string addition)
and a `for` loop to generate an abecedarian series (that is, in
alphabetical order). In Robert McCloskey's book *Make Way for
Ducklings*, the names of the ducklings are Jack, Kack, Lack, Mack, Nack,
Ouack, Pack, and Quack. This loop outputs these names in order:
``` python
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print letter + suffix
```
The output is:
``` python
Jack
Kack
Lack
Mack
Nack
Oack
Pack
Qack
```
Of course, that's not quite right because "Ouack" and "Quack" are
misspelled.
### Exercise 2
Modify the program to fix this error.
## String slices
A segment of a string is called a **slice**. Selecting a slice is
similar to selecting a character:
``` python
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:13]
Python
```
The operator `[n:m]` returns the part of the string from the "n-eth"
character to the "m-eth" character, including the first but excluding
the last. This behavior is counterintuitive, but it might help to
imagine the indices pointing *between* the characters, as in the
following diagram:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book011.png">`{=html}
```{=html}
</DIV>
```
If you omit the first index (before the colon), the slice starts at the
beginning of the string. If you omit the second index, the slice goes to
the end of the string:
``` python
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana'
```
If the first index is greater than or equal to the second the result is
an **empty string**, represented by two quotation marks:
``` python
>>> fruit = 'banana'
>>> fruit[3:3]
''
```
An empty string contains no characters and has length 0, but other than
that, it is the same as any other string.
### Exercise 3
Given that **\'`fruit`**\' is a string, what does **\'`fruit[:]`**\'
mean?\'\'
## Strings are immutable
It is tempting to use the `[]` operator on the left side of an
assignment, with the intention of changing a character in a string. For
example:
``` python
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: object does not support item assignment
```
The "object" in this case is the string and the "item" is the character
you tried to assign. For now, an **object** is the same thing as a
value, but we will refine that definition later. An **item** is one of
the values in a sequence.
The reason for the error is that strings are **immutable**, which means
you can't change an existing string. The best you can do is create a new
string that is a variation on the original:
``` python
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world!
```
This example concatenates a new first letter onto a slice of `greeting`.
It has no effect on the original string.
## Searching
What does the following function do?
``` python
def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
```
In a sense, `find` is the opposite of the `[]` operator. Instead of
taking an index and extracting the corresponding character, it takes a
character and finds the index where that character appears. If the
character is not found, the function returns `-1`.
This is the first example we have seen of a `return` statement inside a
loop. If `word[index] == letter`, the function breaks out of the loop
and returns immediately.
If the character doesn't appear in the string, the program exits the
loop normally and returns `-1`.
This pattern of computation---traversing a sequence and returning when
we find what we are looking for---is a called a **search**.
### Exercise 4
Modify **\'`find`**\' so that it has a third parameter, the index in
**\'`word`**\' where it should start looking.
## Looping and counting
The following program counts the number of times the letter `a` appears
in a string:
``` python
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print count
```
This program demonstrates another pattern of computation called a
**counter**. The variable `count` is initialized to 0 and then
incremented each time an `a` is found. When the loop exits, `count`
contains the result---the total number of `a`'s.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 5** *Encapsulate this code in a function named
**\'`count`**\', and generalize it so that it accepts the string and the
letter as arguments.*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 6** *Rewrite this function so that instead of traversing the
string, it uses the three-parameter version of **\'`find`**\' from the
previous section.*
```{=html}
</DIV>
```
## `string` methods
A **method** is similar to a function---it takes arguments and returns a
value---but the syntax is different. For example, the method `upper`
takes a string and returns a new string with all uppercase letters:
Instead of the function syntax `upper(word)`, it uses the method syntax
`word.upper()`.
``` python
>>> word = 'banana'
>>> new_word = word.upper()
>>> print new_word
BANANA
```
This form of dot notation specifies the name of the method, `upper`, and
the name of the string to apply the method to, `word`. The empty
parentheses indicate that this method takes no argument.
A method call is called an **invocation**; in this case, we would say
that we are invoking `upper` on the `word`.
As it turns out, there is a string method named `find` that is
remarkably similar to the function we wrote:
``` python
>>> word = 'banana'
>>> index = word.find('a')
>>> print index
1
```
In this example, we invoke `find` on `word` and pass the letter we are
looking for as a parameter.
Actually, the `find` method is more general than our function; it can
find substrings, not just characters:
``` python
>>> word.find('na')
2
```
It can take as a second argument the index where it should start:
``` python
>>> word.find('na', 3)
4
```
And as a third argument the index where it should stop:
``` python
>>> name = 'bob'
>>> name.find('b', 1, 2)
-1
```
This search fails because `b` does not appear in the index range from
`1` to `2` (not including `2`).
```{=html}
<DIV CLASS="theorem">
```
**Exercise 7** ***\' There is a string method called**\'`count`**\'
that is similar to the function in the previous exercise. Read the
documentation of this method and write an invocation that counts the
number of**\'`a`s in***`banana`***.*
```{=html}
</DIV>
```
## The `in` operator
The word `in` is a boolean operator that takes two strings and returns
`True` if the first appears as a substring in the second:
``` python
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
```
For example, the following function prints all the letters from `word1`
that also appear in `word2`:
``` python
def in_both(word1, word2):
for letter in word1:
if letter in word2:
print letter
```
With well-chosen variable names, Python sometimes reads like English.
You could read this loop, "for (each) letter in (the first) word, if
(the) letter (appears) in (the second) word, print (the) letter."
Here's what you get if you compare apples and oranges:
``` python
>>> in_both('apples', 'oranges')
a
e
s
```
## String comparison
The comparison operators work on strings. To see if two strings are
equal:
``` python
if word == 'banana':
print 'All right, bananas.'
```
Other comparison operations are useful for putting words in alphabetical
order:
``` python
if word < 'banana':
print 'Your word,' + word + ', comes before banana.'
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.'
else:
print 'All right, bananas.'
```
Python does not handle uppercase and lowercase letters the same way that
people do. All the uppercase letters come before all the lowercase
letters, so:
``` python
Your word, Pineapple, comes before banana.
```
A common way to address this problem is to convert strings to a standard
format, such as all lowercase, before performing the comparison. Keep
that in mind in case you have to defend yourself against a man armed
with a Pineapple.
## Debugging
When you use indices to traverse the values in a sequence, it is tricky
to get the beginning and end of the traversal right. Here is a function
that is supposed to compare two words and return `True` if one of the
words is the reverse of the other, but it contains two errors:
``` python
def is_reverse(word1, word2):
if len(word1) != len(word2):
return False
i = 0
j = len(word2)
while j > 0:
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
return True
```
The first `if` statement checks whether the words are the same length.
If not, we can return `False` immediately and then, for the rest of the
function, we can assume that the words are the same length. This is an
example of the guardian pattern in Section 6.8.
`i` and `j` are indices: `i` traverses `word1` forward while `j`
traverses `word2` backward. If we find two letters that don't match, we
can return `False` immediately. If we get through the whole loop and all
the letters match, we return `True`.
If we test this function with the words "pots" and "stop", we expect the
return value `True`, but we get an IndexError:
``` python
>>> is_reverse('pots', 'stop')
...
File "reverse.py", line 15, in is_reverse
if word1[i] != word2[j]:
IndexError: string index out of range
```
For debugging this kind of error, my first move is to print the values
of the indices immediately before the line where the error appears.
``` python
while j > 0:
print i, j # print here
if word1[i] != word2[j]:
return False
i = i+1
j = j-1
```
Now when I run the program again, I get more information:
``` python
>>> is_reverse('pots', 'stop')
0 4
...
IndexError: string index out of range
```
The first time through the loop, the value of `j` is 4, which is out of
range for the string `'pots'`. The index of the last character is 3, so
the initial value for `j` should be `len(word2)-1`.
If I fix that error and run the program again, I get:
``` python
>>> is_reverse('pots', 'stop')
0 3
1 2
2 1
True
```
This time we get the right answer, but it looks like the loop only ran
three times, which is suspicious. To get a better idea of what is
happening, it is useful to draw a state diagram. During the first
iteration, the frame for `is_reverse` looks like this:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book012.png">`{=html}
```{=html}
</DIV>
```
I took a little license by arranging the variables in the frame and
adding dotted lines to show that the values of `i` and `j` indicate
characters in `word1` and `word2`.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 8** ***\' Starting with this diagram, execute the program on
paper, changing the values of**\'`i`**\' and**\'`j`during each
iteration. Find and fix the second error in this function.*
```{=html}
</DIV>
```
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**object:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Something a variable can refer to. For now, you can use "object" and
"value" interchangeably.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**sequence:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An ordered set; that is, a set of values where each value is identified
by an integer index.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**item:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the values in a sequence.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**index:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An integer value used to select an item in a sequence, such as a
character in a string.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**slice:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A part of a string specified by a range of indices.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**empty string:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A string with no characters and length 0, represented by two quotation
marks.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**immutable:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The property of a sequence whose items cannot be assigned.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**traverse:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To iterate through the items in a sequence, performing a similar
operation on each.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**search:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A pattern of traversal that stops when it finds what it is looking for.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**counter:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A variable used to count something, usually initialized to zero and then
incremented.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**method:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A function that is associated with an object and called using dot
notation.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**invocation:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A statement that calls a method.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 9
A string slice can take a third index that specifies the "step size;"
that is, the number of spaces between successive characters. A step size
of 2 means every other character; 3 means every third, etc.
``` python
''>>> fruit = 'banana'
>>> fruit[0:5:2]
'bnn'
''
```
*A step size of -1 goes through the word backwards, so the
slice`[::-1]`generates a reversed string.*
*Use this idiom to write a one-line version of`is_palindrome`*\'\' from
Exercise **\'6.6**\'.
### Exercise 10
Read the documentation of the string methods at
**\'`docs.python.org/lib/string-methods.html`**\'. You might want to
experiment with some of them to make sure you understand how they work.
**\'`strip`**\' and **\'`replace`**\' are particularly useful.\'\'
*The documentation uses a syntax that might be confusing. For example,
in`find(sub[, start[, end]])`*\'\', the brackets indicate optional
arguments. So **\'`sub`**\' is required, but **\'`start`**\' is
optional, and if you include **\'`start`**\', then **\'`end`**\' is
optional.
### Exercise 11
The following functions are all *intended* to check whether a string
contains any lowercase letters, but at least some of them are wrong. For
each function, describe what the function actually does.\'\'
``` python
''def any_lowercase1(s):
for c in s:
if c.islower():
return True
else:
return False
def any_lowercase2(s):
for c in s:
if 'c'.islower():
return 'True'
else:
return 'False'
def any_lowercase3(s):
for c in s:
flag = c.islower()
return flag
def any_lowercase4(s):
flag = False
for c in s:
flag = flag or c.islower()
return flag
def any_lowercase5(s):
for c in s:
if not c.islower():
return False
return True
''
```
### Exercise 12
ROT13 is a weak form of encryption that involves "rotating" each letter
in a word by 13 places[^1]. To rotate a letter means to shift it through
the alphabet, wrapping around to the beginning if necessary, so 'A'
shifted by 3 is 'D' and 'Z' shifted by 1 is 'A'.\'\'
*Write a function called`rotate_word`that takes a string and an integer
as parameters, and that returns a new string that contains the letters
from the original string "rotated" by the given amount.*
*For example, "cheer" rotated by 7 is "jolly" and "melon" rotated by -10
is "cubed".*
*You might want to use the built-in functions **\'`ord`**\', which
converts a character to a numeric code, and **\'`chr`**\', which
converts numeric codes to characters.*
\'\'Potentially offensive jokes on the Internet are sometimes encoded in
ROT13. If you are not easily offended, find and decode some of them.
## Notes
[^1]: See `<TT>`{=html}wikipedia.org/wiki/ROT13
|
# Think Python/Case study: word play
## Reading word lists
For the exercises in this chapter we need a list of English words. There
are lots of word lists available on the Web, but the one most suitable
for our purpose is one of the word lists collected and contributed to
the public domain by Grady Ward as part of the Moby lexicon project[^1].
It is a list of 113,809 official crosswords; that is, words that are
considered valid in crossword puzzles and other word games. In the Moby
collection, the filename is `113809of.fic`; I include a copy of this
file, with the simpler name `words.txt`, along with Swampy.
This file is in plain text, so you can open it with a text editor, but
you can also read it from Python. (You may need to move the file from
the swampy folder into the main python folder) The built-in function
`open` takes the name of the file as a parameter and returns a **file
object** you can use to read the file.
``` python
>>> fin = open('words.txt')
>>> print fin
<open file 'words.txt', mode 'r' at 0xb7f4b380>
```
`fin` is a common name for a file object used for input. Mode `'r'`
indicates that this file is open for reading (as opposed to `'w'` for
writing).
The file object provides several methods for reading, including
`readline`, which reads characters from the file until it gets to a
newline and returns the result as a string:
``` python
>>> fin.readline()
'aa\r\n'
```
The first word in this particular list is "aa," which is a kind of lava.
The sequence `\r\n` represents two whitespace characters, a carriage
return and a newline, that separate this word from the next.
The file object keeps track of where it is in the file, so if you call
`readline` again, you get the next word:
``` python
>>> fin.readline()
'aah\r\n'
```
The next word is "aah," which is a perfectly legitimate word, so stop
looking at me like that. Or, if it's the whitespace that's bothering
you, we can get rid of it with the string method `strip`:
``` python
>>> line = fin.readline()
>>> word = line.strip()
>>> print word
aahed
```
You can also use a file object as part of a `for` loop. This program
reads `words.txt` and prints each word, one per line:
``` python
fin = open('words.txt')
for line in fin:
word = line.strip()
print word
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 1** *Write a program that reads **\'`words.txt`**\' and
prints only the words with more than 20 characters (not counting
whitespace).*
```{=html}
</DIV>
```
## Exercises
There are solutions to these exercises in the next section. You should
at least attempt each one before you read the solutions.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 2** *In 1939 Ernest Vincent Wright published a 50,000 word
novel called*Gadsby*that does not contain the letter "e." Since "e" is
the most common letter in English, that's not easy to do.* *In fact, it
is difficult to construct a solitary thought without using that most
common symbol. It is slow going at first, but with caution and hours of
training you can gradually gain facility.*
*All right, I'll stop now.*
*Write a function called`has_no_e`that returns **\'`True`**\' if the
given word doesn't have the letter "e" in it.*
*Modify your program from the previous section to print only the words
that have no "e" and compute the percentage of the words in the list
have no "e."*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 3** *Write a function named **\'`avoids`**\' that takes a
word and a string of forbidden letters, and that returns **\'`True`**\'
if the word doesn't use any of the forbidden letters.* *Modify your
program to prompt the user to enter a string of forbidden letters and
then print the number of words that don't contain any of them. Can you
find a combination of 5 forbidden letters that excludes the smallest
number of words?*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 4** *Write a function named`uses_only`that takes a word and
a string of letters, and that returns **\'`True`**\' if the word
contains only letters in the list. Can you make a sentence using only
the letters **\'`acefhlo`**\'? Other than "Hoe alfalfa?"*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 5** *Write a function named`uses_all`that takes a word and a
string of required letters, and that returns **\'`True`**\' if the word
uses all the required letters at least once. How many words are there
that use all the vowels **\'`aeiou`**\'? How about **\'`aeiouy`**\'?*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 6** *Write a function called`is_abecedarian`that returns
**\'`True`**\' if the letters in a word appear in alphabetical order
(double letters are ok). How many abecedarian words are there?*
```{=html}
</DIV>
```
## Search
All of the exercises in the previous section have something in common;
they can be solved with the search pattern we saw in Section 8.6. The
simplest example is:
``` python
def has_no_e(word):
for letter in word:
if letter == 'e':
return False
return A=break
```
The `for` loop traverses the characters in `word`. If we find the letter
"e", we can immediately return `False`; otherwise we have to go to the
next letter. If we exit the loop normally, that means we didn't find an
"e", so we return `True`.
You can write this function more concisely using the `in` operator, but
I started with this version because it demonstrates the logic of the
search pattern.
`avoids` is a more general version of `has_no_e` but it has the same
structure:
``` python
def avoids(word, forbidden):
for letter in word:
if letter in forbidden:
return False
return True
```
We can return `False` as soon as we find a forbidden letter; if we get
to the end of the loop, we return `True`.
`uses_only` is similar except that the sense of the condition is
reversed:
``` python
def uses_only(word, available):
for letter in word:
if letter not in available:
return False
return True
```
Instead of a list of forbidden words, we have a list of available words.
If we find a letter in `word` that is not in `available`, we can return
`False`.
`uses_all` is similar except that we reverse the role of the word and
the string of letters:
``` python
def uses_all(word, required):
for letter in required:
if letter not in word:
return False
return True
```
Instead of traversing the letters in `word`, the loop traverses the
required letters. If any of the required letters do not appear in the
word, we can return `False`.
If you were really thinking like a computer scientist, you would have
recognized that `uses_all` was an instance of a previously-solved
problem, and you would have written:
``` python
def uses_all(word, required):
return uses_only(required, word)
```
This is an example of a program development method called **problem
recognition**, which means that you recognize the problem you are
working on as an instance of a previously-solved problem, and apply a
previously-developed solution.
## Looping with indices
I wrote the functions in the previous section with `for` loops because I
only needed the characters in the strings; I didn't have to do anything
with the indices.
For `is_abecedarian` we have to compare adjacent letters, which is a
little tricky with a `for` loop:
``` python
def is_abecedarian(word):
previous = word[0]
for c in word:
if c < previous:
return False
previous = c
return True
```
An alternative is to use recursion:
``` python
def is_abecedarian(word):
if len(word) <= 1:
return True
if word[0] > word[1]:
return False
return is_abecedarian(word[1:])
```
Another option is to use a `while` loop:
``` python
def is_abecedarian(word):
i = 0
while i < len(word)-1:
if word[i+1] < word[i]:
return False
i = i+1
return True
```
The loop starts at `i=0` and ends when `i=len(word)-1`. Each time
through the loop, it compares the `<I>`{=html}i`</I>`{=html}th character
(which you can think of as the current character) to the
`<I>`{=html}i`</I>`{=html}+1th character (which you can think of as the
next).
If the next character is less than (alphabetically before) the current
one, then we have discovered a break in the abecedarian trend, and we
return `False`.
If we get to the end of the loop without finding a fault, then the word
passes the test. To convince yourself that the loop ends correctly,
consider an example like `'flossy'`. The length of the word is 6, so the
last time the loop runs is when `i` is 4, which is the index of the
second-to-last character. On the last iteration, it compares the
second-to-last character to the last, which is what we want.
Here is a version of `is_palindrome` (see Exercise 6.6) that uses two
indices; one starts at the beginning and goes up; the other starts at
the end and goes down.
``` python
def is_palindrome(word):
i = 0
j = len(word)-1
while i<j:
if word[i] != word[j]:
return False
i = i+i
j = j-j
return True
```
Or, if you noticed that this is an instance of a previously-solved
problem, you might have written:
``` python
def is_palindrome(word):
return is_reverse(word, word)
```
Assuming you did Exercise 8.8.
## Debugging
Testing programs is hard. The functions in this chapter are relatively
easy to test because you can check the results by hand. Even so, it is
somewhere between difficult and impossible to choose a set of words that
test for all possible errors.
Taking `has_no_e` as an example, there are two obvious cases to check:
words that have an 'e' should return `False`; words that don't should
return `True`. You should have no trouble coming up with one of each.
Within each case, there are some less obvious subcases. Among the words
that have an "e," you should test words with an "e" at the beginning,
the end, and somewhere in the middle. You should test long words, short
words, and very short words, like the empty string. The empty string is
an example of a **special case**, which is one of the non-obvious cases
where errors often lurk.
In addition to the test cases you generate, you can also test your
program with a word list like `words.txt`. By scanning the output, you
might be able to catch errors, but be careful: you might catch one kind
of error (words that should not be included, but are) and not another
(words that should be included, but aren't).
In general, testing can help you find bugs, but it is not easy to
generate a good set of test cases, and even if you do, you can't be sure
your program is correct.
According to a legendary computer scientist:
> Program testing can be used to show the presence of bugs, but never to
> show their absence! --- Edsger W. Dijkstra
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**file object:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A value that represents an open file.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**problem recognition:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A way of solving a problem by expressing it as an instance of a
previously-solved problem.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**special case:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A test case that is atypical or non-obvious (and less likely to be
handled correctly).
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 7
This question is based on a Puzzler that was broadcast on the radio
program *Car Talk[^2]*:\'\'
> Give me a word with three consecutive double letters. I\'ll give you a
> couple of words that almost qualify, but don\'t. For example, the word
> committee, c-o-m-m-i-t-t-e-e. It would be great except for the 'i'
> that sneaks in there. Or Mississippi: M-i-s-s-i-s-s-i-p-p-i. If you
> could take out those i's it would work. But there is a word that has
> three consecutive pairs of letters and to the best of my knowledge
> this may be the only word. Of course there are probably 500 more but I
> can only think of one. What is the word?
*Write a program to find it. You can see my solution at
**\'`thinkpython.com/code/cartalk.py`**\'.*
### Exercise 8
Here's another *Car Talk Puzzler*[^3]\'\':
> *"I was driving on the highway the other day and I happened to notice
> my odometer. Like most odometers, it shows six digits, in whole miles
> only. So, if my car had 300,000 miles, for example, I'd see
> 3-0-0-0-0-0.* *"Now, what I saw that day was very interesting. I
> noticed that the last 4 digits were palindromic; that is, they read
> the same forward as backward. For example, 5-4-4-5 is a palindrome, so
> my odometer could have read 3-1-5-4-4-5.*
>
> *"One mile later, the last 5 numbers were palindromic. For example, it
> could have read 3-6-5-4-5-6. One mile after that, the middle 4 out of
> 6 numbers were palindromic. And you ready for this? One mile later,
> all 6 were palindromic!*
>
> *"The question is, what was on the odometer when I first looked?"*
*Write a Python program that tests all the six-digit numbers and prints
any numbers that satisfy these requirements. You can see my solution at
**\'`thinkpython.com/code/cartalk.py`**\'.*
### Exercise 9
Here's another *Car Talk* Puzzler you can solve with a search*[^4]*:
> *"Recently I had a visit with my mom and we realized that the two
> digits that make up my age when reversed resulted in her age. For
> example, if she's 73, I'm 37. We wondered how often this has happened
> over the years but we got sidetracked with other topics and we never
> came up with an answer.* *"When I got home I figured out that the
> digits of our ages have been reversible six times so far. I also
> figured out that if we're lucky it would happen again in a few years,
> and if we're really lucky it would happen one more time after that. In
> other words, it would have happened 8 times over all. So the question
> is, how old am I now?"*
*Write a Python program that searches for solutions to this Puzzler.
Hint: you might find the string method **\'`zfill`**\' useful.*
*You can see my solution at **\'`thinkpython.com/code/cartalk.py`**\'.*
## Notes
[^1]: `wikipedia.org/wiki/Moby_Project`
[^2]: `<TT>`{=html}www.cartalk.com/content/puzzler/transcripts/200725
[^3]: `www.cartalk.com/content/puzzler/transcripts/200803`
[^4]: `www.cartalk.com/content/puzzler/transcripts/200813`
|
# Think Python/Lists
## A list is a sequence
Like a string, a **list** is a sequence of values. In a string, the
values are characters; in a list, they can be any type. The values in
list are called **elements** or sometimes **items**.
There are several ways to create a new list; the simplest is to enclose
the elements in square brackets (`[` and `]`):
``` python
[10, 20, 30, 40]
['crunchy frog', 'ram bladder', 'lark vomit']
```
The first example is a list of four integers. The second is a list of
three strings. The elements of a list don't have to be the same type.
The following list contains a string, a float, an integer, and (lo!)
another list:
``` python
['spam', 2.0, 5, [10, 20]]
```
A list within another list is **nested**.
A list that contains no elements is called an empty list; you can create
one with empty brackets, `[]`.
As you might expect, you can assign list values to variables:
``` python
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> numbers = [17, 123]
>>> empty = []
>>> print cheeses, numbers, empty
['Cheddar', 'Edam', 'Gouda'] [17, 123] []
```
## Lists are mutable
The syntax for accessing the elements of a list is the same as for
accessing the characters of a string---the bracket operator. The
expression inside the brackets specifies the index. Remember that the
indices start at 0:
``` python
>>> print cheeses[0]
Cheddar
```
Unlike strings, lists are mutable. When the bracket operator appears on
the left side of an assignment, it identifies the element of the list
that will be assigned.
``` python
>>> numbers = [17, 123]
>>> numbers[1] = 5
>>> print numbers
[17, 5]
```
The one-eth element of `numbers`, which used to be 123, is now 5.
You can think of a list as a relationship between indices and elements.
This relationship is called a **mapping**; each index "maps to" one of
the elements. Here is a state diagram showing `cheeses`, `numbers` and
`empty`:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book013.png">`{=html}
```{=html}
</DIV>
```
Lists are represented by boxes with the word "list" outside and the
elements of the list inside. `cheeses` refers to a list with three
elements indexed 0, 1 and 2. `numbers` contains two elements; the
diagram shows that the value of the second element has been reassigned
from 123 to 5. `empty` refers to a list with no elements.
List indices work the same way as string indices:
- Any integer expression can be used as an index.
- If you try to read or write an element that does not exist, you get
an `IndexError`.
- If an index has a negative value, it counts backward from the end of
the list.
The `in` operator also works on lists.
``` python
>>> cheeses = ['Cheddar', 'Edam', 'Gouda']
>>> 'Edam' in cheeses
True
>>> 'Brie' in cheeses
False
```
## Traversing a list
The most common way to traverse the elements of a list is with a `for`
loop. The syntax is the same as for strings:
``` python
for cheese in cheeses:
print cheese
```
This works well if you only need to read the elements of the list. But
if you want to write or update the elements, you need the indices. A
common way to do that is to combine the functions `range` and `len`:
``` python
for i in range(len(numbers)):
numbers[i] = numbers[i] * 2
```
This loop traverses the list and updates each element. `len` returns the
number of elements in the list. `range` returns a list of indices from 0
to `<I>`{=html}n`</I>`{=html}−1, where `<I>`{=html}n`</I>`{=html} is the
length of the list. Each time through the loop `i` gets the index of the
next element. The assignment statement in the body uses `i` to read the
old value of the element and to assign the new value.
A `for` loop over an empty list never executes the body:
``` python
for x in empty:
print 'This never happens.'
```
Although a list can contain another list, the nested list still counts
as a single element. The length of this list is four:
``` python
['spam', 1, ['Brie', 'Roquefort', 'Pol le Veq'], [1, 2, 3]]
```
## List operations
The `+` operator concatenates lists:
``` python
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
```
Similarly, the `*` operator repeats a list a given number of times:
``` python
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
```
The first example repeats `[0]` four times. The second example repeats
the list `[1, 2, 3]` three times.
## List slices
The slice operator also works on lists:
``` python
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3]
['b', 'c']
>>> t[:4]
['a', 'b', 'c', 'd']
>>> t[3:]
['d', 'e', 'f']
```
If you omit the first index, the slice starts at the beginning. If you
omit the second, the slice goes to the end. So if you omit both, the
slice is a copy of the whole list.
``` python
>>> t[:]
['a', 'b', 'c', 'd', 'e', 'f']
```
Since lists are mutable, it is often useful to make a copy before
performing operations that fold, spindle or mutilate lists.
A slice operator on the left side of an assignment can update multiple
elements:
``` python
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> t[1:3] = ['x', 'y']
>>> print t
['a', 'x', 'y', 'd', 'e', 'f']
```
## List methods
Python provides methods that operate on lists. For example, `append`
adds a new element to the end of a list:
``` python
>>> t = ['a', 'b', 'c']
>>> t.append('d')
>>> print t
['a', 'b', 'c', 'd']
```
`extend` takes a list as an argument and appends all of the elements:
``` python
>>> t1 = ['a', 'b', 'c']
>>> t2 = ['d', 'e']
>>> t1.extend(t2)
>>> print t1
['a', 'b', 'c', 'd', 'e']
```
This example leaves `t2` unmodified.
`sort` arranges the elements of the list from low to high:
``` python
>>> t = ['d', 'c', 'e', 'b', 'a']
>>> t.sort()
>>> print t
['a', 'b', 'c', 'd', 'e']
```
List methods are all void; they modify the list and return `None`. If
you accidentally write `t = t.sort()`, you will be disappointed with the
result.
## Map, filter and reduce
To add up all the numbers in a list, you can use a loop like this:
``` python
def add_all(t):
total = 0
for x in t:
total += x
return total
```
`total` is initialized to 0. Each time through the loop, `x` gets one
element from the list. The `+=` operator provides a short way to update
a variable:
``` python
total += x
```
is equivalent to:
``` python
total = total + x
```
As the loop executes, `total` accumulates the sum of the elements; a
variable used this way is sometimes called an **accumulator**.
Adding up the elements of a list is such a common operation that Python
provides it as a built-in function, `sum`:
``` python
>>> t = [1, 2, 3]
>>> sum(t)
6
```
An operation like this that combines a sequence of elements into a
single value is sometimes called **reduce**.
Sometimes you want to traverse one list while building another. For
example, the following function takes a list of strings and returns a
new list that contains capitalized strings:
``` python
def capitalize_all(t):
res = []
for s in t:
res.append(s.capitalize())
return res
```
`res` is initialized with an empty list; each time through the loop, we
append the next element. So `res` is another kind of accumulator.
An operation like `capitalize_all` is sometimes called a **map** because
it "maps" a function (in this case the method `capitalize`) onto each of
the elements in a sequence.
Another common operation is to select some of the elements from a list
and return a sublist. For example, the following function takes a list
of strings and returns a list that contains only the uppercase strings:
``` python
def only_upper(t):
res = []
for s in t:
if s.isupper():
res.append(s)
return res
```
`isupper` is a string method that returns `True` if the string contains
only upper case letters.
An operation like `only_upper` is called a **filter** because it selects
some of the elements and filters out the others.
Most common list operations can be expressed as a combination of map,
filter and reduce. Because these operations are so common, Python
provides language features to support them, including the built-in
function `map` and an operator called a "list comprehension."
### Exercise 1
\'\'Write a function that takes a list of numbers and returns the
cumulative sum; that is, a new list where the
**\'`<I>`{=html}i`</I>`{=html}**\'th element is the sum of the first
**\'`<I>`{=html}i`</I>`{=html}+1**\' elements from the original list.
For example, the cumulative sum of **\'`[1, 2, 3]`**\' is
**\'`[1, 3, 6]`**\'.
## Deleting elements
There are several ways to delete elements from a list. If you know the
index of the element you want, you can use `pop`:
``` python
>>> t = ['a', 'b', 'c']
>>> x = t.pop(1)
>>> print t
['a', 'c']
>>> print x
b
```
`pop` modifies the list and returns the element that was removed. If you
don't provide an index, it deletes and returns the last element.
If you don't need the removed value, you can use the `del` operator:
``` python
>>> t = ['a', 'b', 'c']
>>> del t[1]
>>> print t
['a', 'c']
```
If you know the element you want to remove (but not the index), you can
use `remove`:
``` python
>>> t = ['a', 'b', 'c']
>>> t.remove('b')
>>> print t
['a', 'c']
```
The return value from `remove` is `None`.
To remove more than one element, you can use `del` with a slice index:
``` python
>>> t = ['a', 'b', 'c', 'd', 'e', 'f']
>>> del t[1:5]
>>> print t
['a', 'f']
```
As usual, the slice selects all the elements up to, but not including,
the second index.
## Lists and strings
A string is a sequence of characters and a list is a sequence of values,
but a list of characters is not the same as a string. To convert from a
string to a list of characters, you can use `list`:
``` python
>>> s = 'spam'
>>> t = list(s)
>>> print t
['s', 'p', 'a', 'm']
```
Because `list` is the name of a built-in function, you should avoid
using it as a variable name. I also avoid `l` because it looks too much
like `1`. So that's why I use `t`.
The `list` function breaks a string into individual letters. If you want
to break a string into words, you can use the `split` method:
``` python
>>> s = 'pining for the fjords'
>>> t = s.split()
>>> print t
['pining', 'for', 'the', 'fjords']
```
An optional argument called a **delimiter** specifies which characters
to use as word boundaries. The following example uses a hyphen as a
delimiter:
``` python
>>> s = 'spam-spam-spam'
>>> delimiter = '-'
>>> s.split(delimiter)
['spam', 'spam', 'spam']
```
`join` is the inverse of `split`. It takes a list of strings and
concatenates the elements. `join` is a string method, so you have to
invoke it on the delimiter and pass the list as a parameter:
``` python
>>> t = ['pining', 'for', 'the', 'fjords']
>>> delimiter = ' '
>>> delimiter.join(t)
'pining for the fjords'
```
In this case the delimiter is a space character, so `join` puts a space
between words. To concatenate strings without spaces, you can use the
empty string, `''`, as a delimiter.
## Objects and values
If we execute these assignment statements:
``` python
a = 'banana'
b = 'banana'
```
We know that `a` and `b` both refer to a string, but we don't know
whether they refer to the *same* string. There are two possible states:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book014.png">`{=html}
```{=html}
</DIV>
```
In one case, `a` and `b` refer to two different objects that have the
same value. In the second case, they refer to the same object.
To check whether two variables refer to the same object, you can use the
`is` operator.
``` python
>>> a = 'banana'
>>> b = 'banana'
>>> a is b
True
```
In this example, Python only created one string object, and both `a` and
`b` refer to it.
But when you create two lists, you get two objects:
``` python
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False
```
So the state diagram looks like this:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book015.png">`{=html}
```{=html}
</DIV>
```
In this case we would say that the two lists are **equivalent**, because
they have the same elements, but not **identical**, because they are not
the same object. If two objects are identical, they are also equivalent,
but if they are equivalent, they are not necessarily identical.
Until now, we have been using "object" and "value" interchangeably, but
it is more precise to say that an object has a value. If you execute
`a = [1,2,3]`, `a` refers to a list object whose value is a particular
sequence of elements. If another list has the same elements, we would
say it has the same value.
## Aliasing
If `a` refers to an object and you assign `b = a`, then both variables
refer to the same object:
``` python
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
```
The state diagram looks like this:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book016.png">`{=html}
```{=html}
</DIV>
```
The association of a variable with an object is called a **reference**.
In this example, there are two references to the same object.
An object with more than one reference has more than one name, so we say
that the object is **aliased**.
If the aliased object is mutable, changes made with one alias affect the
other:
``` python
>>> b[0] = 17
>>> print a
[17, 2, 3]
```
Although this behavior can be useful, it is error-prone. In general, it
is safer to avoid aliasing when you are working with mutable objects.
For immutable objects like strings, aliasing is not as much of a
problem. In this example:
``` python
a = 'banana'
b = 'banana'
```
It almost never makes a difference whether `a` and `b` refer to the same
string or not.
## List arguments
When you pass a list to a function, the function gets a reference to the
list. If the function modifies a list parameter, the caller sees the
change. For example, `delete_head` removes the first element from a
list:
``` python
def delete_head(t):
del t[0]
```
Here's how it is used:
``` python
>>> letters = ['a', 'b', 'c']
>>> delete_head(letters)
>>> print letters
['b', 'c']
```
The parameter `t` and the variable `letters` are aliases for the same
object. The stack diagram looks like this:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book017.png">`{=html}
```{=html}
</DIV>
```
Since the list is shared by two frames, I drew it between them.
It is important to distinguish between operations that modify lists and
operations that create new lists. For example, the `append` method
modifies a list, but the `+` operator creates a new list:
``` python
>>> t1 = [1, 2]
>>> t2 = t1.append(3)
>>> print t1
[1, 2, 3]
>>> print t2
None
>>> t3 = t1 + [3]
>>> print t3
[1, 2, 3]
>>> t2 is t3
False
```
This difference is important when you write functions that are supposed
to modify lists. For example, this function *does not* delete the head
of a list:
``` python
def bad_delete_head(t):
t = t[1:] # WRONG!
```
The slice operator creates a new list and the assignment makes `t` refer
to it, but none of that has any effect on the list that was passed as an
argument.
An alternative is to write a function that creates and returns a new
list. For example, `tail` returns all but the first element of a list:
``` python
def tail(t):
return t[1:]
```
This function leaves the original list unmodified. Here's how it is
used:
``` python
>>> letters = ['a', 'b', 'c']
>>> rest = tail(letters)
>>> print rest
['b', 'c']
```
### Exercise 2
Write a function called **\'`chop`**\' that takes a list and modifies
it, removing the first and last elements, and returns **\'`None`**\'.
Then write a function called **\'`middle`**\' that takes a list and
returns a new list that contains all but the first and last elements.
## Debugging
Careless use of lists (and other mutable objects) can lead to long hours
of debugging. Here are some common pitfalls and ways to avoid them:
- Don't forget that most list methods modify the argument and
return `None`. This is the opposite of the string methods, which return
a new string and leave the original alone. If you are used to writing
string code like this:
``` python
word = word.strip()
```
It is tempting to write list code like this:
``` python
t = t.sort() # WRONG!
```
Because `sort` returns `None`, the next operation you perform with `t`
is likely to fail.
Before using list methods and operators, you should read the
documentation carefully and then test them in interactive mode. The
methods and operators that lists share with other sequences (like
strings) are documented at `docs.python.org/lib/typesseq.html`. The
methods and operators that only apply to mutable sequences are
documented at `docs.python.org/lib/typesseq-mutable.html`.
- Pick an idiom and stick with it.
Part of the problem with lists is that there are too many ways to do
things. For example, to remove an element from a list, you can use
`pop`, `remove`, `del`, or even a slice assignment.
To add an element, you can use the `append` method or the `+` operator.
But don't forget that these are right:
``` python
t.append(x)
t = t + [x]
```
And these are wrong:
``` python
t.append([x]) # WRONG!
t = t.append(x) # WRONG!
t + [x] # WRONG!
t = t + x # WRONG!
```
Try out each of these examples in interactive mode to make sure you
understand what they do. Notice that only the last one causes a runtime
error; the other three are legal, but they do the wrong thing.
- Make copies to avoid aliasing.
If you want to use a method like `sort` that modifies the argument, but
you need to keep the original list as well, you can make a copy.
``` python
orig = t[:]
t.sort()
```
In this example you could also use the built-in function `sorted`, which
returns a new, sorted list and leaves the original alone. But in that
case you should avoid using `sorted` as a variable name!
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**list:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A sequence of values.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**element:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the values in a list (or other sequence), also called items.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**index:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An integer value that indicates an element in a list.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**nested list:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A list that is an element of another list.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**list traversal:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The sequential accessing of each element in a list.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**mapping:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A relationship in which each element of one set corresponds to an
element of another set. For example, a list is a mapping from indices to
elements.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**accumulator:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A variable used in a loop to add up or accumulate a result.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**reduce:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A processing pattern that traverses a sequence and accumulates the
elements into a single result.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**map:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A processing pattern that traverses a sequence and performs an operation
on each element.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**filter:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A processing pattern that traverses a list and selects the elements that
satisfy some criterion.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**object:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Something a variable can refer to. An object has a type and a value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**equivalent:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Having the same value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**identical:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Being the same object (which implies equivalence).
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**reference:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The association between a variable and its value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**aliasing:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A circumstance where two variables refer to the same object.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**delimiter:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A character or string used to indicate where a string should be split.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 3
Write a function called **`is_sorted`** that takes a list as a parameter
and returns **\'`True`**\' if the list is sorted in ascending order and
**\'`False`**\' otherwise. You can assume (as a precondition) that the
elements of the list can be compared with the comparison operators
**\'`<`**\', **\'`>`**\', etc.\'\'
*For example,`is_sorted([1,2,2])`should return **\'`True`**\'
and`is_sorted(['b','a'])`*\'\' should return **\'`False`**\'.
### Exercise 4
*Two words are anagrams if you can rearrange the letters from one to
spell the other. Write a function called`is_anagram`that takes two
strings and returns **\'`True`**\' if they are anagrams.*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 5** *The (so-called) Birthday Paradox:*
-
*Write a function called`has_duplicates`that takes a list and returns
**\'`True`**\' if there is any element that appears more than once. It
should not modify the original list.*
- \'\'If there are 23 students in your class, what are the chances
that two of you have the same birthday? You can estimate this
probability by generating random samples of 23 birthdays and checking
for matches. Hint: you can generate random birthdays with the
**\'`randint`**\' function in the **\'`random`**\' module.\'\'
*You can read about this problem at
**\'`wikipedia.org/wiki/Birthday_paradox`**\', and you can see my
solution at **\'`thinkpython.com/code/birthday.py`**\'.*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 6**
*Write a function called`remove_duplicates`*\'\' that takes a list and
returns a new list with only the unique elements from the original.
Hint: they don't have to be in the same order.
### Exercise 7
*Write a function that reads the file **\'`words.txt`**\' and builds a
list with one element per word. Write two versions of this function, one
using the **\'`append`**\' method and the other using the idiom
**\'`t = t + [x]`**\'. Which one takes longer to run? Why?*
\'\'You can see my solution at
**\'`thinkpython.com/code/wordlist.py`**\'.
### Exercise 8
*To check whether a word is in the word list, you could use the
**\'`in`**\' operator, but it would be slow because it searches through
the words in order.*
*Because the words are in alphabetical order, we can speed things up
with a bisection search, which is similar to what you do when you look a
word up in the dictionary. You start in the middle and check to see
whether the word you are looking for comes before the word in the middle
of the list. If so, then you search the first half of the list the same
way. Otherwise you search the second half.*
*Either way, you cut the remaining search space in half. If the word
list has 113,809 words, it will take about 17 steps to find the word or
conclude that it's not there.*
*Write a function called **\'`bisect`**\' that takes a sorted list and a
target value and returns the index of the value in the list, if it's
there, or **\'`None`**\' if it's not.*
*Or you could read the documentation of the **\'`bisect`**\' module and
use that!*
### Exercise 9
Two words are a "reverse pair" if each is the reverse of the other.
Write a program that finds all the reverse pairs in the word list.
### Exercise 10
*Two words "interlock" if taking alternating letters from each forms a
new word*^*1*^*. For example, "shoe" and "cold" interlock to form
"schooled."*
- \'\'Write a program that finds all pairs of words that interlock.
Hint: don't enumerate all pairs!\'\'
- \'\'Can you find any words that are three-way interlocked; that is,
every third letter forms a word, starting from the first, second or
third?\'\'
```{=html}
</DIV>
```
```{=html}
<HR CLASS="footnoterule">
```
```{=html}
<DL CLASS="thefootnotes">
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
1
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
This exercise is inspired by an example at `puzzlers.org`.
```{=html}
</DD>
```
```{=html}
</DL>
```
|
# Think Python/Dictionaries
A **dictionary** is like a list, but more general. In a list, the
indices have to be integers; in a dictionary they can be (almost) any
type.
You can think of a dictionary as a mapping between a set of indices
(which are called **keys**) and a set of values. Each key maps to a
value. The association of a key and a value is called a **key-value
pair** or sometimes an **item**.
As an example, we\'ll build a dictionary that maps from English to
Spanish words, so the keys and the values are all strings.
The function `dict` creates a new dictionary with no items. Because
`dict` is the name of a built-in function, you should avoid using it as
a variable name.
``` python
>>> eng2sp = dict()
>>> print eng2sp
{}
```
The squiggly-brackets, `{}`, represent an empty dictionary. To add items
to the dictionary, you can use square brackets:
``` python
>>> eng2sp['one'] = 'uno'
```
This line creates an item that maps from the key `’one’` to the value
`'uno'`. If we print the dictionary again, we see a key-value pair with
a colon between the key and value:
``` python
>>> print eng2sp
{'one': 'uno'}
```
This output format is also an input format. For example, you can create
a new dictionary with three items:
``` python
>>> eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'}
```
But if you print `eng2sp`, you might be surprised:
``` python
>>> print eng2sp
{'one': 'uno', 'three': 'tres', 'two': 'dos'}
```
The order of the key-value pairs is not the same. In fact, if you type
the same example on your computer, you might get a different result. In
general, the order of items in a dictionary is unpredictable.
But that's not a problem because the elements of a dictionary are never
indexed with integer indices. Instead, you use the keys to look up the
corresponding values:
``` python
>>> print eng2sp['two']
'dos'
```
The key `’two’` always maps to the value `'dos'` so the order of the
items doesn't matter.
If the key isn't in the dictionary, you get an exception:
``` python
>>> print eng2sp['four']
KeyError: 'four'
```
The `len` function works on dictionaries; it returns the number of
key-value pairs:
``` python
>>> len(eng2sp)
3
```
The `in` operator works on dictionaries; it tells you whether something
appears as a *key* in the dictionary (appearing as a value is not good
enough).
``` python
>>> 'one' in eng2sp
True
>>> 'uno' in eng2sp
False
```
To see whether something appears as a value in a dictionary, you can use
the method `values`, which returns the values as a list, and then use
the `in` operator:
``` python
>>> vals = eng2sp.values()
>>> 'uno' in vals
True
```
You can do the same with `keys`:
``` python
>>> kees = eng2sp.keys()
>>> ‘one’ in kees
True
```
The `in` operator uses different algorithms for lists and dictionaries.
For lists, it uses a search algorithm, as in Section 8.6. As the list
gets longer, the search time gets longer in direct proportion. For
dictionaries, Python uses an algorithm called a **hashtable** that has a
remarkable property: the `in` operator takes about the same amount of
time no matter how many items there are in a dictionary. I won't explain
how that's possible, but you can read more about it at
`wikipedia.org/wiki/Hash_table`.
### Exercise 1
*Write a function that reads the words in **\'`words.txt`**\' and stores
them as keys in a dictionary. It doesn't matter what the values are.
Then you can use the **\'`in`**\' operator as a fast way to check
whether a string is in the dictionary.*
*If you did Exercise **\'10.8**\', you can compare the speed of this
implementation with the list **\'`in`**\' operator and the bisection
search.*
```{=html}
</DIV>
```
## Dictionary as a set of counters
Suppose you are given a string and you want to count how many times each
letter appears. There are several ways you could do it:
- You could create 26 variables, one for each letter of the alphabet.
Then you could traverse the string and, for each character,
increment the corresponding counter, probably using a chained
conditional.
- You could create a list with 26 elements. Then you could convert
each character to a number (using the built-in function `ord`), use
the number as an index into the list, and increment the appropriate
counter.
- You could create a dictionary with characters as keys and counters
as the corresponding values. The first time you see a character, you
would add an item to the dictionary. After that you would increment
the value of an existing item.
Each of these options performs the same computation, but each of them
implements that computation in a different way.
An **implementation** is a way of performing a computation; some
implementations are better than others. For example, an advantage of the
dictionary implementation is that we don't have to know ahead of time
which letters appear in the string and we only have to make room for the
letters that do appear.
Here is what the code might look like:
``` python
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] += 1
return d
```
The name of the function is **histogram**, which is a statistical term
for a set of counters (or frequencies).
The first line of the function creates an empty dictionary. The `for`
loop traverses the string. Each time through the loop, if the character
`c` is not in the dictionary, we create a new item with key `c` and the
initial value 1 (since we have seen this letter once). If `c` is already
in the dictionary we increment `d[c]`.
Here's how it works:
``` python
>>> h = histogram('brontosaurus')
>>> print h
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
```
The histogram indicates that the letters `’a’` and `'b'` appear once;
`'o'` appears twice, and so on.
### Exercise 2
*Dictionaries have a method called **\'`get`**\' that takes a key and a
default value. If the key appears in the dictionary, **\'`get`**\'
returns the corresponding value; otherwise it returns the default value.
For example:*
``` python
''>>> h = histogram('a')
>>> print h
{'a': 1}
>>> h.get('a', 0)
1
>>> h.get('b', 0)
0
''
```
*Use **\'`get`**\' to write **\'`histogram`**\' more concisely. You
should be able to eliminate the **\'`if`**\' statement.*
```{=html}
</DIV>
```
## Looping and dictionaries
If you use a dictionary in a `for` statement, it traverses the keys of
the dictionary. For example, `print_hist` prints each key and the
corresponding value:
``` python
def print_hist(h):
for c in h:
print c, h[c]
```
Here's what the output looks like:
``` python
>>> h = histogram('parrot')
>>> print_hist(h)
a 1
p 1
r 2
t 1
o 1
```
Again, the keys are in no particular order.
### Exercise 3
*Dictionaries have a method called **\'`keys`**\' that returns the keys
of the dictionary, in no particular order, as a list.*
*Modify`print_hist`*\'\' to print the keys and their values in
alphabetical order.
## Reverse lookup
Given a dictionary `d` and a key `k`, it is easy to find the
corresponding value `v = d[k]`. This operation is called a **lookup**.
But what if you have `v` and you want to find `k`? You have two
problems: first, there might be more than one key that maps to the value
`v`. Depending on the application, you might be able to pick one, or you
might have to make a list that contains all of them. Second, there is no
simple syntax to do a **reverse lookup**; you have to search.
Here is a function that takes a value and returns the first key that
maps to that value:
``` python
def reverse_lookup(d, v):
for k in d:
if d[k] == v:
return k
raise ValueError
```
This function is yet another example of the search pattern, but it uses
a feature we haven't seen before, `raise`. The `raise` statement causes
an exception; in this case it causes a `ValueError`, which generally
indicates that there is something wrong with the value of a parameter.
If we get to the end of the loop, that means `v` doesn't appear in the
dictionary as a value, so we raise an exception.
Here is an example of a successful reverse lookup:
``` python
>>> h = histogram('parrot')
>>> k = reverse_lookup(h, 2)
>>> print k
r
```
And an unsuccessful one:
``` python
>>> k = reverse_lookup(h, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 5, in reverse_lookup
ValueError
```
The result when you raise an exception is the same as when Python raises
one: it prints a traceback and an error message.
The `raise` statement takes a detailed error message as an optional
argument. For example:
``` python
>>> raise ValueError, 'value does not appear in the dictionary'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: value does not appear in the dictionary
```
A reverse lookup is much slower than a forward lookup; if you have to do
it often, or if the dictionary gets big, the performance of your program
will suffer.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 4** *Modify`reverse_lookup`so that it builds and returns a
list of*all*keys that map to **\'`v`**\', or an empty list if there are
none.*
```{=html}
</DIV>
```
## Dictionaries and lists
Lists can appear as values in a dictionary. For example, if you were
given a dictionary that maps from letters to frequencies, you might want
to invert it; that is, create a dictionary that maps from frequencies to
letters. Since there might be several letters with the same frequency,
each value in the inverted dictionary should be a list of letters.
Here is a function that inverts a dictionary:
``` python
def invert_dict(d):
inv = dict()
for key in d:
val = d[key]
if val not in inv:
inv[val] = [key]
else:
inv[val].append(key)
return inv
```
Each time through the loop, `key` gets a key from `d` and `val` gets the
corresponding value. If `val` is not in `inv`, that means we haven't
seen it before, so we create a new item and initialize it with a
**singleton** (a list that contains a single element). Otherwise we have
seen this value before, so we append the corresponding key to the list.
Here is an example:
``` python
>>> hist = histogram('parrot')
>>> print hist
{'a': 1, 'p': 1, 'r': 2, 't': 1, 'o': 1}
>>> inv = invert_dict(hist)
>>> print inv
{1: ['a', 'p', 't', 'o'], 2: ['r']}
```
And here is a diagram showing `hist` and `inv`:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book018.png">`{=html}
```{=html}
</DIV>
```
A dictionary is represented as a box with the type `dict` above it and
the key-value pairs inside. If the values are integers, floats or
strings, I usually draw them inside the box, but I usually draw lists
outside the box, just to keep the diagram simple.
Lists can be values in a dictionary, as this example shows, but they
cannot be keys. Here's what happens if you try:
``` python
>>> t = [1, 2, 3]
>>> d = dict()
>>> d[t] = 'oops'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: list objects are unhashable
```
I mentioned earlier that a dictionary is implemented using a hashtable
and that means that the keys have to be **hashable**.
A **hash** is a function that takes a value (of any kind) and returns an
integer. Dictionaries use these integers, called hash values, to store
and look up key-value pairs.
This system works fine if the keys are immutable. But if the keys are
mutable, like lists, bad things happen. For example, when you create a
key-value pair, Python hashes the key and stores it in the corresponding
location. If you modify the key and then hash it again, it would go to a
different location. In that case you might have two entries for the same
key, or you might not be able to find a key. Either way, the dictionary
wouldn't work correctly.
That's why the keys have to be hashable, and why mutable types like
lists aren't. The simplest way to get around this limitation is to use
tuples, which we will see in the next chapter.
Since dictionaries are mutable, they can't be used as keys, but they
*can* be used as values.
### Exercise 5
Read the documentation of the dictionary method **\'`setdefault`**\' and
use it to write a more concise version of **`invert_dict`**.\'\'
## Memos
If you played with the `fibonacci` function from Section 6.7, you might
have noticed that the bigger the argument you provide, the longer the
function takes to run. Furthermore, the run time increases very quickly.
To understand why, consider this **call graph** for `fibonacci` with
`n=4`:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book019.png">`{=html}
```{=html}
</DIV>
```
A call graph shows a set of function frames, with lines connecting each
frame to the frames of the functions it calls. At the top of the graph,
`fibonacci` with `n=4` calls `fibonacci` with `n=3` and `n=2`. In turn,
`fibonacci` with `n=3` calls `fibonacci` with `n=2` and `n=1`. And so
on.
Count how many times `fibonacci(0)` and `fibonacci(1)` are called. This
is an inefficient solution to the problem, and it gets worse as the
argument gets bigger.
One solution is to keep track of values that have already been computed
by storing them in a dictionary. A previously computed value that is
stored for later use is called a **memo**[^1]. Here is an implementation
of `fibonacci` using memos:
``` python
known = {0:0, 1:1}
def fibonacci(n):
if n in known:
return known[n]
res = fibonacci(n-1) + fibonacci(n-2)
known[n] = res
return res
```
`known` is a dictionary that keeps track of the Fibonacci numbers we
already know. It starts with two items: 0 maps to 0 and 1 maps to 1.
Whenever `fibonacci` is called, it checks `known`. If the result is
already there, it can return immediately. Otherwise it has to compute
the new value, add it to the dictionary, and return it.
### Exercise 6
Run this version of **\'`fibonacci`**\' and the original with a range of
parameters and compare their run times.
## Global variables
In the previous example, `known` is created outside the function, so it
belongs to the special frame called `__main__`. Variables in `__main__`
are sometimes called **global** because they can be accessed from any
function. Unlike local variables, which disappear when their function
ends, global variables persist from one function call to the next.
It is common to use global variables for **flags**; that is, boolean
variables that indicate ("flag") whether a condition is true. For
example, some programs use a flag named `verbose` to control the level
of detail in the output:
``` python
verbose = True
def example1():
if verbose:
print 'Running example1'
```
If you try to reassign a global variable, you might be surprised. The
following example is supposed to keep track of whether the function has
been called:
``` python
been_called = False
def example2():
been_called = True # WRONG
```
But if you run it you will see that the value of `been_called` doesn't
change. The problem is that `example2` creates a new local variable
named `been_called`. The local variable goes away when the function
ends, and has no effect on the global variable.
To reassign a global variable inside a function you have to **declare**
the global variable before you use it:
``` python
been_called = False
def example2():
global been_called
been_called = True
```
The `global` statement tells the interpreter something like, "In this
function, when I say `been_called`, I mean the global variable; don't
create a local one."
Here's an example that tries to update a global variable:
``` python
count = 0
def example3():
count = count + 1 # WRONG
```
If you run it you get:
``` python
UnboundLocalError: local variable 'count' referenced before assignment
```
Python assumes that `count` is local, which means that you are reading
it before writing it. The solution, again, is to declare `count` global.
``` python
def example3():
global count
count += 1
```
If the global value is mutable, you can modify it without declaring it:
``` python
known = {0:0, 1:1}
def example4():
known[2] = 1
```
So you can add, remove and replace elements of a global list or
dictionary, but if you want to reassign the variable, you have to
declare it:
``` python
def example5():
global known
known = dict()
```
## Long integers
If you compute `fibonacci(50)`, you get:
``` python
>>> fibonacci(50)
12586269025L
```
The `L` at the end indicates that the result is a long integer[^2], or
type `long`.
Values with type `int` have a limited range; long integers can be
arbitrarily big, but as they get bigger they consume more space and
time.
The mathematical operators work on long integers, and the functions in
the `math` module, too, so in general any code that works with `int`
will also work with `long`.
Any time the result of a computation is too big to be represented with
an integer, Python converts the result as a long integer:
``` python
>>> 1000 * 1000
1000000
>>> 100000 * 100000
10000000000L
```
In the first case the result has type `int`; in the second case it is
`long`.
### Exercise 7
*Exponentiation of large integers is the basis of common algorithms for
public-key encryption. Read the Wikipedia page on the RSA algorithm[^3]
and write functions to encode and decode messages.*
## Debugging
As you work with bigger datasets it can become unwieldy to debug by
printing and checking data by hand. Here are some suggestions for
debugging large datasets:
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**Scale down the input:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
If possible, reduce the size of the dataset. For example if the program
reads a text file, start with just the first 10 lines, or with the
smallest example you can find. You can either edit the files themselves,
or (better) modify the program so it reads only the first `n` lines. If
there is an error, you can reduce `n` to the smallest value that
manifests the error, and then increase it gradually as you find and
correct errors.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Check summaries and types:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Instead of printing and checking the entire dataset, consider printing
summaries of the data: for example, the number of items in a dictionary
or the total of a list of numbers. A common cause of runtime errors is a
value that is not the right type. For debugging this kind of error, it
is often enough to print the type of a value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Write self-checks:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Sometimes you can write code to check for errors automatically. For
example, if you are computing the average of a list of numbers, you
could check that the result is not greater than the largest element in
the list or less than the smallest. This is called a "sanity check"
because it detects results that are "insane."
Another kind of check compares the results of two different computations
to see if they are consistent. This is called a "consistency check."
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Pretty print the output:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Formatting debugging output can make it easier to spot an error. We saw
an example in Section 6.9. The `pprint` module provides a `pprint`
function that displays built-in types in a more human-readable format.
```{=html}
</DD>
```
```{=html}
</DL>
```
Again, time you spend building scaffolding can reduce the time you spend
debugging.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**dictionary:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A mapping from a set of keys to their corresponding values.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**key-value pair:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The representation of the mapping from a key to a value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**item:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Another name for a key-value pair.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**key:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An object that appears in a dictionary as the first part of a key-value
pair.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**value:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An object that appears in a dictionary as the second part of a key-value
pair. This is more specific than our previous use of the word "value."
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**implementation:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A way of performing a computation.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**hashtable:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The algorithm used to implement Python dictionaries.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**hash function:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A function used by a hashtable to compute the location for a key.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**hashable:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A type that has a hash function. Immutable types like integers, floats
and strings are hashable; mutable types like lists and dictionaries are
not.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**lookup:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A dictionary operation that takes a key and finds the corresponding
value.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**reverse lookup:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A dictionary operation that takes a value and finds one or more keys
that map to it.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**singleton:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A list (or other sequence) with a single element.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**call graph:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A diagram that shows every frame created during the execution of a
program, with an arrow from each caller to each callee.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**histogram:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A set of counters.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**memo:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A computed value stored to avoid unnecessary future computation.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**global variable:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A variable defined outside a function. Global variables can be accessed
from any function.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**flag:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A boolean variable used to indicate whether a condition is true.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**declaration:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A statement like `global` that tells the interpreter something about a
variable.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercise-8
` Dictionaries have a method called 'keys' that returns the keys of the dictionary, in`
no particular order, as a list. Modify print_hist to print the keys and
their values in alphabetical order.
### Exercise 9
*Two words are "rotate pairs" if you can rotate one of them and get the
other (see`rotate_word`in Exercise **\'8.12**\').*
\'\'Write a program that reads a wordlist and finds all the rotate
pairs.
### Exercise 10
*Here's another Puzzler from*Car Talk[^4]*:*
> *This was sent in by a fellow named Dan O'Leary. He came upon a common
> one-syllable, five-letter word recently that has the following unique
> property. When you remove the first letter, the remaining letters form
> a homophone of the original word, that is a word that sounds exactly
> the same. Replace the first letter, that is, put it back and remove
> the second letter and the result is yet another homophone of the
> original word. And the question is, what's the word?* *Now I'm going
> to give you an example that doesn't work. Let's look at the
> five-letter word, 'wrack.' W-R-A-C-K, you know like to 'wrack with
> pain.' If I remove the first letter, I am left with a four-letter
> word, 'R-A-C-K.' As in, 'Holy cow, did you see the rack on that buck!
> It must have been a nine-pointer!' It's a perfect homophone. If you
> put the 'w' back, and remove the 'r,' instead, you're left with the
> word, 'wack,' which is a real word, it's just not a homophone of the
> other two words.*
>
> *But there is, however, at least one word that Dan and we know of,
> which will yield two homophones if you remove either of the first two
> letters to make two, new four-letter words. The question is, what's
> the word?*
*You can use the dictionary from Exercise **\'11.1**\' to check whether
a string is in the word list.*
*To check whether two words are homophones, you can use the CMU
Pronouncing Dictionary. You can download it from
**\'`www.speech.cs.cmu.edu/cgi-bin/cmudict`**\' or from
**\'`thinkpython.com/code/c06d`**\' and you can also download
**\'`thinkpython.com/code/pronounce.py`**\', which provides a function
named`read_dictionary`that reads the pronouncing dictionary and returns
a Python dictionary that maps from each word to a string that describes
its primary pronunciation.*
*Write a program that lists all the words that solve the Puzzler. You
can see my solution at **\'`thinkpython.com/code/homophone.py`**\'.*
## Notes
[^1]: See `wikipedia.org/wiki/Memoization`
[^2]: In Python 3.0, type `long` is gone; all integers, even really big
ones, are type `int`.
[^3]: `wikipedia.org/wiki/RSA`
[^4]: `www.cartalk.com/content/puzzler/transcripts/200717`
|
# Think Python/Tuples
## Tuples are immutable
A tuple is a sequence of values. The values can be any type, and they
are indexed by integers, so in that respect tuples are a lot like lists.
The important difference is that tuples are immutable.
Syntactically, a tuple is a comma-separated list of values:
``` python
>>> t = 'a', 'b', 'c', 'd', 'e'
```
Although it is not necessary, it is common to enclose tuples in
parentheses:
``` python
>>> t = ('a', 'b', 'c', 'd', 'e')
```
To create a tuple with a single element, you have to include the final
comma:
``` python
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple'>
```
Without the comma, Python treats `('a')` as a string in parentheses:
``` python
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
```
Another way to create a tuple is the built-in function `tuple`. With no
argument, it creates an empty tuple:
``` python
>>> t = tuple()
>>> print t
()
```
If the argument is a sequence (string, list or tuple), the result is a
tuple with the elements of the sequence:
``` python
>>> t = tuple('lupins')
>>> print t
('l', 'u', 'p', 'i', 'n', 's')
```
Because `tuple` is the name of a built-in function, you should avoid
using it as a variable name.
Most list operators also work on tuples. The bracket operator indexes an
element:
``` python
>>> t = ('a', 'b', 'c', 'd', 'e')
>>> print t[0]
'a'
```
And the slice operator selects a range of elements.
``` python
>>> print t[1:3]
('b', 'c')
```
But if you try to modify one of the elements of the tuple, you get an
error:
``` python
>>> t[0] = 'A'
TypeError: object doesn't support item assignment
```
You can't modify the elements of a tuple, but you can replace one tuple
with another:
``` python
>>> t = ('A',) + t[1:]
>>> print t
('A', 'b', 'c', 'd', 'e')
```
## Tuple assignment
It is often useful to swap the values of two variables. With
conventional assignments, you have to use a temporary variable. For
example, to swap `a` and `b`:
``` python
>>> temp = a
>>> a = b
>>> b = temp
```
This solution is cumbersome; **tuple assignment** is more elegant:
``` python
>>> a, b = b, a
```
The left side is a tuple of variables; the right side is a tuple of
expressions. Each value is assigned to its respective variable. All the
expressions on the right side are evaluated before any of the
assignments.
The number of variables on the left and the number of values on the
right have to be the same:
``` python
>>> a, b = 1, 2, 3
ValueError: too many values to unpack
```
More generally, the right side can be any kind of sequence (string, list
or tuple). For example, to split an email address into a user name and a
domain, you could write:
``` python
>>> addr = '[email protected]'
>>> uname, domain = addr.split('@')
```
The return value from `split` is a list with two elements; the first
element is assigned to `uname`, the second to `domain`.
``` python
>>> print uname
monty
>>> print domain
python.org
```
## Tuples as return values
Strictly speaking, a function can only return one value, but if the
value is a tuple, the effect is the same as returning multiple values.
For example, if you want to divide two integers and compute the quotient
and remainder, it is inefficient to compute `x/y` and then `x%y`. It is
better to compute them both at the same time.
The built-in function `divmod` takes two arguments and returns a tuple
of two values, the quotient and remainder. You can store the result as a
tuple:
``` python
>>> t = divmod(7, 3)
>>> print t
(2, 1)
```
Or use tuple assignment to store the elements separately:
``` python
>>> quot, rem = divmod(7, 3)
>>> print quot
2
>>> print rem
1
```
Here is an example of a function that returns a tuple:
``` python
def min_max(t):
return min(t), max(t)
```
`max` and `min` are built-in functions that find the largest and
smallest elements of a sequence. `min_max` computes both and returns a
tuple of two values.
## Variable-length argument tuples
Functions can take a variable number of arguments. A parameter name that
begins with `*` **gathers** arguments into a tuple. For example,
`printall` takes any number of arguments and prints them:
``` python
def printall(*args):
print args
```
The gather parameter can have any name you like, but `args` is
conventional. Here's how the function works:
``` python
>>> printall(1, 2.0, '3')
(1, 2.0, '3')
```
You can combine the gather operator with required and positional
arguments:
``` python
def pointless(required, optional=0, *args):
print required, optional, args
```
Run this function with 1, 2, 3 and 4 or more arguments and make sure you
understand what it does.
The complement of gather is **scatter**. If you have a sequence of
values and you want to pass it to a function as multiple arguments, you
can use the `*` operator. For example, `divmod` takes exactly two
arguments; it doesn't work with a tuple:
``` python
>>> t = (7, 3)
>>> divmod(t)
TypeError: divmod expected 2 arguments, got 1
```
But if you scatter the tuple, it works:
``` python
>>> divmod(*t)
(2, 1)
```
### Exercise 1
Many of the built-in functions use variable-length argument tuples. For
example, **\'`max`**\' and **\'`min`**\' can take any number of
arguments:\'\'
``` python
''>>> max(1,2,3)
3
''
```
*But **\'`sum`**\' does not.*
``` python
''>>> sum(1,2,3)
TypeError: sum expected at most 2 arguments, got 3
''
```
*Write a function called **\'`sumall`**\' that takes any number of
arguments and returns their sum.*
## Lists and tuples
`zip` is a built-in function that takes two or more sequences and "zips"
them into a list^1^ of tuples where each tuple contains one element from
each sequence.
This example zips a string and a list:
``` python
>>> s = 'abc'
>>> t = [0, 1, 2]
>>> zip(s, t)
[('a', 0), ('b', 1), ('c', 2)]
```
The result is a list of tuples where each tuple contains a character
from the string and the corresponding element from the list.
If the sequences are not the same length, the result has the length of
the shorter one.
``` python
>>> zip('Anne', 'Elk')
[('A', 'E'), ('n', 'l'), ('n', 'k')]
```
You can use tuple assignment in a `for` loop to traverse a list of
tuples:
``` python
t = [('a', 0), ('b', 1), ('c', 2)]
for letter, number in t:
print number, letter
```
Each time through the loop, Python selects the next tuple in the list
and assigns the elements to `letter` and `number`. The output of this
loop is:
``` python
0 a
1 b
2 c
```
If you combine `zip`, `for` and tuple assignment, you get a useful idiom
for traversing two (or more) sequences at the same time. For example,
`has_match` takes two sequences, `t1` and `t2`, and returns `True` if
there is an index `i` such that `t1[i] == t2[i]`:
``` python
def has_match(t1, t2):
for x, y in zip(t1, t2):
if x == y:
return True
return False
```
If you need to traverse the elements of a sequence and their indices,
you can use the built-in function `enumerate`:
``` python
for index, element in enumerate('abc'):
print index, element
```
The output of this loop is:
``` python
0 a
1 b
2 c
```
Again.
## Dictionaries and tuples
Dictionaries have a method called `items` that returns a list of tuples,
where each tuple is a key-value pair^2^.
``` python
>>> d = {'a':0, 'b':1, 'c':2}
>>> t = d.items()
>>> print t
[('a', 0), ('c', 2), ('b', 1)]
```
As you should expect from a dictionary, the items are in no particular
order.
Conversely, you can use a list of tuples to initialize a new dictionary:
``` python
>>> t = [('a', 0), ('c', 2), ('b', 1)]
>>> d = dict(t)
>>> print d
{'a': 0, 'c': 2, 'b': 1}
```
Combining `dict` with `zip` yields a concise way to create a dictionary:
``` python
>>> d = dict(zip('abc', range(3)))
>>> print d
{'a': 0, 'c': 2, 'b': 1}
```
The dictionary method `update` also takes a list of tuples and adds
them, as key-value pairs, to an existing dictionary.
Combining `items`, tuple assignment and `for`, you get the idiom for
traversing the keys and values of a dictionary:
``` python
for key, val in d.items():
print val, key
```
The output of this loop is:
``` python
0 a
2 c
1 b
```
Again.
It is common to use tuples as keys in dictionaries (primarily because
you can't use lists). For example, a telephone directory might map from
last-name, first-name pairs to telephone numbers. Assuming that we have
defined `last`, `first` and `number`, we could write:
``` python
directory[last,first] = number
```
The expression in brackets is a tuple. We could use tuple assignment to
traverse this dictionary.
``` python
for last, first in directory:
print first, last, directory[last,first]
```
This loop traverses the keys in `directory`, which are tuples. It
assigns the elements of each tuple to `last` and `first`, then prints
the name and corresponding telephone number.
There are two ways to represent tuples in a state diagram. The more
detailed version shows the indices and elements just as they appear in a
list. For example, the tuple `('Cleese', 'John')` would appear:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book020.png">`{=html}
```{=html}
</DIV>
```
But in a larger diagram you might want to leave out the details. For
example, a diagram of the telephone directory might appear:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book021.png">`{=html}
```{=html}
</DIV>
```
Here the tuples are shown using Python syntax as a graphical shorthand.
The telephone number in the diagram is the complaints line for the BBC,
so please don't call it.
## Comparing tuples
The comparison operators work with tuples and other sequences; Python
starts by comparing the first element from each sequence. If they are
equal, it goes on to the next elements, and so on, until it finds
elements that differ. Subsequent elements are not considered (even if
they are really big).
``` python
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
```
The `sort` function works the same way. It sorts primarily by first
element, but in the case of a tie, it sorts by second element, and so
on.
This feature lends itself to a pattern called **DSU** for
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**Decorate**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
a sequence by building a list of tuples with one or more sort keys
preceding the elements from the sequence,
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Sort**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
the list of tuples, and
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**Undecorate**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
by extracting the sorted elements of the sequence.
```{=html}
</DD>
```
```{=html}
</DL>
```
For example, suppose you have a list of words and you want to sort them
from longest to shortest:
``` python
def sort_by_length(words):
t = []
for word in words:
t.append((len(word), word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
return res
```
The first loop builds a list of tuples, where each tuple is a word
preceded by its length.
`sort` compares the first element, length, first, and only considers the
second element to break ties. The keyword argument `reverse=True` tells
`sort` to go in decreasing order.
The second loop traverses the list of tuples and builds a list of words
in descending order of length.
### Exercise 2
In this example, ties are broken by comparing words, so words with the
same length appear in alphabetical order. For other applications you
might want to break ties at random. Modify this example so that words
with the same length appear in random order. Hint: see the
**\'`random`**\' function in the **\'`random`**\' module.\'\'
## Sequences of sequences
I have focused on lists of tuples, but almost all of the examples in
this chapter also work with lists of lists, tuples of tuples, and tuples
of lists. To avoid enumerating the possible combinations, it is
sometimes easier to talk about sequences of sequences.
In many contexts, the different kinds of sequences (strings, lists and
tuples) can be used interchangeably. So how and why do you choose one
over the others?
To start with the obvious, strings are more limited than other sequences
because the elements have to be characters. They are also immutable. If
you need the ability to change the characters in a string (as opposed to
creating a new string), you might want to use a list of characters
instead.
Lists are more common than tuples, mostly because they are mutable. But
there are a few cases where you might prefer tuples:
- In some contexts, like a `return` statement, it is syntactically
simpler to create a tuple than a list. In other contexts, you might
prefer a list.
- If you want to use a sequence as a dictionary key, you have to use
an immutable type like a tuple or string.
- If you are passing a sequence as an argument to a function, using
tuples reduces the potential for unexpected behavior due to
aliasing.
Because tuples are immutable, they don't provide methods like `sort` and
`reverse`, which modify existing lists. But Python provides the built-in
functions `sorted` and `reversed`, which take any sequence as a
parameter and return a new list with the same elements in a different
order.
## Debugging
Lists, dictionaries and tuples are known generically as **data
structures**; in this chapter we are starting to see compound data
structures, like lists of tuples, and dictionaries that contain tuples
as keys and lists as values. Compound data structures are useful, but
they are prone to what I call **shape errors**; that is, errors caused
when a data structure has the wrong type, size or composition. For
example, if you are expecting a list with one integer and I give you a
plain old integer (not in a list), it won't work.
To help debug these kinds of errors, I have written a module called
`structshape` that provides a function, also called `structshape`, that
takes any kind of data structure as an argument and returns a string
that summarizes its shape. You can download it from
`thinkpython.com/code/structshape.py`
Here's the result for a simple list:
``` python
>>> from structshape import structshape
>>> t = [1,2,3]
>>> print structshape(t)
list of 3 int
```
A fancier program might write "list of 3 int*s*," but it was easier not
to deal with plurals. Here's a list of lists:
``` python
>>> t2 = [[1,2], [3,4], [5,6]]
>>> print structshape(t2)
list of 3 list of 2 int
```
If the elements of the list are not the same type, `structshape` groups
them, in order, by type:
``` python
>>> t3 = [1, 2, 3, 4.0, '5', '6', [7], [8], 9]
>>> print structshape(t3)
list of (3 int, float, 2 str, 2 list of int, int)
```
Here's a list of tuples:
``` python
>>> s = 'abc'
>>> lt = zip(t, s)
>>> print structshape(lt)
list of 3 tuple of (int, str)
```
And here's a dictionary with 3 items that map integers to strings.
``` python
>>> d = dict(lt)
>>> print structshape(d)
dict of 3 int->str
```
If you are having trouble keeping track of your data structures,
`structshape` can help.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**tuple:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An immutable sequence of elements.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**tuple assignment:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An assignment with a sequence on the right side and a tuple of variables
on the left. The right side is evaluated and then its elements are
assigned to the variables on the left.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**gather:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The operation of assembling a variable-length argument tuple.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**scatter:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The operation of treating a sequence as a list of arguments.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**DSU:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Abbreviation of "decorate-sort-undecorate," a pattern that involves
building a list of tuples, sorting, and extracting part of the result.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**data structure:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A collection of related values, often organized in lists, dictionaries,
tuples, etc.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**shape (of a data structure):**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A summary of the type, size and composition of a data structure.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 3
Write a function called **`most_frequent`** that takes a string and
prints the letters in decreasing order of frequency. Find text samples
from several different languages and see how letter frequency varies
between languages. Compare your results with the tables at
**\'`wikipedia.org/wiki/Letter_frequencies`**\'.\'\'
### Exercise 4
*More anagrams!*
- \'\'Write a program
that reads a word list from a file (see Section **\'9.1**\') and prints
all the sets of words that are anagrams.Here is an example of what the
output might look like:\'\'
``` python
''['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled']
['retainers', 'ternaries']
['generating', 'greatening']
['resmelts', 'smelters', 'termless']
''
```
*Hint: you might want to build a dictionary that maps from a set of
letters to a list of words that can be spelled with those letters. The
question is, how can you represent the set of letters in a way that can
be used as a key?*
- \'\'Modify the previous program so that it prints the largest set
of anagrams first, followed by the second largest set, and so on. \'\'
- \'\'In Scrabble a "bingo" is when you play all seven tiles in
your rack, along with a letter on the board, to form an eight-letter
word. What set of 8 letters forms the most possible bingos? Hint: there
are seven.\'\'
- \'\'\'\'Two words form a "metathesis pair" if you can transform one
into the other by swapping two letters**\'^**\'3**\'^**\'; for example,
"converse" and "conserve." Write a program that finds all of the
metathesis pairs in the dictionary. Hint: don't test all pairs of words,
and don't test all possible swaps.**\'**\'You can download a solution
from \'\'***\'`thinkpython.com/code/anagram_sets.py`*****.**\'
### Exercise 5
*Here's another Car Talk Puzzler*^*4*^*:*
> *What is the longest English word, that remains a valid English word,
> as you remove its letters one at a time?* *Now, letters can be removed
> from either end, or the middle, but you can't rearrange any of the
> letters. Every time you drop a letter, you wind up with another
> English word. If you do that, you're eventually going to wind up with
> one letter and that too is going to be an English word---one that's
> found in the dictionary. I want to know what's the longest word and
> how many letters does it have?*
>
> *I'm going to give you a little modest example: Sprite. Ok? You start
> off with sprite, you take a letter off, one from the interior of the
> word, take the r away, and we're left with the word spite, then we
> take the e off the end, we're left with spit, we take the s off, we're
> left with pit, it, and I.*
*Write a program to find all words that can be reduced in this way, and
then find the longest one.*
*This exercise is a little more challenging than most, so here are some
suggestions:*
- \'\'You might want to write a function that takes a word and
computes a list of all the words that can be formed by removing one
letter. These are the "children" of the word. \'\'
- \'\'Recursively, a word is reducible if any of its children
are reducible. As a base case, you can consider the empty string
reducible.\'\'
- \'\'The wordlist I provided, **\'`words.txt`**\', doesn't
contain single letter words. So you might want to add "I", "a", and the
empty string.\'\'
- \'\'To improve the performance of your program, you might want
to memoize the words that are known to be reducible.\'\'
*You can see my solution at
**\'`thinkpython.com/code/reducible.py`**\'.*
```{=html}
</DIV>
```
```{=html}
<HR CLASS="footnoterule">
```
```{=html}
<DL CLASS="thefootnotes">
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
1
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
In Python 3.0, `zip` returns an iterator of tuples, but for most
purposes, an iterator behaves like a list.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
2
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
This behavior is slightly different in Python 3.0.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
3
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
This exercise is inspired by an example at `puzzlers.org`.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
4
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
`www.cartalk.com/content/puzzler/transcripts/200651`
```{=html}
</DD>
```
```{=html}
</DL>
```
|
# Think Python/Case study: data structure selection
## Word frequency analysis
As usual, you should at least attempt the following exercises before you
read my solutions.
### Exercise 1
Write a program that reads a file, breaks each line into words, strips
whitespace and punctuation from the words, and converts them to
lowercase.
*Hint: The **\'`string`**\' module provides strings named
**\'`whitespace`**\', which contains space, tab, newline, etc., and
**\'`punctuation`**\' which contains the punctuation characters. Let's
see if we can make Python swear:*
``` python
>>> import string
>>> print string.punctuation
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
```
*Also, you might consider using the string methods **\'`strip`**\',
**\'`replace`**\' and **\'`translate`**\'.*
### Exercise 2
*Go to Project Gutenberg (**\'`gutenberg.org`**\') and download your
favorite out-of-copyright book in plain text format.*
*Modify your program from the previous exercise to read the book you
downloaded, skip over the header information at the beginning of the
file, and process the rest of the words as before.*
*Then modify the program to count the total number of words in the book,
and the number of times each word is used.*
*Print the number of different words used in the book. Compare different
books by different authors, written in different eras. Which author uses
the most extensive vocabulary?*
### Exercise 3
Modify the program from the previous exercise to print the 20 most
frequently-used words in the book.
### Exercise 4
Modify the previous program to read a word list (see
Section **\'9.1**\') and then print all the words in the book that are
not in the word list. How many of them are typos? How many of them are
common words that *should* be in the word list, and how many of them are
really obscure?
## Random numbers
Given the same inputs, most computer programs generate the same outputs
every time, so they are said to be **deterministic**. Determinism is
usually a good thing, since we expect the same calculation to yield the
same result. For some applications, though, we want the computer to be
unpredictable. Games are an obvious example, but there are more.
Making a program truly nondeterministic turns out to be not so easy, but
there are ways to make it at least seem nondeterministic. One of them is
to use algorithms that generate **pseudorandom** numbers. Pseudorandom
numbers are not truly random because they are generated by a
deterministic computation, but just by looking at the numbers it is all
but impossible to distinguish them from random.
The `random` module provides functions that generate pseudorandom
numbers (which I will simply call "random" from here on).
The function `random` returns a random float between 0.0 and 1.0
(including 0.0 but not 1.0). Each time you call `random`, you get the
next number in a long series. To see a sample, run this loop:
``` python
import random
for i in range(10):
x = random.random()
print x
```
The function `randint` takes parameters `low` and `high` and returns an
integer between `low` and `high` (including both).
``` python
>>> random.randint(5, 10)
5
>>> random.randint(5, 10)
9
```
To choose an element from a sequence at random, you can use `choice`:
``` python
>>> t = [1, 2, 3]
>>> random.choice(t)
2
>>> random.choice(t)
3
```
The `random` module also provides functions to generate random values
from continuous distributions including Gaussian, exponential, gamma,
and a few more.
### Exercise 5
*Write a function named`choose_from_hist`that takes a histogram as
defined in Section **\'11.1**\' and returns a random value from the
histogram, chosen with probability in proportion to frequency. For
example, for this histogram:*
``` python
''>>> t = ['a', 'a', 'b']
>>> h = histogram(t)
>>> print h
{'a': 2, 'b': 1}
''
```
*your function should **\'`’a’`**\' with probability **\'2/3**\'
and***`b`**\'\' with probability **\'1/3**\'.
## Word histogram
Here is a program that reads a file and builds a histogram of the words
in the file:
``` python
import string
def process_file(filename):
h = dict()
fp = open(filename)
for line in fp:
process_line(line, h)
return h
def process_line(line, h):
line = line.replace('-', ' ')
for word in line.split():
word = word.strip(string.punctuation + string.whitespace)
word = word.lower()
h[word] = h.get(word, 0) + 1
hist = process_file('emma.txt')
```
This program reads `emma.txt`, which contains the text of *Emma* by Jane
Austen.
`process_file` loops through the lines of the file, passing them one at
a time to `process_line`. The histogram `h` is being used as an
accumulator.
`process_line` uses the string method `replace` to replace hyphens with
spaces before using `split` to break the line into a list of strings. It
traverses the list of words and uses `strip` and `lower` to remove
punctuation and convert to lower case. (It is a shorthand to say that
strings are "converted;" remember that string are immutable, so methods
like `strip` and `lower` return new strings.)
Finally, `process_line` updates the histogram by creating a new item or
incrementing an existing one.
To count the total number of words in the file, we can add up the
frequencies in the histogram:
``` python
def total_words(h):
return sum(h.values())
```
The number of different words is just the number of items in the
dictionary:
``` python
def different_words(h):
return len(h)
```
Here is some code to print the results:
``` python
print 'Total number of words:', total_words(hist)
print 'Number of different words:', different_words(hist)
```
And the results:
``` python
Total number of words: 161073
Number of different words: 7212
```
## Most common words
To find the most common words, we can apply the DSU pattern;
`most_common` takes a histogram and returns a list of word-frequency
tuples, sorted in reverse order by frequency:
``` python
def most_common(h):
t = []
for key, value in h.items():
t.append((value, key))
t.sort(reverse=True)
return t
```
Here is a loop that prints the ten most common words:
``` python
t = most_common(hist)
print 'The most common words are:'
for freq, word in t[0:10]:
print word, '\t', freq
```
And here are the results from *Emma*:
``` python
The most common words are:
to 5242
the 5204
and 4897
of 4293
i 3191
a 3130
it 2529
her 2483
was 2400
she 2364
```
## Optional parameters
We have seen built-in functions and methods that take a variable number
of arguments. It is possible to write user-defined functions with
optional arguments, too. For example, here is a function that prints the
most common words in a histogram
``` python
def print_most_common(hist, num=10)
t = most_common(hist)
print 'The most common words are:'
for freq, word in t[0:num]:
print word, '\t', freq
```
The first parameter is required; the second is optional. The **default
value** of `num` is 10.
If you only provide one argument:
``` python
print_most_common(hist)
```
`num` gets the default value. If you provide two arguments:
``` python
print_most_common(hist, 20)
```
`num` gets the value of the argument instead. In other words, the
optional argument **overrides** the default value.
If a function has both required and optional parameters, all the
required parameters have to come first, followed by the optional ones.
## Dictionary subtraction
Finding the words from the book that are not in the word list from
`words.txt` is a problem you might recognize as set subtraction; that
is, we want to find all the words from one set (the words in the book)
that are not in another set (the words in the list).
`subtract` takes dictionaries `d1` and `d2` and returns a new dictionary
that contains all the keys from `d1` that are not in `d2`. Since we
don't really care about the values, we set them all to None.
``` python
def subtract(d1, d2):
res = dict()
for key in d1:
if key not in d2:
res[key] = None
return res
```
To find the words in the book that are not in `words.txt`, we can use
`process_file` to build a histogram for `words.txt`, and then subtract:
``` python
words = process_file('words.txt')
diff = subtract(hist, words)
print "The words in the book that aren't in the word list are:"
for word in diff.keys():
print word,
```
Here are some of the results from *Emma*:
``` python
The words in the book that aren't in the word list are:
rencontre jane's blanche woodhouses disingenuousness
friend's venice apartment ...
```
Some of these words are names and possessives. Others, like "rencontre,"
are no longer in common use. But a few are common words that should
really be in the list!
### Exercise 6
\'\'Python provides a data structure called **\'`set`**\' that provides
many common set operations. Read the documentation at
**\'`docs.python.org/lib/types-set.html`**\' and write a program that
uses set subtraction to find words in the book that are not in the word
list.
## Random words
To choose a random word from the histogram, the simplest algorithm is to
build a list with multiple copies of each word, according to the
observed frequency, and then choose from the list:
``` python
def random_word(h):
t = []
for word, freq in h.items():
t.extend([word] * freq)
return random.choice(t)
```
The expression `[word] * freq` creates a list with `freq` copies of the
string `word`. The `extend` method is similar to `append` except that
the argument is a sequence.
### Exercise 7
*This algorithm works, but it is not very efficient; each time you
choose a random word, it rebuilds the list, which is as big as the
original book. An obvious improvement is to build the list once and then
make multiple selections, but the list is still big.*
*An alternative is:*
- *Use **\'`keys`**\' to get a list of the words in the book.*
- \'\'Build a list that contains the cumulative sum of the word
frequencies (see Exercise **\'10.1**\'). The last item in this list is
the total number of words in the book, ***\'n***\'.\'\'
- *Choose a random number from 1 to***\'n**\'\'\'. Use a bisection
search
(See Exercise **\'10.8**\') to find the index where the random number
would be inserted in the cumulative sum.\'\'
- *Use the index to find the corresponding word in the word list.*
\'\'Write a program that uses this algorithm to choose a random word
from the book.
## Markov analysis
If you choose words from the book at random, you can get a sense of the
vocabulary, you probably won't get a sentence:
``` python
this the small regard harriet which knightley's it most things
```
A series of random words seldom makes sense because there is no
relationship between successive words. For example, in a real sentence
you would expect an article like "the" to be followed by an adjective or
a noun, and probably not a verb or adverb.
One way to measure these kinds of relationships is Markov analysis,
which characterizes, for a given sequence of words, the probability of
the word that comes next. For example, the song *Eric, the Half a Bee*
begins:
> Half a bee, philosophically,\
> Must, ipso facto, half not be.\
> But half the bee has got to be\
> Vis a vis, its entity. D'you see?\
> \
> But can a bee be said to be\
> Or not to be an entire bee\
> When half the bee is not a bee\
> Due to some ancient injury?\
In this text, the phrase "half the" is always followed by the word
"bee," but the phrase "the bee" might be followed by either "has" or
"is".
The result of Markov analysis is a mapping from each prefix (like "half
the" and "the bee") to all possible suffixes (like "has" and "is").
Given this mapping, you can generate a random text by starting with any
prefix and choosing at random from the possible suffixes. Next, you can
combine the end of the prefix and the new suffix to form the next
prefix, and repeat.
For example, if you start with the prefix "Half a," then the next word
has to be "bee," because the prefix only appears once in the text. The
next prefix is "a bee," so the next suffix might be "philosophically,"
"be" or "due."
In this example the length of the prefix is always two, but you can do
Markov analysis with any prefix length. The length of the prefix is
called the "order" of the analysis.
### Exercise 8
Markov analysis:\'\'
- *Write a program to read a text from a file and perform Markov
analysis. The result should be a dictionary that maps from prefixes
to a collection of possible suffixes. The collection might be a
list, tuple, or dictionary; it is up to you to make an appropriate
choice. You can test your program with prefix length two, but you
should write the program in a way that makes it easy to try other
lengths.*
- *Add a function to the previous program to generate random text
based on the Markov analysis. Here is an example from*Emma\'\' with
prefix length 2:
> He was very clever, be it sweetness or be angry, ashamed or only
> amused, at such a stroke. She had never thought of Hannah till you
> were never meant for me?\" \"I cannot make speeches, Emma:\" he soon
> cut it all himself.
\'\'For this example, I left the punctuation attached to the words. The
result is almost syntactically correct, but not quite. Semantically, it
almost makes sense, but not quite.
- *What happens if you increase the prefix length? Does the random
text make more sense?*
- *Once your program is working, you might want to try a mash-up: if
you analyze text from two or more books, the random text you
generate will blend the vocabulary and phrases from the sources in
interesting ways.*
## Data structures
Using Markov analysis to generate random text is fun, but there is also
a point to this exercise: data structure selection. In your solution to
the previous exercises, you had to choose:
- How to represent the prefixes.
- How to represent the collection of possible suffixes.
- How to represent the mapping from each prefix to the collection of
possible suffixes.
Ok, the last one is the easy; the only mapping type we have seen is a
dictionary, so it is the natural choice.
For the prefixes, the most obvious options are string, list of strings,
or tuple of strings. For the suffixes, one option is a list; another is
a histogram (dictionary).
How should you choose? The first step is to think about the operations
you will need to implement for each data structure. For the prefixes, we
need to be able to remove words from the beginning and add to the end.
For example, if the current prefix is "Half a," and the next word is
"bee," you need to be able to form the next prefix, "a bee."
Your first choice might be a list, since it is easy to add and remove
elements, but we also need to be able to use the prefixes as keys in a
dictionary, so that rules out lists. With tuples, you can't append or
remove, but you can use the addition operator to form a new tuple:
``` python
def shift(prefix, word):
return prefix[1:] + (word,)
```
`shift` takes a tuple of words, `prefix`, and a string, `word`, and
forms a new tuple that has all the words in `prefix` except the first,
and `word` added to the end.
For the collection of suffixes, the operations we need to perform
include adding a new suffix (or increasing the frequency of an existing
one), and choosing a random suffix.
Adding a new suffix is equally easy for the list implementation or the
histogram. Choosing a random element from a list is easy; choosing from
a histogram is harder to do efficiently (see Exercise 13.7).
So far we have been talking mostly about ease of implementation, but
there are other factors to consider in choosing data structures. One is
run time. Sometimes there is a theoretical reason to expect one data
structure to be faster than other; for example, I mentioned that the
`in` operator is faster for dictionaries than for lists, at least when
the number of elements is large.
But often you don't know ahead of time which implementation will be
faster. One option is to implement both of them and see which is better.
This approach is called **benchmarking**. A practical alternative is to
choose the data structure that is easiest to implement, and then see if
it is fast enough for the intended application. If so, there is no need
to go on. If not, there are tools, like the `profile` module, that can
identify the places in a program that take the most time.
The other factor to consider is storage space. For example, using a
histogram for the collection of suffixes might take less space because
you only have to store each word once, no matter how many times it
appears in the text. In some cases, saving space can also make your
program run faster, and in the extreme, your program might not run at
all if you run out of memory. But for many applications, space is a
secondary consideration after run time.
One final thought: in this discussion, I have implied that we should use
one data structure for both analysis and generation. But since these are
separate phases, it would also be possible to use one structure for
analysis and then convert to another structure for generation. This
would be a net win if the time saved during generation exceeded the time
spent in conversion.
## Debugging
When you are debugging a program, and especially if you are working on a
hard bug, there are four things to try:
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**reading:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Examine your code, read it back to yourself, and check that it says what
you meant to say.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**running:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Experiment by making changes and running different versions. Often if
you display the right thing at the right place in the program, the
problem becomes obvious, but sometimes you have to spend some time to
build scaffolding.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**ruminating:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Take some time to think! What kind of error is it: syntax, runtime,
semantic? What information can you get from the error messages, or from
the output of the program? What kind of error could cause the problem
you're seeing? What did you change last, before the problem appeared?
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**retreating:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
At some point, the best thing to do is back off, undoing recent changes,
until you get back to a program that works and that you understand. Then
you can starting rebuilding.
```{=html}
</DD>
```
```{=html}
</DL>
```
Beginning programmers sometimes get stuck on one of these activities and
forget the others. Each activity comes with its own failure mode.
For example, reading your code might help if the problem is a
typographical error, but not if the problem is a conceptual
misunderstanding. If you don't understand what your program does, you
can read it 100 times and never see the error, because the error is in
your head.
Running experiments can help, especially if you run small, simple tests.
But if you run experiments without thinking or reading your code, you
might fall into a pattern I call "random walk programming," which is the
process of making random changes until the program does the right thing.
Needless to say, random walk programming can take a long time.
You have to take time to think. Debugging is like an experimental
science. You should have at least one hypothesis about what the problem
is. If there are two or more possibilities, try to think of a test that
would eliminate one of them.
Taking a break helps with the thinking. So does talking. If you explain
the problem to someone else (or even yourself), you will sometimes find
the answer before you finish asking the question.
But even the best debugging techniques will fail if there are too many
errors, or if the code you are trying to fix is too big and complicated.
Sometimes the best option is to retreat, simplifying the program until
you get to something that works and that you understand.
Beginning programmers are often reluctant to retreat because they can't
stand to delete a line of code (even if it's wrong). If it makes you
feel better, copy your program into another file before you start
stripping it down. Then you can paste the pieces back in a little bit at
a time.
Finding a hard bug requires reading, running, ruminating, and sometimes
retreating. If you get stuck on one of these activities, try the others.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**deterministic:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Pertaining to a program that does the same thing each time it runs,
given the same inputs.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**pseudorandom:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Pertaining to a sequence of numbers that appear to be random, but are
generated by a deterministic program.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**default value:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The value given to an optional parameter if no argument is provided.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**override:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To replace a default value with an argument.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**benchmarking:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The process of choosing between data structures by implementing
alternatives and testing them on a sample of the possible inputs.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 9
*The "rank" of a word is its position in a list of words sorted by
frequency: the most common word has rank 1, the second most common has
rank 2, etc.*
*Zipf's law describes a relationship between the ranks and frequencies
of words in natural languages*^*1*^*. Specifically, it predicts that the
frequency,***\'f, of the word with rankr***\' is:*
```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
**\'f* = *c* *r**\'`<SUP>`{=html}*−*s\'*\'`</SUP>`{=html}* \'\'
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
*where***\'sandc***\' are parameters that depend on the language and the
text. If you take the logarithm of both sides of this equation, you
get:*
```{=html}
<TABLE CLASS="display dcenter">
```
```{=html}
<TR VALIGN="middle">
```
```{=html}
<TD CLASS="dcell">
```
*log*\'*\'f* = **\'log***\'c* − *s* **\'log***\'r* \'\'
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
*So if you plot **\'logfversus**\'log***\'r, you should get a straight
line with slope**\'−*s***\' and intercept**\'log***\'c***\'.\'\'
*Write a program that reads a text from a file, counts word frequencies,
and prints one line for each word, in descending order of frequency,
with **\'logfand**\'log***\'r. Use the graphing program of your choice
to plot the results and check whether they form a straight line. Can you
estimate the value of***s\'?*
## Notes
```{=html}
<DL CLASS="thefootnotes">
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
1
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
See `wikipedia.org/wiki/Zipf's_law`
```{=html}
</DD>
```
```{=html}
</DL>
```
|
# Think Python/Files
## Persistence
Most of the programs we have seen so far are transient in the sense that
they run for a short time and produce some output, but when they end,
their data disappears. If you run the program again, it starts with a
clean slate.
Other programs are **persistent**: they run for a long time (or all the
time); they keep at least some of their data in permanent storage (a
hard drive, for example); and if they shut down and restart, they pick
up where they left off.
Examples of persistent programs are operating systems, which run pretty
much whenever a computer is on, and web servers, which run all the time,
waiting for requests to come in on the network.
One of the simplest ways for programs to maintain their data is by
reading and writing text files. We have already seen programs that read
text files; in this chapters we will see programs that write them.
An alternative is to store the state of the program in a database. In
this chapter I will present a simple database and a module, `pickle`,
that makes it easy to store program data.
## Reading and writing
A text file is a sequence of characters stored on a permanent medium
like a hard drive, flash memory, or CD-ROM. We saw how to open and read
a file in Section 9.1.
To write a file, you have to open it with mode `'w'` as a second
parameter:
``` python
>>> fout = open('output.txt', 'w')
>>> print fout
<open file 'output.txt', mode 'w' at 0xb7eb2410>
```
If the file already exists, opening it in write mode clears out the old
data and starts fresh, so be careful! If the file doesn't exist, a new
one is created.
The `write` method puts data into the file.
``` python
>>> line1 = "This here's the wattle,\n"
>>> fout.write(line1)
```
Again, the file object keeps track of where it is, so if you call
`write` again, it adds the new data to the end.
``` python
>>> line2 = "the emblem of our land.\n"
>>> fout.write(line2)
```
When you are done writing, you have to close the file.
``` python
>>> fout.close()
```
## Format operator
The argument of `write` has to be a string, so if we want to put other
values in a file, we have to convert them to strings. The easiest way to
do that is with `str`:
``` python
>>> x = 52
>>> f.write(str(x))
```
An alternative is to use the **format operator**, `%`. When applied to
integers, `%` is the modulus operator. But when the first operand is a
string, `%` is the format operator.
The first operand is the **format string**, and the second operand is a
tuple of expressions. The result is a string that contains the values of
the expressions, formatted according to the format string.
As an example, the **format sequence** `'%d'` means that the first
expression in the tuple should be formatted as an integer (`d` stands
for "decimal"):
``` python
>>> camels = 42
>>> '%d' % camels
'42'
```
The result is the string `'42'`, which is not to be confused with the
integer value `42`.
A format sequence can appear anywhere in the format string, so you can
embed a value in a sentence:
``` python
>>> camels = 42
>>> 'I have spotted %d camels.' % camels
'I have spotted 42 camels.'
```
The format sequence `'%g'` formats the next element in the tuple as a
floating-point number (don't ask why), and `'%s'` formats the next item
as a string:
``` python
>>> 'In %d years I have spotted %g %s.' % (3, 0.1, 'camels')
'In 3 years I have spotted 0.1 camels.'
```
The number of elements in the tuple has to match the number of format
sequences in the string. Also, the types of the elements have to match
the format sequences:
``` python
>>> '%d %d %d' % (1, 2)
TypeError: not enough arguments for format string
>>> '%d' % 'dollars'
TypeError: illegal argument type for built-in operation
```
In the first example, there aren't enough elements; in the second, the
element is the wrong type.
The format operator is powerful but difficult to use. You can read more
about it at `docs.python.org/lib/typesseq-strings.html`.
## Filenames and paths
Files are organized into **directories** (also called "folders"). Every
running program has a "current directory," which is the default
directory for most operations. For example, when you open a file for
reading, Python looks for it in the current directory.
The `os` module provides functions for working with files and
directories ("os" stands for "operating system"). `os.getcwd` returns
the name of the current directory:
``` python
>>> import os
>>> cwd = os.getcwd()
>>> print cwd
/home/dinsdale
```
`cwd` stands for "current working directory." The result in this example
is `/home/dinsdale`, which is the home directory of a user named
`dinsdale`.
A string like `cwd` that identifies a file is called a **path**. A
**relative path** starts from the current directory; an **absolute
path** starts from the topmost directory in the file system.
The paths we have seen so far are simple filenames, so they are relative
to the current directory. To find the absolute path to a file, you can
use `os.path.abspath`:
``` python
>>> os.path.abspath('memo.txt')
'/home/dinsdale/memo.txt'
```
`os.path.exists` checks whether a file or directory exists:
``` python
>>> os.path.exists('memo.txt')
True
```
If it exists, `os.path.isdir` checks whether it's a directory:
``` python
>>> os.path.isdir('memo.txt')
False
>>> os.path.isdir('music')
True
```
Similarly, `os.path.isfile` checks whether it's a file.
`os.listdir` returns a list of the files (and other directories) in the
given directory:
``` python
>>> os.listdir(cwd)
['music', 'photos', 'memo.txt']
```
To demonstrate these functions, the following example "walks" through a
directory, prints the names of all the files, and calls itself
recursively on all the directories.
``` python
def walk(dir):
for name in os.listdir(dir):
path = os.path.join(dir, name)
if os.path.isfile(path):
print path
else:
walk(path)
```
`os.path.join` takes a directory and a file name and joins them into a
complete path.
### Exercise 1
Modify **\'`walk`**\' so that instead of printing the names of the
files, it returns a list of names. \'\'
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 2** \'\' The **\'`os`**\' module provides a function called
**\'`walk`**\' that is similar to this one but more versatile. Read the
documentation and use it to print the names of the files in a given
directory and its subdirectories.
## Catching exceptions
A lot of things can go wrong when you try to read and write files. If
you try to open a file that doesn't exist, you get an `IOError`:
``` python
>>> fin = open('bad_file')
IOError: [Errno 2] No such file or directory: 'bad_file'
```
If you don't have permission to access a file:
``` python
>>> fout = open('/etc/passwd', 'w')
IOError: [Errno 13] Permission denied: '/etc/passwd'
```
And if you try to open a directory for reading, you get
``` python
>>> fin = open('/home')
IOError: [Errno 21] Is a directory
```
To avoid these errors, you could use functions like `os.path.exists` and
`os.path.isfile`, but it would take a lot of time and code to check all
the possibilities (if "`Errno 21`" is any indication, there are at least
21 things that can go wrong).
It is better to go ahead and try, and deal with problems if they happen,
which is exactly what the `try` statement does. The syntax is similar to
an `if` statement:
``` python
try:
fin = open('bad_file')
for line in fin:
print line
fin.close()
except:
print 'Something went wrong.'
```
Python starts by executing the `try` clause. If all goes well, it skips
the `except` clause and proceeds. If an exception occurs, it jumps out
of the `try` clause and executes the `except` clause.
Handling an exception with a `try` statement is called **catching** an
exception. In this example, the `except` clause prints an error message
that is not very helpful. In general, catching an exception gives you a
chance to fix the problem, or try again, or at least end the program
gracefully.
## Databases
A **database** is a file that is organized for storing data. Most
databases are organized like a dictionary in the sense that they map
from keys to values. The biggest difference is that the database is on
disk (or other permanent storage), so it persists after the program
ends.
The module `anydbm` provides an interface for creating and updating
database files. As an example, I'll create a database that contains
captions for image files.
Opening a database is similar to opening other files:
``` python
>>> import anydbm
>>> db = anydbm.open('captions.db', 'c')
```
The mode `'c'` means that the database should be created if it doesn't
already exist. The result is a database object that can be used (for
most operations) like a dictionary. If you create a new item, `anydbm`
updates the database file.
``` python
>>> db['cleese.png'] = 'Photo of John Cleese.'
```
When you access one of the items, `anydbm` reads the file:
``` python
>>> print db['cleese.png']
Photo of John Cleese.
```
If you make another assignment to an existing key, `anydbm` replaces the
old value:
``` python
>>> db['cleese.png'] = 'Photo of John Cleese doing a silly walk.'
>>> print db['cleese.png']
Photo of John Cleese doing a silly walk.
```
Many dictionary methods, like `keys` and `items`, also work with
database objects. So does iteration with a `for` statement.
``` python
for key in db:
print key
```
As with other files, you should close the database when you are done:
``` python
>>> db.close()
```
## Pickling
A limitation of `anydbm` is that the keys and values have to be strings.
If you try to use any other type, you get an error.
The `pickle` module can help. It translates almost any type of object
into a string suitable for storage in a database, and then translates
strings back into objects.
`pickle.dumps` takes an object as a parameter and returns a string
representation (`dumps` is short for "dump string"):
``` python
>>> import pickle
>>> t = [1, 2, 3]
>>> pickle.dumps(t)
'(lp0\nI1\naI2\naI3\na.'
```
The format isn't obvious to human readers; it is meant to be easy for
`pickle` to interpret. `pickle.loads` ("load string") reconstitutes the
object:
``` python
>>> t1 = [1, 2, 3]
>>> s = pickle.dumps(t1)
>>> t2 = pickle.loads(s)
>>> print t2
[1, 2, 3]
```
Although the new object has the same value as the old, it is not (in
general) the same object:
``` python
>>> t == t2
True
>>> t is t2
False
```
In other words, pickling and then unpickling has the same effect as
copying the object.
You can use `pickle` to store non-strings in a database. In fact, this
combination is so common that it has been encapsulated in a module
called `shelve`.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 3**
*If you did Exercise **\'12.4**\', modify your solution so that it
creates a database that maps from each word in the list to a list of
words that use the same set of letters.*
*Write a different program that opens the database and prints the
contents in a human-readable format.*
```{=html}
</DIV>
```
## Pipes
Most operating systems provide a command-line interface, also known as a
**shell**. Shells usually provide commands to navigate the file system
and launch applications. For example, in Unix, you can change
directories with `cd`, display the contents of a directory with `ls`,
and launch a web browser by typing (for example) `Firefox`.
Any program that you can launch from the shell can also be launched from
Python using a **pipe**. A pipe is an object that represents a running
process.
For example, the Unix command `ls -l` normally displays the contents of
the current directory (in long format). You can launch `ls` with
`os.popen`:
``` python
>>> cmd = 'ls -l'
>>> fp = os.popen(cmd)
```
The argument is a string that contains a shell command. The return value
is a file pointer that behaves just like an open file. You can read the
output from the `ls` process one line at a time with `readline` or get
the whole thing at once with `read`:
``` python
>>> res = fp.read()
```
When you are done, you close the pipe like a file:
``` python
>>> stat = fp.close()
>>> print stat
None
```
The return value is the final status of the `ls` process; `None` means
that it ended normally (with no errors).
A common use of pipes is to read a compressed file incrementally; that
is, without uncompressing the whole thing at once. The following
function takes the name of a compressed file as a parameter and returns
a pipe that uses `gzip` to decompress the contents:
``` python
def open_gzip(filename):
cmd = 'gunzip -c ' + filename
fp = os.popen(cmd)
return fp
```
If you read lines from `fp` one at a time, you never have to store the
uncompressed file in memory or on disk.
## Writing modules
Any file that contains Python code can be imported as a module. For
example, suppose you have a file named `wc.py` with the following code:
``` python
def linecount(filename):
count = 0
for line in open(filename):
count += 1
return count
print linecount('wc.py')
```
If you run this program, it reads itself and prints the number of lines
in the file, which is 7. You can also import it like this:
``` python
>>> import wc
7
```
Now you have a module object `wc`:
``` python
>>> print wc
<module 'wc' from 'wc.py'>
```
That provides a function called `linecount`:
``` python
>>> wc.linecount('wc.py')
7
```
So that's how you write modules in Python.
The only problem with this example is that when you import the module it
executes the test code at the bottom. Normally when you import a module,
it defines new functions but it doesn't execute them.
Programs that will be imported as modules often use the following idiom:
``` python
if __name__ == '__main__':
print linecount('wc.py')
```
`__name__` is a built-in variable that is set when the program starts.
If the program is running as a script, `__name__` has the value
`__main__`; in that case, the test code is executed. Otherwise, if the
module is being imported, the test code is skipped.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 4** *Type this example into a file named **\'`wc.py`**\' and
run it as a script. Then run the Python interpreter and
**\'`import wc`**\'. What is the value of`__name__`when the module is
being imported?* *Warning: If you import a module that has already been
imported, Python does nothing. It does not re-read the file, even if it
has changed.*
*If you want to reload a module, you can use the built-in function
**\'`reload`**\', but it can be tricky, so the safest thing to do is
restart the interpreter and then import the module again.*
```{=html}
</DIV>
```
## Debugging
When you are reading and writing files, you might run into problems with
whitespace. These errors can be hard to debug because spaces, tabs and
newlines are normally invisible:
``` python
>>> s = '1 2\t 3\n 4'
>>> print s
1 2 3
4
```
The built-in function `repr` can help. It takes any object as an
argument and returns a string representation of the object. For strings,
it represents whitespace characters with backslash sequences:
``` python
>>> print repr(s)
'1 2\t 3\n 4'
```
This can be helpful for debugging.
One other problem you might run into is that different systems use
different characters to indicate the end of a line. Some systems use a
newline, represented `\n`. Others use a return character, represented
`\r`. Some use both. If you move files between different systems, these
inconsistencies might cause problems.
For most systems, there are applications to convert from one format to
another. You can find them (and read more about this issue) at
`wikipedia.org/wiki/Newline`. Or, of course, you could write one
yourself.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**persistent:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Pertaining to a program that runs indefinitely and keeps at least some
of its data in permanent storage.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**format operator:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An operator, `%`, that takes a format string and a tuple and generates a
string that includes the elements of the tuple formatted as specified by
the format string.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**format string:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A string, used with the format operator, that contains format sequences.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**format sequence:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A sequence of characters in a format string, like `%d`, that specifies
how a value should be formatted.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**text file:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A sequence of characters stored in permanent storage like a hard drive.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**directory:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A named collection of files, also called a folder.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**path:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A string that identifies a file.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**relative path:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A path that starts from the current directory.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**absolute path:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A path that starts from the topmost directory in the file system.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**catch:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To prevent an exception from terminating a program using the `try` and
`except` statements.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**database:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A file whose contents are organized like a dictionary with keys that
correspond to values.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
```{=html}
<DIV CLASS="theorem">
```
**Exercise 5** The **\'`urllib`**\' module provides methods for
manipulating URLs and downloading information from the web. The
following example downloads and prints a secret message from
**\'`thinkpython.com`**\':\'\'
``` python
import urllib
conn = urllib.urlopen('http://thinkpython.com/secret.html')
for line in conn.fp:
print line.strip()
```
*Run this code and follow the instructions you see there.*
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 6**
*In a large collection of MP3 files, there may be more than one copy of
the same song, stored in different directories or with different file
names. The goal of this exercise is to search for these duplicates.*
- \'\'Write a program that searches a directory and all of its
subdirectories, recursively, and returns a list of complete paths for
all files with a given suffix (like **\'`.mp3`**\'). Hint:
**\'`os.path`**\' provides several useful functions for manipulating
file and path names.\'\'
- \'\'To recognize duplicates, you can use a hash function that
reads the file and generates a short summary of the contents. For
example, MD5 (Message-Digest algorithm 5) takes an arbitrarily-long
"message" and returns a 128-bit "checksum." The probability is very
small that two files with different contents will return the same
checksum.You can read about MD5 at **\'`wikipedia.org/wiki/Md5`**\'. On
a Unix system you can use the program **\'`md5sum`**\' and a pipe to
compute checksums from Python.\'\'
```{=html}
</DIV>
```
```{=html}
<DIV CLASS="theorem">
```
**Exercise 7**
*The Internet Movie Database (IMDb) is an online collection of
information about movies. Their database is available in plain text
format, so it is reasonably easy to read from Python. For this exercise,
the files you need are **\'`actors.list.gz`**\' and
**\'`actresses.list.gz`**\'; you can download them from
**\'`www.imdb.com/interfaces#plain`**\'.*
*I have written a program that parses these files and splits them into
actor names, movie titles, etc. You can download it from
**\'`thinkpython.com/code/imdb.py`**\'.*
*If you run **\'`imdb.py`**\' as a script, it reads
**\'`actors.list.gz`**\' and prints one actor-movie pair per line. Or,
if you **\'`import imdb`**\' you can use the function`process_file`to,
well, process the file. The arguments are a filename, a function object
and an optional number of lines to process. Here is an example:*
``` python
''import imdb
def print_info(actor, date, title, role):
print actor, date, title, role
imdb.process_file('actors.list.gz', print_info)
''
```
*When you call`process_file`, it opens **\'`filename`**\', reads the
contents, and calls`print_info`once for each line in the
file.`print_info`takes an actor, date, movie title and role as arguments
and prints them.*
- \'\'Write a program that reads **\'`actors.list.gz`**\' and
**\'`actresses.list.gz`**\' and uses **\'`shelve`**\' to build a
database
that maps from each actor to a list of his or her films. \'\'
- \'\'Two actors are "costars" if they have been in at least one
movie together. Process the database you built in the previous step and
build a second database that maps from each actor to a list of his or
her costars. \'\'
- \'\'Write a program that can play the "Six Degrees of Kevin
Bacon," which you can read about at
**\'`wikipedia.org/wiki/Six_Degrees_of_Kevin_Bacon`**\'. This problem is
challenging because it requires you to find the shortest path in a
graph. You can read about shortest path algorithms at
**\'`wikipedia.org/wiki/Shortest_path_problem`**\'.\'\'
```{=html}
</DIV>
```
|
# Think Python/Classes and objects
## User-defined types
We have used many of Python's built-in types; now we are going to define
a new type. As an example, we will create a type called `Point` that
represents a point in two-dimensional space.
In mathematical notation, points are often written in parentheses with a
comma separating the coordinates. For example, (0, 0) represents the
origin, and (`<I>`{=html}x`</I>`{=html}, `<I>`{=html}y`</I>`{=html})
represents the point `<I>`{=html}x`</I>`{=html} units to the right and
`<I>`{=html}y`</I>`{=html} units up from the origin.
There are several ways we might represent points in Python:
- We could store the coordinates separately in two variables, `x` and
`y`.
- We could store the coordinates as elements in a list or tuple.
- We could create a new type to represent points as objects.
Creating a new type is (a little) more complicated than the other
options, but it has advantages that will be apparent soon.
A user-defined type is also called a **class**. A class definition looks
like this:
``` python
class Point(object):
"""represents a point in 2-D space"""
```
This header indicates that the new class is a `Point`, which is a kind
of `object`, which is a built-in type.
The body is a docstring that explains what the class is for. You can
define variables and functions inside a class definition, but we will
get back to that later.
Defining a class named `Point` creates a class object.
``` python
>>> print Point
<class '__main__.Point'>
```
Because `Point` is defined at the top level, its "full name" is
`__main__.Point`.
The class object is like a factory for creating objects. To create a
Point, you call `Point` as if it were a function.
``` python
>>> blank = Point()
>>> print blank
<__main__.Point instance at 0xb7e9d3ac>
```
The return value is a reference to a Point object, which we assign to
`blank`. Creating a new object is called **instantiation**, and the
object is an **instance** of the class.
When you print an instance, Python tells you what class it belongs to
and where it is stored in memory (the prefix `0x` means that the
following number is in hexadecimal).
## Attributes
You can assign values to an instance using dot notation:
``` python
>>> blank.x = 3.0
>>> blank.y = 4.0
```
This syntax is similar to the syntax for selecting a variable from a
module, such as `math.pi` or `string.whitespace`. In this case, though,
we are assigning values to named elements of an object. These elements
are called **attributes**.
As a noun, "AT-trib-ute" is pronounced with emphasis on the first
syllable, as opposed to "a-TRIB-ute," which is a verb.
The following diagram shows the result of these assignments. A state
diagram that shows an object and its attributes is called an **object
diagram**:

The variable `blank` refers to a Point object, which contains two
attributes. Each attribute refers to a floating-point number.
You can read the value of an attribute using the same syntax:
``` python
>>> print blank.y
4.0
>>> x = blank.x
>>> print x
3.0
```
The expression `blank.x` means, "Go to the object `blank` refers to and
get the value of `x`." In this case, we assign that value to a variable
named `x`. There is no conflict between the variable `x` and the
attribute `x`.
You can use dot notation as part of any expression. For example:
``` python
>>> print '(%g, %g)' % (blank.x, blank.y)
(3.0, 4.0)
>>> distance = math.sqrt(blank.x**2 + blank.y**2)
>>> print distance
5.0
```
You can pass an instance as an argument in the usual way. For example:
``` python
def print_point(p):
print '(%g, %g)' % (p.x, p.y)
```
`print_point` takes a point as an argument and displays it in
mathematical notation. To invoke it, you can pass `blank` as an
argument:
``` python
>>> print_point(blank)
(3.0, 4.0)
```
Inside the function, `p` is an alias for `blank`, so if the function
modifies `p`, `blank` changes.
### Exercise 1
Write a function called **\'`distance`**\' that it takes two Points as
arguments and returns the distance between them.
## Rectangles
Sometimes it is obvious what the attributes of an object should be, but
other times you have to make decisions. For example, imagine you are
designing a class to represent rectangles. What attributes would you use
to specify the location and size of a rectangle? You can ignore angle;
to keep things simple, assume that the rectangle is either vertical or
horizontal.
There are at least two possibilities:
- You could specify one corner of the rectangle (or the center), the
width, and the height.
- You could specify two opposing corners.
At this point it is hard to say whether either is better than the other,
so we'll implement the first one, just as an example.
Here is the class definition:
``` python
class Rectangle(object):
"""represent a rectangle.
attributes: width, height, corner.
"""
```
The docstring lists the attributes: `width` and `height` are numbers;
`corner` is a Point object that specifies the lower-left corner.
To represent a rectangle, you have to instantiate a Rectangle object and
assign values to the attributes:
``` python
box = Rectangle()
box.width = 100.0
box.height = 200.0
box.corner = Point()
box.corner.x = 0.0
box.corner.y = 0.0
```
The expression `box.corner.x` means, "Go to the object `box` refers to
and select the attribute named `corner`; then go to that object and
select the attribute named `x`."
The figure shows the state of this object:
 An object that is an attribute of another
object is **embedded**.
## Instances as return values
Functions can return instances. For example, `find_center` takes a
`Rectangle` as an argument and returns a `Point` that contains the
coordinates of the center of the `Rectangle`:
``` python
def find_center(box):
p = Point()
p.x = box.corner.x + box.width/2.0
p.y = box.corner.y + box.height/2.0
return p
```
Here is an example that passes `box` as an argument and assigns the
resulting Point to `center`:
``` python
>>> center = find_center(box)
>>> print_point(center)
(50.0, 100.0)
```
## Objects are mutable
You can change the state of an object by making an assignment to one of
its attributes. For example, to change the size of a rectangle without
changing its position, you can modify the values of `width` and
`height`:
``` python
box.width = box.width + 50
box.height = box.height + 100
```
You can also write functions that modify objects. For example,
`grow_rectangle` takes a Rectangle object and two numbers, `dwidth` and
`dheight`, and adds the numbers to the width and height of the
rectangle:
``` python
def grow_rectangle(rect, dwidth, dheight) :
rect.width += dwidth
rect.height += dheight
```
Here is an example that demonstrates the effect:
``` python
>>> print box.width
100.0
>>> print box.height
200.0
>>> grow_rectangle(box, 50, 100)
>>> print box.width
150.0
>>> print box.height
300.0
```
Inside the function, `rect` is an alias for `box`, so if the function
modifies `rect`, `box` changes.
### Exercise 2
Write a function named **`move_rectangle`** that takes a Rectangle and
two numbers named **\'`dx`**\' and **\'`dy`**\'. It should change the
location of the rectangle by adding **\'`dx`**\' to the **\'`x`**\'
coordinate of **\'`corner`**\' and adding **\'`dy`**\' to the
**\'`y`**\' coordinate of **\'`corner`**\'.
## Copying
Aliasing can make a program difficult to read because changes in one
place might have unexpected effects in another place. It is hard to keep
track of all the variables that might refer to a given object.
Copying an object is often an alternative to aliasing. The `copy` module
contains a function called `copy` that can duplicate any object:
``` python
>>> p1 = Point()
>>> p1.x = 3.0
>>> p1.y = 4.0
>>> import copy
>>> p2 = copy.copy(p1)
```
`p1` and `p2` contain the same data, but they are not the same Point.
``` python
>>> print_point(p1)
(3.0, 4.0)
>>> print_point(p2)
(3.0, 4.0)
>>> p1 is p2
False
>>> p1 == p2
False
```
The `is` operator indicates that `p1` and `p2` are not the same object,
which is what we expected. But you might have expected `==` to yield
`True` because these points contain the same data. In that case, you
will be disappointed to learn that for instances, the default behavior
of the `==` operator is the same as the `is` operator; it checks object
identity, not object equivalence. This behavior can be changed---we'll
see how later.
If you use `copy.copy` to duplicate a Rectangle, you will find that it
copies the Rectangle object but not the embedded Point.
``` python
>>> box2 = copy.copy(box)
>>> box2 is box
False
>>> box2.corner is box.corner
True
```
Here is what the object diagram looks like:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book024.png">`{=html}
```{=html}
</DIV>
```
This operation is called a **shallow copy** because it copies the object
and any references it contains, but not the embedded objects.
For most applications, this is not what you want. In this example,
invoking `grow_rectangle` on one of the Rectangles would not affect the
other, but invoking `move_rectangle` on either would affect both! This
behavior is confusing and error-prone.
Fortunately, the `copy` module contains a method named `deepcopy` that
copies not only the object but also the objects it refers to, and the
objects *they* refer to, and so on. You will not be surprised to learn
that this operation is called a **deep copy**.
``` python
>>> box3 = copy.deepcopy(box)
>>> box3 is box
False
>>> box3.corner is box.corner
False
```
`box3` and `box` are completely separate objects.
### Exercise 3
Write a version of **`move_rectangle`** that creates and returns a new
Rectangle instead of modifying the old one.
## Debugging
When you start working with objects, you are likely to encounter some
new exceptions. If you try to access an attribute that doesn't exist,
you get an `AttributeError`:
``` python
>>> p = Point()
>>> print p.z
AttributeError: Point instance has no attribute 'z'
```
If you are not sure what type an object is, you can ask:
``` python
>>> type(p)
<type '__main__.Point'>
```
If you are not sure whether an object has a particular attribute, you
can use the built-in function `hasattr`:
``` python
>>> hasattr(p, 'x')
True
>>> hasattr(p, 'z')
False
```
The first argument can be any object; the second argument is a *string*
that contains the name of the attribute.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**class:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A user-defined type. A class definition creates a new class object.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**class object:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An object that contains information about a user-defined type. The class
object can be used to create instances of the type.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**instance:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An object that belongs to a class.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**attribute:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
One of the named values associated with an object.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**embedded (object):**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An object that is stored as an attribute of another object.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**shallow copy:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To copy the contents of an object, including any references to embedded
objects; implemented by the `copy` function in the `copy` module.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**deep copy:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To copy the contents of an object as well as any embedded objects, and
any objects embedded in them, and so on; implemented by the `deepcopy`
function in the `copy` module.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**object diagram:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A diagram that shows objects, their attributes, and the values of the
attributes.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 4
*`World.py`**\', which is part of Swampy (see Chapter **\'4**\'),
contains a class definition for a user-defined type called**\'`World`.
If you run this code:*
``` python
''from World import *
world = World()
wait_for_user()
''
```
*A window should appear with a title bar and an empty square. In this
exercise we will use this window to draw Points, Rectangles and other
shapes. Add the following lines before`wait_for_user`and run the program
again*
``` python
''canvas = world.ca(width=500, height=500, background='white')
bbox = [[-150,-100], [150, 100]]
canvas.rectangle(bbox, outline='black', width=2, fill='green4')
''
```
*You should see a green rectangle with a black outline. The first line
creates a Canvas, which appears in the window as a white square. The
Canvas object provides methods like **\'`rectangle`**\' for drawing
various shapes.*
*`bbox`is a list of lists that represents the "bounding box" of the
rectangle. The first pair of coordinates is the lower-left corner of the
rectangle; the second pair is the upper-right corner.*
*You can draw a circle like this:*
``` python
''canvas.circle([-25,0], 70, outline=None, fill='red')
''
```
*The first parameter is the coordinate pair for the center of the
circle; the second parameter is the radius.*
*If you add this line to the program, the result should resemble the
national flag of Bangladesh (see
**\'`wikipedia.org/wiki/Gallery_of_sovereign-state_flags`**\').*
- *Write a function called`draw_rectangle`*\'\' that takes a
Canvas and a Rectangle as arguments and draws a representation of the
Rectangle on the Canvas.\'\'
- \'\'Add an attribute named **\'`color`**\' to your Rectangle objects
and
modify **`draw_rectangle`** so that it uses the color attribute as the
fill color.\'\'
- *Write a function called`draw_point`*\'\' that takes a
Canvas and a Point as arguments and draws a representation of the Point
on the Canvas.\'\'
- \'\'Define a new class called Circle with appropriate attributes and
instantiate a few Circle objects. Write a function called
**`draw_circle`** that draws circles on the canvas.\'\'
- *Write a program that draws the national flag of the Czech
Republic.*
Hint: you can draw a polygon like this:\'\'
``` python
''points = [[-150,-100], [150, 100], [150, -100]]
canvas.polygon(points, fill='blue')
''
```
*I have written a small program that lists the available colors; you can
download it from **\'`thinkpython.com/code/color_list.py`**\'.*
|
# Think Python/Classes and functions
## Time
As another example of a user-defined type, we\'ll define a class called
`Time` that records the time of day. The class definition looks like
this:
``` python
class Time(object):
"""represents the time of day.
attributes: hour, minute, second"""
```
We can create a new `Time` object and assign attributes for hours,
minutes, and seconds:
``` python
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
```
The state diagram for the `Time` object looks like this:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book025.png">`{=html}
```{=html}
</DIV>
```
### Exercise 1
Write a function called `print_time` that takes a Time object and prints
it in the form `hour:minute:second`.
Hint: the format sequence `%.2d` prints an integer using at least two
digits, including a leading zero if necessary.
### Exercise 2
Write a boolean function called `is_after` that takes two Time objects,
`t1` and `t2`, and returns `True` if `t1` follows `t2` chronologically
and `False` otherwise.
Challenge: don\'t use an `if` statement.
## Pure functions
In the next few sections, we'll write two functions that add time
values. They demonstrate two kinds of functions: pure functions and
modifiers. They also demonstrate a development plan I'll call
**prototype and patch**, which is a way of tackling a complex problem by
starting with a simple prototype and incrementally dealing with the
complications.
Here is a simple prototype of `add_time`:
``` python
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
return sum
```
The function creates a new `Time` object, initializes its attributes,
and returns a reference to the new object. This is called a **pure
function** because it does not modify any of the objects passed to it as
arguments and it has no effect, like displaying a value or getting user
input, other than returning a value.
To test this function, I'll create two Time objects: `start` contains
the start time of a movie, like *Monty Python and the Holy Grail*, and
`duration` contains the run time of the movie, which is one hour 35
minutes.
`add_time` figures out when the movie will be done.
``` python
>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 0
>>> duration = Time()
>>> duration.hour = 1
>>> duration.minute = 35
>>> duration.second = 0
>>> done = add_time(start, duration)
>>> print_time(done)
10:80:00
```
The result, `10:80:00` might not be what you were hoping for. The
problem is that this function does not deal with cases where the number
of seconds or minutes adds up to more than sixty. When that happens, we
have to "carry" the extra seconds into the minute column or the extra
minutes into the hour column.
Here's an improved version:
``` python
def add_time(t1, t2):
sum = Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
if sum.second >= 60:
sum.second -= 60
sum.minute += 1
if sum.minute >= 60:
sum.minute -= 60
sum.hour += 1
return sum
```
Although this function is correct, it is starting to get big. We will
see a shorter alternative later.
## Modifiers
Sometimes it is useful for a function to modify the objects it gets as
parameters. In that case, the changes are visible to the caller.
Functions that work this way are called **modifiers**.
`increment`, which adds a given number of seconds to a `Time` object,
can be written naturally as a modifier. Here is a rough draft:
``` python
def increment(time, seconds):
time.second += seconds
if time.second >= 60:
time.second -= 60
time.minute += 1
if time.minute >= 60:
time.minute -= 60
time.hour += 1
```
The first line performs the basic operation; the remainder deals with
the special cases we saw before.
Is this function correct? What happens if the parameter `seconds` is
much greater than sixty?
In that case, it is not enough to carry once; we have to keep doing it
until `time.second` is less than sixty. One solution is to replace the
`if` statements with `while` statements. That would make the function
correct, but not very efficient.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 3** *Write a correct version of **\'`increment`**\' that
doesn't contain any loops.*
```{=html}
</DIV>
```
Anything that can be done with modifiers can also be done with pure
functions. In fact, some programming languages only allow pure
functions. There is some evidence that programs that use pure functions
are faster to develop and less error-prone than programs that use
modifiers. But modifiers are convenient at times, and functional
programs tend to be less efficient.
In general, I recommend that you write pure functions whenever it is
reasonable and resort to modifiers only if there is a compelling
advantage. This approach might be called a **functional programming
style**.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 4** \'\' Write a "pure" version of **\'`increment`**\' that
creates and returns a new Time object rather than modifying the
parameter.
## Prototyping versus planning
The development plan I am demonstrating is called "prototype and patch."
For each function, I wrote a prototype that performed the basic
calculation and then tested it, patching errors along the way.
This approach can be effective, especially if you don't yet have a deep
understanding of the problem. But incremental corrections can generate
code that is unnecessarily complicated---since it deals with many
special cases---and unreliable---since it is hard to know if you have
found all the errors.
An alternative is **planned development**, in which high-level insight
into the problem can make the programming much easier. In this case, the
insight is that a Time object is really a three-digit number in base 60
(see `wikipedia.org/wiki/Sexagesimal`)! The `second` attribute is the
"ones column," the `minute` attribute is the "sixties column," and the
`hour` attribute is the "thirty-six hundreds column."
When we wrote `add_time` and `increment`, we were effectively doing
addition in base 60, which is why we had to carry from one column to the
next.
This observation suggests another approach to the whole problem---we can
convert Time objects to integers and take advantage of the fact that the
computer knows how to do integer arithmetic.
Here is a function that converts Times to integers:
``` python
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
```
And here is the function that converts integers to Times (recall that
`divmod` divides the first argument by the second and returns the
quotient and remainder as a tuple).
``` python
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
```
You might have to think a bit, and run some tests, to convince yourself
that these functions are correct. One way to test them is to check that
`time_to_int(int_to_time(x)) == x` for many values of `x`. This is an
example of a consistency check.
Once you are convinced they are correct, you can use them to rewrite
`add_time`:
``` python
def add_time(t1, t2):
seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)
```
This version is shorter than the original, and easier to verify.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 5** *Rewrite **\'`increment`**\'
using`time_to_int`and`int_to_time`.*
```{=html}
</DIV>
```
In some ways, converting from base 60 to base 10 and back is harder than
just dealing with times. Base conversion is more abstract; our intuition
for dealing with time values is better.
But if we have the insight to treat times as base 60 numbers and make
the investment of writing the conversion functions (`time_to_int` and
`int_to_time`), we get a program that is shorter, easier to read and
debug, and more reliable.
It is also easier to add features later. For example, imagine
subtracting two Times to find the duration between them. The naïve
approach would be to implement subtraction with borrowing. Using the
conversion functions would be easier and more likely to be correct.
Ironically, sometimes making a problem harder (or more general) makes it
easier (because there are fewer special cases and fewer opportunities
for error).
## Debugging
A Time object is well-formed if the values of `minutes` and `seconds`
are between 0 and 60 (including 0 but not 60) and if `hours` is
positive. `hours` and `minutes` should be integral values, but we might
allow `seconds` to have a fraction part.
These kind of requirements are called **invariants** because they should
always be true. To put it a different way, if they are not true, then
something has gone wrong.
Writing code to check your invariants can help you detect errors and
find their causes. For example, you might have a function like
`valid_time` that takes a Time object and returns `False` if it violates
an invariant:
``` python
def valid_time(time):
if time.hours < 0 or time.minutes < 0 or time.seconds < 0:
return False
if time.minutes >= 60 or time.seconds >= 60:
return False
return True
```
Then at the beginning of each function you could check the arguments to
make sure they are valid:
``` python
def add_time(t1, t2):
if not valid_time(t1) or not valid_time(t2):
raise ValueError, 'invalid Time object in add_time'
seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)
```
Or you could use an `assert` statement, which checks a given invariant
and raises an exception if it fails:
``` python
def add_time(t1, t2):
assert valid_time(t1) and valid_time(t2)
seconds = time_to_int(t1) + time_to_int(t2)
return int_to_time(seconds)
```
`assert` statements are useful because they distinguish code that deals
with normal conditions from code that checks for errors.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**prototype and patch:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A development plan that involves writing a rough draft of a program,
testing, and correcting errors as they are found.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**planned development:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A development plan that involves high-level insight into the problem and
more planning than incremental development or prototype development.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**pure function:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A function that does not modify any of the objects it receives as
arguments. Most pure functions are fruitful.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**modifier:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A function that changes one or more of the objects it receives as
arguments. Most modifiers are fruitless.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**functional programming style:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A style of program design in which the majority of functions are pure.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**invariant:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A condition that should always be true during the execution of a
program.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 6
Write a function called **`mul_time`** that takes a Time object and a
number and returns a new Time object that contains the product of the
original Time and the number.Then use **`mul_time`** to write a function
that takes a Time object that represents the finishing time in a race,
and a number that represents the distance, and returns a Time object
that represents the average pace (time per mile).\'\'
### Exercise 7
*Write a class definition for a Date object that has attributes
**\'`day`**\', **\'`month`**\' and **\'`year`**\'. Write a function
called`increment_date`that takes a Date object, **\'`date`**\' and an
integer, **\'`n`**\', and returns a new Date object that represents the
day **\'`n`**\' days after **\'`date`**\'. Hint: "Thirty days hath
September\..." Challenge: does your function deal with leap years
correctly? See`wikipedia.org/wiki/Leap_year`*
### Exercise 8
*The **\'`datetime`**\' module provides **\'`date`**\' and
**\'`time`**\' objects that are similar to the Date and Time objects in
this chapter, but they provide a rich set of methods and operators. Read
the documentation at **\'`docs.python.org/lib/datetime-date.html`**\'.*
- *Use the **\'`datetime`**\' module to write a program that gets the
current date and prints the day of the week.*
- *Write a program that takes a birthday as input and prints the
user's age and the number of days, hours, minutes and seconds until
their next birthday.*
|
# Think Python/Classes and methods
## Object-oriented features
Python is an **object-oriented programming language**, which means that
it provides features that support object-oriented programming.
It is not easy to define object-oriented programming, but we have
already seen some of its characteristics:
- Programs are made up of object definitions and function definitions,
and most of the computation is expressed in terms of operations on
objects.
```{=html}
<!-- -->
```
- Each object definition corresponds to some object or concept in the
real world, and the functions that operate on that object correspond
to the ways real-world objects interact.
For example, the `Time` class defined in Chapter 16 corresponds to the
way people record the time of day, and the functions we defined
correspond to the kinds of things people do with times. Similarly, the
`Point` and `Rectangle` classes correspond to the mathematical concepts
of a point and a rectangle.
So far, we have not taken advantage of the features Python provides to
support object-oriented programming. These features are not strictly
necessary; most of them provide alternative syntax for things we have
already done. But in many cases, the alternative is more concise and
more accurately conveys the structure of the program.
For example, in the `Time` program, there is no obvious connection
between the class definition and the function definitions that follow.
With some examination, it is apparent that every function takes at least
one `Time` object as an argument.
This observation is the motivation for **methods**; a method is a
function that is associated with a particular class. We have seen
methods for strings, lists, dictionaries and tuples. In this chapter, we
will define methods for user-defined types.
Methods are semantically the same as functions, but there are two
syntactic differences:
- Methods are defined inside a class definition in order to make the
relationship between the class and the method explicit.
- The syntax for invoking a method is different from the syntax for
calling a function.
In the next few sections, we will take the functions from the previous
two chapters and transform them into methods. This transformation is
purely mechanical; you can do it simply by following a sequence of
steps. If you are comfortable converting from one form to another, you
will be able to choose the best form for whatever you are doing.
## Printing objects
In Chapter 16, we defined a class named `Time` and in Exercise 16.1, you
wrote a function named `print_time`:
``` python
class Time(object):
"""represents the time of day.
attributes: hour, minute, second"""
def print_time(time):
print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)
```
To call this function, you have to pass a `Time` object as an argument:
``` python
>>> start = Time()
>>> start.hour = 9
>>> start.minute = 45
>>> start.second = 00
>>> print_time(start)
09:45:00
```
To make `print_time` a method, all we have to do is move the function
definition inside the class definition. Notice the change in
indentation.
``` python
class Time(object):
def print_time(time):
print '%.2d:%.2d:%.2d' % (time.hour, time.minute, time.second)
```
Now there are two ways to call `print_time`. The first (and less common)
way is to use function syntax:
``` python
>>> Time.print_time(start)
09:45:00
```
In this use of dot notation, `Time` is the name of the class, and
`print_time` is the name of the method. `start` is passed as a
parameter.
The second (and more concise) way is to use method syntax:
``` python
>>> start.print_time()
09:45:00
```
In this use of dot notation, `print_time` is the name of the method
(again), and `start` is the object the method is invoked on, which is
called the **subject**. Just as the subject of a sentence is what the
sentence is about, the subject of a method invocation is what the method
is about.
Inside the method, the subject is assigned to the first parameter, so in
this case `start` is assigned to `time`.
By convention, the first parameter of a method is called `self`, so it
would be more common to write `print_time` like this:
``` python
class Time(object):
def print_time(self):
print '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
```
The reason for this convention is an implicit metaphor:
- The syntax for a function call, `print_time(start)`,
suggests that the function is the active agent. It says something like,
"Hey `print_time`! Here's an object for you to print."
- In object-oriented programming, the objects are the active agents.
A method invocation like `start.print_time()` says "Hey `start`! Please
print yourself."
This change in perspective might be more polite, but it is not obvious
that it is useful. In the examples we have seen so far, it may not be.
But sometimes shifting responsibility from the functions onto the
objects makes it possible to write more versatile functions, and makes
it easier to maintain and reuse code.
### Exercise 1
Rewrite **`time_to_int`** (from Section **\'16.4**\') as a method. It is
probably not appropriate to rewrite **`int_to_time`** as a method; it's
not clear what object you would invoke it on!
## Another example
Here's a version of `increment` (from Section 16.3) rewritten as a
method:
``` python
# inside class Time:
def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)
```
This version assumes that `time_to_int` is written as a method, as in
Exercise 17.1. Also, note that it is a pure function, not a modifier.
Here's how you would invoke `increment`:
``` python
>>> start.print_time()
09:45:00
>>> end = start.increment(1337)
>>> end.print_time()
10:07:17
```
The subject, `start`, gets assigned to the first parameter, `self`. The
argument, `1337`, gets assigned to the second parameter, `seconds`.
This mechanism can be confusing, especially if you make an error. For
example, if you invoke `increment` with two arguments, you get:
``` python
>>> end = start.increment(1337, 460)
TypeError: increment() takes exactly 2 arguments (3 given)
```
The error message is initially confusing, because there are only two
arguments in parentheses. But the subject is also considered an
argument, so all together that's three.
## A more complicated example
`is_after` (from Exercise 16.2) is slightly more complicated because it
takes two Time objects as parameters. In this case it is conventional to
name the first parameter `self` and the second parameter `other`:
``` python
# inside class Time:
def is_after(self, other):
return self.time_to_int() > other.time_to_int()
```
To use this method, you have to invoke it on one object and pass the
other as an argument:
``` python
>>> end.is_after(start)
True
```
One nice thing about this syntax is that it almost reads like English:
"end is after start?"
## The init method
The init method (short for "initialization") is a special method that
gets invoked when an object is instantiated. Its full name is `__init__`
(two underscore characters, followed by `init`, and then two more
underscores). An init method for the `Time` class might look like this:
``` python
# inside class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
```
It is common for the parameters of `__init__` to have the same names as
the attributes. The statement
``` python
self.hour = hour
```
stores the value of the parameter `hour` as an attribute of `self`.
The parameters are optional, so if you call `Time` with no arguments,
you get the default values.
``` python
>>> time = Time()
>>> time.print_time()
00:00:00
```
If you provide one argument, it overrides `hour`:
``` python
>>> time = Time (9)
>>> time.print_time()
09:00:00
```
If you provide two arguments, they override `hour` and `minute`.
``` python
>>> time = Time(9, 45)
>>> time.print_time()
09:45:00
```
And if you provide three arguments, they override all three default
values.
### Exercise 2
*Write an init method for the **\'`Point`**\' class that takes
**\'`x`**\' and **\'`y`**\' as optional parameters and assigns them to
the corresponding attributes.*
## The `__str__` method
`__str__` is a special method, like `__init__`, that is supposed to
return a string representation of an object.
For example, here is a `str` method for Time objects:
``` python
# inside class Time:
def __str__(self):
return '%.2d:%.2d:%.2d' % (self.hour, self.minute, self.second)
```
When you `print` an object, Python invokes the `str` method:
``` python
>>> time = Time(9, 45)
>>> print time
09:45:00
```
When I write a new class, I almost always start by writing `__init__`,
which makes it easier to instantiate objects, and `__str__`, which is
useful for debugging.
### Exercise 3
Write a **\'`str`**\' method for the **\'`Point`**\' class. Create a
Point object and print it.
## Operator overloading
By defining other special methods, you can specify the behavior of
operators on user-defined types. For example, if you define a method
named `__add__` for the `Time` class, you can use the `+` operator on
Time objects.
Here is what the definition might look like:
``` python
# inside class Time:
def __add__(self, other):
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)
```
And here is how you could use it:
``` python
>>> start = Time(9, 45)
>>> duration = Time(1, 35)
>>> print start + duration
11:20:00
```
When you apply the `+` operator to Time objects, Python invokes
`__add__`. When you print the result, Python invokes `__str__`. So there
is quite a lot happening behind the scenes!
Changing the behavior of an operator so that it works with user-defined
types is called **operator overloading**. For every operator in Python
there is a corresponding special method, like `__add__`. For more
details, see `docs.python.org/ref/specialnames.html`.
### Exercise 4
Write an **\'`add`**\' method for the Point class.
## Type-based dispatch
In the previous section we added two Time objects, but you also might
want to add an integer to a Time object. The following is a version of
`__add__` that checks the type of `other` and invokes either `add_time`
or `increment`:
``` python
# inside class Time:
def __add__(self, other):
if isinstance(other, Time):
return self.add_time(other)
else:
return self.increment(other)
def add_time(self, other):
seconds = self.time_to_int() + other.time_to_int()
return int_to_time(seconds)
def increment(self, seconds):
seconds += self.time_to_int()
return int_to_time(seconds)
```
The built-in function `isinstance` takes a value and a class object, and
returns `True` if the value is an instance of the class.
If `other` is a Time object, `__add__` invokes `add_time`. Otherwise it
assumes that the parameter is a number and invokes `increment`. This
operation is called a **type-based dispatch** because it dispatches the
computation to different methods based on the type of the arguments.
Here are examples that use the `+` operator with different types:
``` python
>>> start = Time(9, 45)
>>> duration = Time(1, 35)
>>> print start + duration
11:20:00
>>> print start + 1337
10:07:17
```
Unfortunately, this implementation of addition is not commutative. If
the integer is the first operand, you get
``` python
>>> print 1337 + start
TypeError: unsupported operand type(s) for +: 'int' and 'instance'
```
The problem is, instead of asking the Time object to add an integer,
Python is asking an integer to add a Time object, and it doesn't know
how to do that. But there is a clever solution for this problem: the
special method `__radd__`, which stands for "right-side add." This
method is invoked when a Time object appears on the right side of the
`+` operator. Here's the definition:
``` python
# inside class Time:
def __radd__(self, other):
return self.__add__(other)
```
And here's how it's used:
``` python
>>> print 1337 + start
10:07:17
```
### Exercise 5
Write an **\'`add`**\' method for Points that works with either a Point
object or a tuple: \'\'
- *If the second operand is a Point, the method should return a new
Point whose **\'`<I>`{=html}x`</I>`{=html}**\' coordinate is the sum
of the **\'`<I>`{=html}x`</I>`{=html}**\' coordinates of the
operands, and likewise for the **\'`<I>`{=html}y`</I>`{=html}**\'
coordinates.*
- *If the second operand is a tuple, the method should add the first
element of the tuple to the **\'`<I>`{=html}x`</I>`{=html}**\'
coordinate and the second element to the
**\'`<I>`{=html}y`</I>`{=html}**\' coordinate, and return a new
Point with the result.*
## Polymorphism
Type-based dispatch is useful when it is necessary, but (fortunately) it
is not always necessary. Often you can avoid it by writing functions
that work correctly for arguments with different types.
Many of the functions we wrote for strings will actually work for any
kind of sequence. For example, in Section 11.1 we used `histogram` to
count the number of times each letter appears in a word.
``` python
def histogram(s):
d = dict()
for c in s:
if c not in d:
d[c] = 1
else:
d[c] = d[c]+1
return d
```
This function also works for lists, tuples, and even dictionaries, as
long as the elements of `s` are hashable, so they can be used as keys in
`d`.
``` python
>>> t = ['spam', 'egg', 'spam', 'spam', 'bacon', 'spam']
>>> histogram(t)
{'bacon': 1, 'egg': 1, 'spam': 4}
```
Functions that can work with several types are called **polymorphic**.
Polymorphism can facilitate code reuse. For example, the built-in
function `sum`, which adds the elements of a sequence, works as long as
the elements of the sequence support addition.
Since Time objects provide an `add` method, they work with `sum`:
``` python
>>> t1 = Time(7, 43)
>>> t2 = Time(7, 41)
>>> t3 = Time(7, 37)
>>> total = sum([t1, t2, t3])
>>> print total
23:01:00
```
In general, if all of the operations inside a function work with a given
type, then the function works with that type.
The best kind of polymorphism is the unintentional kind, where you
discover that a function you already wrote can be applied to a type you
never planned for.
## Debugging
It is legal to add attributes to objects at any point in the execution
of a program, but if you are a stickler for type theory, it is a dubious
practice to have objects of the same type with different attribute sets.
It is usually a good idea to initialize all of an objects attributes in
the init method.
If you are not sure whether an object has a particular attribute, you
can use the built-in function `hasattr` (see Section 15.7).
Another way to access the attributes of an object is through the special
attribute `__dict__`, which is a dictionary that maps attribute names
(as strings) and values:
``` python
>>> p = Point(3, 4)
>>> print p.__dict__
{'y': 4, 'x': 3}
```
For purposes of debugging, you might find it useful to keep this
function handy:
``` python
def print_attributes(obj):
for attr in obj.__dict__:
print attr, getattr(obj, attr)
```
`print_attributes` traverses the items in the object's dictionary and
prints each attribute name and its corresponding value.
The built-in function `getattr` takes an object and an attribute name
(as a string) and returns the attribute's value.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**object-oriented language:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A language that provides features, such as user-defined classes and
method syntax, that facilitate object-oriented programming.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**object-oriented programming:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A style of programming in which data and the operations that manipulate
it are organized into classes and methods.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**method:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A function that is defined inside a class definition and is invoked on
instances of that class.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**subject:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The object a method is invoked on.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**operator overloading:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Changing the behavior of an operator like `+` so it works with a
user-defined type.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**type-based dispatch:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A programming pattern that checks the type of an operand and invokes
different functions for different types.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**polymorphic:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
Pertaining to a function that can work with more than one type.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 6
*This exercise is a cautionary tale about one of the most common, and
difficult to find, errors in Python.*
- \'\'Write a definition for a class named **\'`Kangaroo`**\' with the
following
methods:\'\'
- *An`__init__`method that initializes an attribute
named`pouch_contents`to an empty list.*
```{=html}
<!-- -->
```
- *A method named`put_in_pouch`that takes an object of any type and
adds it to`pouch_contents`.*
```{=html}
<!-- -->
```
- *A`__str__`method that returns a string representation of the
Kangaroo object and the contents of the pouch.*
Test your code by creating two \'\'***\'`Kangaroo`*objects, assigning
them to variables named*`kanga`*and*`roo`*, and then adding*`roo`*to the
contents of*`kanga`*****'s pouch.**\'
- **\'Download*`thinkpython.com/code/BadKangaroo.py`***\'\'\'. It
contains
a solution to the previous problem with one big, nasty bug. Find and fix
the bug.**\'**\'If you get stuck, you can download
\'\'***\'`thinkpython.com/code/GoodKangaroo.py`*****, which explains the
problem and demonstrates a solution.**\'
### Exercise 7
*Visual is a Python module that provides 3-D graphics. It is not always
included in a Python installation, so you might have to install it from
your software repository or, if it's not there, from
**\'`vpython.org`**\'.*
*The following example creates a 3-D space that is 256 units wide, long
and high, and sets the "center" to be the point **\'(128, 128, 128)**\'.
Then it draws a blue sphere.*
``` python
''from visual import *
scene.range = (256, 256, 256)
scene.center = (128, 128, 128)
color = (0.1, 0.1, 0.9) # mostly blue
sphere(pos=scene.center, radius=128, color=color)
''
```
*`color`**\' is an RGB tuple; that is, the elements are Red-Green-Blue
levels between 0.0 and 1.0
(see**\'`wikipedia.org/wiki/RGB_color_model`).*
*If you run this code, you should see a window with a black background
and a blue sphere. If you drag the middle button up and down, you can
zoom in and out. You can also rotate the scene by dragging the right
button, but with only one sphere in the world, it is hard to tell the
difference.*
*The following loop creates a cube of spheres:*
``` python
''t = range(0, 256, 51)
for x in t:
for y in t:
for z in t:
pos = x, y, z
sphere(pos=pos, radius=10, color=color)
''
```
- \'\'Put this code in a script and make sure it works for
you.\'\'
- \'\'Modify the program so that each sphere in the cube
has the color that corresponds to its position in RGB space. Notice that
the coordinates are in the range 0--255, but the RGB tuples are in the
range 0.0--1.0. \'\'
- \'\'Download **\'`thinkpython.com/code/color_list.py`**\'
and use the function **`read_colors`** to generate a list of the
available colors on your system, their names and RGB values. For each
named color draw a sphere in the position that corresponds to its RGB
values.\'\'
*You can see my solution at
**\'`thinkpython.com/code/color_space.py`**\'.*
## Further reading
- Wikipedia: VPython
- Wikipedia: RGB color model
|
# Think Python/Inheritance
In this chapter we will develop classes to represent playing cards,
decks of cards, and poker hands. If you don't play poker, you can read
about it at
`wikipedia.org/wiki/Poker`, but
you don\'t have to; I\'ll tell you what you need to know for the
exercises.
If you are not familiar with Anglo-American playing cards, you can read
about them at
`wikipedia.org/wiki/Playing_cards`.
## Card objects
There are fifty-two cards in a deck, each of which belongs to one of
four suits and one of thirteen ranks. The suits are Spades, Hearts,
Diamonds, and Clubs (in descending order in bridge). The ranks are Ace,
2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, and King. Depending on the game
that you are playing, an Ace may be higher than King or lower than 2.
If we want to define a new object to represent a playing card, it is
obvious what the attributes should be: `rank` and `suit`. It is not as
obvious what type the attributes should be. One possibility is to use
strings containing words like `'Spade'` for suits and `'Queen'` for
ranks. One problem with this implementation is that it would not be easy
to compare cards to see which had a higher rank or suit.
An alternative is to use integers to **encode** the ranks and suits. In
this context, "encode" means that we are going to define a mapping
between numbers and suits, or between numbers and ranks. This kind of
encoding is not meant to be a secret (that would be "encryption").
For example, this table shows the suits and the corresponding integer
codes:
---------- --- ---
Spades ↦ 3
Hearts ↦ 2
Diamonds ↦ 1
Clubs ↦ 0
---------- --- ---
This code makes it easy to compare cards; because higher suits map to
higher numbers, we can compare suits by comparing their codes.
The mapping for ranks is fairly obvious; each of the numerical ranks
maps to the corresponding integer, and for face cards:
------- --- ----
Jack ↦ 11
Queen ↦ 12
King ↦ 13
------- --- ----
I am using the ↦ symbol to make it clear that these mappings are not
part of the Python program. They are part of the program design, but
they don't appear explicitly in the code.
The class definition for `Card` looks like this:
``` python
class Card:
"""represents a standard playing card."""
def __init__(self, suit=0, rank=2):
self.suit = suit
self.rank = rank
```
As usual, the init method takes an optional parameter for each
attribute. The default card is the 2 of Clubs.
To create a Card, you call `Card` with the suit and rank of the card you
want.
``` python
queen_of_diamonds = Card(1, 12)
```
## Class attributes
In order to print Card objects in a way that people can easily read, we
need a mapping from the integer codes to the corresponding ranks and
suits. A natural way to do that is with lists of strings. We assign
these lists to **class attributes**:
``` python
# inside class Card:
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7',
'8', '9', '10', 'Jack', 'Queen', 'King']
def __str__(self):
return '%s of %s' % (Card.rank_names[self.rank],
Card.suit_names[self.suit])
```
Variables like `suit_names` and `rank_names`, which are defined inside a
class but outside of any method, are called class attributes because
they are associated with the class object `Card`.
This term distinguished them from variables like `suit` and `rank`,
which are called **instance attributes** because they are associated
with a particular instance.
Both kinds of attribute are accessed using dot notation. For example, in
`__str__`, `self` is a Card object, and `self.rank` is its rank.
Similarly, `Card` is a class object, and `Card.rank_names` is a list of
strings associated with the class.
Every card has its own `suit` and `rank`, but there is only one copy of
`suit_names` and `rank_names`.
Putting it all together, the expression `Card.rank_names[self.rank]`
means "use the attribute `rank` from the object `self` as an index into
the list `rank_names` from the class `Card`, and select the appropriate
string."
The first element of `rank_names` is `None` because there is no card
with rank zero. By including `None` as a place-keeper, we get a mapping
with the nice property that the index 2 maps to the string `'2'`, and so
on. To avoid this tweak, we could have used a dictionary instead of a
list.
With the methods we have so far, we can create and print cards:
``` python
>>> card1 = Card(2, 11)
>>> print card1
Jack of Hearts
```
Here is a diagram that shows the `Card` class object and one Card
instance:
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book026.png">`{=html}
```{=html}
</DIV>
```
`Card` is a class object, so it has type `type`. `card1` has type
`Card`. (To save space, I didn't draw the contents of `suit_names` and
`rank_names`).
## Comparing cards
For built-in types, there are conditional operators (`<`, `>`, `==`,
etc.) that compare values and determine when one is greater than, less
than, or equal to another. For user-defined types, we can override the
behavior of the built-in operators by providing a method named
`__cmp__`.
`__cmp__` takes two parameters, `self` and `other`, and returns a
positive number if the first object is greater, a negative number if the
second object is greater, and 0 if they are equal to each other.
The correct ordering for cards is not obvious. For example, which is
better, the 3 of Clubs or the 2 of Diamonds? One has a higher rank, but
the other has a higher suit. In order to compare cards, you have to
decide whether rank or suit is more important.
The answer might depend on what game you are playing, but to keep things
simple, we'll make the arbitrary choice that suit is more important, so
all of the Spades outrank all of the Diamonds, and so on.
With that decided, we can write `__cmp__`:
``` python
# inside class Card:
def __cmp__(self, other):
# check the suits
if self.suit > other.suit: return 1
if self.suit < other.suit: return -1
# suits are the same... check ranks
if self.rank > other.rank: return 1
if self.rank < other.rank: return -1
# ranks are the same... it's a tie
return 0
```
You can write this more concisely using tuple comparison:
``` python
# inside class Card:
def __cmp__(self, other):
t1 = self.suit, self.rank
t2 = other.suit, other.rank
return cmp(t1, t2)
```
The built-in function `cmp` has the same interface as the method
`__cmp__`: it takes two values and returns a positive number if the
first is larger, a negative number of the second is larger, and 0 if
they are equal.
### Exercise 1
Write a **`__cmp__`** method for Time objects. Hint: you can use tuple
comparison, but you also might consider using integer subtraction.\'\'
## Decks
Now that we have Cards, the next step is to define Decks. Since a deck
is made up of cards, it is natural for each Deck to contain a list of
cards as an attribute.
The following is a class definition for `Deck`. The init method creates
the attribute `cards` and generates the standard set of fifty-two cards:
``` python
class Deck:
def __init__(self):
self.cards = []
for suit in range(4):
for rank in range(1, 14):
card = Card(suit, rank)
self.cards.append(card)
```
The easiest way to populate the deck is with a nested loop. The outer
loop enumerates the suits from 0 to 3. The inner loop enumerates the
ranks from 1 to 13. Each iteration creates a new Card with the current
suit and rank, and appends it to `self.cards`.
## Printing the deck
Here is a `__str__` method for `Deck`:
``` python
#inside class Deck:
def __str__(self):
res = [str(card) for card in self.cards]
return '\n'.join(res)
```
This method demonstrates an efficient way to accumulate a large string:
building a list of strings and then using `join`. The built-in function
`str` invokes the `__str__` method on each card and returns the string
representation.
Since we invoke `join` on a newline character, the cards are separated
by newlines. Here's what the result looks like:
``` python
>>> deck = Deck()
>>> print deck
Ace of Clubs
2 of Clubs
3 of Clubs
...
10 of Spades
Jack of Spades
Queen of Spades
King of Spades
```
Even though the result appears on 52 lines, it is one long string that
contains newlines.
## Add, remove, shuffle and sort
To deal cards, we would like a method that removes a card from the deck
and returns it. The list method `pop` provides a convenient way to do
that:
``` python
#inside class Deck:
def pop_card(self):
return self.cards.pop()
```
Since `pop` removes the *last* card in the list, we are dealing from the
bottom of the deck. In real life bottom dealing is frowned upon^1^, but
in this context it's ok.
To add a card, we can use the list method `append`:
``` python
#inside class Deck:
def add_card(self, card):
self.cards.append(card)
```
A method like this that uses another function without doing much real
work is sometimes called a **veneer**. The metaphor comes from
woodworking, where it is common to glue a thin layer of good quality
wood to the surface of a cheaper piece of wood.
In this case we are defining a "thin" method that expresses a list
operation in terms that are appropriate for decks.
As another example, we can write a Deck method named `shuffle` using the
function `shuffle` from the `random` module:
``` python
# inside class Deck:
def shuffle(self):
random.shuffle(self.cards)
```
Don't forget to import `random`.
### Exercise 2
*Write a Deck method named **\'`sort`**\' that uses the list method
**\'`sort`**\' to sort the cards in a **\'`Deck`**\'. **\'`sort`**\'
uses the`__cmp__`method we defined to determine sort order.*
## Inheritance
The language feature most often associated with object-oriented
programming is **inheritance**. Inheritance is the ability to define a
new class that is a modified version of an existing class.
It is called "inheritance" because the new class inherits the methods of
the existing class. Extending this metaphor, the existing class is
called the **parent** and the new class is called the **child**.
As an example, let's say we want a class to represent a "hand," that is,
the set of cards held by one player. A hand is similar to a deck: both
are made up of a set of cards, and both require operations like adding
and removing cards.
A hand is also different from a deck; there are operations we want for
hands that don't make sense for a deck. For example, in poker we might
compare two hands to see which one wins. In bridge, we might compute a
score for a hand in order to make a bid.
This relationship between classes---similar, but different---lends
itself to inheritance.
The definition of a child class is like other class definitions, but the
name of the parent class appears in parentheses:
``` python
class Hand(Deck):
"""represents a hand of playing cards"""
```
This definition indicates that `Hand` inherits from `Deck`; that means
we can use methods like `pop_card` and `add_card` for Hands as well as
Decks.
`Hand` also inherits `__init__` from `Deck`, but it doesn't really do
what we want: instead of populating the hand with 52 new cards, the init
method for Hands should initialize `cards` with an empty list.
If we provide an init method in the `Hand` class, it overrides the one
in the `Deck` class:
``` python
# inside class Hand:
def __init__(self, label=''):
self.cards = []
self.label = label
```
So when you create a Hand, Python invokes this init method:
``` python
>>> hand = Hand('new hand')
>>> print hand.cards
[]
>>> print hand.label
new hand
```
But the other methods are inherited from `Deck`, so we can use
`pop_card` and `add_card` to deal a card:
``` python
>>> deck = Deck()
>>> card = deck.pop_card()
>>> hand.add_card(card)
>>> print hand
King of Spades
```
A natural next step is to encapsulate this code in a method called
`move_cards`:
``` python
#inside class Deck:
def move_cards(self, hand, num):
for i in range(num):
hand.add_card(self.pop_card())
```
`move_cards` takes two arguments, a Hand object and the number of cards
to deal. It modifies both `self` and `hand`, and returns `None`.
In some games, cards are moved from one hand to another, or from a hand
back to the deck. You can use `move_cards` for any of these operations:
`self` can be either a Deck or a Hand, and `hand`, despite the name, can
also be a `Deck`.
```{=html}
<DIV CLASS="theorem">
```
**Exercise 3** *Write a Deck method called`deal_hands`that takes two
parameters, the number of hands and the number of cards per hand, and
that creates new Hand objects, deals the appropriate number of cards per
hand, and returns a list of Hand objects.*
```{=html}
</DIV>
```
Inheritance is a useful feature. Some programs that would be repetitive
without inheritance can be written more elegantly with it. Inheritance
can facilitate code reuse, since you can customize the behavior of
parent classes without having to modify them. In some cases, the
inheritance structure reflects the natural structure of the problem,
which makes the program easier to understand.
On the other hand, inheritance can make programs difficult to read. When
a method is invoked, it is sometimes not clear where to find its
definition. The relevant code may be scattered among several modules.
Also, many of the things that can be done using inheritance can be done
as well or better without it.
## Class diagrams
So far we have seen stack diagrams, which show the state of a program,
and object diagrams, which show the attributes of an object and their
values. These diagrams represent a snapshot in the execution of a
program, so they change as the program runs.
They are also highly detailed; for some purposes, too detailed. A class
diagrams is a more abstract representation of the structure of a
program. Instead of showing individual objects, it shows classes and the
relationships between them.
There are several kinds of relationship between classes:
- Objects in one class might contain references to objects in another
class. For example, each Rectangle contains a reference to a Point,
and each Deck contains references to many Cards. This kind of
relationship is called **HAS-A**, as in, "a Rectangle has a Point."
- One class might inherit from another. This relationship is called
**IS-A**, as in, "a Hand is a kind of a Deck."
- One class might depend on another in the sense that changes in one
class would require changes in the other.
A **class diagram** is a graphical representation of these
relationships^2^. For example, this diagram shows the relationships
between `Card`, `Deck` and `Hand`.
```{=html}
<DIV CLASS="center">
```
`<IMG SRC="book027.png">`{=html}
```{=html}
</DIV>
```
The arrow with a hollow triangle head represents an IS-A relationship;
in this case it indicates that Hand inherits from Deck.
The standard arrow head represents a HAS-A relationship; in this case a
Deck has references to Card objects.
The star (`*`) near the arrow head is a **multiplicity**; it indicates
how many Cards a Deck has. A multiplicity can be a simple number, like
`52`, a range, like `5..7` or a star, which indicates that a Deck can
have any number of Cards.
A more detailed diagram might show that a Deck actually contains a
*list* of Cards, but built-in types like list and dict are usually not
included in class diagrams.
### Exercise 4
Read **\'`TurtleWorld.py`**\', **\'`World.py`**\' and **\'`Gui.py`**\'
and draw a class diagram that shows the relationships among the classes
defined there.
## Debugging
Inheritance can make debugging a challenge because when you invoke a
method on an object, you might not know which method will be invoked.
Suppose you are writing a function that works with Hand objects. You
would like it to work with all kinds of Hands, like PokerHands,
BridgeHands, etc. If you invoke a method like `shuffle`, you might get
the one defined in `Deck`, but if any of the subclasses override this
method, you'll get that version instead.
Any time you are unsure about the flow of execution through your
program, the simplest solution is to add print statements at the
beginning of the relevant methods. If `Deck.shuffle` prints a message
that says something like `Running Deck.shuffle`, then as the program
runs it traces the flow of execution.
As an alternative, you could use this function, which takes an object
and a method name (as a string) and returns the class that provides the
definition of the method:
``` python
def find_defining_class(obj, meth_name):
for ty in type(obj).mro():
if meth_name in ty.__dict__:
return ty
```
Here's an example:
``` python
>>> hand = Hand()
>>> print find_defining_class(hand, 'shuffle')
<class 'Card.Deck'>
```
So the `shuffle` method for this Hand is the one in `Deck`.
`find_defining_class` uses the `mro` method to get the list of class
objects (types) that will be searched for methods. "MRO" stands for
"method resolution order."
Here's a program design suggestion: whenever you override a method, the
interface of the new method should be the same as the old. It should
take the same parameters, return the same type, and obey the same
preconditions and postconditions. If you obey this rule, you will find
that any function designed to work with an instance of a superclass,
like a Deck, will also work with instances of subclasses like a Hand or
PokerHand.
If you violate this rule, your code will collapse like (sorry) a house
of cards.
## Glossary
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**encode:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
To represent one set of values using another set of values by
constructing a mapping between them.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**class attribute:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An attribute associated with a class object. Class attributes are
defined inside a class definition but outside any method.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**instance attribute:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
An attribute associated with an instance of a class.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**veneer:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A method or function that provides a different interface to another
function without doing much computation.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**inheritance:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The ability to define a new class that is a modified version of a
previously defined class.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**parent class:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The class from which a child class inherits.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**child class:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A new class created by inheriting from an existing class; also called a
"subclass."
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**IS-A relationship:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The relationship between a child class and its parent class.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**HAS-A relationship:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The relationship between two classes where instances of one class
contain references to instances of the other.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**class diagram:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A diagram that shows the classes in a program and the relationships
between them.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**multiplicity:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
A notation in a class diagram that shows, for a HAS-A relationship, how
many references there are to instances of another class.
```{=html}
</DD>
```
```{=html}
</DL>
```
## Exercises
### Exercise 5
*The following are the possible hands in poker, in increasing order of
value (and decreasing order of probability):*
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
***pair:***
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*two cards with the same rank*
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
****two pair:****
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*two pairs of cards with the same rank*
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
****three of a kind:****
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*three cards with the same rank*
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
****straight:****
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*five cards with ranks in sequence (aces can be high or low, so
**\'`Ace-2-3-4-5`**\' is a straight and so is
**\'`10-Jack-Queen-King-Ace`**\', but **\'`Queen-King-Ace-2-3`**\' is
not.)*
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
****flush:****
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*five cards with the same suit*
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
****full house:****
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*three cards with one rank, two cards with another*
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
****four of a kind:****
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*four cards with the same rank*
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
****straight flush:****
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*five cards in sequence (as defined above) and with the same suit*
```{=html}
</DD>
```
```{=html}
</DL>
```
*The goal of these exercises is to estimate the probability of drawing
these various hands.*
- *Download the following files from **\'`thinkpython.com/code`**\':*
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
***`Card.py`***
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
*: A complete version of the **\'`Card`**\', **\'`Deck`**\' and
**\'`Hand`**\' classes in this chapter.*
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
****`PokerHand.py`****
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
\'\': An incomplete implementation of a class
that represents a poker hand, and some code that tests it.\'\'
```{=html}
</DD>
```
```{=html}
</DL>
```
- **\'If you run*`PokerHand.py`***\'\'\', it deals six 7-card poker
hands
and checks to see if any of them contains a flush. Read this code
carefully before you go on.\'\'\'\'
- **\'Add methods
to*`PokerHand.py`*named**\'**`'has_pair`**`'`\'\'\'\',
**\'**`'has_twopair`**`'`**\', etc. that return True or False according
to whether or not the hand meets the relevant criteria. Your code should
work correctly for "hands" that contain any number of cards (although 5
and 7 are the most common sizes).\'\'\'\'
- **\'Write a method named*`classify`***\'\'\' that figures out
the highest-value classification for a hand and sets the
\'\'***\'`label`*****attribute accordingly. For example, a 7-card hand
might contain a flush and a pair; it should be labeled "flush".**\'
- \'\'\'\'When you are convinced that your classification methods are
working, the next step is to estimate the probabilities of the various
hands. Write a function in \'\'***\'`PokerHand.py`*****that shuffles a
deck of cards, divides it into hands, classifies the hands, and counts
the number of times various classifications appear.**\'
- \'\'\'\'Print a table of the classifications and their
probabilities.
Run your program with larger and larger numbers of hands until the
output values converge to a reasonable degree of accuracy. Compare your
results to the values at
\'\'***\'`wikipedia.org/wiki/Hand_rankings`*****.**\'
### Exercise 6
*This exercise uses TurtleWorld from Chapter **\'4**\'. You will write
code that makes Turtles play tag. If you are not familiar with the rules
of tag, see **\'`wikipedia.org/wiki/Tag_(game)`**\'.*
- \'\'Download **\'`thinkpython.com/code/Wobbler.py`**\' and run it.
You
should see a TurtleWorld with three Turtles. If you press the
**\'Run**\' button, the Turtles wander at random.\'\'
- \'\'Read the code and make sure you understand how it works.
The **\'`Wobbler`**\' class inherits from **\'`Turtle`**\', which means
that the **\'`Turtle`**\' methods **\'`lt`**\', **\'`rt`**\',
**\'`fd`**\' and **\'`bk`**\' work on Wobblers.The **\'`step`**\' method
gets invoked by TurtleWorld. It invokes **\'`steer`**\', which turns the
Turtle in the desired direction, **\'`wobble`**\', which makes a random
turn in proportion to the Turtle's clumsiness, and **\'`move`**\', which
moves forward a few pixels, depending on the Turtle's speed.\'\'
- \'\'Create a file named **\'`Tagger.py`**\'. Import everything from
**\'`Wobbler`**\', then define a class named **\'`Tagger`**\' that
inherits from **\'`Wobbler`**\'. Call **`make_world`** passing the
**\'`Tagger`**\' class object as an argument.\'\'
- \'\'Add a **\'`steer`**\' method to **\'`Tagger`**\' to override the
one in
**\'`Wobbler`**\'. As a starting place, write a version that always
points the Turtle toward the origin. Hint: use the math function
**\'`atan2`**\' and the Turtle attributes **\'`x`**\', **\'`y`**\' and
**\'`heading`**\'.\'\'
- \'\'Modify **\'`steer`**\' so that the Turtles stay in bounds.
For debugging, you might want to use the **\'Step**\' button, which
invokes **\'`step`**\' once on each Turtle.\'\'
- \'\'Modify **\'`steer`**\' so that each Turtle points toward its
nearest
neighbor. Hint: Turtles have an attribute, **\'`world`**\', that is a
reference to the TurtleWorld they live in, and the TurtleWorld has an
attribute, **\'`animals`**\', that is a list of all Turtles in the
world.\'\'
- \'\'Modify **\'`steer`**\' so the Turtles play tag. You can add
methods
to **\'`Tagger`**\' and you can override **\'`steer`**\' and
**`__init__`**, but you may not modify or override **\'`step`**\',
**\'`wobble`**\' or **\'`move`**\'. Also, **\'`steer`**\' is allowed to
change the heading of the Turtle but not the position.Adjust the rules
and your **\'`steer`**\' method for good quality play; for example, it
should be possible for the slow Turtle to tag the faster Turtles
eventually.\'\'
*You can get my solution from **\'`thinkpython.com/code/Tagger.py`**\'.*
```{=html}
</DIV>
```
```{=html}
<HR CLASS="footnoterule">
```
```{=html}
<DL CLASS="thefootnotes">
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
1
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
See `wikipedia.org/wiki/Bottom_dealing`.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-thefootnotes">
```
2
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-thefootnotes">
```
The diagrams I am using here are similar to UML (see
`wikipedia.org/wiki/Unified_Modeling_Language`), with a few
simplifications.
```{=html}
</DD>
```
```{=html}
</DL>
```
|
# Think Python/Debugging
Different kinds of errors can occur in a program, and it is useful to
distinguish among them in order to track them down more quickly:
- Syntax errors are produced by Python when it is translating the
source code into byte code. They usually indicate that there is
something wrong with the syntax of the program. Example: Omitting
the colon at the end of a `def` statement yields the somewhat
redundant message `SyntaxError: invalid syntax`.
- Runtime errors are produced by the interpreter if something goes
wrong while the program is running. Most runtime error messages
include information about where the error occurred and what
functions were executing. Example: An infinite recursion eventually
causes the runtime error "maximum recursion depth exceeded."
- Semantic errors are problems with a program that runs without
producing error messages but doesn't do the right thing. Example: An
expression may not be evaluated in the order you expect, yielding an
incorrect result.
The first step in debugging is to figure out which kind of error you are
dealing with. Although the following sections are organized by error
type, some techniques are applicable in more than one situation.
## Syntax errors
Syntax errors are usually easy to fix once you figure out what they are.
Unfortunately, the error messages are often not helpful. The most common
messages are `SyntaxError: invalid syntax` and
`SyntaxError: invalid token`, neither of which is very informative.
On the other hand, the message does tell you where in the program the
problem occurred. Actually, it tells you where Python noticed a problem,
which is not necessarily where the error is. Sometimes the error is
prior to the location of the error message, often on the preceding line.
If you are building the program incrementally, you should have a good
idea about where the error is. It will be in the last line you added.
If you are copying code from a book, start by comparing your code to the
book's code very carefully. Check every character. At the same time,
remember that the book might be wrong, so if you see something that
looks like a syntax error, it might be.
Here are some ways to avoid the most common syntax errors:
- Make sure you are not using a Python keyword for a variable name.
```{=html}
<!-- -->
```
- Check that you have a colon at the end of the header of every
compound statement, including `for`, `while`, `if`, and `def`
statements.
- Make sure that any strings in the code have matching
quotation marks.
- If you have multiline strings with triple quotes (single or double),
make
sure you have terminated the string properly. An unterminated string may
cause an `invalid token` error at the end of your program, or it may
treat the following part of the program as a string until it comes to
the next string. In the second case, it might not produce an error
message at all!
- An unclosed opening operator---`(`, `{`, or
`[`---makes Python continue with the next line as part of the current
statement. Generally, an error occurs almost immediately in the next
line.
- Check for the classic `=` instead of `==` inside
a conditional.
- Check the indentation to make sure it lines up the way it
is supposed to. Python can handle space and tabs, but if you mix them it
can cause problems. The best way to avoid this problem is to use a text
editor that knows about Python and generates consistent indentation.
If nothing works, move on to the next section\...
### I keep making changes and it makes no difference.
If the interpreter says there is an error and you don't see it, that
might be because you and the interpreter are not looking at the same
code. Check your programming environment to make sure that the program
you are editing is the one Python is trying to run.
If you are not sure, try putting an obvious and deliberate syntax error
at the beginning of the program. Now run it again. If the interpreter
doesn't find the new error, you are not running the new code.
There are a few likely culprits:
- You edited the file and forgot to save the changes before running it
again. Some programming environments do this for you, but some
don't.
- You changed the name of the file, but you are still running the old
name.
- Something in your development environment is configured incorrectly.
- If you are writing a module and using `import`, make sure you don't
give your module the same name as one of the standard Python
modules.
- If you are using `import` to read a module, remember that you have
to restart the interpreter or use `reload` to read a modified file.
If you import the module again, it doesn't do anything.
If you get stuck and you can't figure out what is going on, one approach
is to start again with a new program like "Hello, World!," and make sure
you can get a known program to run. Then gradually add the pieces of the
original program to the new one.
## Runtime errors
Once your program is syntactically correct, Python can compile it and at
least start running it. What could possibly go wrong?
### My program does absolutely nothing.
This problem is most common when your file consists of functions and
classes but does not actually invoke anything to start execution. This
may be intentional if you only plan to import this module to supply
classes and functions.
If it is not intentional, make sure that you are invoking a function to
start execution, or execute one from the interactive prompt. Also see
the "Flow of Execution" section below.
### My program hangs
If a program stops and seems to be doing nothing, it is "hanging." Often
that means that it is caught in an infinite loop or infinite recursion.
- If there is a particular loop that you suspect is the problem, add a
`print` statement immediately before the loop that says "entering
the loop" and another immediately after that says "exiting the
loop." Run the program. If you get the first message and not the
second, you've got an infinite loop. Go to the "Infinite Loop"
section below.
- Most of the time, an infinite recursion will cause the program to
run for a while and then produce a "RuntimeError: Maximum recursion
depth exceeded" error. If that happens, go to the "Infinite
Recursion" section below. If you are not getting this error but you
suspect there is a problem with a recursive method or function, you
can still use the techniques in the "Infinite Recursion" section.
- If neither of those steps works, start testing other loops and other
recursive functions and methods.
- If that doesn't work, then it is possible that you don't understand
the flow of execution in your program. Go to the "Flow of Execution"
section below.
#### Infinite Loop
If you think you have an infinite loop and you think you know what loop
is causing the problem, add a `print` statement at the end of the loop
that prints the values of the variables in the condition and the value
of the condition.
For example:
``` python
while x > 0 and y < 0 :
# do something to x
# do something to y
print "x: ", x
print "y: ", y
print "condition: ", (x > 0 and y < 0)
```
Now when you run the program, you will see three lines of output for
each time through the loop. The last time through the loop, the
condition should be `false`. If the loop keeps going, you will be able
to see the values of `x` and `y`, and you might figure out why they are
not being updated correctly.
#### Infinite Recursion
Most of the time, an infinite recursion will cause the program to run
for a while and then produce a `Maximum recursion depth exceeded` error.
If you suspect that a function or method is causing an infinite
recursion, start by checking to make sure that there is a base case. In
other words, there should be some condition that will cause the function
or method to return without making a recursive invocation. If not, then
you need to rethink the algorithm and identify a base case.
If there is a base case but the program doesn't seem to be reaching it,
add a `print` statement at the beginning of the function or method that
prints the parameters. Now when you run the program, you will see a few
lines of output every time the function or method is invoked, and you
will see the parameters. If the parameters are not moving toward the
base case, you will get some ideas about why not.
#### Flow of Execution
If you are not sure how the flow of execution is moving through your
program, add `print` statements to the beginning of each function with a
message like "entering function `foo`," where `foo` is the name of the
function.
Now when you run the program, it will print a trace of each function as
it is invoked.
### When I run the program I get an exception.
If something goes wrong during runtime, Python prints a message that
includes the name of the exception, the line of the program where the
problem occurred, and a traceback.
The traceback identifies the function that is currently running, and
then the function that invoked it, and then the function that invoked
*that*, and so on. In other words, it traces the sequence of function
invocations that got you to where you are. It also includes the line
number in your file where each of these calls occurs.
The first step is to examine the place in the program where the error
occurred and see if you can figure out what happened. These are some of
the most common runtime errors:
```{=html}
<DL CLASS="description">
```
```{=html}
<DT CLASS="dt-description">
```
**NameError:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
You are trying to use a variable that doesn't exist in the current
environment. Remember that local variables are local. You cannot refer
to them from outside the function where they are defined.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**TypeError:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
There are several possible causes:
- You are trying to use a value improperly. Example: indexing a
string, list, or tuple with something other than an integer.
- There is a mismatch between the items in a format string and the
items passed for conversion. This can happen if either the number of
items does not match or an invalid conversion is called for.
- You are passing the wrong number of arguments to a function or
method. For methods, look at the method definition and check that
the first parameter is `self`. Then look at the method invocation;
make sure you are invoking the method on an object with the right
type and providing the other arguments correctly.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**KeyError:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
You are trying to access an element of a dictionary using a key that the
dictionary does not contain.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**AttributeError:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
You are trying to access an attribute or method that does not exist.
Check the spelling! You can use `dir` to list the attributes that do
exist. If an AttributeError indicates that an object has `NoneType`,
that means that it is `None`. One common cause is forgetting to return a
value from a function; if you get to the end of a function without
hitting a `return` statement, it returns `None`. Another common cause is
using the result from a list method, like `sort`, that returns `None`.
```{=html}
</DD>
```
```{=html}
<DT CLASS="dt-description">
```
**IndexError:**
```{=html}
</DT>
```
```{=html}
<DD CLASS="dd-description">
```
The index you are using to access a list, string, or tuple is greater
than its length minus one. Immediately before the site of the error, add
a `print` statement to display the value of the index and the length of
the array. Is the array the right size? Is the index the right value?
```{=html}
</DD>
```
```{=html}
</DL>
```
The Python debugger (`pdb`) is useful for tracking down Exceptions
because it allows you to examine the state of the program immediately
before the error. You can read about `pdb` at
`docs.python.org/lib/module-pdb.html`.
### I added so many `print` statements I get inundated with output
One of the problems with using `print` statements for debugging is that
you can end up buried in output. There are two ways to proceed: simplify
the output or simplify the program.
To simplify the output, you can remove or comment out `print` statements
that aren't helping, or combine them, or format the output so it is
easier to understand.
To simplify the program, there are several things you can do. First,
scale down the problem the program is working on. For example, if you
are searching a list, search a *small* list. If the program takes input
from the user, give it the simplest input that causes the problem.
Second, clean up the program. Remove dead code and reorganize the
program to make it as easy to read as possible. For example, if you
suspect that the problem is in a deeply nested part of the program, try
rewriting that part with simpler structure. If you suspect a large
function, try splitting it into smaller functions and testing them
separately.
Often the process of finding the minimal test case leads you to the bug.
If you find that a program works in one situation but not in another,
that gives you a clue about what is going on.
Similarly, rewriting a piece of code can help you find subtle bugs. If
you make a change that you think doesn't affect the program, and it
does, that can tip you off.
## Semantic errors
In some ways, semantic errors are the hardest to debug, because the
interpreter provides no information about what is wrong. Only you know
what the program is supposed to do.
The first step is to make a connection between the program text and the
behavior you are seeing. You need a hypothesis about what the program is
actually doing. One of the things that makes that hard is that computers
run so fast.
You will often wish that you could slow the program down to human speed,
and with some debuggers you can. But the time it takes to insert a few
well-placed `print` statements is often short compared to setting up the
debugger, inserting and removing breakpoints, and "stepping" the program
to where the error is occurring.
### My program doesn't work.
You should ask yourself these questions:
- Is there something the program was supposed to do but which doesn't
seem to be happening? Find the section of the code that performs
that function and make sure it is executing when you think it
should.
- Is something happening that shouldn't? Find code in your program
that performs that function and see if it is executing when it
shouldn't.
```{=html}
<!-- -->
```
- Is a section of code producing an effect that is not what you
expected? Make sure that you understand the code in question,
especially if it involves invocations to functions or methods in
other Python modules. Read the documentation for the functions you
invoke. Try them out by writing simple test cases and checking the
results.
In order to program, you need to have a mental model of how programs
work. If you write a program that doesn't do what you expect, very often
the problem is not in the program; it's in your mental model.
The best way to correct your mental model is to break the program into
its components (usually the functions and methods) and test each
component independently. Once you find the discrepancy between your
model and reality, you can solve the problem.
Of course, you should be building and testing components as you develop
the program. If you encounter a problem, there should be only a small
amount of new code that is not known to be correct.
### I've got a big hairy expression and it doesn't do what I expect.
Writing complex expressions is fine as long as they are readable, but
they can be hard to debug. It is often a good idea to break a complex
expression into a series of assignments to temporary variables.
For example:
``` python
self.hands[i].addCard(self.hands[self.findNeighbor(i)].popCard())
```
This can be rewritten as:
``` python
neighbor = self.findNeighbor(i)
pickedCard = self.hands[neighbor].popCard()
self.hands[i].addCard(pickedCard)
```
The explicit version is easier to read because the variable names
provide additional documentation, and it is easier to debug because you
can check the types of the intermediate variables and display their
values.
Another problem that can occur with big expressions is that the order of
evaluation may not be what you expect. For example, if you are
translating the expression `<I>`{=html}x`</I>`{=html}/2 π into Python,
you might write:
``` python
y = x / 2 * math.pi
```
That is not correct because multiplication and division have the same
precedence and are evaluated from left to right. So this expression
computes `<I>`{=html}x`</I>`{=html} π / 2.
A good way to debug expressions is to add parentheses to make the order
of evaluation explicit:
``` python
y = x / (2 * math.pi)
```
Whenever you are not sure of the order of evaluation, use parentheses.
Not only will the program be correct (in the sense of doing what you
intended), it will also be more readable for other people who haven't
memorized the rules of precedence.
### I've got a function or method that doesn't return what I expect
If you have a `return` statement with a complex expression, you don't
have a chance to print the `return` value before returning. Again, you
can use a temporary variable. For example, instead of:
``` python
return self.hands[i].removeMatches()
```
you could write:
``` python
count = self.hands[i].removeMatches()
return count
```
Now you have the opportunity to display the value of `count` before
returning.
### I\'m really, really stuck and I need help.
First, try getting away from the computer for a few minutes. Computers
emit waves that affect the brain, causing these symptoms:
- Frustration and rage.
```{=html}
<!-- -->
```
- Superstitious beliefs ("the computer hates me") and
magical thinking ("the program only works when I wear my hat backward").
- Random walk programming (the attempt to program by writing
every possible program and choosing the one that does the right thing).
If you find yourself suffering from any of these symptoms, get up and go
for a walk. When you are calm, think about the program. What is it
doing? What are some possible causes of that behavior? When was the last
time you had a working program, and what did you do next?
Sometimes it just takes time to find a bug. I often find bugs when I am
away from the computer and let my mind wander. Some of the best places
to find bugs are trains, showers, and in bed, just before you fall
asleep.
### No, I really need help.
It happens. Even the best programmers occasionally get stuck. Sometimes
you work on a program so long that you can't see the error. A fresh pair
of eyes is just the thing.
Before you bring someone else in, make sure you are prepared. Your
program should be as simple as possible, and you should be working on
the smallest input that causes the error. You should have `print`
statements in the appropriate places (and the output they produce should
be comprehensible). You should understand the problem well enough to
describe it concisely.
When you bring someone in to help, be sure to give them the information
they need:
- If there is an error message, what is it and what part of the
program does it indicate?
- What was the last thing you did before this error occurred? What
were the last lines of code that you wrote, or what is the new test
case that fails?
- What have you tried so far, and what have you learned?
When you find the bug, take a second to think about what you could have
done to find it faster. Next time you see something similar, you will be
able to find the bug more quickly.
Remember, the goal is not just to make the program work. The goal is to
learn how to make the program work.
|
# Think Python/Answers
## Chapter 1
See below for Chapter 1 exercises.
### Exercise 1.2
1.) How many seconds are there in 42 minutes 42 seconds?
\>\>\> (42 \* 60) + 42
**2562 seconds**
2.) How many miles are there in 10 kilometers? Hint there are 1.61
kilometers in a mile.
\>\>\> 10/1.61
**6.21 miles**
3.) If you run a 10 kilometer race in 42 minutes 42 seconds, what is
your average time per mile? What is your average speed in miles per
hour? (Hint: there are about 1.61 kilometers in a mile.)
\>\>\> 10 / 1.61 \# convert kilometers to miles
6.211180124223602
\>\>\> (42 \* 60) + 42 \# convert time to seconds
2562
\>\>\> 2562 / 6.211180124223602 \# what is your average time (seconds)
per mile
412.482
\>\>\> 412.482 / 60 \# what is your average time (minutes) per mile
**6.874700000000001**
\>\>\> 60 / 6.874700000000001 \# miles per hour
**8.727653570337614**
How about another way
\>\>\> 10 / 42.7 \# avg kilometers per minute
0.23419203747072598
\>\>\> 0.23419203747072598 \* 60 \# kilometers per hour
14.05152224824356
\>\>\> 14.05152224824356 / 1.61 \# convert to M.P.H
8.727653570337614
or a one-liner
\>\>\> (10 / 1.61) / (42.7 / 60) \# (distance in miles) / (time in
hours)
8.727653570337614 \# miles/hour
## Chapter 2
### Exercise 2.1
If you type an integer with a leading zero, you might get a confusing
error:
``` python
>>> zipcode = 02492
^
SyntaxError: invalid token
```
Other number seem to work, but the results are bizarre:
``` python
>>> zipcode = 02132
>>> print zipcode
1114
```
So python is assuming you want to convert an octal number to a decimal
number. In the base 8 numbering system where valid numbers are **0, 1,
2, 3, 4, 5, 6 and 7**.
``` python
Base 8: 00 01 02 03 04 05 06 07 10 11 12 13 14 15 16 17 20 21 22 23 24
Base 10: 00 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20
```
Every 8 numbers we increment the left hand columns. This means that the
right most column is the number of \'ones\'. The one to the left of that
is a tally of the number of \'eights\', the one next to that is a tally
of a full column of \'eight\' times the \'eight column\' - 64. The one
next to that is 64\*8 - 512 and so on. For more information read Base
Eight math.
That is why **zipcode = 02492** is invalid as the digit 9 is not a valid
octal number. We can do the conversion manually as follows:
``` python
>>> print 02132
1114
>>> (2*512)+(1*64)+(3*8)+(2*1)
1114
>>>
```
### Exercise 2.2
The volume of a sphere with radius **r** is *4/3* π *r*^*3*^\'\'. What
is the volume of a sphere with radius 5?
``` python
>>> pi = 3.1415926535897932
>>> r = 5
>>> 4/3*pi*r**3 # This is the wrong answer
392.69908169872411
>>> r = 5.0 # Radius can be a float here as well, but is not _necessary_.
>>> 4.0/3.0*pi*r**3 # Using floats give the correct answer
523.5987755982989
>>>
```
Suppose the cover price of a book is \$24.95, but bookstores get a 40%
discount. Shipping costs \$3 for the first copy and 75 cents for each
additional copy. What is the total wholesale cost for 60 copies?\'\'
``` python
$24.95 Cost
$9.98 Discount per book
$14.97 Cost per book after discount
60 Total number of books
$898.20 Total cost not inc delivery
$3.00 First book delivery
59 Remaining books
$0.75 Delivery cost for extra books
$44.25 Total cost for extra books
$47.25 Total Delivery cost
$945.45 Total Bill
This answer is wrong because 40.0/100.0 return wrong value 0.40000000000000002 for more info see IEEE 754 (Standard for Floating-Point Arithmetic)
>>> (24.95-24.95*40.0/100.0)*60+3+0.75*(60-1)
945.44999999999993
>>> 24.95*0.6*60+0.75*(60-1)+3
945.45
You can use the decimal module to maintain precision.
from decimal import Decimal
..
...
def wholesale_cost(args):
d = 1 - args.get('discount')/100
purchase = Decimal(args.get('cost') * d * 60)
return purchase + Decimal(args.get('delivery'))
args = {'cost': 24.95, 'discount': 40, 'delivery': 3.00+0.75*59}
```
Another solution using functions as well as input prompts:
``` python
# Total wholesale book cost calculator
cover_price = 24.95
number_of_books = int(input("How many books do you want to order at wholesale? "))
def ship_cost (number_of_books):
if number_of_books == 1:
return (number_of_books * 3) # Cost of shipping one book is $3
else:
return (3 + (number_of_books - 1) * 0.75) # Each additional copy of the book is $0.75 to ship
def discounted_price(number_of_books):
return(cover_price - (cover_price * .4)) # There is a 40% discount on wholesale book sales
def wholesale_cost(number_of_books):
return ((discounted_price(number_of_books) * number_of_books) + ship_cost(number_of_books))
print("The cost of buying and shipping", number_of_books, "books is $",round(wholesale_cost(number_of_books), 2))
```
If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per
mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace
again, what time do I get home for breakfast?
Answer: **7:30 am**
How I did it:
``` python
>>> start = (6*60+52)*60
>>> easy = (8*60+15)*2
>>> fast = (7*60+12)*3
>>> finish_hour = (start + easy + fast)/(60*60.0)
>>> finish_floored = (start + easy + fast)//(60*60) #int() function can also be used to get integer value, but it hasn't taught yet.
>>> finish_minute = (finish_hour - finish_floored)*60
>>> print ('Finish time was %d:%d' % (finish_hour,finish_minute))
Finish time was 7:30
*** ANOTHER WAY ***
start_time_hr = 6 + 52 / 60.0
easy_pace_hr = (8 + 15 / 60.0 ) / 60.0
tempo_pace_hr = (7 + 12 / 60.0) / 60.0
running_time_hr = 2 * easy_pace_hr + 3 * tempo_pace_hr
breakfast_hr = start_time_hr + running_time_hr
breakfast_min = (breakfast_hr-int(breakfast_hr))*60
breakfast_sec= (breakfast_min-int(breakfast_min))*60
print ('breakfast_hr', int(breakfast_hr) )
print ('breakfast_min', int (breakfast_min) )
print ('breakfast_sec', int (breakfast_sec) )
>>>
```
## Chapter 3
### Exercise 3.1
Python provides a built-in function called *len* that returns the length
of a string, so the value of len(\'allen\') is 5. Write a function named
right_justify that takes a string named *s* as a parameter and prints
the string with enough leading spaces so that the last letter of the
string is in column 70 of the display.
``` python
>>> def right_justify(s):
print (' '*(70-len(s))+s)
>>> right_justify('allen')
allen
>>>
```
Alternate Solution Using concatenation and repetition
``` python
def right_justify(s):
total_length = 70
current_length = len(s)
current_string = s
while current_length < total_length:
current_string = " " + current_string
current_length = len(current_string)
print(current_string)
OUTPUT
>>> right_justify("monty")
monty
```
### Exercise 3.3
You can see my solution at <http://thinkpython.com/code/grid.py>.
``` python
"""
Solution to Exercise 3.5 on page 27 of Think Python
Allen B. Downey, Version 1.1.24+Kart [Python 3.2]
"""
# here is a mostly-straightforward solution to the
# two-by-two version of the grid.
def do_twice(f):
f()
f()
def do_four(f):
do_twice(f)
do_twice(f)
def print_beam():
print('+ - - - -', end='')
def print_post():
print('| ', end='')
def print_beams():
do_twice(print_beam)
print('+')
def print_posts():
do_twice(print_post)
print('|')
def print_row():
print_beams()
do_twice(print_posts)
def print_grid():
do_twice(print_row)
print_beams()
print_grid()
____________
# another solution
def do_twice(f):
f()
f()
def do_four(f):
do_twice(f)
do_twice(f)
def print_column():
print '+----+----+'
def print_row():
print '| | |'
def print_rows():
do_four(print_row)
def do_block():
print_column()
print_rows()
def print_block():
do_twice(do_block)
print_column()
print_block()
# nathan moses-gonzales
_________
# straight-forward solution to 4x4 grid
def do_twice(f):
f()
f()
def do_four(f): # not needed for 2x2 grid
do_twice(f)
do_twice(f)
def print_beam():
print('+----', end='')
def print_post():
print('| ', end='')
def print_beams():
do_twice(print_beam)
print('+')
def print_posts():
do_twice(print_post)
print('|')
def print_row():
print_beams()
do_twice(print_posts)
def print_grid2x2():
do_twice(print_row)
print_beams()
def print_beam4():
do_four(print_beam)
print('+')
def print_post4():
do_four(print_post)
print('|')
def print_row4():
print_beam4()
do_twice(print_post4)
def print_grid4x4():
do_four(print_row4)
print_beam4()
print_grid4x4()
-----------------------
# here is a less-straightforward solution to the
# four-by-four grid
def one_four_one(f, g, h):
f()
do_four(g)
h()
def print_plus():
print '+',
def print_dash():
print '-',
def print_bar():
print '|',
def print_space():
print ' ',
def print_end():
print
def nothing():
"do nothing"
def print1beam():
one_four_one(nothing, print_dash, print_plus)
def print1post():
one_four_one(nothing, print_space, print_bar)
def print4beams():
one_four_one(print_plus, print1beam, print_end)
def print4posts():
one_four_one(print_bar, print1post, print_end)
def print_row():
one_four_one(nothing, print4posts, print4beams)
def print_grid():
one_four_one(print4beams, print_row, nothing)
print_grid()
comment = """
After writing a draft of the 4x4 grid, I noticed that many of the
functions had the same structure: they would do something, do
something else four times, and then do something else once.
So I wrote one_four_one, which takes three functions as arguments; it
calls the first one once, then uses do_four to call the second one
four times, then calls the third.
Then I rewrote print1beam, print1post, print4beams, print4posts,
print_row and print_grid using one_four_one.
Programming is an exploratory process. Writing a draft of a program
often gives you insight into the problem, which might lead you to
rewrite the code to reflect the structure of the solution.
--- Allen
"""
print comment
# another solution
def beam():
plus = "+"
minus = "-"*4
print(plus, minus, plus,minus, plus, minus, plus, minus, plus)
def straight():
straight = "|"
space = " "*4
print(straight, space, straight, space, straight, space, straight, space,
straight, space)
def quad_straight():
straight()
straight()
straight()
straight()
def twice():
beam()
quad_straight()
beam()
quad_straight()
def quad():
twice()
twice()
beam()
quad()
-- :)
------------------
# Without functions.
print("+ - - - - " * 2 + "+")
print("|\t\t | \t\t|\n" * 3 + "|\t\t | \t\t|")
print("+ - - - - " * 2 + "+")
print("|\t\t | \t\t|\n " *3 + "|\t\t | \t\t|")
print("+ - - - - " * 2 + "+")
------------------
Why not using the first solution and adapt it to the number of rows
def do_twice(f):
f()
f()
def do_four(f):
do_twice(f)
do_twice(f)
def print_column():
print '+----+----+----+----+'
def print_row():
print '| | | | |'
def print_rows():
do_four(print_row)
def do_block():
print_column()
print_rows()
def print_block():
do_twice(do_block)
# print_column()
do_twice(do_block)
print_column()
print_block()
-----------------------
# mteodor
def draw_line(bar, middle = ' ', repeat = 2, length = 2):
""" Draw a single line like this:
[ (B M*repeat)*length B]
"""
for k in range(length):
print("%s %s " % (bar, middle*repeat), end='')
print(bar)
def draw_grid(length = 2, height = 2, width = 2):
""" Draw a grid like this:
+ -- + -- +
| | |
| | |
+ -- + -- +
| | |
| | |
+ -- + -- +
where:
* length x height are the table size
* width is the size of a cell/column
"""
for i in range(height):
draw_line('+', '-', width, length)
for j in range(length):
draw_line('|', ' ', width, length)
draw_line('+', '-', width, length)
draw_grid(4, 4, 3)
--------------------------
#kipp
# auto adjust size of columns
size=4
def beam():
print(" + - - - -"*size, "+")
def post():
print(" | "*size, "|")
def repeat(func):
func()
func()
func()
# manual adjust size for rows
# this is 4
beam()
repeat(post)
beam()
repeat(post)
beam()
repeat(post)
beam()
repeat(post)
beam()
```
## Chapter 4
### 4.3 Exercise 1
``` python
from TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
def square(t):
for i in range(4):
fd(t, 100)
lt(t)
square(bob)
wait_for_user()
```
### 4.3 Exercise 2
``` python
from TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print(bob)
def square(t, length):
t = Turtle()
for i in range(4):
fd(t, length)
lt(t)
square(bob, 200)
wait_for_user()
```
### 4.3 Exercise 3
``` python
from swampy.TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
print(bob)
def polygon(t, length, n):
for i in range(n):
fd(t, length)
lt(t, 360 / n)
polygon(bob, 50, 8)
wait_for_user()
```
## Chapter 5
### Exercise 5.2
``` python
def countdown(a): # A typical countdown function
if a < 0:
print("Blastoff")
elif a > 0:
print(a)
countdown(a - 1)
def call_function(n,a): # The countdown function is called "n" number of times. Any other function can be used instead of countdown function.
for i in range(n):
countdown(a)
call_function(3, 10)
```
### Exercise 5.3
``` python
def is_triangle(a, b, c):
if a <= b+c:
if b <= a+c:
if c <= a+b:
return 'yes'
else:
return 'no'
else:
return 'no'
else:
return 'no'
is_triangle(1, 12, 1)
'no'
```
### Exercise 5.3
``` python
def is_triangle(a, b, c):
if a<=b+c and b<=a+c and c<=a+b:
return 'yes'
else:
return 'no'
is_triangle(1, 12, 3)
'no'
```
## Chapter 9
### Exercise 9.1
``` python
fin = open('words.txt')
for line in fin:
word = line.strip()
if len(word) > 20:
print (word)
```
### Exercise 9.2
``` python
fin = open('words.txt')
def has_no_e(word):
for char in word:
if char in 'Ee':
return False
return True
count = 0
for line in fin:
word = line.strip()
if has_no_e(word):
count += 1
print (word)
percent = (count / 113809.0) * 100
print (str(percent)) + "% of the words don't have an 'e'."
```
### Exercise 9.3
``` python
fin = open('words.txt')
def avoids(word,letter):
for char in word:
if char in letter:
return False
return True
letter = raw_input('What letters to exclude? ')
count = 0
for line in fin:
word = line.strip()
if avoids(word, letter):
count += 1
print word
percent = (count / 113809.0) * 100
print str(percent) + "% of the words don't have " + letter + '.'
```
### Exercise 9.4
``` python
def uses_only(word, letters):
"""returns true if word is made only out of letters else flase"""
for letter in word:
if letter not in letters:
return False
return True
```
## Chapter 10
### Exercise 10.1
Write a function called nested_sum that takes a nested list of integers
and add up the elements from all of the nested lists.
``` python
def nested_sum(nestedList):
'''
nestedList: list composed of nested lists containing int.
Returns the sum of all the int in the nested list
'''
newList = []
#Helper function to flatten the list
def flatlist(nestedList):
'''
Returns a flat list
'''
for i in range(len(nestedList)):
if type(nestedList[i]) == int:
newList.append(nestedList[i])
else:
flatlist(nestedList[i])
return newList
flatlist(nestedList)
print sum(newList)
nested_sum(nestedList)
```
### Exercise 10.2
Write a function named \"capitalize_nested\" that takes a nested list of
strings and returns a new nested list with all strings capitalized.
``` python
>>> def capitalize_nested(l):
def capitalize(s):
return s.capitalize()
for n, i in enumerate(l):
if type(i) is list:
l[n] = capitalize_nested(l[n])
elif type(i) is str:
l[n] = capitalize(i)
return l
```
### Exercise 10.3
Write a function that takes a list of numbers and returns the cumulative
sum.
``` python
>>> def cumulative(l):
cumulative_sum = 0
new_list = []
for i in l:
cumulative_sum += i
new_list.append(cumulative_sum)
return new_list
```
### Exercise 10.4
Write a function called middle that takes a list and returns a new list
that contains all but the first and last elements.
``` python
>>> def middle(x):
res = []
i = 1
while i <= len(x)-2:
res.append(x[i])
i += 1
return res
```
This can also be done simply with a slice.
``` python
>>> def middle(x):
return x[1:-1]
```
### Exercise 10.5
Write a function called chop that takes a list and modifies it, removing
the first and last elements, and returns None.
``` python
>>> def chop(x):
del x[:1]
del x[-1:]
```
## Chapter 11
### Exercise 11.1
Write a function that reads the words in words.txt and stores them as
keys in a dictionary. It doesn't matter what the values are. Then you
can use the in operator as a fast way to check whether a string is in
the dictionary.
``` python
fin = open('words.txt')
englishdict = dict()
def create_diction():
counter = 0
dictionairy = dict()
for line in fin:
word = line.strip()
dictionairy[word] = counter
counter += 1
return dictionairy
```
### Exercise 11.2
``` python
def invert_dict(s):
i={}
for key in s:
v=s[key]
i.setdefault(v, []).append(key)
return i
```
Edit: This was not the exercise I found in my edition of \'Think
Python\', so I\'ve added my answer in case anyone else is curious: Use
get to write histogram more concisely. You should be able to eliminate
the if statement.
``` python
def histogram(s):
d = dict()
for c in s:
d[c] = d.get(c,0)+1
return d
```
### Exercise 11.3
Dictionaries have a method called keys that returns the keys of the
dictionary, in no particular order, as a list. Modify print_hist to
print the keys and their values in alphabetical order.
``` python
v = {'p' : 1, 'a' : 1, 'r' : 2, 'o' : 1, 't' : 1}
def print_hist(h):
d = []
d += sorted(h.keys())
for c in d:
print(c, h[c])
```
OR
``` python
v = {'p' : 1, 'a' : 1, 'r' : 2, 'o' : 1, 't' : 1}
def print_hist(h):
for c in sorted(h.keys()):
print c, h[c]
```
### Exercise 11.4
Modify reverse_lookup so that it builds and returns a list of all keys
that map to v, or an empty list if there are none.
``` python
def reverse_lookup(d,v):
l = list()
for c in d:
if d[c] == v:
l.append(c)
return l
```
## Chapter 12
### Exercise 12.1
``` python
numbers = (1,2,3)
def sumall(numbers):
x = 0
for i in numbers:
x = x + i
print x
sumall(numbers)
```
or
``` python
def sumall(*t):
x = 0
for i in range(len(t)):
x += t[i]
return x
```
or
``` python
def sumall(*args):
t = list(args)
return sum(t)
```
or
``` python
def sumall(*args):
return sum(args)
```
### Exercise 12.2
``` python
import random
def sort_by_length(words):
t = []
for word in words:
t.append((len(word),word))
t.sort(reverse=True)
res = []
for length, word in t:
res.append(word)
i=0
final = []
while i <= len(res)-2:
if len(res[i]) == len(res[i+1]):
y_list = [res[i], res[i+1]]
random.shuffle(y_list)
final = final + y_list
i += 2
else:
final.append(res[i])
i += 1
if i == len(res)-1:
final.append(res[i])
return final
```
or
``` python
from random import shuffle
def sort_by_length(words):
r = []
d = dict()
for word in words:
d.setdefault(len(word), []).append(word)
for key in sorted(d, reverse=True):
if len(d[key]) > 1:
shuffle(d[key])
r.extend(d[key])
return r
```
### Exercise 12.3
``` python
import string
def most_frequent(s):
d = dict()
inv = dict()
for char in s:
if char in string.ascii_letters:
letter = char.lower()
d[letter] = d.get(letter, 0) + 1
for letter, freq in d.items():
inv.setdefault(freq, []).append(letter)
for freq in sorted(inv, reverse=True):
print('{:.2%}:'.format(freq/(sum(list(inv)*len(inv[freq])))), ', '.join(inv[freq]))
```
## Chapter 13
### Exercise 13.7
``` python
from string import punctuation, whitespace, digits
from random import randint
from bisect import bisect_left
def process_file(filename):
h = dict()
fp = open(filename)
for line in fp:
process_line(line, h)
return h
def process_line(line, h):
line = line.replace('-', ' ')
for word in line.split():
word = word.strip(punctuation + whitespace + digits)
word = word.lower()
if word != '':
h[word] = h.get(word, 0) + 1
hist = process_file('emma.txt')
def cum_sum(list_of_numbers):
cum_list = []
for i, elem in enumerate(list_of_numbers):
if i == 0:
cum_list.append(elem)
else:
cum_list.append(cum_list[i-1] + elem)
return cum_list
def random_word(h):
word_list = list(h.keys())
num_list = []
for word in word_list:
num_list.append(h[word])
cum_list = cum_sum(num_list)
i = randint(1, cum_list[-1])
pos = bisect_left(cum_list, i)
return word_list[pos]
print(random_word(hist))
```
## Chapter 14
### Exercise 14.3
``` python
import shelve
def dict_of_signatures_and_words(filename='words.txt'):
d = dict()
for line in open(filename):
word = line.lower().strip()
signature = ''.join(sorted(word))
d.setdefault(signature, []).append(word)
return d
def db_of_anagrams(filename='anagrams', d=dict_of_signatures_and_words()):
db = shelve.open(filename)
for key, values in d.items():
if len(values)>1:
for index, value in enumerate(values):
db[value]=values[:index]+values[index+1:]
db.close()
def print_contents_of_db(filename='anagrams'):
db = shelve.open(filename, flag='r')
for key in sorted(db):
print(key.rjust(12), '\t<==>\t', ', '.join(db[key]))
db.close()
db_of_anagrams()
print_contents_of_db()
```
### Exercise 14.5
``` python
# Replace urllib.request with urllib if you use Python 2.
# I would love to see a more elegant solution for this exercise, possibly by someone who understands html.
import urllib.request
def check(zip_code):
if zip_code == 'done':
return False
else:
if len(zip_code) != 5:
print('\nThe zip code must have five digits!')
return True
def get_html(zip_code):
gibberish = urllib.request.urlopen('http://www.uszip.com/zip/' + zip_code)
less_gib = gibberish.read().decode('utf-8')
return less_gib
def extract_truth(code, key, delimiter):
pos = code.find(key) + len(key)
nearly_true = code[pos:pos+40]
truth = nearly_true.split(delimiter)[0]
return truth
while True:
zip_code = input('Please type a zip code (5 digits) or "done" if want to stop:\n')
if not check(zip_code):
break
code = get_html(zip_code)
invalid_key = '(0 results)'
if invalid_key in code:
print('\nNot a valid zip code.')
continue
name_key = '<title>'
name_del = ' zip'
name = extract_truth(code, name_key, name_del)
pop_key = 'Total population</dt><dd>'
pop_del = '<'
pop = extract_truth(code, pop_key, pop_del)
if not 1 < len(pop) < 9:
pop = 'not available'
print('\n' + name)
print('Population:', pop, '\n')
```
## Chapter 15
### Exercise 15.1
``` python
import math
class Point(object):
"""represents a point in 2-D space"""
def distance(p1, p2):
distance = math.sqrt((p2.x - p1.x)**2 + (p2.y - p1.y)**2)
return distance
p1 = Point()
p2 = Point()
p1.x = 3
p1.y = 2
p2.x = 4
p2.y = 3
print(distance(p1, p2))
```
### Exercise 15.3
``` python
import copy
def move_rectangle(rec, dx, dy):
""" does a deep copy and return the newRec with changes applied """
newRec = copy.deepcopy(rec)
newRec.corner.x += dx
newRec.corner.y += dy
return newRec
```
## Chapter 16
### Exercise 16.1
``` python
def print_time(t):
print '%.2d:%.2d:%.2d' % (t.hour, t.minute, t.second)
```
or
``` python
# Solution for Python3
# More on string formatting: http://docs.python.org/py3k/library/string.html#formatspec
def print_time(t):
# 0 is a fill character, 2 defines the width
print('{}:{:02}:{:02}'.format(t.hour, t.minute, t.second))
```
### Exercise 16.2
``` python
def is_after(t1, t2):
return (t1.hour, t1.minute, t1.second) > (t2.hour, t2.minute, t2.second)
```
### Exercise 16.3
``` python
# Comment not by the author: This will give a wrong result, if (time.second + seconds % 60) > 60
def increment(time, seconds):
n = seconds/60
time.second += seconds - 60.0*n
time.minute += n
m = time.minute/60
time.minute -= m*60
time.hour += m
```
or
``` python
# Solution for Python3
# Replace '//' by '/' for Python2
def increment(time, seconds):
time.second += seconds
time.minute += time.second//60
time.hour += time.minute//60
time.second %= 60
time.minute %= 60
time.hour %= 24
```
``` python
# A different way of going about it
def increment(time, seconds):
# Converts total to seconds, then back to a readable format
time.second = time.hour*3600 + time.minute*60 + time.second + seconds
(time.minute, time.second) = divmod(time_in_seconds, 60)
(time.hour, time.minute) = divmod(time.minute, 60)
```
### Exercise 16.4
``` python
# Solution for Python3
# Replace '//' by '/' for Python2
from copy import deepcopy
def increment(time, seconds):
r = deepcopy(time)
r.second += seconds
r.minute += r.second//60
r.hour += r.minute//60
r.second %= 60
r.minute %= 60
r.hour %= 24
return r
```
### Exercise 16.5
``` python
class Time(object):
"""represents the time of day.
attributes: hour, minute, second"""
time = Time()
time.hour = 11
time.minute = 59
time.second = 30
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def increment(time, addtime):
seconds = time_to_int(time)
return int_to_time(seconds + addtime)
def print_time (x):
print 'The time is %.2d : %.2d : %.2d' % (x.hour, x.minute, x.second)
print_time (time)
newtime = increment (time, 70)
print_time (newtime)
```
### Exercise 16.6
``` python
def time_to_int(time):
minutes = time.hour * 60 + time.minute
seconds = minutes * 60 + time.second
return seconds
def int_to_time(seconds):
time = Time()
minutes, time.second = divmod(seconds, 60)
time.hour, time.minute = divmod(minutes, 60)
return time
def mul_time(time, factor):
seconds = time_to_int(time)
seconds *= factor
seconds = int(seconds)
return int_to_time(seconds)
def average_pace(time, distance):
return mul_time(time, 1/distance)
```
### Exercise 16.7
Write a class definition for a Date object that has attributes *day*,
*month* and *year*. Write a function called *increment_date* that takes
a Date object, *date*, and an integer, *n*, and returns a new Date
object that represents the day *n* days after *date*. Hint: "Thirty days
hath September\..." Challenge: does your function deal with leap years
correctly? See *wikipedia.org/wiki/Leap_year*.
``` python
class Date(object):
"""represents a date.
attributes: day, month, year"""
def print_date(date):
# German date format
print('{}.{}.{}'.format(date.day, date.month, date.year))
def is_leap_year(year):
# http://en.wikipedia.org/wiki/Leap_year#Algorithm
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
return False
return True
return False
def month_list(year):
if is_leap_year(year):
return [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
return [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
def days_of_year(year):
if is_leap_year(year):
return 366
return 365
def date_to_int(date):
days = 0
for year in range(1, date.year):
days += days_of_year(year)
month_days = month_list(date.year)
for month in range(1, date.month):
days += month_days[month - 1]
days += date.day - 1
return days
def int_to_date(days):
date = Date()
date.year = 1
next_days = 365
while days >= next_days:
date.year += 1
days -= next_days
next_days = days_of_year(date.year)
date.month = 1
next_days = 31
month_days = month_list(date.year)
while days >= next_days:
date.month += 1
days -= next_days
next_days = month_days[date.month - 1]
date.day = days + 1
return date
def increment_date(date, n):
days = date_to_int(date)
return int_to_date(days + n)
d1 = Date()
d1.day, d1.month, d1.year = 8, 3, 2012
print_date(d1)
d2 = increment_date(d1, 7)
print_date(d2)
```
### Exercise 16.8
1\. Use the *datetime* module to write a program that gets the current
date and prints the day of the week.
``` python
from datetime import date
def current_weekday():
i = date.today()
print i.strftime('%A')
current_weekday()
```
2\. Write a program that takes a birthday as input and prints the user's
age and the number of days, hours, minutes and seconds until their next
birthday.
``` python
# Python3 solution. Replace "input" by "raw_input" for Python2.
from datetime import datetime
def time_until_birthday():
dob_input = input(('Please enter the date of your birth in '
'the format "mm/dd/yyyy": '))
dob = datetime.strptime(dob_input, '%m/%d/%Y')
now = datetime.now()
if now > datetime(now.year, dob.month, dob.day):
age = now.year - dob.year
next_year = True
else:
age = now.year - dob.year - 1
next_year = False
time_to_birthday = datetime(now.year + next_year,
dob.month, dob.day) - now
days = time_to_birthday.days
hours, remainder = divmod(time_to_birthday.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
print("\nYou are {} years old.".format(age))
print(("You have {0} days, {1} hours, {2} minutes and {3} "
"seconds left until your next birthday.").format(
days, hours, minutes, seconds))
time_until_birthday()
```
## Chapter 17
### Exercise 17.8
2\.
``` python
from visual import scene, sphere
scene.range = (256, 256, 256)
scene.center = (128, 128, 128)
t = range(0, 256, 51)
for x in t:
for y in t:
for z in t:
pos = x, y, z
color = (x/255., y/255., z/255.)
sphere(pos=pos, radius=10, color=color)
```
3\. Download <http://thinkpython.com/code/color_list.py> and use the
function *read_colors* to generate a list of the available colors on
your system, their names and RGB values. For each named color draw a
sphere in the position that corresponds to its RGB values.
``` python
# As there currently (2013-04-12) is no function read_colors in color_list.py
# I use a workaround and simply import the variable COLORS from color_list.py.
# I then use the function all_colors() on COLORS to get a list of the colors.
from color_list import COLORS
from visual import scene, sphere
def all_colors(colors_string=COLORS):
"""Extract a list of unique RGB-tuples from COLORS.
The tuples look like (r, g, b), where r, g and b are each integers in
[0, 255].
"""
# split the string into lines and remove irrelevant lines
lines = colors_string.split('\n')[2:-2]
# split the individual lines and remove the names
numbers_only = [line.split()[:3] for line in lines]
# turn strings into ints and rgb-lists into tuples
rgb_tuples = [tuple([int(s) for s in lst]) for lst in numbers_only]
# return a list of unique tuples
return list(set(rgb_tuples))
def make_spheres(color_tuples=all_colors()):
scene.range = (256, 256, 256)
scene.center = (128, 128, 128)
for (r, g, b) in color_tuples:
sphere(pos=(r, g, b), radius=7, color=(r/255., g/255., b/255.))
if __name__ == '__main__':
make_spheres()
```
## Chapter 3.5
### calculator
``` python
#recursion or recursive
print "\n INDEX\n""\n C=1 for addition\n""\n C=2 for substraction\n""\n
C=3 for multiplication\n""\n C=4 for division\n""\n C=5 for to find modulus\n""\n C=6 to find factorial\n"
C=input("Enter your choice here: ")
def add(x,y):
c=x+y
print x,"+",y,"=",c
def sub(x,y):
c=x-y
print x,"-",y,"=",c
def mul(x,y):
c=x*y
print x,"*",y,"=",c
def div(x,y):
c=x/y
print x,"/",y,"=",c
def mod(x,y):
c=x%y
print x,"%",y,"=",c
if C==6:
def f(n):
if n==1:
print n
return n
else:
print n,"*",
return n*f(n-1)
n=input("enter your no here: ")
print f(n)
if C==1:
a=input("Enter your first no here: ")
b=input("Enter your second no here: ")
add(a,b)
elif C==2:
a=input("Enter your first no here: ")
b=input("Enter your second no here: ")
sub(a,b)
elif C==3:
a=input("Enter your first no here: ")
b=input("Enter your second no here: ")
mul(a,b)
elif C==4:
a=input("Enter your first no here: ")
b=input("Enter your second no here: ")
div(a,b)
elif C==5:
a=input("Enter your first no here: ")
b=input("Enter your second no here: ")
mod(a,b)
```
### palindrome
``` python
def first(word):
return word[0]
def last(word):return word[-1]
def middle(word):
return word[1:-1]
def palindrome(word):
if first(word)==last(word):
word = middle(word)
n=len(word)
if n<2:
print "palindrome"
else:
return palindrome(word)
else:
print "not palindrome"
word=raw_input("Enter the string:")
palindrome(word)
```
### sum of all digits
``` python
def sum_of_n_numbers(number):
if(number==0):
return 0
else:
return number + sum_of_n_numbers(number-1)
num = raw_input("Enter a number:")
num=int(num)
sum = sum_of_n_numbers(num)
print sum
###another answer in case of while loops
def sum_of_Digits(number):
sum=0
while number>0:
digit=number%10
sum=sum+digit
number=number/10
return sum
num=raw_input("enter the number")
num=int(num)
sum_of_digits=sum_of_Digits(num)
print sum_of_digits
```
### Exercise 18.5
``` python
class Card(object):
suit_names = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
rank_names = [None, 'Ace', '2', '3', '4', '5', '6', '7',
'8', '9', '10', 'Jack', 'Queen', 'King']
def __init__(self, suit = 0, rank = 2):
self.suit = suit
self.rank = rank
def __str__(self):
return '%s of %s' % (Card.rank_names[self.rank],
Card.suit_names[self.suit])
def __cmp__(self, other):
c1 = (self.suit, self.rank)
c2 = (other.suit, other.rank)
return cmp(c1, c2)
def is_valid(self):
return self.rank > 0
class Deck(object):
def __init__(self, label = 'Deck'):
self.label = label
self.cards = []
for i in range(4):
for k in range(1, 14):
card = Card(i, k)
self.cards.append(card)
def __str__(self):
res = []
for card in self.cards:
res.append(str(card))
print self.label
return '\n'.join(res)
def deal_card(self):
return self.cards.pop(0)
def add_card(self, card):
self.cards.append(card)
def shuffle(self):
import random
random.shuffle(self.cards)
def sort(self):
self.cards.sort()
def move_cards(self, other, num):
for i in range(num):
other.add_card(self.deal_card())
def deal_hands(self, num_hands, num_cards):
if num_hands*num_cards > 52:
return 'Not enough cards.'
l = []
for i in range(1, num_hands + 1):
hand_i = Hand('Hand %d' % i)
self.move_cards(hand_i, num_cards)
l.append(hand_i)
return l
class Hand(Deck):
def __init__(self, label = ''):
self.cards = []
self.label = label
# 18-6, 1-4:
class PokerHand(Hand):
def suit_hist(self):
self.suits = {}
for card in self.cards:
self.suits[card.suit] = self.suits.get(card.suit, 0) + 1
return self.suits
def rank_hist(self):
self.ranks = {}
for card in self.cards:
self.ranks[card.rank] = self.ranks.get(card.rank, 0) + 1
return self.ranks
def P(self):
self.rank_hist()
for val in self.ranks.values():
if val >= 2:
return True
return False
def TP(self):
self.rank_hist()
count = 0
for val in self.ranks.values():
if val == 4:
return True
elif val >= 2 and val < 4:
count += 1
return count >= 2
def TOAK(self):
self.rank_hist()
for val in self.ranks.values():
if val >= 3:
return True
return False
def STRseq(self):
seq = []
l = STRlist()
self.rank_hist()
h = self.ranks.keys()
h.sort()
if len(h) < 5:
return []
# Accounts for high Aces:
if 1 in h:
h.append(1)
for i in range(5, len(h)+1):
if h[i-5:i] in l:
seq.append(h[i-5:i])
return seq
def STR(self):
seq = self.STRseq()
return seq != []
def FL(self):
self.suit_hist()
for val in self.suits.values():
if val >= 5:
return True
return False
def FH(self):
d = self.rank_hist()
keys = d.keys()
for key in keys:
if d[key] >= 3:
keys.remove(key)
for key in keys:
if d[key] >= 2:
return True
return False
def FOAK(self):
self.rank_hist()
for val in self.ranks.values():
if val >= 4:
return True
return False
def SFL(self):
seq = self.STRseq()
if seq == []:
return False
for list in seq:
list_suits = []
for index in list:
for card in self.cards:
if card.rank == index:
list_suits.append(card.suit)
list_hist = histogram(list_suits)
for key in list_hist.keys():
if list_hist[key] >= 5:
return True
return False
def classify(self):
self.scores = []
hands = ['Pair', 'Two-Pair',
'Three of a Kind', 'Straight',
'Flush', 'Full House',
'Four of a Kind', 'Straight Flush']
if self.P():
self.scores.append(1)
if self.TP():
self.scores.append(2)
if self.TOAK():
self.scores.append(3)
if self.STR():
self.scores.append(4)
if self.FL():
self.scores.append(5)
if self.FH():
self.scores.append(6)
if self.FOAK():
self.scores.append(7)
if self.SFL():
self.scores.append(8)
if self.scores != []:
return hands[max(self.scores)-1]
def STRlist():
s = []
for i in range(0,9):
s.append(range(1,14)[i:i+5])
s.append([10,11,12,13,1])
return s
def histogram(l):
d = dict()
for k in range(len(l)):
d[l[k]] = 1 + d.get(l[k],0)
return d
# 18-6, 5:
def p(config = '', trials = 10000, n = 1):
"""Estimates probability that the
nth dealt hand will be config. A hand
consists of seven cards."""
successes = 0
for i in range(1, trials + 1):
deck = Deck('Deck %d' % i)
deck.shuffle()
box = Hand()
deck.move_cards(box, (n-1)*7)
hand = PokerHand('Poker Hand %d' % i)
deck.move_cards(hand, 7)
if hand.classify() == config:
successes += 1
return 1.0*successes/trials
#Iterate until first desired config.:
if __name__ == '__main__':
c = 1
while True:
deck = Deck()
deck.shuffle()
hand = PokerHand('Poker Hand %d' % c)
deck.move_cards(hand, 5)
print hand
print hand.SFL()
if hand.SFL():
print hand.STRseq()
break
print ''
c += 1
Code by Victor Alvarez
```
## Appendix B
### Exercise B.1
Read the Wikipedia page on Big-Oh notation and answer the following
questions:
1\. *What is the order of growth of n³ + n²? What about 1000000n³ + n²?
What about n³ + 1000000n²?*
: A: All are O(n³)
2\. *What is the order of growth of (n² + n) · (n + 1)? Before you start
multiplying, remember that you only need the leading term.*
: A: O(n³)
3\. *If f is in O(g), for some unspecified function g, what can we say
about af + b, where a and b are constants?*
: A: a and b are also O(g) since O-notation uses the leading
coefficient. Constants are O(1), so they are irrelevant in this
case.
4\. \'\'If f1 and f2 are in O(g), what can we say about f1 + f2?
: A: Assuming the author means that g in this problem is separate from
g the last problem, then O(g) remains unchanged.
5\. *If f1 is in O(g) and f2 is in O(h), what can we say about f1 + f2?*
: A: f1 + f2 may or may not match the higher order of growth of either
O(g) and O(h). If f1 or f2 are the leading coefficients, then f1 +
f2 will have the same order of growth as the the largest order of
growth of either O(g) or O(h). If that is not the case, then any
information about order of growth of f1 + f2 is unknown to us. i.e.
It doesn\'t matter that they are being added.
6\. *If f1 is in O(g) and f2 is O(h), what can we say about f1 · f2?*
: A: This is different. If f1 and f2 are multiplied (and assuming they
each contain an n in them) then O(f1 · f2) has to be O(n) or larger.
It could be larger if f1 is n³, for example, but it must at least be
O(n).
### Exercise B.3
Write a function called *bisection* that takes a sorted list and a
target value and returns the index of the value in the list, if it's
there, or *None* if it's not.
``` python
from bisect import bisect_left
def bisection(sorted_list, item):
i = bisect_left(sorted_list, item)
if i < len(sorted_list) and sorted_list[i] == item:
return i
else:
return None
if __name__ == '__main__':
a = [1, 2, 3]
print(bisection(a, 2)) # expect 1
b = [1, 3]
print(bisection(b, 2)) # expect None
c = [1, 2]
print(bisection(c, 3)) # expect None
```
|
# Think Python/Index
## Index
```{=html}
<TABLE CELLSPACING=6 CELLPADDING=0>
```
```{=html}
<TR>
```
```{=html}
<TD VALIGN=top ALIGN=left>
```
-
Ackerman function, 6.11
- AttributeError, 15.7, A.2.3
```{=html}
<!-- -->
```
- Austin, Jane, 13.3
```{=html}
<!-- -->
```
- abecedarian, 8.3, 9.2
```{=html}
<!-- -->
```
- abs function, 6.1
```{=html}
<!-- -->
```
- absolute path, 14.4, 14.11
```{=html}
<!-- -->
```
- access, 10.2
```{=html}
<!-- -->
```
- accumulator, 10.14
```{=html}
<!-- -->
```
-
histogram, 13.3
- list, 10.7
```{=html}
<!-- -->
```
- string, 18.5
```{=html}
<!-- -->
```
- sum, 10.7
```{=html}
<!-- -->
```
- add method, 17.7
```{=html}
<!-- -->
```
- addition with carrying, 7.6
```{=html}
<!-- -->
```
- algorithm, 1.2, 1.7, 7.6, 13.7
```{=html}
<!-- -->
```
-
Euclid, 6.11
- MD5, 14.12
```{=html}
<!-- -->
```
- RSA, 11.7
```{=html}
<!-- -->
```
- square root, 7.9
```{=html}
<!-- -->
```
- aliasing, 10.10, 10.11, 10.14, 15.2, 15.6, 17.12
```{=html}
<!-- -->
```
-
copying to avoid, 10.13
- alphabet, 4.12
```{=html}
<!-- -->
```
- alternative execution, 5.5
```{=html}
<!-- -->
```
- ambiguity, 1.4
```{=html}
<!-- -->
```
- anagram, 10.15
```{=html}
<!-- -->
```
- anagram set, 12.11, 14.7
```{=html}
<!-- -->
```
- and operator, 5.3
```{=html}
<!-- -->
```
- anydbm module, 14.6
```{=html}
<!-- -->
```
- append method, 10.6, 10.12, 10.15, 18.4, 18.6
```{=html}
<!-- -->
```
- arc function, 4.3
```{=html}
<!-- -->
```
- argument, 3.1, 3.5, 3.8, 3.8, 3.14, 10.12
```{=html}
<!-- -->
```
-
gather, 12.4
- keyword, 4.5, 4.11, 12.7, 19.2
```{=html}
<!-- -->
```
- list, 10.12
```{=html}
<!-- -->
```
- optional, 8.8, 10.9, 11.3
```{=html}
<!-- -->
```
- variable-length tuple, 12.4
```{=html}
<!-- -->
```
- argument scatter, 12.4
```{=html}
<!-- -->
```
- arithmetic operator, 2.5
```{=html}
<!-- -->
```
- assert statement, 16.5
```{=html}
<!-- -->
```
- assignment, 2.11, 7.1, 10.1
```{=html}
<!-- -->
```
-
item, 8.5, 10.2, 12.1
- multiple, 7.8, 11.6
```{=html}
<!-- -->
```
- tuple, 12.2, 12.3, 12.5, 12.10
```{=html}
<!-- -->
```
- assignment statement, 2.2
```{=html}
<!-- -->
```
- attribute
```{=html}
<!-- -->
```
-
\_\_dict\_\_, 17.10
- class, 18.2, 18.10
```{=html}
<!-- -->
```
- initializing, 17.10
```{=html}
<!-- -->
```
- instance, 15.2, 15.8, 18.2, 18.10
```{=html}
<!-- -->
```
- available colors, 15.9, 17.12
\
\
- Bacon, Kevin, 14.12
```{=html}
<!-- -->
```
- Bangladesh, national flag, 15.9
```{=html}
<!-- -->
```
- Button widget, 19.2
```{=html}
<!-- -->
```
- base case, 5.9, 5.13
```{=html}
<!-- -->
```
- benchmarking, 13.9, 13.11
```{=html}
<!-- -->
```
- big, hairy expression, A.3.2
```{=html}
<!-- -->
```
- binding, 19.8, 19.10
```{=html}
<!-- -->
```
- bingo, 12.11
```{=html}
<!-- -->
```
- birthday, 16.7
```{=html}
<!-- -->
```
- birthday paradox, 10.15
```{=html}
<!-- -->
```
- bisect module, 10.15
```{=html}
<!-- -->
```
- bisection search, 10.15
```{=html}
<!-- -->
```
- bisection, debugging by, 7.7
```{=html}
<!-- -->
```
- bitwise operator, 2.5
```{=html}
<!-- -->
```
- body, 3.5, 3.14, 5.13, 7.3
```{=html}
<!-- -->
```
- bool type, 5.2
```{=html}
<!-- -->
```
- boolean expression, 5.2, 5.13
```{=html}
<!-- -->
```
- boolean function, 6.4, 16.1
```{=html}
<!-- -->
```
- boolean operator, 8.9
```{=html}
<!-- -->
```
- borrowing, subtraction with, 7.6, 16.4
```{=html}
<!-- -->
```
- bound method, 19.6, 19.10
```{=html}
<!-- -->
```
- bounding box, 15.9, 19.4, 19.10
```{=html}
<!-- -->
```
- bracket
```{=html}
<!-- -->
```
-
squiggly, 11
- bracket operator, 8.1, 10.2, 12.1
```{=html}
<!-- -->
```
- branch, 5.5, 5.13
```{=html}
<!-- -->
```
- break statement, 7.4
```{=html}
<!-- -->
```
- bug, 1.3, 1.3, 1.7
```{=html}
<!-- -->
```
-
worst, 17.12
- worst ever, 19.11
\
\
- Callable object, 19.7
```{=html}
<!-- -->
```
- Canvas coordinate, 19.3, 19.8
```{=html}
<!-- -->
```
- Canvas item, 19.3
```{=html}
<!-- -->
```
- Canvas object, 15.9
```{=html}
<!-- -->
```
- Canvas widget, 19.3
```{=html}
<!-- -->
```
- Car Talk, 9.7, 9.7, 9.7, 11.10, 12.11
```{=html}
<!-- -->
```
- Card class, 18.1
```{=html}
<!-- -->
```
- Collatz conjecture, 7.3
```{=html}
<!-- -->
```
- Czech Republic, national flag, 15.9
```{=html}
<!-- -->
```
- calculator, 1.8, 2.12
```{=html}
<!-- -->
```
- call graph, 11.5, 11.9
```{=html}
<!-- -->
```
- callback, 19.2, 19.6, 19.7, 19.8, 19.9, 19.10
```{=html}
<!-- -->
```
- card, playing, 18
```{=html}
<!-- -->
```
- carrying, addition with, 7.6, 16.2, 16.4
```{=html}
<!-- -->
```
- case-sensitivity, variable names, 2.10
```{=html}
<!-- -->
```
- catch, 14.11
```{=html}
<!-- -->
```
- chained conditional, 5.6, 5.13
```{=html}
<!-- -->
```
- character, 8.1
```{=html}
<!-- -->
```
- checksum, 14.12
```{=html}
<!-- -->
```
- child class, 18.7, 18.10
```{=html}
<!-- -->
```
- choice function, 13.2
```{=html}
<!-- -->
```
- circle function, 4.3
```{=html}
<!-- -->
```
- circular definition, 6.5
```{=html}
<!-- -->
```
- class, 15.1, 15.8
```{=html}
<!-- -->
```
-
Card, 18.1
- Date, 16.7
```{=html}
<!-- -->
```
- Deck, 18.4
```{=html}
<!-- -->
```
- Hand, 18.7
```{=html}
<!-- -->
```
- Kangaroo, 17.12
```{=html}
<!-- -->
```
- Point, 15.1, 17.5
```{=html}
<!-- -->
```
- parent, 18.7
```{=html}
<!-- -->
```
- Rectangle, 15.3
```{=html}
<!-- -->
```
- SimpleTurtleWorld, 19.6
```{=html}
<!-- -->
```
- Time, 16.1
```{=html}
<!-- -->
```
- class attribute, 18.2, 18.10
```{=html}
<!-- -->
```
- class definition, 15.1
```{=html}
<!-- -->
```
- class diagram, 18.8, 18.10
```{=html}
<!-- -->
```
- class object, 15.1, 15.8
```{=html}
<!-- -->
```
- close method, 14.2, 14.6, 14.8
```{=html}
<!-- -->
```
- cmp function, 18.3
```{=html}
<!-- -->
```
- \_\_cmp\_\_ method, 18.3
```{=html}
<!-- -->
```
- colon, 3.5, A.1
```{=html}
<!-- -->
```
- color list, 15.9, 17.12
```{=html}
<!-- -->
```
- comment, 2.9, 2.11
```{=html}
<!-- -->
```
- commutativity, 2.8, 17.8
```{=html}
<!-- -->
```
- compare function, 6.1
```{=html}
<!-- -->
```
- comparison
```{=html}
<!-- -->
```
-
string, 8.10
- tuple, 12.7, 18.3
```{=html}
<!-- -->
```
- comparison operator, 5.2
```{=html}
<!-- -->
```
- compile, 1.1, 1.7
```{=html}
<!-- -->
```
- composition, 3.4, 3.8, 3.14, 6.3, 18.4
```{=html}
<!-- -->
```
- compound statement, 5.4, 5.13
```{=html}
<!-- -->
```
- compression
```{=html}
<!-- -->
```
-
file, 14.8
- concatenation, 2.8, 2.11, 3.9, 8.3, 8.5, 10.9
```{=html}
<!-- -->
```
-
list, 10.4, 10.12, 10.15
- condition, 5.4, 5.13, 7.3, A.2.2
```{=html}
<!-- -->
```
- conditional, A.1
```{=html}
<!-- -->
```
-
chained, 5.6, 5.13
- nested, 5.7, 5.13
```{=html}
<!-- -->
```
- conditional execution, 5.4
```{=html}
<!-- -->
```
- conditional operator, 18.3
```{=html}
<!-- -->
```
- conditional statement, 5.4, 5.13, 6.4
```{=html}
<!-- -->
```
- config method, 19.3
```{=html}
<!-- -->
```
- consistency check, 11.8, 16.4
```{=html}
<!-- -->
```
- contributors, 0
```{=html}
<!-- -->
```
- conversion
```{=html}
<!-- -->
```
-
type, 3.2
- coordinate
```{=html}
<!-- -->
```
-
Canvas, 19.3, 19.8
- pixel, 19.8
```{=html}
<!-- -->
```
- coordinate sequence, 19.4
```{=html}
<!-- -->
```
- copy
```{=html}
<!-- -->
```
-
deep, 15.6
- shallow, 15.6
```{=html}
<!-- -->
```
- slice, 8.4, 10.5
```{=html}
<!-- -->
```
- to avoid aliasing, 10.13
```{=html}
<!-- -->
```
- copy module, 15.6
```{=html}
<!-- -->
```
- copying objects, 15.6
```{=html}
<!-- -->
```
- count method, 8.8
```{=html}
<!-- -->
```
- counter, 8.7, 8.12, 11.1, 11.6
```{=html}
<!-- -->
```
- counting and looping, 8.7
```{=html}
<!-- -->
```
- crosswords, 9.1
```{=html}
<!-- -->
```
- cummings, e. e., 1.3.1
```{=html}
<!-- -->
```
- cumulative sum, 10.7
\
\
- Date class, 16.7
```{=html}
<!-- -->
```
- Deck class, 18.4
```{=html}
<!-- -->
```
- Dijkstra, Edsger, 9.5
```{=html}
<!-- -->
```
- Doyle, Arthur Conan, 1.3.4
```{=html}
<!-- -->
```
- DSU pattern, 12.7, 12.10, 13.4
```{=html}
<!-- -->
```
- data structure, 12.9, 12.10, 13.9
```{=html}
<!-- -->
```
- database, 14.6, 14.11, 14.12
```{=html}
<!-- -->
```
- datetime module, 16.7
```{=html}
<!-- -->
```
- dead code, 6.1, 6.10, A.2.4
```{=html}
<!-- -->
```
- debugger (pdb), A.2.3
```{=html}
<!-- -->
```
- debugging, 1.3, 1.3, 1.6, 1.7, 2.10, 3.13, 4.10, 5.12, 6.9, 8.11,
9.5, 10.13, 11.8, 12.9, 13.10, 14.10, 15.7, 16.5, 17.10, 18.9, 19.9,
A
```{=html}
<!-- -->
```
-
by bisection, 7.7
- emotional response, 1.6, A.3.4
```{=html}
<!-- -->
```
- experimental, 1.3.4
```{=html}
<!-- -->
```
- superstition, A.3.4
```{=html}
<!-- -->
```
- deck, playing cards, 18.4
```{=html}
<!-- -->
```
- declaration, 11.6, 11.9
```{=html}
<!-- -->
```
- decorate-sort-undecorate pattern, 12.7
```{=html}
<!-- -->
```
- decrement, 7.2, 7.8
```{=html}
<!-- -->
```
- deep copy, 15.6, 15.8
```{=html}
<!-- -->
```
- deepcopy function, 15.6
```{=html}
<!-- -->
```
- def keyword, 3.5
```{=html}
<!-- -->
```
- default value, 13.5, 13.11, 17.5
```{=html}
<!-- -->
```
-
avoiding mutable, 17.12
- definition
```{=html}
<!-- -->
```
-
circular, 6.5
- class, 15.1
```{=html}
<!-- -->
```
- function, 3.5
```{=html}
<!-- -->
```
- recursive, 12.11
```{=html}
<!-- -->
```
- del operator, 10.8
```{=html}
<!-- -->
```
- deletion, element of list, 10.8
```{=html}
<!-- -->
```
- delimiter, 10.9, 10.14
```{=html}
<!-- -->
```
- deterministic, 13.2, 13.11
```{=html}
<!-- -->
```
- development plan, 4.11
```{=html}
<!-- -->
```
-
encapsulation and generalization, 4.8
- incremental, 6.2, A.1
```{=html}
<!-- -->
```
- planned, 16.4
```{=html}
<!-- -->
```
- problem recognition, 9.3, 9.4
```{=html}
<!-- -->
```
- prototype and patch, 16.2, 16.4
```{=html}
<!-- -->
```
- random walk programming, 13.10, A.3.4
```{=html}
<!-- -->
```
- diagram
```{=html}
<!-- -->
```
-
call graph, 11.9
- class, 18.8, 18.10
```{=html}
<!-- -->
```
- object, 15.2, 15.3, 15.6, 15.8, 16.1, 18.2
```{=html}
<!-- -->
```
- stack, 3.10, 10.12
```{=html}
<!-- -->
```
- state, 2.2, 7.1, 8.11, 10.2, 10.10, 10.11, 11.4, 12.6, 15.2, 15.3,
15.6, 16.1, 18.2
```{=html}
<!-- -->
```
- \_\_dict\_\_ attribute, 17.10
```{=html}
<!-- -->
```
- dict function, 11
```{=html}
<!-- -->
```
- dictionary, 11, 11, 11.9, 12.6, A.2.3
```{=html}
<!-- -->
```
-
initialize, 12.6
- invert, 11.4
```{=html}
<!-- -->
```
- lookup, 11.3
```{=html}
<!-- -->
```
- looping with, 11.2
```{=html}
<!-- -->
```
- reverse lookup, 11.3
```{=html}
<!-- -->
```
- subtraction, 13.6
```{=html}
<!-- -->
```
- traversal, 12.6, 17.10
```{=html}
<!-- -->
```
- dictionary methods
```{=html}
<!-- -->
```
-
anydbm module, 14.6
- directory, 14.4, 14.11
```{=html}
<!-- -->
```
-
walk, 14.4
- working, 14.4
```{=html}
<!-- -->
```
- dispatch
```{=html}
<!-- -->
```
-
type-based, 17.9
- dispatch, type-based, 17.8
```{=html}
<!-- -->
```
- divisibility, 5.1
```{=html}
<!-- -->
```
- division
```{=html}
<!-- -->
```
-
floating-point, 2.5
- floor, 2.5, 5.12
```{=html}
<!-- -->
```
- divmod, 12.3, 16.4
```{=html}
<!-- -->
```
- docstring, 4.9, 4.11, 15.1
```{=html}
<!-- -->
```
- documentation, 1.8
```{=html}
<!-- -->
```
- dot notation, 3.3, 3.14, 8.8, 15.2, 17.2, 18.2
```{=html}
<!-- -->
```
- double letters, 9.7
```{=html}
<!-- -->
```
- drag-and-drop, 19.8
```{=html}
<!-- -->
```
- duplicate, 10.15, 10.15, 11.10, 14.12
\
\
- Einstein, Albert, 4.6
```{=html}
<!-- -->
```
- Entry widget, 19.5
```{=html}
<!-- -->
```
- Euclid's algorithm, 6.11
```{=html}
<!-- -->
```
- Event object, 19.8
```{=html}
<!-- -->
```
- element, 10.1, 10.14
```{=html}
<!-- -->
```
- element deletion, 10.8
```{=html}
<!-- -->
```
- elif keyword, 5.6
```{=html}
<!-- -->
```
- ellipses, 3.5
```{=html}
<!-- -->
```
- else keyword, 5.5
```{=html}
<!-- -->
```
- email address, 12.2
```{=html}
<!-- -->
```
- embedded object, 15.3, 15.8, 17.12
```{=html}
<!-- -->
```
-
copying, 15.6
- emotional debugging, 1.6, A.3.4
```{=html}
<!-- -->
```
- empty list, 10.1
```{=html}
<!-- -->
```
- empty string, 8.12, 10.9
```{=html}
<!-- -->
```
- encapsulation, 4.4, 4.11, 6.3, 7.5, 8.7, 18.7
```{=html}
<!-- -->
```
- encode, 18.1, 18.10
```{=html}
<!-- -->
```
- encrypt, 18.1
```{=html}
<!-- -->
```
- encryption, 11.7
```{=html}
<!-- -->
```
- end of line character, 14.10
```{=html}
<!-- -->
```
- enumerate function, 12.5
```{=html}
<!-- -->
```
- epsilon, 7.5
```{=html}
<!-- -->
```
- equality and assignment, 7.1
```{=html}
<!-- -->
```
- equivalence, 10.10
```{=html}
<!-- -->
```
- equivalent, 10.14
```{=html}
<!-- -->
```
- error
```{=html}
<!-- -->
```
-
compile-time, A
- runtime, 1.3.2, 2.10, 5.10, 5.12, A
```{=html}
<!-- -->
```
- semantic, 1.3.3, 2.1, 2.10, 8.11, A, A.3
```{=html}
<!-- -->
```
- shape, 12.9
```{=html}
<!-- -->
```
- syntax, 1.3.1, 2.10, A
```{=html}
<!-- -->
```
- error checking, 6.8
```{=html}
<!-- -->
```
- error message, 1.3.1, 1.3.3, 1.6, 2.1, 2.10, A.1
```{=html}
<!-- -->
```
- eval function, 7.9
```{=html}
<!-- -->
```
- evaluate, 2.6
```{=html}
<!-- -->
```
- event, 19.10
```{=html}
<!-- -->
```
- event handler, 19.8
```{=html}
<!-- -->
```
- event loop, 19.1, 19.10
```{=html}
<!-- -->
```
- event string, 19.8
```{=html}
<!-- -->
```
- event-driven programming, 19.2, 19.9, 19.10
```{=html}
<!-- -->
```
- exception, 1.3.2, 1.7, 2.10, A, A.2.3
```{=html}
<!-- -->
```
-
AttributeError, 15.7, A.2.3
- IndexError, 8.2, 8.11, 10.2, A.2.3
```{=html}
<!-- -->
```
- IOError, 14.5
```{=html}
<!-- -->
```
- KeyError, 11, A.2.3
```{=html}
<!-- -->
```
- NameError, 3.9, A.2.3
```{=html}
<!-- -->
```
- OverflowError, 5.12
```{=html}
<!-- -->
```
- RuntimeError, 5.10
```{=html}
<!-- -->
```
- SyntaxError, 3.4
```{=html}
<!-- -->
```
- TypeError, 8.1, 8.5, 11.4, 12.1, 12.4, 14.3, 17.3, A.2.3
```{=html}
<!-- -->
```
- UnboundLocalError, 11.6
```{=html}
<!-- -->
```
- ValueError, 5.11, 11.3, 12.2
```{=html}
<!-- -->
```
- exception, catching, 14.5
```{=html}
<!-- -->
```
- executable, 1.1, 1.7
```{=html}
<!-- -->
```
- exercise, secret, 14.12
```{=html}
<!-- -->
```
- exists function, 14.4
```{=html}
<!-- -->
```
- experimental debugging, 1.3.4, 13.10
```{=html}
<!-- -->
```
- expression, 2.5, 2.6, 2.11
```{=html}
<!-- -->
```
-
big and hairy, A.3.2
- boolean, 5.2, 5.13
```{=html}
<!-- -->
```
- extend method, 10.6
\
\
- False special value, 5.2
```{=html}
<!-- -->
```
- Fermat's Last Theorem, 5.14
```{=html}
<!-- -->
```
- Frame widget, 19.6
```{=html}
<!-- -->
```
- Free Documentation License, GNU, 0, 0
```{=html}
<!-- -->
```
- factorial function, 6.5, 6.8
```{=html}
<!-- -->
```
- fibonacci function, 6.7, 11.5
```{=html}
<!-- -->
```
- file, 14
```{=html}
<!-- -->
```
-
compression, 14.8
- permission, 14.5
```{=html}
<!-- -->
```
- reading and writing, 14.2
```{=html}
<!-- -->
```
- file object, 9.1, 9.6
```{=html}
<!-- -->
```
- filename, 14.4
```{=html}
<!-- -->
```
- filter pattern, 10.7, 10.14
```{=html}
<!-- -->
```
- find function, 8.6
```{=html}
<!-- -->
```
- flag, 11.6, 11.9
```{=html}
<!-- -->
```
- float function, 3.2
```{=html}
<!-- -->
```
- float type, 2.1
```{=html}
<!-- -->
```
- floating-point, 2.11, 7.5
```{=html}
<!-- -->
```
- floating-point division, 2.5
```{=html}
<!-- -->
```
- floor division, 2.5, 2.11, 5.12
```{=html}
<!-- -->
```
- flow of execution, 3.7, 3.14, 6.7, 6.9, 7.3, 18.9, 19.9, A.2.2
```{=html}
<!-- -->
```
- flower, 4.12
```{=html}
<!-- -->
```
- folder, 14.4
```{=html}
<!-- -->
```
- for loop, 4.2, 8.3, 10.3, 12.5
```{=html}
<!-- -->
```
- formal language, 1.4, 1.7
```{=html}
<!-- -->
```
- format operator, 14.3, 14.11, A.2.3
```{=html}
<!-- -->
```
- format sequence, 14.3, 14.11
```{=html}
<!-- -->
```
- format string, 14.3, 14.11
```{=html}
<!-- -->
```
- frabjuous, 6.5
```{=html}
<!-- -->
```
- frame, 3.10, 3.14, 5.9, 6.5, 11.5
```{=html}
<!-- -->
```
- frequency, 11.1
```{=html}
<!-- -->
```
-
letter, 12.11
- word, 13.1, 13.12
```{=html}
<!-- -->
```
- fruitful function, 3.11, 3.14
```{=html}
<!-- -->
```
- frustration, A.3.4
```{=html}
<!-- -->
```
- function, 3.5, 3.14, 17.1
```{=html}
<!-- -->
```
-
abs, 6.1
- ack, 6.11
```{=html}
<!-- -->
```
- arc, 4.3
```{=html}
<!-- -->
```
- choice, 13.2
```{=html}
<!-- -->
```
- circle, 4.3
```{=html}
<!-- -->
```
- cmp, 18.3
```{=html}
<!-- -->
```
- compare, 6.1
```{=html}
<!-- -->
```
- deepcopy, 15.6
```{=html}
<!-- -->
```
- dict, 11
```{=html}
<!-- -->
```
- enumerate, 12.5
```{=html}
<!-- -->
```
- eval, 7.9
```{=html}
<!-- -->
```
- exists, 14.4
```{=html}
<!-- -->
```
- factorial, 6.5
```{=html}
<!-- -->
```
- fibonacci, 6.7, 11.5
```{=html}
<!-- -->
```
- find, 8.6
```{=html}
<!-- -->
```
- float, 3.2
```{=html}
<!-- -->
```
- getattr, 17.10
```{=html}
<!-- -->
```
- getcwd, 14.4
```{=html}
<!-- -->
```
- hasattr, 15.7, 17.10
```{=html}
<!-- -->
```
- int, 3.2
```{=html}
<!-- -->
```
- isinstance, 6.8, 17.8
```{=html}
<!-- -->
```
- len, 3.15, 8.2, 11
```{=html}
<!-- -->
```
- list, 10.9
```{=html}
<!-- -->
```
- log, 3.3
```{=html}
<!-- -->
```
- max, 12.3, 12.4
```{=html}
<!-- -->
```
- min, 12.3, 12.4
```{=html}
<!-- -->
```
- open, 9.1, 9.1, 14.2, 14.5, 14.6
```{=html}
<!-- -->
```
- polygon, 4.3
```{=html}
<!-- -->
```
- popen, 14.8
```{=html}
<!-- -->
```
- randint, 10.15, 13.2
```{=html}
<!-- -->
```
- random, 12.7, 13.2
```{=html}
<!-- -->
```
- raw_input, 5.11
```{=html}
<!-- -->
```
- recursive, 5.8
```{=html}
<!-- -->
```
- reload, 14.9, A.1.1
```{=html}
<!-- -->
```
- repr, 14.10
```{=html}
<!-- -->
```
- reversed, 12.8
```{=html}
<!-- -->
```
- shuffle, 18.6
```{=html}
<!-- -->
```
- sorted, 12.8
```{=html}
<!-- -->
```
- sqrt, 3.3, 6.2
```{=html}
<!-- -->
```
- str, 3.2
```{=html}
<!-- -->
```
- sum, 12.4
```{=html}
<!-- -->
```
- tuple, 12.1
```{=html}
<!-- -->
```
- type, 15.7
```{=html}
<!-- -->
```
- zip, 12.5
```{=html}
<!-- -->
```
- function argument, 3.8
```{=html}
<!-- -->
```
- function call, 3.1, 3.14
```{=html}
<!-- -->
```
- function composition, 6.3
```{=html}
<!-- -->
```
- function definition, 3.5, 3.6, 3.14, 3.14
```{=html}
<!-- -->
```
- function frame, 3.10, 3.14, 5.9, 11.5
```{=html}
<!-- -->
```
- function object, 3.5, 3.15
```{=html}
<!-- -->
```
- function parameter, 3.8
```{=html}
<!-- -->
```
- function syntax, 17.2
```{=html}
<!-- -->
```
- function type
```{=html}
<!-- -->
```
-
modifier, 16.3
- pure, 16.2
```{=html}
<!-- -->
```
- function, fruitful, 3.11
```{=html}
<!-- -->
```
- function, math, 3.3
```{=html}
<!-- -->
```
- function, reasons for, 3.12
```{=html}
<!-- -->
```
- function, trigonometric, 3.3
```{=html}
<!-- -->
```
- function, tuple as return value, 12.3
```{=html}
<!-- -->
```
- function, void, 3.11
```{=html}
<!-- -->
```
- functional programming style, 16.3, 16.6
\
\
- GCD (greatest common divisor), 6.11
```{=html}
<!-- -->
```
- GNU Free Documentation License, 0, 0
```{=html}
<!-- -->
```
- GUI, 19.1, 19.10
```{=html}
<!-- -->
```
- Gui module, 19.1
```{=html}
<!-- -->
```
- gamma function, 6.8
```{=html}
<!-- -->
```
- gather, 12.4, 12.10
```{=html}
<!-- -->
```
- generalization, 4.5, 4.11, 9.3, 16.4
```{=html}
<!-- -->
```
- geometry manager, 19.6, 19.10
```{=html}
<!-- -->
```
- get method, 11.1
```{=html}
<!-- -->
```
- getattr function, 17.10
```{=html}
<!-- -->
```
- getcwd function, 14.4
```{=html}
<!-- -->
```
- global statement, 11.6
```{=html}
<!-- -->
```
- global variable, 11.6, 11.9
```{=html}
<!-- -->
```
-
update, 11.6
- graphical user interface, 19.1
```{=html}
<!-- -->
```
- greatest common divisor (GCD), 6.11
```{=html}
<!-- -->
```
- grid, 3.15
```{=html}
<!-- -->
```
- guardian pattern, 6.8, 6.10, 8.11
```{=html}
<!-- -->
```
- gzip (Unix command), 14.8
\
\
- HAS-A relationship, 18.8, 18.10
```{=html}
<!-- -->
```
- Hand class, 18.7
```{=html}
<!-- -->
```
- Hello, World, 1.5
```{=html}
<!-- -->
```
- Holmes, Sherlock, 1.3.4
```{=html}
<!-- -->
```
- HTMLParser module, 19.11
```{=html}
<!-- -->
```
- hanging, A.2.2
```{=html}
<!-- -->
```
- hasattr function, 15.7, 17.10
```{=html}
<!-- -->
```
- hash function, 11.4, 11.9
```{=html}
<!-- -->
```
- hashable, 11.4, 11.9, 12.6
```{=html}
<!-- -->
```
- hashtable, 11, 11.9
```{=html}
<!-- -->
```
- header, 3.5, 3.14, A.1
```{=html}
<!-- -->
```
- help utility, 1.8
```{=html}
<!-- -->
```
- hexadecimal, 15.1
```{=html}
<!-- -->
```
- high-level language, 1.1, 1.7
```{=html}
<!-- -->
```
- histogram, 11.1, 11.1, 11.9
```{=html}
<!-- -->
```
-
random choice, 13.2, 13.7
- word frequencies, 13.3
```{=html}
<!-- -->
```
- homophone, 11.10
```{=html}
<!-- -->
```
- hyperlink, 19.11
```{=html}
<!-- -->
```
- hypotenuse, 6.2
\
\
- IMDb (Internet Movie Database), 14.12
```{=html}
<!-- -->
```
- Image module, 19.11
```{=html}
<!-- -->
```
- IndexError, 8.2, 8.11, 10.2, A.2.3
```{=html}
<!-- -->
```
- Internet Movie Database (IMDb), 14.12
```{=html}
<!-- -->
```
- IOError, 14.5
```{=html}
<!-- -->
```
- IS-A relationship, 18.8, 18.10
```{=html}
<!-- -->
```
- identical, 10.14
```{=html}
<!-- -->
```
- identity, 10.10
```{=html}
<!-- -->
```
- if statement, 5.4
```{=html}
<!-- -->
```
- image viewer, 19.11
```{=html}
<!-- -->
```
- immutability, 8.5, 8.5, 8.12, 10.11, 11.4, 12.1, 12.8
```{=html}
<!-- -->
```
- implementation, 11.1, 11.9, 13.9
```{=html}
<!-- -->
```
- import statement, 3.14, 4.1, 14.9
```{=html}
<!-- -->
```
- in operator, 8.9, 9.3, 10.2, 11
```{=html}
<!-- -->
```
- increment, 7.2, 7.8, 16.3, 17.3
```{=html}
<!-- -->
```
- incremental development, 6.10, A.1
```{=html}
<!-- -->
```
- indentation, 3.5, 17.2, A.1
```{=html}
<!-- -->
```
- index, 8.1, 8.1, 8.11, 8.12, 10.2, 10.14, 11, A.2.3
```{=html}
<!-- -->
```
-
looping with, 9.4, 10.3
- negative, 8.2
```{=html}
<!-- -->
```
- slice, 8.4, 10.5
```{=html}
<!-- -->
```
- starting at zero, 8.1, 10.2
```{=html}
<!-- -->
```
- infinite loop, 7.3, 7.8, 19.1, A.2.2, A.2.2
```{=html}
<!-- -->
```
- infinite recursion, 5.10, 5.13, 6.8, A.2.2, A.2.2
```{=html}
<!-- -->
```
- inheritance, 18.7, 18.10
```{=html}
<!-- -->
```
- init method, 17.5, 17.10, 18.1, 18.4, 18.7
```{=html}
<!-- -->
```
- initialization (before update), 7.2
```{=html}
<!-- -->
```
- instance, 4.1, 4.11, 15.1, 15.8
```{=html}
<!-- -->
```
-
as argument, 15.2
- as return value, 15.4
```{=html}
<!-- -->
```
- instance attribute, 15.2, 15.8, 18.2, 18.10
```{=html}
<!-- -->
```
- instantiation, 15.1
```{=html}
<!-- -->
```
- int function, 3.2
```{=html}
<!-- -->
```
- int type, 2.1
```{=html}
<!-- -->
```
- integer, 2.11
```{=html}
<!-- -->
```
-
long, 11.7
- interactive mode, 1.1, 1.7, 2.4, 3.11
```{=html}
<!-- -->
```
- interface, 4.6, 4.10, 4.11, 18.9
```{=html}
<!-- -->
```
- interlocking words, 10.15
```{=html}
<!-- -->
```
- interpret, 1.1, 1.7
```{=html}
<!-- -->
```
- invariant, 16.5, 16.6, 19.9
```{=html}
<!-- -->
```
- invert dictionary, 11.4
```{=html}
<!-- -->
```
- invocation, 8.8, 8.12
```{=html}
<!-- -->
```
- is operator, 10.10, 15.6
```{=html}
<!-- -->
```
- isinstance function, 6.8, 17.8
```{=html}
<!-- -->
```
- item, 8.12, 10.1
```{=html}
<!-- -->
```
-
Canvas, 19.3, 19.10
- dictionary, 11.9
```{=html}
<!-- -->
```
- item assignment, 8.5, 10.2, 12.1
```{=html}
<!-- -->
```
- item update, 10.3
```{=html}
<!-- -->
```
- items method, 12.6
```{=html}
<!-- -->
```
- iteration, 7, 7.3, 7.8
\
\
- join method, 10.9, 18.5
\
\
- Kangaroo class, 17.12
```{=html}
<!-- -->
```
- Kevin Bacon Game, 14.12
```{=html}
<!-- -->
```
- KeyError, 11, A.2.3
```{=html}
<!-- -->
```
- Koch curve, 5.14
```{=html}
<!-- -->
```
- key, 11, 11.9
```{=html}
<!-- -->
```
- key-value pair, 11, 11.9, 12.6
```{=html}
<!-- -->
```
- keyboard input, 5.11
```{=html}
<!-- -->
```
- keys method, 11.2
```{=html}
<!-- -->
```
- keyword, 2.3, 2.3, 2.11, A.1
```{=html}
<!-- -->
```
-
def, 3.5
- elif, 5.6
```{=html}
<!-- -->
```
- else, 5.5
```{=html}
<!-- -->
```
- keyword argument, 4.5, 4.11, 12.7, 19.2, 19.10
\
\
- Label widget, 19.2
```{=html}
<!-- -->
```
- Linux, 1.3.4
```{=html}
<!-- -->
```
- language
```{=html}
<!-- -->
```
-
formal, 1.4
- high-level, 1.1
```{=html}
<!-- -->
```
- low-level, 1.1
```{=html}
<!-- -->
```
- natural, 1.4
```{=html}
<!-- -->
```
- programming, 1.1
```{=html}
<!-- -->
```
- safe, 1.3.2
```{=html}
<!-- -->
```
- Turing complete, 6.5
```{=html}
<!-- -->
```
- leap of faith, 6.6
```{=html}
<!-- -->
```
- len function, 3.15, 8.2, 11
```{=html}
<!-- -->
```
- letter frequency, 12.11
```{=html}
<!-- -->
```
- letter rotation, 8.13, 11.10
```{=html}
<!-- -->
```
- lipogram, 9.2
```{=html}
<!-- -->
```
- list, 10, 10.9, 10.14, 12.8
```{=html}
<!-- -->
```
-
as argument, 10.12
- comprehension, 10.7
```{=html}
<!-- -->
```
- concatenation, 10.4, 10.12, 10.15
```{=html}
<!-- -->
```
- copy, 10.5
```{=html}
<!-- -->
```
- element, 10.2
```{=html}
<!-- -->
```
- empty, 10.1
```{=html}
<!-- -->
```
- function, 10.9
```{=html}
<!-- -->
```
- index, 10.2
```{=html}
<!-- -->
```
- membership, 10.2
```{=html}
<!-- -->
```
- method, 10.6
```{=html}
<!-- -->
```
- nested, 10.1, 10.3
```{=html}
<!-- -->
```
- of objects, 18.4
```{=html}
<!-- -->
```
- of tuples, 12.5
```{=html}
<!-- -->
```
- operation, 10.4
```{=html}
<!-- -->
```
- repetition, 10.4
```{=html}
<!-- -->
```
- slice, 10.5
```{=html}
<!-- -->
```
- traversal, 10.3, 10.14
```{=html}
</TD>
```
```{=html}
<TD VALIGN=top ALIGN=left>
```
- literalness, 1.4
```{=html}
<!-- -->
```
- local variable, 3.9, 3.14
```{=html}
<!-- -->
```
- log function, 3.3
```{=html}
<!-- -->
```
- logarithm, 13.12
```{=html}
<!-- -->
```
- logical operator, 5.2, 5.3
```{=html}
<!-- -->
```
- long integer, 11.7
```{=html}
<!-- -->
```
- lookup, 11.9
```{=html}
<!-- -->
```
- lookup, dictionary, 11.3
```{=html}
<!-- -->
```
- loop, 4.2, 4.11, 7.3, 12.5
```{=html}
<!-- -->
```
-
condition, A.2.2
- event, 19.1
```{=html}
<!-- -->
```
- for, 4.2, 8.3, 10.3
```{=html}
<!-- -->
```
- infinite, 7.3, 19.1, A.2.2
```{=html}
<!-- -->
```
- nested, 18.4
```{=html}
<!-- -->
```
- traversal, 8.3
```{=html}
<!-- -->
```
- while, 7.3
```{=html}
<!-- -->
```
- looping
```{=html}
<!-- -->
```
-
with dictionaries, 11.2
- with indices, 9.4
```{=html}
<!-- -->
```
- with strings, 8.7
```{=html}
<!-- -->
```
- looping and counting, 8.7
```{=html}
<!-- -->
```
- looping with indices, 10.3
```{=html}
<!-- -->
```
- low-level language, 1.1, 1.7
```{=html}
<!-- -->
```
- ls (Unix command), 14.8
\
\
- Markov analysis, 13.8
```{=html}
<!-- -->
```
- McCloskey, Robert, 8.3
```{=html}
<!-- -->
```
- MD5 algorithm, 14.12
```{=html}
<!-- -->
```
- Menubutton widget, 19.7
```{=html}
<!-- -->
```
- Monty Python and the Holy Grail, 16.2
```{=html}
<!-- -->
```
- MP3, 14.12
```{=html}
<!-- -->
```
- map pattern, 10.7, 10.14
```{=html}
<!-- -->
```
- map to, 18.1
```{=html}
<!-- -->
```
- mapping, 10.2, 10.14, 13.8
```{=html}
<!-- -->
```
- mash-up, 13.8
```{=html}
<!-- -->
```
- math function, 3.3
```{=html}
<!-- -->
```
- max function, 12.3, 12.4
```{=html}
<!-- -->
```
- membership
```{=html}
<!-- -->
```
-
bisection search, 10.15
- dictionary, 11
```{=html}
<!-- -->
```
- list, 10.2
```{=html}
<!-- -->
```
- set, 11
```{=html}
<!-- -->
```
- memo, 11.5, 11.9
```{=html}
<!-- -->
```
- mental model, A.3.1
```{=html}
<!-- -->
```
- metaphor, method invocation, 17.2
```{=html}
<!-- -->
```
- metathesis, 12.11
```{=html}
<!-- -->
```
- method, 8.8, 8.12, 17.1, 17.11
```{=html}
<!-- -->
```
-
\_\_cmp\_\_, 18.3
- \_\_str\_\_, 17.6, 18.5
```{=html}
<!-- -->
```
- add, 17.7
```{=html}
<!-- -->
```
- append, 10.6, 10.12, 18.4, 18.6
```{=html}
<!-- -->
```
- close, 14.2, 14.6, 14.8
```{=html}
<!-- -->
```
- config, 19.3
```{=html}
<!-- -->
```
- count, 8.8
```{=html}
<!-- -->
```
- extend, 10.6
```{=html}
<!-- -->
```
- get, 11.1
```{=html}
<!-- -->
```
- init, 17.5, 18.1, 18.4, 18.7
```{=html}
<!-- -->
```
- items, 12.6
```{=html}
<!-- -->
```
- join, 10.9, 18.5
```{=html}
<!-- -->
```
- keys, 11.2
```{=html}
<!-- -->
```
- mro, 18.9
```{=html}
<!-- -->
```
- pop, 10.8, 18.6
```{=html}
<!-- -->
```
- radd, 17.8
```{=html}
<!-- -->
```
- read, 14.8
```{=html}
<!-- -->
```
- readline, 9.1, 14.8
```{=html}
<!-- -->
```
- remove, 10.8
```{=html}
<!-- -->
```
- replace, 13.1
```{=html}
<!-- -->
```
- setdefault, 11.4
```{=html}
<!-- -->
```
- sort, 10.6, 10.13, 12.7, 18.6
```{=html}
<!-- -->
```
- split, 10.9, 12.2
```{=html}
<!-- -->
```
- string, 8.13
```{=html}
<!-- -->
```
- strip, 9.1, 13.1
```{=html}
<!-- -->
```
- translate, 13.1
```{=html}
<!-- -->
```
- update, 12.6
```{=html}
<!-- -->
```
- values, 11
```{=html}
<!-- -->
```
- void, 10.6
```{=html}
<!-- -->
```
- method append, 10.15
```{=html}
<!-- -->
```
- method resolution order, 18.9
```{=html}
<!-- -->
```
- method syntax, 17.2
```{=html}
<!-- -->
```
- method, bound, 19.6
```{=html}
<!-- -->
```
- method, list, 10.6
```{=html}
<!-- -->
```
- min function, 12.3, 12.4
```{=html}
<!-- -->
```
- model, mental, A.3.1
```{=html}
<!-- -->
```
- modifier, 16.3, 16.6
```{=html}
<!-- -->
```
- module, 3.3, 3.14, 3.14
```{=html}
<!-- -->
```
-
anydbm, 14.6
- bisect, 10.15
```{=html}
<!-- -->
```
- copy, 15.6
```{=html}
<!-- -->
```
- datetime, 16.7
```{=html}
<!-- -->
```
- Gui, 19.1
```{=html}
<!-- -->
```
- HTMLParser, 19.11
```{=html}
<!-- -->
```
- Image, 19.11
```{=html}
<!-- -->
```
- os, 14.4
```{=html}
<!-- -->
```
- pickle, 14.1, 14.7
```{=html}
<!-- -->
```
- pprint, 11.8
```{=html}
<!-- -->
```
- profile, 13.9
```{=html}
<!-- -->
```
- random, 10.15, 12.7, 13.2, 18.6
```{=html}
<!-- -->
```
- reload, 14.9, A.1.1
```{=html}
<!-- -->
```
- shelve, 14.7, 14.12
```{=html}
<!-- -->
```
- string, 13.1
```{=html}
<!-- -->
```
- structshape, 12.9
```{=html}
<!-- -->
```
- urllib, 14.12, 19.11
```{=html}
<!-- -->
```
- Visual, 17.12
```{=html}
<!-- -->
```
- vpython, 17.12
```{=html}
<!-- -->
```
- World, 15.9
```{=html}
<!-- -->
```
- module object, 3.3, 14.9
```{=html}
<!-- -->
```
- module, writing, 14.9
```{=html}
<!-- -->
```
- modulus operator, 5.1, 5.13
```{=html}
<!-- -->
```
- mro method, 18.9
```{=html}
<!-- -->
```
- multiline string, 4.9, A.1
```{=html}
<!-- -->
```
- multiple assignment, 7.1, 7.8, 11.6
```{=html}
<!-- -->
```
- multiplicity (in class diagram), 18.8, 18.10
```{=html}
<!-- -->
```
- mutability, 8.5, 10.2, 10.5, 10.11, 11.6, 12.1, 12.8, 15.5
```{=html}
<!-- -->
```
- mutable object, as default value, 17.12
\
\
- NameError, 3.9, A.2.3
```{=html}
<!-- -->
```
- Newton's method, 7.5
```{=html}
<!-- -->
```
- None special value, 3.11, 6.1, 6.10, 10.6, 10.8
```{=html}
<!-- -->
```
- natural language, 1.4, 1.7
```{=html}
<!-- -->
```
- negative index, 8.2
```{=html}
<!-- -->
```
- nested conditional, 5.7, 5.13
```{=html}
<!-- -->
```
- nested list, 10.1, 10.3, 10.14
```{=html}
<!-- -->
```
- newline, 5.11, 7.1, 18.5
```{=html}
<!-- -->
```
- not operator, 5.3
```{=html}
<!-- -->
```
- number, random, 13.2
\
\
- OverflowError, 5.12
```{=html}
<!-- -->
```
- object, 8.5, 8.12, 10.10, 10.10, 10.14, 15.1
```{=html}
<!-- -->
```
-
Callable, 19.7
- Canvas, 15.9
```{=html}
<!-- -->
```
- class, 15.1
```{=html}
<!-- -->
```
- copying, 15.6
```{=html}
<!-- -->
```
- Event, 19.8
```{=html}
<!-- -->
```
- embedded, 15.3, 15.8, 17.12
```{=html}
<!-- -->
```
- file, 9.1, 9.6
```{=html}
<!-- -->
```
- function, 3.5, 3.15
```{=html}
<!-- -->
```
- module, 14.9
```{=html}
<!-- -->
```
- mutable, 15.5
```{=html}
<!-- -->
```
- printing, 17.2
```{=html}
<!-- -->
```
- object code, 1.1, 1.7
```{=html}
<!-- -->
```
- object diagram, 15.2, 15.3, 15.6, 15.8, 16.1, 18.2
```{=html}
<!-- -->
```
- object-oriented language, 17.11
```{=html}
<!-- -->
```
- object-oriented programming, 17.1, 17.11, 18.7
```{=html}
<!-- -->
```
- octal, 2.2
```{=html}
<!-- -->
```
- odometer, 9.7
```{=html}
<!-- -->
```
- open function, 9.1, 9.1, 14.2, 14.5, 14.6
```{=html}
<!-- -->
```
- operand, 2.5, 2.11
```{=html}
<!-- -->
```
- operator, 2.11
```{=html}
<!-- -->
```
-
and, 5.3
- bitwise, 2.5
```{=html}
<!-- -->
```
- boolean, 8.9
```{=html}
<!-- -->
```
- bracket, 8.1, 10.2, 12.1
```{=html}
<!-- -->
```
- comparison, 5.2
```{=html}
<!-- -->
```
- conditional, 18.3
```{=html}
<!-- -->
```
- del, 10.8
```{=html}
<!-- -->
```
- format, 14.3, 14.11, A.2.3
```{=html}
<!-- -->
```
- in, 8.9, 9.3, 10.2, 11
```{=html}
<!-- -->
```
- is, 10.10, 15.6
```{=html}
<!-- -->
```
- logical, 5.2, 5.3
```{=html}
<!-- -->
```
- modulus, 5.1, 5.13
```{=html}
<!-- -->
```
- not, 5.3
```{=html}
<!-- -->
```
- or, 5.3
```{=html}
<!-- -->
```
- overloading, 17.11
```{=html}
<!-- -->
```
- slice, 8.4, 8.13, 10.5, 10.12, 12.1
```{=html}
<!-- -->
```
- string, 2.8
```{=html}
<!-- -->
```
- update, 10.7
```{=html}
<!-- -->
```
- operator overloading, 17.7, 18.3
```{=html}
<!-- -->
```
- operator, arithmetic, 2.5
```{=html}
<!-- -->
```
- option, 19.2, 19.10
```{=html}
<!-- -->
```
- optional argument, 8.8, 10.9, 11.3
```{=html}
<!-- -->
```
- optional parameter, 13.5, 17.5
```{=html}
<!-- -->
```
- or operator, 5.3
```{=html}
<!-- -->
```
- order of operations, 2.7, 2.10, A.3.2
```{=html}
<!-- -->
```
- os module, 14.4
```{=html}
<!-- -->
```
- other (parameter name), 17.4
```{=html}
<!-- -->
```
- overloading, 17.11
```{=html}
<!-- -->
```
- override, 13.5, 13.11, 17.5, 18.3, 18.7, 18.9
\
\
- PEMDAS, 2.7
```{=html}
<!-- -->
```
- PIL (Python Imaging Library), 19.11
```{=html}
<!-- -->
```
- Point class, 15.1, 17.5
```{=html}
<!-- -->
```
- Project Gutenberg, 13.1
```{=html}
<!-- -->
```
- Puzzler, 9.7, 9.7, 9.7, 11.10, 12.11
```{=html}
<!-- -->
```
- Pythagorean theorem, 6.2
```{=html}
<!-- -->
```
- Python 3.0, 1.5, 2.5, 5.11, 11.7, 12.5
```{=html}
<!-- -->
```
- Python debugger (pdb), A.2.3
```{=html}
<!-- -->
```
- Python Imaging Library (PIL), 19.11
```{=html}
<!-- -->
```
- packing widgets, 19.6, 19.10
```{=html}
<!-- -->
```
- palindrome, 6.11, 8.13, 9.4, 9.7, 9.7
```{=html}
<!-- -->
```
- parameter, 3.8, 3.9, 3.14, 10.12
```{=html}
<!-- -->
```
-
gather, 12.4
- optional, 13.5, 17.5
```{=html}
<!-- -->
```
- other, 17.4
```{=html}
<!-- -->
```
- self, 17.2
```{=html}
<!-- -->
```
- parent class, 18.7, 18.7, 18.10
```{=html}
<!-- -->
```
- parentheses
```{=html}
<!-- -->
```
-
argument in, 3.1
- empty, 3.5, 8.8
```{=html}
<!-- -->
```
- matching, 1.3.1
```{=html}
<!-- -->
```
- overriding precedence, 2.7
```{=html}
<!-- -->
```
- parameters in, 3.8, 3.9
```{=html}
<!-- -->
```
- parent class in, 18.7
```{=html}
<!-- -->
```
- tuples in, 12.1
```{=html}
<!-- -->
```
- parse, 1.4, 1.7, 14.12
```{=html}
<!-- -->
```
- pass statement, 5.4
```{=html}
<!-- -->
```
- path, 14.4, 14.11
```{=html}
<!-- -->
```
-
absolute, 14.4
- relative, 14.4
```{=html}
<!-- -->
```
- pattern
```{=html}
<!-- -->
```
-
DSU, 12.7, 13.4
- decorate-sort-undecorate, 12.7
```{=html}
<!-- -->
```
- filter, 10.7, 10.14
```{=html}
<!-- -->
```
- guardian, 6.8, 6.10, 8.11
```{=html}
<!-- -->
```
- map, 10.7, 10.14
```{=html}
<!-- -->
```
- reduce, 10.7, 10.14
```{=html}
<!-- -->
```
- search, 8.6, 8.12, 9.3, 11.3
```{=html}
<!-- -->
```
- swap, 12.2
```{=html}
<!-- -->
```
- pdb (Python debugger), A.2.3
```{=html}
<!-- -->
```
- permission, file, 14.5
```{=html}
<!-- -->
```
- persistence, 14.1, 14.11
```{=html}
<!-- -->
```
- pi, 3.3, 7.9
```{=html}
<!-- -->
```
- pickle module, 14.1, 14.7
```{=html}
<!-- -->
```
- pickling, 14.7
```{=html}
<!-- -->
```
- pie, 4.12
```{=html}
<!-- -->
```
- pipe, 14.8, 14.12
```{=html}
<!-- -->
```
- pixel coordinate, 19.8
```{=html}
<!-- -->
```
- plain text, 9.1, 13.1, 14.12, 19.11
```{=html}
<!-- -->
```
- planned development, 16.4, 16.6
```{=html}
<!-- -->
```
- playing card, Anglo-American, 18
```{=html}
<!-- -->
```
- poetry, 1.4
```{=html}
<!-- -->
```
- point, mathematical, 15.1
```{=html}
<!-- -->
```
- poker, 18, 18.11
```{=html}
<!-- -->
```
- polygon function, 4.3
```{=html}
<!-- -->
```
- polymorphism, 17.9, 17.11, 18.9
```{=html}
<!-- -->
```
- pop method, 10.8, 18.6
```{=html}
<!-- -->
```
- popen function, 14.8
```{=html}
<!-- -->
```
- portability, 1.1, 1.7
```{=html}
<!-- -->
```
- postcondition, 4.10, 6.9, 18.9
```{=html}
<!-- -->
```
- pprint module, 11.8
```{=html}
<!-- -->
```
- precedence, 2.11, A.3.2
```{=html}
<!-- -->
```
- precondition, 4.10, 4.11, 4.11, 6.9, 10.15, 18.9
```{=html}
<!-- -->
```
- prefix, 13.8
```{=html}
<!-- -->
```
- pretty print, 11.8
```{=html}
<!-- -->
```
- print statement, 1.5, 1.7, 17.6, A.2.4
```{=html}
<!-- -->
```
- problem recognition, 9.3, 9.4, 9.6
```{=html}
<!-- -->
```
- problem solving, 1, 1.7
```{=html}
<!-- -->
```
- profile module, 13.9
```{=html}
<!-- -->
```
- program, 1.2, 1.7
```{=html}
<!-- -->
```
- program testing, 9.5
```{=html}
<!-- -->
```
- programming language, 1.1
```{=html}
<!-- -->
```
- prompt, 1.1, 1.7, 5.11
```{=html}
<!-- -->
```
- prose, 1.4
```{=html}
<!-- -->
```
- prototype and patch, 16.2, 16.4, 16.6
```{=html}
<!-- -->
```
- pseudorandom, 13.2, 13.11
```{=html}
<!-- -->
```
- pure function, 16.2, 16.6
```{=html}
<!-- -->
```
- python.org, 1.8
\
\
- quotation mark, 1.5, 2.1, 2.1, 4.9, 8.4, A.1
\
\
- Ramanujan, Srinivasa, 7.9
```{=html}
<!-- -->
```
- Rectangle class, 15.3
```{=html}
<!-- -->
```
- RSA algorithm, 11.7
```{=html}
<!-- -->
```
- RuntimeError, 5.10, 6.8
```{=html}
<!-- -->
```
- radd method, 17.8
```{=html}
<!-- -->
```
- radian, 3.3
```{=html}
<!-- -->
```
- rage, A.3.4
```{=html}
<!-- -->
```
- raise statement, 11.3, 16.5
```{=html}
<!-- -->
```
- randint function, 10.15, 13.2
```{=html}
<!-- -->
```
- random function, 12.7, 13.2
```{=html}
<!-- -->
```
- random module, 10.15, 12.7, 13.2, 18.6
```{=html}
<!-- -->
```
- random number, 13.2
```{=html}
<!-- -->
```
- random text, 13.8
```{=html}
<!-- -->
```
- random walk programming, 13.10, A.3.4
```{=html}
<!-- -->
```
- rank, 18.1
```{=html}
<!-- -->
```
- raw_input function, 5.11
```{=html}
<!-- -->
```
- read method, 14.8
```{=html}
<!-- -->
```
- readline method, 9.1, 14.8
```{=html}
<!-- -->
```
- recursion, 5.8, 5.8, 5.13, 6.5, 6.6
```{=html}
<!-- -->
```
-
base case, 5.9
- infinite, 5.10, 6.8, A.2.2
```{=html}
<!-- -->
```
- recursive definition, 6.5, 12.11
```{=html}
<!-- -->
```
- reduce pattern, 10.7, 10.14
```{=html}
<!-- -->
```
- reducible word, 11.10, 12.11
```{=html}
<!-- -->
```
- redundancy, 1.4
```{=html}
<!-- -->
```
- refactoring, 4.7, 4.7
```{=html}
<!-- -->
```
- reference, 10.11, 10.12, 10.14
```{=html}
<!-- -->
```
-
aliasing, 10.11
- relative path, 14.4, 14.11
```{=html}
<!-- -->
```
- reload function, 14.9, A.1.1
```{=html}
<!-- -->
```
- remove method, 10.8
```{=html}
<!-- -->
```
- repetition, 4.2
```{=html}
<!-- -->
```
-
list, 10.4
- replace method, 13.1
```{=html}
<!-- -->
```
- repr function, 14.10
```{=html}
<!-- -->
```
- representation, 15.1, 15.3, 18.1
```{=html}
<!-- -->
```
- return statement, 5.8, 6.1, A.3.3
```{=html}
<!-- -->
```
- return value, 3.1, 3.14, 6.1, 15.4
```{=html}
<!-- -->
```
-
tuple, 12.3
- reverse lookup, dictionary, 11.3, 11.9
```{=html}
<!-- -->
```
- reverse word pair, 10.15
```{=html}
<!-- -->
```
- reversed function, 12.8
```{=html}
<!-- -->
```
- rotation
```{=html}
<!-- -->
```
-
letters, 11.10
- rotation, letter, 8.13
```{=html}
<!-- -->
```
- rules of precedence, 2.7, 2.11
```{=html}
<!-- -->
```
- running pace, 1.8, 2.12, 16.7
```{=html}
<!-- -->
```
- runtime error, 1.3.2, 2.10, 5.10, 5.12, A, A.2.3
\
\
- Scrabble, 12.11
```{=html}
<!-- -->
```
- SimpleTurtleWorld class, 19.6
```{=html}
<!-- -->
```
- SVG, 19.11
```{=html}
<!-- -->
```
- Swampy, 4.1, 9.1, 15.9, 18.11, 19.1
```{=html}
<!-- -->
```
- SyntaxError, 3.4
```{=html}
<!-- -->
```
- safe language, 1.3.2
```{=html}
<!-- -->
```
- sanity check, 11.8
```{=html}
<!-- -->
```
- scaffolding, 6.2, 6.10, 11.8
```{=html}
<!-- -->
```
- scatter, 12.4, 12.10
```{=html}
<!-- -->
```
- script, 1.1, 1.7
```{=html}
<!-- -->
```
- script mode, 1.1, 1.7, 2.4, 3.11
```{=html}
<!-- -->
```
- search, 11.3
```{=html}
<!-- -->
```
- search pattern, 8.6, 8.12, 9.3
```{=html}
<!-- -->
```
- search, bisection, 10.15
```{=html}
<!-- -->
```
- secret exercise, 14.12
```{=html}
<!-- -->
```
- self (parameter name), 17.2
```{=html}
<!-- -->
```
- semantic error, 1.3.3, 1.7, 2.1, 2.10, 8.11, A, A.3
```{=html}
<!-- -->
```
- semantics, 1.3.3, 1.7, 17.1
```{=html}
<!-- -->
```
- sequence, 8.1, 8.12, 10.1, 10.9, 12.1, 12.8
```{=html}
<!-- -->
```
-
coordinate, 19.4
- set, 13.6
```{=html}
<!-- -->
```
-
anagram, 12.11, 14.7
- set membership, 11
```{=html}
<!-- -->
```
- setdefault method, 11.4
```{=html}
<!-- -->
```
- sexagesimal, 16.4
```{=html}
<!-- -->
```
- shallow copy, 15.6, 15.8
```{=html}
<!-- -->
```
- shape, 12.10
```{=html}
<!-- -->
```
- shape error, 12.9
```{=html}
<!-- -->
```
- shell, 14.8
```{=html}
<!-- -->
```
- shelve module, 14.7, 14.12
```{=html}
<!-- -->
```
- shuffle function, 18.6
```{=html}
<!-- -->
```
- sine function, 3.3
```{=html}
<!-- -->
```
- singleton, 11.4, 11.9, 12.1
```{=html}
<!-- -->
```
- slice, 8.12
```{=html}
<!-- -->
```
-
copy, 8.4, 10.5
- list, 10.5
```{=html}
<!-- -->
```
- string, 8.4
```{=html}
<!-- -->
```
- tuple, 12.1
```{=html}
<!-- -->
```
- update, 10.5
```{=html}
<!-- -->
```
- slice operator, 8.4, 8.13, 10.5, 10.12, 12.1
```{=html}
<!-- -->
```
- sort method, 10.6, 10.13, 12.7, 18.6
```{=html}
<!-- -->
```
- sorted function, 12.8
```{=html}
<!-- -->
```
- source code, 1.1, 1.7
```{=html}
<!-- -->
```
- special case, 9.5, 9.6, 16.3
```{=html}
<!-- -->
```
- special value
```{=html}
<!-- -->
```
-
False, 5.2
- None, 3.11, 6.1, 6.10, 10.6, 10.8
```{=html}
<!-- -->
```
- True, 5.2
```{=html}
<!-- -->
```
- split method, 10.9, 12.2
```{=html}
<!-- -->
```
- sqrt, 6.2
```{=html}
<!-- -->
```
- sqrt function, 3.3
```{=html}
<!-- -->
```
- square root, 7.5
```{=html}
<!-- -->
```
- squiggly bracket, 11
```{=html}
<!-- -->
```
- stack diagram, 3.10, 3.10, 3.14, 4.12, 5.9, 6.5, 6.11, 10.12
```{=html}
<!-- -->
```
- state diagram, 2.2, 2.11, 7.1, 8.11, 10.2, 10.10, 10.11, 11.4, 12.6,
15.2, 15.3, 15.6, 16.1, 18.2
```{=html}
<!-- -->
```
- statement, 2.4, 2.11
```{=html}
<!-- -->
```
-
assert, 16.5
- assignment, 2.2, 7.1
```{=html}
<!-- -->
```
- break, 7.4
```{=html}
<!-- -->
```
- compound, 5.4
```{=html}
<!-- -->
```
- conditional, 5.4, 5.13, 6.4
```{=html}
<!-- -->
```
- for, 4.2, 8.3, 10.3
```{=html}
<!-- -->
```
- global, 11.6
```{=html}
<!-- -->
```
- if, 5.4
```{=html}
<!-- -->
```
- import, 3.14, 4.1, 14.9
```{=html}
<!-- -->
```
- pass, 5.4
```{=html}
<!-- -->
```
- print, 1.5, 1.7, 17.6, A.2.4
```{=html}
<!-- -->
```
- raise, 11.3, 16.5
```{=html}
<!-- -->
```
- return, 5.8, 6.1, A.3.3
```{=html}
<!-- -->
```
- try, 14.5
```{=html}
<!-- -->
```
- while, 7.3
```{=html}
<!-- -->
```
- step size, 8.13
```{=html}
<!-- -->
```
- str function, 3.2
```{=html}
<!-- -->
```
- \_\_str\_\_ method, 17.6, 18.5
```{=html}
<!-- -->
```
- string, 2.1, 2.11, 10.9, 12.8
```{=html}
<!-- -->
```
-
accumulator, 18.5
- comparison, 8.10
```{=html}
<!-- -->
```
- empty, 10.9
```{=html}
<!-- -->
```
- immutable, 8.5
```{=html}
<!-- -->
```
- method, 8.8
```{=html}
<!-- -->
```
- multiline, 4.9, A.1
```{=html}
<!-- -->
```
- operation, 2.8
```{=html}
<!-- -->
```
- slice, 8.4
```{=html}
<!-- -->
```
- triple-quoted, 4.9
```{=html}
<!-- -->
```
- string method, 8.13
```{=html}
<!-- -->
```
- string module, 13.1
```{=html}
<!-- -->
```
- string representation, 14.10, 17.6
```{=html}
<!-- -->
```
- string type, 2.1
```{=html}
<!-- -->
```
- strip method, 9.1, 13.1
```{=html}
<!-- -->
```
- structshape module, 12.9
```{=html}
<!-- -->
```
- structure, 1.4
```{=html}
<!-- -->
```
- subclass, 18.7
```{=html}
<!-- -->
```
- subject, 17.2, 17.11, 19.6
```{=html}
<!-- -->
```
- subtraction
```{=html}
<!-- -->
```
-
dictionary, 13.6
- with borrowing, 7.6
```{=html}
<!-- -->
```
- subtraction with borrowing, 16.4
```{=html}
<!-- -->
```
- suffix, 13.8
```{=html}
<!-- -->
```
- suit, 18.1
```{=html}
<!-- -->
```
- sum function, 12.4
```{=html}
<!-- -->
```
- superclass, 18.7
```{=html}
<!-- -->
```
- superstitious debugging, A.3.4
```{=html}
<!-- -->
```
- swap pattern, 12.2
```{=html}
<!-- -->
```
- syntax, 1.3.1, 1.3.1, 1.7, 17.1, A.1
```{=html}
<!-- -->
```
- syntax error, 1.3.1, 1.7, 2.10, A
\
\
- Tagger, 18.11
```{=html}
<!-- -->
```
- Text widget, 19.5
```{=html}
<!-- -->
```
- Time class, 16.1
```{=html}
<!-- -->
```
- Tkinter, 19.1
```{=html}
<!-- -->
```
- True special value, 5.2
```{=html}
<!-- -->
```
- Turing complete language, 6.5
```{=html}
<!-- -->
```
- Turing Thesis, 6.5
```{=html}
<!-- -->
```
- Turing, Alan, 6.5
```{=html}
<!-- -->
```
- TurtleWorld, 4.1, 5.14, 18.11
```{=html}
<!-- -->
```
- TypeError, 8.1, 8.5, 11.4, 12.1, 12.4, 14.3, 17.3, A.2.3
```{=html}
<!-- -->
```
- temporary variable, 6.1, 6.10, A.3.2
```{=html}
<!-- -->
```
- test case, minimal, A.2.4
```{=html}
<!-- -->
```
- testing
```{=html}
<!-- -->
```
-
and absence of bugs, 9.5
- incremental development, 6.2
```{=html}
<!-- -->
```
- interactive mode, 1.1
```{=html}
<!-- -->
```
- is hard, 9.5
```{=html}
<!-- -->
```
- knowing the answer, 6.2
```{=html}
<!-- -->
```
- leap of faith, 6.6
```{=html}
<!-- -->
```
- minimal test case, A.2.4
```{=html}
<!-- -->
```
- text
```{=html}
<!-- -->
```
-
plain, 9.1, 13.1, 14.12, 19.11
- random, 13.8
```{=html}
<!-- -->
```
- text file, 14.11
```{=html}
<!-- -->
```
- token, 1.4, 1.7
```{=html}
<!-- -->
```
- traceback, 3.10, 3.14, 5.10, 5.12, 11.3, A.2.3
```{=html}
<!-- -->
```
- translate method, 13.1
```{=html}
<!-- -->
```
- traversal, 8.3, 8.3, 8.6, 8.11, 8.12, 9.3, 9.3, 10.7, 10.14, 11.1,
11.2, 12.5, 12.5, 12.7, 13.3
```{=html}
<!-- -->
```
-
dictionary, 17.10
- list, 10.3
```{=html}
<!-- -->
```
- traverse
```{=html}
<!-- -->
```
-
dictionary, 12.6
- triangle, 5.14
```{=html}
<!-- -->
```
- trigonometric function, 3.3
```{=html}
<!-- -->
```
- triple-quoted string, 4.9
```{=html}
<!-- -->
```
- try statement, 14.5
```{=html}
<!-- -->
```
- tuple, 12.1, 12.3, 12.8, 12.10
```{=html}
<!-- -->
```
-
as key in dictionary, 12.6, 13.9
- assignment, 12.2
```{=html}
<!-- -->
```
- comparison, 12.7, 18.3
```{=html}
<!-- -->
```
- in brackets, 12.6
```{=html}
<!-- -->
```
- singleton, 12.1
```{=html}
<!-- -->
```
- slice, 12.1
```{=html}
<!-- -->
```
- tuple assignment, 12.3, 12.5, 12.10
```{=html}
<!-- -->
```
- tuple function, 12.1
```{=html}
<!-- -->
```
- turtle typewriter, 4.12
```{=html}
<!-- -->
```
- type, 2.1, 2.1, 2.11
```{=html}
<!-- -->
```
-
bool, 5.2
- dict, 11
```{=html}
<!-- -->
```
- file, 14
```{=html}
<!-- -->
```
- float, 2.1
```{=html}
<!-- -->
```
- int, 2.1
```{=html}
<!-- -->
```
- list, 10
```{=html}
<!-- -->
```
- long, 11.7
```{=html}
<!-- -->
```
- set, 13.6
```{=html}
<!-- -->
```
- str, 2.1
```{=html}
<!-- -->
```
- tuple, 12.1
```{=html}
<!-- -->
```
- user-defined, 15.1, 16.1
```{=html}
<!-- -->
```
- type checking, 6.8
```{=html}
<!-- -->
```
- type conversion, 3.2
```{=html}
<!-- -->
```
- type function, 15.7
```{=html}
<!-- -->
```
- type-based dispatch, 17.8, 17.9, 17.11
```{=html}
<!-- -->
```
- typewriter, turtle, 4.12
```{=html}
<!-- -->
```
- typographical error, 13.10
\
\
- UML, 18.8
```{=html}
<!-- -->
```
- UnboundLocalError, 11.6
```{=html}
<!-- -->
```
- Unix command
```{=html}
<!-- -->
```
-
gzip, 14.8
- ls, 14.8
```{=html}
<!-- -->
```
- URL, 14.12, 19.11
```{=html}
<!-- -->
```
- underscore character, 2.3
```{=html}
<!-- -->
```
- uniqueness, 10.15
```{=html}
<!-- -->
```
- update, 7.2, 7.5, 7.8
```{=html}
<!-- -->
```
-
coordinate, 19.8
- database, 14.6
```{=html}
<!-- -->
```
- global variable, 11.6
```{=html}
<!-- -->
```
- histogram, 13.3
```{=html}
<!-- -->
```
- item, 10.3
```{=html}
<!-- -->
```
- slice, 10.5
```{=html}
<!-- -->
```
- update method, 12.6
```{=html}
<!-- -->
```
- update operator, 10.7
```{=html}
<!-- -->
```
- urllib module, 14.12, 19.11
```{=html}
<!-- -->
```
- use before def, 2.10, 3.6
```{=html}
<!-- -->
```
- user-defined type, 15.1, 16.1
\
\
- ValueError, 5.11, 11.3, 12.2
```{=html}
<!-- -->
```
- Visual module, 17.12
```{=html}
<!-- -->
```
- value, 2.1, 2.11, 10.10, 10.10, 11.9
```{=html}
<!-- -->
```
-
default, 13.5
- tuple, 12.3
```{=html}
<!-- -->
```
- values method, 11
```{=html}
<!-- -->
```
- variable, 2.2, 2.11
```{=html}
<!-- -->
```
-
global, 11.6
- local, 3.9
```{=html}
<!-- -->
```
- temporary, 6.1, 6.10, A.3.2
```{=html}
<!-- -->
```
- updating, 7.2
```{=html}
<!-- -->
```
- variable-length argument tuple, 12.4
```{=html}
<!-- -->
```
- vector graphics, 19.11
```{=html}
<!-- -->
```
- veneer, 18.6, 18.10
```{=html}
<!-- -->
```
- void function, 3.11, 3.14
```{=html}
<!-- -->
```
- void method, 10.6
```{=html}
<!-- -->
```
- vpython module, 17.12
\
\
- World module, 15.9
```{=html}
<!-- -->
```
- walk, directory, 14.4
```{=html}
<!-- -->
```
- while loop, 7.3
```{=html}
<!-- -->
```
- whitespace, 3.13, 5.12, 9.1, 14.10, A.1
```{=html}
<!-- -->
```
- widget, 19.1, 19.10
```{=html}
<!-- -->
```
-
Button, 19.2
- Canvas, 19.3
```{=html}
<!-- -->
```
- Entry, 19.5
```{=html}
<!-- -->
```
- Frame, 19.6
```{=html}
<!-- -->
```
- Label, 19.2
```{=html}
<!-- -->
```
- Menubutton, 19.7
```{=html}
<!-- -->
```
- Text, 19.5
```{=html}
<!-- -->
```
- widget, packing, 19.6
```{=html}
<!-- -->
```
- word count, 14.9
```{=html}
<!-- -->
```
- word frequency, 13.1, 13.12
```{=html}
<!-- -->
```
- word, reducible, 11.10, 12.11
```{=html}
<!-- -->
```
- working directory, 14.4
```{=html}
<!-- -->
```
- worst bug, 17.12
```{=html}
<!-- -->
```
-
ever, 19.11
\
\
- Zipf's law, 13.12
```{=html}
<!-- -->
```
- zero, index starting at, 8.1, 10.2
```{=html}
<!-- -->
```
- zip function, 12.5
```{=html}
<!-- -->
```
-
use with dict, 12.6
```{=html}
</TD>
```
```{=html}
</TR>
```
```{=html}
</TABLE>
```
```{=html}
<HR>
```
|
Subsets and Splits