100% found this document useful (6 votes)
383 views64 pages

Instant Download Introduction To Computing and Programming in Python, Global Edition Mark J. Guzdial PDF All Chapter

ebook

Uploaded by

jungarioji
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
100% found this document useful (6 votes)
383 views64 pages

Instant Download Introduction To Computing and Programming in Python, Global Edition Mark J. Guzdial PDF All Chapter

ebook

Uploaded by

jungarioji
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 64

Full download test bank at ebook ebookmass.

com

Introduction to Computing and


Programming in Python, Global
Edition Mark J. Guzdial

CLICK LINK TO DOWLOAD

https://ebookmass.com/product/introduction-
to-computing-and-programming-in-python-
global-edition-mark-j-guzdial/

ebookmass.com
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Introduction To Computing And Problem Solving Using


Python 1st Edition E. Balaguruswamy

https://ebookmass.com/product/introduction-to-computing-and-
problem-solving-using-python-1st-edition-e-balaguruswamy/

Introduction to Computation and Programming Using


Python, Third Edition John V. Guttag

https://ebookmass.com/product/introduction-to-computation-and-
programming-using-python-third-edition-john-v-guttag/

Python Programming for Beginners: 2 Books in 1 - the


Ultimate Step-By-Step Guide to Learn Python Programming
Quickly With Practical Exercises Mark Reed

https://ebookmass.com/product/python-programming-for-
beginners-2-books-in-1-the-ultimate-step-by-step-guide-to-learn-
python-programming-quickly-with-practical-exercises-mark-reed/

Introduction to Computing Using Python: An Application


Development Focus, 2nd Edition – Ebook PDF Version

https://ebookmass.com/product/introduction-to-computing-using-
python-an-application-development-focus-2nd-edition-ebook-pdf-
version/
Quantum Computing by Practice: Python Programming in
the Cloud with Qiskit and IBM-Q Vladimir Silva

https://ebookmass.com/product/quantum-computing-by-practice-
python-programming-in-the-cloud-with-qiskit-and-ibm-q-vladimir-
silva/

Python Programming and SQL: 10 Books in 1 - Supercharge


Your Career with Python Programming and SQL Andrew Reed

https://ebookmass.com/product/python-programming-and-
sql-10-books-in-1-supercharge-your-career-with-python-
programming-and-sql-andrew-reed/

Introduction to Quantum Computing (River Publishers


Series in Rapids in Computing and Information Science
and Technology) 1st Edition Ahmed Banafa

https://ebookmass.com/product/introduction-to-quantum-computing-
river-publishers-series-in-rapids-in-computing-and-information-
science-and-technology-1st-edition-ahmed-banafa/

A Beginners Guide to Python 3 Programming 2nd Edition


John Hunt

https://ebookmass.com/product/a-beginners-guide-to-
python-3-programming-2nd-edition-john-hunt/

Introduction to Computing 1st Edition David A. Joyner

https://ebookmass.com/product/introduction-to-computing-1st-
edition-david-a-joyner/
Introduction to
Computing and
Programming
TM
in Python
A MULTIMEDIA APPROACH

Mark J. Guzdial and Barbara Ericson


College of Computing/GVU
Georgia Institute of Technology

Fourth Edition
Global Edition

Boston Columbus Indianapolis New York San Francisco Hoboken


Amsterdam Cape Town Dubai London Madrid Milan Munich Paris Montreal Toronto
Delhi Mexico City São Paulo Sydney Hong Kong Seoul Singapore Taipei Tokyo
Vice President and Editorial Director, ECS: Marcia J. Horton Senior Manufacturing Controller, Global Edition: Kay Holman
Executive Editor: Tracy Johnson Media Production Manager, Global Edition: Vikram Kumar
Assistant Acquisitions Editor, Global Edition: Aditee Agarwal Global HE Director of Vendor Sourcing and Procurement: Diane Hynes
Executive Marketing Manager: Tim Galligan Director of Operations: Nick Sklitsis
Marketing Assistant: Jon Bryant Operations Specialist: Maura Zaldivar-Garcia
Senior Managing Editor: Scott Disanno Cover Designer: Lumina Datamatics
Production Project Manager: Greg Dulles Manager, Rights and Permissions: Rachel Youdelman
Program Manager: Carole Snyder Associate Project Manager, Rights and Permissions: Timothy Nicholls
Project Editor, Global Edition: K.K. Neelakantan Full-Service Project Management: Kalpana Arumugam, SPi Global

MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAKE NO REPRESENTATIONS ABOUT THE SUITABILITY OF THE INFORMATION
CONTAINED IN THE DOCUMENTS AND RELATED GRAPHICS PUBLISHED AS PART OF THE SERVICES FOR ANY PURPOSE. ALL SUCH
DOCUMENTS AND RELATED GRAPHICS ARE PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND. MICROSOFT AND/OR ITS
RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO THIS INFORMATION,
INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY, WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS
FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE
SUPPLIERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING
FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE
DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL
ERRORS. CHANGES ARE PERIODICALLY ADDED TO THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS
MAY MAKE IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED HEREIN AT ANY TIME.
PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE VERSION SPECIFIED.

Pearson Education Limited


Edinburgh Gate
Harlow
Essex CM20 2JE
England

and Associated Companies throughout the world

Visit us on the World Wide Web at:


www.pearsonglobaleditions.com

© Pearson Education Limited 2016

The rights of Mark J. Guzdial and Barbara Ericson to be identified as the authors of this work have been asserted by them in accordance with the
Copyright, Designs and Patents Act 1988.

Authorized adaptation from the United States edition, entitled Introduction to Computing and Programming in Python™ : A Multimedia Approach, Fourth
Edition, ISBN 9780134025544, by Mark J. Guzdial and Barbara Ericson published by Pearson Education © 2016.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic,
mechanical, photocopying, recording or otherwise, without either the prior written permission of the publisher or a license permitting restricted copying in
the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6−10 Kirby Street, London EC1N 8TS.

All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in the author or publisher any
trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners.

British Library Cataloguing-in-Publication Data

A catalogue record for this book is available from the British Library

10 9 8 7 6 5 4 3 2 1

ISBN 10: 1-292-10986-6


ISBN 13: 978-1-292-10986-2

Typeset in 10.5/13 Times by SPi Global


Printed and bound in Malaysia.
Dedicated to our first teachers, our parents:
Janet, Charles, Gene, and Nancy
This page intentionally left blank
Contents
Preface for the Fourth Edition 13
Preface to the First Edition 18
About the Authors 24

1 INTRODUCTION 25
1 Introduction to Computer Science and Media
Computation 27
1.1 What Is Computer Science About? 27
1.2 Programming Languages 30
1.3 What Computers Understand 33
1.4 Media Computation: Why Digitize Media? 35
1.5 Computer Science for Everyone 37
1.5.1 It’s About Communication 37
1.5.2 It’s About Process 37
1.5.3 You Will Probably Need It 38

2 Introduction to Programming 42
2.1 Programming Is About Naming 42
2.1.1 Files and Their Names 44
2.2 Programming in Python 45
2.3 Programming in JES 46
2.4 Media Computation in JES 47
2.4.1 Showing a Picture 51
2.4.2 Playing a Sound 54
2.4.3 Naming Values 54
2.5 Making a Program 57
2.5.1 Functions: Real Math-Like Functions That Take
Input 61
6 Contents

3 Creating and Modifying Text 68


3.1 Strings: Making Human Text in a Computer 68
3.1.1 Making Strings from Strings: Telling Stories 70
3.2 Taking Strings Apart with For 73
3.2.1 Testing the Pieces 75
3.2.2 Taking String Apart, and Putting Strings Together 78
3.2.3 Taking Strings Apart with Indices 81
3.2.4 Mirroring, Reversing, and Separating Strings with Index 83
3.2.5 Encoding and Decoding Strings Using a Keyword Cipher 85
3.3 Taking Strings Apart by Words 87
3.4 What’s Inside a String 90
3.5 What a Computer Can Do 91

4 Modifying Pictures Using Loops 98


4.1 How Pictures Are Encoded 99
4.2 Manipulating Pictures 104
4.2.1 Exploring Pictures 108
4.3 Changing Color Values 110
4.3.1 Using Loops in Pictures 110
4.3.2 Increasing/Decreasing Red (Green, Blue) 112
4.3.3 Testing the Program: Did That Really Work? 117
4.3.4 Changing One Color at a Time 118
4.4 Creating a Sunset 119
4.4.1 Making Sense of Functions 119
4.5 Lightening and Darkening 124
4.6 Creating a Negative 125
4.7 Converting to Grayscale 126
4.8 Specifying Pixels by Index 128

5 Picture Techniques with Selection 138


5.1 Replacing Colors: Red-Eye, Sepia Tones, and Posterizing 138
5.1.1 Reducing Red-Eye 142
5.1.2 Sepia-Toned and Posterized Pictures: Using
Conditionals to Choose the Color 144
5.2 Comparing Pixels: Edge Detection 150
5.3 Background Subtraction 153
5.4 Chromakey 156
5.5 Coloring in ranges 161
Contents 7

5.5.1 Adding a Border 161


5.5.2 Lightening the Right Half of a Picture 162
5.6 Selecting without Retesting 163

6 Modifying Pixels by Position 169


6.1 Processing Pixels Faster 169
6.1.1 Looping across the Pixels with Range 171
6.1.2 Writing Faster Pixel Loops 173
6.2 Mirroring a Picture 175
6.3 Copying and Transforming Pictures 182
6.3.1 Copying 183
6.3.2 Copying Smaller and Modifying 189
6.3.3 Copying and Referencing 191
6.3.4 Creating a Collage 193
6.3.5 General Copying 196
6.3.6 Rotation 197
6.3.7 Scaling 200
6.4 Combining Pixels: Blurring 205
6.5 Blending Pictures 208
6.6 Drawing on Images 210
6.6.1 Drawing with Drawing Commands 212
6.6.2 Vector and Bitmap Representations 213
6.7 Programs as Specifying Drawing Process 215
6.7.1 Why Do We Write Programs? 216

2 SOUND 225
7 Modifying Sounds Using Loops 227
7.1 How Sound Is Encoded 227
7.1.1 The Physics of Sound 227
7.1.2 Investigating Different Sounds 230
7.1.3 Encoding the Sound 235
7.1.4 Binary Numbers and Two’s Complement 236
7.1.5 Storing Digitized Sounds 237
7.2 Manipulating Sounds 239
7.2.1 Open Sounds and Manipulating Samples 239
7.2.2 Using the JES MediaTools 242
7.2.3 Looping 243
7.3 Changing the Volume of Sounds 244
8 Contents

7.3.1 Increasing Volume 244


7.3.2 Did That Really Work? 245
7.3.3 Decreasing Volume 249
7.3.4 Using Array Index Notation 250
7.3.5 Making Sense of Functions in Sounds 251
7.4 Normalizing Sounds 251
7.4.1 Generating Clipping 253

8 Modifying Samples in a Range 259


8.1 Manipulating Different Sections of the Sound Differently 259
8.1.1 Revisiting Index Array Notation 260
8.2 Splicing Sounds 262
8.3 General Clip and Copy 269
8.4 Reversing Sounds 271
8.5 Mirroring 273
8.6 On Functions and Scope 273

9 Making Sounds by Combining Pieces 279


9.1 Composing Sounds Through Addition 279
9.2 Blending Sounds 280
9.3 Creating an Echo 282
9.3.1 Creating Multiple Echoes 284
9.3.2 Creating Chords 284
9.4 How Sampling Keyboards Work 285
9.4.1 Sampling as an Algorithm 289
9.5 Additive Synthesis 289
9.5.1 Making Sine Waves 289
9.5.2 Adding Sine Waves Together 291
9.5.3 Checking Our Result 292
9.5.4 Square Waves 293
9.5.5 Triangular Waves 295
9.6 Modern Music Synthesis 297
9.6.1 MP3 297
9.6.2 MIDI 298

10 Building Bigger Programs 302


10.1 Designing Programs Top-Down 303
10.1.1 A Top-Down Design Example 304
10.1.2 Designing the Top-Level Function 305
10.1.3 Writing the Subfunctions 307
Contents 9

10.2 Designing Programs Bottom-Up 311


10.2.1 An Example Bottom-Up Process 312
10.3 Testing Your Program 312
10.3.1 Testing the Edge Conditions 314
10.4 Tips on Debugging 315
10.4.1 Finding Which Statement to Worry About 316
10.4.2 Seeing the Variables 316
10.4.3 Debugging the Adventure Game 318
10.5 Algorithms and Design 321
10.6 Connecting to Data Outside a Function 322
10.7 Running Programs Outside of JES 326

3 TEXT, FILES, NETWORKS, DATABASES,


AND UNIMEDIA 333
11 Manipulating Text with Methods and Files 335
11.1 Text as Unimedia 335
11.2 Manipulating Parts of Strings 336
11.2.1 String Methods: Introducing Objects and Dot Notation 337
11.2.2 Lists: Powerful, Structured Text 339
11.2.3 Strings Have No Font 341
11.3 Files: Places to Put Your Strings and Other Stuff 341
11.3.1 Opening and Manipulating Files 343
11.3.2 Generating Form Letters 344
11.3.3 Reading and Manipulating Data from the Internet 345
11.3.4 Scraping Information from a Web Page 348
11.3.5 Reading CSV Data 349
11.3.6 Writing Out Programs 351
11.4 The Python Standard Library 352
11.4.1 More on Import and Your Own Modules 353
11.4.2 Adding Unpredictably to Your Program with Random 354
11.4.3 Reading CSV Files with a Library 356
11.4.4 A Sampling of Python Standard Libraries 356

12 Advanced Text Techniques: Web


and Information 361
12.1 Networks: Getting Our Text from the Web 361
12.1.1 Automating Access to CSV Data 365
12.1.2 Accessing FTP 367
10 Contents

12.2 Using Text to Shift Between Media 368


12.3 Moving Information Between Media 371
12.4 Using Lists as Structured Text for Media Representations 374
12.5 Hiding Information in a Picture 375
12.5.1 Hiding a Sound Inside a Picture 377

13 Making Text for the Web 383


13.1 HTML: The Notation of the Web 383
13.2 Writing Programs to Generate HTML 388
13.2.1 Making Home Pages 390
13.3 Databases: A Place to Store Our Text 393
13.3.1 Relational Databases 395
13.3.2 An Example Relational Database Using Hash Tables 396
13.3.3 Working with SQL 399
13.3.4 Using a Database to Build Web Pages 401

4 MOVIES 407
14 Creating and Modifying Movies 409
14.1 Generating Animations 410
14.2 Working with Video Source 419
14.2.1 Video Manipulating Examples 419
14.3 Building a Video Effect Bottom-Up 423

15 Speed 430
15.1 Focusing on Computer Science 430
15.2 What Makes Programs Fast? 430
15.2.1 What Computers Really Understand 431
15.2.2 Compilers and Interpreters 432
15.2.3 What Limits Computer Speed? 436
15.2.4 Does It Really Make a Difference? 438
15.2.5 Making Searching Faster 441
15.2.6 Algorithms That Never Finish or Can’t Be Written 443
15.2.7 Why Is Photoshop Faster than JES? 444
15.3 What Makes a Computer Fast? 444
15.3.1 Clock Rates and Actual Computation 445
15.3.2 Storage: What Makes a Computer Slow? 446
15.3.3 Display 447
Contents 11

16 Functional Programming 450


16.1 Using Functions to Make Programming Easier 450
16.2 Functional Programming with Map and Reduce 454
16.3 Functional Programming for Media 457
16.3.1 Media Manipulation without Changing State 458
16.4 Recursion: A Powerful Idea 459
16.4.1 Recursive Directory Traversals 464
16.4.2 Recursive Media Functions 466

17 Object-Oriented Programming 471


17.1 History of Objects 471
17.2 Working with Turtles 473
17.2.1 Classes and Objects 473
17.2.2 Sending Messages to Objects 474
17.2.3 Objects Control Their State 476
17.3 Teaching Turtles New Tricks 478
17.3.1 Overriding an Existing Turtle Method 480
17.3.2 Working with Multiple Turtles at Once 481
17.3.3 Turtles with Pictures 483
17.3.4 Dancing Turtles 484
17.3.5 Recursion and Turtles 487
17.4 An Object-Oriented Slide Show 488
17.4.1 Making the Slide Class More Object-Oriented 491
17.5 Object-Oriented Media 493
17.6 Joe the Box 498
17.7 Why Objects? 499

APPENDIX 506
A Quick Reference to Python 506
A.1 Variables 506
A.2 Function Creation 507
A.3 Loops and Conditionals 507
A.4 Operators and Representation Functions 508
A.5 Numeric Functions 509
A.6 Sequence Operations 509
A.7 String Escapes 509
12 Contents

A.8 Useful String Methods 509


A.9 Files 510
A.10 Lists 510
A.11 Dictionaries, Hash Tables, or Associative Arrays 510
A.12 External Modules 510
A.13 Classes 511
A.14 Functional Methods 511

Bibliography 512

Index 515
Preface for the
Fourth Edition
We started Media Computation in the of Summer 2002, and taught it for the first time
in Spring 2003. It’s now over ten years later, which is a good time to summarize the
changes across the second, third, and fourth editions.
Media Computation has been used successfully in an undergraduate course at Geor-
gia Tech for the last dozen years. The course continues to have high retention rates (over
85% of students complete the class with a passing grade), and is majority female. Both
students and teachers report enjoying the course, which is an important recommendation
for it.
Researchers have found that Media Computation works in a variety of contexts.
The University of Illinois-Chicago had the first Media Computation paper outside of
Georgia, and they showed how switching to MediaComp improved their retention
rates in classes that were much more diverse than those at Georgia Tech [41]. The
University of California-San Diego adopted Media Computation as part of a big change
in their introductory course, where they also started using pair-programming and peer
instruction. Their paper at the 2013 SIGCSE Symposium showed how these changes
led to dramatic improvements in student retention, even measured a year later in the
Sophomore year. The paper also won the Best Paper award at the conference [27].
It’s been particularly delightful to see Media Computation adopted and adapted for
new settings, like Cynthia Bailey Lee’s creation of a MATLAB Media Computation
curriculum [12].
Mark wrote a paper in 2013, summarizing ten years of Media Computation research.
Media Computation does often improve retention. Our detailed interview studies with
female students supports the claim that they find the approach to be creative and engag-
ing, and that’s what keeps the students in the class. That paper won the Best Paper award
at the 2013 International Computing Education Research (ICER) Conference [33].

HOW TO TEACH MEDIA COMPUTATION


Over the last 10 years, we have learned some of the approaches that work best for
teaching Media Computation.

• Let the students be creative. The most successful Media Computation classes
use open-ended assignments that let the students choose what media they use.
For example, a collage assignment might specify the use of particular filters and
compositions, but allow for the student to choose exactly what pictures are used.
These assignments often lead to the students putting in a lot more time to get just
the look that they wanted, and that extra time can lead to improved learning.
14 Preface for the Fourth Edition

• Let the students share what they produce. Students can produce some beautiful
pictures, sounds, and movies using Media Computation. Those products are more
motivating for the students when they get to share them with others. Some schools
provide online spaces where students can post and share their products. Other
schools have even printed student work and held an art gallery.
• Code live in front of the class. The best part of the teacher actually typing in code
in front of the class is that nobody can code for long in front of an audience and
not make a mistake. When the teacher makes a mistake and fixes it, the students
see (a) that errors are expected and (b) there is a process for fixing them. Coding
live when you are producing images and sounds is fun, and can lead to unexpected
results and the opportunity to explore, “How did that happen?”
• Pair programming leads to better learning and retention. The research results on
pair programming are tremendous. Classes that use pair programming have better
retention results, and the students learn more.
• Peer instruction is great. Not only does peer instruction lead to better learning
and retention outcomes, but it also gives the teacher better feedback on what the
students are learning and what they are struggling with. We strongly encourage
the use of peer instruction in computing classes.
• Worked examples help with creativity learning. Most computer science classes
do not provide anywhere nearly enough worked-out examples for students to
learn from. Students like to learn from examples. One of the benefits of Media
Computation is that we provide a lot of examples (we’ve never tried to count the
number of for and if statements in the book!), and it’s easy to produce more
of them. In class, we do an activity where we hand out example programs, then
show a particular effect. We ask pairs or groups of students to figure out which
program generated that effect. The students talk about code, and study a bunch of
examples.

AP CS PRINCIPLES
The Advanced Placement exam in CS Principles1 has now been defined. We have
explicitly written the fourth edition with CS Principles in mind. For example, we show
how to measure the speed of a program empirically in order to contrast two algorithms
(Learning Objective 4.2.4), and we explore multiple ways of analyzing CSV data from
the Internet (Learning Objectives 3.1.1, 3.2.1, and 3.2.2).
Overall, we address the CS Principles learning objectives explicitly in this book as
shown below:
• In Big Idea I: Creativity:
• LO 1.1.1: . . . use computing tools and techniques to create artifacts.
• LO 1.2.1: . . . use computing tools and techniques for creative expression.
1
http://apcsprinciples.org
Preface for the Fourth Edition 15

• LO 1.2.2: . . . create a computational artifact using computing tools and techniques


to solve a problem.
• LO 1.2.3: . . . create a new computational artifact by combining or modifying
existing artifacts.
• LO 1.2.5: . . . analyze the correctness, usability, functionality, and suitability of
computational artifacts.
• LO 1.3.1: . . . use programming as a creative tool.
• In Big Idea II: Abstraction:
• LO 2.1.1: . . . describe the variety of abstractions used to represent data.
• LO 2.1.2: . . . explain how binary sequences are used to represent digital data.
• LO 2.2.2: . . . use multiple levels of abstraction in computation.
• LO 2.2.3: . . . identify multiple levels of abstractions being used when writing
programs.
• In Big Idea III: Data and information:
• LO 3.1.1: . . . use computers to process information, find patterns, and test
hypotheses about digitally processed information to gain insight and knowledge.
• LO 3.2.1: . . . extract information from data to discover and explain connections,
patterns, or trends.
• LO 3.2.2: . . . use large data sets to explore and discover information and knowl-
edge.
• LO 3.3.1: . . . analyze how data representation, storage, security, and transmission
of data involve computational manipulation of information.
• In Big Idea IV: Algorithms:
• LO 4.1.1: . . . develop an algorithm designed to be implemented to run on a
computer.
• LO 4.1.2: . . . express an algorithm in a language.
• LO 4.2.1: . . . explain the difference between algorithms that run in a reasonable
time and those that do not run in a reasonable time.
• LO 4.2.2: . . . explain the difference between solvable and unsolvable problems
in computer science.
• LO 4.2.4: . . . evaluate algorithms analytically and empirically for efficiency,
correctness, and clarity.
• In Big Idea V: Programming:
• LO 5.1.1: . . . develop a program for creative expression, to satisfy personal
curiosity or to create new knowledge.
• LO 5.1.2: . . . develop a correct program to solve problems.
• LO 5.2.1: . . . explain how programs implement algorithms.
• LO 5.3.1: . . . use abstraction to manage complexity in programs.
16 Preface for the Fourth Edition

• LO 5.5.1: . . . employ appropriate mathematical and logical concepts in program-


ming.
• In Big Idea VI: The Internet:
• LO 6.1.1: . . . explain the abstractions in the Internet and how the Internet func-
tions.

CHANGES IN THE FOURTH EDITION


1. We fixed lots of bugs that our crack bug-finders identified in the third edition.
2. We changed most of the pictures in the book – they were getting stale, and our kids
wanted us to not use as many pictures of them.
3. We added more end-of-chapter questions.
4. We added a whole new chapter, on text as a medium and manipulating strings
(to make sentences, koans, and codes). This isn’t a necessary chapter (e.g., we
introduce for and if statements, but we didn’t remove the introductions later in
the book). For some of our teachers, playing with text with shorter loops (iterating
over all the characters in a sentence is typically smaller than the thousands of pixels
in a picture) is a more comfortable way to start.
5. We gave up fighting the battle of inventing a Web scraper that could beat out the
changes that Facebook made, which kept breaking the one we put in the 3rd edition
and then kept updating on the teacher’s website2 . Instead, we wrote examples in
this book for processing CSV (Comma-Separated Values), a common format for
sharing data on the Internet. We parse the CSV from a file using string processing,
then using the CSV library in Python, and then accessing the data by URL.
6. We added some new edge detection code which is shorter and simpler to understand.
7. We added more with turtles: creating dancing turtles (using sleep from the time
module to pause execution) and recursive patterns.
8. We updated the book to use the latest features in JES, which include those that
reduce the need to use full pathnames (a problem identified by Stephen Edwards
and his students in their SIGCSE 2014 paper [43]).

ACKNOWLEDGMENTS
Our sincere thanks go out to all our reviewers and bug-finders:
• At the top of the list is Susan Schwarz of the US Military Academy at West Point.
Susan runs a large course with many instructors, and pays careful attention to
what’s going in all of the sections of the course. She turned that attention on
the third edition of this book. She caught many bugs, and gave us lots of useful
feedback. Thanks, Susan!
2
http://home.cc.gatech.edu/mediaComp and http://www.mediacomputation.org
Preface for the Fourth Edition 17

• Our other bug finders for the book were John Rutkiewicz, U. Massachusetts–
Dartmouth; Brian Dorn, U. Nebraska–Omaha; Dave Largent, Ball State Univer-
sity; Simon, University of Newcastle; Eva Heinrich, Massey University; Peter
J. DePasquale, The College of New Jersey, and Bill Leahy, Georgia Institute of
Technology.
• Matthew Frazier, North Carolina State University, worked with us in the summer
of 2014 to create a new version of JES – fixing many bugs, and improving JES
considerably.
• We are grateful for the feedback from our book reviewers for the 4th edition:
Andrew Cencini, Bennington College; Susan Fox, Macalester College; Kristin
Lamberty, University of Minnesota-Morris; Jean Smith, Technical College of the
Lowcountry; and William T. Verts, University of Massachusetts-Amherst.
• We are grateful for the input from our book reviewers for the 3rd edition, too:
Joseph Oldham, Centre College; Lukasz Ziarek, Purdue University;Joseph
O’Rourke, Smith College; Atul Prakash, University of Michigan; Noah D. Bar-
nette, Virginia Tech; Adelaida A. Medlock, Drexel University; Susan E. Fox,
Macalester College; Daniel G. Brown, University of Waterloo; Brian A. Malloy,
Clemson University; Renee Renner, California State University, Chico.

Mark Guzdial and Barbara Ericson


Georgia Institute of Technology
Preface to the First Edition
Research in computing education makes it clear that one doesn’t just “learn to program.”
One learns to program something [8, 19], and the motivation to do that something can
make the difference between learning and not learning to program [5]. The challenge
for any teacher is to pick a something that is a powerful enough motivator.
People want to communicate. We are social creatures and the desire to communicate
is one of our primal motivations. Increasingly, the computer is used as a tool for com-
munication even more than a tool for calculation. Virtually all published text, images,
sounds, music, and movies today are prepared using computing technology.
This book is about teaching people to program in order to communicate with digital
media. The book focuses on how to manipulate images, sounds, text, and movies as
professionals might, but with programs written by students. We know that most people
will use professional-grade applications to perform these type of manipulations. But,
knowing how to write your own programs means that you can do more than what your
current application allows you to do. Your power of expression is not limited by your
application software.
It may also be true that knowing how the algorithms in a media applications work
allows you to use them better or to move from one application to the next more easily.
If your focus in an application is on what menu item does what, every application is
different. But if your focus is on moving or coloring the pixels in the way you want,
then maybe it’s easier to get past the menu items and focus on what you want to say.
This book is not just about programming in media. Media-manipulation programs
can be hard to write or may behave in unexpected ways. Natural questions arise, like
“Why is the same image filter faster in Photoshop?” and “That was hard to debug—Are
there ways of writing programs that are easier to debug?” Answering questions like
these is what computer scientists do. There are several chapters at the end of the book
that are about computing, not just programming. The final chapters go beyond media
manipulation to more general topics.
The computer is the most amazingly creative device that humans have ever conceived.
It is completely made up of mind-stuff. The notion “Don’t just dream it, be it” is really
possible on a computer. If you can imagine it, you can make it “real” on the computer.
Playing with programming can be and should be enormous fun.

OBJECTIVES, APPROACH AND ORGANIZATION


The curricular content of this book meets the requirements of the “imperative-first”
approach described in the ACM/IEEE Computing Curriculum 2001 standards document
[2]. The book starts with a focus on fundamental programming constructs: assignments,
sequential operations, iteration, conditionals, and defining functions. Abstractions
Preface to the First Edition 19

(e.g., algorithmic complexity, program efficiency, computer organization, hierarchi-


cal decomposition, recursion, and object-oriented programming) are emphasized later,
after the students have a context for understanding them.
This unusual ordering is based on the findings of research in the learning sciences.
Memory is associative. We remember new things based on what we associate them with.
People can learn concepts and skills on the premise that they will be useful some day but
the concepts and skills will be related only to the premises. The result has been described
as “brittle knowledge” [25]—the kind of knowledge that gets you through the exam
but is promptly forgotten because it doesn’t relate to anything but being in that class.
Concepts and skills are best remembered if they can be related to many different
ideas or to ideas that come up in one’s everyday life. If we want students to gain
transferable knowledge (knowledge that can be applied in new situations), we have to
help them to relate new knowledge to more general problems, so that the memories get
indexed in ways that associate with those kinds of problems [22]. In this book, we teach
with concrete experiences that students can explore and relate to (e.g., conditionals for
removing red-eye in pictures) and later lay abstractions on top of them (e.g., achieving
the same goal using recursion or functional filters and maps).
We know that starting from the abstractions doesn’t really work for computing
students. Ann Fleury has shown that students in introductory computing courses just
don’t buy what we tell them about encapsulation and reuse (e.g., [7]). Students prefer
simpler code that they can trace easily and they actually think that such code is better.
It takes time and experience for students to realize that there is value in well-designed
systems. Without experience, it’s very difficult for students to learn the abstractions.
The media computation approach used in this book starts from what many people
use computers for: image manipulation, exploring digital music, viewing and creating
Web pages, and making videos. We then explain programming and computing in terms
of these activities. We want students to visit Amazon (for example) and think, “Here’s
a catalog Web site—and I know that these are implemented with a database and a
set of programs that format the database entries as Web pages.” We want students to
use Adobe Photoshop and GIMP and think about how their image filters are actually
manipulating red, green, and blue components of pixels. Starting from a relevant context
makes transfer of knowledge and skills more likely. It also makes the examples more
interesting and motivating, which helps with keeping students in the class.
The media computation approach spends about two-thirds of the time on giving
students experiences with a variety of media in contexts that they find motivating. After
that two-thirds, though, they naturally start to ask questions about computing. “Why is
it that Photoshop is faster than my program?” and “Movie code is slow—How slow do
programs get?” are typical. At that point, we introduce the abstractions and the valuable
insights from computer science that answer their questions. That’s what the last part
of this book is about.
A different body of research in computing education explores why withdrawal or
failure rates in introductory computing are so high. One common theme is that com-
puting courses seem “irrelevant” and unnecessarily focus on “tedious details” such
as efficiency [21, 1]. A communications context is perceived as relevant by students
20 Preface to the First Edition

(as they tell us in surveys and interviews [6, 18]). The relevant context is part of the
explanation for the success we have had with retention in the Georgia Tech course for
which this book was written.
The late entrance of abstraction isn’t the only unusual ordering in this approach. We
start using arrays and matrices in Chapter 3, in our first significant programs. Typically,
introductory computing courses push arrays off until later, because they are obviously
more complicated than variables with simple values. A relevant and concrete context
is very powerful [19]. We find that students have no problem manipulating matrices of
pixels in a picture.
The rate of students withdrawing from introductory computing courses or receiving
a D or F grade (commonly called the WDF rate) is reported in the 30–50% range or
even higher. A recent international survey of failure rates in introductory computing
courses reported that the average failure rate among 54 U.S. institutions was 33% and
among 17 international institutions was 17% [24]. At Georgia Tech, from 2000 to 2002,
we had an average WDF rate of 28% in the introductory course required for all majors.
We used the first edition of this text in our course Introduction to Media Computation.
Our first pilot offering of the course had 121 students, no computing or engineering
majors, and two-thirds of the students were female. Our WDF rate was 11.5%.
Over the next two years (Spring 2003 to Fall 2005), the average WDF rate at Georgia
Tech (across multiple instructors, and literally thousands of students) was 15% [29].
Actually, the 28% prior WDF rate and 15% current WDF rate are incomparable, since
all majors took the first course and only liberal arts, architecture, and management
majors took the new course. Individual majors have much more dramatic changes.
Management majors, for example, had a 51.5% WDF rate from 1999 to 2003 with the
earlier course, and had a 11.2% failure rate in the first two years of the new course [29].
Since the first edition of this book was published, several other schools have adopted
and adapted this approach and evaluated their result. All of them have reported similar,
dramatic improvements in success rates [4, 42].

Ways to Use This Book


This book represents what we teach at Georgia Tech in pretty much the same order.
Individual teachers may skip some sections (e.g., the section on additive synthesis,
MIDI, and MP3), but all of the content here has been tested with our students.
However, this material has been used in many other ways.
• A short introduction to computing could be taught with just Chapters 2 (intro-
duction to programming) and 3 (introduction to image processing), perhaps with
some material from Chapters 4 and 5. We have taught even single-day workshops
on media computation using just this material.
• Chapters 6 through 8 basically replicate the computer science concepts from
Chapters 3 through 5 but in the context of sounds rather than images. We find
the replication useful—some students seem to relate better to the concepts of
iteration and conditionals when working with one medium than with the other.
Preface to the First Edition 21

Further, it gives us the opportunity to point out that the same algorithm can have
similar effects in different media (e.g., scaling a picture up or down and shifting a
sound higher or lower in pitch are the same algorithm). But it could certainly be
skipped to save time.
• Chapter 12 (on movies) introduces no new programming or computing concepts.
While motivational, movie processing could be skipped to save time.
• We recommend getting to at least some of the chapters in the last unit, in order to
lead students into thinking about computing and programming in a more abstract
manner, but clearly not all of the chapters have to be covered.

Python and Jython


The programming language used in this book is Python. Python has been described as
“executable pseudo-code.” We have found that both computer science majors and non
majors can learn Python. Since Python is actually used for communications tasks (e.g.,
Web site development), it’s a relevant language for an introductory computing course.
For example, job advertisements posted to the Python Web site (http://www.python.
org) show that companies like Google and Industrial Light & Magic hire Python pro-
grammers.
The specific dialect of Python used in this book is Jython (http://www.jython.
org). Jython is Python. The differences between Python (normally implemented in C)
and Jython (which is implemented in Java) are akin to the differences between any
two language implementations (e.g., Microsoft vs. GNU C++ implementations)—the
basic language is exactly the same, with some library and details differences that most
students will never notice.

TYPOGRAPHICAL NOTATIONS
Examples of Python code look like this: x = x + 1. Longer examples look like this:
def helloWorld():
print "Hello, world!"

When showing something that the user types in with Python’s response, it will have
a similar font and style, but the user’s typing will appear after a Python prompt (>>>):
>>> print 3 + 4
7

User interface components of JES (Jython Environment for Students) will be spec-
ified using a small caps font, like Save menu item and the Load button.
There are several special kinds of sidebars that you’ll find in the book.

Computer Science Idea: An Example Idea


Key computer science concepts appear like this.

22 Preface to the First Edition

Common Bug: An Example Common Bug


Common things that can cause your program to fail appear like this.


Debugging Tip: An Example Debugging Tip


If there’s a good way to keep a bug from creeping into your programs in the first place,
it’s highlighted here.


Making It Work Tip: An Example How to Make It Work


Best practices or techniques that really help are highlighted like this.


INSTRUCTOR RESOURCES
The instructor resources are available on the Pearson Education’s Instructor Resource
Center at www.pearsonglobaleditions.com/guzdial:
• PowerPoint Presentation slides

ACKNOWLEDGMENTS
Our sincere thanks go out to the following:
• Jason Ergle, Claire Bailey, David Raines, and Joshua Sklare, who made the initial
version of JES with surprising quality in an amazingly short amount of time. Over
the years, Adam Wilson, Larry Olson, Yu Cheung (Toby) Ho, Eric Mickley, Keith
McDermott, Ellie Harmon, Timmy Douglas, Alex Rudnick, Brian O’Neill, and
William Fredrick (Buck) Scharfnorth III have made JES into the useful and still
understandable tool that it is today.
• Adam Wilson built the MediaTools that are so useful for exploring sounds and
images and processing video.
• Andrea Forte, Mark Richman, Matt Wallace, Alisa Bandlow, Derek Chambless,
Larry Olson, and David Rennie helped build course materials. Derek, Mark, and
Matt created many example programs.
• There were several people who really made the effort come together at Georgia
Tech. Bob McMath, Vice-Provost at Georgia Tech, and Jim Foley, Associate Dean
for Education in the College of Computing, invested in this effort early on. Kurt
Eiselt worked hard to make this effort real, convincing others to take it seriously.
Janet Kolodner and Aaron Bobick were excited and encouraging about the idea
of media computation for students new to computer science. Jeff Pierce reviewed
Preface to the First Edition 23

and advised us on the design of the media functions used in the book. Aaron
Lanterman gave me lots of advice on how to convey the digital material content
accurately. Joan Morton, Chrissy Hendricks, David White, and all the staff of the
GVU Center made sure that we had what we needed and that the details were
handled to make this effort come together. Amy Bruckman and Eugene Guzdial
bought Mark time to get the final version completed.
• We are grateful to Colin Potts and Monica Sweat who have taught this class at
Georgia Tech and given us many insights about the course.
• Charles Fowler was the first person outside of Georgia Tech willing to take the
gamble and trial the course in his own institution (Gainesville College), for which
we’re very grateful.
• The pilot course offered in Spring 2003 at Georgia Tech was very important in
helping us improve the course. Andrea Forte, Rachel Fithian, and Lauren Rich did
the assessment of the pilot offering of the course, which was incredibly valuable in
helping us understand what worked and what didn’t. The first teaching assistants
(Jim Gruen, Angela Liang, Larry Olson, Matt Wallace, Adam Wilson, and Jose
Zagal) did a lot to help create this approach. Blair MacIntyre, Colin Potts, and
Monica Sweat helped make the materials easier for others to adopt. Jochen Rick
made the CoWeb/Swiki a great place for CS1315 students to hang out.
• Many students pointed out errors and made suggestions to improve the book.
Thanks to Catherine Billiris, Jennifer Blake, Karin Bowman, Maryam Doroudi,
Suzannah Gill, Baillie Homire, Jonathan Laing, Mireille Murad, Michael Shaw,
Summar Shoaib, and especially Jonathan Longhitano, who has a real flair for
copyediting.
• Thanks to former Media Computation students Constantino Kombosch, Joseph
Clark, and Shannon Joiner for permission to use their snapshots from class in
examples.
• The research work that led to this text was supported by grants from the National
Science Foundation—from the Division of Undergraduate Education, CCLI pro-
gram, and from the CISE Educational Innovations program. Thank you for the
support.
• Thanks to computing students Anthony Thomas, Celines Rivera, and Carolina
Gomez for allowing us to use their pictures.
• Finally but most important, thanks to our children Matthew, Katherine, and Jennifer
Guzdial, who allowed themselves to be photographed and recorded for Mommy
and Daddy’s media project and who were supportive and excited about the class.

Mark Guzdial and Barbara Ericson


Georgia Institute of Technology
Pearson would like to thank and acknowledge Dheeraj D., REVA Institute of Technol-
ogy and Management Kattigenahalli, Somitra Sanadhya, Indian Institute of Technology
Delhi, and Simon, University of Newcastle, for contributing to the Global Edition, and
Shaligram Prajapat, Devi Ahilya University Indore, Ng Hu, Multimedia University,
Rohit Tahiliani, Renjith S., and Shivani Pandit, for reviewing the Global Edition.
About the Authors
Mark Guzdial is a professor in the School of Interactive Computing in the College
of Computing at Georgia Institute of Technology. He is one of the founders of the
ACM’s International Computing Education Research workshop series. Dr. Guzdial’s
research focuses on learning sciences and technology, specifically, computing education
research. His first books were on the programming language Squeak and its use in
education. He was the original developer of “Swiki” (Squeak Wiki), the first wiki
developed explicitly for use in schools. He is a Fellow and a Distinguished Educator
of the ACM. He is on the editorial boards of the Journal of the Learning Sciences and
Communications of the ACM. He was a recipient of the 2012 IEEE Computer Society
Undergraduate Teaching Award.
Barbara Ericson is a research scientist and the director of Computing Outreach for
the College of Computing at Georgia Tech. She has been working on improving intro-
ductory computing education since 2004.
She has served as the teacher education representative on the Computer Science
Teachers Association board, the co-chair of the K-12 Alliance for the National Center
for Women in Information Technology, and as a reader for the Advanced Placement
Computer Science exams. She enjoys the diversity of the types of problems she has
worked on over the years in computing including computer graphics, artificial intelli-
gence, medicine, and object-oriented programming.
Mark and Barbara received the 2010 ACM Karl V. Karlstrom Award for Outstanding
Computer Educator for their work on Media Computation including this book. They led
a project called “Georgia Computes!” for six years, which had a significant impact in
improving computing education in the US state of Georgia [31]. Together, they Mark
and Barbara are leaders in the Expanding Computing Education Pathways (ECEP)
alliance3

3
http://www.ecepalliance.org
PART

1 INTRODUCTION

Chapter 1 Introduction to Computer Science


and Media Computation
Chapter 2 Introduction to Programming
Chapter 3 Creating and Modifying Text
Chapter 4 Modifying Pictures Using Loops
Chapter 5 Picture Techniques with Selection
Chapter 6 Modifying Pixels by Position
This page intentionally left blank
CHAPTER
Introduction

1 to Computer Science
and Media Computation
1.1 WHAT IS COMPUTER SCIENCE ABOUT?

1.2 PROGRAMMING LANGUAGES

1.3 WHAT COMPUTERS UNDERSTAND

1.4 MEDIA COMPUTATION: WHY DIGITIZE MEDIA?

1.5 COMPUTER SCIENCE FOR EVERYONE

Chapter Learning Objectives


• To explain what computer science is about and what computer scientists are
concerned with.
• To explain why we digitize media.
• To explain why it’s valuable to study computing.
• To explain the concept of an encoding.
• To explain the basic components of a computer.

1.1 WHAT IS COMPUTER SCIENCE ABOUT?


Computer science is the study of process: how we or computers do things, how we
specify what we do, and how we specify what the stuff is that we’re processing. That’s
a pretty dry definition. Let’s try a metaphorical one.

Computer Science Idea: Computer Science Is the Study of Recipes


‘‘Recipes’’ here are a special kind—one that can be executed by a computational device,
but this point is only of importance to computer scientists. The important point overall is
that a computer science recipe defines exactly what has to be done.
More formally, computer scientists study algorithms which are step-by-step proce-
dures to accomplish a task. Each step in an algorithm is something that a computer
already knows how to do (e.g., add two small integer numbers) or can be taught how to
do (e.g., adding larger numbers including those with a decimal point). A recipe that can
run on a computer is called a program. A program is a way to communicate an algorithm
in a representation that a computer can execute.


To use our metaphor a bit more—think of an algorithm as the step-by-step way that
your grandmother made her secret recipe. She always did it the same way, and had a
28 Chapter 1 Introduction to Computer Science and Media Computation

reliably great result. Writing it down so that you can read it and do it later is like turning
her algorithm into a program for you. You execute the recipe by doing it—following
the recipe step-by-step in order to create something the way that your grandmother did.
If you give the recipe to someone else who can read the language of the recipe (maybe
English or French), then you have communicated that process to that other person, and
the other person can similarly execute the recipe to make something the way that your
grandmother did.
If you’re a biologist who wants to describe how migration works or how DNA
replicates, then being able to write a recipe that specifies exactly what happens, in
terms that can be completely defined and understood, is very useful. The same is true
if you’re a chemist who wants to explain how equilibrium is reached in a reaction.
A factory manager can define a machine-and-belt layout and even test how it works—
before physically moving heavy things into position—using computer programs. Being
able to exactly define tasks and/or simulate events is a major reason why computers
have radically changed so much of how science is done and understood.
In fact, if you can’t write a recipe for some process, maybe you don’t really under-
stand the process, or maybe the process can’t actually work the way that you are thinking
about it. Sometimes, trying to write the recipe is a test in itself. Now, sometimes you
can’t write the recipe because the process is one of the few that cannot be executed by
a computer. We will talk more about those in Chapter 14.
It may sound funny to call programs a recipe, but the analogy goes a long way. Much
of what computer scientists study can be defined in terms of recipes.
• Some computer scientists study how recipes are written: Are there better or worse
ways of doing something? If you’ve ever had to separate egg whites from yolks, you
realize that knowing the right way to do it makes a world of difference. Computer
science theoreticians think about the fastest and shortest recipes, and the ones that
take up the least amount of space (you can think about it as counter space—the
analogy works), or even use the least amount of energy (which is important when
running on low-power devices like cell phones). How a recipe works, completely
apart from how it’s written (e.g., in a program), is called the study of algorithms.
Software engineers think about how large groups can put together recipes that still
work. (Some programs, like the ones that keep track of credit card transactions,
have literally millions of steps!) The term software means a collection of computer
programs (recipes) that accomplish a task.
• Other computer scientists study the units used in recipes. Does it matter whether
a recipe uses metric or English measurements? The recipe may work in either
case, but if you don’t know what a pound or a cup is, the recipe is a lot less
understandable to you. There are also units that make sense for some tasks and
not others, but if you can fit the units to the tasks, you can explain yourself more
easily and get things done faster—and avoid errors. Ever wonder why ships at
sea measure their speed in knots? Why not use something like meters per second?
Sometimes, in certain special situations—on a ship at sea, for instance—the more
common terms aren’t appropriate or don’t work as well. Or we may invent new
kinds of units, like a unit that represents a whole other program or a computer, or
Section 1.1 What Is Computer Science About? 29

a network like your friends and your friends’ friends in Facebook. The study of
computer science units is referred to as data structures. Computer scientists who
study ways of keeping track of lots of data (in lots of different kinds of units) and
figuring out how to access the data quickly are studying databases.
• Can recipes be written for anything? Are there some recipes that can’t be written?
Computer scientists know that there are recipes that can’t be written. For example,
you can’t write a recipe that can absolutely tell whether some other recipe will
actually work. How about intelligence? Can we write a recipe such that a computer
following it would actually be thinking (and how would you tell if you got it right)?
Computer scientists in theory, intelligent systems, artificial intelligence, and
systems worry about things like this.
• There are even computer scientists who focus on whether people like what the
recipes produce, almost like restaurant critics for a newspaper. Some of these
are human–computer interface specialists who worry about whether people can
understand and make use of the recipes (“recipes” that produce an interface that
people use, like windows, buttons, scrollbars, and other elements of what we think
about as a running program).
• Just as some chefs specialize in certain kinds of recipes, like crepes or barbecue,
computer scientists also specialize in certain kinds of recipes. Computer scientists
who work in graphics are mostly concerned with recipes that produce pictures,
animations, and even movies. Computer scientists who work in computer music
are mostly concerned with recipes that produce sounds (often melodic ones, but
not always).
• Still other computer scientists study the emergent properties of recipes. Think
about the World Wide Web. It’s really a collection of millions of recipes (programs)
talking to one another. Why would one section of the Web get slower at some
point? It’s a phenomenon that emerges from these millions of programs, certainly
not something that was planned. That’s something that networking computer
scientists study. What’s really amazing is that these emergent properties (that
things just start to happen when you have many, many recipes interacting at once)
can also be used to explain noncomputational things. For example, how ants forage
for food or how termites make mounds can also be described as something that
just happens when you have lots of little programs doing something simple and
interacting. There are computer scientists today who study how the Web allows for
new kinds of interactions, particularly in large groups (like Facebook or Twitter).
Computer scientists who study social computing are interested in how these new
kinds of interactions work and the characteristics of the software that are most
successful for promoting useful social interactions.

The recipe metaphor also works on another level. Everyone knows that some things
in a recipe can be changed without changing the result dramatically. You can always
increase all the units by a multiplier (say, double) to make more. You can always add
more garlic or oregano to the spaghetti sauce. But there are some things that you cannot
change in a recipe. If the recipe calls for baking powder, you may not substitute baking
30 Chapter 1 Introduction to Computer Science and Media Computation

CHICKEN CACCIATORE
3 whole, boned chicken breasts 1 (28 oz) can chopped tomatoes
1 medium onion, chopped 1 (15 oz) can tomato sauce
1 tbsp chopped garlic 1 (6.5 oz) can mushrooms
2 tbsp and later 1 4 c olive oil 1 (6 oz) can tomato paste
1 1 2 c flour 12
of (26 oz) jar of spaghetti
14
c Lawry’s seasoning salt sauce
1 bell pepper, chopped (optional) 3 tbsp Italian seasoning
any color 1 tsp garlic powder (optional)
Cut up the chicken into pieces about 1 inch square. Saute the
onion and garlic until the onion is translucent. Mix the flour and
Lawry’s salt. You want about 1:4–1:5 ratio of seasoning salt to flour
and enough of the whole mixture to coat the chicken. Put the cut up
chicken and seasoned flour in a bag, and shake to coat. Add the coated
chicken to the onion and garlic. Stir frequently until browned.
You’ll need to add oil to keep from sticking and burning; I sometimes
add up to 1 4 cup of olive oil. Add the tomatoes, sauce, mushrooms,
and paste (and the optional peppers, too). Stir well. Add the Italian
seasoning. I like garlic, so I usually add the garlic powder, too. Stir
well. Because of all the flour, the sauce can get too thick. I usually
cut it with the spaghetti sauce, up to 1 2 jar. Simmer 20–30 minutes.

FIGURE 1.1
A cooking recipe—you can always double the ingredients, but throwing in an extra cup
of flour won’t cut it, and don’t try to brown the chicken after adding the tomato sauce!

soda. The order matters. If you’re supposed to brown the chicken and then add tomato
sauce, you won’t get the same result if you add tomato sauce and then (somehow) try
to brown the chicken (Figure 1.1).
The same holds for software recipes. There are usually things you can easily change:
the actual names of things (though you should change names consistently), some of
the constants (numbers that appear as plain old numbers, not as variables), and maybe
even some of the data ranges (sections of the data) being manipulated. But the order of
the commands to the computer, however, almost always has to stay exactly as stated.
As we go on, you’ll learn what can be safely changed, and what can’t.

1.2 PROGRAMMING LANGUAGES


Computer scientists write a recipe in a programming language (Figure 1.2). Different
programming languages are used for different purposes. Some of them are wildly
popular, like Java and C++. Others are more obscure, like Squeak and Scala. Some
others are designed to make computer science ideas very easy to learn, like Scheme or
Python, but the fact that they’re easy to learn doesn’t always make them very popular
or the best choice for experts building larger or more complicated recipes. It’s a hard
balance in teaching computer science to pick a language that is easy to learn and is
popular and useful enough to experts that students are motivated to learn it.
Why don’t computer scientists just use natural human languages, like English or
Spanish? The problem is that natural languages evolved the way they did to enhance
Section 1.2 Programming Languages 31

Python/Jython

def hello():
print "Hello World"

Java

class HelloWorld {
static public void main( String args[] ) {
System.out.println( "Hello World!" );
}
}

C++

#include <iostream.h>

main() {
cout << "Hello World!" << endl;
return 0;
}

Scheme

(define helloworld
(lambda ()
(display "Hello World")
(newline)))

FIGURE 1.2
Comparing programming languages: a common simple programming task is to print the
words ‘‘Hello World!’’ to the screen.

communications between very smart beings—humans. As we’ll explain more in the


next section, computers are exceptionally dumb. They need a level of specificity that
natural language isn’t good at. Further, what we say to one another in natural commu-
nication is not exactly what you’re saying in a computational recipe. When was the
last time you told someone how a video game like Mario Kart or Minecraft or Call of
Duty worked in such minute detail that they could actually replicate the game (say, on
paper)? English isn’t good for that kind of task.
There are so many different kinds of programming languages because there are so
many different kinds of recipes to write and people use these languages. Programs
written in the programming language C tend to be very fast and efficient, but they also
tend to be hard to read, hard to write, and require units that are more about computers
than about bird migrations, or DNA, or whatever else you want to write your recipe
about. The programming language Lisp (and related languages like Scheme, Racket,
and Common Lisp) is very flexible and is well suited to exploring how to write recipes
that have never been written before, but Lisp looks so strange compared to languages
like C. If you want to hire a hundred programmers to work on your project, it will be
32 Chapter 1 Introduction to Computer Science and Media Computation

easier to find a hundred programmers who know a popular language than a less popular
one—but that doesn’t mean that the popular language is the best one for your task!
The programming language that we’re using in this book is Python (visit http://
www.python.org for more information on it). Python is a popular programming lan-
guage, used very often for Web and media programming. The Web search engine
Google uses Python. The media company Industrial Light & Magic also uses Python.
A list of companies using Python is available at http://css.dzone.com/articles/
best-python-companies-work. Python is easy to learn, easy to read, very flexible,
but not as efficient as other programming languages. The same algorithm coded in C
and in Python will probably be faster in C. Python is a good language for writing pro-
grams that work within an application, like the image manipulation language GIMP
(http://www.gimp.org) or the 3D content creation tool Blender (http://www.
blender.org).
The version of Python used in this book is called Jython (http://www.jython.
org).1 Jython is a form of Python that is particularly effective for programming in
multimedia that will work across multiple computer platforms. You can download a
version of Jython for your computer from the Jython Web site that will work for all kinds
of purposes. Most programs written for Jython will work without change in Python.
In this book, we will describe how to program in Jython using a programming
environment called JES (Jython Environment for Students) that has been developed to
make it easier to program in Jython. JES has some features for working with media, like
viewers for sounds and images. JES also has embedded in it some special functions for
manipulating digital media that are made available to you without you doing anything
special. Anything you can do in JES, you can also do in normal Jython, though you
will have to explicitly include the special libraries.
Media Computation special libraries work with other environments and other forms
of Python, too.
• Pythy developed by Stephen Edwards and his colleagues at Virginia Tech is a
browser-based programming environment.2 All programming occurs through a
Web browser with Pythy, and programs and media are stored in the cloud. Programs
that work in JES will work in Pythy.
• A team led by Paul Gries at the University of Toronto has implemented portions
of the special media libraries in JES to work in other forms of Python.3
• The books at http://www.interactivepython.org/ by Brad Miller at Luther
College support manipulation of images in Python in all of their ebooks.
Let’s revisit here two of the most important terms that we’ll be using in this book:
• A program is a description in a programming language of a process that achieves
some result that is useful to someone. A program can be small (like one that imple-
ments a calculator) or huge (like one your bank uses to track all of its accounts).
1
Python is often implemented in the programming language C. Jython is Python implemented in
Java—this means that Jython is actually a program written in Java.
2
See https://github.com/web-cat/pythy for information on installing Pythy.
3
See https://code.google.com/p/pygraphics/ for information on the Pygraphics library.
Section 1.3 What Computers Understand 33

• An algorithm (in contrast) is a description of a process in a step-by-step manner,


not tied to any programming language. The same algorithm may be implemented in
many different languages in many different ways in many different programs—but
they would all be the same process if we’re talking about the same algorithm.

Computer Science Idea: Computer Science is about People


A famous computer scientist, Edsger W. Dijkstra, once said that, ‘‘Computer Science is
no more about computers than astronomy is about telescopes.’’ Computer science is
about people. People think about process in all those different ways (from a data
perspective, to issues of human−computer interfaces, to artificial intelligence). People
use programming languages, and they prefer different ways of communicating and
thinking, so different languages result. People make the programs and the languages.
Most decisions in computer science are not about computers. Most decisions in
computer science are about people.


1.3 WHAT COMPUTERS UNDERSTAND


Computational recipes are written to run on computers. What does a computer know
how to do? What can we tell the computer to do in the recipe? The answer is, “very,
very little.” Computers are exceedingly stupid. They really only know about numbers.
Actually, even to say that computers know numbers is not really correct. Computers
use encodings of numbers. Computers are electronic devices that react to voltages on
wires. Each wire is called a bit. If a wire has a voltage on it, we say that it encodes a 1.
If it has no voltage on it, we say that it encodes a 0. We group these wires (bits) into
sets. A set of 8 bits is called a byte. So, from a set of eight wires (a byte), we have a
pattern of eight 0’s and 1’s, for example, 01001010. Using the binary number system,
we can interpret this byte as a number (Figure 1.3). That’s where we come up with the
claim that a computer knows about numbers.4
A computer has a memory filled with bytes. Everything that a computer is working
with at a given instant is stored in its memory. This means that everything a computer
is working with is encoded in its bytes: JPEG pictures, Excel spreadsheets, Word
documents, annoying Web pop-up ads, and the latest spam email.
A computer can do lots of things with numbers. It can add them, subtract them,
multiply them, divide them, sort them, collect them, duplicate them, filter them (e.g.,
“Make a copy of these numbers, but only the even ones.”), and compare them and
do things based on the comparison. For example, a computer can be told in a recipe,
“Compare these two numbers. If the first one is less than the second one, jump to step
5 in this recipe. Otherwise, continue on to the next step.”
So far, it looks like the computer is a kind of fancy calculator, and that’s certainly why
it was invented. One of the first uses of a computer was to calculate projectile trajectories
during World War II (“If the wind is coming from the SE at 15 mph, and you want to
hit a target 0.5 miles away at an angle of 30 degrees East of North, then incline your
4
We’ll talk more about this level of the computer in the chapter Speed.
34 Chapter 1 Introduction to Computer Science and Media Computation

wires
0 27 = 128* 0 = 0 +
1 26 = 64* 1 = 64 +
0 25 = 32* 0 = 0 +
0 24 = 16* 0 = 0 +
1 23 = 8* 1 = 8 +
0 22 = 4* 0 = 0 +
1
1 2 = 2* 1 = 2 +
0 20 = 1* 0 = 0

interpreted as 74

FIGURE 1.3
Eight wires with a pattern of voltages is a byte, which is interpreted as a pattern of eight
0’s and 1’s, which in turn is interpreted as a decimal number.

launcher to . . .”). Modern computers can do billions of calculations per second. But
what makes the computer useful for general recipes is the concept of encodings.

Computer Science Idea: Computers Can Layer Encodings


Computers can layer encodings to virtually any level of complexity. Numbers can be
interpreted as characters, which can be interpreted in sets as Web pages, which can be
interpreted to appear as multiple fonts and styles. But at the bottom-most level, the
computer only ‘‘knows’’ voltages, which we interpret as numbers. Encodings let us forget
about lower-level details. Encodings are an example of abstraction, which give us new
concepts to use which allow us to ignore other details.


If one of these bytes is interpreted as the number 65, it could simply be the number
65. Or it could be the letter A using a standard encoding of numbers to letters called the
American Standard Code for Information Interchange (ASCII). If the 65 appears in a
collection of other numbers that we’re interpreting as text, and it’s in a file that ends in
“.html” it might be part of something that looks like this <a href=. . ., which a Web
browser will interpret as the definition of a link. Down at the level of the computer, that
A is just a pattern of voltages. Many layers of recipes up, at the level of a Web browser,
it defines something that you can click on to get more information.
If the computer understands only numbers (and that’s a stretch already), how does
it manipulate these encodings? Sure, it knows how to compare numbers, but how does
that extend to being able to alphabetize a class list? Typically, each layer of encoding
is implemented as a piece or layer in software. There’s software that understands how
to manipulate characters. The character software knows how to do things like compare
names because it has encoded that a comes before b and so on, and that the numeric
comparison of the order of numbers in the encoding of the letters leads to alphabetical
comparisons. The character software is used by other software that manipulates text in
files. That’s the layer that something like Microsoft Word or Notepad or TextEdit would
use. Still another piece of software knows how to interpret HTML (the language of the
Section 1.4 Media Computation: Why Digitize Media? 35

Web), and another layer of the same software knows how to take HTML and display
the right text, fonts, styles, and colors.
We can similarly create layers of encodings in the computer for our specific tasks.
We can teach a computer that cells contain mitochondria and DNA, and that DNA
has four kinds of nucleotides, and that factories have these kinds of presses and these
kinds of stamps. Creating layers of encoding and interpretation so that the computer is
working with the right units (recall back to our recipe analogy) for a given problem, is
the task of data representation or defining the right data structures.
If this sounds like a lot of software, it is. When software is layered this way, it
slows the computer down a bit. But the powerful thing about computers is that they’re
amazingly fast—and getting faster all the time!

Computer Science Idea: Moore’s Law


Gordon Moore, one of the founders of Intel (maker of computer processing chips)
claimed that the number of transistors (a key component of computers) would double at
the same price every 18 months, effectively meaning that the same amount of money
would buy twice as much computing power every 18 months. This means that computers
keep getting smaller, faster, and cheaper. This law has held true for decades.


Computers today can execute literally billions of recipe steps per second. They can
hold in memory literally encyclopedias of data! They never get tired or bored. Search
a million customers for an individual cardholder? No problem! Find the right set of
numbers to get the best value out of an equation? Piece of cake!
Process millions of picture elements or sound fragments or movie frames? That’s
media computation. In this book, you will write recipes that manipulate images,
sounds, text, and even other recipes. This is possible because everything in the computer
is represented digitally, even recipes. We would not be able to do media computation if
the media were not represented digitally. By the end of the book, you will have written
recipes to implement digital video special effects that create Web pages in the same
way that Amazon and eBay do, and that filter images like Photoshop.

1.4 MEDIA COMPUTATION: WHY DIGITIZE MEDIA?


Let’s consider an encoding that would be appropriate for pictures. Imagine that pictures
are made up of little dots. That’s not hard to imagine: look really closely at your monitor
or at a TV screen and you will see that your images are already made up of little dots.
Each of these dots is a distinct color. Physics tells us that colors can be described as the
sum of red, green, and blue. Add the red and green to get yellow. Mix all three together
to get white. Turn them all off and you get a black dot.
What if we encoded each dot in a picture as a collection of three bytes, one each for
the amount of red, green, and blue at that dot on the screen? And we collect a bunch
of these three-byte sets to determine all the dots of a given picture? That’s a pretty
reasonable way of representing pictures, and it’s essentially how we’re going to do it
in Chapter 4.
36 Chapter 1 Introduction to Computer Science and Media Computation

Manipulating these dots (each referred to as a pixel or picture element) can take a
lot of processing. There are thousands or even millions of them in a picture that you
might want to work with on your computer or on the Web. But the computer doesn’t
get bored, and it’s very fast.
The encoding that we will be using for sound involves 44,100 two-byte sets (called
a sample) for each second of time. A three-minute song requires 158,760,000 bytes
(twice that for stereo). Doing any processing on this takes a lot of operations. But at a
billion operations per second, you can do lots of operations to every one of those bytes
in just a few moments.
Creating encodings of this kind for media requires a change to the media. Look at the
real world: it isn’t made up of lots of little dots that you can see. Listen to a sound: Do
you hear thousands of little bits of sound per second? The fact that you can’t hear little
bits of sound per second is what makes it possible to create these encodings. Our eyes
and ears are limited: we can only perceive so much, and only things that are just so
small. If you break up an image into small enough dots, your eyes can’t tell that it’s not
a continuous flow of color. If you break up a sound into small enough pieces, your ears
can’t tell that the sound isn’t a continuous flow of auditory energy.
The process of encoding media into little bits is called digitization, sometimes
referred to as “going digital.” Digital means (according to the Longman Dictionaries)
Using a system in which information is recorded or sent out electronically in the form
of numbers, usually ones and zeros.5 Making things digital is about turning things from
continuous and uncountable to something that we can count, as if with our fingers.
Digital media, done well, feel the same to our limited human sensory apparatus
as the original. Phonograph recordings (ever seen one?) capture sound continuously
as an analog signal. Photographs (on film) capture light as a continuous flow. Some
people say that they can hear a difference between phonograph recordings and CD
recordings, but to our ears and most measurements, a CD (which is digitized sound)
sounds just the same, or maybe clearer. Digital cameras at high enough resolutions
produce photograph-quality pictures.
Why would you want to digitize media? Because then the media will be easier to
manipulate, to replicate exactly, to compress, to search, to index and classify (e.g., to
group similar images or sounds together), to compare, and to transmit. For example,
it’s hard to manipulate images that are in photographs, but it’s very easy when the same
images are digitized. This book is about using the increasingly digital world of media
and manipulating it—and learning computation in the process.
Moore’s Law has made media computation feasible as an introductory topic. Media
computation relies on the computer doing lots and lots of operations on lots and lots of
bytes. Modern computers can do this easily. Even with slow (but easy to understand)
languages, even with inefficient (but easy to read and write) recipes, we can learn about
computation by manipulating media.

5
Definition of “digital” from Longman Dictionary of Contemporary English. Copyright © 2009 by
Pearson Education. Reprinted with permission.
Section 1.5 Computer Science for Everyone 37

When we manipulate media, we need to be respectful of the author’s digital rights.


Modifying images and sounds for educational purposes is allowed under fair use laws
(which limit or create exceptions to an owner’s copyright). However, sharing or pub-
lishing manipulated images or sounds could infringe on the owner’s copyright.

1.5 COMPUTER SCIENCE FOR EVERYONE


Why should you learn about computer science by writing programs that manipulate
media? Why should anyone who doesn’t want to be a computer scientist learn about
computer science? Why should you be interested in learning about computation by
manipulating media?
Most professionals today manipulate media: papers, videos, tape recordings, pho-
tographs, and drawings. Increasingly, this manipulation is done with a computer. Media
are very often in a digitized form today.
We use software to manipulate these media. We use Adobe Photoshop for manip-
ulating our images, and Audacity to manipulate our sounds, and perhaps Microsoft
PowerPoint for assembling our media into slideshows. We use Microsoft Word for
manipulating our text, and Google Chrome or Microsoft Internet Explorer for
browsing media on the Internet.
So why should anyone who does not want to be a computer scientist study computer
science? Why should you learn to program? Isn’t it enough to learn to use all this great
software? The following sections provide answers to these questions.

1.5.1 It’s About Communication


Digital media are manipulated with software. If you can only manipulate media with
software that someone else made for you, you are limiting your ability to communicate.
What if you want to say something that can’t be said in software from Adobe, Microsoft,
Apple, and the rest? Or what if you want to say something in a way they don’t support?
If you know how to program, even if it would take you longer to do it yourself, you
have the freedom to manipulate the media your way.
What about learning these tools in the first place? In our years working with com-
puters, we have seen many types of software come and go as the package for drawing,
painting, word processing, video editing, and so on. You can’t learn just a single tool
and expect to be able to use it for your entire career. If you know how the tools work,
you have a core understanding that can transfer from tool to tool. You can think about
your media work in terms of the algorithms, not the tools.
Finally, if you’re going to prepare media for the Web, for marketing, for print, for
broadcast, or for any use whatsoever, it’s worthwhile for you to have a sense of what’s
possible and what can be done with media. It’s even more important as a consumer
of media that you know how the media can be manipulated, to know what’s true and
what could be just a trick. If you know the basics of media computation, you have an
understanding that goes beyond what any individual tool provides.

1.5.2 It’s About Process


In 1961, Alan Perlis gave a talk at MIT in which he argued that computer science, and
programming explicitly, should be part of a liberal education [35]. Perlis is an important
38 Chapter 1 Introduction to Computer Science and Media Computation

figure in the field of computer science. The highest award in computer science is the
ACM Turing Award. Perlis was the first recipient of that award. He’s an important figure
in software engineering and he started several of the first computer science departments
in the United States.
Perlis’s argument can be made in comparison with calculus. Calculus is generally
considered part of a liberal education: not everyone takes calculus, but if you want to
be well educated, you will typically take at least a term of calculus. Calculus is the
study of rates, which is important in many fields. Computer science, as stated earlier
in this chapter, is the study of process. Process is important to nearly every field, from
business to science to medicine to law. Knowing process formally is important for
everyone. Using a computer to automate processes has changed every profession.
Jeannette Wing has argued that everyone should learn computational thinking [23].
She views the types of skills taught in computing as critical skills for all students. This
is what Alan Perlis predicted: that automating computation would change the way we
learn about our world.

1.5.3 You Will Probably Need It


A team of researchers at Carnegie Mellon University did a study in 20056 where they
answered the question, “In the future, where will the programmers be, and how many
will there be?” They predicted that most programmers would not be professional soft-
ware developers. Most people who wrote programs would likely be people who needed
to write little programs to do something that they needed in their daily work. They
estimated that the ratio of professional software to end-user programmers would be as
high as 1:9, i.e., for every professional programmer in the world, there are nine more
people who are programming but just to help them out with their daily work. That result
suggests that many of you now reading this book will likely need to program one day,
even if you never make it your career.
The reality is that many people program today. Scientists and engineers write pro-
grams to create models and test them in simulations, or to analyze data. Graphics
designers write programs to make program tasks in Photoshop or GIMP to save them-
selves time, or to move their designs onto the Web. Accountants program when they
create complex spreadsheets. Many professionals need to store and manipulate process,
and thus learn to program, just as Alan Perlis predicted.

PROBLEMS
1.1 A study performed by a team of researchers at Carnegie Mellon University
in 2005 predicted that most programmers would not be professional software
developers. Use a web browser and a search engine like Google to find out how
the population of programmers is being studied these days. List some possible
areas in which programming could be required in everyday life.
6
See http://dl.acm.org/citation.cfm?id=1083231.1083232&coll=DL&dl=ACM&CFID=347064215&
CFTOKEN=87606004.
Problems 39

1.2 The 2013 Nobel Prize in Chemistry was in some sense a Nobel Prize given for
work in computer science. What was the role of computers in that Nobel Prize?
1.3 Text characters are encoded in different ways. The bottom level is always binary
in bytes, but a different binary pattern can be used to represent different char-
acters. Two of these encodings are ASCII and Unicode. See if you can do Web
searches on ASCII and Unicode. What’s the difference between ASCII and
Unicode? Why would we need Unicode if we already had ASCII?
1.4 Consider the representation for pictures described in Section 1.4, where each
dot (pixel) in the picture is represented by three bytes, for the red, green, and blue
components of the color at that dot. How many bytes does it take to represent a
640 by 480 picture, a common picture size on the Web? How many bytes does
it take to represent a 1024 by 768 picture, a common screen size? (What do you
think is meant now by a “three megapixel” camera?)
1.5 One bit can represent 0 or 1. With two bits you have four possible combinations
00, 01, 10, and 11. How many different combinations can you make with four
bits or eight bits (one byte)? Each combination can be used to represent a binary
number. How many numbers can you represent with 2 bytes (16 bits)? How
many numbers can you represent with four bytes?
1.6 Microsoft Word used to use an encoding of a word-processing document called
“DOC.” Most recent versions of Microsoft Word use a different encoding called
“DOCX.” What’s the difference between them?
1.7 One of the powerful ideas in computer science is that encodings can be layered.
Most of the encodings we’ve talked about so far (e.g., pixels in a picture, char-
acters, floating point numbers) are based on binary. XML is a way of encoding
information in text, which is in turn encoded in binary. What are the advantages
and disadvantages of using XML rather than binary encodings?
1.8 How can you encode a floating-point number in terms of bytes? Do a search
on the Web for “floating point.” You will find that there are different encodings
of floating point numbers. Take a common one like the IEEE Floating Point
Standard as an example. Assuming single precision, what is the largest and
smallest numbers that you can represent in that encoding?
1.9 As we said in the chapter, computer science is about people. Start your explo-
ration of computer science by exploring the people who are computer scientists
and influence computer science. As you do, find Web sites that you believe are
credible for your information, and include the URL in your answers—with your
reasons for believing that source is credible. What general rules do you use to
determine what is a credible Web site?
1.10 What is digitization? Define digital as per Longman Dictionaries. Justify the
need to digitize media. How has Moore’s Law made media computation feasi-
ble? Bring out the difference between phonograph and photograph.
1.11 Search for Gordon Moore on the web. What claim was he making with respect
to computing power? What was Moore’s observation?
Another random document with
no related content on Scribd:
organization of Moslem society was based, and by which it had
always been maintained. It had not received the sanction of popular
approbation or consent. The dethronement of Hischem was an
arbitrary deed of violence unconfirmed by any evidence of voluntary
abdication. As there had been no formal renunciation of vested
rights, those rights were only suspended, and the subjects of the
Khalif were not, in law, absolved from their allegiance.
The constitution of the Council of State, whose jurisdiction
extended but a short distance beyond the walls of Cordova, was
partly oligarchical and partly democratic. A formal assemblage of
citizens conferred upon Ibn-Djahwar, the most prominent member of
that body, an office whose powers and privileges appertained to the
anomalous dignity of the autocratic supreme magistrate of a
republic. The course of Ibn-Djahwar was characterized by the
greatest moderation and justice. Unlike the Cæsars of Rome, whose
despotic edicts were registered by an obsequious senate, the
president of the Moorish Council of State refused, of his own volition,
to decide or even to examine any question until it had been publicly
presented to his associates, and he required that all official
communications should be addressed to them. This habitual
deference to the opinions of his colleagues, which, however,
invariably coincided with his own, increased the consideration in
which he was held by the nobility, the army, the clergy, and the
people. The new magistrate, in addition to the eminent qualifications
which both suggested and justified his promotion, was aided by
many adventitious circumstances which rarely fail to elicit the
admiration or the homage of mankind. He belonged to a family of
ancient and distinguished lineage. His ancestors had served the
khalifs in the departments of finance and war. He was the most
opulent citizen of the capital, and had managed, by an exercise of
thrift and economy unusual in his station, to make vast
accumulations to his wealth without ever incurring the suspicion of
corruption or tyranny. The measures he adopted for the public
welfare were dictated by the most exemplary prudence and wisdom.
Taxes were reduced. Mercantile enterprise was promoted by the
assurance of public security, derived from the protection of the
highways and the repression of crime. Intimate commercial relations
were established between Cordova and the other principalities of
Andalusia, resulting in the interchange of commodities and the
extension of trade. With a prudent regard for future contingencies, he
provisioned the principal cities and forts under his jurisdiction. The
magazines of the capital alone contained supplies for the entire
population of the kingdom for many months. Important reforms were
instituted in the army. The Berbers, ever an element of discord, were
disbanded. Such as had been notorious for their atrocities were
exiled. Their places were filled by a volunteer soldiery, which, in its
general character, corresponded to our militia, and in whose
organization the sentiments or the prejudices of no single faction
were allowed to predominate. One division of this force, commanded
by an officer of experience and ability, was made responsible for the
peace of the city. The most distinguished citizens were enrolled in
the guard of public safety, and by turns patrolled the streets. Public
business was transacted with no more ceremony than was required
to make it impressive by commanding respect. The numerous throng
of parasites and dependents usually considered an indispensable
appendage to the royal dignity no longer encumbered the
antechambers of the palace. The formerly lucrative profession of
informer, patronized by even the greatest khalifs as a precaution
against treason, became deservedly infamous. The judicial tribunals
were organized in the interests of equity. Competent advocates, who
received compensation from the public treasury, were appointed to
prosecute the causes of such as were too poor to employ counsel.
Immigration was encouraged, and a considerable portion of the
capital which had been demolished during the civil wars was rebuilt
by the colonists, who, weary of perpetual strife, sought the protection
of a new government which seemed to offer to its subjects the fairest
hopes of peace and tranquillity. The administration of the finances
was conducted in accordance with the strictest principles of
economy, and officials charged with the collection of taxes were
compelled to render accounts at stated times, and were held
responsible, under heavy penalties, for the performance of their
duties. The extraordinary and illegal burdens which had been
imposed upon the mosques were abolished, and the clergy once
more entered upon the enjoyment of the revenues of which they had
been arbitrarily deprived. The disorders of the times had raised up a
great number of impostors,—half physicians, half sorcerers,—who,
to the great detriment of medical science and of the public health,
plied their trade, sustained by the ignorance and credulity of the
populace, ever easily deluded by the arts of charlatans. These were
prosecuted by the government for magic, and to provide against a
recurrence of the evil a college of physicians was organized, who
passed upon the knowledge and the qualifications of every future
practitioner. Such were the reforms effected by the prudence and the
sagacity of Ibn-Djahwar. Although they produced for a time a
semblance of prosperity, this was delusive and rather apparent than
real. The calamities which had, almost without intermission, afflicted
Cordova for a quarter of a century had forever degraded her from the
proud rank of imperial cities. Her inhabitants had been massacred.
Her wealth had been dispersed. Her trade had been destroyed. The
literary prestige which had exalted her name far above even those of
the polished capitals of the Moslem empire of the East had been
swept away amidst the turmoil of barbarian supremacy. Henceforth
the political eminence which she had once enjoyed was to be
transferred to the cities of Toledo, Saragossa, Almeria, Badajoz,
Seville, and Granada.
The policy of the early khalifs, who thoroughly appreciated the
dangerous character of their African allies, had established the
Berber hordes on the northern and western frontiers of their
dominions, and as far as possible from their capital. The incessant
warfare maintained by the Christians, as had been foreseen, so
occupied these barbarians that their attention was diverted from the
provinces of the South by the circumstances of their location, and
the consequent demand for unremitting vigilance required by the
proximity of an audacious and persevering enemy. The loyalty of the
governors of this territory, whose capital was Saragossa, had never
been above suspicion. The propensity of the Africans to rebellion
was habitually indulged by their chieftains, who carried into the
distant North the licentious independence of the Desert. During the
existence of the khalifate, the Emirs of Saragossa conceded to the
Ommeyade princes the doubtful allegiance of tributary vassals rather
than the implicit obedience of faithful subjects. Their martial instincts,
their predatory inclinations, and their constant familiarity with danger
made them a race of formidable and experienced warriors. The
family of Ibn-Hud, whose most distinguished ancestor was appointed
governor of the frontier by the Khalif Abdallah, was the founder of the
dynasty which raised Saragossa to great political influence among
the independent estates of Moorish Spain. By political alliances with
its Christian neighbors, it long preserved the integrity of its domain. It
encouraged agriculture, commerce, manufactures. It patronized the
arts. The portal of the palace mosque, still intact, conveys an idea of
the barbaric extravagance of its architecture. Its princes were far
from considering the pursuits of science as incompatible with regal
dignity. One composed a work on mathematics. Another delighted to
pass the hours of darkness in the study of the heavens. It was a
singular destiny which had transformed the seat of these ferocious
nomads—as a rule so insensible to extraneous influences—into one
of the centres of Moslem civilization.
The fortunate experiment of Cordova in abolishing the empire—a
measure which resulted in the restoration of peace—was imitated by
Seville, a city which in population, opulence, and commercial
resources had always been a powerful rival of the capital, and was
now destined to assume a pre-eminent rank among the ephemeral
dynasties of the Peninsula.
The expulsion of Kasim by the infuriated mob of Cordova was
followed by his exclusion from the territory of Seville. Popular
indignation had been aroused by a tyrannical order requiring that a
thousand houses should forthwith be vacated by the citizens for the
accommodation of his African followers. A garrison of Berbers had
already exasperated the inhabitants by its repeated acts of insolence
and cruelty. The prospect of an army of privileged banditti being
quartered in their homes, an occupancy which was equivalent to
absolute confiscation, drove the people of Seville to revolt. Abul-
Kasim-Mohammed, the Kadi, and other representatives of the
malcontents by promises of military promotion and pecuniary
rewards easily induced the Berber governor to renounce the service
of a master whom fortune seemed about to abandon. The gates
were closed in the very face of the Emir. The walls were occupied by
thousands of armed citizens prepared to defend, at all hazards, their
newly obtained liberty. Kasim, after stipulating for the delivery of his
treasures and the restoration of his sons who happened to be at that
time in the city, consented to retire forever from the scenes of his
former power. His rear-guard had scarcely been lost sight of from the
battlements before the Berber garrison was notified to depart, and,
relieved from apprehensions of hostile interference, the Sevillians
proceeded without delay to the task of political reorganization.
By the unanimous voice of the multitude, prompted by the nobles,
who, nevertheless, regarded his wealth with envy and his popularity
with disdain, the Kadi was offered the supreme magistracy. The
character of this personage, whose descendants played a prominent
part in the subsequent events of Andalusia, was a singular
compound of executive ability, profound dissimulation, and insatiable
avarice. Unlike the aristocratic ruler of Cordova, his origin was mean
and plebeian. The eminent genius of his father Ismail, who attained
to equal distinction in the widely different professions of arms,
theology, and law, first attracted public notice to a family
inconspicuous as yet except for the honorable principles and the
plodding industry of its members. He had transmitted to his son a
large share of his talents; but Abul-Kasim was deficient in those
virtues which in a responsible station often compensate for the
absence of distinguished abilities. His office of kadi, which he had
secured by flattery and retained by treason, he valued only as a
stepping-stone to absolute power. Aware that the tender of
sovereignty was not a recognition of superior merit, but a shrewd
artifice of the nobles by which, in case of the restoration of the
House of Ibn-Hamud to the throne, their caste might contrive to
escape and the wrath of the avenger be concentrated on the head of
an individual whose obscure birth, dignified by immense possessions
and ever-increasing influence, rendered him peculiarly obnoxious to
the aristocratical order, Abul-Kasim declined the invidious distinction.
When urged to reconsider his decision, he finally consented to
accept, provided councillors of his own choice were associated with
him in the administration. This having been readily conceded, he
appointed several of the most prominent and haughty members of
the Sevillian nobility, whose protection might be secured or their
treasonable complicity established in the event of a counter-
revolution, together with a number of his own dependents, who had
little to recommend them but a talent for intrigue and a blind devotion
to the interests of their patron.
The first efforts of Abul-Kasim were directed to the establishment
of a military force. For the first time since the Conquest, Seville was
left absolutely destitute of the ordinary means of defence. With the
expulsion of the Berbers, the last individual trained in the profession
of arms had disappeared. The arsenal was well provided with
military supplies, but neither the magistrate nor the people had the
least practical knowledge of the equipment or the discipline
indispensable for the effective organization of an army. The genius of
Abul-Kasim was, however, not daunted by even apparently
insuperable obstacles. He established recruiting stations in every
settlement which acknowledged the jurisdiction of Seville. The
tempting inducements offered—pay greatly exceeding that usually
allowed the soldiers of the khalif and the assurance of unrestricted
pillage—soon lured to his standard crowds of needy and rapacious
adventurers. The exigencies of the occasion forbade a critical
scrutiny of the nationality or the antecedents of these volunteers.
Arabs, Berbers, Christians, and foreigners were enlisted without
hesitation. In accordance with a well-established precedent, the
slave-markets were ransacked and the warlike natives of Nubia and
the Soudan purchased, and marshalled side by side with political
refugees, escaped criminals, and the dregs of the Sevillian populace.
The excesses of military license, long practised with impunity, had
rendered the profession of a soldier highly unpopular and even
disreputable, and few citizens of honorable connections and
irreproachable character could now be induced to voluntarily incur
the odium attaching to a class universally regarded as the scourge of
society. By untiring diligence and lavish expenditure, Abul-Kasim
finally succeeded in collecting a force of a few hundred men. No
more significant indication of the decadence of the Moslem empire
could be adduced than the fact that among a people renowned for
martial ardor and long accustomed to warfare an army of sufficient
strength to defend the most populous city of the Peninsula could not
be raised even by bounties, by the hope of plunder, or by purchase.
The difficulties arising from the anomalous political condition of
Seville were well known to the petty princes of the shattered
khalifate. The prize which the rich and defenceless city offered to the
ambition of an enterprising commander was too tempting to long
remain secure. Yahya, the son of Ali, the Edrisite Khalif who had
recently refused to trust his person among the perfidious inhabitants
of Cordova after they had tendered him the government and who
now ruled the principality of Malaga, suddenly appeared with a
powerful Berber army before the walls of Seville. Resistance was
impossible, and Yahya was informed that the city would
acknowledge his pretensions if his soldiers were not permitted to
enter the gates. This proposition he was not unwilling to accept, but
demanded, as an indispensable preliminary, the delivery of
hostages, to be selected from the families of the most prominent
citizens and the nobility. When this condition was proposed,
negotiations were at once suspended, for no one was prepared to
incur the risk. The Berbers had never renounced their savage
practices. They were not accustomed to observe the faith of treaties,
even where their own interests were concerned. The massacre of
captives and hostages was in perfect accordance with their
sanguinary instincts, and a sudden caprice, or the fear of escape,
might in an instant cause the annihilation of the flower of the
Sevillian youth. In this trying emergency neither the patriotism nor
the confidence of Abul-Kasim in his good fortune deserted him. He
placed his own son in the hands of the Berber prince, and removed
the apprehensions of his countrymen by convincing Yahya that this
pledge was a sufficient warrant for the fidelity of the people. Relying
on the authority vested in a nominal sovereign, the Kadi now seized
the opportunity of delivering himself from his councillors, and they
were, one after another, under various pretexts, dismissed from
office. Animated by the hope of one day being able to assert his
independence, he next devoted his energies to the acquisition of
new territory and the consolidation of his power. The noble self-
sacrifice he had exhibited in exposing his son to danger for the
public welfare had raised his character in the estimation of every
class of citizens. The nobility regarded him with undisguised
gratitude and admiration. His popularity with the masses, now
liberated from the insults of the soldiery, was unbounded. The faquis
extolled the justice and generosity of a magistrate who had removed
the tyrannical exactions imposed on their order. Secure of the
devotion of the army, whose interests he was careful never to
neglect, the Kadi, having formed an alliance with the governor of
Carmona, began to make incursions into the dominions of the
princes who surrounded him. He overran the province of Beja. He
plundered the settlements on the sea-coast west of Cadiz. The son
of the Emir of Badajoz was defeated by his troops and taken
prisoner. He even menaced Cordova, and compelled Ibn-Djahwar
and his colleagues to enlist Berber mercenaries for its defence. He
projected an expedition against the Christians, which failed on
account of the treachery of the Emir of Badajoz, who repaid the
previous misfortune to his arms with an ambuscade, which inflicted
serious injury on the forces of Abul-Kasim and caused his retreat.
Meanwhile, the isolated states and communities of the ancient
khalifate were threatened with the recurrence of a deplorable political
and social calamity. The depopulated provinces of Southern Spain,
the incessant prevalence of hostility, the desire of sharing in the
spoils of a country where their race had obtained incalculable wealth
and absolute power, the insatiable thirst of military adventure, had
produced, since the exaltation of the House of Ali, an enormous
African immigration. The Berbers now swarmed in countless
numbers over the plains to the south and west of the Sierra Morena,
a region once considered the garden of Andalusia, and where their
flocks still found a rich and abundant pasturage. Heretofore the
allegiance of these unruly adventurers had been divided among a
hundred petty chieftains, apparently incapable of harmony and
united in nothing save an undying hatred of the indigenous
population. Now, however, the case was altered. A national
sentiment had arisen, which was soon confirmed by the inspiration of
numbers, by the consciousness of strength, by the remembrance of
injury, and by the hope of revenge. All eyes were turned towards
Yahya, the ruler of Malaga, who, a Berber by descent and traditions,
was also the representative of an African dynasty, and, for that
reason, admirably qualified to be the leader of a national movement.
The universal enthusiasm was artfully encouraged by the secret
emissaries of the prince. The chieftains, with singular accord,
surrendered their precarious authority. The passions of the
barbarians were inflamed with the prospect of booty, and Yahya was
publicly recognized as the head of the entire Berber party.
No such unanimity of thought and action had, before this time,
ever been evinced by the turbulent and mutually jealous colonists
from Africa. The alliances of the various tribes had always been of
temporary duration, formed and maintained by necessity in the face
of an enemy. At the conclusion of a campaign each clan resumed
the unrestrained liberty and patriarchal independence incident to a
pastoral life. But the present organization promised to be permanent,
and was consequently fraught with danger. It augured ill for the
prevalence of civilized institutions in Europe that the country which,
even under the most adverse political conditions, had preserved in a
large measure its intellectual superiority and its artistic excellence
should become the prey of ruthless barbarians, who had already
desolated its fairest provinces and levelled its most beautiful
architectural monuments with the earth. The moment was a most
favorable one for the realization of this ominous scheme of barbarian
ambition. The people of the Moslem States of Spain were inflamed
with sentiments of mutual suspicion and hatred. The two great cities
of Cordova and Seville were experimenting with a novel and untried
form of government. The only ally of the latter, the governor of
Carmona, had recently been disposed of by the conquest of his
territory and its annexation to the principality of Malaga. But one
possibility existed of counteracting the impending ruin. Could a
coalition of the parties hostile to Berber supremacy be formed, the
destruction of all the beneficial results accomplished by the
Ommeyade dynasty might be averted. This plan, however, despite
its obvious necessity, seemed impracticable. The reciprocal enmity
maintained by citizens of the various principalities was far more
violent than the apprehension with which they regarded the possible
restoration of African tyranny. Some had sustained, others had
inflicted, unpardonable injuries upon their neighbors. In many
instances the despised Christian had been called in to contribute to
the humiliation of an execrated but too powerful adversary. By this
means, so repugnant to the principles of a conscientious Moslem,
the coveted vengeance had been secured. Fine estates had been
laid waste. Families had been extirpated. Entire districts had been
swept by conflagration. The sanctity of the harem, so dear to every
Oriental, had been profaned by the cruel insults and shameless
lubricity of the gigantic and repulsive barbarians of the North, and
their blasphemous jests had echoed through the stately colonnades
of Moslem temples, the desecration of whose hallowed precincts by
infidels was, under the law of Islam, punishable with death.
The penetrating sagacity of Abul-Kasim had early foreseen the
impending misfortune as well as the appropriate remedy. The
method he pursued in the application of that remedy does great
credit to his political ingenuity and administrative genius. It was
apparent at a glance that he himself, as the head of a coalition,
would not receive the support of even those whose property and
liberties were in imminent peril. Prejudice against the obscurity of his
birth, jealousy of his talents and his authority, fear of the
consequences of his ambition, would prevent that general co-
operation of all factions indispensable to success. He therefore
resolved to avail himself of a threadbare artifice, which had already
more than once been practised with surprising results by
unscrupulous aspirants to power. He determined to again resurrect
the unfortunate Hischem II., by the assistance of his name rescue
the Peninsula from the threatened Berber domination, and, having
consolidated its scattered fragments, to claim as his own reward the
sovereignty of the restored khalifate. The fate of the royal puppet of
Al-Mansur had never been absolutely ascertained. One account—
probably the most correct one—declared that he had perished when
Cordova was sacked by the Berbers. Another attributed his death to
the relentless cruelty of the tyrant Suleyman. The tales of
mendacious travellers, who declared that they had seen and
conversed with him in Arabia and Palestine, were eagerly received
and industriously circulated by the ignorant populace, powerfully
influenced by every tale of wonder and mystery. The attachment of
all classes to the memory of this degenerate monarch was
extravagant and almost inexplicable. He was endowed with none of
those splendid qualities which are commonly associated with the
office of royalty. Retained for years in rigid seclusion and veiled
whenever he appeared in public, his features and his demeanor
were alike unfamiliar to his subjects. The selfish and unprincipled
ambition of an aspiring minister had, by the application of every
device of sensual pleasure, reduced a mind of more than ordinary
parts to the verge of imbecility. Of the innumerable and brilliant
achievements of his nominal reign not one could be even indirectly
attributed to his personal influence or to his counsel. The lustre
which illuminated the throne of Hischem II., whose victorious
standards moved forward with unbroken success for almost a
generation, was only the reflected glory of the hajib, Al-Mansur. But
personal disadvantages and misfortune rather enhanced than
diminished his popularity, which grew with the progress of time.
Amidst the confusion and wide-spread disaster of foreign invasion
and intestine conflict, the intellectual defects and abandoned vices of
the last of the Ommeyades were forgotten. Only the military triumphs
and domestic security of a period made illustrious under his auspices
now appealed to the sympathy and the pride of the persecuted
nobles, citizens, and peasantry. They remembered that during his
reign, twice in every year for a quarter of a century, the Christian
frontier had receded for many leagues before the irresistible impetus
of the Moslem arms. They recalled with exultation that the trophies of
the holiest of Spanish shrines had been suspended in the
magnificent mosque of their capital. There existed still in the memory
of the aged reminiscences of great military displays on the eve of a
Holy War; of convoys guarding the rich spoils wrested from the
infidel; of splendid embassies which proffered the friendship or the
allegiance of distant kingdoms; of interminable processions of
manacled and dejected captives; of the impressive chants which,
publicly recited on the occasion of a triumph, attested the gratitude of
the fanatical and the devout; of the deafening acclamations of
assembled thousands. Repetitions of the romantic fables which
purported to relate the wanderings and the distress of Hischem had
invested these accounts with a plausibility which their manifold
inconsistencies never merited. The impossibility of some, the
obvious contradictions of others, the uncertain and suspicious origin
of all, were overlooked. It was sufficient for the uncritical and
excitable masses that a khalif whose reign had been identified with
the most famous epoch of Moslem greatness might possibly be still
alive. Under these circumstances, every ridiculous legend
concerning his appearance and his occupations, every new tale of
his condition and his movements, invented by imaginative foreigners,
obtained the ready credence of persons whose education and whose
knowledge of the world should have at once detected their absurdity.
In the city of Calatrava there had lived for several years a weaver
of mats, who in age, mental characteristics, and personal
appearance was said to bear an extraordinary resemblance to the
missing Hischem. The birthplace and the antecedents of this
individual, whose name was Khalaf—an appellation in itself
suggestive from its similarity to the title of sovereignty—were
unknown. His reticence on this point confirmed the rash assumption
of his imperial descent, and the consideration with which he was
regarded by his townsmen having aroused his ambition, he publicly
declared his identity with the Ommeyade prince. The people, already
half convinced, supported the imposture, which rested upon no
tangible evidence whatever, and, in their enthusiasm, they even went
so far as to declare their independence of their suzerain, the Emir of
Toledo. On the appearance of the latter at the head of an army,
however, the Calatravans repented of their indiscretion, promptly
expelled the aspiring mat-maker, and, with many protestations of
repentance, returned to their allegiance.
Intelligence of these events having been communicated to Abul-
Kasim, he caused search to be made for the unsuccessful impostor.
In due time his retreat was discovered, and he was conducted to
Seville. There he was submitted to the inspection of the concubines
and slaves of Hischem; their perplexity, their interest, or their fears
prevailed over their penetration; and the illiterate and obscure
mechanic was declared by those who were the best qualified to
judge to be the undoubted descendant of a line of celebrated kings.
This important preliminary having been accomplished, Abul-Kasim
announced the alleged discovery of Hischem by letter to all of the
princes and dignitaries of Moorish Spain. The result, while creditable
to their patriotism and national pride, did little honor to the keenness
of their wits or the accuracy of their perceptions. In Cordova alone
the elation of the populace overcame the authority but not the
discretion or the judgment of the magistrate; and Ibn-Djahwar, while
he might condemn the propagation of a contemptible political fraud,
was forced to recognize its utility in effecting a union of factions
whose combined influence might prevent the destruction of
organized government in the Peninsula and the consequent
retardation of the social and intellectual progress of Europe. With the
wildest demonstrations of joy, the inhabitants of the old Ommeyade
capital evinced their loyalty to a dynasty whose princes they had so
often adored and so often defied; the powers of the Council of State
were popularly supposed to be merged into those of the empire; and
Ibn-Djahwar and his aristocratic colleagues announced themselves
the servants of the plebeian impostor, who held a mimic court in the
palace of his master, the shrewd and intriguing Kadi of Seville. The
example of Cordova was speedily followed by the states of Denia
and the Balearic Isles, Tortosa, and Valencia.
Yahya, from his stronghold at Carmona, saw with wonder and
dismay the establishment and progress of the formidable
confederacy which had already thwarted his projects and threatened
the speedy overthrow of his power. The intoxication to which he was
habitually addicted caused him to neglect the precautions dictated by
ordinary prudence. While overcome with wine he was lured into a
nocturnal ambuscade and killed, with the larger portion of his
command; and Ismail, the son of the Kadi, who had charge of the
victorious detachment, returned to receive the congratulations of the
people of Seville.
The death of Yahya was a fatal blow to the hopes of the Berber
party. None of his family possessed, in an equal degree, talents for
organization or the confidence of their followers, advantages which
had so effectually promoted the fortunes of the deceased
commander. His death was no sooner known than the Berbers
disbanded, and with characteristic inconstancy returned to the
tranquil pursuits of pastoral life. Even the integrity of his own
dominions could no longer be maintained. His brother Edris was
raised to the throne of Malaga, but Mohammed, a cousin of the
latter, had already received the homage of the garrison of Algeziras;
the Africans of the province began to show signs of insubordination,
and Edris saw himself confronted at the outset of his reign with
difficulties which already seemed to portend a disastrous termination
of the projected Berber empire. The impatience of Abul-Kasim soon
outstripped his discretion as well as his resources. He endeavored to
secure for his puppet the prestige which would attach to his cause by
the occupation of Cordova, but the authorities of that city
peremptorily refused him admittance, and their temporary support of
the false Hischem having, in their judgment, served its purpose, they
formally renounced their allegiance to the impostor.
The centre of political disturbance in the Peninsula now shifts to
the Mediterranean coast and to the eastern confines of Andalusia.
Almeria had, since the dissolution of the khalifate, enjoyed, to a
remarkable degree, immunity from the prevalent disorders. That city
was the largest and the most opulent commercial emporium of the
Spanish Mohammedans. So far from having been injured by the
evils afflicting every other principality, she seemed to have profited
by the misfortunes of her neighbors. Her governors had been neither
conquered nor deposed, and her Emir still held the commission
bestowed by a khalif. The insecurity of other ports had practically
driven the commerce of the country to the protection of the mighty
castle which commanded her harbor. She had experienced few of
the political vicissitudes which had distracted the provinces of the
North and West. While they had fallen under African or Jewish
influence, she had retained all the traditions, the pride, and the
exclusiveness of a community where the Arab element
predominated. The nominal ruler was Zohair, a prince of mediocre
talents and effeminate character; but the control of the government
was substantially vested in the vizier, Ibn-Abbas, who united great
literary accomplishments and executive ability with boundless
avarice and a fertile genius for intrigue. He was one of the most
learned of men. The elegance of his epistolary style was famous. He
was a distinguished composer and improvisatore. His person was
strikingly handsome. His family traced their origin to the Defenders of
the Prophet. The vanity and presumption which he constantly
displayed were as offensive as his talents and accomplishments
were remarkable. His affluence and the state which he maintained in
an era of national decadence convey some idea of the prodigal
splendor exhibited by the Arab nobility in the prosperous days of the
empire. His palace equalled in extent and in the magnificence of its
appointments the most sumptuous abodes of royalty. The gardens
with which it was surrounded recalled, by their profusion of rare and
delicious flowers, the teeming wealth of tropical vegetation. Crowds
of slaves ministered to the caprices of a haughty but indulgent
master. Among the beauties of his harem were numbered five
hundred singers, selected as much for loveliness of feature and
symmetry of form as for their proficiency in the art of music. In one of
the noblest apartments of this princely mansion was the library. It
contained eighty thousand volumes, without including the separate
and unbound manuscripts,—if these were considered the figure
exceeded a hundred thousand. No room in the palace was furnished
with more splendor and extravagance. The shelves were of aromatic
woods inlaid with various precious materials, such as ivory, tortoise-
shell, and mother-of-pearl. The ornamentation was of gold. Enamels
glittered upon the walls. The floor was composed of great slabs of
white marble. In this elegant retreat the vizier, with whom the love of
literature was a passion, passed no inconsiderable portion of his
time. The fortune which enabled him to maintain such regal luxury
was estimated at the enormous sum of five hundred thousand
ducats, equal to seven million dollars of our money.
The policy of Ibn-Abbas had always been characterized by
unrelenting hostility to the members of other factions. Berbers,
Christians, and Jews had been repeatedly visited with decided
marks of his disfavor. His representations had induced Zohair, alone
of all the Arab princes, to hold aloof from the alliance formed against
the Africans. Hebrews were the especial objects of his antipathy. The
influence of this race, paramount in the adjacent principality of
Granada, and which had at different times interfered with the
accomplishment of his ambitious projects, now led indirectly to
important events, seriously affecting the stability of existing
institutions as well as the ultimate political destinies of the Peninsula.
Wonderfully favored by nature, as well as by the industry of a
numerous population, the province of Granada early began to give
evidence of that greatness which culminated in its erection into an
independent and powerful kingdom. The Jews, attracted by the
productiveness of its soil, the salubrity of its climate, and the
mercantile advantages of its situation, had settled there in such
numbers that the capital was, even before the accession of the first
Abd-al-Rahman, known as a Jewish city. The financial ability and
enterprise of their race had enabled them to surpass all commercial
rivals, and the trade of the province eventually passed into their
hands. Their wealth was beyond computation; their Semitic
affiliations protected them from political outrage and religious
persecution; while the experience and the abilities of their leaders
were often employed by the illiterate princes who, either as vassals
or petty sovereigns, occupied the throne of Granada. During the
period under consideration that state was ruled by Habus, a
monarch of African origin, and the influence of the Berber party was
predominant and unquestioned throughout his dominions, although
they contained many sympathizers with the fallen dynasty and
thousands of Christian tributaries.
At the head of the Hebrews of Granada was the famous Rabbi
Samuel, of the family of Levi, who enjoyed the unusual distinction of
being the chief councillor of a Mussulman sovereign. Born in an
humble station at Cordova, he early developed a taste for literature,
and had profited to the utmost by the admirable educational facilities
afforded by the schools of the capital. His diligence had been
rewarded by the acquisition of vast stores of knowledge. He was an
accomplished linguist, a talented poet. His conversation and his
writings demonstrated his thorough acquaintance with all the
learning of the time. His official correspondence, for felicity of
expression and purity of diction, was the envy of the scholars of
every Andalusian court. In the perfection of his chirography, he
excelled the performance of experts in that art, an extraordinary
attainment in an age when the greatest importance was attached to
regularity in the characters and beauty in the ornamentation of books
and inscriptions. The controversial works of Samuel enjoyed a high
reputation among the theologians and philosophers of his sect, while
his patronage of the learned and the liberality with which he
rewarded the struggling efforts of aspiring genius endeared his name
to every member of the commonwealth of letters. His familiarity with
the most abstruse branches of science, his proficiency in rhetoric,
mathematics, and astronomy were considered almost supernatural
by his contemporaries. He educated at his own expense deserving
but indigent youths of his nation; a number of secretaries were kept
constantly employed under his direction in transcribing copies of the
Talmud, to be presented to the poor; and afflicted and destitute Jews
of such distant countries as Egypt, Palestine, and Persia had
frequent reason to applaud the generous and charitable conduct of
the Chief Rabbi of Granada.
The advancement of Samuel to a position demanding the
exercise of the highest diplomatic talents, as well as the possession
of extensive knowledge and a profound acquaintance with human
nature, was due in a great measure to his own genius and to the
reputation his abilities had already acquired. He owed nothing to the
fortuitous advantages of rank or fortune. His family was poor. His
ancestors could boast of no connection with either the kings of
Judea or the priests of the ancient hierarchy. For years he had
maintained himself by the sale of spices in a little shop in the bazaar
of Malaga. An accident brought him to the notice of Al-Arif, Vizier of
the King of Granada, and he became the secretary of that official,
who, upon his death-bed, recommended him to his sovereign as a
servant eminently worthy of confidence. The event justified the wise
advice of the vizier. The rabbi of a detested race inspired the respect
and received the willing homage of the proudest Arab nobles, who
could not but admire the unaffected dignity with which he bore the
honors of his exalted station. He was the only prime-minister of his
sect mentioned in history who ever openly directed the policy of a
Moslem government. Such was his unerring sagacity that one of his
countrymen said that his counsels were such as might have been
directly inspired by the omniscience of God. He conducted the
administration of public affairs with the most consummate wisdom,
and the subsequent power and grandeur of the kingdom of Granada
were largely attributable to the genius of this eminent Hebrew
statesman.
A spirit of rivalry, aggravated by prejudice of race and jealousy of
power, had arisen between the viziers of Almeria and Granada.
While Samuel sustained his claims to superiority by a dignified
indifference, Ibn-Abbas endeavored to undermine and subvert the
influence of the rabbi by the most dishonorable artifices that hatred
could invent. But, to the mortification of the vindictive minister, his
efforts proved futile. In vain he caused to be spread fictitious rumors
of the avarice, the oppression, the ambitious hopes, and the
meditated treachery of his rival. The confidence of both monarch and
people was too well founded in the honor and integrity of Samuel to
be shaken by the malicious falsehoods of an avowed enemy. In the
mean time, Habus having died, an attempt was made by Ibn-Abbas
to excite a revolution by espousing the pretensions of a younger son
of the deceased king. But Badis, the heir-apparent, through the
influence of Samuel, ascended the throne in defiance of foreign
interference and internal discord. The first act of Badis, influenced
probably by the suggestions of his politic adviser,—for Samuel
continued to enjoy the favor and confidence of the son in the same
degree that he had formerly done under the father,—was an attempt
at reconciliation with Zohair, prince of Almeria. The latter affected to
receive these proposals with pleasure, and then, suddenly, without
the consent required by the law of nations, having traversed at the
head of an armed escort the territory of his neighbor, appeared
before the walls of his capital. The flagrant discourtesy of this act
was overlooked by the angry and astonished host in his desire for
harmony. Zohair and his companions were entertained with
becoming hospitality; and the Arab Emir was dazzled by the
splendors of a palace which stood on the site afterwards to be
occupied by the peerless Alhambra. But the prince of Almeria,
forgetting the amenities demanded by his position, bore himself with
insufferable arrogance; the members of his train assumed an air of
insolent superiority which aroused the indignation of the court and
the people; while the vizier, whose pride seemed to have mastered
his sense of official propriety, conducted himself without regard to the
consequences certain to result from the resentment of an infuriated
enemy. After a few days of ineffectual negotiation, the conference
was abruptly concluded; and Zohair and his retinue departed, only to
fall into an ambuscade which the outraged Granadans had prepared
for them in the depths of the sierra. The most heroic valor availed but
little in the presence of overwhelming odds; the possibility of escape
was effectually removed by the precipices and gorges of a mountain
solitude; and the prince with most of his followers perished upon the
weapons of the Berber soldiery or were hurled into ravines whose
depths were shrouded in perpetual darkness. Of those who survived,
the soldiers were beheaded; and the court dignitaries, who were
classed as non-combatants, were released, with a single exception.
Ibn-Abbas, after enduring the taunts of an ungenerous and
triumphant foe, was loaded with heavy fetters and thrown into a
dungeon. His pathetic appeals for mercy were unheeded by the
ferocious Badis. He vainly tried to tempt the cupidity of his jailers
with the offer of a bribe of sixty thousand ducats. In accordance with
the ruthless customs of mediæval barbarity, the captive minister was
dragged in chains before the throne and pierced with the sword-
thrusts of the monarch and his courtiers until life was extinct. Thus
perished the accomplished Ibn-Abbas through the consequences of
his own temerity, and with him was removed one of the greatest
obstacles of both national unity and Berber ambition.
Before the inhabitants of Almeria had recovered from the
consternation caused by the death of their sovereign, his domains
were appropriated by the Emir of Valencia. This step, perhaps
advised by the astute Kadi of Seville, at all events greatly
strengthened the power of that dignitary by extending the domain of
a vassal of the pretended Hischem and removing all prospect of the
accession of another dangerous enemy. This fortunate circumstance
having relieved his apprehensions of disturbance from the
successors of Zohair, the wily Abul-Kasim began to carry his
insidious operations into the court of Granada. The employment of
spies, some of whom occupied high official positions, made this
enterprising statesman intimately acquainted with the secret
transactions of every Divan in the Peninsula. His emissaries at
Granada, while informing him of the discontent prevailing in that city
on account of the tyranny and habitual intoxication of the King, which
kept the people in constant alarm, also communicated the opinion
that it would not be difficult, by means of an insurrection, to bring the
entire principality under the jurisdiction of Seville. To insure success
for this notable enterprise a competent leader was required, a task of
little difficulty in a country long accustomed to revolution and
swarming with able and unscrupulous men. There lived at this time
at Granada a prominent personage named Abu-al-Fotuh, who
combined the rather inconsistent professions of a soldier of fortune
and a peripatetic philosopher. A native of Djordjan, on the shores of
the Caspian,—the Hyrcania of the ancients,—the affluent
circumstances of his family had provided for him an excellent
education, and he was well versed in all the learning of the East. Not
only was he remarkably proficient in grammar and astronomy, but
the occult sciences were the objects of his especial predilection. A
recognized authority on geomancy and astrology, he was regarded
with awe by the vulgar, who thought that they detected in his habits
and occupations evidence of communication with the mysterious
powers of the unseen world. This popular impression his interests
engaged him to confirm by every artifice of perverted ingenuity. His
house was secluded from observation, and contained a well-
equipped laboratory, whose caldrons and alembics were firmly
believed by his neighbors to be implements devoted to the unlawful
practice of magic. In his dress and his manners he affected an air of
profound mystery and reserve. His garments were embroidered with
cabalistic symbols. His staff was entwined with serpents. In public he
maintained a taciturnity unusual with his voluble race, a trait too
often accepted by the thoughtless multitude as an indication of
superior wisdom. The scientific acquirements and literary tastes of
this remarkable individual did not deter him from adopting for his
pecuniary benefit the most disreputable arts of the charlatan. His
mansion was daily visited by crowds eager to learn the
prognostications of the future derived from the casting of horoscopes
and the study of the stars. Officials of distinguished rank were
included among his patrons; royalty itself did not disdain to
interrogate the oracles of destiny; and the relations of this learned
impostor with the King of Granada, embellished by the genius of an
accomplished writer, form the subject of one of the most fascinating
tales in the English language. Although his present occupations were
those of peace, the years of Abu-al-Fotuh had not been passed

You might also like