Recipe 1.15. Word-Wrapping Lines of TextProblemYou want to turn a string full of miscellaneous whitespace into a string formatted with linebreaks at appropriate intervals, so that the text can be displayed in a window or sent as an email. SolutionThe simplest way to add newlines to a piece of text is to use a regular expression like the following.
DiscussionThe code given in the Solution preserves the original formatting of the string, inserting additional line breaks where necessary. This works well when you want to preserve the existing formatting while squishing everything into a smaller space:
But sometimes the existing whitespace isn't important, and preserving it makes the result look bad:
Looks pretty ragged. In this case, we want to get replace the original newlines with new ones. The simplest way to do this is to preprocess the string with another regular expression:
But regular expressions are relatively slow; it's much more efficient to tear the string apart into
See Also
|
Wednesday, October 28, 2009
Recipe 1.15. Word-Wrapping Lines of Text
How This Book Is Organized
< Day Day Up > |
How This Book Is OrganizedThe book is divided into 13 chapters, organized by subject:
|
< Day Day Up > |
10.4 Package Specification
[ Team LiB ] |
10.4 Package SpecificationProgramming has always involved the "packaging" of related programs. This includes compiling a group of programs into a single object library and configuring the code of a single subsystem under one source code directory. Configuration management tools allow us to package our software under logical and functional subject areas so developers can easily locate programs for check-out and check-in purposes. For some environments, the highest abstraction of a unit of software is a procedure. The management of the software repository then becomes the management of many individual programs. For other languages, procedures that collectively satisfy a major functional requirement compile into one object module, managed as one software unit. This is the case with C programming where multiple C functions compile as one C object file. Java packages contain Java classes and the compiler relies on a match between directory and package name. A programmer who needs to use a procedure must first identify the module and then identify the specific function, procedure, or method needed. The C language uses a header file, a separate file from the C algorithmic code, that defines the interface�this is the first step in learning how to use another programmer's C code. Complexity of a programming language and the programming environment hinders development. IDEs are very successful with helping developers quickly locate reusable programs that are part of the development environment. Many of these IDE tools allow you to add your newly developed code to the library repository�this enables a developer to search for a particular interface and easily locate the API of another developer. Oracle's JDeveloper and Procedure Builder are IDE tools that provide this type of rapid development environment support. Without the use of an IDE, the features of a language can lead to small amounts of code reuse. One of the most powerful features of PL/SQL is the simplicity of the package specification. The PL/SQL language requires that the interface to a program collection compile into a single program unit. This program unit, the package specification, is not complex. It simply defines the API. The package body contains the details of the logic. You can incorporate PL/SQL package specification in the design process. High-level design includes defining high-level interfaces and documenting what an implementation will do. The package specification identifies interfaces and includes and uses code and comments to define the interface. A set of package specifications can represent the complete top-level design of a system. A package body with pseudocode and comments can represent the detailed design. In theory, should you see the code to a package specification on a programmer's desk, you should not know whether they are at the tail end of the design phase or the beginning of the code phase. The package specification overlaps the design and coding phase. The package specification defines a set of interfaces and operations performed on a set of objects, such as tables in a schema. It is also a compiled object in the database, subject to syntax rules and database privileges. The package specification is a single ASCII file that compiles as a single program unit. The package body is also a single ASCII file. The body compiles only after a successful compilation of the specification. You can put the specification in the same file as the body. 10.4.1 Syntax and StyleThe basic package specification syntax is:
There is no order to the procedures and functions in the specification. Put them in a logical order that suits the developer. The package body will include the PL/SQL code for each of the subprograms in the specification. Each subprogram in the specification must have an accompanying subprogram body. The package specification can declare data types such as a record type, data declarations such as a record, and exceptions. All data objects declared in the package specification are global. Therefore, only declare what needs to be global. The PROCEDURE statement in the package body, including the subprogram name, parameter names, parameter modes, and parameter types, must match the PROCEDURE statement in the specification. The same holds true for the FUNCTION subprogram. The package body template for the preceding specification is:
A package specification may declare exceptions. Let's modify PACKAGE_NAME so it declares an exception. The exception name is INVALID_OPERATION. The package code is the same, but with an exception declaration. Exceptions are sometimes declared all in the beginning of the spec, sometimes all at the bottom. Most important, comments should indicate which subprograms potentially raise which exceptions.
The user of PACKAGE_NAME has a question: "What procedures raise this exception?" Assuming the answer is PROCEDURE_NAME_1, the application code, should it choose to handle a possible exception, looks like this:
A package specification can also declare type definitions such as records. If a procedure is to return a student name and status, the option exists to declare a record type in the specification, as follows:
The package users should drive the design. You should consider the user community when designing the specification. Overloading of procedures and functions is a frequent technique to making a package interface acceptable to a wide audience. A reasonable suggestion to the prior PACKAGE_NAME specification is to declare a function in the spec and have this return a student record type. Why? Because it can make the application using the package easier to write and easier to read. Such a modification changes the specification to the following:
10.4.2 Developing a SpecificationA Booch (Grady Booch) diagram, showing just one package in Figure 10-5, is an excellent paradigm for design. These diagrams are easy to whiteboard for technical group discussion. They provide a clear image of the software architecture. Booch diagrams specify what operations exist. This enables one to look at the system requirements and judge if the operations designed will satisfy the requirements. Figure 10-5. Students Package.We begin this section with a software requirement to implement procedures that perform operations on the STUDENTS table. Chapter 4 includes the DDL, entity diagram, and sample data for a student application. We have some software to write. First, we need to implement the following:
We begin with a model depicting these operations. These operations belong together in a package because they each perform functions on the student's table. The package name will be STUDENTS_PKG. The development must transition from the graphical model to an interface design. We use the package specification as a vehicle for describing this interface. The following paragraphs illustrate the development toward an interface specification. ADD_STUDENT SUBPROGRAMBelow is a list of the columns of the STUDENTS table. Also refer to the STUDENTS table DDL in the data model demo of Chapter 4 (p. 146).
The STUDENT_ID column is the primary key and is generated with the sequence STUDENTS_PK_SEQ. This column value is determined in the body of the ADD_STUDENT procedure and will use the sequence attribute NEXTVAL during the INSERT statement. The three columns after STUDENT_ID are mandatory column values. The last two are optional. We should make STATE and LICENSE_NO optional parameters in the procedure call. These will have a default of NULL in the procedure interface.
An application program can use this interface with the following call:
The interface also permits:
NO_OF_STUDENTS SUBPROGRAMThis should be a function. The requirement is to return an attribute of the entire student body. The following is a function with some flexibility. The user can use this function to get the number of students who have a specific major, a specific status, or a combination. The two parameters passed would be (1) the subject major description value from the MAJOR_LOOKUP table and (2) a status value of "Degree" or "Certificate."
This interface permits the package user to write the following calls:
The STATUS column indicates the student's status with the school and has a CHECK constraint with valid values of "Degree" and "Certificate." PACKAGE SPECIFICATIONThe package specification now defines the interfaces. It initially appears to meet the requirements of adding a student and returning a count of students in the school. This is a starting point. We can add subprograms as needed. Additional procedures and functions can enhance the overall functionality of the package.
|
[ Team LiB ] |
Section 13.2. Data Display Debugger
13.2. Data Display DebuggerThe Data Display Debugger (DDD) is a graphical front end to GDB and other command line debuggers. DDD has many advanced features beyond simply viewing source code and stepping through a debug session. Figure 13-1 is a screen shot of the DDD's main screen. Figure 13-1. Data Display Debugger[View full size image] DDD is invoked as follows: $ ddd --debugger xscale_be-gdb webs Without the --debugger flag, DDD would attempt to invoke the native GDB on your development host, which is not what you want if you are planning to debug an application on your target system. The second argument on the DDD command line is the program you will be debugging. See the man page for DDD for additional details. Using the command tool as shown in Figure 13-1, you can step through your program. You can set breakpoints either graphically or via the GDB console window at the bottom of the DDD screen. For target debugging, you must first connect your debugger to the target system as we did in Listing 13-4, using the target command. This command is issued in the GDB window of the ddd main screen. When you are connected to the target, you can execute similar commands to the sequence described in the previous example to isolate the program failure. Figure 13-2 shows the DDD display during the later phase of this debugging session. Figure 13-2. Debug session in DDD[View full size image] Notice that in Figure 13-2 we have initiated the display of some important program variables that can help us narrow the cause of the segmentation fault. We can watch these variables as we step through the program using the command tool shown in the figure. DDD is a powerful graphical front end for GDB. It is relatively easy to use and widely supported for many development hosts. Consult Section 13.7.1 at the end of this chapter for a link to the GNU DDD documentation. |
Chapter A. Tutti-Fruti Ubuntu
Chapter A. Tutti-Fruti Ubuntu
In This Chapter
Kubuntu: The GNOMEless Ubuntu
Helping young learners with Edubuntu
The lightweight Xubuntu
You say Ubuntu, I say Kubuntu. You say Edubuntu, I say Xubuntu. Why don't we just . . . Anyway, there's more to Ubuntu than just Ubuntu. As the song says, there are actually four variations of Ubuntu.
This appendix introduces them all. Ubuntu makes it easy to download each version and burn a CD-ROM. You can make and boot any or all discs. It's fun to experiment and explore the diverse Ubuntu world and make the decision as to which one best suits your needs.
Trying a Different Look: Kubuntu
Kubuntu is Ubuntu that uses the K Desktop Environment (KDE) graphical desktop in place of GNOME. KDE and GNOME are similar in many ways. However, KDE is considered to use more advanced technology than GNOME.
The ordinary computer user won't find that much difference between KDE and GNOME. Some people like KDE, others like GNOME, and yet others — like myself — don't care.
Kubuntu provides the same range of applications, such as Openoffice.org, that Ubuntu does. New Kubuntu releases follow the same six-month schedule, too. Please browse www.kubuntu.org for more information about this product.
The following instructions assume you're working from an Ubuntu computer with a writable CD-ROM or DVD drive.
You need to download a Kubuntu CD-ROM image from an Ubuntu mirror to a computer from which you can burn the image to a writable CD. Follow these steps:
Click your Firefox browser icon on the GNOME panel.
Type www.kubuntu.org/download.php in the Location text box and press the Enter key.
Click the Download link for the latest version.
Click the link to your continent.
The menu of download sites expands to different countries.
Click your country.
The menu expands to show universities and various organizations.
Click any of the various university or organization links (that house Kubuntu mirrors).
The list further expands to one or more actual download sites.
Click a download site.
The Opening Kubuntu-6.10 dialog opens.
Click the Save File button.
The Downloads dialog opens, showing a progress meter.
Click the Cleanup button and close the dialog when the download finishes.
After you download the Kubuntu disc image, you'll want to burn a CD-ROM. Follow these steps:
Insert a writable CD-ROM in your computer's CD burner drive.
From the GNOME menu bar, choose SystemAdministrationTerminal.
Type the following command to burn the CD-ROM:
sudo cdrecorder -v Desktop/kubuntu*iso
When the burn finishes, you can either reboot directly from the new disc or eject the disc and use it to boot another machine. Your computer boots from the Kubuntu CD-ROM, just like an Ubuntu disc. After the computer boots, you see the screen in Figure A-1 .
Figure A-1: The Kubuntu screen.
If you're comfortable using Ubuntu, you should feel at home using the KDE interface in Kubuntu.
5.4. Test First
< Day Day Up > |
5.4. Test FirstHaving a good suite of tests is important�so important, that many developers advocate writing the tests for new code before a single line of the code itself! This is called test driven development, or TDD for short. Such tests represent the requirements that your code must satisfy in order to be considered correct. To see how Eclipse makes TDD simple, keep the unit test you just created, but delete the Factorial.java file (select it in the Package Explorer and press Delete). The editor for the FactorialTest class will shown an error immediately because the Factorial class is not defined anymore. This simulates the state you would be in if you had written your test class first. Put the text cursor on the first line that has an error and press Ctrl+1 (Edit Quick Fix). Select the "Create class 'Factorial'" option and press Enter. When the New Java Class dialog appears, press Enter to accept the defaults. Now, go back to the FactorialTest editor and note that the compiler complains that there is no factorial(int) method. Press Ctrl+1 to create one. Unfortunately, the current version of Eclipse is not always smart enough to figure out the right return type, so you may need to change the generated return type to be a double. Use a dummy return value (0.0) for now. At this point, Factorial.java should look something like this:
Tip: Of course, this is not the right way to calculate a factorial, but all you want to do at this point is get the program to compile again. Now you have a test case, a little bit of code, and no errors�so try running the tests. Unsurprisingly, they fail. At this point in actual TDD, you would go back to the code being tested and fix it so that it passes the tests, then add another test, make that work, and repeat the process until done. Compare this technique with what most people typically do. They write a bunch of code first, then write a trivial little test program to exercise that code (maybe something with a main() method and a few println() statements). Once that test is working, they throw the test away and assume their class will never break again. Don't ever throw tests away! Nurture them, slowly add to them, and run them often, preferably as part of an automated build and test system. Techniques even exist to create unit tests for user interfaces. Tip: When you get a bug report from your users, your first impulse may be to fix the bug. Instead, stop and write a unit test that fails because of the bug. Then, change the code so the test works. This ensures your fix actually solves the problem and helps improve your tests over time. The JUnit view is covered in more detail in Part VII. If you want to learn more about unit testing best practices, see:
|
< Day Day Up > |
3.1 Standard Algorithm
< Day Day Up > |
3.1 Standard AlgorithmThe standard pattern movement algorithm uses lists or arrays of encoded instructions, or control instructions, that tell the computer-controlled character how to move each step through the game loop. The array is indexed each time through the loop so that a new set of movement instructions gets processed each time through. Example 3-1 shows a typical set of control instructions. Example 3-1. Control instructions data structure
In this example, turnRight and turnLeft would contain the number of degrees by which to turn right or left. If this were a tile-based game in which the number of directions in which a character could head is limited, turnRight and turnLeft could mean turn right or left by one increment. stepForward and stepBackward would contain the number of distance units, or tiles, by which to step forward or backward. This control structure also could include other instructions, such as fire weapon, drop bomb, release chaff, do nothing, speed up, and slow down, among many other actions appropriate to your game. Typically you set up a global array or set of arrays of the control structure type to store the pattern data. The data used to initialize these pattern arrays can be loaded in from a data file or can be hardcoded within the game; it really depends on your coding style and on your game's requirements. Initialization of a pattern array, one that was hardcoded, might look something such as that shown in Example 3-2. Example 3-2. Pattern initialization
In this example, the pattern instructs the computer-controlled character to move forward 2 distance units, move forward again 2 distance units, turn right 10 degrees, turn right again 10 degrees, move forward 2 distance units, move forward again 2 distance units, and turn left 10 degrees. This specific pattern causes the computer-controlled character to move in a zigzag pattern. To process this pattern, you need to maintain and increment an index to the pattern array each time through the game loop. Further, each time through the loop, the control instructions corresponding to the current index in the pattern array must be read and executed. Example 3-3 shows how such steps might look in code. Example 3-3. Processing the pattern array
As you can see, the basic algorithm is fairly simple. Of course, implementation details will vary depending on the structure of your game. It's also common practice to encode several different patterns in different arrays and have the computer select a pattern to execute at random or via some other decision logic within the game. Such techniques enhance the illusion of intelligence and lend more variety to the computer-controlled character's behavior. |
< Day Day Up > |
Using Symmetric (Private) Key Encryption
< Day Day Up > |
Using Symmetric (Private) Key EncryptionAs mentioned previously symmetric key encryption uses a single private key for both encryption and decryption. To provide support for this type of encryption, the BCL defines the System::Security::Cryptography::SymmetricAlgorithm abstract class, which is the base class for all symmetric algorithm classes. There are wrapper classes for several popular symmetric cryptographic algorithms, all of which derive from this SymmetricAlgorithm class:
Essentially each of those classes are abstract base classes for their respective algorithms, and any class that implements any of those algorithms must derive from these classes. For example, a class called DESCryptoServiceProvider (derived from the DES class) provides a wrapper for the DES implementation provided by the Cryptographic service provider. Private Key Encrypting/Decrypting Demo Using DESThe CryptoStream class is used to perform cryptographic transformations on any data stream and is under the System::Security::Cryptography namespace. It derives from System::IO::Stream, and thus we can call any Stream methods on a CryptoStream object just as if it were a network or file stream object. The CryptoStream constructor is as follows:
The first parameter is a stream object that may be a file stream, a memory stream, or a network stream, and it's on this stream that the cryptographic transformation is performed. The second argument is an ICryptoTransform object that defines the cryptographic transform that is to be performed on the stream. Any class that derives from the SymmetricAlgorithm has a CreateEncryptor method that returns an ICryptoTransform object. Thus, to perform a DES transform on the data stream, instantiate a DESCryptoServiceProvider object and call CreateEncryptor on it, or, if you want to perform a Rijndael transformation, then instantiate a RijndaelManaged object and call CreateEncryptor. In fact you may also pass any class derived from the HashAlgorithm class, because they will all be implementing the ICryptoTransform interface, though the issue would be that hash algorithms are not key-based, and thus the security of the encryption would be considerably reduced. The third and last parameter for the CryptoStream constructor is a CrytopStreamMode enumeration value that specifies either read mode (CryptoStreamMode::Read) or write mode (CryptoStreamMode::Write). Now let's look at what it takes to encrypt a file. We'll look at a function with the following syntax:
As you can see, this file takes only two parameters�an input file name and an output file name. However, before I throw some code at you, let's look at the generic steps involved in encrypting a file and the details of how the EncryptFile accomplished each given step.
That's it. Eight simple steps (about 50 lines of C++ code) to do something as advanced as taking an input file, opening it, reading every byte, encrypting every byte, and then writing the encrypted data to disk. At this point, let's see the actual C++ code for the EncryptFile (Listing 4-1). (Note that the comments in the code are in bold to make it easier to tie the aforementioned file-encryption steps to the actual implementation code.) Listing 4-1. The EncryptFile function outputs encrypted data from a specified input file to a specified output using a supplied private key.
Now, let's turn our attention to the task of decrypting data. For this operation, I've included a function called DecryptFile:
Once again, I'll first list the basic steps of decrypting a file and outputting the results to another file and then present an implementation of that list in the form of the DecryptFile function.
Once again, we have eight easy-to-follow steps for reading data from a file, decrypting it, and writing it to another file. Listing 4-2 shows the code for the DecryptFile (again, the comments are in bold so that you can match these steps with the actual C++ implementation). Listing 4-2. The DecryptFile function takes input from a physical file and outputs DES decrypted data to a specified file name using a supplied private key.
It's one thing to present an allegedly helpful function (or two in this case), but let's take another step and see these functions at work in a demo application that allows you to both encrypt and decrypt files using a private key encryption algorithm�specifically, DES.
Now that you've seen how private key encryption works, let's have a look at public key encryption. |
< Day Day Up > |
Section 22.1. Performance Characteristics of Stored Programs
22.1. Performance Characteristics of Stored ProgramsMySQL stored programs can often add to application functionality and developer efficiency, and there are certainly many cases where the use of a procedural language such as the MySQL stored program language can do things that a nonprocedural language like SQL cannot. There are also a number of reasons why a MySQL stored program approach may offer performance improvements over a traditional SQL approach:
Having said that, we don't want to give you the impression that we think you should rewrite all of your non-trivial SQL statements in MySQL stored programs. In fact, it is usually the case that if you can express your needs in "straight" SQL, that will be the most efficient approach. And do remember that complex arithmetic computations will usually be slower in a stored program than in an equivalent SQL statement. |
Section 17.3. C API Datatypes
17.3. C API Datatypes
Here is a list of C API data types from the
mysql.h header file:
MYSQL
A database handle structure created by
mysql_init( ) and released with
mysql_close( ).MYSQL_RES
A structure for a results set from an SQL query. This
structure is used by fetch functions and is released with
mysql_free_result( ).MYSQL_ROW
A structure for holding a row of data from a results set. The
data is retrieved from this structure by the
mysql_fetch_row( ) function.MYSQL_FIELD
A structure for holding an array of information about a field
of a results set. The array may be set with the
mysql_fetch_field( ) function. The elements
include name, table, and
def for the default value.MYSQL_FIELD_OFFSET
Used for recording a pointer location for a results set. The
offset value can be retrieved by the
mysql_row_tell( ) function and deployed with
mysql_row_seek( ).my_ulonglong
A variable type for storing the number of rows for functions
such as mysql_affected_rows( ),
mysql_num_rows( ), and
mysql_insert_id( ). To print the value of a
variable using this type, copy the value to another variable that
uses the unsigned long type.
Chapter 7. I18N Actions
|
Chapter 7. I18N ActionsTopics in This Chapter
At the end of the 20th century, with the World Wide Web in its infancy, most Web sites were implemented for a single language, but that's starting to change as more Web sites offer content in multiple languages. Web sites that adapt to a reader's native language and customs have an obvious competitive advantage over those that do not. JSTL provides a number of actions that help you internationalize your Web sites:
JSTL also provides a handful of actions for formatting and parsing numbers, currencies, percents, and dates in a locale-dependent manner; those actions are discussed in "Formatting Actions" on page 308. This chapter begins with an overview of the first five actions listed above, followed by an introduction to internationalization concepts, including locales, resource bundles, Unicode, and charsets. Subsequently, we discuss how you can make the most of the JSTL actions listed above. If you don't know anything about the JSTL internationalization (I18N) actions or if you need to brush up on internationalization, you should read this entire chapter. If you're already familiar with the <fmt:message> action but you're not entirely comfortable with locales, resource bundles, charsets and Unicode, you can probably start reading at "I18N and L10N" on page 258.[1] If you've already used the <fmt:message> action and you understand the basics of internationalization, you can begin reading at "Localization Contexts" on page 263.
|
|
Chapter 6: Distinguished Names and Certificates
Chapter 6: Distinguished Names and Certificates
Overview
Asymmetric
encryption provides ways of allowing you to distribute keys with
relative safety that other people can use to send encrypted messages or
verify signatures you have created. The problem, however, is that from
the point of view of the people you are distributing the public keys
to, the simple presence of a public key is not enough for someone to
determine whether it is the public key they have or even if the use
they are being asked to put it to is one that you intended.
Distinguished names and the certificates that carry them were created to solve this problem.
This chapter introduces distinguished names,
certificates, and certification requests. Distinguished names contain
information about the owner of a public key carried by a certificate.
Certification requests provide a mechanism by which you can ask some
other party, presumably trusted by the people you want to give the
certificate to, to issue you with a certificate that can also be
trusted. In general, this is done by issuing a certificate that can be
verified using another certificate issued by the trusted party that is
already in the hands of the people who you want to accept your new
certificate.
By the end of this chapter, you should
Understand what an X.500 name is
Understand what a public key certificate is, most particularly those that use X.509
Be able to make use of the Java classes representing X.500 name and certificates
Be able to generate your own certification requests and certificates
Be able to create a certificate from a certificate request
Be able to form multiple certificates into a certificate chain, or path
Finally, you should understand how to make use of
the certificate storage class in Java and how to selectively retrieve
certificates from it.