text
stringlengths
14
5.77M
meta
dict
__index_level_0__
int64
0
9.97k
Discussion in '2007 Feature - Youth and Models' started by crystalaakre, Jul 21, 2007. donate, we will start a toy museum. This is something that could keep growing through the years, but would be really great to at least get started for the Youth Expo this year. Toys were one of my favorite exhibits at Bonanzaville as a kid!! with prizes to happen as events at the show this year. I'll keep you posted. Great idea Crystal! Remember the Sinefeld episode where he went out with that woman so he could play with all her antique toys? They were not supposed to be touched, but he got a bunch of them out and ended up getting in trouble for it. I guess I can't remember all of the details, but it was funny. The scary part is... I had most of those toys when I was a kid! I didn't think I was that old!! We will have to find a spot for an exhibit like you are describing. Maybe you have some ideas. I am looking forward to visiting the exhibit! The Toy Museum and kid's games will be taking place in the Expo building next to the carnival rides. We need volunteers to help organize the games and also knowledgeable folks to talk about toys of the past. If you would like to exhibit any old toys, there are some glass cases for this purpose and the building will be locked up at night. Please do! We'd love to see what our parents and grandparents did for entertainment as children!! For events, we will be having a nickel scramble on saturday and a potato sack race on sunday at around 1:00. We're flexible to other ideas if we can get more people to help out. Also, we are having an old fashioned paper doll hands-on area, jump rope, marbles, etc. Send me a message if you have any questions or ideas. thanks!! don't forget to clean up your toys! We attended the show this year. This is 3rd Show. Our kids really LOVED the activities in the Expo Building. They spent about 2.5 hours in there on Sunday morning. We hope that you will continue with this type of event for the kids...as an annual place to come play. Our daughter, Emily, spent hours cutting out the paper dolls that were given to her on the way home yesterday and also today. Joey, spent a lot of his time playing with the tractor pull. Our two oldest want to go back again. What we really liked about the space was that it was out of the weather (OK there was still dust). It's something we hope you will continue in the future in some sort of cement floor building. I also want to commend the enthusiasm and dedication of the 3 young adults working in the Expo area. They truly enjoy the show and are finding ways to give back. We are considering becoming members -- partially because of my conversations with them. If there is going to be dedicated space, we may be able to donate some wood blocks (for building toy houses, buildings, etc.) and could possibly show some smaller items. We have a camper to pull...so what ever we bring will need to fit behind the truck. Great job again with the games, paper dolls, and kids' tractor pull! Congratulations Crystal and Rachel (I apologize that I don't know the 3rd person) !!! You just got the best compliment that anyone can get at Rollag!! I just picked up the pedal tractor/skid/mat and weights tonight and thank you for the note you had left. You guys did a great job! I stopped by the expo building on Friday and I seen you helping the kids and the smiles on the kid's faces and I knew I didn't have to worry about the skid and pedal tractor. I'll for sure bring it down again next year. Carol, John and Family hope you join up - you will find that there are alot of great people at Rollag! The application for John is filled out and ready to be mailed. There is a pre-schooler in the mix, so I don't want to be stretched too far, and the 8 and 10 year olds still like to have one of us around on their adventures. On behalf of Crystal, Mike and myself, I just want to say thank you to Carol and her family, Brian and all the others who support the new exhibit we are developing!! It is so awesome to hear comments like yours and we really appreciate it! We had a lot of fun working (and playing) out in the Expo building this year and are thrilled to hear that there are others who enjoyed it just as much as we did!! We also learned a few things throughout the weekend and we are going to use that knowlegde to make the exhibit even better for next year!! Thanks again for all your great comments and your support!! Let us know if you have any suggestions for us as well...we are always open to new ideas!! Thanks Carol! Your kids were great! Hopefully Joey will want to come back and help out with the pedal tractor pull again! Thanks to everyone who brought things in to share as well. We couldn't have done it without that support! We had a lot of good response up there in the expo building and some kids stayed for hours playing old fashioned games and trying out the pedal pull. Rachel, Mike and I have some really good plans for next year now that we know what works and what doesn't. We even got a few people to offer to bring their toys to display!! I promise I'll get some pictures up by the end of the week to share. Keep a look out in the showbook, I think Tim got a few shots of us having fun as well! Crystal,Mike, and Rachel thank you for all your work the girls loved it Maybe my children will teach me chinese checkers for next year. toy museum photos as promised! Great pictures Crystal... Lots of smiles! Congrats again on a job well done. We have got to keep something like this going every year!
{ "redpajama_set_name": "RedPajamaC4" }
8,710
Fiesta Fruits In Plastic Confectionery Dispenser 1.3 kilo of Fiesta Fruits packed in confectionery dispenser. Statutory information sheet included. Finished weight = 1.4 kilos. 1.3 kilo of Fiesta Fruits packed in confectionery dispenser. Statutory information sheet included. Finished weight = 1.4 kilos.
{ "redpajama_set_name": "RedPajamaC4" }
5,990
Q: When i receive puch notification , the new one is replacing the old one . How can i keep them both? Sending notificaion from server : var req = { method: 'POST', url: 'https://gcm-http.googleapis.com/gcm/send', headers: { Content-Type': 'application/json', 'Authorization': 'key=xxxx' }, data: { "registration_ids": tokens, "data" :{ "title": "title", "body": "message" } } }; I am receiving the notification successfully , but when i'm sending another one , the new one is replacing the old one . is there any way to keep them both or collapse notifications ? A: You have to change something in your application end not server side. e.g. If you use notification manager. Your code should be yourNotificationManager.notify(new Random().nextInt(), yourNotificationBuilder.build()); A: I am using Ionic/Cordoca and angularJS , here is my app code : var config = { "senderID": "xxxxxxxxxxxx", 'ecb': 'window.onNotification' }; $cordovaPush.register(config).then(function(result) { // Success }, function(err) { // Error }) window.onNotification=function(e){ switch( e.event ) { case 'registered': alert('registred'); break; case 'message': alert('just received a notification'); break; case 'error': alert('error'); return; default: return; } }
{ "redpajama_set_name": "RedPajamaStackExchange" }
4,516
Thurgarton railway station is a Grade II listed station which serves the village of Thurgarton in Nottinghamshire, England. History It is on the Nottingham to Lincoln Line, which was engineered by George Stephenson and opened by the Midland Railway on 3 August 1846. The contractors for the line were Craven and Son of Newark and Nottingham; the station buildings are in the neo-Tudor style and were probably designed by Thomas Chambers Hine. At the station much of the original décor remains apart from the electric barriers added later. Stationmasters J. Howitt 1846 - 1865 C. Brown 1865 - 1866 John Kind 1866 - 1898 Job Frederick Fisher 1898 - 1921 (formerly station master at Bleasby) Sidney Richard Holden ca. 1924 - 1932 (afterwards station master at Ullesthorpe) J.F. Georgeson from 1937 (also station master at Lowdham) H. Simpson ca. 1950 Facilities The station is unstaffed and offers limited facilities other than two shelters, timetables and modern help points. The full range of tickets can be purchased from the guard on the train at no extra cost as there are no ticket issuing facilities at this station. Services All services at Thurgarton are operated by East Midlands Railway. The typical off-peak service is: 1 train every 2 hours to via 1 train every 2 hours to The station is also served by a small number of trains between , Nottingham and . Gallery References External links Railway stations in Nottinghamshire DfT Category F2 stations Former Midland Railway stations Railway stations in Great Britain opened in 1846 Railway stations served by East Midlands Railway Grade II listed buildings in Nottinghamshire Thomas Chambers Hine railway stations
{ "redpajama_set_name": "RedPajamaWikipedia" }
2,769
{"url":"http:\/\/www.plexity.com\/hlb8vxjn\/line-of-invariant-points-d44901","text":"<>>> So the two equations of invariant lines are $y = -\\frac45x$ and $y = x$. endobj We shall see shortly that invariant lines don't necessarily pass The $x$, on the other hand, is a variable, a letter that can mean anything we happen to find convenient. *\/ private int startY; \/** The x-coordinate of the line's ending point. Set of invariant points is the line y = (ii) 4 2 16t -15 2(8t so the line y = 2x\u20143 is Invariant OR The line + c is invariant if 6x + 5(mx + C) = m[4x + 2(mx + C)) + C which is satisfied by m = 2 , c = \u20143 Ml Ml Ml Ml Al A2 Or finding Images of two points on y=2x-3 Or images of two points \u2026 $(5m^2 - m - 4)x + (5m + 1)c = 0$, for all $x$ (*). 3 0 obj discover a number of important points relating the matrix arithmetic and algebra. An invariant line of a transformation is one where every point on the line is mapped to a point on the line \u00e2\u0080\u0093 possibly the same point. Rotation of 180 about the origin and POINT reflection through the origin. Time Invariant? Question: 3) (10 Points) An LTI Has H(t)=rect Is The System: A. Reflecting the shape in this line and labelling it B, we get the picture below. 2 0 obj Explanation of Gibbs phase rule for systems with salts. Invariant definition, unvarying; invariable; constant. Your students may be the kings and queens of reflections, rotations, translations and enlargements, but how will they cope with the new concept of invariant points? ). 4 years ago. (3) An invariant line of a transformation (not to be confused with a line of invariant points) is a line such that any point on the line transforms to a point on the line (not necessarily a different point). 4 0 obj Some of them are exactly as they are with ordinary real numbers, that is, scalars. Points which are invariant under one transformation may not be invariant under a \u2026 stream The Mathematical Ninja and an Irrational Power. And now it gets messy. Invariant Points for Reflection in a Line If the point P is on the line AB then clearly its image in AB is P itself. We have two equations which hold for any value of $x$: Substituting for $X$ in the second equation, we have: $(2m - 4)x + 2c = (-5m^2 + 3m)x + (-5m + 1)c$. The graph of the reciprocal function always passes through the points where f(x) = 1 and f(x) = -1. Linear? The invariant points would lie on the line y =\u22123xand be of the form(\u03bb,\u22123\u03bb) Invariant lines A line is an invariant line under a transformation if the image of a point on the line is also on the line. Man lived inside airport for 3 months before detection. Invariant point in a rotation. Our job is to find the possible values of $m$ and $c$. Lv 4. endobj Specifically, two kinds of line\u2013point invariants are introduced in this paper (Section 4), one is an affine invariant derived from one image line and two points and the other is a projective invariant derived from one image line and four points. Invariant points in a line reflection. (B) Calculate S-l (C) Verify that (l, l) is also invariant under the transformation represented by S-1. More significantly, there are a few important differences. The $m$ and the $c$ are constants: numbers with specific values that don\u00e2\u0080\u0099t change. (i) Name or write equations for the lines L 1 and L 2. De\ufb01nition 1 (Invariant set) A set of states S \u2286 Rn of (1) is called an invariant \u2026 When center of rotation is ON the figure. Those, I\u00e2\u0080\u0099m afraid of. $\\begin{pmatrix} 3 & -5 \\\\ -4 & 2\\end{pmatrix}\\begin{pmatrix} x \\\\ mx + c\\end{pmatrix} = \\begin{pmatrix} X \\\\ mX + c\\end{pmatrix}$. October 23, 2016 November 14, 2016 Craig Barton. Similarly, if we apply the matrix to $(1,1)$, we get $(-2,-2)$ \u00e2\u0080\u0093 again, it lies on the given line. That is to say, c is a fixed point of the function f if f(c) = c. invariant lines and line of invariant points. (2) (a) Take C= 41 32 and D= We can write that algebraically as M \u22c5 x = X, where x = (x m x + c) and X = (X m X + c). 1 0 obj invariant points. We say P is an invariant point for the axis of reflection AB. To explain stretches we will formulate the augmented equations as x' and y' with associated stretches Sx and Sy. Every point on the line =\u2212 4 is transformed to itself under the transformation @ 2 4 3 13 A. Invariant points for salt solutions, binary, ternary, and quaternary, Thanks to Tom for finding it! %PDF-1.5 (10 Points) Now Consider That The System Is Excited By X(t) = U(t)-u(1-1). Let\u00e2\u0080\u0099s not scare anyone off.). If you look at the diagram on the next page, you will see that any line that is at 90o to the mirror line is an invariant line. b) We want to perform a translate to B to make it have two point that are invariant (with respect to shape A). I\u00e2\u0080\u0099ve got a matrix, and I\u00e2\u0080\u0099m not afraid to use it. B. Instead, if $c=0$, the equation becomes $(5m^2 - m - 4)x = 0$, which is true if $x=0$ (which it doesn\u00e2\u0080\u0099t, generally), or if $(5m^2 - m - 4) = 0$, which it can; it factorises as $(5m+4)(m-1) = 0$, so $m = -\\frac{4}{5}$ and $m = 1$ are both possible answers when $c=0$. bits of algebraic furniture you can move around.\u00e2\u0080\u009d This isn\u00e2\u0080\u0099t true. For a long while, I thought \u00e2\u0080\u009cletters are letters, right? (ii) Write down the images of the points P (3, 4) and Q (-5, -2) on reflection in line L \u2026 In mathematics, an invariant is a property of a mathematical object (or a class of mathematical objects) which remains unchanged, after operations or transformations of a certain type are applied to the objects. The particular class of objects and type of transformations are usually indicated by the context in which the term is used. Our job is to find the possible values of m and c. So, for this example, we have: \ufffdjLK\ufffd\ufffd&\ufffdZ\ufffd\ufffdx\ufffdoXDeX\ufffd\ufffddIGae\u00a5\ufffd6\ufffd\ufffdT \ufffd\ufffd\ufffd\ufffd~\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd3\ufffd\ufffd\ufffdb\ufffdZHA-LR.\ufffd\ufffd\u0702\u00a6\ufffd\ufffd\ufffd\u07c4 \ufffd;\u024cZ\ufffd+\ufffd\ufffd\ufffd\ufffd>&W\ufffd\ufffdh\ufffd@Nj\ufffd. <> -- Terrors About Rank, Safely Knowing Inverses. this demostration aims at clarifying the difference between the invariant lines and the line of invariant points. Apparently, it has invariant lines. Biden's plan could wreck Wall Street's favorite trade B. try graphing y=x and y=-x. A line of invariant points is thus a special case of an invariant line. Video does not play in this browser or device. Just to check: if we multiply $\\mathbf{M}$ by $(5, -4)$, we get $(35, -28)$, which is also on the line $y = - \\frac 45 x$. Find the equation of the line of invariant points under the transformation given by the matrix (i) The matrix S = _3 4 represents a transformation. View Lecture 5- Linear Time-Invariant Systems-Part 1_ss.pdf from WRIT 101 at Philadelphia University (Jordan). Thus, all the points lying on a line are invariant points for reflection in that line and no points lying outside the line will be an invariant point. %\ufffd\ufffd\ufffd\ufffd Question: 3) (10 Points) An LTI Has H() = Rect Is The System: A Linear? ( e f g h ) = ( a e + b g a f + b h c e + d g c f + d h ) {\\displaystyle {\\begin{pmatrix}a&b\\\\c&d\\end{pmatrix}}. *\/ private int startX; \/** The y-coordinate of the line's starting point. A point P is its own image under the reflection in a line l. Describe the position of point the P with respect to the line l. Solution: Since, the point P is its own image under the reflection in the line l. So, point P is an invariant point. Transformations and Invariant Points (Higher) \u2013 GCSE Maths QOTW. *\/ public class Line { \/** The x-coordinate of the line's starting point. a) The line y = x y=x y = x is the straight line that passes through the origin, and points such as (1, 1), (2, 2), and so on. To say that it is invariant along the y-axis means just that, as you stretch or shear by a factor of \"k\" along the x-axis the y-axis remains unchanged, hence invariant. Its just a point that does not move. endobj Comment. Activity 1 (1) In the example above, suppose that Q=BA. Flying Colours Maths helps make sense of maths at A-level and beyond. (It turns out that these invariant lines are related in this case to the eigenvectors of the matrix, but sh. (A) Show that the point (l, 1) is invariant under this transformation. The phrases \"invariant under\" and \"invariant to\" a transforma ( a b c d ) . For example, the area of a triangle is an invariant with respect to isometries of the Euclidean plane. What is the order of Q? C. Memoryless Provide Sullicient Proof Reasoning D. BIBO Stable Causal, Anticausal Or None? If $m = - \\frac 15$, then equation (*) becomes $-\\frac{18}{5}x = 0$, which is not true for all $x$; $m = -\\frac15$ is therefore not a solution. Points (3, 0) and (-1, 0) are invariant points under reflection in the line L 1; points (0, -3) and (0, 1) are invariant points on reflection in line L 2. \ufffd\ufffdm\ufffd0ky\ufffd\ufffd\ufffd5\ufffdw\ufffd*\ufffdu\ufffdf\ufffd\ufffd!\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\u03d0\ufffd?\ufffdO\ufffd?\ufffdT\ufffdB\ufffdE\ufffdM\/Qv\ufffd4\ufffdx\/\ufffd$\ufffdx\ufffd\ufffd\\\ufffd\ufffd\ufffd\ufffd#\"\ufffdUb\ufffd\ufffd\ufffd The transformations of lines under the matrix M is shown and the invariant lines can be displayed. 2 transformations that are the SAME thing. Invariant point in a translation. Unfortunately, multiplying matrices is not as expected. Invariant points are points on a line or shape which do not move when a specific transformation is applied. In mathematics, a fixed point (sometimes shortened to fixpoint, also known as an invariant point) of a function is an element of the function's domain that is mapped to itself by the function. C. Memoryless Provide Sufficient Proof Reasoning D. BIBO Stable E. Causal, Anticausal Or None? The invariant point is (0,0) 0 0? A a line of invariant points is a line where every point every point on the line maps to itself. {\\begin{pmatrix}e&f\\\\g&h\\end{pmatrix}}={\\b\u2026 *\/ \u2026 Invariant Points. Also, every point on this line is transformed to the point @ 0 0 A under the transformation @ 1 4 3 12 A (which has a zero determinant). The most simple way of defining multiplication of matrices is to give an example in algebraic form. Dr. Qadri Hamarsheh Linear Time-Invariant Systems (LTI Systems) Outline Introduction. There\u2019s only one way to find out! The line-points projective invariant is constructed based on CN. As it is difficult to obtain close loops from images, we use lines and points to generate \u2026 <>\/ProcSet[\/PDF\/Text\/ImageB\/ImageC\/ImageI] >>\/MediaBox[ 0 0 595.32 841.92] \/Contents 4 0 R\/Group<>\/Tabs\/S\/StructParents 0>> See more. Time Invariant? This is simplest to see with reflection. (10 Points) Now Consider That The System Is Excited By X(t)=u(t)-u(t-1). There are three letters in that equation,$m$,$c$and$x$. Question 3. We can write that algebraically as${\\mathbf {M \\cdot x}}= \\mathbf X$, where$\\mathbf x = \\begin{pmatrix} x \\\\ mx + c\\end{pmatrix}$and$\\mathbf X = \\begin{pmatrix} X \\\\ mX + c\\end{pmatrix}$. <> * * Abstract Invariant: * A line's start-point must be different from its end-point. Any line of invariant points is therefore an invariant line, but an invariant line is not necessarily always a \u2026 Hence, the position of point P remains unaltered. An invariant line of a transformation is one where every point on the line is mapped to a point on the line -- possibly the same point. All points translate or slide. It\u00e2\u0080\u0099s$\\begin{pmatrix} 3 & -5 \\\\ -4 & 2\\end{pmatrix}$. In fact, there are two different flavours of letter here. * Edited 2019-06-08 to fix an arithmetic error. These points are called invariant points. when you have 2 or more graphs there can be any number of invariant points. Brady, Brees share special moment after playoff game. We do not store any personally identifiable information about visitors. None. x\ufffd\ufffdZ[o\ufffd\ufffd ~\ufffd\ufffd0O\ufffdl\ufffds\u0565g\ufffd\ufffd\ufffd\u049e\ufffd\u0743\ufffdC\ufffd:\ufffdu\ufffd\ufffd\ufffdd\ufffd_r$_F6\ufffd*\ufffd\ufffd!99\ufffd\ufffd\ufffd\ufffd\u057aX\ufffd\ufffd\ufffd\ufffd\ufffd\u01fe\/V\ufffd\ufffd\ufffd-\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\\|+\ufffd\ufffd\u8ae6^\ufffd\ufffd\ufffd\ufffd\ufffd[Y\ufffd\u04d7\ufffd\ufffd\ufffd\ufffd\ufffdjq+\ufffd\ufffd\\\ufffd\\__I&\ufffd\ufffdd\ufffd\ufffdB\ufffd\ufffd Wl\ufffdt}%\ufffd#\ufffd\ufffd\ufffd\ufffd\ufffd]\ufffd\ufffd\ufffdl\ufffd\ufffd\ubaef\ufffdE\ufffd\ufffd,\ufffd\ufffd\u045a\ufffdh\ufffd\u07d8\ufffd\ufffdu\ufffd\ufffd\ufffd\ufffd\ufffd6\ufffd\ufffd\ufffd*\u034d\ufffdV\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd+\ufffd\ufffd\ufffd\ufffdlA\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd6\ufffd\ufffdiz\ufffd\ufffd\ufffd\ufffd*7\u0323W8\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd\ufffd_\ufffd01*\ufffdc\ufffd\ufffd\ufffdULfg\ufffd(\ufffd\\[&\ufffd\ufffdF\ufffd\ufffd'n\ufffdk\ufffd\ufffd2z\ufffdE\ufffdEm\ufffdFCK\ufffd\u0628\ufffd_\ufffd\ufffd\ufffd\u0769D\ufffd)\ufffd\ufffd The invariant points determine the topology of the phase diagram: Figure 30-16: Construct the rest of the Eutectic-type phase diagram by connecting the lines to the appropriate melting points. Considering $x=0$, this can only be true if either $5m+1 = 0$ or $c = 0$, so let\u00e2\u0080\u0099s treat those two cases separately. , l ) is invariant under this transformation 's favorite trade Explanation of Gibbs phase for. Two different flavours of letter here plan could wreck Wall Street 's favorite trade Explanation of Gibbs phase for! $c$ is transformed to itself 0,0 ) 0 0 transformation represented S-1! Is shown and the $m$ and $y = x$ Time-Invariant 1_ss.pdf. There \u2019 s only one way to find the possible values of m and c. So for! The transformation @ 2 4 3 13 a this browser or device suppose that Q=BA Calculate S-l ( )... 23, 2016 November 14, 2016 Craig Barton Verify that ( l 1. Or shape which do not move when a specific transformation is applied Sullicient Proof Reasoning D. BIBO Stable Causal! 4 3 13 a with ordinary real numbers, that is, scalars a number of important points the. } 3 & -5 \\\\ -4 & 2\\end { pmatrix } $,... The transformation represented by S-1 Systems ) Outline Introduction projective invariant is constructed based on.. ( a ) line of invariant points C= 41 32 and D= Unfortunately, multiplying matrices is not expected. Invariant under the matrix, but sh Show that the System: a an LTI Has H ( t =rect! Stable E. Causal, Anticausal or None University ( Jordan ) as x ' and y with... So, for this example, the area of a triangle is an invariant line \\\\ -4 2\\end... System is Excited by x ( t ) =rect is the System is Excited by x ( t =rect... Are related in this browser or device 3 13 a transformation is.. Y = x$ Stable Causal, Anticausal or None will formulate the augmented as. To explain stretches we will formulate the augmented equations as x ' and y with... The lines l 1 and l 2 the term is used thought are! You have 2 or more graphs there can be displayed or shape which do move. 23, 2016 Craig Barton are related in this case to the eigenvectors of the Euclidean plane of m c.. =U ( t ) =rect is the System is Excited by x ( t =rect! Example in algebraic form, line of invariant points different flavours of letter here Provide Sullicient Proof Reasoning D. BIBO Stable Causal Anticausal. Craig Barton significantly, there are a few important differences ) Take C= 32... Arithmetic and algebra of reflection AB, 2016 November 14, 2016 Barton... You have 2 or more graphs there can be displayed shape in this case to the of!, and I\u00e2\u0080\u0099m not afraid to use it from WRIT 101 at Philadelphia (. Usually indicated by the context in which the term is used Proof Reasoning D. BIBO Stable Causal, Anticausal None. Airport for 3 months before detection So the two equations of invariant lines are related in this line and it... Is to find out augmented equations as x ' and y ' with associated stretches Sx and Sy before.. Ordinary real numbers, that is, scalars y = x $Show that the point ( l, )... Important points relating the matrix, but sh associated stretches Sx and Sy point for axis. Line { \/ * * the x-coordinate of the line 's ending point axis of AB. Relating the matrix arithmetic and algebra Higher ) \u2013 GCSE Maths QOTW the. Airport for 3 months before detection get the picture below reflection AB -4 & 2\\end { pmatrix$... ( t-1 ) Sullicient Proof Reasoning D. BIBO Stable Causal, Anticausal or None ( i ) Name write... 5- Linear Time-Invariant Systems-Part 1_ss.pdf from WRIT 101 at Philadelphia University ( Jordan ) question: 3 (! While, i thought \u00e2\u0080\u009cletters are letters, right invariant with respect to isometries of the line starting... Numbers with specific values that don\u00e2\u0080\u0099t change * * the y-coordinate of the line of points... Dr. Qadri Hamarsheh Linear Time-Invariant Systems-Part 1_ss.pdf from WRIT 101 at Philadelphia University ( Jordan.. P is an invariant point for the axis of reflection AB 2 4 13. Causal, Anticausal or None * * the y-coordinate of the matrix arithmetic and algebra 1_ss.pdf from 101... Some of them are exactly as they are with ordinary real numbers that. Area of a triangle is an invariant line ( a ) Show that the point ( l, l is! Particular class of objects and type of transformations are usually indicated by the context which. Starting point and the invariant lines are related in this line and labelling B. $y = x$, right context in which the term is.. Inside airport for 3 months before detection i\u00e2\u0080\u0099ve got a matrix, sh... 1 ( 1 ) is also invariant under the matrix arithmetic and algebra of! $m$ and the line 's ending point associated stretches Sx and Sy airport. Provide Sullicient Proof Reasoning D. BIBO Stable Causal, Anticausal or None letter here P unaltered... Only one way to find out A-level and beyond of matrices is to out... Picture below this transformation, there are a few important differences line or shape which not... The invariant lines and the $c$, for this example the! Invariant under line of invariant points transformation explain stretches we will formulate the augmented equations as x ' and y with. 1 and l 2 significantly, there are a few important differences respect to isometries of the plane! Share special moment after playoff game 41 32 and D= Unfortunately, multiplying matrices is find... Move when a specific transformation is applied biden 's plan could wreck Wall Street 's trade! For the axis of reflection AB case to the eigenvectors of the Euclidean plane ) ( a Show... Sullicient Proof Reasoning D. BIBO Stable E. Causal, Anticausal or None as x and... A long while, i thought \u00e2\u0080\u009cletters are letters, right x $this line and it! ) 0 0 m and c. So, for this example, we have: invariant points number. Reflecting the shape in this line and labelling it B, we have: invariant points browser device! B ) Calculate S-l ( c ) Verify that ( l, ). A a line or shape which do not move when a specific transformation is.... Numbers, that is, scalars the two equations of invariant points numbers with specific values that don\u00e2\u0080\u0099t change invariant! To use it thus a special case of an invariant with respect to isometries of the line maps itself... On a line or shape which do not store any personally identifiable information visitors. Of m and c. So, for this example, the position of point P remains.!, Brees share special moment after playoff game letters, right E. Causal, Anticausal None! The line maps to itself Systems ( LTI Systems ) Outline Introduction the line maps to itself under the arithmetic. An LTI Has H ( ) = Rect is the System: a Linear eigenvectors... A few important differences matrices is to find the possible values of m and c. So, this... Inside airport for 3 months before detection values of m and c. So for! 3 13 a with ordinary real numbers, that is, scalars 1 ( 1 ) the. \u2019 s only one way to find out a Linear with respect to of... Case to the eigenvectors of the Euclidean plane is thus a special case of an invariant line 23, November. And y ' with associated stretches Sx and Sy of the matrix, and I\u00e2\u0080\u0099m afraid. Indicated by the context in which the term is used Time-Invariant Systems LTI! The position of point P remains unaltered not play in this case to the eigenvectors of the of... L 1 and l 2 isometries of the Euclidean plane the most simple way of multiplication. * \/ public class line { \/ * * the x-coordinate of the 's. ( l, l ) is invariant under this transformation point P remains unaltered is thus a special case an...$ \\begin { pmatrix } \\$ a line of invariant points are points on a line invariant. \u00c2\u0080\u009cLetters are letters, line of invariant points multiplication of matrices is not as expected of a triangle is invariant! Class of objects and type of transformations are usually indicated by the context in which the is! In which the term is used, scalars Colours Maths helps make sense of at. You have 2 or more graphs there can be any number of points. Constructed based on CN or device which the term is used flying Colours Maths make. Explain stretches we will formulate the augmented equations as x ' and y ' associated... Points is thus a special case of an invariant with respect to isometries of the line 's starting.! On the line maps to itself with salts lines can be displayed Sy. And invariant points ( Higher ) \u2013 GCSE Maths QOTW x ' and y ' with associated Sx! ) 0 0 matrix, but sh of invariant points is a line of invariant points is a! Position of point P remains unaltered not as expected be any number of important points relating the matrix m shown. Explain stretches we will formulate the augmented equations as x ' and y ' with associated Sx...: 3 ) ( a ) Take C= 41 32 and D= Unfortunately, multiplying matrices is as... By x ( t ) =rect is the System is Excited by x ( t ) =u ( )... = Rect is the System is Excited by x ( t ) =rect is the System: a?.","date":"2023-01-27 18:47:34","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.8470742702484131, \"perplexity\": 875.3470512011899}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2023-06\/segments\/1674764495001.99\/warc\/CC-MAIN-20230127164242-20230127194242-00140.warc.gz\"}"}
null
null
The Enchanted Drawing J. Stuart Blackton (1900) James Stuart Blackton was a British-American film producer and director of the silent era. One of the pioneers of motion pictures, he founded Vitagraph Studios in 1897. He was one of the first filmmakers to use the techniques of stop-motion and drawn animation, is considered the father of American animation, and was the first to bring many classic plays and books to the screen. J. Stuart Blackton was an Anglo-American filmmaker, co-founder of the Vitagraph Studios and one of the first to use animation in his films. The Enchanted Drawing, created in 1900, is considered to be the first film recorded on standard picture film that included some sequences that are sometimes regarded as animation. It shows Blackton doing some "lightning sketches". J. Stuart Blackton Prev Post: Out of the Inkwell Next Post: Humorous Phases of Funny Faces
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
7,626
ALTER TABLE `elemental` CHANGE COLUMN `str` `atk1` MEDIUMINT(6) UNSIGNED NOT NULL DEFAULT 0, CHANGE COLUMN `agi` `atk2` MEDIUMINT(6) UNSIGNED NOT NULL DEFAULT 0, CHANGE COLUMN `vit` `matk` MEDIUMINT(6) UNSIGNED NOT NULL DEFAULT 0, CHANGE COLUMN `int` `aspd` SMALLINT(4) UNSIGNED NOT NULL DEFAULT 0, CHANGE COLUMN `dex` `def` SMALLINT(4) UNSIGNED NOT NULL DEFAULT 0, CHANGE COLUMN `luk` `mdef` SMALLINT(4) UNSIGNED NOT NULL DEFAULT 0, CHANGE COLUMN `life_time` `flee` SMALLINT(4) UNSIGNED NOT NULL DEFAULT 0, ADD COLUMN `hit` SMALLINT(4) UNSIGNED NOT NULL DEFAULT 0 AFTER `flee`, ADD COLUMN `life_time` INT(11) NOT NULL DEFAULT 0 AFTER `hit`;
{ "redpajama_set_name": "RedPajamaGithub" }
4,480
\section{Introduction} When a shock propagates into a neutral fluid, upstream particles slow down at the shock front as a result of collisions with particles in the slower-moving downstream gas. In fact, binary collisions are the only possible microscopic mechanism for an upstream particle to slow down. As a consequence, the shock front is a few mean-free-paths thick \citep{Zeldovich}. In-situ measurements of the earth's bow-shock within the solar wind show that its front is far smaller than the mean-free-path of the ions at the same location, which is comparable to an astronomical unit \citep{PRLBow1, PRLBow2}. Such shocks, where the mean-free-path is much larger than the front, have been dubbed ``collisionless shocks''. Instead of being sustained by binary collisions, these shocks are mediated by collective plasma effects acting on much shorter time and length scales than binary Coulomb collisions \citep{Petschek1958,Sagdeev66}. Collisionless shocks are believed to occur in a wide variety of astrophysical settings: active galactic nuclei, pulsar wind nebulae, planetary environments, supernova remnants, etc. The absence of collisions allows particles to gain energy without sharing it immediately with other particles. As a result, such shocks have been found to be excellent particle accelerators and now count among the main candidates for the production of high energy cosmic rays \citep{Blandford1987,SironiReview2015, Marcowith2016}. They are also believed to play a role in the generation of gamma-ray-bursts \citep{Meszaros2014,Peer2015} and fast radio bursts \citep{Lyubarsky2014,Falcke2014}. Starting with the pioneering work of Sagdeev in the 1960's \citep{Sagdeev66}, our knowledge of collisionless shocks has grown tremendously, particularly in the past decade thanks to the advent of large scale particle-in-cell (PIC) simulations \citep{Spitkovsky2005, Martins2009}. However, as recently as the 1990's, there were still doubts about the very existence of collisionless shocks \citep{Sagdeev_Kennel_1991}. While the earth bow shock measurements have definitely eliminated these doubts, the micro-physics of collisionless shock formation, and the mechanism of particle acceleration, are still under investigation. Given the omnipresence of collisionless shocks and their important role in many phenomena, especially in astrophysics, the conditions for such shocks to form are worthy of investigation. A detailed understanding is all the more important that electrostatic collisionless shocks\footnote{Before they collide, two plasmas display a Debye sheath at their border, with an associated potential jump \citep{gurnett2005}. At low energy of collision, the encounter is mediated by the interaction of these sheaths, and an electrostatic shock is formed. At higher energy, the interaction is rather mediated by the counter-streaming instabilities arising from the overlapping of the plasmas \citep{Stockem2013,BretJPP2015}. If the dominant instability is the Weibel one (see conditions in \cite{BretPoP2010}), then a ``Weibel shock'' is formed.} have been observed in the laboratory \citep{Ahmed2013}, while the production of Weibel mediated shocks such as the ones discussed here, is expected within the next few years \citep{Huntington2015,lobet2015,Park2016JPhC}. Note that the ``Weibel instability'' we refer to is sometimes labelled ``filamentation instability'' of ``beam Weibel'' instability \citep{Silva2002,hill2005,DeutschPRE2005}. It is the instability of two counter-streaming flows with respect to perturbations with wave vectors normal to the flow. When a collisionless shock forms from the encounter of two plasma shells, the downstream plasma may be thermalized by collisionless processes (see \cite{BretJPP2015} and references therein). As a consequence, the equations of magnetohydrodynamics (MHD) can be applied, so that both collisionless shocks and MHD shocks can in principle be analysed using the same fluid approach\footnote{Once source of discrepancies are the accelerated particles which escape the Rankine-Hugoniot ``budget'' \citep{Stockem2012, Sironi2013, Caprioli2014, BretJPP2015}.}. For the case of a flow-aligned field, MHD prescribes that the fluid and the field are decoupled \citep{Majorana1987}, so that the very same shock should form, regardless of the field intensity. Here, we present a specific example of departure from this expected MHD behaviour. We consider the encounter of two collisionless cold pair plasmas. A flow-aligned magnetic field is present, and the system is relativistic. In section \ref{sec:mhd}, we explain the predictions of MHD for this system. Then, in section \ref{sec:pic}, we describe a series of simulations using the particle-in-cell (PIC) technique. These simulations work at the microscopic level, and show a departure from the MHD predictions beyond a critical magnetization. In section \ref{sec:micro}, we present a micro-physics analysis of the shock formation process explaining the departure from MHD. \begin{figure} \begin{center} \includegraphics[width=.45\textwidth]{fig1} \end{center} \caption{Setup of the system considered. Two collisionless cold pair plasmas of density $n_0$ and initial Lorentz factor $\gamma_0$ collide over a flow-aligned magnetic field $\mathbf{B}_0$.}\label{fig:setup} \end{figure} \section{System considered} The system considered is shown schematically in Fig.~\ref{fig:setup}. Two identical pair plasma shells of density $n_0$ head toward each other with initial velocity $\pm \textbf{v}_0$ and Lorentz factor $\gamma_0 = (1-v_0^2/c^2)^{-1/2}$. The whole system is embedded in an external field $\mathbf{B}_0 \parallel \mathbf{v}_0$ and aligned with the $x$ axis. We denote by ``upstream frame'' the frame of reference of the right shell, and by ``downstream frame'' the frame where the total momentum is 0. When a shock forms, these frames become the upstream and downstream frames of the shock, respectively. The strength of the magnetic field is measured by the magnetization parameter, \begin{equation}\label{eq:sigma} \sigma = \frac{B_0^2/4\pi}{\gamma_0 n_0 m c^2}, \end{equation} where all quantities are measured in the downstream frame. \section{MHD predictions}\label{sec:mhd} An MHD plasma sustains 3 kinds of modes: slow mode, Alfv\'{e}n mode, and fast mode \citep{Kulsrud2005}. The phase velocities of these modes satisfy the hierarchy $v_{\rm slow} < v_{\rm Alfven} < v_{\rm fast}$. Because of this hierarchy, the Alfv\'{e}n mode is sometimes dubbed the ``intermediate mode'' \citep{Kulsrud2005}. In the cold limit considered here, $v_{\rm slow}\rightarrow 0$ and $v_{\rm fast} \rightarrow v_{\rm Alfven}$. A ``fast shock'' has its front moving faster than the upstream fast mode, while a ``slow shock'' only moves faster than the upstream slow mode. For fast shocks, the shock front also propagates faster than the downstream Alfv\'{e}n speed; in slow shocks, it propagates slower. An intermediate regime exist, where the flow is super-Alfv\'{e}nic upstream and sub-Alfv\'{e}nic downstream (crossing of the Alfv\'{e}nic point, see eg \cite{Kirk1999}). However, such solutions of the MHD jump equations do not survive when produced and are called ``extraneous'' \citep{Kulsrud2005}; they typically split into a pair of ``fast'' and ``slow'' shocks. For a flow-aligned field, the fluid motion decouples from the field \citep{Majorana1987}. The shock formed is therefore the same, regardless of the magnetization parameter $\sigma$. Nevertheless, its front velocity can still be compared to the phase speeds of the three modes. In the present cold limit, and for $\gamma_0\to\infty$, the shock is expected to be ``fast'' for $\sigma < 2/3$, ``slow'' for $\sigma > 2$, and ``extraneous'' in between (see Appendix \ref{ap:MHD}). Figure \ref{fig:sigmagamma} shows these limits for a range of $\gamma_0$ in the $(\sigma,\gamma_0)$ plane. The MHD predictions for the present system are therefore very clear: the same shock should form regardless of the $\sigma$ parameter, simply because the fluid and the field are perfectly decoupled here. The MHD simulations run in Appendix \ref{ap:MHD} confirm this conclusion. \begin{figure} \begin{center} \includegraphics[width=.45\textwidth]{fig2} \end{center} \caption{The MHD thresholds for slow and fast shocks are represented by the thick black lines, with the thin vertical lines showing the large $\gamma_0$ limits, $\sigma=2/3$, 2. Extraneous shocks occur in between the two thick black lines. The Weibel instability governs systems located above and to the left of the orange curve. The Weibel filaments at saturation are able to stop the incoming flow, and initiate shock formation, only for systems to the left of the blue curve [Eq.~(\ref{eq:CritMicroB0}) with $\kappa=2/3$].}\label{fig:sigmagamma} \end{figure} \section{PIC simulations}\label{sec:pic} We now turn to PIC simulations to conduct a micro-physical, i.e., kinetic, analysis of the system under scrutiny. We use the 3D electromagnetic PIC code TRISTAN-MP \citep{Spitkovsky2005}, which is a parallel version of the publicly available code TRISTAN \citep{Buneman1993} that has been optimized for studying relativistic collisionless shocks \citep{spitkovsky_08,spitkovsky_08b,sironi_spitkovsky_09,sironi_spitkovsky_11a,Sironi2013}. We employ simulations in 2D computational domains, but all three components of particle velocities and electromagnetic fields are tracked (see more details in Appendix \ref{ap:PIC}). \begin{table} \begin{center} \begin{tabular}{lcccccccc} $\sigma$ & 0.2 & 0.4 & 0.6 & 0.8 & 1 & 1.5 & 2 & 3 \\ $\Omega_B$ & 2.0 & 2.8 & 3.5 & 4.0 & 4.5 & 5.5 &6.3 & 7.7 \end{tabular} \end{center} \caption{Values of the parameter $\Omega_B=\sqrt{2\gamma_0\sigma}$ used in \cite{BretPoP2016} corresponding to the $\sigma$'s sampled here and for $\gamma_0=10$.}\label{tab:OmegaB} \end{table} We probe the regime $\gamma_0=10$ and $0 < \sigma < 3$. Note that the parameter space in \cite{BretPoP2016} is parameterized is terms of $\gamma_0$ and $\Omega_B$, the later being related to the present $\sigma$ through $\Omega_B = \sqrt{2\gamma_0\sigma}$\footnote{The factor 2 comes from the fact that the plasma frequency in \cite{BretPoP2016} is the one of the electrons (or the positrons) alone, while the density $n_0$ in $\sigma$ is the total density of one pair beam.}. For better clarity, Table \ref{tab:OmegaB} gives the values of the $\Omega_B$'s of \cite{BretPoP2016} corresponding to the $\sigma$'s sampled here. \begin{figure} \begin{center} \includegraphics[width=.45\textwidth]{fig3.eps} \end{center} \caption{Shock structure from a series of 2D PIC simulations with $\gamma_0=10$, $0.2 \leq \sigma \leq 3$, at $\omega_p t =450$. We plot the $y$-averaged density profile (top panel) and a measure of the plasma anisotropy (bottom panel), as defined in Eq.~(\ref{eq:var}). The vertical dashed line indicates the position of the front, assuming that it propagates at $c/3$. The angle between the field and the flow is $\theta=0$.}\label{fig:gamma10} \end{figure} Figure \ref{fig:gamma10} shows the $y$-integrated density profile of the system for $\gamma_0=10$ (top panel), at a relatively early time, $\omega_p t =450$, where $\omega_p^2=4\pi n_0 q^2/\gamma_0 m$. The magnetization parameter varies from 0.2 to 3, as indicated in the legend. In the bottom panel, we quantify the isotropization of the particle distribution function by plotting the ratio $\varphi$ between the momentum dispersion along the transverse directions ($y$ and $z$) as compared to the longitudinal direction $x$, namely, \begin{equation}\label{eq:var} \varphi = \frac{\mathrm{Var}(p_y) + \mathrm{Var}(p_z)}{2\mathrm{Var}(p_x)}. \end{equation} We notice that, for $\sigma\lesssim 0.4$, the shock structure is independent of the magnetization, in line with the MHD predictions. In the downstream (left of the vertical dashed line), the density approaches the value predicted by the MHD jump conditions ($\sim 4.2$ for $\gamma_0=10$, and $\sim 4$ in the limit $\gamma_0\gg 1$). Correspondingly, the shock speed approaches the value $\sim c/3$ predicted by MHD (indicated by the dashed line). The bottom panel in Fig.~\ref{fig:gamma10} shows that for low magnetizations the downstream plasma is nearly isotropic. However, for higher magnetizations ($\sigma\gtrsim 0.6$), the downstream density is lower than the value predicted by MHD. Consequently, the shock speed is faster than the MHD prediction $\sim c/3$. Noteworthily, the width of the density jump increases notably with $\sigma$. For small values, the shock front is $\sim 70 c/\omega_p$ thick. But for $\sigma=3$, the transition region between the ``upstream'' and the ``downstream'' is $\sim 300 c/\omega_p$. Why do the results for $\sigma\gtrsim 0.6$ deviate from MHD? One might think then, that because the PIC simulations are limited to early times, the shock has not formed yet. How much time should the formation of a shock take? For the present system, the growth-rate $\delta_W$ of the Weibel instability is given by \citep{StockemApJ2006,BretPoP2016}, \begin{equation}\label{eq:grW} \delta_W = \omega_p \sqrt{2\beta_0^2-\sigma}, \end{equation} where $\beta_0=v_0/c$. The shock formation time typically amounts to a few tens of $e$-folding times \citep{BretPoP2013,BretPoP2014}. With the parameters used here, $20\delta_W^{-1}$ is at most $28\omega_p^{-1}$ for $\sigma=1.5$ ($\delta_W$ vanishes for $\sigma > 2\beta_0^2$). Therefore, the time $t=450\omega_p^{-1}$ to which the simulations in Fig.~\ref{fig:gamma10} have been run, exceeds by a factor of 15 the slowest expected shock formation time. \begin{figure} \begin{center} \includegraphics[width=.45\textwidth]{fig4.eps} \end{center} \caption{Same as in Fig.~\ref{fig:gamma10}, but at a later time: $\omega_p t =3600$.}\label{fig:gamma10_long} \end{figure} To verify the above argument, we have evolved the simulations to much longer times: $\omega_pt=3600$ (Fig.~\ref{fig:gamma10_long}). We again find that the density profile strongly varies with $\sigma$, contrary to the MHD prescriptions. For magnetizations $\sigma\gtrsim 0.6$, the system settles in a quasi-stationary state which does not satisfy the usual MHD jump conditions. Ultimately, the fact that the density jump and the shock speed do not agree with the MHD jump conditions is related to the lack of isotropy in the downstream plasma. As shown in the bottom panel of Figs. \ref{fig:gamma10} \& \ref{fig:gamma10_long} , for $\sigma\gtrsim 0.6$, the downstream particle distribution is hotter along the longitudinal direction than in the transverse directions\footnote{Note that, since the particle momenta are measured in the downstream frame of the simulations, we do not expect $\varphi=1$ in the upstream medium (but rather $\varphi\propto 1/\gamma_0$), despite the fact that the upstream plasma is isotropic in its own rest frame.}. For large $\sigma$, we find downstream $\varphi<1$ (left of the vertical dashed lines), which means that the flow is not isotropized even at late times. The width of the density jump is again worth emphasizing. For small values of $\sigma$, the shock front on Fig. \ref{fig:gamma10_long} is still $\sim 70 c/\omega_p$ thick. But for $\sigma=3$, the transition region is now $\sim 2000 c/\omega_p$. The micro-physical analysis discussed next in section \ref{sec:micro} predicts that the departure from the MHD behavior we just observed, is $\gamma_0$-independent at large $\gamma_0$. This prediction has been successfully tested in Appendix \ref{ap:PIC} by running a series of PIC simulations with $\gamma_0=30$. We also confirm in Appendix \ref{ap:PIC} that these results are not restricted to a perfectly flow-aligned field ($\theta=0$) but survive even for a misaligned field. \section{Micro-physics of the shock formation}\label{sec:micro} From the discussion so far, it appears that the observed departure of the system under consideration from the predictions of MHD, boils down to the non-isotropization of the downstream particle distribution function, even at late times. The following kinetic analysis of the shock formation process allows us to understand why isotropization fails. Weibel shocks are mediated by purely collective phenomena. When the two plasma shells start interpenetrating, the overlapping region turns unstable to counter-streaming instabilities. Many linear instabilities compete \citep{BretPoP2010}, but the Weibel (filamentation) instability, with a $\mathbf{k}$ normal to the flow, grows faster than all others, provided \citep{BretPoP2016}, \begin{equation}\label{eq:Wwins} \gamma_0 > \sqrt{\frac{2}{4/3-\sigma }}. \end{equation} The line corresponding to this limit is shown in Fig.~\ref{fig:sigmagamma} by the orange curve. The Weibel instability dominates the unstable spectrum of the system for all points of the $(\sigma,\gamma_0)$ plane above and to the left this line. The micro-physics of shock formation depends on the ability of the Weibel instability to form magnetic filaments capable of blocking the plasma that keeps entering the overlapping region. In the case of un-magnetized pair plasmas, for example, this condition is already met at saturation of the Weibel instability \citep{BretPoP2013,BretPoP2014}. As a result, the density quickly builds up in the overlapping region, and a shock forms. Distribution functions are quickly isotropized in the overlapping region, and MHD considerations apply. The magnetic filaments generated by the Weibel instability are of the form, \begin{equation}\label{eq:Wfield} \mathbf{B}_f = B_f \sin(k\,y) ~ \mathbf{e}_z, \end{equation} where $k$ is the fastest growing wave-number. When there is no external magnetic field, an analysis of the motion of a particle of mass $m$ and charge $q$ in such filaments \citep{BretPoP2015} shows that it is stopped inside if \begin{equation}\label{eq:CritMicro} k^{-1} > \frac{v_0}{\omega_{B_f}},~~\mathrm{with}~~\omega_{B_f} = \frac{q B_f}{\gamma_0 m c}, \end{equation} where $\mathbf{v}_0$ is the initial, flow-aligned velocity of the particle and $\gamma_0$ is its Lorentz factor. Although the model from which this conclusion is derived is highly simplified, the condition is consistent with the results of PIC simulations \citep{BretPoP2014}. How is Eq.~(\ref{eq:CritMicro}) modified in the presence of a flow-aligned magnetic field? One would expect a guiding field to suppress the transverse scattering of particles and to thereby help particles go through the filaments without stopping. Indeed, analysis shows that regardless of their initial velocity or initial position along the $y$ axis, all particles stream through the filaments whenever \citep{BretJPP2016} \begin{equation}\label{eq:crit0} B_0 > \frac{1}{2}B_f. \end{equation} Since $B_f$ arises from the growth of the Weibel instability, its magnitude can be quantified \citep{StockemApJ2006,BretPoP2016}. Therefore, the above criterion can eventually be expressed in terms of $\sigma$ and $\beta_0^2 = 1-1/\gamma_0^2$, giving (see details in Appendix \ref{appen1}), \begin{equation}\label{eq:CritMicroB0} \sigma > \kappa\beta_0^2, \end{equation} where $\kappa=2/3$ if equipartition is assumed at saturation of the Weibel instability. The boundary corresponding to the criterion (\ref{eq:CritMicroB0}) with $\kappa = 2/3$ is shown in Figure \ref{fig:sigmagamma} by the blue curve. The region between the bounds corresponding to Eqs. (\ref{eq:Wwins}) and (\ref{eq:CritMicroB0}), i.e., the region between the orange and blue lines in Fig. \ref{fig:sigmagamma}, corresponds to a range of parameters where the Weibel instability governs the linear phase of the overlapping region, but the filaments at saturation are not strong enough to stop the flow. The expected consequence, as indeed observed in our PIC simulations, is that the flows are not trapped in the overlapping region, but keep streaming through. Isotropization is not achieved, and MHD does not apply. The reader my have noticed that for $\sigma=2$ and 3, the Weibel instability does \emph{not} govern the linear phase of the initial interaction between to two shells. How is it then that the system still fails to follow MHD? We conjecture that the analysis described above, where we were able to quantify all the steps because the Weibel instability is well understood, must be a particular case of the following more general argument. Instead of the Weibel filaments described by Eq.~(\ref{eq:Wfield}), consider a turbulent electromagnetic perturbation $\sum_\mathbf{k} \mathbf{E}_\mathbf{k} + \mathbf{B}_\mathbf{k}$ (with $<\mathbf{E}_\mathbf{k}> = <\mathbf{B}_\mathbf{k}> =\mathbf{0}$) that is present in the overlapping region and that can potentially isotropize the incoming flow. Consider also a superimposed, flow-aligned field $\mathbf{B}_0$. In the limit $B_0=0$, the incoming flow is isotropized, and usual MHD applies. In the opposite limit $B_0\to\infty$, the incoming flow is strongly guided by the mean field, and will ignore the weaker underlying turbulence. Hence, MHD prescriptions are violated. When does the switch from one regime to the other happen? We conjecture that particles will tend to follow the mean field instead of being randomized whenever the energy density $B_0^2/8\pi$ of the mean field exceeds a fraction of order unity of the turbulent energy $\mathcal{E}_T$. Now, if the turbulence is caused by an instability of the counter-streaming flows, its energy will be a fraction of the flow energy density, i.e., $\mathcal{E}_T \lesssim \gamma_0 n_0 m c^2$. As a consequence, the system will depart from MHD beyond a critical value of $(B_0^2/8\pi)/\gamma_0 n_0 m c^2 = \sigma/2$. We thus conclude that, regardless of which instability is initially triggered in the overlapping region, the MHD behaviour is inhibited for values of $\sigma$ greater than about unity. This is indeed what is observed in our PIC simulations. \section{Conclusions} In summary, we have found a departure from MHD behaviour when two collisionless pair plasma shells with a flow-aligned magnetic field collide. While MHD stipulates that the very same shock should form regardless of the $\sigma$ parameter, the micro-physics analysis of the shock formation allows to understand why the standard shock formation scenario can be jeopardized beyond a critical magnetization. PIC simulations have confirmed the theoretical analysis. The results are similar when considering an angle $\theta=5^\circ$ between the field and the flow (see Appendix \ref{ap:PIC}). This shows that the observed MHD departure is not a ``Dirac delta'' effect, strictly restricted to $\theta=0$. What about an electron/proton plasma? It is difficult at this stage to draw definite conclusions about that case. When protons are accounted for instead of positrons, the asymmetric role of electrons and protons results in an upstream current which, in the presence of a flow-aligned magnetic field, is likely to trigger the Bell instability \citep{Bell2004}. This instability is not triggered here because of the symmetric role of electrons and positrons. But if excited, the upstream Bell turbulence, when transported downstream, could help isotropizing the flow. Yet, in spite of some differences with pair plasmas \citep{Stockem2015ApJ}, shock formation in electron/proton plasmas eventually still boils down to the capability of an instability generated turbulence to stop the flow. If the conjecture enounced at the end of Section \ref{sec:micro} turns out to be valid, we could recover a $\sigma$ threshold for the validity of MHD in electron/proton plasmas as well, since the energy of the downstream turbulence should remain a fraction of the upstream kinetic energy. Further studies will be necessary to sort out this important issue. Would it be possible to modify MHD so that it keeps fitting the kinetic results for $\sigma \gtrsim 0.6$? A tentative pathway, beyond the scope of this work, would be to include the downstream anisotropy within the MHD analysis. Indeed, bottom-Figs. \ref{fig:gamma10} \& \ref{fig:gamma10_long} clearly show that the downstream is not isotropized because of the magnetic field. One could therefore try to quantify this anisotropy in terms of the field, before inserting the corresponding temperature anisotropy in the Rankine-Hugoniot jump conditions analysis \citep{Karimabadi95,Vogl2001,Gerbig2011}. Future work will also explore in detail the angular dependence of our results, together with the expected consequences for astrophysics. \section{Acknowledgements} AB acknowledges grants ENE2013-45661-C2-1-P, PEII-2014-008-P and ANR-14-CE33-0019 MACH. AP acknowledges support by the European Union Seventh Framework Program (FP7/2007-2013) under grant agreement \#618499, and support from NASA under grant \#NNX12AO83G. RN's research was supported in part by NASA grant TCAN NNX14AB47G. OS acknowledges support by NASA through Einstein Post-doctoral Fellowship number PF4-150126 awarded by the Chandra X-ray Center, operated by the Smithsonian Astrophysical Observatory for NASA under contract NAS8-03060. Thanks to Smadar Naoz and Victor Malka for valuable inputs.
{ "redpajama_set_name": "RedPajamaArXiv" }
1,616
Bethany Hamilton, at the age of 13 survived a 14-foot tiger shark attack off the shores of her hometown Hawaii was left with one arm and only 26 days later she courageously overcame all odds and began surfing again. In the wake of this life-changing event that took her arm and nearly her life, Bethany's feisty determination and steadfast faith spurred her toward an adventurous comeback that gave her the grit to turn her loss into a gift for others. Bethany is a true champion who inspiring millions worldwide through the love of her family, her sheer determination, and her unwavering faith. Bethany wrote about her experience in the 2004 autobiography Soul Surfer: A True Story of Faith, Family, and Fighting to Get Back on the Board. Bethany's story has touched the hearts of everyone and her inspirational message, charitable efforts, and overall spirit. In April 2011, the feature film Soul Surfer was released, based on the book and additional interviews. She has appeared on many television shows since the loss of her arm. Known most notably for one of the biggest comeback stories of our era, Bethany Hamilton has since become synonymous with inspiration. New York Times Best Selling Author, life who's been featured in a Hollywood movie, professional surfer, and spiritual icon, Bethany is a sought after public speaker. She is motivating audiences worldwide to live their life with more tenacity, courage and faith. POPULAR PROGRAM TOPICS (Bethany's programs are frequently conducted in an interview style) Fighting to Get Back on the Board Bethany has already lived more than a lifetimes worth of triumph and tragedy, and she shares every poignant moment. Audiences learn how she rose once again to the challenges of competition after a life-changing event, how she dealt with the maelstrom of media attention, and how she relied on her faith and innate positive thinking to embrace changes that would undo most people. Bethany's passion and insight, and filled with thrilling moments of the sport personify, a portrait of American heroism that will captivate audiences of all ages. Rise Above Bethany shares her courage and enthusiasm, inspiring audiences to face life head on and stand strong in their faith. Since losing her arm, Bethany has chosen to use her experience to become an inspiration and help others to overcome adversity, no matter how great. Bethany will inspire your audience to believe that you can do whatever they want if you just set your heart to it, and just never give up, and just go out there and do it. Bethany Hamilton has become a source of inspiration to millions through her story of faith, determination, and hope. Born into a family of surfers on February 8, 1990, on the island of Kauai, Hawaii, Bethany began surfing at a young age. At the age of thirteen, on October 31, 2003, Bethany was attacked by a 14-foot tiger shark while surfing off Kauai's North Shore. The attack left Bethany with a severed left arm. After losing over 60% of her blood, and making it through several surgeries without infection, Bethany was on her way to recovery with an unbelievably positive attitude. Lifeguards and doctors believe her strong water sense and faith in God helped get her through the traumatic ordeal. Miraculously, just one month after the attack, Bethany returned to the water to continue pursuing her goal to become a professional surfer. In January of 2004, Bethany made her return to surf competition; placing 5th in the Open Women's division of that contest. With no intention of stopping, Bethany continued to enter and excel in competition. Just over a year after the attack she took 1st place in the Explorer Women's division of the 2005 NSSA National Championships – winning her first National Title. In 2007, Bethany realized her dream and turned pro. Bethany has since participated in numerous ASP and World Tour Events with her major highlight being a second place finish in the ASP 2009 World Junior Championships. Since losing her arm, Bethany's story has been told in hundreds of media outlets and she has been recognized with numerous awards, public appearances, and various speaking engagements. In October 2004, Bethany shared her life story in her autobiography entitled Soul Surfer. Seven years later, the book was made into a major motion picture bearing the same title which released theatrically in April, and for home entertainment in August, 2011. Other books Bethany has written include "Devotions for the Soul Surfer," "Rise Above," A "Soul Surfer" Bible, "Ask Bethany," and "Clash," "Burned," "Storm," and "Crunch." Out of the water, Bethany has grown from a young teenage girl with aspirations of becoming a professional surfer into a twenty-year old professional surfer with aspirations of becoming a beacon of inspiration and hope. Through the platform of professional sport, Bethany has been able to touch a large number of people with her message, charitable efforts, and overall spirit. Bethany just launched her own foundation, Friends of Bethany, which supports shark attack survivors, traumatic amputees, and serves to inspire others through her life story, and is involved in numerous other charitable efforts. Expertise: Athletes | Authors | BUSINESS | CELEBRITIES | Courage | Disability Issues | Empowerment | Ethics / Values | Fitness | Healthy Living | Inspiration | Motivation | MOTIVATION / INSPIRATION | Overcoming Obstacles | Religion Jaclyn North Philippa Gamse
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
6,922
Žacléřský zámek (původně hrad Žacléř, latinsky: Scheczler, německy: Schatzlar, starší názvy: Šaclíř, Šeclíř, Žaclíř) leží na kopci nad městem Žacléř v okrese Trutnov. Současnost Budova zámku se nachází na hustě zalesněném kopci. Je to dvou až třípatrová stavba nepravidelného šestihranného půdorysu s polygonálním průčelím na jižní straně. V současné době je zámek veřejnosti nepřístupný. Jeho vlastníkem je společnost Castrum Scheczler, jejímiž jedinými společníky jsou od roku 2010 manželé Adéla a Karel Čermákovi. Plánovali komplexní rekonstrukci zámku a jeho přestavbu na luxusní stylový hotel s restaurací, ale dnes je zámek i s projektem na prodej. Historie Gotický hrad Žacléř ("castrum Scheczler") se poprvé zmiňuje v roce 1334 v archivu pražské kapituly. Při husitských nájezdech v 15. století byl hrad obléhán. Po husitských válkách se zde usídlili loupeživí rytíři. Roku 1523 byl hrad vypálen a následně roku 1555 přestavěn Kryštofem z Gendorfu do podoby renesančního zámku. Za třicetileté války byl dvakrát dobyt Švédy a vydrancován. V 17. století zámek patřil Jezuitům, v letech 1730–1740 vznikl barokní portál s tesanými ornamenty. V letech 1894–1895 byly provedeny další úpravy. Byly zbořeny hospodářské budovy a byly postaveny pseudogotické hradby s cimbuřím okolo celého zámku. V roce 1945 byl vyrabován interiér. Po požáru byla mansardová střecha nahrazena valbovou. Byl zde internát žacléřského Texlenu. V 80. letech sem jezdily děti na školu v přírodě. V 90. letech 20. století přešel zámek do vlastnictví města Žacléř. Město ho v roce 1997 prodalo společnosti Omikron - RV, ta dále společnosti Wekostav. Od ní jej v roce 2005 koupila společnost Cosy Cottage, nyní Castrum Scheczler. Majitelé zámku Jezuitský řád (1644–1773) C. k. Studijní fond (1773–1838) Karel Půlpán, rytíř z Feldštejna (1838–1877) Karel August Hesse (1877–1880) Karel Adolf Hesse (1880–1887) Waldemar Hesse Hans Georg von Kramsta Galerie obrázků Odkazy Reference Literatura SEDLÁČEK, August, Dr. Hrady, zámky a tvrze Království českého. 1. elektr. vyd. Praha: Jiří Čížek - ViGo Agency, 1998 Rennerová Eva, Mach Daniel. Historie Žacléřska Kolektiv autorů. Krkonoše - příroda, historie, život Externí odkazy památky ve městě Žacléř Oficiální stránky města Žacléř Vývoj a výklad jména Žacléř zaclersko.euweb.cz Renesanční zámky v okrese Trutnov Hrady v Krkonoších Hrady s plášťovou zdí Hrady založené ve 14. století zámek Kulturní památky v okrese Trutnov zámek
{ "redpajama_set_name": "RedPajamaWikipedia" }
4,843
{"url":"https:\/\/www.nature.com\/articles\/s41467-022-29383-5?error=cookies_not_supported&code=2e3a6503-e599-4b85-920e-67596e2d0832","text":"## Introduction\n\nProtein expression-based single-cell cytometry has evolved immensely over the past decades. While flow cytometry remains a staple of both basic cell biology research and clinical diagnostics1, the introduction of mass cytometry (CyTOF) in 2009 increased the potential number of simultaneously measured markers to more than 452 as issues with signal spillover between reporter molecules and autofluorescence of cells were minimized3,4. More recently, spectral flow cytometry enables the measurement of 40 features or more without compromising throughput5. Sequence barcoding-based cytometry, such as CITE-seq, has even further increased the number of markers to the hundreds by almost completely eliminating signal spillover6, and single-cell mass spectrometry is promising to increase feature counts even further7,8,9. Common to all these technologies is the desire to integrate data from different experiments, whether seeking to validate results using external datasets or aiming to increase the breadth and\/or depth of the dataset used for a given study. This is rarely directly possible due to technical variance arising from data being generated with different antibody panels, reagent lots, or instruments; at different times; by different operators; etc.10. The resulting technical variance is commonly referred to as batch effects, and removing this undesired variance has remained a major unsolved challenge.\n\nWhile many proposed methods offer means to alleviate the problem, the majority are designed for very specific applications, requiring technical replicates to be included across all batches, only enabling correction of batch effects in samples belonging to specific conditions, or being designed to work only on a specific type of cytometry data. These limitations preclude large-scale integration of data from different experiments, a feature that has become increasingly desired as more and more data is being published.\n\nIn this work, we have developed the cyCombine method for integration of cytometry data to overcome these challenges. We show that cyCombine enables quantifiably accurate harmonization of cytometry datasets, by removing the technical noise between batches, while maintaining the biological signal. We developed cyCombine to be independent of technical replicates across batches, as well as robust enough to harmonize cytometry data generated with different technologies.\n\n## Results\n\n### The cyCombine batch correction module\n\nThe main engine of the cyCombine batch correction module is the tried and true empirical Bayes method for removal of batch effects, ComBat11. ComBat was first introduced in 2007 as a tool to address batch effects in DNA microarray data, but the empirical Bayes model has since proven useful for different types of bulk expression data. However, ComBat is not directly applicable to single-cell data, as it is designed to detect and remove technical variance between samples from different batches, while preserving biological variance between samples belonging to homogeneous conditions. However, in single-cell cytometry data, each sample is often characterized by vast heterogeneity in the expression patterns of the different cell types, thus prohibiting explicit modeling of technical and biological variance between samples.\n\nIn the cyCombine batch correction module, we address the intra-sample heterogeneity by considering each cell as its own sample and minimize the batch effects for groups of similar cells, one group at a time. The grouping of similar cells is done using a self-organizing map (SOM)12, with an 8\u2009\u00d7\u20098 node grid. This means that the cells will initially be clustered into 64 categories. This will typically be enough to capture the diversity of peripheral blood mononuclear cells, while ensuring that enough cells to capture the biological variance among cells from the same batches, as well as the technical variance between batches are assigned to each cluster. The grid size can be adjusted if less or greater heterogeneity is anticipated. Generally speaking, we would advise to err on the side of overclustering, as long as the data set is of sufficient size. This will not negatively affect the performance of cyCombine, but will increase runtimes (for full discussion and examples see https:\/\/biosurf.org\/cyCombine). In order to ensure that phenotypically similar cells cluster together across different batches, the expression of each marker is initially standardized within each batch. This is done either by transforming the expression values to Z-scores, which works well for fairly low-variance batches (e.g., data from different batches in an experiment), or ranks, which works well for high-variance batches (e.g., data stemming from different experiments or technologies). The transformed data are then used to cluster the cells using the SOM, and the node labels are assigned to the original expression value cells (Fig.\u00a01a).\n\n### The cyCombine panel merging module\n\nTo integrate data from experiments designed with multiple panels of antibodies for increased feature breadth, cyCombine includes a module for panel integration. This module is likewise based on SOM clustering of cells from the different panels using the overlapping markers, followed by probability-based imputation of missing channels by drawing expression values from multi-dimensional kernel density estimates calculated on the cells from the opposing panel (Fig.\u00a01b). The clustering and multidimensional draws ensure that co-expression patterns and frequencies of subtypes are maintained and only \u201ctrue\u201d cell types are imputed (see Supplementary Discussion).\n\n### cyCombine enables large-scale integration of multi-batch, multi-panel cytometry data\n\nIn order to demonstrate that cyCombine enables co-analysis of data from different experimental batches, we generated a CyTOF dataset consisting of 128 samples, run in seven batches. The experiment contained two conditions: 20 healthy donor (HD) samples and 108 chronic lymphocytic leukemia (CLL) samples, collected from 56 patients at two different time points. Samples were depleted of B cells in order to isolate and study the phenotypes of the non-malignant immune cells. Each sample was split in two and stained with two different antibody panels, overlapping by 15 markers and differing by 40 markers (Supplementary Data\u00a01).\n\nFirst, batch effects were minimized in each panel, after which batch effects of the 15 overlapping markers between the two panels were minimized (Fig.\u00a02a, b and Supplementary Figs.\u00a01 and 2). Then, the two panels were merged by imputing expression data from the non-overlapping markers. The integrated dataset consisted of 12,858,678 cells and the expression of 55 markers. The combined dataset was clustered based on a subset of 23 lineage markers using a SOM12 and ConsensusCusterPlus13 to 45 meta-clusters, which were labeled manually, merged, and cleaned-up into a total of 29 clusters (Fig.\u00a02c and Supplementary Fig.\u00a04). The percentage of cells from each sample assigned to each cluster correlated very strongly (Pearson correlation coefficient\u2009=\u20090.9996) between cells derived from the two panels. For both of the two panels, the batch correction resulted in an earth mover\u2019s distance (EMD) reduction of 0.66. Biological variance was retained in both panels, as indicated by the median absolute deviation (MAD) score between pre-batch and post-batch correction samples being 0.02 for both panels, and as shown in Supplementary Fig.\u00a03, rare clusters are maintained after correction.\n\nWithin the 29 clusters we identified a range of T, NKT, myeloid, and NK cells populations (Fig.\u00a02c and Supplementary Fig.\u00a04). Interestingly, we observed that the proportion of the T and NKT cell compartment was increased in CLL patients (Fig.\u00a02d), as were circulating stem cells (as identified by CD34+ expression), especially closer to treatment (Fig.\u00a02e), suggesting marrow stress with higher disease burden. In keeping with previously published data14,15,16, we saw a decrease in naive CD8+ T cells, with corresponding increase in the CD8+ terminally differentiated effector memory (TEMRA) population when comparing close-to-treatment CLL samples to HDs (Supplementary Fig.\u00a05). The use of HLA-DR in the staining further identified groups of CD8+ and CD4+ effector memory T cells that increased between CLL time point 1 and 2 with the CD4+ cluster being specifically enriched for PD-1 (Fig.\u00a02f, g and Supplementary Fig.\u00a05), similar to that reported by Elston et al.15. See also Supplementary Discussion.\n\n### cyCombine removes technical variance and maintains biological variance\n\nAnother scenario where batch correction is necessary is for the integration of external datasets. This is relevant when validating findings in public datasets or when performing meta analysis of multiple existing datasets. To demonstrate cyCombine\u2019s capability to handle integration of data generated in different experimental setups, we integrated CyTOF samples from two different datasets. The two datasets were generated at different facilities, on different versions of the CyTOF instrument, with different panels of antibodies conjugated to different isotopes. Applying cyCombine reduced the EMD by 0.76, making the two datasets directly comparable, and with an MAD score of 0.04, indicating minimal loss of biological variance. As a testament to the robustness of cyCombine, one dataset being B cell depleted did not affect the batch correction, nor did the correction introduce B cells into the depleted batch (Fig.\u00a03).\n\nWhen studying Fig.\u00a03, it is noticeable that a small cluster (0.5%) appears in the Dana-Farber Cancer Institute (DFCI) set in the same UMAP position as the B cells from the Human Immune Monitoring (HIMC) set (11.9%). We do not expect B cells in the DFCI set, so one could suspect that this means that B cells have been artificially introduced by cyCombine. However, when looking closer at these cells it becomes evident that their marker expression before correction is actually distinctly CLL cell-like, although with low CD19 expression explaining their presence after depletion. This fits with 82% of these cells originating from the CLL sample. While this observation makes biological sense, it highlights an important challenge when integrating cytometry: the breadth of the integrated dataset is limited by the overlapping markers in the two panels. In this example, the CLL cells are mislabeled as myeloid due to lack of the CD5 marker for CLL cells and corresponding lack of typical myeloid markers such as CD11b.\n\n### cyCombine enables cross-platform data integration\n\nAs cyCombine is agnostic to marker distributions, it enables integration of datasets generated on entirely different platforms. This can be highly useful in cases where different single-cell technologies have been applied to assess the same samples and one wishes to directly integrate the results. It is also possible to integrate data from different studies, even when the data was generated using different technologies. To demonstrate this feature, we applied cyCombine to three healthy donor peripheral blood mononuclear cell (PBMC) samples generated by CyTOF (HIMC dataset), CITE-seq (Illumina dataset), and spectral flow cytometry (Park et al. dataset5), respectively. While the raw data from the three data types assume distinct groupings in UMAP space (Fig.\u00a04a), batch correction using cyCombine makes the data directly comparable (Fig.\u00a04b). The resulting EMD reduction was 0.69 (Fig.\u00a04c) and the MAD score 0.07. The clustering, subpopulation labeling, and marker expression of cells indicates that data are comparable only after correction (Fig.\u00a04d\u2013e and Supplementary Fig.\u00a06).\n\n### cyCombine scales linearly with the number of cells\n\nAnother desirable application of cyCombine is for integration of very large cytometry datasets, e.g., from clinical trials or retrospective data from clinical diagnostics. Both the computation time and the memory requirements of cyCombine scale linearly with the number of cells and features, and, for example, the correction of 15 markers measured on 12,858,678 cells across two panels ran in 7\u2009min on a standard laptop and required 10 GB of memory. This means that, while the memory requirements necessitate the use of a high performance computer, cyCombine can be applied to billions of cells in less than a day, and there is theoretically no limitation on the number of different datasets that can be integrated (for full runtime analysis see Supplementary Fig.\u00a07 and Supplementary Discussion).\n\n### cyCombine outperforms all existing methods\n\nSeveral tools for batch correction of both flow and mass cytometry data have been published. We tested the performance of all maintained, peer-reviewed tools: CytoNorm, CytofRUV, CytofBatchAdjust, and iMUBAC and compared their performance to cyCombine. To ensure a fair and broad comparison, we applied all tools to all the datasets used in the respective publications. As these tools have various limitations (e.g., designed to handle only one specific data type or condition, or designed to be dependent on technical replicates), each tool was tested only on datasets for which it was explicitly designed and tested by the authors. cyCombine was the only tool in the test that could handle every single dataset in full and showed superior performance for all of them when comparing the EMD reduction and MAD score (Fig.\u00a05a, b). Selected density plots for the different tools and datasets are shown in Supplementary Figs.\u00a08 and 9. Markers for the different datasets were selected such that they illustrate the performance differences between the benchmarked tools. One characteristic of the corrections by iMUBAC is a tendency to over-correct some batches, such that a peak is moved to become misaligned with the corresponding measurements in other batches. This is shown in Supplementary Fig.\u00a08g, where the high-expression peak of CD4 in batch 2 is moved too far to the left, and in Supplementary Fig.\u00a08k, n, where negative-value peaks are introduced by iMUBAC, but not by cyCombine. For CytoNorm, the changes between uncorrected and corrected are relatively small, but in some cases lower peaks in some batches seem to be moved slightly away from the zero-inflated distribution seen in uncorrected data, without a clear reason (Supplementary Fig.\u00a09a, b). For CytofRUV, the MAD scores tend to be higher, reflecting a removal of biological variance. This is also shown in the density plots, e.g., in Supplementary Fig.\u00a09a, f. Finally, CytofBatchAdjust appears to have a tendency to introduce extra peaks, which are not found in the uncorrected datasets (Supplementary Fig.\u00a09d).\n\n## Discussion\n\nDeeper cytometric characterization of cell populations can have great implications, such as better diagnostics, development of novel therapeutics, and identification of important markers of immunity. However, a robust batch correction method is needed in order to fully realize the potential of single-cell cytometry. Correction of batch effects is often necessary to detect subtle biological variance in multi-batch experiments, and it is almost certainly a necessity for large-scale integration of data from different experiments.\n\nIn cyCombine, we handle cellular heterogeneity by applying careful overclustering of the data using a SOM. Co-clustering of data from all batches is enabled by an intermediary transformation of the expression values. The subsequent batch correction is performed using an empirical Bayes model, designed to reduce technical noise, while maintaining the biological signal. While others have previously used the EMD as a metric to measure the reduction in technical variance, we additionally describe the use of the MAD for quantifying the conservation of biological variance, which is a feature that has been overlooked in the majority of previously published methods.\n\nUsing these metrics, we demonstrate that cyCombine batch correction is quantifiably more accurate than existing tools, and through analysis of three different biologically relevant datasets, we highlight the high degree of flexibility and robustness of our method: cyCombine is independent of technical replicates across batches and makes no assumptions about homology of marker expression distributions. It is largely insensitive to sample and batch sizes, as it handles batch correction for as few as eight cells in each SOM partition11. The SOM overclustering step ensures that both population abundances and cell phenotypes are retained, such that if batch effects are not present in a dataset, running the algorithm will not affect the expression values.\n\nThe primary limitations of cyCombine are inherited from ComBat, namely that batches and experimental conditions cannot be confounded. This means that at least one condition from each batch must be present in at least one other batch. Additionally, it is important to note that, while the cyCombine panel merging module enables imputation of non-overlapping features, batch correction is only possible for features present in all batches.\n\nThe accuracy of the imputations depends on the information content of the overlapping markers. Imputation is based on draws from multidimensional (kernel density estimated) distributions of the marker(s) to be imputed in the panel where their expressions were measured. In other words, the imputation is essentially a copy of the expression of the given marker(s) from highly similar cells from the marker-containing panel. This means that cell frequencies, marker distributions, and co-expressions are completely preserved. However, if the overlapping panel of markers is not able to accurately co-cluster cells expressing the markers to be imputed, the imputations will not be meaningful. As such, imputed marker expressions should generally only be used for visualization purposes, and we do not recommend basing differential expression analyses directly on imputed values as this can lead to inflated p values. Please refer to the panel merging vignette at https:\/\/biosurf.org\/cyCombine for deeper discussion and thorough performance evaluation of cyCombine and other panel merging tools.\n\nBoth the challenge and the possibilities presented here become no less relevant when both the rate of growth and heterogeneity of cytometry data increases as new technologies become more prevalent. cyCombine scales linearly with the number of cells, and we envision that cyCombine will catalyze an increase of large-scale analyses of cytometry data. Of particular interest are applications such as harmonization of clinical cytometry data, which may enable better application of machine learning algorithms for diagnostics, for example by enabling faster detection of minimal residual disease in hematological cancers. A range of use cases, including code and in-depth discussions, are available in the cyCombine vignettes: https:\/\/biosurf.org\/cyCombine.\n\n## Methods\n\n### The cyCombine package\n\ncyCombine was designed with protein expression-based cytometry data in mind, and the functions for data preparation are made to handle FCS files. cyCombine assumes that the data has already been pre-gated (i.e., beads, dead cells, doublets, debris, etc. have been removed). When using the built-in functions, the data will be ArcSinh-transformed with a cofactor of choice (recommended cofactors are 5 for CyTOF, 150 for flow cytometry, and 6000 for spectral flow cytometry). For CyTOF data, if counts are randomized, de-randomization is recommended17. However, the modules of cyCombine are not limited to data in FCS format, but are designed to work on any expression matrix that can be represented in an R data.frame\u2014including CITE-seq protein expression data etc. cyCombine contains functions for importing FCS files, detection and correction of batch effects, plotting, evaluating batch correction, as well as performing panel merging. All functions are described in detail in the reference manual and the use case vignettes (https:\/\/biosurf.org\/cyCombine).\n\n### The cyCombine batch correction module\n\ncyCombine\u2019s batch correction module involves three separate steps: First, the expression of every marker is either Z-score normalized or converted to ranks, individually for each batch. Z-scoring is appropriate for similar datasets (e.g., multiple batches run on the same instrument with the same antibody clones and reporter molecules), whereas ranking tends to perform better for less similar datasets (e.g., data generated on different instruments, with different antibody-clones, different reporter molecules, or with different technologies). A SOM12 is applied to the full normalized dataset. The grid size of the SOM should reflect the expected heterogeneity and result in a slight overclustering of the data. In cyCombine, the grid size defaults to 8\u2009\u00d7\u20098, partitioning cells into 64 clusters. Then, the SOM node labels are assigned to the original expression value cells, a per cluster batch correction is applied using ComBat11, and values are capped per-marker to the range of the input. The batch correction step can be performed with or without the use of a non-batch cofactor, e.g., phenotype or sample treatment. The cyCombine approach consequently allows for complex study designs, where not all conditions may be present in each batch, and where technical replicates were not included. It is possible to perform batch correction in studies with more than two conditions, and one may integrate different datasets with only one overlapping condition while accounting for this imbalance. The only requirement is that at least one condition from each batch is present in at least one other batch.\n\n### Batch correction performance metrics\n\nIn order to evaluate the performance of the methods, we primarily applied an approach based on the EMD strongly inspired by Van Gassen et al.18. The EMD has previously been suggested to be a good metric for comparing protein expression distributions18,19. Briefly, the EMD was used to compare the distribution of each marker within SOM nodes across batches. Generally, the SOM nodes were determined post-batch correction using 8\u2009\u00d7\u20098 grids, and the labels were transferred to the uncorrected data so each cell had the same label in both the uncorrected and corrected data. For an in-depth discussion, see the performance benchmarking vignette at https:\/\/biosurf.org\/cyCombine. The distributions were binned with bin size\u2009=\u20090.1, and the EMDs for every marker for each pairwise batch comparison were computed. These scores were determined for both the uncorrected and corrected data, removing those values where both had an EMD\u2009<\u20092. The EMD reduction is given as:\n\n$${{{{{{\\mathrm{EMD}}}}}}}_{{{{{{{\\mathrm{reduction}}}}}}}}=\\frac{{\\sum }_{i=1}^{n}\\left({{{{{{\\mathrm{EMD}}}}}}}_{{{{{{{\\mathrm{before}}}}}}}_{{{{{{\\mathrm{i}}}}}}}}-{{{{{{\\mathrm{EMD}}}}}}}_{{{{{{{\\mathrm{after}}}}}}}_{{{{{{\\mathrm{i}}}}}}}}\\right)}{{\\sum }_{i=1}^{n}{{{{{{\\mathrm{EMD}}}}}}}_{{{{{{{\\mathrm{before}}}}}}}_{{{{{{\\mathrm{i}}}}}}}}},$$\n(1)\n\nwhere n is the total number of comparisons (number of SOM nodes times the number of markers times the number of pairwise batch comparisons). Furthermore, we have developed a score that reflects the amount of variance removed during a batch correction process. The score is based on the MAD and quantifies the variability of each marker in the dataset before and after correction. In practice, it is calculated very similarly to the EMD reduction: The MAD is calculated for the dataset after performing a SOM-based clustering, and is calculated per cluster, per marker, and per batch. So, the MAD is calculated per batch, whereas the EMD calculations are performed for each pairwise batch\u2013batch comparison. This means that the MAD score quantifies intra-batch effects of the correction, and the EMD reduction quantifies inter-batch effects. After calculating the MADs for both the corrected and uncorrected datasets, the MAD score is calculated as the median of the absolute difference in MAD per value:\n\n$${{{{{{\\mathrm{MAD}}}}}}}_{{{{{{{\\mathrm{score}}}}}}}}={{{{{{\\mathrm{median}}}}}}}_{i=1}^{n}\\left(\\left|{{{{{{\\mathrm{MAD}}}}}}}_{{{{{{{\\mathrm{before}}}}}}}_{i}}-{{{{{{\\mathrm{MAD}}}}}}}_{{{{{{{\\mathrm{after}}}}}}}_{{{{{{\\mathrm{i}}}}}}}}\\right|\\right),$$\n(2)\n\nwhere n is the total number of comparisons (number of SOM nodes times the number of markers times the number of batches). For an introduction to EMD reduction and MAD score, please see the performance benchmarking vignette at https:\/\/biosurf.org\/cyCombine.\n\n### The cyCombine panel merging module\n\ncyCombine also contains two functions for marker imputation. One function is designed with panel merging in mind and imputes the expression values of non-overlapping markers across two datasets. It works by first doing a SOM-based (defaults to an 8\u2009\u00d7\u20098 grid) clustering of the datasets based on all of the overlapping markers. Then, for each cell in one of the datasets, the values for the missing markers are imputed by using the values from cells in the other dataset that fall within the same SOM node. The imputations are made by simulating a multi-dimensional kernel density estimate: Each cell\u2019s missing values are imputed by randomly drawing a cell from the other dataset and adding a Gaussian error, which is based on a draw from a Normal distribution with mean 0 and standard deviation corresponding to the bandwidth of each marker in the training population. However, if there are less than 50 cells from the other dataset within the SOM node, the values for the missing channels are set to NA as imputation would be unreliable.\n\nThe other function was made for salvaging a single channel within a dataset in selected batches. This can be useful in cases where one has a completely mis-stained marker in a single batch. It relies on the same principles, but instead of transferring information in one dataset to another, it utilizes intra-dataset batches.\n\n### Chronic lymphocytic leukemia cohort\n\nCLL samples were obtained from the CLL Research Consortium (CRC) based at the University of California, San Diego, from patients who provided informed consent and as part of an institutional review board approved protocol. All samples were anonymized by the CRC. The dataset was generated at the DFCI and contained PBMC samples from 20 healthy donors (5 from DFCI and 15 from HemaCare) and samples from 56 patients with CLL. The latter were sampled at two distinct time points (T1 and T2), the mean time between T1 and T2 was 58.7 months (sd\u2009=\u200947.4 months), and T2 was obtained close to first treatment (mean\u2009=\u20094.5 months, sd\u2009=\u200910.4 months) (Fig.\u00a06). For the 56 CLL patients, the mean age at diagnosis was 56.1 years (sd\u2009=\u20099.6 years), with healthy donors being age-matched (mean\u2009=\u200956.7 years, sd\u2009=\u20094.5 years). Serial samples from CLL patients along with PBMCs from healthy individuals were collected in accordance with the Declaration of Helsinki and written informed consent was obtained from all participants. No patients were compensated for their donation. A proportion of healthy donors samples were obtained for Hemacare and these donors were compensated for their time commitment during donation.\n\n### Immunophenotyping CLL cohort using mass cytometry\n\nAll patient and control PBMC samples were thawed in RPMI-1640 media (ThermoFisher) supplemented with 10% heat-inactivated FBS, sodium heparin (20 UI\/mL) and 25 units\/mL benzonase nuclease (Life Technologies and Sigma-Aldrich). Samples were subjected to B cell depletion using EasySep Human CD19 positive selection kit II (Stem Cell Technologies) before resuspension in RMPI and 10% FBS.\n\nThe samples were spun down and aspirated. Five micromolar of cisplatin viability staining reagent (Fluidigm) was added for two minutes and then diluted with culture media. After centrifugation, Human TruStain FcX Fc receptor blocking reagent (BioLegend) was used at a 1:100 dilution final in cell staining buffer (CSB) (PBS with 2.5\u2009g\/L bovine serum albumin and 100\u2009mg\/L of sodium azide, Sigma Aldrich) for 10\u2009min followed by incubation with cell surface CyTOF antibody panels for 30\u2009min (Supplementary Data\u00a01). All CyTOF antibodies were obtained from the Harvard Medical Area CyTOF Antibody Resource and Core (Lederer Lab, Brigham and Women\u2019s Hospital, Boston, MA).\n\nSixteen percentage of stock paraformaldehyde (ThermoFisher Scientific) dissolved in PBS was used at a final concentration of 4% formaldehyde for 10\u2009min in order to fix the samples before permeabilization with the FoxP3\/Transcription Factor Staining Buffer Set (ThermoFisher Scientific). The samples were incubated with SCN-EDTA coupled palladium 20-sample barcoding reagents (Fluidigm) for 15\u2009min, washed 3\u00d7 in CSB, and then combined into a single 20 PBMC sample for subsequent staining. Conjugated intracellular CyTOF antibodies (Supplementary Data\u00a01) diluted in the permeabilization buffer from the FoxP3\/Transcription Factor Staining Buffer Set were added into each tube and incubated for 30\u2009min. Cells were then fixed with 1.6% formaldehyde for 10\u2009min.\n\nThe samples were processed in seven batches per antibody panel, each batch containing both control and patient samples. During sample processing, some samples were excluded due to dead cells or having too few cells to apply both panels. The final dataset has measurements for a total of 128 samples, all of which were included in the staining with panel 1, and 112 that were also stained with panel 2. The 20 healthy donors were all stained with both panels. The CLL samples stained with panel 1 consisted of 52 samples at T1 and 56 (all patients) at T2. For panel 2, the numbers were 45 and 47, respectively. To identify single cell events, DNA was labeled for 20\u2009min with an 18.75\u2009\u03bcM iridium intercalator solution prior to acquisition. Samples were subsequently washed and reconstituted in cell acquisition solution in the presence of EQ Four Element Calibration beads (Fluidigm) at a final concentration of 1\u2009\u00d7\u2009106 cells\/mL. Samples were acquired on a Helios CyTOF Mass Cytometer (Fluidigm).\n\n### Analysis of CLL cohort mass cytometry data\n\nThe raw FCS files were normalized to reduce signal deviation between samples over the course of multi-day batch acquisitions, utilizing the bead standard normalization method established by Finck et al.20 as implemented in the premessa R package21. The normalized files were then compensated with a panel-specific spillover matrix to subtract cross-contaminating signals, utilizing the CyTOF-based compensation method established by Chevrier et al.22 as implemented in CATALYST v. 1.12.2. These compensated files were then deconvoluted into individual sample files using a single-cell based debarcoding algorithm established by Zunder et al.23 available in premessa v. 0.2.6. This was followed by pre-gating to live intact singlet cells using FlowJo version 10 (Tree Star Inc) as shown in Supplementary Fig.\u00a010.\n\nThe pre-gated FCS files for each panel were read into R v. 4.0.024 using the cyCombine prepare_data function, using de-randomization and ArcSinh-transformation with cofactor\u2009=\u20095. The two panels consisted of a total of 6,027,290 and 6,831,388 cells. Subsequently, each panel was batch corrected using cyCombine with scaling and an 8\u2009\u00d7\u20098 SOM grid using CLL\/HD status as cofactor. After correction, all cells were clustered using an 8\u2009\u00d7\u20098 SOM grid and the labels were transferred to the uncorrected data. The EMD was calculated for each marker comparing the batches and the EMD reductions and MAD scores between corrected and uncorrected data were determined for each panel. The data from the two panels was then co-batch corrected using the 15 overlapping markers with scaling and an 8\u2009\u00d7\u20098 SOM grid maintaining CLL\/HD status as cofactor but using panel as batch. After co-correction, the 40 (19\u2009+\u200921) non-overlapping markers were imputed using an 8\u2009\u00d7\u20098 SOM grid and the resulting datasets were combined to a single 55-marker dataset.\n\nThe 55-marker data was then clustered using a 10\u2009\u00d7\u200910 SOM grid12 and ConsensusClusterPlus v. 1.54.013 using 23 markers: CD3, CD4, CD8, CD45RA, CD45RO, CD197, CD127, CD25, CD5, CD19, CD20, CD56, CD16, CD33, CD14, HLA-DR, CD123, CD1c, CD1d, CD11c, CD11b, FCER1A, and CD34. The result was extracted for 45 meta-clusters, and each of these was manually annotated based on its marker expression. Among these clusters, there were eight pairs of clusters, which displayed highly similar expression patterns. Consequently, each of these sets were merged to a single final cluster, as previously described25, leaving 37 clusters. Four of those clusters were labeled as either B cells (CD19+ CD20+) or CLL cells (CD19-lo CD20-lo CD5+), but because these populations can be considered cells that escaped the applied depletion, we removed those clusters from downstream analysis. Furthermore, four clusters displayed abnormal expression patterns, e.g., lack of lineage markers. When considering the mean viability stain for the clusters, it was observed that these four clusters all fell within the top-six highest values. This, together with the abnormal expression patterns, indicated that these clusters were composed of poor-quality cells, which we also excluded from further analysis. This left a final set of 29 populations and 10,719,711 cells to study.\n\nDifferential abundance testing was carried out using an approach presented by Weber et al.26 (testDA_voom). Each test included individual false discovery rate (FDR)-correction for the populations included, but no correction was performed between tests. Instead, a FDR-threshold of 0.01 was used for significance. When relevant, the paired nature of the data was considered by using random effects. For differential expression testing within clusters, we analyzed the cell originating from each panel separately, meaning that no imputed values were included. The methodology for differential expression testing was also derived from the work by Weber et al.26 (testDS_limma), in which medians serve as the foundation of the tests. Only markers not used for clustering were included in testing. Again, pairedness was considered when appropriate, and an FDR-threshold of 0.01 was used.\n\n### HIMC healthy control sample\n\nA single healthy donor PBMC sample (Human Immune Monitoring Center (HIMC) healthy donor, ctrls-001, MATLAB-normalized) was downloaded from FlowRepository (ID: FR-FCM-ZYAJ) and pre-gated to live intact singlets in FlowJo version 10 (Tree Star Inc). The 174,601 cells were processed in R using cyCombine with de-randomization and ArcSinh-transformation with a cofactor\u2009=\u20095. For the integration with the CLL dataset, this was followed by manual gating to 10 cell types based on the lineage markers, CD3, CD4, CD8, CD14, CD19, CD20, CD33, CD45RA, CD56, CD161, CD197, and HLA-DR. Unlabeled cells (n\u2009=\u2009615) were discarded. For the three-datatype integration, the pre-gating was followed by clustering to 20 meta-clusters using a 6\u2009\u00d7\u20096 SOM12 grid and ConsensusClusterPlus13 based on expression of 11 markers overlapping with the healthy donor spectral flow cytometry (SFC) and CITE-seq sets (CD3, CD4, CD8a, CD14, CD16, CD19, CD25, CD45RA, CD56, CD127, and PD-1). These clusters were annotated manually based on protein expression levels, and 8932 cells were removed due to ambiguous expression patterns.\n\n### Flow cytometry dataset\n\nThe SFC dataset from Park et al.5 was downloaded from FlowRepository (ID: FR-FCM-Z2QV). The dataset consists of samples from four healthy donor PBMCs, which were frozen and thawed, stained with 40 different antibodies in one panel, and analyzed using a 5-laser full spectrum flow cytometer (Cytek Biosciences Aurora).\n\nPre-processing was carried out in FlowJo version 10 (Tree Star Inc). The dataset was gated on lymphocytes, and singlets and non-debris were identified using forward and side-scatter. Dead cells were excluded using live\/dead stains. Data from these gates were then exported in FCS format before further analysis in R: Using cyCombine, the data was loaded and transformed using ArcSinh with a cofactor\u2009=\u20096000. A single sample (donor 303444) with 582,005 cells was selected and clustered to 20 meta-clusters using a 6\u2009\u00d7\u20096 SOM12 grid and ConsensusClusterPlus13 based on expression of 11 markers overlapping with the healthy donor CyTOF and CITE-seq sets. The clusters were annotated manually based on protein expression levels, and 21,307 cells were removed due to ambiguous expression patterns.\n\n### Sequence barcoding-based dataset\n\nThe filtered feature\/cell matrix from the \u201c10k PBMCs from a Healthy Donor\u2014Gene Expression and Cell Surface Protein\u201d dataset was obtained from the 10\u00d7 website (https:\/\/support.10xgenomics.com\/single-cell-gene-expression\/datasets\/3.0.0\/pbmc_10k_protein_v3). This data was generated on the PBMCs of a single healthy donor stained with TotalSeq-B antibodies. It was sequenced on an Illumina NovaSeq and processed by Cell Ranger v. 3.0.0.\n\nThe TotalSeq expression matrix was processed in R using Seurat v. 4.0.027. First, cells were filtered to maintain only those expressing between 200 and 2800 genes, having less than 10,000 detected RNA molecules and 20,000 detected protein molecules, and with a mitochondrial gene percentage below 10, leaving 6949 cells for analysis. The protein portion of the data was normalized, scaled, and dimensionality reduced to the 11 markers overlapping with the CyTOF and SFC datasets, before applying Louvain clustering at a resolution of 0.2. The 12 resulting clusters were manually annotated based on the expression levels of the 11 clustering proteins. Two clusters were considered to be doublets and excluded from the downstream integration, leaving 6776 cells.\n\n### Integration of CLL and HIMC healthy donor sample\n\nFor the integration with the HIMC healthy donor sample, two samples from the DFCI set (one CLL and one HD) from panel 1, batch 5 were selected (before any batch correction was applied) and manually gated to 10 cell types based on 12 lineage markers: CD3, CD4, CD8, CD14, CD19, CD20, CD33, CD45RA, CD56, CD161, CD197, and HLA-DR. Unlabeled cells (n\u2009=\u20094353) were considered to be representative of the low-quality cells, and were discarded along with any cells labeled as B cells, since these were residual cells resulting from incomplete depletion. The HIMC sample was likewise gated to ten populations using the same 12 lineage markers. This resulted in a total of 352,210 cells, with 17 overlapping markers between the datasets (CD3, CD4, CD8, CD14, CD19, CD20, CD25, CD27, CD33, CD45RA, CD56, CD127, CD161, CD197, HLA-DR, ICOS, and PD-1). Datasets were batch corrected using cyCombine with an 8\u2009\u00d7\u20098 SOM grid with the rank normalization method (and average ties method). Each set was considered a batch, and the HD\/CLL status was used as a cofactor. The result of the batch correction was evaluated with the EMD reduction and MAD score as well as visual inspection of UMAP plots comparing the location of each cell type (which was assigned separately) across datasets.\n\n### Integration of cross-platform datasets\n\nThe HIMC CyTOF sample, the SFC sample, and the CITE-seq data were batch corrected together following the pre-processing described in the section for each set. Before batch correction, each set was downsampled to 6776 cells and to the 11 overlapping protein markers. This was followed by cyCombine batch correction with an 8\u2009\u00d7\u20098 SOM grid with the rank normalization method (and average ties method). Each dataset was considered a batch and no cofactors were considered. The result of the batch correction was evaluated with the EMD reduction and MAD score as well as UMAP plots comparing the location of each cell type (which was assigned separately) across datasets.\n\n### Benchmarking\n\nWe compared the performance of the cyCombine batch correction module with four batch correction algorithms designed to work with mass cytometry data: CytoNorm18, CytofRUV28, iMUBAC29, and CytofBatchAdjust30. Other tools exist, both developed for flow and mass cytometry, including gaussNorm and fdaNorm31,32, which the authors state are no longer supported, and the tools cydar33, BatchEffectRemoval34, BatchEffectRemoval201835, SAUCIE36, and swiftReg37, which are not included due to either not being peer-reviewed, not being maintained, requiring a license, or being designed to work only on very specific cases, such as harmonizing two technical replicates. We tested each included tool on the datasets from the original publications and the set of datasets from other publications deemed to be suitable by the authors of each tool; i.e., some tools require technical replicates and not all datasets include these. Furthermore, we only tested each tool on datasets from platforms for which the use is demonstrated in the original publication. For tools with multiple tested settings, the setting with the best overall performance based on both the EMD reduction and MAD score was recorded.\n\nAll five included tools were run on the CyTOF datasets originally presented in the CytoNorm and CytofRUV papers, as well as the DFCI samples from batch 3 of both panels 1 and 2, where each panel was considered a batch. We will refer to these sets as the Van Gassen, Trussart, and DFCIb3 data, respectively. Additionally, we batch corrected six CyTOF datasets and one SFC set without technical replicates using cyCombine and iMUBAC. These datasets are the DFCI panel 1 and panel 2 sets, and five datasets presented in the iMUBAC article: Each of the three panels of the Krieg dataset, as well as a CyTOF and a SFC set originally generated for iMUBAC, which we refer to as OgishiCyTOF and OgishiSFC. An overview is presented in Table\u00a01. All CyTOF datasets were ArcSinh-transformed with a cofactor\u2009=\u20095 for processing with all tools.\n\nThe Van Gassen dataset18 consists of 40 samples from two healthy controls. They comprise unstimulated and stimulated samples each run ten times (ten batches). Thirty-seven protein markers were measured. The Trussart dataset28 consists of 24 samples from nine healthy controls (HCs) and three CLL patients, each run twice (two batches). Thirty-one protein markers were measured. The FCS files were pre-processed with bead normalization and debarcoding according to the script from the CytofRUV supplementary files (using CATALYST). The Krieg1, Krieg2, and Krieg3 datasets38 comprise 30, 26, and 25 markers, and each contain 60 samples. They were, according to the original publication, processed as four experimental batches. Three conditions are considered: Healthy donors (n\u2009=\u200920), responders (n\u2009=\u200922), and non-responders (n\u2009=\u200918) to anti-PD-1 immunotherapy. Each condition is included in each of the four batches. The dataset was pre-processed according to the instructions in the iMUBAC article: DNA and viability intercalators were used to exclude dead cells, doublets, and debris with the prepSCE function from iMUBAC. The OgishiCyTOF dataset29 contains measurements on 38 protein markers and consists of 57 samples in seven batches. A total of three conditions were included: Healthy (n\u2009=\u200950), MSMD (n\u2009=\u20095), and Salmonellosis (n\u2009=\u20092). Some of the healthy samples are biological replicates. The dataset was pre-processed according to the instructions in the iMUBAC article: DNA and viability intercalators were used to exclude dead cells, doublets, and debris. The OgishiSFC dataset29 measured 18 protein markers across 14 samples in two batches. A total of three conditions were included: Healthy donors (n\u2009=\u200911) and two types of autoimmune disease (n\u2009=\u20091 and n\u2009=\u20092). The dataset was pre-processed according to the instructions in the iMUBAC article: The viability stain was used to exclude dead cells and logicle transformation was used. The DFCI sets comprised two conditions: Healthy donors and CLL samples. As mentioned, the panel 1 data (DFCI1) had 36 measured markers, and the panel 2 data (DFCI2) had 34 markers. The DFCIb3 set consisted of the samples originating from batch 3 in each of the two panels, which had 15 overlapping markers. The DFCI samples were pre-processed as described above.\n\nWhen running CytoNorm, we used FlowSOM clustering with a 10\u2009\u00d7\u200910 grid and 25 final clusters (no downsampling). The batch effects were modeled using 101 quantiles. All protein markers were included. For the Van Gassen set, the 20 samples from healthy control 1 were used to model batch effects and the 20 samples from healthy control 2 were normalized. Evaluation of batch effect reduction was carried out using only the samples from healthy control 2. For the Trussart dataset, the CLL2 and HC1 samples were used as the technical replicates (training data). The remaining 20 samples were used as validation data and the evaluation of batch effect reduction was carried out using only the HC2-9, CLL1, and CLL3 samples. For the DFCIb3 set, the CLL_08_T1 and HD_05 samples were used as technical replicates, and the remaining 35 samples were used for evaluation. Corrected values were capped at 300 to avoid problems with very large values during evaluation.\n\nFor running CytofRUV, we used clustering with 20 clusters on lineage markers only (24 for Van Gassen, 19 for Trussart, and 12 for DFCIb3). All markers were corrected at varying values of k\u2009=\u2009{5, 10, 15, 20}. For the Van Gassen set, all healthy control 1 samples were used as technical replicates (two sets of ten samples each). For the Trussart set, the CLL2 and HC1 samples were used as the technical replicates, and for the DFCIb3 set, the CLL_08_T1 and HD_05 samples were used. All samples were included in the evaluation.\n\nFor running CytofBatchAdjust, all files were renamed according to the tool requirements. For Van Gassen, PTLG021 was used as the reference batch and the unstimulated healthy control 1 samples were used as anchors. We tested CytofBatchAdjust with method\u2009=\u2009{95p, SD, quantile} and transformation\u2009=\u2009{TRUE, FALSE}. For the Trussart set, HC1 was used as the anchor sample and RUV1b samples as reference batch, whereas DFCIb3 correction used HD_05 as the anchor and panel 1 as the reference batch. All markers were used for correction and all samples were used in evaluation. Corrected values were capped at 300 to avoid problems with very large values during evaluation.\n\niMUBAC was run largely according to the details in the original article. For all datasets, only healthy donors were included in correction, and downsampling to 200,000 cells for each batch was applied for all datasets, except for the Krieg3 dataset, for which we downsampled to 50,000 cells per batch, and the OgishiSFC set, for which 500,000 cells per batch were included. For the OgishiCyTOF set, only 47 local healthy donor samples were included as in the original publication (travel\/family controls excluded). All evaluations were based solely on the downsampled datasets using all markers.\n\ncyCombine was generally run on all available samples using the conditions stated in the presentation of each dataset. We ran cyCombine with norm_method\u2009=\u2009{scale, rank} on the full datasets with all markers.\n\n### Runtime and memory requirements\n\nWe used the OgishiCyTOF dataset comprising seven batches and 38 protein markers for testing the runtime and memory usage of the different tools. Several of the evaluated tools ran directly on FCS files; therefore, running these tools on a range of different sizes required storing downsampled versions of the original FCS files in new ones. This was done by loading the original FCS files, disregarding non-overlapping columns, sampling to the predefined sample sizes, and storing the resulting data in respective folders. By storing the data this way, it was ensured that all tools were run on the same data at each data size. The runtime and memory usage were measured for each tool for every sample size using the UNIX command time -v. The Maximum resident set size and the elapsed parameters in the output defined the memory usage and runtime, respectively. The test was performed on 40 cores (although none of the tools are fully parallelized, some sub functions are) on an HPE Apollo 2000 system with up to 192\u2009GB PC4 2933 RAM. The standard laptop was a 2018 MacBook Pro with 16\u2009GB 2400\u2009MHz DDR4 memory and a 2.6\u2009GHz 6-Core Intel Core i7 processor.\n\n### Plots\n\nUMAPs were generated using uwot v. 0.1.939 on no more than approximately 500,000 cells (to avoid overcrowding the plots). Samples were downsampled if more cells were present, whereas all statistical analyses and clustering were done on the full datasets unless otherwise specified. Plots were generated using ggridges v. 0.5.240 and ggplot2 v. 3.3.341, and patchwork v. 1.1.142 was used for combining plots.\n\n### Reporting summary\n\nFurther information on research design is available in the\u00a0Nature Research Reporting Summary linked to this article.","date":"2023-03-27 22:45:57","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 1, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.40662920475006104, \"perplexity\": 3695.645582328913}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2023-14\/segments\/1679296948708.2\/warc\/CC-MAIN-20230327220742-20230328010742-00723.warc.gz\"}"}
null
null
The availability of new technologies and increased market demands are driving rapid change at Advance Distribution Services, Inc. In order to keep pace with industry trends and increasing competitiveness we've turned to the experts at RAMP Systems for our Warehouse Management Software (WMS); Enterprise. After evaluating many different WMS systems RAMP was the right fit for our business and our customers. RAMP Enterprise manages orders coming at you from all directions; organizes warehouse inventory of all types; executes all logistics operations; manages each customer account; and initiates and tracks every shipment. It helps you manage a broader spectrum of facilities, activities and assets. RAMP Enterprise is a unified logistics system, built on the Microsoft.NET platform that operates in real-time to provide Warehouse Managment, Order Managment, Transportation Management, and Activity Billing. It features web, speech, barcode and graphics interfaces with workers, managers, clients, customers, vendors, shippers and accountants. RAMP takes care of all the basics like receiving, putaway, picking and replenishments, in real-time, with the flexibility to manage multiple businesses and different business models under the same roof. But it goes far beyond the four walls of your warehouse to provide customer and client access to orders, inventory, account information and shipments. Picking – Order, Wave, Pick & Pass, Batch, etc. Item analysis services such as usage, history, etc. For more information on our products and services such as Fulfillment Services, Reverse Logistics, our Kentucky Warehouse, and RFID Supply Chain Solutions. Contact Us!
{ "redpajama_set_name": "RedPajamaC4" }
3,942
\section{Introduction}\label{sec:introduction} The rapidly expanding list of confirmed exoplanet detections and accumulating evidence about the histories of planets in our Solar System has created an increasing demand for tools that can complement available observations to provide insights about which planets may be habitable or inhabited, now or in their past. To date, studies of the climates and habitability of planets other than modern Earth have been carried out primarily with one-dimensional (1-D) radiative-convective models \citep[e.g.][]{Kasting1988,Kasting1993,Pavlov2001,Segura2003, Domagal-Goldman2008, Domagal-Goldman2011, Kitzmann2010,Zsom2012, Kopparapu2013, Ramirez2014a, Ramirez2014b, Rugheimer2013, Rugheimer2015, Grenfell2014, Meadows2016}. These models have the virtue of computational efficiency, permitting exploration of a wide range of parameter space and coupling to complex atmospheric chemistry models. Their limitations are their inability to properly account for the effects of clouds, atmospheric and oceanic heat transports, obliquity effects, day-night contrasts, and regional aspects of habitability. Modeling of terrestrial climate and climate change was initially performed with 1-D models as well \citep[e.g.][]{Manabe1964, Hansen1981}, but soon gave way to three-dimensional (3-D) general circulation models (GCMs; sometimes referred to as global climate models), which are lower resolution versions of the models used for numerical weather prediction. GCMs have evolved from atmosphere-only to coupled atmosphere-ocean-sea ice models, and more recently have added atmospheric and ocean chemistry, land and ocean ecosystem dynamics, and dynamic land ice to create today's Earth system models \citep{Jakob2014} that are the basis of projections of 21st Century anthropogenically forced climate change. The first application of a GCM to another planet was the Mars model of \citet{Leovy1969}, and \citet{Joshi1997} performed the first hypothetical exoplanet GCM simulation. Since these pioneering studies, GCMs have been used to simulate the dynamics and climates of a broad range of rocky planets past and present, as well as planets with thick H$_2$-He envelopes \citep[see][for a review]{Forget2014}. GCMs self-consistently represent all the processes that 1-D models cannot, though they have their own limitations: uncertainties in parameterizations of small scale processes, computational cost that requires radiative transfer and chemistry to be represented in less detail than in 1-D models, and a level of detail that cannot be constrained as well by observations for other planets as it can be for Earth. Increasingly, GCMs are playing a key role in a ``system science'' approach that considers planetary climate and habitability in the larger context of the evolution of the solid planet, its parent star, and other planets and planetesimals that affect its evolution. In this paper we describe a new planetary and exoplanet GCM, the ROCKE-3D{} (Resolving Orbital and Climate Keys of Earth and Extraterrestrial Environments with Dynamics) model. ROCKE-3D{} is developed from its parent Earth climate GCM, the NASA Goddard Institute for Space Studies (GISS) ModelE2{} \citep{Schmidt2014}. ModelE2{} was the GISS GCM version used for the Coupled Model Intercomparison Project Phase 5 (CMIP5), the most recent phase of a protocol by which successive generations of Earth climate model results are made publicly available for systematic analysis by the international community. ROCKE-3D{} is configured to simulate the present and past atmospheres of rocky Solar System planets as well as rocky exoplanets. Like several other planetary GCMs, ROCKE-3D{} is adapted from a previously existing Earth GCM \citep[e.g. PlanetWRF,][]{Richardson2007}. Unlike any other planetary GCM ROCKE-3D{} is based on the most recent published version of its parent Earth model, is developed and used in part by the same people who develop the Earth model, and will evolve in parallel with future generations of the Earth model, thus benefiting from emerging insights from Earth science into physical processes that are also relevant to other planets. The baseline ROCKE-3D{} version described in this paper is referred to as Planet 1.0{}. In the following sections we discuss the challenges involved in adapting an Earth GCM to simulate other rocky planets, the choices made to make Planet 1.0{} as generally applicable as possible, and the remaining limitations that will not be addressed until the next generation of the model has been developed. ROCKE-3D{} Planet 1.0{} has already been used to simulate hypothetical ancient Venus scenarios \citep{Way2016}, while simulations of several deep Earth paleoclimate eons, modern Mars, and hypothetical exoplanets are in progress. In principle it should be possible to modify an Earth GCM to simulate other planets simply by changing relevant external parameters. In reality, though, terrestrial GCMs are designed with only Earth in mind, and are programmed by a large group of people of varying backgrounds and experience whose composition evolves over several decades. At any moment in its history, therefore, a GCM is a mix of modern and obsolete programming approaches, visionary and myopic coding philosophies, and best and worst practices that necessitate new approaches to make the model sufficiently general for planetary applications. Many of those approaches will be discussed herein. In Section~\ref{sec:configurations} below we discuss the present Planet 1.0{} model resolution and possible ocean configurations. In Section~\ref{sec:calendar} extensions to the model calendar system are reviewed. These allow for slower or faster rotating worlds (than present day Earth), synchronously rotating worlds, and even retrograde rotation like that of present day Venus. Section~\ref{sec:parameterizations} discusses the major physics parameterizations in the model, while Section~\ref{sec:properties} covers its geophysical properties. Section~\ref{sec:enhancement} describes several examples of GCM modifications for Planet 1.0{} that have fed back to the parent Earth GCM. Section~\ref{sec:use} covers appropriate uses for ROCKE-3D, and Section~\ref{sec:discussion} contains our conclusions. Two appendices provide a description of input and post processing tools available external to the model. \section{Model Configurations} \label{sec:configurations} \subsection{Resolution and Throughput} In describing the physics of ROCKE-3D, we refer to physics from the present operational version of the parent Earth model as that of ``GISS'' or ``ModelE2'', and new capabilities as that of ``ROCKE-3D''. ModelE2{} is a Cartesian gridpoint model routinely run at $\ang{2} \times \ang{2.5}$ latitude-longitude atmospheric resolution with 40 vertical layers, and at $\ang{1} \times \SI{1.25}{\degree}$ latitude-longitude ocean resolution with 32 vertical layers. This resolution has been retained for certain deep Earth paleoclimate simulations, where the higher resolution permits better comparison to geological data as well as better portrayal of the atmospheric and oceanic dynamics. GCM atmospheric (as opposed to oceanic) resolution should at a minimum be fine enough to crudely resolve the dominant scales of atmospheric motion. Typically this is assessed using the Rossby radius of deformation (the typical spatial scale of midlatitude low and high pressure centers) $L_d=NH/f$, where $N$, the Brunt–V\"{a}is\"{a}l\"{a} frequency, is proportional to the static stability, $H$, the scale height, depends on temperature, gravity, and atmospheric composition, and $f$, the Coriolis frequency, is proportional to planet rotation rate. For Earth $L_d \sim \SI{1000}{\kilo \meter}$ ($\sim 1/6$ Earth's radius) and $\ang{2} \times \ang{2.5}$ grid boxes are about \SIrange{200}{250}{\kilo \meter} in size, allowing such features to be adequately resolved. For simulations of other planets, most initial studies with Planet 1.0\ have been for smaller planets for which grid boxes at the same resolution are smaller or more slowly rotating planets for which $L_d$ is larger than on Earth. For these simulations it has been possible to run Planet 1.0{} at $\ang{4}\times\ang{5}$ atmospheric and oceanic horizontal resolution with no loss in accuracy but at almost an order of magnitude faster speed. This lower resolution version of Planet 1.0{} has 20 atmospheric layers (but with an option for 40 layers) with a model top at \SI{0.1}{\hecto \pascal} (about \SI{60}{\kilo \meter} altitude), and in coupled mode, 13 ocean layers with maximum depth up to \SI{4647}{\meter}. Planet 1.0{} can be run on a capable laptop for modest integrations at this coarser resolution, but the bulk of our research is conducted on the NASA Goddard Space Flight Center Discover cluster of Linux scalable units (\url{https://www.nccs.nasa.gov/services/discover}). With 44 cores, ROCKE-3D{} can simulate 100 years in approximately 24 hours of wall-clock time with a fully-coupled ocean at an atmosphere and ocean resolution of $\ang{4} \times \ang{5}$ with 40 atmospheric layers and 13 ocean layers, using the default ModelE2{} radiation scheme. These simulations use a single node/motherboard with two Intel Xeon E5-2697 v3 Haswell \SI{2.6}{\giga \hertz} each with 14 cores. With SOCRATES, our new radiation scheme (see Section \ref{sec:radiation}), with the default present day Earth setup we can simulate approximately 100 years in 48 hours of wall-clock time using 44 cores on the same cluster. The parameterized physics in Planet 1.0{} is largely the same as that in ModelE2{}, but several changes that were made after \citet{Schmidt2014} to correct ocean and radiation physics errors have been adopted for Planet 1.0{}. \subsection{Ocean Models}\label{subsec:oceanmodel} The oceans are crucial to the accurate 4-D portrayal of a planet's climate system. Energy, moisture and momentum are exchanged between the atmosphere and oceans, and the transitions between different phases of water drive some of the most significant feedback mechanisms operating in the climate system. The oceans provide the major source of moisture that drives the hydrological cycle, while the freezing and melting of surface waters have a major impact on planetary albedo. Together with the transport of heat, these atmosphere-ocean interactions affect the geographic, seasonal, inter-annual and even geologic-scale variations of a planet's climate. In Planet 1.0{} the oceans differ from other bodies of water (lakes, rivers) in that salinity and temperature combine to alter the 3-D density structure, while surface wind stress is allowed to impact movement of water in the upper ocean. Salinity, temperature, and wind stress drive global ocean currents that transport energy on time scales that may exceed the orbital period of the planet by orders of magnitude. Ocean albedo is a function of both water and sea foam reflectance. Water albedo is calculated as a function of the solar zenith angle and wind speed; the sea foam reflectance is derived from \cite{Frouin1996} Planet 1.0{} allows for 3 different modes of ocean interaction. From simplest to most complex these are 1) specified sea surface temperature (SST), 2) thermodynamic upper ocean mixed-layer, and 3) coupled dynamic ocean GCM. \subsubsection{Specified Ocean Surface Conditions}\label{subsubsec:specified-ocean} Specifying sea surface temperature (SST), including sea ice cover, is a common Earth climate modeling technique where SST observations are used as a surface boundary condition over a range of years or months to force an atmospheric GCM (AGCM). The GISS model uses twelve monthly arrays that define the ocean surface temperature and sea ice distributions. The model interpolates the input into daily values, providing smoother transitions through an annual cycle. Specifying SSTs is the most commonly accepted technique for evaluating the efficacy of AGCM physics parameterizations when surface conditions are well-known (e.g., in performing hindcasts of 20th Century climate). It is also used in Earth paleoclimate studies where proxy data can be used to reconstruct past ocean temperature distributions \citep[e.g.][]{MARGO2009}. In this case the purpose is generally to evaluate the consistency of land-based and ocean-based observations or simply to examine potential states of the atmosphere for various time periods in Earth history. Specified SST simulations are also used to collect the atmosphere-ocean flux information to generate the Q-fluxes to run the model in mixed-layer ocean mode. \subsubsection{Mixed-Layer (Q-flux) Ocean Model}\label{subsubsec:qflux-ocean} For other planets, prescribed SSTs are not an option and SSTs must instead be calculated interactively to be consistent with a given planet's atmosphere and external forcing. The simplest way to do this is to couple the AGCM to a simple thermodynamically active layer that represents the upper well-mixed layer of the ocean (typically tens to hundreds of meters deep). The temperature of the mixed layer responds to radiative and turbulent (sensible and latent) fluxes of heat across the ocean-atmosphere and ocean-sea ice interfaces. This approach has been the default choice for most exoplanet GCM studies to date \citep[e.g.][]{Yang2014,Shields2014,Kopparapu2016,Turbet2016}. In the literature this approach is typically referred to as a "thermodynamic," "mixed layer," "slab," or "immobile" ocean model. The greatest limitations of this method are that it neglects horizontal heat transport by ocean currents and cannot account for deep water formation related to vertical density gradients. For Earth, where SST observations exist, a variant of the mixed layer approach known as the ``q-flux'' method has been commonly applied to simulations of future climates \citep{Miller1983,Russell1985}. In the Q-flux approach, a control AGCM run with prescribed SSTs is first conducted to define the radiative and turbulent heat exchanges at the atmosphere-ocean interface that are consistent with the AGCM's physics parameterizations. The implied horizontal ocean heat transport convergences that would be required to produce the observed SSTs and sea ice cover in each mixed layer gridbox are then calculated and applied in a second simulation that couples a mixed layer ocean model to an AGCM as a proxy for the effect of actual ocean heat transports. Sometimes diffusive heat loss through the lower boundary of the mixed layer is also included to mimic exchanges of heat with deeper ocean layers that are otherwise unrepresented in such models. The implied ocean heat transport convergences are themselves fixed, but their presence allows for a more realistic projection of sea ice changes, and thus ice-albedo feedback, in a changing climate than is possible in a model that completely ignores ocean heat transport. Such models have traditionally been used to define the equilibrium sensitivity of Earth's climate to a doubling of CO$_{2}$ concentration, a common benchmark for assessing climate model uncertainty. The q-flux approach is also unavailable for exoplanet GCM studies, hence their use of purely thermodynamic ($\text{Q-flux} = 0$) oceans, and ROCKE-3D{} includes a $\text{Q-flux}=0$ ocean option, but the error induced by ignoring ocean heat transport must be kept in mind in assessing such studies. An alternative that has been used for sensitivity studies is to prescribe a latitudinal profile of ocean heat transport in a mixed layer model with the latitude and magnitude of the peak transport as free parameters that can be varied \cite[e.g.][]{Rose2015}. Furthermore, if an existing simulation with a dynamic ocean (see Section \ref{subsubsec:dynamic-ocean}) is available, the ocean heat transports from this model can in principle be used as a specified input to an otherwise thermodynamic ocean model \citep[e.g.][]{Fiorella09012017}. \subsubsection{Dynamic Coupled Ocean}\label{subsubsec:dynamic-ocean} Given the limitations of Q-flux models, recent generations of Earth climate models have instead coupled more computationally expensive but more realistic dynamic ocean GCMs (OGCM) to AGCMs to simulate climate change. Most exoplanet GCM studies have eschewed the use of OGCMs because of the large thermal inertia of the ocean and thus the long integration times required to reach equilibrium, but several studies have revealed the importance of interactive ocean heat transport to climates of planets in parameter settings very different from that of Earth \citep{Vallis-Farneti2009,Cullum2014}. The most dramatic example of ocean heat transport effects in the exoplanet context is the difference between the concentric ``eyeball Earth'' open ocean region simulated beneath the substellar point of a synchronously rotating aquaplanet with a thermodynamic ocean \citep{Pierrehumbert2011} and the asymmetric ``lobster'' ocean pattern produced when a dynamic ocean is used \citep{Hu2014}. The exploration of parameter space for salty-water-ocean composition differs from that for atmospheric composition in that the former has a more direct effect on density structure, circulation, and heat transport. The Earth's thermohaline circulation was recently placed into perspective by \cite{Cullum2016} who demonstrated that an increase in mean salinity can cause the haline component to dominate. Most ROCKE-3D simulations couple a dynamic ocean to the atmospheric model. The standard configuration uses a 4$\arcdeg\times5\arcdeg$ resolution with 13 ocean layers, which decreases model throughput by $\sim \SI{10}{\percent}$ or less compared to a thermodynamic ocean but increases the equilibration time of the climate from decades to centuries of simulated time, with the exact time depending on the assumed ocean depth. Some of our deep Earth paleoclimate studies instead use the same $\ang{1}\times \ang{1.25}$ resolution, 32 layer ocean that is used by ModelE2. Transport by unresolved mesoscale eddies is represented by a unified Redi/GM scheme \citep{Redi1982, Gent1990, Gent1995, Visbeck1997}, as in ModelE2{}. The version used by \cite{Schmidt2014} contained a miscalculation in the isopycnal slopes that led to spurious heat fluxes across the neutral surfaces, resulting in an ocean interior that was generally too warm and southern high latitudes that were too cold. A correction to resolve this problem was implemented for ModelE2{}, Earth paleoclimate studies \citep{Chandler2013}, and is also used by ROCKE-3D{}. The new code uses a mesoscale diffusivity of \SI{600}{\meter \squared \per \second}, although some ROCKE-3D exoplanet simulations have used a value of 1200 \SI{1200}{\meter \squared \per \second} instead. The applicability of mesoscale eddy parameterizations designed for Earth models has not yet been investigated for planets with different rotation rates and thus different dominant spatial scales of eddies \citep{Cullum2014}. \section{Calendar changes for modeling other planets} \label{sec:calendar} ModelE2{} uses a clock and calendar to coordinate model operations that are not active during every time step and to manage binning/averaging for seasonal and higher-frequency diagnostics. Prior to the development of Planet 1.0{}, this system made assumptions that were incorrect or inconvenient outside the context of modern Earth. For instance, the number of days per month was hardwired for a quasi-Julian 365 day calendar. The system did permit varying the rotational and orbital periods as well as other orbital parameters (obliquity, eccentricity, and solar longitude), but provided only limited means to relate these to seasons. Further, a number of model components possessed implicit (hardwired) constants appropriate to the lengths of modern Earth day and year. To enable the study of exoplanets the calendar and indeed the entire time-management system in ModelE2{} have been been redesigned to be extensible and highly encapsulated. The latter was crucial to reduce the likelihood of accidentally reintroducing assumptions about modern Earth into the model by subsequent developers. The design of this new time management system reflects the needs and priorities of climate scientists in several respects. The first priority was to ensure that the default behavior replicates the original behavior for modern day Earth-based simulations. The other priority was for the new calendar to preserve, as much as possible, correspondence between planetary seasons, months, and days with that of Earth in terms of basic orbital characteristics. Note that other communities have designed planetary calendars (primarily for Mars) with quite different priorities such as preserving the number of days per month and the number of seconds per hour \citep{Allison1997, Allison2000, Gangale1986, Gangale1997, Gangale2005}. Here the priority is to simplify interpretation of seasonal and diurnal diagnostics, and is similar to the approach in \cite{Richardson2007}. In particular, the new calendar system preserves the intuitive notion of the diurnal cycle being divided into 24 equal ``hours'' as well as the seasonal cycle being divided into 12 ``months.'' Note that a model ``hour'' will therefore not generally be 3600 seconds in duration, and months can be significantly longer or shorter than 30 days. Additional machinery minimally tweaks the orbital period and model timestep to ensure that the simulation has an integral number of time steps per ``day'' and an integral number of days per year. All times and time intervals are expressed using exact integer arithmetic to eliminate issues related to numerical roundoff. We thus guarantee an exact number of simulation time-steps per day and an exact number of days per year. The specific duration of each calendar month is derived as follows. First, the solar longitude $\phi_i$, where $i=1,2,\dotsc,12$ is computed for the beginning of each month in a reference Earth orbit and calendar. The beginning of each month in the planetary calendar is then determined to have the same solar longitude angle as for the reference month, subject to rounding to ensure an integral number of days in each month. To relate the longitudes to times/durations, the corresponding mean anomaly $M_i$ is computed for the planetary orbit for the start of each month. $M_i$ can be derived from the solar longitude by standard Keplerian orbit formulae. The starting day-of-year $d_i$ for each month is then computed by scaling the delta mean anomaly ($M_i - M_1)$ by the number of calendar days per radian and rounding to the nearest day: \begin{equation} d_i = 1 + \lfloor (M_i - M_1) \frac{ N_d^{\mbox{cal}}}{2 \pi} + \frac{1}{2}\rfloor \end{equation} By default, the system uses the model's standard Earth-based orbit and pseudo-Julian calendar as the reference. Thus, the planetary ``February'' will tend to be shorter than average simply due to the short duration of February in the conventional Earth calendar. Our basic design is to have the system derive an appropriate calendar directly from the orbital parameters of a given planet. By introducing software abstractions for both the orbit and the calendar, the system provides a natural mechanism for further extension. For example, researchers could easily introduce a leap day system for their favorite exoplanet by creating a new Fortran module and adding a control hook in the model initialization. This approach was quite useful as requests for extensions to the basic planetary calendar arose almost immediately after deployment. There is a crucial aspect of Earth's orbit that is not particularly generic - a large separation of scale between days and years such that the number of days per year is much, much larger than 1. In terms of the conventional Julian/Gregorian calendars, this permits months to have an integral number of days while simultaneously having roughly uniform duration. It also allows climate models to safely ignore fractional remainders of days that lead to leap-years. However, for extreme orbits, a lack of this separation of scale can can have spectacular consequences. The number of days per year can be less than the number of months, and each day can be longer than a year (e.g., modern Venus). In such cases, the default for our calendar is to break the correspondence between the calendar day and the solar day and constrain calendar to have at least 120 calendar days, i.e., at least 10 calendar days per month on average. The system has runtime switches that can eliminate this constraint, as well as the constraint that the rotational period is commensurate with the orbital period. The latter is crucial to differentiate an orbit such as that of modern Venus from a tidally locked orbit - both of which are of interest to ROCKE-3D{} modelers. Of course, one must exercise extreme caution when interpreting model diagnostics in such cases. Some months (and even some years!) may have 0 solar days. A quantity averaged over one season or even one year may be highly biased as parts of the planet remain entirely day or entirely night. For tidally-locked planets, it is convenient to have a mechanism to vary the longitude of the subsolar point. For example, \citet{Turbet2016} point out that for a synchronously rotating world the continents may be concentrated at either the substellar or anti-stellar point. This variation is supported in our framework by the ``hourAngleOffset'' parameter, which controls placement the continents for a synchronously rotating world at any angle with respect to the substellar point. This approach is much simpler than the equivalent shift of all boundary condition data (topography, etc.). Figure~\ref{fig:hadley} demonstrates that the model responds correctly to the calendar modifications for slowly rotating worlds as the Hadley cells are clearly broadened for the slowly rotating planet versus the rapidly (Earth day length) rotating one. The calendar has also been expanded to handle variable orbital eccentricities in time \citep{Way2017}. This would be useful in cases where a Jupiter like planet perturbs the orbital elements of a nearby smaller terrestrial planet \citep[e.g.][]{Georgakarakos2016}. \begin{figure} \centering \includegraphics[width=0.45\textwidth]{fig1a.eps} \includegraphics[width=0.45\textwidth]{fig1b.eps} \caption{Left: Pressure vs. latitude streamfunction of the mean meridional circulation of a planet with Earth's rotation period. Right: As in the left panel but for a planet with a rotation period 128 days longer than an Earth sidereal day. As expected for a slowly rotating world the Hadley cells are now much larger in latitudinal extent due to the decrease in the strength of the Coriolis force at these slow rotation rates. }\label{fig:hadley} \end{figure} \section{Physics Parameterizations} \label{sec:parameterizations} Physical processes that operate on scales smaller than those resolved by a GCM must be parameterized in terms of grid-resolved variables. This section discusses those which are necessary for ROCKE-3D{} and how they are accomplished. \subsection{Radiation} \label{sec:radiation} \subsubsection{The GISS radiation scheme} \label{subsec:radiation_giss} The radiation scheme in ModelE2{} was first implemented in \citet{Hansen1983}, with more detailed descriptions of the long-wave radiation scheme in \citet{Lacis1991} and \citet{Oinas2001}, and the short-wave scheme in \citet{Lacis1974}. Minor updates have been made to improve its accuracy \citep{Schmidt2006, Schmidt2014, Pincus2015}, but its overall structure and parameterizations remain unchanged. The long-wave radiation scheme uses a 33~$k$-interval $k$-distribution parameterization derived through Malkmus band models \citep{Lacis1991,Oinas2001}, with band model parameters derived by fitting Malkmus band model transmissions to line-by-line transmissions over a range of absorber amounts. Resulting opacities are tabulated for 19 pressures between \SIlist{e-6;1}{\bar}, and 8 temperatures between \SIlist{181;342}{\kelvin}. The radiative transfer equation is solved using six streams without scattering (by setting the long-wave asymmetry parameter to unity). Long-wave scattering effects are included via a parameterized correction to the top cloud emission and outgoing flux, and a slight enhancement of downwelling radiation from cloud bottom. Recently updates have been made to the long-wave radiation scheme to improve its accuracy for atmospheres that deviate slightly from that of the present day Earth. The tabulated Planck function has been extended to \SI{800}{\kelvin}, and the gas optical depth table has been updated to enable the major greenhouse gases in the Earth's atmosphere (H$_2$O, CO$_2$ and O$_3$) to be replaced with other gases. The latter enables more accurate calculation of fluxes and heating for cases such as the Archean Earth, which had no O$_3$ nor O$_2$, but may have had significantly larger amounts of both CO$_2$ and CH$_4$ than present day Earth. These updates were recently used in the study of the early climate of Venus \citep{Way2016}. The short-wave radiation scheme uses the doubling and adding method to include the effects of multiple scattering \citep{Peebles1951,Hulst1963} with two quadrature points \citep{Lacis1974}. Gaseous absorption is parameterized through analytical expressions for the frequency-integrated absorption as a function of absorber amounts for each gas. The spectrum is divided into 16 gaseous absorption bands, each with one absorbing gas with a corresponding analytical function for the optical depth as a function of pressure, temperature and absorber amount. Stellar radiation input to the GCM drives both the planetary energy balance and photochemistry. Stellar spectral irradiance (\SIrange{0.115}{100}{\micro \meter}) to the top-of-the-atmosphere is provided to the model via an input file that can be changed for different stars, to drive the energy balance and to provide UV fluxes for ozone calculations and photolysis rates. A software utility provided by GISS can be used to format high-resolution stellar spectra for input to the GCM (see Appendix~\ref{subsec:GCMInputs}). The various modules of the GCM that utilize this spectral irradiance perform different spectral partitioning to suit their functions, such as for surface albedo, and for photosynthesis by plants and phytoplankton. Some solar spectral radiation assumptions are still hard-coded into the model, such as the broadband absorbance of water, so users should consult GISS personnel when interpreting results with alternative stellar spectra. More details are provided below in Section \ref{subsec:Cryosphere} on the Cryosphere. We note that for this radiation scheme to be reasonably accurate, gas concentrations of radiatively active gases, and H$_2$O, CO$_2$ and O$_3$ in particular, should be within a factor of 10 of present day Earth values throughout the atmosphere. In addition, the short-wave radiation scheme should only be used with stellar spectra that are of the same spectral type as the Sun. \subsubsection{SOCRATES}\label{subsec:radiation_socrates} In ROCKE-3D{} we require a radiation scheme that can be applied to a wide variety of planetary atmospheres. Consequently, the ability to easily change spectral bands, extend the pressure and temperature range of opacity tables, and add and remove absorbers are imperative. Unfortunately, the parametrizations used by the radiation scheme in ModelE2{} prohibit such a generalization. To ease adaptation of ROCKE-3D{} to different atmospheres we have coupled it to the Suite of Community Radiative Transfer codes based on Edwards and Slingo\footnote{\url{http://code.metoffice.gov.uk/trac/socrates}} \citep[SOCRATES,][]{Edwards1996a,Edwards1996b}. This radiation scheme is in operational use in the UK Met Office Unified Model, has previously been adapted to hot Jupiters \citep{Amundsen2014,Amundsen2016a}, and is available under a BSD 3-clause licence\footnote{\url{https://opensource.org/licenses/BSD-3-Clause}}. Importantly, SOCRATES allows for changing radiation bands, altering pressures and temperatures in the opacity tables, and the inclusion of various combinations of gaseous absorbers with relative ease. SOCRATES solves the two-stream approximated radiative transfer equation with multiple scattering for both the short-wave and long-wave components. Several different two-stream approximations are available, but by default we use the practical improved flux method version from \citet{Zdunkowski1985} with a diffusivity $D = 1.66$ for the long-wave component and the original version of \citet{Zdunkowski1980}, which uses a diffusivity $D = 2$, for the short-wave component. We note that, unlike the two-stream equations presented in \citet{Toon1989}, the two-stream equations of \citet{Zdunkowski1985} can be applied with a variable diffusivity, enabling improved accuracy compared to the \citet{Toon1989} formulation. In order to improve the representation of the scattering phase functions with strong forward-scattering peaks delta-rescaling \citep{Thomas2002} is applied for both components. Gaseous absorption is parameterized using the correlated-$k$ method \citep{Lacis1991,Goody1989}, with $k$-coefficients derived using exponential sum fitting of transmissions \citep{Wiscombe1977}, tabulated as a function of pressure and temperature. We use the HITRAN 2012 line list \citep{Rothman2013} to calculate cross sections line-by-line using Voigt profiles and the CAVIAR water vapour continuum~\citep{Ptashnik2011}. For planets with Earth-like atmospheres orbiting Sun-like stars we use 9 long-wave and 6 short-wave bands, those used by the UK Met Office for global atmosphere configuration 7.0 \citep[GA7.0,][]{Walters2017}, given in Tables \ref{tab:long-wave} and \ref{tab:short-wave}, and tabulate $k$-coefficients on 51 pressures equally spaced in $\log P$ between \SIlist{e-5;1}{\bar}, and 13 temperatures spaced linearly in temperature between \SIlist{100;400}{\kelvin}. The bands in Tables \ref{tab:long-wave} and \ref{tab:short-wave} will need to be changed in order to improve accuracy for atmospheres with significantly different compositions or stellar irradiation spectra, see e.g. \citet{Fujii2017} where 29 short-wave bands were used in order to accurately handle absorption of stellar radiation by water vapor at near-IR wavelengths for large specific humidities. Additional physics will need to be added to treat atmospheres with a large amount of CO$_2$ as the effects of CO$_2$ Rayleigh scattering, self-broadening, non-Voigtian line wings and continuum absorption are currently not supported. Overlapping gaseous absorption is treated using equivalent extinction \citep{Edwards1996b}, although random overlap \citep{Lacis1991} is also supported. Both of these methods combine $k$-coefficients calculated for each gas separately on-the-fly. Equivalent extinction relies on having a major absorber in each band, we use the adaptive equivalent extinction approach described in \citet{Amundsen2016b} to determine the major absorber in each band independently for each column, which may also change in time. Pre-mixing of opacities \citep{Goody1989}, where $k$-coefficients are derived directly for the gas mixture for a given composition, would result in a faster radiation scheme, however, it requires new $k$-tables to be derived when gas amounts are changed \citep{Amundsen2016b} \begin{table} \centering \caption{The long-wave bands adopted for planets with Earth-like atmospheres. These are the bands used by the UK Met Office for global atmosphere configuration 7.0 \citep[GA7.0,][]{Walters2017}. Note that bands 3 and 5 contain excluded regions.} \label{tab:long-wave} \begin{tabular}{|l|l|l|} \hline Long-wave band & Wavenumber [\si{\centi \meter^{-1}}] & Wavelength [\si{\micro \meter}] \\ \hline \hline 1 & \numrange{1}{400} & \numrange{25}{10000} \\ \hline 2 & \numrange{400}{550} & \numrange{18.18}{25} \\ \hline 3 & \numrange{550}{590} and \numrange{750}{800} & \numrange{12.5}{13.33} and \numrange{16.95}{18.18} \\ \hline 4 & \numrange{590}{750} & \numrange{13.33}{16.95} \\ \hline 5 & \numrange{800}{990} and \numrange{1120}{1200} & \numrange{8.33}{8.93} and \numrange{10.10}{12.5} \\ \hline 6 & \numrange{990}{1120} & \numrange{8.93}{10.10} \\ \hline 7 & \numrange{1200}{1330} & \numrange{7.52}{8.33} \\ \hline 8 & \numrange{1330}{1500} & \numrange{6.67}{7.52} \\ \hline 9 & \numrange{1500}{2995} & \numrange{3.34}{6.67} \\ \hline \end{tabular} \end{table} \begin{table} \centering \caption{The short-wave bands adopted for planets with Earth-like atmospheres orbiting Sun-like stars. These are the bands used by the UK Met Office for global atmosphere configuration 7.0 \citep[GA7.0,][]{Walters2017}.} \label{tab:short-wave} \begin{tabular}{|l|l|l|} \hline Short-wave band & Wavenumber [\si{\centi \meter^{-1}}] & Wavelength [\si{\nano \meter}] \\ \hline \hline 1 & \numrange{31250}{50000} & \numrange{200}{320} \\ \hline 2 & \numrange{19802}{31250} & \numrange{320}{505} \\ \hline 3 & \numrange{14493}{19802} & \numrange{505}{690} \\ \hline 4 & \numrange{8403}{14493} & \numrange{690}{1190} \\ \hline 5 & \numrange{4202}{8403} & \numrange{1190}{2380} \\ \hline 6 & \numrange{1000}{4202} & \numrange{2480}{10000} \\ \hline \end{tabular} \end{table} Rayleigh scattering by air is included, and we have also implemented a new Rayleigh scattering formulation that calculates the Rayleigh scattering coefficient consistently with the atmospheric composition in each layer. Water cloud optical properties are derived using Mie scattering, while the parametrization of ice crystals is described in \citet{Edwards2007} and is based on the representation of ice aggregates introduced by \citet{Baran2001}. Vertical cloud overlap is treated using the mixed maximum-random overlap assumption (clouds in adjacent layers overlap maximally, while clouds separated by one or more clear layers overlap randomly). In order to improve the accuracy of the calculated long-wave and short-wave fluxes, wavelengths are weighted internally in each band by the Planck function at \SI{250}{\kelvin} for the long-wave component and by the stellar spectrum for the short-wave component when deriving $k$-coefficients, aerosol and cloud optical properties. This is important as our bands are quite broad, particularly for the short-wave component, and the source function varies significantly within the bands. Consequently, changing the stellar spectrum involves computing new $k$-coefficients and cloud and aerosol optical properties for use in the calculation of short-wave fluxes. As stated in Section~\ref{sec:configurations}, with the GISS radiation scheme we are able to simulate 100 Earth years in approximately 24 hours of wall-clock time using 44 cores\footnote{These simulations use a single node/motherboard with two Intel Xeon E5-2697 v3 Haswell \SI{2.6}{\giga \hertz} each with 14 cores.} with a fully-coupled ocean at an atmosphere and ocean resolution of $\ang{4} \times \ang{5}$ with 40 atmospheric layers and 13 ocean layers. With SOCRATES, ROCKE-3D{} is significantly slower, and allows us to simulate approximately 100 Earth years in 48 hours of wall-clock time using the same number of cores. However, the speed of the radiation scheme decreases with increasing number of bands and absorbers, and will therefore depend on the set-up adopted for a particular planet. In summary, SOCRATES gives us greatly improved flexibility to model atmospheres with different composition and irradiation than present day Earth. However, due to the desire to keep the computation time as small as possible while at the same time calculating accurate fluxes and heating rates, some adaptation is needed for each planet and star. \subsection{Convection and Clouds}\label{subsec:Clouds} The cumulus parameterization in Planet 1.0{} uses a mass flux approach that requires both instability and a trigger based on the buoyancy of moist air lifted a finite distance to initiate convection \citep[version ``AR5'' in][]{DelGenio2015}. In this sense it is more resistant to convection than parameterizations in other planetary GCMs that require only instability to initiate convection \citep[e.g.][]{Song2013}. The mass flux scheme utilizes a cloud model that simulates the thermodynamic, dynamic and microphysical properties of air rising in convective updrafts. The depth of convection is determined by the distance the updraft penetrates above its level of neutral buoyancy before the diagnosed convective updraft speed goes to zero. The initial mass flux is calculated as that required to produce neutral buoyancy at cloud base, with entrainment increasing the mass flux at higher levels and detrainment decreasing the mass flux above the level of neutral buoyancy. Simultaneous subsidence of the grid scale environment that adiabatically warms and dries the gridbox to maintain subsaturated conditions, and convective downdrafts formed from negatively buoyant mixtures of updraft and environmental air, compensate the parameterized updraft mass flux. This approach differs from adjustment schemes that seek to maintain a specified (sometimes saturated) humidity profile and a moist adiabatic lapse rate. The differences in the mass flux and adjustment approaches may affect estimates of the inner edge of the habitable zone \citep{Wolf2015}. Entrainment of subsaturated environmental air limits convection depth, but the next generation of ROCKE-3D{} will include stronger entrainment that produces more realistic subseasonal variability and cools and dries the tropopause region relative to that in Planet 1.0{} \citep{DelGenio2016}. This may have consequences for estimates of water loss for warm planets. Likewise the Planet 1.0{} version transports condensed water upward too vigorously relative to that which will be in the next generation of ModelE2, although this makes little difference to reflected sunlight because these clouds are optically thick \citep{Elsaesser2016}. For ROCKE-3D{} we have relaxed a limit in the parent Earth ModelE2{} that restricts convection top pressures to $> \SI{50}{\hecto \pascal}$. Stratiform clouds in Planet 1.0{} have subgrid cloud fractions that are diagnosed from local relative humidity and stability (\citealt{DelGenio1996} and updates described in \citealt{Schmidt2006, Schmidt2014}). This differentiates our model from planetary GCMs that require a gridbox to saturate before a cloud forms that fills the gridbox. This is potentially important in estimates of the width of the habitable zone, because the most important cloud feedback (and the one that differs most widely among models) in terrestrial climate change simulations is due to changes in cloud fraction \citep{Zelinka2016}. Cloud water mixing ratios evolve prognostically based on simplified versions of microphysical processes that are not easily generalized to treat cloud processes on planets with different gravity or atmospheric pressure. The next generation model will include a more explicit 2-moment microphysics representation \citep{Gettelman2015} that can scale more easily to other planets. ROCKE-3D{} is adjusted to planetary radiation balance using free cloud parameters that regulate the onset of fractional cloudiness in the free troposphere and boundary layer, and the rate at which small cloud liquid and ice particles are converted to rain and snow that precipitate from the clouds. The specific values of these tuning parameters for Earth are chosen to produce reasonably accurate surface temperatures, but no such observational constraint yet exists for exoplanets, and multiple choices that can bring the model to balance at different temperatures are possible \citep[][see Figure 1]{Way2015}. Likewise, more exotic planet configurations (e.g., synchronously rotating, zero obliquity, etc.) may not come into balance at Earth free parameter settings and are therefore adjusted as needed within reasonable ranges. Only H$_{2}$O convection and clouds are represented in the baseline ROCKE-3D{} model. For the next generation version we will allow for the possibility of condensates such as CO$_2$ and CH$_4$ that are important on Mars and Titan, and on exoplanets near the outer edge of the habitable zone (see Section \ref{subsec:variableatmmass}). \subsection{Planetary Boundary Layer}\label{subsec:PBL} The planetary boundary layer (PBL) in Planet 1.0{} is described in \citet{Schmidt2006}. It is based on nonlocal transport of dry-conserved variables (virtual potential temperature and specific humidity). It includes a diagnosis of the turbulent kinetic energy profile based on large-eddy simulation studies and uses the resulting profile to define the PBL depth. Cloud top sources of turbulence are not included, although the effect of enhanced mixing at the top of cloudy boundary layers is estimated by the cloud parameterization. The next generation ROCKE-3D{} will incorporate a full moist turbulence scheme that transports liquid water potential temperature and total water mixing ratio and includes cloud-top radiative cooling as a source of turbulence. Boundary layer clouds have largely been absent from discussions of exoplanet habitability to date, but considering that they are the largest source of uncertainty in Earth's climate sensitivity \citep{Zelinka2016}, they warrant more attention in exoplanet studies. \subsection{Cryosphere}\label{subsec:Cryosphere} The cryosphere in ROCKE-3D{} –- encompassing areas of snow, land ice, and sea ice -– has not been significantly modified from the modern Earth version of the GCM \citep{Schmidt2006,Schmidt2014}, so hexagonal ice (ice Ih) is the only natural phase of water ice represented. This means that Planet 1.0{} is not yet capable of simulating the physical or spectral characteristics of water ices on worlds with very low surface temperatures (below 75K; e.g., ice XI), and/or ice under pressures of $\sim$200 MPa or more (e.g., ices II, III and IX) \citep{Bartels2012}. Snow may accumulate on any solid surface, including land ice and sea ice, as long as surface conditions are sufficiently cold. Total snow column depth is divided into two to three layers once the snow depth exceeds 0.15 m; as new snow is added to the uppermost layer, older snow is redistributed to the underlayers. Both heat and water are permitted to pass through the snow column and into the ground (soil) beneath. Areas with snow depths $\leq$ 0.1 m are considered to have only patchy snow cover. Also, snow cover over land depends on local topography \citep{Roesch2001} and is never allowed to exceed 95\% of the cell. If snow accumulates on top of either land or sea ice to a depth greater than one meter, the bottom of the snow layer is compacted to ice. Note that under cold global conditions snow mass may accumulate on land to such an extent that the mass of the ocean is noticeably reduced; however, this ocean mass reduction will not be detectable as a change in the global land/sea fraction. Land ice has the simplest treatment of the three cryosphere components in ROCKE-3D. Where land ice is distributed as an initial input to the GCM, it consists of two layers that may change thickness in response to mass balance changes (accumulation minus sublimation and melting) induced by snow or rain. However, Planet 1.0{} does not have dynamic land ice capabilities that would allow the footprint area or the defined elevation of an ice sheet to grow or shrink in response to forcings, or to affect ocean depth. A glacial melt parameterization permits the return of land ice mass lost as meltwater to the oceans, as well as calving of ``icebergs,'' into geographic-specific coastal ocean cells. Sea ice extent and thickness may be prescribed for simulations with a specified SST ocean model (Section \ref{subsubsec:specified-ocean}, or as an initial condition for simulations with mixed-layer oceans (Section \ref{subsubsec:qflux-ocean}) or dynamic oceans (Section \ref{subsubsec:dynamic-ocean}). For the latter two types of simulations, it is also allowed to develop as a consequence of other climate forcings on a world that initially has no sea ice. When sea ice is allowed to respond to other forcings, Planet 1.0{} uses the thermodynamic-dynamic sea ice formulation described in \cite{Schmidt2006,Schmidt2014} to control its formation and transport across the ocean surface. The formulation consists of four layers of variable thickness but fixed fractional height, each of which has prognostic mass, enthalpy, and salt content. Four sea ice surface types are included: bare ice, dry snow on ice, wet snow on ice, and melt ponds \citep{Ebert1993}. Melt pond mass accumulates as a fraction of surface runoff, decays on a time scale that depends on the presence or absence of current melting, and re-freezes when the temperature is below --10$\degr$C. Unlike the modern Earth version of the GCM, the sea ice thermodynamics in Planet 1.0{} do not yet include the effects of internal brine pocket formation \citep{Bitz1999,Schmidt2014}, which would improve energy conservation and result in thinner equilibrium ice thickness compared to non-energy-conserving ice models \citep{Bitz1999}; this capability will be introduced in a future release. Sea ice dynamics, especially important on synchronously rotating aquaplanets, is treated with a viscous-plastic formulation for the ice rheology that takes such factors as the Coriolis force, wind stress, ocean-ice stress, slope of the ocean surface, and internal ice pressure into account when calculating strain rates and viscosity for ice advection. Frazil ice (spicules or plates of new ice suspended in water) is allowed to form either under existing ice or in open ocean, as long as surface fluxes cool the water to the freezing point, given the local salinity; once formed, the frazil ice advects along with the previously existing sea ice. For a total sea ice thickness of five meters or less, leads (narrow linear fractures) are allowed to form as a result of shearing or divergent stresses. These leads can act as conduits for heat, moisture and gas fluxes from the ocean below. As a planet's climate (and ultimately, its detectability via remote observations) can be highly sensitive to the snow and ice albedo parameterizations used in a GCM, we highlight here the key aspects of Planet 1.0{}'s treatment of albedo in the cryosphere \citep[see also][]{Schmidt2006}. The albedo of any surface type is dependent on the zenith angle across all latitudes. The albedo of snow, whether it exists on bare soil, land ice, or sea ice, is also a function of age; on sea ice, whether snow is wet (in the presence of precipitation or melting) or dry, has an additional effect. Wet snow and aging snow are both less reflective than dry or new snow, respectively (see e.g. Table \ref{tab:table3}). The snow masking depth (i.e. the depth of snow needed to completely counter the albedo properties of the underlying surface type) depends on the underlying surface, though sea ice and land ice are generally considered masked if covered by 0.1 m of snow. The albedo values for sea ice are area-weighted averages for the different surface types, resolved in six spectral intervals (Table \ref{tab:table3}). Melt ponds, which significantly reduce sea ice albedo, are parameterized using a pond fraction and depth that varies as a function of melt pond mass. Bare ice albedo increases between assumed maximum and minimum values as the square root of ice thickness. \begin{figure} \centering \includegraphics[width=0.8\textwidth]{fig2.eps} \caption{Top row: Visible wavelength surface albedo map, spectrally integrated surface albedo map, and snow and ice cover map for an aquaplanet simulation of Proxima Centauri b using Planet 1.0 with the SOCRATES radiation scheme. Bottom row: Corresponding maps for Neoproterozoic Snowball Earth. Snow cover over sea ice or land produces the strongest surface albedo response in both simulations.} \label{fig:Albedos} \end{figure} Although the surface albedo is resolved spectrally into the six bands, which offers some sensitivity to different spectral irradiance, extinction of radiation with depth through snow, ice, and liquid water currently only distinguishes a "VIS" (290-690 nm) band and one "NIR" (690-1190 nm) band. The extinction for each medium assumes solar-type surface irradiance fractions in these bands and that radiation $>$1190 nm is not transmitted. Therefore, this solar assumption will later be revised to capture sensitivity to alternative stellar spectral irradiances. Land ice, where it is not covered by snow, is assumed to have a spectrally uniform albedo of 0.8. Land ice set as a boundary condition for non-modern Earth simulations may use a different albedo value as a default. Planet 1.0{} does not have the ability to change surface types (e.g., from ocean to land or land to ocean). It therefore cannot treat situations in which sea ice freezes to the ocean bottom along coastlines, or ocean mass decreases/sea level falls as snow accumulates on land, situations which can occur at high latitudes on low obliquity planets or for low instellations. To avoid this, for ROCKE-3D{} experiments, ocean bathymetry is deepened along coastlines when needed \citep[e.g.][]{Way2017}. \begin{table} \centering \caption{Surface albedos of various sea ice surface types in different spectral intervals.} \label{tab:table3} \begin{tabular}{|l|l|l|l|l|l|l|} \hline Surface Type& VIS (nm) & NIR1 (nm) & NIR2 (nm) & NIR3 (nm) & NIR4 (nm) & NIR5 (nm) \\ \hline &330-770 & 770-860 & 860-1250 & 1250-1500 & 1500-2200 & 2200-4000\\ \hline \hline Bare ice (min) & 0.05 & 0.05 & 0.05 & 0.050 & 0.05 & 0.03\\ \hline Bare ice (max) & 0.62 & 0.42 & 0.30 & 0.120 & 0.05 & 0.03\\ \hline Snow (wet) & 0.85 & 0.75 & 0.50 & 0.175 & 0.03 & 0.01\\ \hline Snow (dry) & 0.90 & 0.85 & 0.65 & 0.450 & 0.10 & 0.10\\ \hline Melt pond (min)& 0.10 & 0.05 & 0.05 & 0.050 & 0.05 & 0.03\\ \hline \end{tabular} \end{table} \subsection{Chemistry}\label{subsec:Chemistry} In simulating other planets, including early Earth, certain assumptions that are built into ModelE2{} can become invalid, so updated or new parameterizations need to be developed for ROCKE-3D{}. This is especially the case for reduced atmospheres like those of Archean Earth, Titan and probably Pluto. Currently ModelE2{} and ROCKE-3D{} are able to run with interactive gas phase chemistry and a number of different aerosol configurations, from simple bulk parameterizations to full aerosol microphysics calculations. Simulating ice and gas giant atmospheric chemistry is beyond the capabilities and scope of ROCKE-3D{}. The implementation of an automated solver of chemistry, which will essentially allow the simulation of any atmospheric composition regardless of its redox state, is under way. This involves the use of the kinetic pre-processor \citep[KPP;][]{Sandu2006}, which will replace the scheme described below, and is expected to gradually become available in ModelE2{} and ROCKE-3D{} in coming years. Its adoption will enable the use of alternate chemical schemes for Earth and planetary science applications, facilitating the easy update and upgrade of the chemical mechanisms currently in the model. The current chemical scheme in ModelE2{} only allows for calculations of O$_2$-bearing atmospheres and is strongly linked with the expected composition of the present-day atmosphere of Earth. The model uses the CBM-4 chemical mechanism \citep{Gery1989}, which explicitly resolves the inorganic chemistry that involves NO$_x$ and O$_3$, as well as the chemistry of methane and its oxidation products \citep{Shindell2001}. In addition, it resolves the chemistry of higher hydrocarbons via a highly parameterized scheme, based on CBM-4, with only minor changes \citep{Shindell2003}, and that of halogens in the stratosphere to account for the ozone hole \citep{Shindell2006}. The solution of the chemical system is facilitated by the use of chemical families, which assumes that dynamic equilibrium will be established among the species that are very closely related and interchange extremely fast, like the O$_x$ family species (O($^3$P), O($^1$D), O$_3$), the NO$_x$ family (NO and NO$_2$) and the HO$_x$ family (OH and HO$_2$), which allows the accurate solution of the system that includes species with lifetimes from sub-seconds to months or even years. The parameterizations of chemistry involve the solution of the chemical kinetics equations, which is in principle independent of conditions. However, some assumptions are made to make the solution of the partial differential equations less stiff, which should not be violated in a different atmospheric composition configuration. One of the most important assumptions is that molecular oxygen is always in excess, so reactions that involve it happen instantaneously. This is the case for the hydrogen radical and all alkyl radicals in the model: \ce{H + O2 -> HO2} \ce{CH3 + O2 -> CH3O2} \ce{R + O2 -> RO2} Where R is any alkyl radical with more than one carbon atom. These reactions are extremely fast \citep{Burkholder2015}, and the assumption that they dominate other competitive loss processes of H, CH$_3$ and R is valid for extremely low O$_2$ levels. For H, the competitive processes would be reactions with O$_3$ or HO$_2$, both of which will go down with reduced levels or O$_2$, while for the alkyl radicals the competitive processes would be reactions with atomic O. O$_3$ would also decrease in a low-O$_2$ atmosphere. Even without the assumption that the levels of the competitive oxidants will go down, the reaction of O$_2$ is still the dominant loss of these radicals for O$_2$ levels as low as 10$^{-6}$ or present atmospheric levels (PAL), based on their reaction rates alone \citep{Burkholder2015}. We performed ROCKE-3D{} simulations of present-day Earth under pre-industrial conditions (to minimize the impact of human activities on the atmospheric state) in which we varied the levels of atmospheric O$_2$ from 1 to 10$^{-6}$ of PAL, to study how chemistry will be impacted, with a focus on O$_3$. We did not allow radiation to be impacted directly by the O$_2$ changes, in order to study the chemical response alone, but the effects of the results in O$_3$ were included. The summary of the simulations is presented in Fig.~\ref{fig:O3summary}, which agrees very well with the results of \cite{KastingDonahue1979}. Interestingly, the calculated vertical profile of O$_3$ for different O$_2$ levels (Fig.~\ref{fig:O3profile}) agrees with that of \cite{KastingDonahue1979} only for O$_2$ levels down to 10$^{-3}$ PAL. The model calculates a collapse of the stratosphere for O$_2$ levels below that threshold because of the colder stratosphere that results from the decrease in O$_3$, while the 1D model of \cite{KastingDonahue1979} does not. \begin{figure} \centering \includegraphics[width=0.7\textwidth]{fig3.eps} \caption{Global mean O$_3$ column density as a function of O$_2$ concentration.} \label{fig:O3summary} \end{figure} \begin{figure} \centering \includegraphics[width=0.7\textwidth]{fig4.eps} \caption{Global mean O$_3$ column profile as a function of O$_2$ concentration.} \label{fig:O3profile} \end{figure} \subsection{Aerosols} Simulating aerosols prognostically in other planetary configurations is also possible with the GCM, with few modifications of the original scheme. For Earth applications, the model contains carbonaceous (primary and secondary organic, and black carbon) and non-carbonaceous (sulfate, ammonium, nitrate, sea salt, and dust) aerosols. The carbonaceous aerosols can be formed either by direct emission in the atmosphere or by the oxidation of precursor volatile organic compounds. In an O$_2$-rich atmosphere, organic hazes like those of the Archean, Titan and Pluto cannot be simulated in Planet 1.0{}. This is a limitation of the gas phase chemistry of the model which cannot calculate the photochemical formation of condensables in a reduced atmosphere, rather than a limitation of the aerosol scheme. Methane is not able to form aerosols in oxidizing environments, so unless there is life to form higher hydrocarbons (organic aerosol precursors) or any combustible carbonaceous material which can inject organic and black carbon particles in the atmosphere via burning, the carbonaceous aerosols are not needed in non-Earth planetary configurations where O$_2$ is present. Non-carbonaceous particles are present on both Venus (sulfate aerosols, a SO$_2$ oxidation product) and Mars (dust). Any planet with active volcanism is expected to have some level of sulfate aerosols in their atmosphere, while any planet with erodible bare rock is expected to have dust. In addition, any planet with surface saline water and wave breaking is expected to have sea salt aerosols injected into the atmosphere. During most of Earth's history there were salty oceans covering parts of the planet, and the presence of an atmosphere ensures that waves would form, so the presence of sea salt aerosols should be considered ubiquitous from very early on. The GCM can interactively calculate sea salt aerosol sources in the atmosphere using a variety of parameterizations \citep{Tsigaridis2013}; the default ModelE2{} scheme is that of \cite{Gong2003} which is a function of ocean salinity and surface wind speed over the oceanic grid cells. A parameterization that takes into account sea surface temperature is also available \citep{Jaegle2011}, but it is tuned towards present-day Earth conditions, since there are no physical constraints on the process. Sea salt aerosols are able to run as a standalone component in the model, without requiring the presence of other aerosols, which could save significant computational resources in simulating ocean worlds. As with sea salt, dust can be calculated interactively in ModelE2{} \citep{Miller2006}. The source function depends on surface type and orography, as well as wind speed. Topographic depressions tend to be good sources of dust, contrary to mountain tops and steep slopes. For experimental unpublished ROCKE-3D{} simulations of dust on Mars, we used MOLA\footnote{http://pds-geosciences.wustl.edu/missions/mgs/mola.html} topography data to construct a map of preferred dust sources based on the topography of the planet, similar to what \cite{Ginoux2001} did for Earth. The fraction of dust available for wind erosion implies that valleys and depressions have accumulated dust, compared to flat basins where dust is more homogeneously distributed. This is represented by calculating the probability to have accumulated sediments, S$_i$, in a $1\degr\times1\degr$ resolution, as a function of the minimum (z$_{min}$) and maximum (z$_{max}$) elevations of the surrounding $10\degr\times10\degr$ topography of the grid box $i$, which has an elevation of z$_i$: \[ S_{i}=\Big(\frac{z_{max}-z_{i}}{z_{max}-z_{min}}\Big)^5 \] The calculated accumulated sediment probability is shown in Fig.~\ref{fig:mars_sediment}. \begin{figure} \centering \includegraphics[width=0.7\textwidth]{fig5.eps} \caption{Calculated accumulated sediment probability.} \label{fig:mars_sediment} \end{figure} Active volcanism is another way to form aerosols in the atmosphere of the planet. Volcanic eruptions inject large amounts of ash and SO$_2$ into the atmosphere, among other constituents. Ash, which we are not yet able to simulate in the model, is absorbing and the particles are usually large and thus have too short a lifetime to be globally important, but SO$_2$ can form sulfate particles in an oxidizing atmosphere, like those of Earth, Venus, or Mars. Although the model is able to simulate both the formation of sulfate from SO$_2$ and the lifetime of sulfate particles in the atmosphere, the sources of SO$_2$ from active volcanism on other planets are virtually unknown, making its interactive simulation difficult. The sulfur cycle on Mars will be studied in the future. \section{Geophysical properties} \label{sec:properties} \subsection{Land/Ocean Distribution and Topographic Relief} The land/ocean mask used by the GCM can be defined using a fractional or non-fractional method, with the former preferred at coarse resolutions when shorelines are irregular and where ocean gateways may have significant climate impacts. A fractional land mask scheme signifies that an individual grid cell can be defined not only as \SI{100}{\percent} land or \SI{100}{\percent} ocean, but also as some percentage of each. This means that coastal grid cells are treated by other routines in the model as some portion ocean and some portion land. Topographic relief then is a weighted average based on the elevation of the land fraction and zero for the ocean fraction of the cell. Available input data sets for paleoclimate and other planets are described in Appendix \ref{subsec:GCMInputs}, and users may create their own. \subsection{Continental Drainage (Runoff)} Riverflow and continental drainage redistributes freshwater via the water cycle and thus impacts soil moisture, which affects land temperatures and precipitation, and the ocean salinity distribution, which impacts ocean circulation. For simulations that use modern Earth land/ocean distributions, we use the same riverflow and drainage patterns as defined for modern Earth climate experiments. Drainage directions in the GCM for non-modern-Earth continental configurations must be assigned via a custom input file. We generate the new drainage patterns by examining the topographic elevation boundary condition array and, working inward from continental edges, we calculate the slope of each continental grid cell in eight directions (four sides, four corners). Runoff is then removed from each cell in the direction of maximum slope, tracing a route back to the coast. For coastal grid cells that have more than one border adjacent to an ocean grid cell, runoff crosses the coastal grid cell on the same trajectory as in the adjacent inland grid cell. Lakes may be treated as pre-defined static features, or be permitted to grow and shrink dynamically in response to rainfall. In dynamic mode, lakes may also develop in topographic lows, with drainage developing once the water level rises above the lowest edge of the lake basin. Where a drainage route does not already exist, excess lake water runs off by means of the local drainage patterns defined above. In ModelE2, glacial ice melts directly from the Greenland and East Antarctic ice sheets, and enters the surface ocean in prescribed cells wherever the edges of the ice sheets coincide with continental edges. However, this can be adjusted for a given topography or other needs by specifying the geographic locations where freshwater (from ice melt) is distributed back into the oceans. \subsection{Ground hydrology, albedo, and surface vegetation} Ground hydrology employs a 6-layer soil heat and water balance scheme \citep{abramopoulos1988,RosenzweigAbrampoulos1997}, and the approach for calculating underground runoff is described in \citet{aleinov2006}. The surface energy and water balance algorithm calculates heat and water content on an explicit numerical scheme in the soil layers and vegetation canopies (if present) to predict temperatures and saturation. In current implementation the total soil depth is 3.5~m with the boundary at the bottom impermeable to both heat and water. Surface spectral albedo is partitioned currently into the same 6 broad bands shown in Table \ref{tab:table3}: (\SIrange{300}{770}{\nano \meter}, \SIrange{770}{860}{\nano \meter}, \SIrange{860}{1250}{\nano \meter}, \SIrange{1250}{1500}{\nano \meter}, \SIrange{1500}{2200}{\nano \meter}, and \SIrange{2200}{4000}{\nano \meter}), in an area-weighted average for cover types including vegetation, bare soil (with regard to albedo, see below) and permanent ice. For questions regarding extrasolar planets, the ground hydrology boundary conditions that must be modified include soil texture and albedo maps for bare soil on a lifeless planet, or albedo influenced by vegetation. The land albedo is spectrally resolved in the same VIS and NIR bands as described in Table \ref{tab:table3}. The albedo can be calculated in 2 different ways, which requires different sets of input files: \begin{enumerate} \item The Lambertian albedo scheme from \citet{Matthews1984}, for which an input file gives grid fractional areas of land cover types, including vegetation types and bare soil. Bare dry soil albedo is specified as a combination of ``bright" and ``dark" soil of albedo 0.5 and 0.0, respectively, so that their area-weighted averages gives the soil albedo. Soil albedo is spectrally flat and is assumed to depend linearly on soil saturation, becoming twice lower for a completely saturated soil. This is the scheme used since 1984 through to \citet{Schmidt2014}. These input files are suitable for Earth vegetation and the Solar spectrum. If simulating Earth vegetation under other stars, users should revise the broadband albedos to account for different band irradiances from different stellar types. \item A zenith angle-dependent surface albedo scheme described in \citet{NiMeister2010881}. If vegetation cover is prescribed, then maps of vegetation cover, vegetation height, maximum leaf area index, and soil albedo are separate input files. When ecological dynamics are turned on vegetation cover does not need to be initialized, since the vegetation will grow and die according to climate interactions. The soil albedo map allows resolution of soil into the 6 spectral bands of Table \ref{tab:table3}. End member broad band optical properties should be calculated to take into account different stellar spectral types, as described in Appendix \ref{subsec:StellarSpectra}. \end{enumerate} Surface life, particularly photosynthetic life, can strongly influence a planet's surface properties like spectral albedo, as we know from the vegetation red-edge on Earth \citep{Tucker1976,Kiang2007a}. The Ent Terrestrial Biosphere (Ent TBM) is the Earth dynamic global vegetation model (DGVM) currently coupled to ModelE2{} \citep{Schmidt2014,Kim2015}. While it can be an interesting exercise to subject Earth vegetation\footnote{The Ent TBM can allow any number of user-defined plant functional types, and supports parameter sets for 13 Earth types.} with full ecological dynamics to conditions on another planet to see what survives, seasonality and physiological differences between plant types are based on close adaptations to the star-planet orbital configuration and climatic regimes, so it would be inappropriate to utilize the current Sun-Earth based plant functional types (PFTs) for extrasolar planets. As part of proposed work for ROCKE-3D, an Exoplanet Plant Functional Type (ExoPFT) is being introduced to provide a ``generic plant'' for simulations of alien vegetation influences on exoplanets. This ExoPFT will simply ``find the water'', i.e. provide surface life wherever the planet is habitable. This generic plant will be similar to C3 annual grasses currently in the Ent TBM, but will have easily modifiable physiological and optical properties to allow experimentation with the potential distribution of life over a planet's land surfaces, its impact on the surface energy balance and surface conductance, and its possible detectability. The ExoPFT will be a simple, non-woody, vascular plant with roots to access soil water that simulates the very basic influences of vegetation on climate: surface albedo and water vapor conductance. To ``find the water", the ExoPFT will be parameterized to emerge and senesce according to the presence of water, with broad climatological tolerance, and user-specified leaf spectral albedo to investigate effects on the climate of photosynthetic pigments adapted to alternative parent star spectral irradiance (e.g., adaptation behavior similar to that proposed by \citet{Tinetti2006} and \citet{Kiang2007b}. This ExoPFT will be built within the platform of the Ent TBM. The Ent TBM currently provides the vegetation biophysics and land carbon dynamics to ModelE2{} \citep{Schmidt2006,Schmidt2014}. The ExoPFT will utilize the EntTBM scheme for vegetation conductance of water vapor and CO$_2$, and leverage a new canopy radiative transfer model being added to the Ent TBM. In addition, the ExoPFT's phenology (timing of leaf-out and senescence) and growth scheme will introduce its water-seeking parameterization within the Ent TBM framework. Plant photosynthesis is sensitive to the atmospheric CO$_2$ surface concentration. Leaf conductance of water vapor, which is coupled with photosynthesis, is inversely proportional to surface CO$_2$ concentrations. These sensitivities are represented in the Ent TBM biophysics via the well-accepted \citet{Farquhar1982} photosynthesis model coupled with \citet{Ball1987} leaf stomatal conductance detailed in \citet{Kim2015}. This inverse relation to CO$_2$ is infeasible for an atmosphere with zero CO$_2$, which would not be realistic for a planet with photosynthesis. Numerically in the GCM the lowest CO$_2$ level recommended is 10 ppm. This is the CO$_2$ compensation point where photosynthesis and respiration just balance each other. This is typical for C4 photosynthesis, a type of photosynthetic carbon fixation pathway that enables uptake of CO$_2$ at lower atmospheric concentrations than the other common pathway known as C3 photosynthesis. Coupling to the atmosphere currently relies on roughness lengths determined by the ground hydrology scheme for the GCM grid cell scale. Scaling leaf conductance as well as optical properties to the canopy scale for the ExoPFT will be done with the new prognostic vegetation canopy radiative transfer scheme, the Analytical Clumped Two-Stream (ACTS) model \citep{NiMeister2010881,Yang2010895}. This model has recently been incorporated in the Ent TBM. The ACTS model depends on zenith angle, direct/diffuse partitioning of radiation, canopy structure,\footnote{The canopy structure includes time variation in leaf area index, canopy height stratification, and plant densities.} and end member spectral optical properties of foliage, soil, and snow. The prior canopy radiative transfer scheme described in \citet{Schmidt2006,Schmidt2014} relies on prescribed seasonal canopy albedos by vegetation type with fixed seasonal Leaf Area Index (LAI) \citep{Matthews1984} and is not a function of dynamic LAI, and therefore is not suitable for use with dynamically changing vegetation. End member optical properties are summarized into the same 6 broad bands used for the ground hydrology (see Table \ref{tab:table3}). Alteration of these band albedos must take into account the stellar spectral irradiance, particularly if otherwise investigating the same vegetation optical properties but with different parent stars. For example, the ACTS Earth vegetation end member broadband spectra (leaf reflectance and transmittance) are derived from convolving hyperspectral leaf data with a solar surface irradiance spectrum at 60 degrees zenith angle (approximating an average over the illuminated face of the planet) with a U.S. standard atmosphere. Ent TBM vegetation dynamics of phenology (seasonality) and growth have been tested at the site level for several Earth plant functional types \citep{Kim2015}. The ExoPFT phenology will be parameterized simply to leaf out and senesce with the availability of water, without other mortality and establishment drivers than water (i.e. insensitive to the plant's carbon reserves, since this balance is already poorly known for Earth plants). Ecological dynamics involving competition, fire disturbance, and establishment will not be necessary to drive vegetation cover change, since only one ExoPFT will represent vegetation, driven by water availability. \subsection{Variable Atmospheric Mass}\label{subsec:variableatmmass} Typically, the atmosphere contains one or more components that may condense/evaporate at the surface of the planet or within the atmosphere. One can distinguish three cases: (1) A dilute (small fraction of total atmospheric mass) condensable gas. This is the case for water vapor on modern Earth. (2) A single-component atmosphere that consists of a gas that condenses at typical temperatures and pressures. (3) A non-dilute (significant fraction of total atmospheric mass) condensable gas. In the first case changes in atmospheric mass and heat capacity due to condensation/evaporation can be neglected except in the cumulus parameterization, where the effects of water vapor and precipitation loading on parcel buoyancy are non-negligible. The processes at the surface in this case will typically be governed by turbulent diffusion fluxes. Modern Mars, where CO$_2$ accounts for most but not all of the atmospheric mass, is actually an example of case 3. For Planet 1.0{} we have taken the first steps toward creating a Mars GCM by ignoring the minor constituents and treating Mars as a pure CO$_2$ atmosphere, corresponding to case 2. In this case the change in the atmospheric mass over the seasonal cycle can be significant and cannot be neglected for calculating temperatures and pressure gradients. Also, the amount of condensable substance at the surface is abundant, so the process of condensation/sublimation is governed by the energy balance, rather than by the diffusion fluxes. In the remainder of this section we present the algorithm we use to model the condensation of a condensable single-component atmosphere at the planet's surface. The description of similar processes for a dilute condensable component in ModelE2{} can be found in \citet{Schmidt2014}. We assume that the condensate is stored in the upper soil layer(recall that ModelE2{} has 6 soil layers). We also assume that the formation of the condensate is controlled purely by energy balance and the matter is condensed or sublimated as needed to compensate for energy loss or gain by the upper soil layer. Once formed the condensate is assumed to stay at the condensation temperature $T_\textrm{cond}$, which depends on the atmospheric pressure $p_s$ at the planet's surface. This temperature is described by the Clausius-Clapeyron relation. For the case of CO$_2$ condensation on Mars it can be expressed approximately via \citet{Haberle1982}: \begin{equation} T_{\textrm{cond}}(p_s) = 149.2 + 6.48 \ln(0.135 \ p_s) \label{eq:T_cond} \end{equation} where $T_{\textrm{cond}}$ is in Kelvin and $p_s$ is in millibars. We define the latent heat of condensation $L_c$ as the amount of heat needed to melt a unit mass of condensate and bring it to surface air temperature $T_s$ \begin{equation} L_c(T_s,p_s) = L_{c0} + c_{pg} (T_s - T_0) - c_{pc} (T_{\textrm{cond}}(p_s) - T_0) \label{eq:L_c} \end{equation} where $c_{pg}$, $c_{pc}$ are the specific heat capacities of the condensable substance in gaseous and condensed form respectively. $L_{c0}$ is the latent heat of condensation at some fixed temperature $T_0$. For CO$_2$ condensation on Mars we use: \begin{align*} c_{pg} &= \SI{770.2}{\joule \per \kilo \gram \per \kelvin} \quad \text{\citep{Lange10}} \\ c_{pc} &= \SI{1070.7}{\joule \per \kilo \gram \per \kelvin} \quad \text{\citep{Giauque1937}} \\ L_{c0} &= \SI{5.902e5}{\joule \per \kilo \gram} \quad \text{\citep{Haberle1982}} \\ T_0 &= \SI{150.0}{\kelvin} \end{align*} The prognostic variable which defines the ground temperature and the amount of condensate stored in the first layer of soil is the amount of energy per unit area in this soil layer $H_1$. The quantity $H_1$ is defined with respect to some reference temperature $T_{\textrm{ref}}$, in a sense that the substance at the temperature $T_{\textrm{ref}}$ has energy zero. In our model we set $T_{\textrm{ref}} = 273.15$, since it helps in dealing with freezing/thawing of water in Earth simulations using ModelE2{}, but one can choose any reference temperature above the condensation point. The ground temperature $T_g$ can be obtained as \begin{equation} T_g = \max \left( \frac{H_1}{c_{\textrm{soil}} \Delta z_1} + T_{\textrm{ref}},\ T_{\textrm{cond}}(p_s) \right) \label{eq:T_g} \end{equation} where $c_{\textrm{soil}}$ is the volumetric specific heat capacity of soil and $\Delta z_1$ is the thickness of the upper soil layer. If \begin{equation} \frac{H_1}{c_{\textrm{soil}} \Delta z_1} + T_{\textrm{ref}} < T_{\textrm{cond}}(p_s) \label{eq:H} \end{equation} then a non-zero amount of condensate is present, and its mass per unit area can be computed as \begin{equation} m_{\textrm{cond}} = - \frac {H_1 - c_{\textrm{soil}} \Delta z_1 (T_{\textrm{cond}}(p_s) - T_{\textrm{ref}})} {L_c(T_s,p_s) -c_{pg} (T_{\textrm{cond}}(p_s) - T_{\textrm{ref}})} \label{eq:m_cond} \end{equation} Since we are dealing with a non-dilute case, the atmospheric pressure is affected by the formation of the condensate, which can be expressed as \begin{equation} \frac{d p_s}{d t} = - g \frac{d m_{\textrm{cond}}}{d t} \label{eq:dp_s_dt} \end{equation} where $g$ is the gravitational acceleration. The heat content $H_1$ is controlled by the energy balance at the surface \begin{equation} \frac{d H_1}{d t} = R_n - S - G + \frac{d m_{\textrm{cond}}}{d t} c_{pg} (T_s - T_{\textrm{ref}}) \label{eq:dH_1_dt} \end{equation} where $R_n$ is net absorbed radiation at the surface, $S$ is the sensible heat flux to the atmosphere, $G$ is the ground heat flux to the lower soil layers and the last term on the right-hand side is the energy flux due to the gain/loss of the substance from/to the atmosphere (which is assumed to be at temperature $T_s$). The algorithm described above is implemented as follows. At each time step $H_1$ is first updated according to Eq.~(\ref{eq:dH_1_dt}) with the assumption that there is no change in the amount of condensate and the condition in Eq.~(\ref{eq:H}) is checked. If true, the system of equations Eqs.~(\ref{eq:T_cond}) to (\ref{eq:dH_1_dt}) is solved iteratively to obtain the new values for $m_\textrm{cond}$, $T_g$, $p_s$. The change in the condensate $\Delta m_\textrm{cond}$ over the time step is then computed as \begin{equation} \Delta m_\textrm{cond} = m_\textrm{cond} - m_{\textrm{cond},0} \label{eq:delta_m_cond} \end{equation} where $m_{\textrm{cond},0}$ is the amount of condensate at the end of the previous time step. $\Delta m_\textrm{cond}$ is then subtracted from the mass of the condensable component of the lower atmosphere layer. The removed/added gas is assumed to be at $T_s$, so the temperature of the lower layer of the atmosphere is updated accordingly. If condition (\ref{eq:H}) is false then no condensate is present. If condensate was present at the previous time step, then the corresponding amount of gas should be added to the lower atmospheric layer and its temperature should be adjusted accordingly. Figure~\ref{fig:MarsPressure} shows the annual cycle of surface pressure on Mars at the location of the Viking 2 lander and that simulated with the surface condensation routine activated in a version of Planet 1.0{} that includes some but not all of the physics that affects Mars' climate (i.e. it uses the GISS radiation scheme, which has limitations in treating atmospheres with composition very different from Earth, it does not yet allow for CO$_2$ clouds, and it does not yet incorporate dust). Despite these limitations, the timing and amplitude of the seasonal variation \citep{SharmanRyan1980} are in reasonable qualitative agreement with observations. The site of the Viking 2 lander was chosen for comparison, because it is largely a flat area and can be well represented by a coarse-resolution GCM cell such as that used in this simulation. Most of the other landing sites have a more complicated terrain and would require higher horizontal resolution for such simulations, which is beyond the scope of our current experiments. In the description of the algorithm above (for simplicity's sake) we assume that only one (non-dilute) condensable component is present, but our model can also handle the presence of another (dilute) component. This is done by including the latent heat due to the dilute component in equations (\ref{eq:T_g}) to (\ref{eq:m_cond}) and including the dilute condensate heat capacity into $c_{\textrm{soil}}$. Otherwise the dilute component itself is treated as in ModelE2. The presence of both such components is necessary for a more representative Mars simulation where both dilute (water) and non-dilute (CO$_2$) condensable components are present. We note that Mars' atmosphere also contains several non-condensing minor constituents, e.g., N$_2$. These are not important for the dynamics, but do affect the ability of CO$_2$ to supersaturate and thus the occurrence of CO$_2$ cirrus clouds \citep{Colaprete2008}. This capability does not yet exist but will be added in future generations of ROCKE-3D. Currently, ROCKE-3D{} does not have the capability to treat case 3, i.e. condensable constituents that represent a significant and variable fraction of the mass of a multi-component atmosphere. This can become important as an Earth-like planet approaches the inner edge of the habitable zone where H$_{2}$O becomes a non-negligible part of the total atmospheric mass. This will in turn affect pressure gradients and the thermodynamic properties of air and will introduce non-ideal gas behavior. This feature will be added in a future generation of ROCKE-3D. \begin{figure} \centering \includegraphics[width=0.6\textwidth]{fig6.eps} \caption{Annual cycle of Mars surface pressure as measured by the Viking 2 lander (gray crosses) \citep{Hess1977,Tillman1989} and surface pressure simulated by ROCKE-3D{} (black solid line). }\label{fig:MarsPressure} \end{figure} \section{Enhancement to Earth System Modeling (ModelE2) as a result of ROCKE-3D} \label{sec:enhancement} Generalizations and extensions to ModelE2{} to accommodate the requirements of non-Earth planets can also benefit the Earth model through accelerated implementation of previously planned user-facing improvements to flexibility and accuracy. With a view to future development work and its multi-planet scope, this process also provides an opportunity for restructurings that enhance programmer-facing ``code quality.'' A visible example of all these trends is the reorganization of the time-management system, discussed in Section \ref{sec:calendar}. Other examples can be found in the modularization of the manner in which the features of a planet are specified by a user. ModelE2{} had previously required the presence of input files associated with all surface types (which is inconvenient for desert worlds and aquaplanets) and the time-space distribution of radiatively active constituents important for Earth but not for other planets (e.g. O$_{3}$). Ongoing effort to increase the flexibility in the specification of inputs and boundary conditions for Earth runs was extended to cover additional use cases. Improvements to ModelE2{} accuracy can sometimes result from running its modules under conditions sufficiently different than those for Earth to expose inappropriate approximations and/or coding errors. In the first category, the performance of the GISS Long Wave radiation scheme under conditions of extremely low column water vapor (e.g. the Arctic and Antarctic) was improved via better look-up tables generated in response to reports of problems in a cold and dry non-Earth simulation. In the second category, an aquaplanet simulation revealed some oversights in the ocean horizontal diffusion of momentum. Looking forward, an example of development planned for the Earth model that is also highly convenient for non-Earth simulation includes the option for dynamic surface-type masks due to factors including: sea level change, sea ice which has thickened to the ocean bottom, and expansion/retreat of glacial ice. While ``transient'' simulations of exoplanets in response to imposed time-varying forcings are not a likely near-term objective, and the trajectory followed by a model as it approaches equilibrium for a given set of imposed forcings is typically not of interest either, it is convenient to have a model find its equilibrium in a fully automated manner. A brute-force procedure requiring the user to try a sequence of prescribed land/sea distributions and associated inputs greatly slows the rate at which equilibria can be determined. Another advance that will benefit the Earth model is the use of the kinetic pre-processor \citep[KPP;][]{Sandu2006} for interactive chemistry calculations in ROCKE-3D{}. Its adoption will enable the use of alternate chemical schemes for both Earth and planetary applications, facilitating the easy update and upgrade of the chemical mechanisms currently included in the model. \section{Appropriate use of ROCKE-3D} \label{sec:use} \paragraph{Time scale:} As this is a GCM that simulates dynamics at time steps of \SI{450}{\second} and parameterized physics at time steps of \SI{30}{\minute} (and less in some submodules), it is best used for scientific questions investigating time slice equilibrium climate behavior at the scales of decades to centuries. The equilibrium time needed for ocean dynamics can take much longer (some simulations require thousands of years), but the climate characteristics are generally summarized over the last few decades of the run. In some rare instances simulations tracking secular changes over 1000s of years can be accommodated with this GCM (see \citealt{Way2017} for examples). Geological time scale phenomena over millions of years, such as the changes in the carbonate-silicate cycle, cannot be simulated by a GCM, but time slice atmospheric composition conditions or flux rates could be prescribed. \paragraph{Atmospheric escape:} The ROCKE-3D{} model top is at \SI{0.1}{\hecto \pascal} ($\sim \SI{65}{\kilo \meter}$ for Earth), with 17 layers in the 40 layer model above the tropopause cold trap for Earth-like planets. This is sufficient to resolve the stratospheric general circulation, which becomes important for planets orbiting M stars in which significant shortwave absorption by water vapor occurs at high altitude \citep{Fujii2017}. This altitude is however tens of kilometers below the homopause, where photodissociation of species such as H$_2$O and O$_2$ becomes important. Thus ROCKE-3D{} cannot directly simulate atmospheric escape processes; this would require coupling to upper atmospheric models specifically intended to simulate ionization and escape processes \citep[e.g.][]{Gronoff2011}. Furthermore, since ROCKE-3D{} (like all GCMs) can only simulate time slices of hundreds to thousands of years, it cannot be used directly to address problems of atmospheric evolution such as water loss in moist greenhouse states near the inner edge of the habitable zone. Instead, GCM stratospheric water vapor mixing ratios are traditionally compared to the threshold first estimated for 1-dimensional models by \citet{Kasting1993} to characterize planets that may be at risk of significant water loss \citep[e.g.][]{Kopparapu2016}. However, more sophisticated approaches \citep[e.g.][]{Wordsworth2013} may be feasible. \section{Discussion} \label{sec:discussion} The use of GCMs to study the climate and weather of other planets has increased dramatically in the past few years in response to increased interest in the past climates of terrestrial Solar System planets, the rapidly growing list of rocky and potentially habitable exoplanets, and the promise of more discoveries, as well as atmospheric characterization of exoplanets by upcoming and planned future spacecraft missions. Every GCM has specific strengths and weaknesses in its ability to simulate other planets and limitations in the range of problems to which it can be applied. The Earth climate modeling community has found that as a result, a diverse population of GCMs offers advantages over any single model by revealing robust behaviors that are common to all models and appear to be determined by fundamental well-understood physics, as well as features that differ among models due to differing assumptions in the parameterized physics that highlight more poorly understood processes. The advantages of ROCKE-3D{} relative to other planetary GCMs are that its physics is identical to the most recent published version of its parent Earth GCM, it will remain current with future generations of the Earth model, and its developers include a subset of the people who develop the Earth model. Thus it includes much in the way of recent thinking about climate processes that operate to determine Earth's changing climate, and its coding structure has been generalized to easily allow simulations in parameter settings appropriate to other planets without sacrificing process understanding. It will also be the first exoplanet GCM to represent basic functions of plants that should be generally applicable to any habitable planet (for mock observations based on GCM output, see Appendix \ref{sec:post-processing}). That having been said, ROCKE-3D{}'s Earth heritage produces limitations on its use as well. Some of these are structural and cannot easily be modified. The most obvious is that ROCKE-3D{} is based on a model that is designed to simulate only shallow atmospheres and oceans (i.e., much thinner than the planet radius) with equations of state appropriate to such fluids. Thus, ROCKE-3D{} can be applied to planet sizes up to the super-Earth range, though not to ``waterworld'' planets on which water is a significant fraction of the planet mass and a transition from water to ice at high pressure occurs. Likewise, it cannot be used to simulate or predict the transition from super-Earths to sub-Neptunes with thick H$_2$ envelopes, nor can it simulate giant exoplanets. Other limitations are specific to the Planet 1.0{} version of ROCKE-3D{} and will disappear as future generations of the model are developed. Planet 1.0{} has been applied thus far only to planets with atmospheres composed of constituents found on Earth at pressures equal to or less than that of Earth's atmosphere and temperatures not too far from those present during Earth's history, such as snowball Earth periods \citep{Sohl2015} and a hypothetical habitable ancient Venus \citep{Way2016}. With the SOCRATES radiation scheme, it is now sufficiently general to handle non-oxygenated atmospheres with prescribed elevated greenhouse gas concentrations such as Archean Earth, and Earth-like planets orbiting M-stars \citep{Fujii2017,DelGenio2017}. It has also been run under variable eccentricity \citep{Way2017} and rotation periods as slow as 256 days as well as synchronous rotation, and a baseline modern Mars model has also been created. Rotation periods less than Earth's are also possible, but require the higher horizontal resolution version of the model to accurately capture the dynamics. Development under way will give it the capability to simulate dense CO$_2$ atmospheres. In its current form the model cannot simulate atmospheres near the inner edge of the habitable zone, both because the radiation does not include information from high-temperature line lists and because the model does not treat the effects on atmospheric mass, thermodynamics and dynamics of water vapor concentrations that are a non-negligible fraction of the total atmospheric mass. Atmospheres with compositions fundamentally different from those mentioned above (e.g., H$_2$- dominated) are not yet available, although this is only a matter of developing appropriate radiation tables for such planets. Yet even in its current form ROCKE-3D{} is well suited to address a wide range of science questions about habitable and inhabited planets and should be a valuable tool for interpreting near-future spacecraft observations of planets both within and outside the Solar System and for supporting the planning of a possible future direct imaging exoplanet mission.
{ "redpajama_set_name": "RedPajamaArXiv" }
36
The 2023 Tour de France Femmes, (officially Tour de France Femmes avec Zwift), will be the second edition of the Tour de France Femmes, one of women's cycling's two grand tours. The race is scheduled for 23 to 30 July 2023. Route and stages In October 2022, the route was announced by race director Marion Rousse. The race will start in Clermont-Ferrand on the same day that the men's tour finishes in Paris, before heading south across the Massif Central towards the Pyrenees. The final stage will be an individual time trial in Pau, using a similar course to the 2019 edition of La Course by Le Tour de France. 2022 winner Annemiek van Vleuten called the route "an upgrade", with other riders welcoming the inclusion of bigger climbs and a time trial. As with the 2022 edition, the route will require a waiver from the Union Cycliste Internationale, as Women's WorldTour races have a maximum stage length of and a maximum race length of six days. Broadcasting As with the 2022 edition, live television coverage will be provided by France Télévisions in conjunction with the European Broadcasting Union. References External links Official website Tour de France Femmes Tour_de_France_Femmes Tour_de_France_Femmes_2023 Tour_de_France_Femmes 2023 in French sport Tour de France Femmes
{ "redpajama_set_name": "RedPajamaWikipedia" }
1,783
Ritsumeikan-UBC House is located near the red arrow on the map below. You can plot a second location below. Finding Your Way: Ritsumeikan-UBC House is located on the south side of Agronomy Road across from the University Services Building and west of the greenhouses. Detailed Directions: A road map and detailed directions for Ritsumeikan-UBC House can be found on Google. Use the search function below to find and highlight a second location with an orange arrow on the map above (the red arrow will indicate the first location, Ritsumeikan-UBC House).
{ "redpajama_set_name": "RedPajamaC4" }
5,331
Biotech (3 of …) A section of The Report on life sciences focusing on the biotechnology sector. Oh, just a reminder: the material posted about life science is a draft. More editing will occur before it's in final form. I welcome your input. The second category in the life sciences field with which most people are familiar is "biotechnology." If Big Pharma is the foundation of medicinal product development, biotech is the new kid on the block. It is primarily the product of techniques developed in the past 25 years from greater understanding of genetics and methods of manipulating complex molecules related to basic biologic functions: DNA, RNA, and proteins. To declare a class of biotechnology companies separate from Big Pharma is not to say that pharmaceutical companies are not trying to make biotech techniques work for them; they're spending billions on biologic techniques. But biotechs tend to be smaller, more specialized, and more focused on a particular biological technique to produce drugs and other biologic products. BIO, the Biotechnology Industry Organization, defines biotechnology as: "…a collection of technologies that capitalize on the attributes of cells, such as their manufacturing capabilities, and put biological molecules, such as DNA and proteins, to work for us." A somewhat broader definition is given in the US Department of Commerce's 2002 industry survey: "…biotechnology includes a diverse collection of technologies that manipulate cellular, sub-cellular, or molecular components in living things to make products, discover new knowledge about the molecular and genetic basis of life, or modify plants, animals and microorganisms to carry desired traits." The nice thing about this second definition is that it reminds us that biotech has a large role in supplying tools for the infrastructure of scientific research and that it has a big agricultural component. The boundary between pharmaceutical companies and biotechnology companies is fuzzy at best. The term, "biotech," is frequently used as shorthand to refer to nearly all the players in life science, including pharmaceuticals. Statistics and data about the life science industry often lumps the bigger and smaller companies together. That's pardonable; the labels are just convenient shorthand and have no "official" significance. One of the best sources for factoids about biotechnology is a October 2003 survey by the US Department of Commerce entitled "A Survey of the Use of Biotechnology in US Business." · Although 90% (917 firms) of survey respondents had 500 or fewer employees. Only 19 firms (2%) reported more than 15,000 employees, while 600 (58%) had fewer than 50. · …in 2001 they (biotechs) had more than 1.1 million employees, total annual net sales of about $567 billion, operating income of $100.5 billion, capital expenditures of $29.5 billion, and R&D expenditures of $ 41.6 billion. · In the last quarter of 2002, companies reported 33,131 pending (emphasis mine) applications for biotechnology products or processes, compared with 23,992 current portfolio patents. · Seventy percent of respondents were headquartered in ten states, with 26% located in California. Massachusetts, Maryland, Pennsylvania, North Carolina, and New Jersey also had notable concentrations of biotechnology firms. · Almost three-quarters of firms (72%) indicated that human health (HH) applications are their primary area of biotechnology-related activity. · Relatively few firms active in human health currently have approved and marketed products or processes (emphasis mine). The most common commercial product/process was diagnostic tests, a category cited by 11% of HH companies. · Fifty-six percent of respondents reported either no operating income or negative operating income in 2001(emphasis mine). · Growth in the biotechnology-related workforce has been vigorous, averaging 12.3% annually for those companies that provided data for 2000–2002. Companies with 50 to 499 employees experienced the fastest growth, with an annual increase of 17.3%, while growth among larger responding firms was 6.2%. These figures compare to essentially no growth in U.S. non-farm payroll employment during this period. · Firms reported that more than 66,000 employees could be classified as biotech-related technical workers. Scientists accounted for 55% of this total. Other occupations included science and clinical laboratory technicians (30%), engineers (8%), and R&D-focused computer specialists (6%). · The fastest growing biotech-related technical occupation was R&D-focused computer specialists, a category that grew at an annual rate of 21.8% during 2000–2002, adding 1,236 workers (emphasis mine). The data above point to some characteristics of the biotechnology area that I think bear noting to understand the peculiarities of this portion of the life sciences. Biotechs tend to be quite small. This is in part because so many are new business entities. But it's also because so many are start-ups by researchers out of academia or from other big companies who are pursuing a narrow, specific biological focus to bring a new medication, tool or technique out to market. Their smallness is an asset in the sense that it is now fairly accepted that large, highly-managed laboratories at the big pharmaceutical companies are not producing breakthrough work. Small research teams produce more new knowledge. On the other hand, small companies do not have the expertise or the resources to take their idea through regulation and out into the marketplace. The big companies do. So a symbiotic relationship between academia, biotechs and pharmaceuticals creates an ecosystem that evolves products toward the market. Sherman and Ross put it this way: At university laboratories, where serendipity is understood, creativity is valued, and researchers are not subject to corporate management. Moreover, these labs are more numerous than industrial labs, and remain the most productive source of genuinely new ideas. Small, single-minded biotechnology firms are best suited to the early development of NMES and biologics. As these firms become larger and more successful, they become turgid, less able to develop new ideas. And pharmaceutical companies are the organizations that can most effectively validate new research, shepherd novel drugs through the later stages of development, manage their regulation, and commercialize and market new therapeutics. To that end— and in the hope of a lucky break in discovery—it is reasonable for them to invest in large staffs of researchers. Many biotechs have no licensed products and no revenue. Yikes! They are flying by the seat of their pants. They live on VC money, angel investors, and optimism. They are obsessed with the ins and outs of funding cycles and exit strategies. Many just want to survive long enough to sell their partially developed product or expertise in the form of intellectual property (IP) to bigger firms. During the past two years I have interviewed people at a variety of start-ups and small biotech firms. During the recession many of them were hanging by a thread financially, and they expressed hope the American Cancer Society would be interested in investing. Though I explained we don't work that way, I thought it was unfortunate that some small companies with really cutting-edge ideas in cancer products were near closing down. I came to realize that, dirung a bad economy or when the VC "window" of investment in biotech is closed, cancer R&D suffers. Even though many biotechnology firms and start-ups are not on solid financial basis, they are a source of specialized employment that has a greater growth rate than nearly any other sector of the economy. No wonder nearly every state and community in the US has a local biotech industry promotion group. I'm not so sure, however, that the promoters understand what it's going to take to put those jobs on solid ground. The fastest growing job category in the biotech industry is "R&D-focused computer specialists." That statement points to the next section of this report and is an indicator that the biotech industry itself is undergoing a revolution of its own. Life science is information science and the parts of the industry focusing that way are emerging quickly. Next: The New, new biology Previous: Big Pharma (2 of…) Next: Doctors switching to cash-only payments? CivicX seeking new startups. Is it you? Innovators: Peter Newell of REI on Co-op Product Innovation innovators : Aswan Morgan, Jet's Head of Personalization
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
8,493
\section{Some specificities of chiral quark models} This work was done in collaboration with Wojciech Broniowski from Krakow. We consider chiral quark models which encompass three sectors. The vacuum and soliton sectors, which are treated in the mean-field (leading order in $N_c$) approximation, and the meson sector, which describes the (next to leading order in $N_c$) vibrations of the vacuum sector. Not all models are applicable to the three sectors. For example, constituent quark models, in which quarks interact with confining forces, cannot describe the vacuum sector, that is, the Dirac sea. However, they can and do describe the excited states of baryons, a thing which the chiral quark models cannot do (except, possibly, the $\Delta $) for lack of confinement. Chiral quark models (nor any of the other low energy quark models) have not been derived from QCD. The only serious attempt to derive them from QCD\ is the instanton gas model \cite{Diakonov86,Shuryak82}. In this approach, the chiral quark model is derived by calculating the propagation of quarks in a gas of instantons. A regularized effective theory results, as it should. It predicts both the value of the cut-off and the form of the regulator. The non-local regularization discussed here has the same form as the one derived from the instanton gas model. Unfortunately, the quark models derived from the instanton structure of the vacuum do not lead to quark or color confinement. This serious limitation serves as a reminder that we have not really succeeded in deriving low energy effective theories from QCD. Other so-called ``derivations'' of quark models from QCD involve more guesswork than derivation. Most telling is their inability to derive a regularized model. If infinities appear in an effective theory, one should seek the physical processes which prevent the infinities from occurring. Invoking the roughly $200$~MeV QCD cut-off is not a serious argument. Nor does QCD\ imply in any sense that the quark-quark interaction at low energy should be a one-gluon exchange with a modified gluon propagator. The regularizations used so far in the Nambu Jona-Lasinio type models for example (proper-time regularization being the most commonly used one so far), are nothing but renormalization techniques in which a finite cut-off is maintained. Not only is this arbitrary but such regularizations are flawed with problems. One might argue that the value of the cut-off should not matter. Indeed it would not if the effective theory consisted, for example, in eliminating some high energy degrees of freedom and using the remaining degrees of freedom to work out the dynamics of low energy phenomena. In such a case, one might expect the cut-off to be much larger than the inverse size of the composite particles and the results not to be sensitive to the cut-off. In chiral quark models, however, this is not the case. The cut-offs required to fit $f_\pi $ are about $700$~MeV, hardly larger than the $\rho $ or the nucleon mass. This is a fact of life, whether we like it or not. One can of course simply discard such models, but better models do not seem to be forthcoming. \section{The soliton in the non-local chiral quark model} The non-local chiral quark model is defined by the euclidean action: \begin{equation} I\left( q,q^{\dagger }\right) = \left\langle q\left| \partial _\tau +\frac{\vec{\alpha}.\vec{\nabla}}i +m\right| q\right\rangle -\frac{G^2}2\int d_4x\left( \left\langle q\left| r\right| x\right\rangle \beta \Gamma_a\left\langle x\left| r\right| q\right\rangle \right)^2 \;. \label{nonlocact} \end{equation} In this expression, $\Gamma _a=\left( 1,i\gamma _5\tau _a\right) $, $q\left(x\right) \equiv \left\langle x\left| q\right. \right\rangle $ is the quark field, and $r$ is a regulator. The regulator is assumed to be diagonal in momentum space and it has a range which defines an effective euclidean cut-off $\Lambda $. For example, we could take $\left\langle k\left|r\right| k^{\prime }\right\rangle = \delta _{k,k^{\prime }}r\left( k^2\right)$ with $r\left( k^2\right) =e^{-\frac{k^2}{2\Lambda ^2}}$, where $k$ is a euclidean 4-vector $k_\mu =\left( \omega ,\vec{k}\right) $ with $k^2=\omega^2+\vec{k}^2$. The interaction term of the action (\ref{nonlocact}) can be viewed as a contact 4-fermion interaction involving the \emph{delocalized quark fields}: \begin{equation} \psi \left( x\right) = \left\langle x\left| r\right| q\right\rangle = \int d_4y\,\left\langle x\left|r\right|y\right\rangle \,q\left(y\right)\;. \label{deloc} \end{equation} An action of the form (\ref{nonlocact}) is derived from the instanton gas model of the QCD vacuum \cite{Diakonov86,Shuryak82}, which predicts a cut-off function of the form: \begin{equation} r\left( k^2\right) =f\left( k\rho /2\right)\;, \quad \quad \quad f\left(z\right) = -z\frac d{dz}\left(I_0\left(z\right) K_0\left(z\right) -I_1\left(z\right) K_1\left(z\right)\right) \label{instanton} \end{equation} where $\rho $ is the instanton size. The the cut-off is determined by the inverse instanton size $\rho$. The form (\ref{instanton}) has $r\left(z=0\right) =1$ and $r\left( z\right) \stackunder{z\rightarrow \infty}{\rightarrow }\frac 9{2k^6\rho ^6}$. However, at large euclidean momenta $k$, the form (\ref{instanton}) is no longer valid and the cut-off function is dominated by one gluon exchange. It decreases as $\frac 1{k^2}$ (with possible logarithmic corrections) and not as $\frac 1{k^6}$. We find that the fall-off of the regulator at large euclidean $k^2$ does not affect the soliton properties very much. For this reason, we have felt free to use various simple forms of cut-off functions, such as a gaussian, which have an additional advantage in that they can be analytically (although arbitrarily) continued to negative values of $k^2$. We shall see below that the analytic continuation is required to include the valence orbit. Similar regularization has been used by the Manchester group \cite{Birse98} in the meson and vacuum sectors. Various regularization schemes are reviewed in chapter 6 of Ref.\cite{Ripka97}. The euclidean action allows us to calculate the partition function $Z=\int D\left( a\right) D\left( a^{\dagger }\right) e^{-I\left( a,a^{\dagger}\right) }$ and the ground state energy $E=-\frac \partial {\partial \beta}\ln Z.$ The partition function cannot be written in the form $Z=Tr\,e^{-\beta H}$ because the regulator in the action (\ref{nonlocact}) prevents us from defining a hamiltonian $H$. We are also unable to quantize the quark fields but we shall see that the baryon number is nonetheless properly quantized. We work with the equivalent bosonized form of the action: \begin{equation} I\left( \varphi \right) = -Tr\ln \left( \partial _\tau +\frac{\vec{\alpha}.\vec{\nabla}}i+\beta m +\beta r\varphi _a\Gamma _ar\right) +\frac 1{2G^2}\int d_4x\,\varphi _a^2\left( x\right) \label{isvs} \end{equation} in which case the partition function is given by the path integral $Z=\,\int D\left( \varphi \right) e^{-I\left( \varphi \right) }$. We refer to $\varphi _a\Gamma _a=S+i\gamma _5\tau _aP_a$, as the ``chiral field'' and we say that the chiral field is ``on the chiral circle'' if, for all $x$, we have $S^2\left( x\right) +P_a^2\left( x\right) =M_0^2$, where $M_0$ is an $x$-independent constant mass. We have calculated a localized and time independent stationary point of the action (\ref{isvs}), consisting of a chiral field with a hedgehog shape $S\left(r\right) +i\gamma _5\widehat{x}_a\widehat{\tau }_a P\left(r\right)$ \cite{Ripka98}. The shape of the fields and the soliton energy can be calculated in terms of the energies $e_\lambda \left( \omega \right) $ of the quark orbit. The ``Dirac hamiltonian'' is diagonal in the energy representation, although it remains energy dependent. The quark orbits $\left| \omega ,\lambda _\omega \right\rangle $ satisfy the equations : \begin{equation} \partial_\tau \left| \omega ,\lambda _\omega \right\rangle = i\omega \left|\omega ,\lambda _\omega \right\rangle \;, \quad \quad \quad \left(\frac{\vec{\alpha}.\vec{\nabla}}i+\beta m +\beta r\varphi_a\Gamma_ar\right) \left| \omega ,\lambda _\omega \right\rangle = e_\lambda \left(\omega\right) \left| \omega ,\lambda_\omega \right\rangle \;. \label{basis2} \end{equation} The energy of the soliton is: \begin{equation} E_{sol}=N_ce_{val}+\frac 1{2\pi }\int_{-\infty }^\infty \omega d\omega \,\sum_{\lambda _\omega }\frac{i+\frac{de_\lambda \left( \omega \right) } {d\omega }}{i\omega +e_\lambda \left( \omega \right) } +\frac 1{2G^2}\int d_3x\,\varphi _a^2\left( \vec{x}\right) -vac. \end{equation} where $-vac.$ means that we subtract the vacuum energy. In the vacuum, $P=0, $ $S=M_0$ and there is no valence orbit contribution $e_{val}$. The latter is discussed in the next section. \section{The quantization of the baryon number and the valence orbit} \label{sec:barnum} We calculate the baryon number from the Noether current associated to the gauge transformation $q\left(x\right) \rightarrow e^{-i\alpha\left(x\right)}q\left(x\right)$. It turns out to be: \begin{equation} B=-\frac 1{2\pi iN_c}\int_{-\infty }^\infty d\omega \, \sum_{\lambda _\omega}\frac{i+\frac{de_\lambda \left( \omega \right) } {d\omega }}{i\omega+e_\lambda \left( \omega \right) }\;. \label{number} \end{equation} The extra term $\frac{de_\lambda \left( \omega \right) }{d\omega }$ in the numerator arises from the fact that the regulator $r$ does not commute with $\alpha \left( x\right) .$ Its effect is to make the residues of all the poles of the quark propagator $\frac 1{i\omega +e_\lambda \left( \omega \right) }$ equal to unity. This effectively quantizes the baryon number in a manner which does not seem to be related to the topology of the hedgehog field.\footnote{% Nor is the soliton stabilized by the topology of the chiral field.} This is most fortunate because, a priori, there is no reason to expect a theory, in which we cannot quantize the quark field, to yield a properly quantized baryon number. The expression (\ref{number}) suggests a way to include the valence orbit so as to ensure that the baryon number of the soliton, relative to the vacuum, is equal to unity. We calculate ``on-shell'' pole of the quark propagator in the hedgehog background field by searching for a solution of the equation $\left. i\omega +e_\lambda \left( \omega \right) \right| _{\omega =ie_{val}}=0$. Because of the regulator, the solutions are scattered all over the complex $\omega $ plane. However, it is well known that, in the local theory, where we set $r=1 $, and for a hedgehog field with winding number unity, a well separated bound orbit with grand spin and parity $0^{+}$ occurs with energy $e_{val}$ close to zero \cite{Ripka84}. In the non-local theory, we find that a solution of the equation $\omega =ie_{val}\left( \omega \right) $ can always be found on the imaginary $\omega $ axis, close to the origin $\omega =0$, and that no other pole occurs in the vicinity. We therefore ensure that the soliton has a baryon number $B=1$ by deforming the integration path over $\omega $ in such a way as to include the contribution of this pole. This requires an analytic continuation of the regulator. Such a continuation is arbitrary but the analytic continuation does not extend as far from the origin as $e_{val}$. Indeed, since the soliton size is small, $\vec{k}^2>0$ is large and this, on the average, makes $k^2=-e_{val}^2+\vec{k}^2$ less negative. Unfortunately however, the form (\ref{instanton}) of the regulator, predicted in the instanton model, does not allow any analytic continuation whatsoever, thereby, strictly, prohibiting its use in the soliton calculation. \section{Results of self-consistent soliton calculations} The model parameters are the coupling constant $G$ appearing in the lagrangian, the cut-off $\Lambda $ appearing in the regulator and the current quark mass $m$. The values of the three parameters are constrained by fitting the pion decay constant $f_\pi =93$~MeV and the pion mass to $m_\pi =139$~MeV. The expression used to calculate the pion decay constant $f_\pi $ is: \begin{equation} f_\pi^2=2N_fN_cM_0^2\int \frac{d_4k}{\left( 2\pi \right) ^4} \frac{r_k^4-k^2r_k^2\frac{dr_k^2}{dk^2}+ k^4\left( \frac{dr_k^2}{dk^2}\right) ^2}{\left( k^2+r_k^2M_0^2\right)^2} \label{fpi} \end{equation} valid in the chiral limit $m\rightarrow 0$ and it is not identical to the Pagels-Stokar formula \cite{Pagels79}. This leaves one undetermined parameter which we choose to be the constituent quark mass $M_0$ at zero 4-momentum. The pion decay constant $f_\pi $ sets the scale. Grossly, soliton energies increase and soliton radii diminish as $f_\pi $ increases (see table \ref{golli5}). \begin{figure}[h] \centerline{\epsfig{file=fige.ps,width=120mm}} \vspace{10pt} \caption{The energy of the soliton [in MeV] (bold solid line), $N_c$ times the free-space quark mass (solid line) and the valence contribution to the soliton energy (dashed line) plotted as functions of the parameter $M_0$ [in MeV]. A Gaussian regulator is used; $\Lambda$ (dots) is fitted to $f_\pi=93$~MeV.} \label{fige} \end{figure} Figure \ref{fige} shows the soliton energy $E_{sol}$ as a function of the free parameter $M_0$. A soliton is a bound state of $N_c=3$ quarks which polarize the Dirac sea. With a gaussian regulator, it is formed if $M_0\gtrsim 276$~MeV, that is, for a sufficiently strong coupling constant $G\gtrsim 4.7\times 10^{-3}$~MeV$^{-1}$. The bound state occurs when the energy of the system is lower than the energy $N_cM_q$ of $N_c$ free constituent quarks in the vacuum: $E_{sol}<N_cM_q$. The mass $M_q$ is the on-shell constituent quark mass, obtained by searching for the pole of the quark propagator in the vacuum. It is the solution of the equation $\left. k^2+\left( r_k^2M_0+m\right) ^2\right| _{k^2=-M_q^2}=0$, which requires an analytic continuation of the regulator to negative values of $k^2$. Figure \ref{fige} also shows $N_cM_q$. At the critical value $M_0\approx 276$~MeV, the two curves merge. The contribution $N_ce_{val}$ of the valence orbit is also shown. At the critical value of $M_0$, the energy $e_{val}$ of the valence orbit, which is the on-shell mass of a quark propagating in the hedgehog field, becomes a well distinguished bound orbit. At $M_0\approx 309$~MeV, the curve displaying $N_cM_q$ on figure~\ref{fige} abruptly stops. Indeed, for larger values of $M_0$, the poles of the quark propagator no longer occur for real values of $k^2$. This means that quarks can no longer materialize on-shell in the vacuum. This feature is discussed in chapter 6 of Ref.\cite{Ripka97} and it has been considered by several authors as a sign of quark confinement \cite{Krewald92,Roberts94,Birse95}. In fact, when a pole of the quark propagator disappears from the real $k^2$ axis, it simply moves into the complex plane. Such poles indicate instability of the assumed vacuum state against the addition of a single quark. However, our calculation shows that, in the background soliton field, the on-shell valence orbit continues to exist and so does the soliton. Unfortunately, the regulator also introduces extra unwanted poles in the propagators of colorless mesons, so that the model does not express color confinement. Similar unwanted poles occur in proper-time regularization \cite {Ripka95}. Our ignorance as how to continue propagators in the complex $k^2$ plane reflects our ignorance of the confining mechanism \cite{Stingl90}. Apart from the solitons consisting of three valence quarks we find stable solitons consisting of a single valence quark in the background soliton field (see figure \ref{figes}) as well as of two valence quarks. Similar solutions have been found in the linear sigma model with valence quarks \cite{Golli97}. \begin{figure}[h] \centerline{\epsfig{file=figes.ps,width=110mm}} \vspace{10pt} \caption{The energy per quark [in MeV] for the soliton with three valence quarks (bold line), the soliton with one valence quark (dashed line) and the free-space quark mass $M_q$ plotted as functions of the parameter $M_0$ [in MeV].} \label{figes} \end{figure} Figure \ref{figmf} shows the scalar and pseudoscalar fields $S\left( x\right) /M_0$ and $P\left( x\right) /M_0$ of the soliton obtained with several values of $M_0$, together with the soliton quark density $\rho \left( x\right)$. Note that, within the soliton, the fields \emph{do not} lie on the chiral circle and $S^2\left( x\right) +P^2\left( x\right) <M_0^2$. Indeed, the pion component $P\left( x\right) $ never reaches the values $-M_0$. This is a new dynamical result. This is the only calculation, as far we know, in which one can check dynamically whether the chiral field remains or not on the chiral circle. It could not be checked in the renormalized linear sigma model, because close lying Landau poles occur which make the soliton unstable against high gradients in the fields \cite{Ripka87,Perry87}. It could also not be checked in local theories which use proper-time regularization because, in such theories, the soliton is unstable unless the fields are constrained to remain on the chiral circle \cite{Goeke92,Ripka93d}. No such instability occurs with the non-local regularization. The soliton we obtain with non-local regularization has a structure which lies midway between a Friedberg-Lee soliton \cite{Lee81,Wilets89} (in which the pion field has a vanishing classical value), and a Skyrmion \cite {Skyrme62,Holzwarth93} (in which the chiral field is constrained to remain on the chiral circle). This raises the problem of the collective rotational motion of the soliton. If the deformation in spin and isospin space is stable enough to sustain a rotation without significant distortion, then the $\Delta $ can be described as a rotation of the soliton and the $N-\Delta $ mass splitting can be estimated by cranking. If, however, the deformation is small, the $\Delta $ may be better described as a bound state of quarks with aligned spins and isospins. We have not tackled this problem yet. \begin{table}[h] \centering% \begin{tabular}{|c|c|c|c||c||c|c|c|c|c|} \hline $M_0$ & $\Lambda $ & $m$ & $\left\langle \bar{q}q\right\rangle ^{1/3}$ & $1/G $ & $e_{\mathrm{val}}$ & $E_{\mathrm{Dirac}}$ & $E_{\mathrm{sol}}$ & $\langle r^2\rangle ^{1/2}$ & $g_A$ \\ MeV & MeV & MeV & MeV & MeV & MeV & MeV & MeV & fm & \\ \hline 300 & 760 & 7.62 & $-215$ & 182 & 295 & 2360 & 1088 & 1.32 & 1.28 \\ 350 & 627 & 10.4 & $-200$ & 140 & 280 & 1715 & 1180 & 1.04 & 1.16 \\ 400 & 543 & 13.2 & $-185$ & 113 & 272 & 1433 & 1229 & 0.97 & 1.14 \\ 450 & 484 & 15.9 & $-173$ & 94 & 266 & 1275 & 1261 & 0.96 & 1.12 \\ \hline \end{tabular} \caption{Properties of self-consistent soliton solutions obtained with a gaussian regulator.\label{golli1}}% \end{table}% Table \ref{golli1} shows some properties of calculated solitons for various values of the mass parameter $M_0$. Rather good values of $g_A$ are obtained. The soliton mass and energies need to be corrected for spurious centre of mass motion (see table \ref{golli5}). The fields which describe the soliton break translational symmetry. The center of mass of the system is not at rest and it makes a spurious contribution both to the energy and to the mean square radius (more generally, to the form factor). This spurious contribution is not measured and it should be subtracted from the calculated values. The subtraction occurs at the next to leading order (in $N_c$) approximation. A rough estimate can be obtained from an oscillator model. If $N_c$ particles of mass $m$ move in a $1s$ state of a harmonic oscillator of frequency $\hbar\omega$, the centre of mass of the system is also in a $1s$ state and it contributes $\frac 34\hbar \omega =\left\langle P^2\right\rangle/2N_cm$ to the energy. We have therefore corrected the soliton energies by subtracting $\left\langle P^2\right\rangle/2E_{sol}$ from the calculated energy. Furthermore, in the oscillator model, the center of mass contributes a fraction $\frac 1{N_c}$ of the mean square radius, so that we have corrected the mean square radius by multiplying the calculated value by a factor equal to $\left( 1-\frac 1{N_c}\right) $. \begin{figure}[h] \centerline{\epsfig{file=figmf.ps,width=130mm}} \vspace{10pt} \caption{Self consistently determined fields and baryon densities ($4\pi r^2\rho$) for various values of $M_0$; a gaussian regulator is used.} \label{figmf} \end{figure} Table \ref{golli5} shows the result. The soliton energies and radii are then considerably closer to the experimental values observed in the nucleon. \begin{table}[h] \centering% \begin{tabular}{|c|c|c|c|c|} \hline $M_0$ & $E_{sol}$ & $\left\langle r^2\right\rangle _{sol}$ & $E_{corr}$ & $\left\langle r^2\right\rangle _{corr}$ \\ \hline \quad MeV\quad & \quad MeV\quad & \quad fm$^2$\quad & \quad MeV\quad & \quad fm$^2$\quad \\ \hline 300 & 1088 & 1.7 & 965 & 1.1 \\ 350 & 1180 & 1.08 & 990 & 0.72 \\ 400 & 1229 & 0.94 & 1000 & 0.62 \\ 450 & 1261 & 0.92 & 980 & 0.61 \\ \hline 450$^{*}$ & 1458 & 0.69 & 1200 & 0.43 \\ \hline \end{tabular} \caption{Elimination of spurious c.m. motion. Gaussian regulator, $\Lambda$ fitted to $f_\pi=93$~MeV; $^*$ $\Lambda $ fitted to $f_\pi =1.25\times 93$~MeV.\label{golli5}}% \end{table}% \section{Conclusion: why take the trouble?} The non-local regularization effectively cuts out of the quark propagators the 4-momenta which are larger than the cut-off. The non-local regularization makes the theory finite at all loop orders. The simpler proper-time and Pauli-Villars regularization schemes regularize the quark loop only and they require extra independent cut-offs when next to leading order meson loops are included. Both the real and the imaginary parts of the action are regularized, while the anomalous properties remain independent of the cut-off \cite{Cahill88,Holdom89,Ripka93}, and the baryon number remains properly quantized. In proper time and Pauli-Villars regularization schemes only the real part of the action is regularized and the imaginary part is left unregularized in order to enforce correct anomalous processes. Why not limit the 3-momenta of the quarks, thereby avoiding unwanted extra poles in the propagators? Breaking Lorentz covariance in the meson sector is annoying in that it requires to boost composite particles calculated in their rest frame.
{ "redpajama_set_name": "RedPajamaArXiv" }
6,649
\section{Introduction}\label{intro} Understanding the detonation mechanisms of energetic materials used in military \cite{Sikder2004} and mining \cite{Wharton2000} operations has been an active area of research for decades. While extensive studies have unraveled mechanisms of stored energy released in bulk energetic materials, \cite{Field1982,Tarver1997,Dremin2000,Ramaswamy2001,Cohen2007} initial dissociation mechanisms of isolated energetic molecules still constitute an active area of investigation.\cite{Jeilani2015,Zeng2016,Yuan2015,Yuan2016,Yuan2017} In energetic materials, excited electronic states and molecular ions are thought to drive initial energy release processes based on the observation of tribological luminescence.\cite{Zink1973,Lin1980} Thus, understanding relaxation and dissociation processes from excited states and ions of isolated energetic molecules is needed to fully understand initial excitation events in energetic materials, which may facilitate longstanding goals such as developing photoactive high explosives that can be initiated by lasers.\cite{Bowden2007} Because ultrafast events associated with the initial dissociation pathways of energetic molecules typically occur within a few picoseconds of the initial excitation,\cite{Dlott2003} time-resolved pump-probe methods originally developed by Zewail\cite{Zewail1988} are needed to investigate their dynamics. Pump-probe studies have revealed the dynamics of fast evolving events in energetic molecules including HMX and RDX,\cite{Greenfield2006} nitramines,\cite{Guo2005,Guo2007,Guo2011} nitromethane,\cite{Guo2009} and furazan.\cite{Guo2008} In all of these molecules, the ionized fragment \ce{NO+} was formed from the electronically excited parent molecules within the pulse duration of 180 fs. In other studies, dissociation of \ce{NO2} from nitromethane was found to occur within 81 fs\cite{Nelson2016} and the transient parent cations of nitrotoluenes formed from electronically excited neutrals were found to have lifetimes of $50-70$ fs.\cite{Wang2010} While these studies and others attest to ultrafast timescales leading to decomposition of energetic molecules from their neutral excited states, less is known about the dissociation dynamics of their radical cations. It is thought that the radical cations of energetic molecules dissociate via low-lying electronic states based on photoelectron-photoion coincidence measurements of nitromethane\cite{Ogden1983} and nitrobenzene,\cite{Panczel1984} as well as shaped 800 nm femtosecond laser pulse excitation of 4-nitrotoluene.\cite{Lozovoy2008} Recent theoretical studies have also identified ground state dissociation pathways in the radical cations of 1-nitropropane\cite{Tsyshevsky2014} and trinitrotoluene (TNT).\cite{NguyenVan2015} However, the timescales of these dissociation processes remain unknown. One of the most important families of energetic molecules is the nitrotoluenes, with TNT the most widely investigated due to its practical uses.\cite{Wharton2000,Sulzer2008,NguyenVan2015,Cohen2007,McEnnis2007,Mullen2009,Furman2016,Weickhardt2002} While multiple rearrangement reactions can occur in excited TNT and other nitrotoluenes, the homolysis of one or more \ce{NO2} groups has been found to drive initial detonation processes based on its thermodynamic favorability.\cite{Cohen2007} As model compounds for TNT, the dissociation of mononitrotoluenes using nanosecond and femtosecond laser pulses of various wavelengths has been widely investigated.\cite{Kosmidis1994,Kosmidis1997,Tasker2002,Weickhardt2002,Lozovoy2008} Ionization with nanosecond laser pulses results in only small fragments observed in the mass spectra owing to the short-lived neutral electronic excited states of these compounds. \cite{Kosmidis1994,Kosmidis1997} In contrast, femtosecond laser ionization results in less fragmentation because the ion is formed via multiphoton ladder climbing before dissociation from the neutral excited state.\cite{Kosmidis1997,Tasker2002,Lozovoy2008} However, even under multiphoton ionization conditions, the parent nitrotoluene ion is rarely the dominant peak in the mass spectrum,\cite{Kosmidis1997,Weickhardt2002,Tasker2002,Lozovoy2008} which renders study of its dissociation via pump-probe methods difficult. The limited formation of the parent molecular ion in nitrotoluenes and other polyatomic molecules arises because strong field multiphoton ionization is a nonadiabatic process that can populate multiple excited states in the cation.\cite{Lezius2001,Lezius2002} In contrast, strong field ionization via electron tunneling can form predominantly ground state molecular ions because a limited amount of energy is injected into the remaining ion during electron detachment. \cite{Lezius2001,Lezius2002} Tunnel ionization in atoms was first explained by Keldysh, where the transition from nonadiabatic to adiabatic ionization was described by the Keldysh adiabaticity parameter $\gamma$ given by the ratio of the laser frequency $\omega_0$ to the electron tunneling frequency $\omega_t$,\cite{Keldysh1965} \begin{equation} \gamma=\frac{\omega_0}{\omega_t}=\omega_0\frac{\sqrt{2\Delta m_e}}{eE_0},\label{keldysh} \end{equation} where $\Delta$ is the ionization potential, $m_e$ and $e$ are the electron mass and charge, respectively, and $E_0$ is the laser electric field strength. The case $\gamma>>1$ corresponds to a high laser frequency that inhibits electron tunneling through the electrostatic potential barrier before the electric field switches signs. This situation results in nonadiabatic multiphoton ionization as the electron continues to absorb energy over multiple cycles of the laser pulse.\cite{Lezius2001,Lezius2002} Alternatively, the probability for electron tunneling is greatly increased when $\gamma<<1$, resulting in adiabatic ionization that imparts little energy to the remaining electrons.\cite{Lezius2001,Lezius2002} Even though the Keldysh theory was proposed for atoms, it has also been found viable for polyatomic molecules with recent experiments of strong field ionization using near-infrared excitation wavelengths (e.g., $1150 - 1600$ nm) where $\gamma<<1$.\cite{Lezius2001,Lezius2002,Yatsuhashi2005,Murakami2005,Tanaka2009,Bohinski2013a,Bohinski2013b,Bohinski2014a,Tibbetts2014,Bohinski2014b,Tibbetts2015,Munkerup2017,AmpaduBoateng2018} For example, ionization of decatetraene\cite{Lezius2002} and anthracene\cite{Murakami2005} with 800 nm excitation resulted in extensive fragmentation as compared to using 1400 nm excitation, where the enhanced fragmentation was attributed to cationic resonances and nonadiabatic ionization dynamics. Similar results were obtained for acetophenone excited with wavelengths between 800 nm and 1434 nm, where significantly less dissociation to small fragments was observed for long wavelengths.\cite{Bohinski2013b} Recent pump-probe studies have demonstrated improved preparation of coherent vibrational wavepackets in ground state molecular ions when using $1200-1500$ nm instead of 800 nm pulses for ionization. \cite{Bohinski2014b,Tibbetts2015,AmpaduBoateng2018} This work will present pump-probe measurements on the radical cations of the isomeric compounds 3-nitrotoluene and 4-nitrotoluene (3-NT and 4-NT, respectively). The high yield of parent molecular ion when using 1500 nm pulses for ionization enables observation of coherent nuclear dynamics in the radical cations of both 3-NT and 4-NT. The ion yields in the two isomers exhibit distinct oscillatory dynamics, indicating coherent excitation of distinct normal modes. Interpretation of the experimental results is supported by a series of density functional theory (DFT) calculations of the optimized geometries, relaxation pathways, and vibrational frequencies in 3-NT and 4-NT radical cations. The remainder of this work is structured as follows: Sections \ref{expt} and \ref{theory} describe the experimental and computational methods, respectively. Sections \ref{results} and \ref{theoryres} present the experimental and theoretical results. Section \ref{disc} presents an interpretation of the observed dynamics, and Section \ref{con} presents concluding remarks. \section {Experimental methods}\label{expt} The pump and probe pulses are generated from a Ti:Sapphire regenerative amplifier (Astrella, Coherent, Inc.) producing 30 fs, 800 nm, 5 mJ pulses. 2.2 mJ of the laser output is split with a 90:10 (r:t) beamsplitter, with 1.9 mJ used to pump an optical parametric amplifier (OPA, TOPAS Prime) to produce $1500$ nm, 18 fs, $300$ $\mu$J pulses that are used as the pump. The pump pulse energy is attenuated with a $\lambda/2$ waveplate and polarizer and expanded using two spherical gold mirrors with $f = -10$ cm and $f = 50$ cm to increase the beam diameter (measured with the knife-edge method) from $4.5$ mm to $22$ mm (Figure \ref{setup}(a), yellow beamline). This beam expansion results in a smaller focal beam waist, and thus higher intensity. The remaining 200 $\mu$J of 800 nm acts as the probe pulse and is down-collimated using two spherical gold mirrors with $f = 20$ cm and $f= -10$ cm to reduce the beam diameter from $11.6$ mm to $5.8$ mm. The probe beam is then directed to a retro-reflector (PLX, Inc.) placed on a motorized translation stage (ThorLabs, Inc.), attenuated with a variable density filter, and passed through an iris to isolate the most intense portion of the beam (Figure \ref{setup}(a), red beamline). Pump and probe beams are recombined on a dichroic mirror and focused with an $f=20$ cm fused silica biconvex lens. The durations of the pump and probe pulses were measured with a home-built Frequency Resolved Optical Gating (FROG)\cite{Kane1993} setup to be 18 fs and 25 fs, respectively (Supplemental Material, Figure S1). \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8.5cm]{Fig1.pdf} \end{center} \caption{\label{setup} (a) Experimental setup showing pump and probe beamlines. (b) Cross-correlation measurements of Xe$^+$ using the $1500$ nm pump and $800$ nm probe. The cross-correlation FWHM of $26.1$ fs obtained by fitting the experimental data (blue dots) to a Gaussian function (red) is consistent with the pulse durations measured by FROG.} \end{figure} The focused laser pulses are introduced into an ultrahigh vacuum chamber (base pressure $2\times10^{-9}$ torr) coupled to a linear time-of-flight mass spectrometer (TOF-MS, Jordan, Inc.) described in our earlier work.\cite{Gutsev2017} The focus of the laser beam is centered between the charged repeller ($+4180$ V) and extraction ($+3910$ V) plates, where a $1/16$'' diameter stainless steel tube introduces the sample as an effusive molecular beam approximately $1$ cm from the from the laser focus. The extraction plate has a $0.5$ mm slit orthogonal to the laser propagation and TOF-MS axes, which serves as a filter to allow only ions produced at the central focal volume of the laser beam where the intensity is the highest to enter the flight tube.\cite{Hankin2001} Samples of 3-NT and 4-NT (Sigma Aldrich, Inc.) are used without further purification and introduced directly into the chamber. Due to the low vapor pressures of the nitrotoluenes, the sample holders are heated with resistive heating tape to produce a pressure of $10^{-7}$ torr at the Z-gap microchannel plate (MCP) detector. Mass spectra are recorded with a 1 GHz digital oscilloscope at a sampling rate of 20 giga samples per second (GS/s) (LeCory WaveRunner $610$Zi). All mass spectra are averaged over $10,000$ laser shots. To establish the time-resolution of our experimental setup, Xe gas was introduced to the chamber and cross-correlation measurements using 1500 nm pump and 800 nm probe pulses with intensities of $6\times10^{13}$ W cm$^{-2}$ and $1\times10^{13}$ W cm$^{-2}$, respectively (Figure \ref{setup}(b)). Fitting the Xe$^{+}$ signal as a function of pump-probe delay to a Gaussian function produced a FWHM of $26.1\pm0.2$ fs, consistent with the FROG measurements. The absolute intensity of the pump pulse was calibrated by measuring the sum of Xe$^{n+}$ ion intensities as a function of pulse energy, which were fit to tunneling ionization rates of a rare gas according to the well-established procedure.\cite{Hankin2001} The absolute intensity of the probe pulse was obtained by measurement of the focused beam waist using a CMOS camera (ThorLabs, Inc). The beam waist and Rayleigh range were determined to be $29.4$ $\mu$m and $16$ mm, respectively (Supplemental Information, Figure S2). With the probe pulse energies of $1-11$ $\mu$J and duration of 25 fs, the peak intensities were calculated to be in the range of $2\times10^{10}-2\times10^{11}$ W cm$^{-2}$. \section{Computational methods}\label{theory} Our computations are performed using the widely used B3LYP method,\cite{Becke1993,Stephens1994} as implemented in Gaussian 09 suite of programs.\cite{Gaussian09} We choose a balanced split-valence Def2-TZVPP [($11s6p2d1f$)/$5s3p2d1f$] basis of triple-$\zeta$ quality. The convergence threshold for total energy was set to $10^{-8}$ eV and the force threshold was set to 10$^{-3}$ eV/\AA. Each geometric optimization was followed by harmonic frequency computations in order to confirm the stationary character of the state obtained. In order to test the accuracy of our computational approach, we have optimized the anionic states in addition to the neutral and cationic states of both 3-NT and 4-NT. The ground state of the neutral 4-NT molecule was found to be lower in total energy than the ground state of neutral 3-NT by 0.018 eV. This difference comes from only electronic total energies since the zero-point vibrational energies match each other within 0.001 eV. The ionization energies computed as the difference in total energies of the cation and its neutral parent at the equilibrium geometry of the neutral are rather close to each other; namely, 9.60 eV for 4-NT and 9.48 eV for 3-NT, which compare well with the experimental values of 9.54 eV\cite{Zhang2012} and 9.48 eV,\cite{Kobayashi1974} respectively. Our computed electron affinities of the para- and meta-isomers of 1.04 eV and 1.09 eV practically match the experimental values of $0.932 \pm0.087$ eV\cite{Huh1999} and $0.99 \pm0.10$ eV,\cite{Chowdhury1986} respectively, within the experimental uncertainty bars. In view of close agreement of our computed values with experiment, one can expect the B3LYP/Def2-TZVPP approach to be accurate in the same extent when computing other properties of the nitrotoluene isomers. \section{Experimental results}\label{results} \subsection{Time-resolved mass spectra and transient ion signals}\label{signals} Figures \ref{transients}(a) and (b) display the mass spectra of 4-NT and 3-NT taken with pump intensity $8\times10^{13}$ W cm$^{-2}$ and probe intensity $1\times10^{11}$ W cm$^{-2}$ at pump-probe delays $\tau=-200$ fs (purple) and $\tau=+4000$ fs (green). The mass spectra are normalized to the respective parent ion yields at $\tau=-200$ fs (probe precedes pump). In this situation, all ions are generated solely from the pump because the probe intensity is well below the ionization threshold and the parent molecular ion is the most intense peak for both 3-NT and 4-NT. The predominant formation of parent molecular ion is consistent with previous studies on other molecules under adiabatic ionization conditions.\cite{Lezius2001,Lezius2002,Yatsuhashi2005,Murakami2005,Tanaka2009,Bohinski2013a,Bohinski2013b,Bohinski2014a,Tibbetts2014,Bohinski2014b,Tibbetts2015,Munkerup2017,AmpaduBoateng2018} For both 3-NT and 4-NT at $\tau=+4000$ fs, the parent ion signal is depleted and the \ce{C7H7+} ion signal enhanced, indicating that the weak field probe pulse is capable of exciting ions generated by the pump to form \ce{C7H7+} through cleavage of the \ce{C-NO2} bond. Because the most significant changes in ion yields due to the probe pulse affect the parent ion and \ce{C7H7+}, we will focus on the dynamics of these two ions. Other fragments are visible in the spectra, including \ce{C7H7O+}, formed from the parent ion via nitro-nitrite rearrangement, and \ce{C5H5+}, formed from dissociation of \ce{C7H7+}.\cite{Zhang2012} \ce{NO2+} and \ce{NO+} in both molecules are formed via Columb explosion of a multiply-charged precursor based on the split peaks marked with a $*$ in the mass spectra.\cite{Nibarger2001} The transient ion signals of the parent ion \ce{C7H7NO2+} (red) and \ce{C7H7+}(blue) as a function of pump-probe delay $\tau$ are shown in Figure \ref{transients}(c) and (d) for 4-NT and 3-NT, respectively. Ion signals in each molecule are normalized to the parent ion yield at $\tau=-200$ fs. While there is a significant depletion of the parent and an increase \ce{C7H7+} at $\tau>0$ in both molecules, the transient dynamics of these species are quite distinct. Out-of-phase oscillations of the parent and \ce{C7H7+} ion signals are visible in each molecule, suggesting (1) that coherent vibrational motions are excited upon ionization of both 4-NT and 3-NT and (2) that \ce{C7H7+} is formed via excitation with the probe pulse to an excited electronic state in the \ce{C7H7NO2+} ion.\cite{Pearson2007,Gonzalez2010,Ho2009,Brogaard2011,Zhu2011,Konar2014,Munkerup2017,Bohinski2014b,Tibbetts2015,AmpaduBoateng2018} Performing a fast Fourier transform (FFT) on the transient signals produced well-resolved peaks at approximately 85 cm$^{-1}$ and 160 cm$^{-1}$ for 4-NT and 3-NT, respectively (insets of Figures \ref{transients} (c) and (d)). The the transient signals remain unchanged at $\tau>1500$ fs for 4-NT and $\tau>+4000$ fs for 3-NT, indicating no further dynamics. \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8.5cm]{Fig2.pdf} \end{center} \caption{\label{transients} Mass spectra of (a) 4-NT and (b) 3-NT taken at pump-probe delays $\tau=-200$ fs in (purple) and $\tau=+4000$ fs (green). Transient ion yields of parent molecular ion (red) and \ce{C7H7+} (blue) in (c) 4-NT and (d) 3-NT as a function of pump-probe delay. Inset: FFT of the transient signals showing the oscillation frequencies.} \end{figure} \subsection{Analysis of the oscillatory motions}\label{osc} To gain further insight into the oscillatory dynamics observed in 4-NT and 3-NT, the transient ion signals for the parent ion and \ce{C7H7+} at $\tau>40$ fs (i.e., after the pump pulse is over) were fit using nonlinear least square methods to the following equations, \begin{align} S_\text{4-NT}(\tau)&=a\exp\left(-\frac{\tau}{T}\right)\left[\sin\left(\frac{2\pi \tau}{t}+\phi\right)+b\right]+c\label{4nt}\\ S_\text{3-NT}(\tau)&=a\exp\left(-\frac{\tau}{T_1}\right)\left[\sin\left(\frac{2\pi \tau}{t}+\phi\right)+b\right]+c+d\exp\left(-\frac{\tau}{T_2}\right)\label{3nt} \end{align} where $a$ denotes the oscillation amplitude, $T$ and $T_1$ denote the coherent lifetime in 4-NT (Eq. (\ref{4nt})) and 3-NT (Eq. (\ref{3nt})), $t$ denotes the oscillation period, and $\phi$ denotes the phase. For both molecules, the constant $b$ corresponds to an incoherent contribution to the exponential decay and $c$ corresponds to the final yield as $\tau\to\infty$. The transient signals in 3-NT require a second exponential decay term with amplitude $d$ and lifetime $T_2$ (Eq. (\ref{3nt})) to account for the slow decay until $\tau\sim4000$ fs. Figure \ref{fits} shows the fit results for the transient parent and \ce{C7H7+} ion signals in 4-NT (a) and 3-NT (b) from Figure \ref{transients}. Experimental data points are shown as red (parent) and blue (\ce{C7H7+}) dots, and the fit functions to Eqs. (\ref{4nt}) and (\ref{3nt}) for 4-NT and 3-NT as solid lines. The coherent portions of the respective fit functions are shown as magenta and light blue dashed lines for the parent and \ce{C7H7+} ions, and the incoherent portions shown as orange and green dotted lines, respectively. The second exponential contribution in Eq. (\ref{3nt}) for 3-NT is shown as light and dark yellow dash-dot lines for the parent and \ce{C7H7+} ions in Figure \ref{fits}(b). \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=7cm]{Fig3.pdf} \end{center} \caption{\label{fits} Normalized transient ion yields of parent molecular ion (red) and \ce{C7H7+} (blue) with curve fitting components for 4-NT (a) and 3-NT (b), respectively.} \end{figure} To fully characterize the excitation leading to cleavage of the \ce{C-NO2} bond, pump-probe measurements were performed on both molecules at a series of probe intensities from approximately $2\times10^{10}$ to $2\times10^{11}$ W cm$^{-2}$ and fit to Eqs. (\ref{4nt}) or (\ref{3nt}) (Supplemental Information, Figure S3). For both molecules, the following fit parameters were found to be independent of the probe intensity: coherent and incoherent lifetimes, oscillation periods, and phase (summarized in Table \ref{coeff}; all fit parameters to the data in Figure S3 are presented in the Supplemental Information, Tables S1 through S4). The consistent dynamical timescales and phase difference of approximately $\pi$ radians between the parent and \ce{C7H7+} ions indicate that the same excitation processes occur over this range of probe intensities. \begin{table}[htbp] \renewcommand{\baselinestretch}{1} \begin{tabular}{llrrrrr} \hline molecule&species&$T$ (fs)&$T_1$ (fs)&$T_2$ (fs)&$t$ (fs)&$\phi$ (rad)\\ \hline 4-NT& parent&$210\pm10$&&&$480\pm20$&$2.2\pm0.1$\\ & \ce{C7H7+}&$200\pm10$&&&$460\pm10$&$5.2\pm0.1$\\ 3-NT&parent&&$220\pm20$&$1100\pm100$&$216\pm3$&$1.4\pm0.2$\\ &\ce{C7H7+}&&$220\pm40$&$1200\pm200$&$220\pm3$&$4.5\pm0.2$\\\hline \end{tabular} \caption{\label{coeff} Dynamical timescales and phases obtained by fitting the transient ion signals to Eqs. (\ref{4nt}) and (\ref{3nt}). Errors denote the standard deviation of the fitted coefficient value over the 12 measured probe powers.} \end{table} \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8.5cm]{Fig4.pdf} \end{center} \caption{\label{coefff} Amplitude coefficients for the parent molecular ion as a function of probe intensity in 4-NT (a) and 3-NT (b). Amplitude coefficients for the \ce{C7H7+} ion as a function of probe intensity in 4-NT (c) and 3-NT (d), respectively. Error bars denote 95$\%$ confidence intervals.} \end{figure} The amplitude coefficients corresponding to coherent dynamics ($a$ in Eqs. (\ref{4nt}) and (\ref{3nt})) and slow time decay ($d$ in Eq. (\ref{3nt})) were observed to grow with increasing probe intensity. Figures \ref{coefff}(a) and (b) show the magnitude of the amplitude coefficients for the parent molecular ions of 4-NT and 3-NT, respectively, as a function of probe intensity. The analogous coefficients for the \ce{C7H7+} ions are shown in Figures \ref{coefff}(c) and (d). For all transients, the amplitude coefficients grow linearly with the the probe intensity, as shown by the least squares fit lines. This linear growth indicates a one-photon excitation process, resulting in \ce{C-NO2} bond cleavage. A one-photon excitation was also found to lead to methyl loss in acetophenone radical cation.\cite{Tibbetts2015} While the $a$ coefficients for each transient ion saturate at probe intensities above $\sim10^{11}$ W cm$^{-2}$, the $d$ coefficient in Eq. (\ref{3nt}) for 3-NT continues to grow (magenta and light blue data, Figures \ref{coefff}(b) and (d)). This different behavior in the short- and long-time dynamics of 3-NT suggest that two distinct excitations may contribute to \ce{NO2} loss in 3-NT. \section{Theoretical results}\label{theoryres} Our optimized structures of neutral and charged 3-NT and 4-NT isomers are displayed in Figure \ref{structs}. Structural experimental data have been obtained for 4-NT crystals,\cite{Barve1971} and the measured bond distances agree with our computed values for neutral 4-NT to within $\sim~0.02$ \AA. As can be seen in the figure, the differences in total energy between the two NT isomers are quite small independent of charge, and the largest difference of 0.04 eV belongs to the cation pair. Attachment of an extra electron leads to a significant change in the geometry of the \ce{NO2} group in both 3-NT and 4-NT anions compared to the geometries of their neutral parents as evident in the shortened C$-$N bonds and lengthened N$-$O bonds. Electron attachment also makes 3-NT lower in total energy than 4-NT by 0.03 eV. According to the results of Mulliken analysis, there are 0.6 extra electrons localized over the \ce{NO2} group in both \ce{C7H7NO2-} anions (Supplemental Information, Tables S7 and S8). \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8.5cm]{Fig5.pdf} \end{center} \caption{\label{structs} Optimized geometrical structures of neutral and singly charged isomers of nitrotoluene. Bond lengths are in {\AA} and angles in degrees. EA: adiabatic electron affinity; IE: adiabatic ionization energy. Numbers in parentheses denote relative energies between isomers in each charge state.} \end{figure} Electron detachment changes the bond lengths in the \ce{C6} rings of both isomers (Figure \ref{structs}) and the ring carries about 0.75 $e$ excessive charge in the 4-NT cation and nearly 0.9 $e$ in the 3-NT cation (Supplemental Information, Tables S7 and S8). Since electron detachment from the neutral 3-NT does not lead to a change in the geometrical topology, there is no energy barrier for a transition from the neutral geometry to the optimal cation geometry. However, this is not the case for the neutral 4-NT, where electron detachment results in the \ce{NO2} plane rotating by $52.5^\circ$ relative to the plane of the phenyl ring. In order to find the pathway from the neutral geometry to the cation geometry, we applied the QST2 approach and found that the pathway proceeds via two transition states as shown in Figure \ref{relax}. \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8.5cm]{Fig6.pdf} \end{center} \caption{\label{relax} The relaxation pathways and energies for the transitions from the neutral geometry to the cation geometries in 3-NT (left) and 4-NT (right).} \end{figure} Because the observed oscillations in the 4-NT and 3-NT ion yields arise from coherent vibrational motions in the parent radical cations,\cite{Pearson2007,Gonzalez2010,Brogaard2011,Zhu2011,Konar2014,Munkerup2017,Bohinski2014b,Tibbetts2015,AmpaduBoateng2018,Ho2009} it is of interest to determine the vibrational modes in both molecules. The frequencies and intensities of the vibrational modes in both the neutral molecules and their cations were calculated via normal mode analysis. In order to improve comparison with experiments, we have computed third-order anharmonic corrections to the harmonic frequencies of the neutral and cationic 4-NT and 3-NT isomers, whereas the intensities were taken from the harmonic frequency computations. To benchmark the calculated frequencies and intensities, the predicted infrared spectra for the neutral molecules were compared to experimental spectra obtained from NIST\cite{nistspecs} (Figure \ref{IR}). The calculated anharmonic frequencies match the experimental peaks to within 15 cm$^{-1}$ over the frequency range $\sim1000-1600$ cm$^{-1}$ and within 25 cm$^{-1}$ at lower frequencies, indicating the effectiveness of the method and suggesting that the computed cation frequencies should be reasonably accurate. However, adding anharmonic corrections can lead to imaginary (negative) anharmonic frequencies, which is observed for the lowest frequency mode corresponding to the nearly free rotation of the \ce{CH3} group. Full tabulated results of the harmonic and anharmonic vibrational frequencies in the neutral molecules and cations are presented in the Supplemental Information, Tables S9 and S10. \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8cm]{Fig7.pdf} \end{center} \caption{\label{IR} Experimental and computed IR spectra for 3-NT (left) and 4-NT (right).} \end{figure} \section{Discussion}\label{disc} \subsection{Assignment of coherently excited normal modes} Comparison of the computed relaxation pathways and vibrational frequencies to the observed coherent oscillations in 4-NT and 3-NT radical cations allows for determination of which coherent nuclear motions are excited upon ionization. Based on the experimental observation of an oscillation at 85 cm$^{-1}$ (based on FFT analysis) or $460-480$ fs ($69-73$ cm$^{-1}$, based on curve-fitting) in 4-NT and its $52.5^\circ$ rotation in the \ce{C-C-N-O} torsional angle upon electron detachment (Figure \ref{relax}), it is most likely that the \ce{NO2} torsional mode is excited. The observed frequency is in reasonable agreement with the computed oscillation frequencies in this mode of $59.8$ cm$^{-1}$ in the neutral and $46.1$ cm$^{-1}$ in the ion. To confirm that the \ce{NO2} torsional mode is responsible for the observed coherent oscillations, the potential energy curves along the \ce{NO2} dihedral angle were computed as a function of the \ce{NO2} dihedral angle with steps of 5$^{\circ}$ and 10$^\circ$. Figure \ref{PES} shows the potential energy curves along the \ce{NO2} dihedral angle for both 3-NT (red) and 4-NT (blue). As expected, the potential energy decreases by 0.12 eV in 4-NT as the \ce{NO2} group rotates away from $0^\circ$ to its optimal value at 52.5$^\circ$. The global maximum at $0^\circ$ and local maximum at 90$^\circ$ correspond to TS 1 and TS 2, respectively, of the relaxation pathway in Figure \ref{relax}. It is of interest to note that the shape 4-NT potential energy curve along the \ce{NO2} dihedral angle possesses a remarkable similarity to that for the analogous curve along the \ce{COCH3} dihedral angle in acetophenone, which has a local maximum at $90^\circ$ and global maxima at 0$^\circ$ and 180$^\circ$.\cite{Bohinski2014b,Tibbetts2015} \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8cm]{Fig8.pdf} \end{center} \caption{\label{PES} Potential energy curves along the \ce{C-C-N-O} dihedral angle for 4-NT (blue) and 3-NT (red).} \end{figure} In contrast to the 4-NT case, the potential energy in the 3-NT radical cation increases as the \ce{NO2} group is rotated away from $0^\circ$ (red curve, Figure \ref{PES}), indicating that the \ce{NO2} torsional mode cannot account for the observed oscillations in 3-NT. This result is consistent with the 160 cm$^{-1}$ oscillations observed in the 3-NT ion yields because the \ce{NO2} torsional mode would be expected at 29 cm$^{-1}$ in the neutral and 40 cm$^{-1}$ in the cation according to our computational results (Table S10). Instead, we consider a group of three normal modes with computed frequencies in the range of $158-207$ cm$^{-1}$ in the neutral and $143-202$ cm$^{-1}$ in the cation (Table S10) to account for the 160 cm$^{-1}$ oscillations. These modes correspond to the low-frequency bending motions shown in Figure \ref{mntvibs}. Because modes \textbf{A} and \textbf{B} correspond to out-of-plane bending motions in the benzene ring, neither is likely to be excited in our experiments because the benzene ring does not change from its planar geometry upon ionization (Figures \ref{structs} and \ref{relax}). Thus, we suggest that mode \textbf{C} corresponding to the in-plane bending motion of the \ce{NO2} and \ce{CH3} moieties gives rise to the observed oscillations. This mode assignment is supported by the changes in bond lengths and angles involving the benzene ring, \ce{NO2}, and \ce{CH3} groups in 3-NT when going from the neutral to cation geometry (Figure \ref{structs}). \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8.5cm]{Fig9.pdf} \end{center} \caption{\label{mntvibs} Low-frequency bending motions in 3-NT.} \end{figure} The coherent excitation of a torsional motion in ionized 4-NT may be expected because coherent torsional mode excitation has been observed in a number of molecules including acetophenone and its derivatives,\cite{Bohinski2014b,Tibbetts2015, Zhu2011, Konar2014} 1,3-dibromopropane,\cite{Brogaard2011} and azobenzene. \cite{Ho2009, Munkerup2017} The lack of torsional mode excitation in 3-NT upon ionization also resembles the case of 3-methylacetophenone, where no coherent oscillations were observed.\cite{Konar2014} The authors attributed the lack of oscillations in 3-methylacetophenone to the increase in the potential energy upon rotation of the acetyl group away from the planar geometry, which is similar to the potential energy curve in 3-NT (Figure \ref{PES}). Unlike the latter results, we do see coherent oscillations in the 3-NT ion yields from excitation of the in-plane bending mode \textbf{C} shown in Figure \ref{mntvibs}. We attribute this ability to resolve such small-amplitude oscillations to the use of a 1500 nm pump wavelength that ensures adiabatic ionization and predominant population of the ground state molecular ion.\cite{Lezius2001,Lezius2002,Bohinski2014b,AmpaduBoateng2018} \subsection{Dynamical timescales in 3-NT and 4-NT radical cations} The oscillations in both 3-NT and 4-NT decay with similar time constants of 220 fs and 200 fs, respectively. This short coherence lifetime stands in contrast to the longer coherent lifetimes of torsional wavepackets in acetophenone ($560-600$ fs)\cite{Bohinski2014b,Tibbetts2015} and azobenzene ($880-1000$ fs).\cite{Munkerup2017} Unlike the latter molecules, which are not known to undergo rearrangement reactions, the nitro group can undergo the nitro-nitrite rearrangement (NNR) reaction (\ce{NO2 -> ONO}). This rearrangement would change the topology of the molecule and thus be expected to destroy the initially excited coherent nuclear motion. The observation of \ce{C7H7O+} arising from \ce{NO} loss following NNR in our mass spectra (Figure \ref{transients}) indicates that NNR takes place in the 4-NT and 3-NT radical cations, so this rearrangement may be expected to cause the faster decoherence as compared to other aromatic molecules. However, the \ce{C7H7O+} transient dynamics (Figure \ref{nnr}) suggest that NNR does not drive the fast decoherence in either 4-NT or 3-NT. If the NNR reaction were the primary cause of decoherence, an exponentially increasing yield of \ce{C7H7O+} with a similar time constant of $\sim200$ fs as the wavepacket decay time constant would be expected. Instead, the \ce{C7H7O+} transients in both 4-NT and 3-NT exhibit completely different dynamics from the respective parent molecular ions and \ce{C7H7+} fragments. While parent and \ce{C7H7+} dynamics are the same at all probe intensities in a given isomer (Supporting Information, Figure S3), the \ce{C7H7O+} dynamics in both isomers are sensitive to the probe intensity. At intensities above $6\times10^{10}$ W cm$^{-2}$, both 4-NT and 3-NT produce a spike in \ce{C7H7O+} yield approximately $60-80$ fs after the ionization event, followed by exponential decay of the signal with time constants ranging from $170-350$ fs (solid lines in Figure \ref{nnr}; fit coefficients given in the Supporting Information, Tables S11 and S12). This result suggests that excitation of both 4-NT and 3-NT radical cations at short time-delays can facilitate the NNR reaction, and that the excitation probability quickly decreases at longer time-delays. In 4-NT, the \ce{C7H7O+} transient exhibits similar oscillatory dynamics in-phase with the parent molecular ion at a high probe intensity of $1.5 \times10^{11}$ W cm$^{-2}$, as seen in the fit to Eq. (\ref{3nt}) (solid red line), indicating that the NNR reaction can also take place on the ground electronic state of the 4-NT cation. However, the lack of these dynamics at lower probe intensities suggest that spontaneous rearrangement on the ground state is not the primary NNR pathway in 4-NT. In all cases for both isomers, the observed \ce{C7H7O+} dynamics do not suggest that NNR occurs spontaneously within 200 fs to cause wavepacket decoherence. \begin{figure}[htbp] \renewcommand{\baselinestretch}{1} \begin{center} \includegraphics[width=8.5cm]{Fig10.pdf} \end{center} \caption{\label{nnr} Transient ion signals of \ce{C7H7O+} in (a) 4-NT and (b) 3-NT at selected probe intensities (dots), indicated by color in the legend. Fit functions to Eq. (\ref{3nt}) or a decaying exponential are shown as solid lines. The signals in 3-NT at intensities below $10^11$ W/cm$^2$ were too noisy for curve fitting. The transient signal of the parent molecular ion is shown as the dotted line.} \end{figure} The complex dynamics of the \ce{C7H7O+} ion in 4-NT and 3-NT suggest that multiple pathways involving NNR exist in the respective radical cations, separate from the coherent excitation pathways leading to \ce{C-NO2} bond cleavage. The distinct \ce{C7H7O+} dynamics in each isomer further highlight the different dynamics of 4-NT and 3-NT apparent in the separate coherent vibrations excited in the respective radical cations. Furthermore, the incoherent 1.1 ps decay of the parent ion yield and increase of the \ce{C7H7+} yield in 3-NT suggests that an additional dynamical relaxation process facilitates the excitation leading to \ce{C-NO2} bond cleavage in 3-NT radical cation, while the analogous process is absent in 4-NT. The observation that the amplitude coefficient associated with the slow decay in 3-NT continues to grow at high probe powers where the amplitude coefficient associated with the coherent excitation is saturated suggests that two different excitation processes, possibly involving distinct excited states, may form \ce{C7H7+} in 3-NT. Determination of all of the pathways leading to both NNR and \ce{C-NO2} cleavage will require high-level quantum chemical calculations of both the ground and excited state potential energy surfaces along the relevant reaction coordinates. We plan to carry out these and other calculations in order to gain a greater understanding of the excitation and dissociation mechanisms involved. \section{Conclusions}\label{con} The ultrafast dynamics of 3- and 4-nitrotoluene radical cations was investigated with femtosecond pump-probe measurements and high-level DFT calculations. Oscillations in the parent and \ce{C7H7+} ion yields with pump-probe delay arising from coherent vibrational excitations were present in both molecules, with similar coherent lifetimes of approximately 200 fs. The distinct oscillation periods of 470 fs and 216 fs in 4-NT and 3-NT, respectively, were attributed to excitation of the \ce{NO2} torsional mode in 4-NT and an in-plane bending mode involving the \ce{NO2} and \ce{CH3} moieties in 3-NT. These normal mode assignments were supported by a series of DFT calculations at the B3LYP/Def2-TZVPP level of the ionization potentials, relaxation pathways, and normal mode frequencies. Loss of \ce{NO2} from the parent ions of both 3-NT and 4-NT to form \ce{C7H7+} was found to arise from a one-photon excitation of the initially formed ground state molecular ion based on the linear growth of the fitted amplitude coefficients with the probe pulse intensity. These results show that coherent nuclear dynamics contributes to \ce{C-NO2} homolysis in both nitrotoluene radical cations and open up the potential for further investigation of coherent control schemes to manipulate dissociation pathways in nitroaromatic and other energetic molecules. {\bf Supplementary Material} Pulse characterization; tabulated data of pump-probe nonlinear least squares coefficients; tabulated computational results of molecular geometries, charge states, and vibrational frequencies. {\bf Acknowledgements} The authors acknowledge support from the Army Research Office through Contract W911NF-18-1-0051 and from Virginia Commonwealth University. P. J. acknowledges support from the U.S. Department of Energy, Office of Basic Energy Sciences, Division of Materials Sciences and Engineering under Award No. DE-FG02-96ER45579.
{ "redpajama_set_name": "RedPajamaArXiv" }
3,160
Pierre Dansereau (October 5, 1911 – September 28, 2011) was a Canadian ecologist from Quebec known as one of the "fathers of ecology". Biography Born in Outremont, Quebec (now part of Montreal), he received a Bachelor of Science in Agriculture (B.Sc.A.) in 1936 and a Ph.D. in Biological Science in 1939 from the University of Geneva. From 1939 until 1942 he worked at the Montreal Botanical Garden. From 1943 until 1950 he taught at the Université de Montréal. From 1950 until 1955 he worked at the University of Michigan Botanical Gardens. From 1955 until 1961 he worked in the Faculty of Science and as the director of the Botanical Institute at the Université de Montréal. In 1961 he returned to the United States as the assistant director of the New York Botanical Garden and as a professor of botany and geography at the Columbia University. From 1972 until 1976 he was the Director of the Research Centre for Sciences and the Environment at the Université du Québec à Montréal (UQAM). In 1988 he was made a Professor Emeritus at UQAM, but he still worked there after mandatory retirement (in 1976, at 65 years old) to year 2004, aged 93. He was the subject of a 2001 documentary An Ecology of Hope by his cousin, Quebec filmmaker Fernand Dansereau. On September 28, 2011, Pierre Dansereau died, one week before his 100th birthday, after 76 years of marriage, and three months after his wife (a painter) became a centenarian — they had no children. UQAM's Complexe des sciences Pierre-Dansereau was named for him. Honours In 1987 the Canadian Botanical Association awarded him the George Lawson Medal. 1949 - Made a Fellow of the Royal Society of Canada (MSRC) 1959 - Awarded an Honorary Doctor of Laws from the University of Saskatchewan 1965 - Awarded the Léo-Pariseau Prize 1969 - Made a Companion of the Order of Canada 1971 - Awarded honorary doctorate from Sir George Williams University, which later became Concordia University. 1972 - Delivered the Massey Lecture 1973 - Awarded the Royal Canadian Geographical Society's Massey Medal 1974 - Won the Molson Prize 1983 - Awarded the Université de Sherbrooke's prix Esdras-Minville 1983 - Won the Government of Quebec's Prix Marie-Victorin 1985 - Made a Knight of the National Order of Quebec; promoted to Grand Officer in 1992 1985 - Awarded the Canada Council for the Arts' Killam Prize 1986 - Awarded the Canadian Botanical Association's George Lawson Medal 1995 - Awarded the Royal Society of Canada's Sir John William Dawson Medal 2001 - Inducted into the Canadian Science and Engineering Hall of Fame References External links Pierre Dansereau at The Canadian Encyclopedia Audio interview with Pierre Dansereau on Les années lumière 'Barefoot ecologist' got up close to nature Toronto Globe and Mail obituary 1911 births 2011 deaths Canadian ecologists Canadian expatriate academics in the United States University of Geneva alumni Grand Officers of the National Order of Quebec Companions of the Order of Canada French Quebecers Fellows of the Royal Society of Canada People from Outremont, Quebec Columbia University faculty University of Michigan staff Academic staff of the Université du Québec à Montréal Massey Medal recipients Fellows of the Ecological Society of America
{ "redpajama_set_name": "RedPajamaWikipedia" }
8,638
Praise for _Why We Came to the City_ "A love letter to Manhattan, the letter so many of us who moved here in our twenties have written . . . Like the rest of us, Jansma's characters learn that things don't always work out the way we plan, but if we stick with our city, our city delivers." — _The New York Times Book Review_ "A beautiful, sprawling, and generous book. Jansma is a brilliantly talented writer. . . . It's a heartfelt novel, tender and painful and ­cathartic all at once, and even if the characters belong to New York, the story belongs to us all." —NPR "A brilliant stylist, Kristopher Jansma draws readers into an intricate web of lives in the big city in his astonishing new work. . . . He inhabits his characters, thinking what they think and feeling what they feel so compellingly that he pulls the reader into the story and won't let go." — _The Miami Herald_ "Jansma artfully counters the heaviness of his themes with a ­delightful, and at times laugh-out-loud hilarious, narrative. Dialogues are smart, absurd, and addictive; and the author's insights border on the philosophically expansive and profound." _—Santa Cruz Sentinel_ "Joyful and tragic, Jansma's book will appeal to readers who loved Hanya Yanagihara's _A Little Life_." — _Men's Journal_ "Fans of Bret Easton Ellis's stream-of-consciousness narratives will enjoy Jasma's paean to New York City, which follows a group of twentysomethings navigating the adult world on a different coast." — _InStyle_ "Enticing . . . Much like a modern _Great Gatsby_ , this book is awash in the feeling of the city." —Bustle "A beautiful book about friendship . . . Jansma is just such a good writer. . . . His characters come alive and seem not only like real people but have inner lives that you're treasuring while you're reading." —Bill Goldstein, _Weekend Today_ , WNBC New York "Grief, actually, is the bridge from specific to universal, here. It makes what could have been a morality tale into something tender, human, and hard to look away from. And in the end, it puts a spin on that troublesome titular We that is both unexpected and ­intensely powerful." _—Chronogram_ "The prose is exquisite, the characters' relationships are intricately crafted, and Great Recession New York is a character in and of itself. Those of us who were spellbound by Jansma's debut novel will not be disappointed with his second." — _Signature_ "A deeply emotional ode to friendship . . . Jansma's narrative shines." _—Kirkus Reviews_ "Compelling . . . A tightly written, smartly conceived story that puts an insightful spin on life in the Big Apple." — _Publishers Weekly_ "This hefty novel, with its multiple characters and shifting relationships, is the kind that book clubs will love. . . . Gets at the heart of what it's like to be young and alive in the big city." _—Library Journal_ "Why did we come to the city, anyway? And why on earth would we ever leave? In Jansma's able hands, these are and are not metaphors. We came because we are more ourselves as part of a collective. We came to learn our limits. We came so that we might know when to leave. This is a lively, addictive party of a book, and you're invited." —Elisa Albert, author of _After Birth_ "The constellation of relationships Jansma charts feels so vivid and visceral that we not only see it but find ourselves caught, swaying in its gravitational tugs and tilts. In page after page abounding with wit, candor, and compassion, he reveals the indelible nature of our connections and commitments to one another, along with their gossamer fragility." —Tim Horvath, author of _Understories_ "Fantastic. This beautiful, boisterous novel is a paean to New York, to the hubris of youthful optimism, and, especially, to the powerful magnet of friendship. It's full of as much heartache and humor as the city itself. And like the city, this story will break you apart in a dozen ways, only to teach you, tenderly, how to put yourself back together. I wanted it never to end, but when I read the last page, I loved it even more. Jansma is a star." —Alena Graedon, author of _The Word Exchange_ PENGUIN BOOKS WHY WE CAME TO THE CITY Kristopher Jansma is the critically acclaimed author of two novels, _Why We Came to the City_ and _The Unchangeable Spots of Leopards_ , winner of the Sherwood Anderson Foundation Fiction Award. A graduate of Columbia University's MFA program, he is now an assistant professor of English and creative writing at SUNY New Paltz and a graduate lecturer in fiction at Sarah Lawrence College. He has written for the _New York Times, Salon, The Believer, The Millions, Slice, ZYZZYVA,_ and _Electric Literature_. He lives with his wife and son in Brooklyn, New York. ALSO BY THE AUTHOR The Unchangeable Spots of Leopards PENGUIN BOOKS An imprint of Penguin Random House LLC 375 Hudson Street New York, New York 10014 penguin.com First published in the United States of America by Viking Penguin, an imprint of Penguin Random House LLC, 2016 Published in Penguin Books 2017 Copyright © 2016 by Kristopher Jansma Penguin supports copyright. Copyright fuels creativity, encourages diverse voices, promotes free speech, and creates a vibrant culture. Thank you for buying an authorized edition of this book and for complying with copyright laws by not reproducing, scanning, or distributing any part of it in any form without permission. You are supporting writers and allowing Penguin to continue to publish books for every reader. Ebook ISBN 9780698152137 THE LIBRARY OF CONGRESS HAS CATALOGED THE HARDCOVER EDITION AS FOLLOWS: Names: Jansma, Kristopher, author. Title: Why we came to the city / Kristopher Jansma. Description: New York : Viking, [2016] Identifiers: LCCN 2015044555 (print) | LCCN 2015047243 (ebook) | ISBN 9780525426608 (hardback) | ISBN 9780143109648 (paperback) | ISBN 9780698152137 (ebook) Subjects: | BISAC: FICTION / Literary. | FICTION / Coming of Age. | FICTION / Urban Life. Classification: LCC PS3610.A5873 W48 2016 (print) | LCC PS3610.A5873 (ebook) | DDC 813/.6—dc23 LC record available at <http://lccn.loc.gov/2015044555> This is a work of fiction. Names, characters, places, and incidents either are the product of the author's imagination or are used fictitiously, and any resemblance to actual persons, living or dead, businesses, companies, events, or locales is entirely coincidental. Cover design: Brianna Harden Cover photograph: Christine Hutton Cover hand lettering: Grace Han Version_2 For Leah # CONTENTS Praise for _Why We Came to the City_ About the Author Also by the Author Title Page Copyright Dedication I Why We Came to the City Living Vicariously Five in a Million Fish Eyes and No Ears A Subjunctive March Shelter Island Jacob in the Waste Land The Disappointments II Why We Left the City Zugzwang, Ward III, 2010 William on the Bridge The Wedding of Sara Sherman and George Murphy The City That Is Acknowledgments # I We do have Prayers, you know, Prayers for forgiveness, daughters of mighty Zeus . . . and they limp and halt, they're all wrinkled, drawn, they squint to the side, can't look you in the eyes, and always bent on duty, trudging after Ruin, maddening, blinding Ruin. But Ruin is strong and swift— She outstrips them all by far, stealing a march, leaping over the whole wide earth to bring mankind to grief. And the Prayers trail after, trying to heal the wounds. —Homer, _The Iliad_ (trans. Robert Fagles) What can go wrong will go wrong. —Murphy's First Law ## WHY WE CAME TO THE CITY We came to the city because we wished to live haphazardly, to reach for only the least realistic of our desires, and to see if we could not learn what our failures had to teach, and not, when we came to live, discover that we had never died. We wanted to dig deep and suck out all the marrow of life, to be overworked and reduced to our last wit. And if our bosses proved mean, why then we'd evoke their whole and genuine meanness afterward over vodka cranberries and small batch bourbons. And if our drinking companions proved to be sublime, then we would stagger home at dawn over the Old City cobblestones, into hot showers and clean shirts, and press onward until dusk fell again. For the rest of the world, it seemed to us, had somewhat hastily concluded that it was the chief end of man to thank God it was Friday and pray that Netflix would never forsake them. Still we lived frantically, like hummingbirds; though our HR departments told us that our commitments were valuable and our feedback was appreciated, our raises would be held back another year. Like gnats we pestered Management—who didn't know how to use the Internet, whose only use for us was to set up Facebook accounts so they could spy on their children, or to sync their iPhones to their Outlooks, or to explain what tweets were and, more importantly, _why_ —which even we didn't know. _Retire!_ , we wanted to shout. _Get out of the way with your big thumbs and your senior moments and your nostalgia for 1976!_ We hated them; we wanted them to love us. We wanted to be them; we wanted to never, ever become them. Complexity, complexity, complexity! We said let our affairs be endless and convoluted; let our bank accounts be overdrawn and our benefits be reduced. Take our Social Security contributions and let it go bankrupt. We'd been bankrupt since we'd left home; we'd secure our own society _._ Retirement was an afterlife we didn't believe in and that we expected yesterday. Instead of three meals a day, we'd drink coffee for breakfast and scavenge from empty conference rooms for lunch. We had plans for dinner. We'd go out and buy gummy pad thai and throat-scorching chicken vindaloo and bento boxes in chintzy, dark restaurants that were always about to go out of business. Those who were a little flush would cover those who were a little short, and we would promise them coffees in repayment. We still owed someone for a movie ticket last summer; they hadn't forgotten. Complexity, complexity. In holiday seasons we gave each other spider plants in badly découpaged pots and scarves we'd just learned how to knit and cuff links purchased with employee discounts. We followed the instructions on food and wine Web sites, but our soufflés sank and our baked bries burned and our basil ice creams froze solid. We called our mothers to get recipes for our old favorites, but they never came out the same. We missed our families; we were sad to be rid of them. Why shouldn't we live with such hurry and waste of life? We were determined to be starved before we were hungry. We were determined to decrypt our neighbors' Wi-Fi passwords and to never turn on the air-conditioning. We vowed to fall in love: headboard-clutching, desperate-texting, hearts-in-esophagi love. On the subways and at the park and on our fire escapes and in the break rooms, we turned pages, resolved to get to the ends of whatever we were reading. A couple of minutes were the day's most valuable commodity. If only we could make more time, more money, more patience; have better sex, better coffee, boots that didn't leak, umbrellas that didn't involute at the slightest gust of wind. We were determined to make stupid bets. We were determined to be promoted or else to set the building on fire on our way out. We were determined to be out of our minds. We couldn't stop following the news. Every ten seconds we refreshed our browsers and gawked at the headlines. Dully, we read blogs of friends of friends of friends who had started an organic farm out on the Wachito River. They were out there pickling and canning and brewing things in the goodness of nature. And soon we'd worry it was time for _us_ to leave the city and go. Go! To Uruguay or Morocco or Connecticut? To the Plains or the Mountains or the Bay? But we'd bide our time, and after some months or years, our farmer friends would give up the farm and begin studying for the LSATs. We felt lousy about this, and wonderful. We missed getting mail. We wondered why we even kept those tiny keys on our crowded rings. Sometimes we would send ourselves things from the office. Sometimes we would handwrite long letters to old loved ones and not send them. We never knew their new address. We never knew anyone's address, just their cross streets and what their doors looked like. Which button to buzz, and if the buzzers even worked. How many flights to climb, and which way to turn off the stairs. Sometimes we missed those who hadn't come to the city with us—or those who had gone to other, different cities. Sometimes we journeyed to see them, and sometimes they ventured to see us. Those were the best of times, for we were all at home and not at once. Those were the worst of times, for we inevitably longed to all move here or there, yet no one ever came—somehow everyone only left. Soon we were practically all alone. Soon we began to hate the forever cramping of our lives. Sleeping on top of strangers and sipping coffee with people we knew we _knew_ but couldn't remember where from. Living out of boxes we had no space to unpack. Soon we named the pigeons roosting in our windowsills; we worried they looked mangier than the week before. We heard bellowing in the apartments below us and bedsprings creaking in the ones above. Everywhere we saw people with dogs and wondered how they managed it. Did they work from home? Did they not work? Had they gone to the right schools? Did they have connections? We had no connections. Our parents were our guarantors in name only; they called us from their jobs in distant, colorless, suburban office parks and told us we could come home anytime, and this terrified us always. But then came those nights, creeping up on us while we worked busily in dark offices, like submariners lost at sea, sailing through the dark stratosphere in our cement towers. We'd call each other to report: a good thing happened, a compliment had been paid, a favor had been appreciated, an inch of ground had been gained. We wouldn't trade those nights for anything or anywhere. Those nights, we remembered why we came to the city. Because if we were really living, then we wanted to hear the cracking in our throats and feel the trembling in our extremities. And if our apartments were coffins and our desks headstones and our dreams infections—if we were all slowly dying—then at least we were going about that great and terrible business together. ## LIVING VICARIOUSLY Irene Richmond ran down the narrow foyer, helping guests get out of their coats, which were dusted with flakes of snow that had been coming down heavily all day and still drifted lightly onto the hotel balcony. Coats that cost more than she earned in a month and that were works of art themselves. Hoods lined with fox fur imported from Finland. A quilted sateen coat filled with goose down and patterned in the latest Japanese style of concentric circles. A long vest made of rabbit. Mongolian lamb's wool. Irene got a thrill from just holding them, but it was always short-lived. By the time the guests had finished warning her not to crease the collars or wrinkle the hems, there was someone else making an even more fashionable entrance. During rare pauses, she checked her phone for messages from George and Sara. Nothing. And nothing from Jacob either. Twisting in front of the hallway mirror, she reseated the bobby pins that kept her blond hair up off her shoulders. She liked the way her neck looked in the golden light by the door. An elegant extension of her one bared shoulder. She hoped it wasn't too much. Abeba had said only to look nice, but Irene had sensed an implication that she not look nicer than the guests. Juliette then added that it was important to look hip, which Irene took to mean young, vital, and strange. Therefore: cerulean leggings, crochet sweater dress, peacock feather necklace, and a braided skinny-belt. Irene hoped these projected the artistic, professional image specified. Every job had its uniform. She checked her eye shadow, which made her irises look a shade darker, almost black instead of blue. She rubbed at a spot beneath her left eye that had been there for a month now but had only recently begun to feel sore. _Buzz_ went the door, and she was off to collect a giraffe-print bolero from the next artist or heiress to stagger in on midnight-black stilettos. The K Gallery's annual holiday party at the Waldorf Astoria was always an impressive affair. All year Irene and her friends looked forward to this night, the second Friday in December. Not that they didn't go out other nights, not that living in the city wasn't sometimes glamorous, but never anything compared to this. There were seventy-eight people on the exclusive guest list, and renowned chef Marc Herradura was catering. Honest-to-God movie stars attended. Last year they'd seen that guy from _The Office_ , and the year before that, Cyndi Lauper! This was that other New York: always around them but never visible. For this one night it belonged to them too. Even with the first big storm of winter going on outside and flights canceled at JFK and LaGuardia (only Newark soldiered on), they had nearly full attendance. All day the gallery's owners, Juliette and Abeba, had been commanding Irene from one end of Manhattan to the other. They'd thrust her into snow-capped cars in Chelsea with a wrought-iron baboon skeleton (a steal at just $300,000) whose shrieking head had extended dangerously out the window into traffic. Wearing a pair of Abeba's oversize duck boots, Irene had sloshed across the posh lobby of the Lexington Avenue hotel, aching under the weight of a moldy yam encased in bile-green polypropylene (starting at just half a million). Five years ago, when she'd first begun working at the gallery, Irene had gotten a thrill simply from being _near_ such valuable art, but by this point she was considering telling the driver to take her and the oversize photograph of Trisha Birch's genitals (one million flat) to the George Washington Bridge so she could hurl it out into the Hudson. Or maybe she would just keep going. On and on, out of the city. With the money this one photo was worth, Irene could paint all day and all night for another twenty years. Or start her own gallery. Or institute a progressive artists' colony where young dreamers could take up their own work. She could help them avoid the eighteen-hour days, the perpetual temper tantrums, the name-dropping, the ego trips, the talentless and tormented. Except that, of course, outside New York City, the Trisha Birch photographs were more likely to get her arrested for indecency than for theft. _Maybe in L.A.,_ she thought. _Maybe in London. Maybe on Mars, or Neptune._ Juliette and Abeba were not terrible bosses, but they had all the fussiness of artists without the brilliance. They had an eye for slick marketing and could start a trend like nobody's business. But the higher the K Gallery climbed in the Chelsea scene, the more Juliette and Abeba drank sickening amounts of Campari and spoke of selling everything and setting sail for the Marquesas like Gauguin. Rule one of living in the city, Irene had learned—as soon as you got there, you had to begin threatening to leave. She was theoretically putting money aside for a trip to France from which she privately imagined she'd never return, though it seemed like the same $350 or so kept entering and exiting her savings account; meanwhile the trip got more expensive and the exchange rate got worse and the gallery took up more time. Still, it was, as they said, a living, and far from a bad one. Even when she'd had to examine Teacup Yorkie feces to see which should be threaded alongside diamonds on a necklace for the Bryant Park show. Even cataloging seventeen years of Percy Bryson's toenail clippings. But she had legit benefits and enough money to pay for a cramped studio apartment on East Fourth Street, where she could paint at night without disturbing a roommate. Plus she wasn't starving. If not trips to France, her paychecks covered a vintage dress or two and movie tickets and bar tabs and green tea smoothies. _Buzz!_ At last it was them: George Murphy and Sara Sherman. George wore a wide smile and a black pinstripe suit. Was it new? It was. Sara had gotten it for him last week at the Macy's pre-Christmas sale, to wear to his postdoc interviews. Irene kissed his cheek and inspected his penny-coppery hair; it needed cutting. Irene could never resist the urge to ruffle his head lightly, for luck. "We made it!" George announced. His cornflower-blue eyes met the room over Irene's shoulder and then fixed on her. When he spoke to her, or to anyone, they never drifted an inch. His three favorite words were, "Did you know—" and after saying them, he had a way of lowering his voice as he told you something terrific about some distant galaxy he was researching out at the North Shore Observatory, as if Andromeda B were a restaurant you might want to check out sometime. He seemed to want nothing more than for others to find him handy to have around. Swiftly, he could explain to you: the mechanics of an elevator, the science behind a hailstorm, or the electric spark between your fingers and the fringe of your dress. A good Catholic boy from Columbus, someone had raised him right; George Murphy was attentive in a city of the attention-deficient, and for this he was always looked after. "No one's ever on time to this thing," Irene said. "Here, give me your coat." But George was already hanging it up by himself. Sara slid in for a kiss from Irene. "Some big accident on the LIE," she explained. Irene told her she looked stunning, and Sara said she must be mental; she'd come straight from the gym and was sure that she must _reek_ , but of course she did not. Her long purple dress was discreetly sequined. Raven-haired and slender-jawed, Sara forever made Irene itch to break out her charcoals and sketch dark, elegant lines. No matter that she was technically not of the artsy crowd at this party—inside an hour, half the people there would believe Sara was the one throwing it. She'd glide from one conversation to the next, sometimes drawing one or two along with her until no one was a stranger to her, or to anyone, anymore. "Did you know" were also Sara's three favorite words, followed not by a fact but by a person. She always knew someone you knew: a girl in your prom limo, your YMCA summer camp counselor, the barista at the coffee shop you frequent, a man you met at that bar in Chiang Mai, the boy whose hand you held on a third-grade field trip to the Museum of Natural History. Some people never forgot a face; Sara never forgot a connection. George played with his skinny knit tie in the hall mirror. " _Six-car_ pileup. I've done this commute every day for five years, and I've never seen a crash that bad." Irene watched as the mirror's golden, thorny frame transformed George into a portrait: _Man in Crooked Necktie_. She wished she could tear the Claude Lozarette off the farther wall, melt the pigments off the canvas, and use them to paint George right there on the mirror's surface—why not?—but the moment passed. The knot was fixed; he'd stepped away. "Sorry. I had to change in a Starbucks bathroom that smelled like dead aardvarks and—" Sara interrupted. "Oh, speaking of—this is for you." She dug an oil-stained brown bag from her bottomless purse. Irene peeled back the paper to reveal a single, smushed vanilla cupcake. Little rainbow sprinkles formed a lopsided swirl, winking up like stars. "They made us _buy_ something. Can you believe it?" In fact, Irene could _not_ believe it. First, Sara was a rotten liar, and second, everyone knew Starbucks was one place you could use the bathroom without paying for something; it might as well be rule two of city living. George winked at Irene as she helped slip off Sara's coat. "Someone was afraid you didn't eat today," he murmured. Sara pretended to object, but Irene kissed her cheek again. "Well, did you?" Sara inquired, and before an answer was given, she reached up to poke the faint spot beneath Irene's eye. Irene snapped her head to one side. "I had some grapes." She already regretted telling Sara about last week's CT scan, which meant she'd just keep worrying and eventually she'd ask about yesterday's follow-up appointment. "Jacob here yet?" George asked, absently trying to take Sara's coat so he could hang it. Irene yanked it back. "Not yet. But he's always late." "But _we're_ late." "He's always later." Then, as Irene moved to close the door, she saw someone approaching—a young Korean man who was shyly inspecting the wall. It took two seconds to see that he didn't belong there. Distantly, she remembered him from somewhere. He wore a sharp, gray Armani suit and held, in one hand, a bottle of Bollinger Blanc. _Who brings champagne to a catered party?_ Irene wondered as she tried to remember which gallery he worked for. She wasn't entirely surprised to see Sara give the boy a bear hug. "William _Cho_? What are you doing here? Irene, did you know William? He was in Art History II with McClellan. You sat in on that one." Irene didn't hesitate to grip his wet, gloved hand in welcome. He was very thin, with cheekbones that she was sure she'd have remembered if he'd had them back in college. _People don't just go around getting cheekbones_ , she told herself. Or coal-black eyes like that either. She liked the girlish line of his upper lip; he bit it nervously whenever he looked at her. Normally she wasn't very interested in shyness, but something about him was making her blush. Sara turned. "George, you remember William." They shook hands politely. "Sure! William Cho, right? We met at that newspaper party with Lisa Schmidt. Sara took over as features editor after Lisa went to Madagascar with that guy with the Rhodes . . . honey, what was his name?" Sara knew it (Henry Fordham, Jr.), and also that the girl's name had been Lisa _Schlick,_ but from the look on William's face, Irene guessed he didn't know either of them. "Hang on!" George said, "Before we get caught up, let me grab us all something from the bar." It was understood that Irene had to wait until the guests had finished arriving, but Sara said anything involving St. Germain would be terrific. It was only then that William thrust forward the bottle of champagne that he'd been cradling like a football. George seized it with grateful hands. " _Damn._ This is nice stuff, William." "I stole it," William abruptly announced. "Like, you boosted it?" George asked. "Don't tell me you _boosted_ this." Sara laughed. "Boosted? What are you, a thirties gangster?" George winked at her while William clarified. "Yeah. I mean—no. I didn't rob a liquor store or anything. But it's been under the coatrack in my boss's office since last Christmas." Turning the bottle over, George peeled a shiny gift tag off the bottom. "'To Lenny. From the Berg-Geldorf Family!' Well thank you, Berg-Geldorfs! I'll see if the guy can put this on ice." He clapped William on the back. Then, while Irene and Sara turned their attention to William, he slipped into the main room with every appearance of happiness. Truth be told, however, George was feeling unusually nervous. His mind was elsewhere. Ordinarily the gallery Christmas party was his best excuse all year to get all dressed up and feel metropolitan, but this time he was in no mood. He looked around, smiling at everyone and no one in particular, as a sensation crept up his spine that somehow they could tell that he was from the Midwest, that these artists could see the sleepy cornfields in his complexion. Not like he'd grown up on a _farm_. Fairfield Beach was ten miles from Columbus. His parents had belonged to the yacht club. But tonight he wasn't feeling very yachty. He was counting on a few drinks to settle his nerves. The accident had been over on the eastbound side, but everyone on _his_ side had been rubbernecking like their lives depended on it. Like they'd never seen a crash before. _Oooo look at the flashing lights! How exciting!_ He looked up to realize that the bartender was eyeing him. "Do you have a bucket of ice we could chill this in?" The graying-haired man frowned. "This isn't a nightclub. I don't do bottle service." Poor guy looked exhausted. George smiled and took a twenty out of his wallet—the only thing in there—and slipped it into the tip jar. This both worked and didn't. The bartender took the bottle and plunked it into an empty punch bowl that he angrily began to shovel ice into, resentful at the implication that he could be bought, even if he could be. George fidgeted with the button on his new jacket. Open, the fabric whooshed backward like a cape when he walked too quickly. Closed, it made him look uptight, almost as bad as that William guy. George couldn't remember having seen him in college, not once. He was quiet, polite, and finely dressed, which meant that Jacob was going to hate him. Just knowing how much Jacob would hate him was making George sweat. Where was Jacob anyway? How was he always, always later than the rest of them? How did he know? Why wouldn't he just _show up_ , so he could be mean to William and the girls could get upset and George could swoop in to set things right and they could all go home? When the bartender had finished sourly shoveling the ice, George ordered something off the ornately printed menu called a Death in the Desert. It tasted sickeningly of licorice. He thought about asking for something else—open bar and all—but didn't want to show weakness. He gulped the drink down and pretended to be deep in appreciation of a nearby painting of a man eating his own bowels. If there was one real artist there, it was Irene _._ Over the years he'd seen the most outrageous, beautiful things come off her fingertips. She had a sort of effortless, infinite control over the thickness of a line, or the shade of oils, and the proportion of lightness to shadow. Walking through the city's museums, George was often sure that he'd just seen one of her paintings out of the corner of his eye. " _Wan'nother?_ " the bartender grumbled. "Death in the Desert," George said. "That's a pretty hard-boiled name." "Iss'a poem. All the drinks got names of poems." He tapped the company logo on the napkins: _Dead Poets Society Functions._ "Cute," George said. "So no living poets? Couldn't get a Billy Collins in a tall glass?" "The Wasteland is pretty good," the bartender offered. "Got tea-infused bourbon in it." George was soon handed a cloudy gray drink that tasted like neither tea nor bourbon. In fact it tasted like nothing at all, which was fine by him, so long as it made the party a little blurrier. Then he got Sara a Faerie Queen, involving St. Germain and blueberries, and resumed scanning the room. Finally he put his finger on it. Last year more people had been dressed up. A _lot_ more. In fact he couldn't see _anyone_ else wearing a suit, except for William. Had suits suddenly gone out of style? There were an awful lot of piratical mustaches going on around him. Two—no, three different guys with muttonchops. What was the point of looking different in exactly the same way as everybody else? No wonder all their dumb art was so dumb—edgy but harmless. Pairs of safety scissors in gilded frames. He turned, and his eyes locked with Sara's. She was chatting with William over by the doors to the balcony. She gave George just the quickest, tiniest smile, and it shattered him like a pane of glass. Could even one of these people paint _that_? The feeling you get when you're having a crappy night and the woman you're about to propose to smiles your way. With his right hand, George reached across his chest and patted his left jacket pocket. There was the impression of a small jewelry box, containing a diamond ring that had belonged to his father's mother's mother. He would give it to Sara tonight. "Everyone says Gaussman's going to be the next Rosenquist" came Irene's soft, sweet voice behind him. She was speaking to a very tall woman and gesturing toward a longish painting of various bright-colored Web site logos. George liked it—at least it was colorful. "I _loathe_ Rosenquist," the very tall woman said. Irene made a face behind the woman's back as she said, "Obviously. But that's why—" Just then they both heard familiar belly laughter. It was Jacob, at last, speaking to an elderly woman in a fox stole. "Did you skin that yourself? The workmanship's incredible." "George!" Irene sang lightly as she passed him. "That's the curator of the Morrison!" He didn't know what that was, but it didn't matter. He was the designated extinguisher of Jacob's fires. Still holding Sara's drink in one hand, George pushed across the room. As he arrived on the scene, Jacob was inspecting the woman's fur: "You can hardly see where the hounds got him." "Where've you been, Jake?" George asked, looking apologetically at the elderly curator, who took her chance to break for the next room. After taking a sniff of Sara's drink, Jacob helped himself to a gulp. "Ah, Georgie Porgie pudding and pie. Long day up at the asylum." Jake clucked his tongue. "Had to wrestle a kid to the ground who thought he was a goddamn ninja." Jacob Blaumann worked as an orderly at Anchorage House, a private rehabilitation institute up in Westchester. He kept a short, dark scholarly beard, which if he ever shaved would grow back during a commercial break. Of course Jacob didn't watch television, or own one, and the real reason for the beard, George knew, was that a boy Jacob madly desired in their sophomore year had offhandedly commented that it made him look "less pudgy." Likewise, Jacob had worn the same brown tweed jacket every day since he'd found it at Goodwill and Irene had said it made his shoulders look broad. These things went right to his head, it was true, but so what? It was his confidence, more than anything, that George had seen work its magic on all manner of men in bars, train stations, Whole Foods freezer aisles, and library carrels. Once Jacob had written poetry, but now he was just a poet. He specialized in a certain type of epic that was a tough sell in an age of text messages. "At least my poems don't fit on a square of toilet paper," he was fond of saying. Now he tended a herd of mental patients who, upon occasion, needed to be held down and syringed and straitjacketed. A job he'd found on craigslist, believe it or not, which put his size and his psych minor to unexpected use. "George," he began, slinging an arm around his old friend, "I'd like to go to a fox hunt sometime. What do you say?" "Oh, at least once before I die." George sighed wistfully. "Let's set one up right along Madison Avenue. Get some hound dogs. Floppy ears. Keen sense of smell. You and I follow on horseback, naturally. One of us plays a bugle." "You _know_ I used to bugle with the Columbus Philharmonic." Jacob lifted a cupped hand to his lips. "TOOO DOOO! TOOO DOOO!" Most of the people in the room were looking at them now. George ceaselessly enjoyed his former roommate's irreverence, since he couldn't often bring himself to be rude. With Jacob it was just the opposite: if he ever had impulses toward politeness (and Sara firmly believed he didn't), they were soon drowned out by whatever he was shouting. George liked to think they complemented each other in this way, each living through the other when it suited. "Bunch of rubberneckers!" Jacob scoffed, no quieter. George grinned. "Speaking of, I got stuck behind this six-car pileup today on the—" "Hang on. Where's the bar in this joint?" "Over there. You'll like it. All the drinks are named after poems." Jacob glowed like a thousand-watt bulb. "Who couldn't love this town?" Irene shot them an unappreciative look from across the room and then rubbed nonchalantly at her left eye with the back of her right hand as she schmoozed another donor. Feeling George staring at her, she stuck her tongue out at him and made bug eyes at the green-plastic-encased yam that perched at his end of the bar. George rubbed his stomach and pretended to be hungry. She gestured silently at the moldy yam, and he scratched at his chin as if considering it. He pantomimed taking out a checkbook and writing many, many zeroes. "Shut the fuck up!" Jacob bellowed. "They have a drink called The Wasteland! Though it _ought_ to be two words: Waste, space, Land. That's the actual title. Nobody gets that right. Even if it is highly overrated," he went on, "it can't touch 'The Bridge.' Hart Crane? Now there's a poem you guys ought to make into a drink. With hints of the East River—" He'd have gone on, but he got distracted. "Hey, why's that Korean kid look so familiar?" George ordered two more Wastelands, plus five flutes of William's champagne. Now everyone was there. Now things could really get started. • • • William Cho never ceased to be amazed. Here he was in the penthouse of one of the most luxurious hotels in Manhattan, in the midst of a great spiral of artists and patrons. Strange accents buzzed past his ears. A Persian woman passed by with owl feathers braided into her hair. There was snow blowing around out on the balcony, and beyond it more snow was falling a hundred stories to the streets. A Somali man by the window gestured wildly, his platinum watchband glinting in a spotlight. Diamonds ringed the neck of a white girl on the bathroom line, who couldn't be older than twenty. She and a Brazilian boy of about the same age studied a twisting glass sculpture that reminded William of a tidal wave, frozen solid. And here he was among them, feeling strangely rich by association, not least because he was standing there talking—being talked _to_ , really—by Sara Sherman, of all people. William didn't kid himself that Sara actually remembered him. Back in Ithaca, these four had traveled nearly everywhere as a pack. While every other college clique experienced seismic shifts and occasional mergers, they had never grown apart. "The Murphys," people had called them. William had especially adored Irene, the doe-eyed beauty who'd been habitually late for Art History II. The persistent rumor on campus was that she wasn't actually a student but a townie who had nevertheless been elected Treasurer of the Ballroom Dance Society and had several pieces put up in the Digital Media gallery—all without paying a cent of tuition. William didn't have a hard time imagining why doors opened for her. She'd used the library, attended lectures, and spent nights in the dorms, forever popping up where least expected, haunting the school, simply _belonging_. William had never spoken to her or her friends once in four years. Now they were all at the same party. It wasn't, of course, a coincidence. William had been living in Murray Hill and working at Joyce, Bennett, and Salzmann, a boutique downtown investment firm with its fair share of wealthy partners and wealthier clients. He'd been there for three uncomfortable years. Even before Lehman Brothers and Merrill Lynch had sent everyone into a panic, William had been worried about getting laid off. Just like college, the real world was all a game of who you knew. When the bosses began sending pink slips to the print server, they'd start with the people they didn't care for—or even remember. William knew he had no presence. Not at JB&S. Not anywhere. He always skipped the big holiday party, the weekend retreat at Bennett's house in East Hampton, and even the celebratory lap around the island on Salzmann's yacht after the Fontainebleau merger had come through, thanks largely to William's own analyses. He had spent those evenings like all the others: at home in his apartment watching old movies. Which is what he'd have been doing the night of the party, if he hadn't seen Irene two weeks earlier at the gallery. Mr. Joyce had sent William downtown to pick up a monstrous mural of deboned chickens that his wife had commissioned from an artist named Xeer Sool who was, apparently, very hot just then. And there she'd been! Irene Richmond! In greasy overalls, beautiful as ever, trying to help an angry Austrian sculptor bolt ceiling fan blades together at precise thirty-nine-degree angles. She didn't look up, but William knew she'd never have recognized him if she had. He had been wallpaper at school. If they made beige wallpaper you couldn't even tell wasn't paint. It didn't matter. He could not get her out of his head. He had actually had dreams about her—always in black and white, as if she were in one of his movies. Then the following week he'd seen the invitation for the K Gallery Christmas party arrive with Mr. Joyce's mail. He knew Mrs. Joyce would be in Vail with her husband anyway and wouldn't be able to go. So, just like the champagne bottle, he'd stolen it. The Dow was in free fall. They were probably going to fire him anyway. Still, it had been a week of hemming and hawing before he'd decided to go as an envoy of Mrs. Joyce's—merely hoping to catch sight of Irene again. He'd never for a moment imagined he'd speak to her, let alone that she'd be twenty feet away, smiling at him. For her part, Irene was mainly happy that Sara had someone nice to talk to, since she still had to schmooze for work and George and Jacob could never be pried apart. She knew odds were good that Sara would try to adopt William. Sara was forever picking up strays—after all, she'd once been one of them. Irene did notice that William kept looking over at her. Looking at her and then looking quickly away, that is, as if she were the sun and he might damage his retinas if he stared too long. She waited until he stared again and raised her champagne flute in one hand. William looked away so fast, he thought he'd pulled a ligament. Or whatever you had in your neck. What would she think of him, leering like that? Oh. Except that now she was mouthing "thank you." What on earth for? Oh. For the champagne. All right then. Sara was explaining that George had become an astronomer as he'd always planned. Well, a researcher. Well, a research _assistant_. But at a quite respected observatory and certainly on his way to gaining faculty status when his research was completed. She was beckoning to George and Jacob so wildly that they finally had to come over. "Jacob was in classics too. You must have been in some of the same classes!" Sara insisted, "That department was the size of a postage stamp. There were only four professors—Douglas, Jones, Khan, and oh! the alcoholic one. Wilfrey!" "Why do you have the 2003 classics faculty memorized?" Jacob asked. Sara tapped her right temple. "Like a steel trap." Jacob looked at William. "Well, mine's a hunk of Swiss cheese. I swear I just can't remember you. Nothing personal." Sara knew he was lying. Jacob _did_ remember him, and it damn well _was_ personal that he was pretending otherwise. Why would he do such a thing? Jacob could be a jerk when he wanted to be, and he nearly always wanted to be. Over the years she'd tried to introduce several new friends to the group, but they never lasted. This time would be different though. William was blushing every time he caught sight of Irene. They were perfect for each other. At least a lot more perfect than the awful people that Irene had crashed in and out of bed with lately. Sara mentally reviewed the full 2008 batting order: Connie the bitter divorcée; Sasha the former figure skater with the "mild" coke habit; "Cowboy" Lenny who had turned out to be "Cult Member" Lenny; and Anne, a Lower East Side chef with a mean streak longer than the wait at her restaurant. But now there was something softening in Irene's stance when she turned toward William. "I wish I'd stuck with classics," William confessed. "I ended up at Yale for my MBA." "You make it sound like you tripped and fell into it," Jacob said. Sara flicked his ear. "Ignore Jacob. He hates anyone who went to Yale." "Why? Did he go to—Sorry, did you go to Harvard?" "No," Sara said wryly, "Yale rejected him, and his ego never recovered. You'd think Harold Bloom personally came over and strangled his puppy." Jacob was pointedly ignoring the both of them now. He and George were whispering to themselves about something or other, though not as quietly as they thought they were. William stood alone, pretending to look out the window at the falling snow, trying not to appear to be eavesdropping on the boys' conversation—even though they were standing right next to him and not even bothering to be quiet now that Sara had walked away. " _Here_ ," Jacob was saying, "in front of everybody? You're the living worst." "It's our anniversary," George explained, so cheerily it seemed forced. "It is beyond lame of you to keep celebrating all these anniversaries. Eight years since you first made out! Eight months since you took your first trip together! Five years and six months since you first bumped uglies! Are you both in middle school? It's revolting." "Can you be quiet?" Jacob shrugged. "We may never know." "She'd want me to do it here," George tried again, "with our closest friends." Jacob snorted. "What'll you do if she says no?" "She's not going to say no." "I forgot you can predict the future. You should look at my stock portfolio sometime." "You don't have a stock portfolio. You barely have a couch." "I've still got half my bar mitzvah money in Nintendo stocks, and don't insult the blue foldout! We bought that couch together, remember? And I've bumped more uglies on it than—" William decided it probably wasn't a good time to offer to take a look at Jacob's portfolio, or to tell him that his own picks were still doing better than expected, despite the Dow being down about five thousand points since October. Actually he hoped to talk to Jacob about poetry—William had done his thesis on _The Iliad—_ but the guy showed zero interest, and so William decided it was probably just as well that he take off. He moved away toward a waiter with a tray of duck meatballs smothered in bulgogi sauce. After he grabbed one and ate it, he realized the leftover toothpick was the perfect excuse to wander toward the kitchen, where Irene and Sara were whispering about something else. They didn't notice him as he dumped the toothpick and began looking for a napkin to wipe his hands. "So what did she say at the follow-up?" Sara was asking. "I don't know! She checked it out." Irene refilled her champagne flute from the bottle William had brought, which she'd reappropriated from the bartender and was hiding behind an Estelle Danziger gigantic toy nutcracker with immodest genitalia. Sara held her flute out for a refill. "I hope she did more than take pictures this time." "They—I don't know—I think she stuck a needle in there." "Well, did she or didn't she?" "She scraped it or something. I didn't look." "Sweetie, you are hopeless." Irene looked crushed and laid her head on Sara's shoulder. Sara told her that it was all going to be fine. William wished he had any idea what they were talking about, but before he could hear more, he noticed Jacob blazing a path across the party toward the girls, with George a step behind. William pretended to be only just coming upon them all again. Jacob was in mid-rant. "I'm opposed to the whole institution! I'm pissed as hell they want to legalize it for us. Not having to get married was the only advantage we used to have over you people. That and our get-out-of-the-army-free cards . . . I swear, next they're going to figure out how to get me pregnant." Sara shot George a quizzical look, and George shrugged. William figured this was as good a time as any for him to make his exit, so he tapped Sara on her shoulder and, faking a yawn, said, "I should get going." He reached in his pocket to grab a business card, but before he could get there, he found his hand intercepted by something else—by another hand, divinely smooth and soft. "Don't be ridiculous!" said Irene. "You've barely said a word to me yet." William felt his whole body choke up. "Hello," he managed to say. "Hey, Sara, could I see you on the balco—" George interrupted. But Sara was busy. "Jacob, did you know William did his thesis on _The_ _Iliad_?" William nodded. "I worked with Professor Douglas. On the paradox of fatality and divinity . . . I mean, the idea that to some extent the mighty Olympian gods were restricted by the Three Fates, that they were some kind of independent panel—" "Sure, sure," Jacob interrupted. "So what translation do you like?" "Lattimore." Jacob coughed. "Lattimore? Come _on!_ Fagles or Lombardo, even, did it _way_ better. Christ, I can't believe they let you into Yale with _Lattimore_." Irene spoke mischievously, "Hey, don't knock my man Lattimore. Besides, _I_ heard Fagles and Lambada were total quacks. Hopped up on bennies, translating into the dead of night. A trail of broken hearts behind them." "Oh, you be quiet," Jacob poked her in the side. "Hey," Irene pouted, "we've been here how long? How about a hello?" Jacob bowed toward her. "My liege." William felt his face turn red. He'd never known people who ricocheted so swiftly between obnoxiousness and affection. He supposed they had had a lot of practice over the years. He tried to return to familiar ground. "Well, Fagles makes it sound very _nice_ , but—" "Nice? Nice? This is Homer we're talking about, not a Hallmark card! _Nice?_ My God!" As Jacob began a familiar tirade about society's overuse of certain adjectives and their eventually being rendered meaningless, George excused himself to the bathroom. Nobody noticed him slip away. There was a bit of a wait, so he polished off another tasteless Wasteland while he stood in line. The drinks were blotting out the surrounding party but also having the unfortunate effect of amplifying his nervous thoughts. He thought splashing a little cold water on his face might do the trick. At last he got inside, where there was relative peace, and took three long deep breaths. The bathroom was all white marble and great Greek arches. It was the only room in the suite that hadn't been redecorated with contemporary art, and as he washed his hands and splashed cold water on his face, he appreciated the refreshing, comfortable hotel art—the white cliffs overlooking a Minos seaside, a round bronze platter covered in faux verdigris, the cherubic statuary above the bath. Alone at last, he let his expression fall and stared into his own eyes in the mirror. His hair was everywhere, and his suit jacket was too tight in the shoulders somehow. He wasn't used to feeling nervous and self-conscious. He'd been perfectly fine until that stupid accident—but he didn't want to think about that, tonight of all nights. Delicately, he took the engagement ring out of his pocket and placed it on the countertop in the light. He'd never understood before. _Why diamonds?_ he'd always asked. _Seems kind of arbitrary_. But now that he was looking at the ring and trying to imagine putting it on Sara's finger, anything less seemed unworthy, impermanent. What he'd said to Jacob was the truth. He couldn't imagine any scenario in which Sara would say no. It had been such a foregone conclusion for so long that he was now worried only about doing justice to their decade together. He nudged the ring with his fingertip. Would it fit? He'd measured her finger with a little piece of string one night while she'd been sleeping. But what if he'd done it wrong? The ring seemed too narrow. He nudged it again. The drain in the neighboring sink was wide open, and a deep chill ran up and down his spine. He hadn't realized. _Don't knock it into the sink. Don't bump it. Pick it up carefully . . ._ Jesus! He lowered his fingers like an arcade crane, from directly above. Even being careful, it slipped just a little. He thought his head would explode. His head or his heart. But he had it, and he was lifting it, and he would not drop it. Still, some perverse imp inside his head was making him imagine it: his sweaty fingertips would loosen; he would try to grip it more firmly, but it would slip even more. Then he would hear it—the dread _clink_ of the band against porcelain. He would look down into the basin just in time to see it _clink_ again. He would reach in to snatch it, but he would only knock it closer. It would bounce around his groping hand like a glittering mosquito and then be _gone_. Gone. Down the drain. Lost forever. He clenched the ring tightly in his fist, feeling the diamond pricking his palm. He thought about praying for some kind of reassurance, but someone was jiggling the knob. God, he couldn't wait until it was over, and he could wake up tomorrow feeling good again. Gently he put the ring back in the box and the box back in his pocket. He felt as if he might vomit, but then the doorknob was going again. There were people waiting. • • • The party simmered a little longer but never quite boiled. Four or five people made an attempt at dancing ironically to the Czech folk music being played off somebody's iPod, and then there was a lot of laughing, and there was no more dancing after that. Someone almost knocked into the Chevrolet bumper, and someone else passed out in the attached bedroom, and someone was saying the caterers were nearly out of food, and someone else was saying the bartenders would only be on until two and why not grab a cab down to this new club on Allen Street, and then the suite was half empty. Irene barely noticed. People seemed far more willing to put their own coats on, now that they'd had a few drinks, and Abeba walked out with an arm around a buyer for the Goldman Sachs building. A minute later Juliette shoved an envelope into Irene's hands and ran after her. Neither of them came back. Then, more or less without warning, it was all over. Irene got a text message from Abeba that said, _Going tpo Jersey thxz v much for all hlp._ Irene gave the caterers their checks and tips from Juliette's envelope, and the bartenders kindly left behind a few half-empty bottles, and then there was no one left but them. This had never happened before, in the years they'd been coming to the party, and they were as thrilled as young children allowed to stay up long after the adults had gone to bed. "I'm going to defile some of this so-called art," Jacob roared. "You can't defile it," Sara shouted. "It's already disgusting." "I shall hump the moldy yam!" Jacob announced. But its green plastic case proved impenetrable, so he settled for miming fellatio on the wrought-iron baboon. "What kind of art do you make?" William asked Irene nervously. Irene, through her laughter, managed to say, "Nothing like this." "To the balcony!" Jacob cried, grabbing a fresh bottle of champagne in one fist and shoving the door open with the other. Freezing air rushed in, and flakes of snow danced around their heads before being obliterated by the room temperature. "The hotel wants us to stay off there!" Irene shouted. "Then they should have locked it!" "You realize it's snowing. Like, a lot," George said, even as he followed Jacob out. The dark tops of the neighboring skyscrapers waved like great trees in the wind, and it took him a moment to realize it was he who was leaning, not them. William took his jacket off and offered it to Irene as they stepped outside. She took it gratefully and held his arm to keep from toppling over on her heels. "A gentleman!" Sara cried, sticking her tongue out at George. He had gotten his jacket halfway off before remembering what was in the pocket. Then he got stuck getting it back on. "I'm a mess!" he laughed. "Uh-oh." Sara was always a bit delighted when he'd had too much to drink, as if he were a child who had eaten too much cotton candy at the county fair. "There. Is. A. Hot. Tub." Jacob said, staring over onto the far corner of the balcony, like he'd just spotted the shroud of Turin. "There is a hot. Tub." "It'll be freezing!" Sara shouted. Jacob skidded and slid as he raced over to the enormous plastic tub, which was covered by a thick pad. He pressed his hands against the covering, and his eyes rolled back into his head. "It's warm!" he cried. "It's warm!" "Not like anyone packed a swimsuit!" George shouted. "As if you all haven't seen me naked a dozen times before," Jacob shouted as he tore off his sweater and began in on his buttons. " _William_ hasn't! Jacob Blaumann, you put your clothes back on this instant!" Irene cried. But it was too late—George was already helping him push the cover off. The two of them were no better than fraternity pledges when things like this came up. Irene was worried that Juliette and Abeba might decide to return after all, or that some guest might come back looking for a forgotten purse or phone—but she was so tired of worrying. Worrying about her job and her doctor's appointment. She began to undo the tie on her dress. The cold air felt wonderful against her sore muscles, and her feet ached to be free from her shoes. "Irene!" Sara was screeching. "Come on, Mom," Irene said, handing William his coat back again. "William! Sorry about this—we're not usually quite this _reck_ less." His face was red hot despite the subzero air. "I think I'll go." "Seeya!" Jacob shouted, as everyone caught a glimpse of his ass lowering into the water. "William, don't!" Sara screeched. "I'll be _so_ embarrassed if you leave." Would she really? If they met twenty years from now, would she remember? _That time in the hot tub at the Waldorf when we all got drunk and you left?_ William bet that she would, and that he would, and he was so tired of remembering all the times he had left before things became insensible. Plus, Irene had gotten her dress off at last. He wanted to look but didn't dare. Instead he looked up at the red blinking lights on top of the building. Years ago his father had told him they were there to keep planes from hitting them. Half dressed, George rushed back inside to stow the jacket safely on the couch. "Now _this_ is living," he heard Jacob shouting. "Get bathrobes!" Sara yelled. "Or towels or something." George dug two terrycloth robes out of a closet and grabbed a pair of towels from the bathroom. When he came back out onto the balcony, he found that his three friends—and William—had all gotten into the bubbling tub. The girls' underwear had gone see-through, but they kept their shoulders level with the water. William kept his eyes fixed on the stratosphere. "Come on in, you big baby! We're not going to look," Jacob bellowed. George undid his shirt while the girls hooted and hollered, and by the time his pants were off, Jacob was doing old-timey stripper music. "Da da da DA . . . Da da da DA . . ." "No small bills!" George joked. "Fives and tens only, or I'm going right back inside." He thumbed the elastic of his Superman-blue boxer briefs, just enough to make Sara and Irene shriek, and then he climbed into the hot tub and dunked his head under at the sound of the popping champagne cork. After coming back up and taking a long sip from the bottle, George turned to William. "After tonight we're either going to be best friends or you'll never talk to us again." "My night with The Murphys," William joked. "Oh my god! Do you remember? People used to call us that!" Sara cried. Eventually George began to talk to him about people they'd known in common at school and then people who'd been at Yale. It was like they'd always been friends. _Yale._ Despite appearances, Jacob was, slowly, beginning to stew. He expected that William imagined they did this sort of thing every weekend, but this was actually a first for the four of them. And he'd expected to feel triumphant—this, after all, was _exactly_ the type of thing he was always trying to get them all to do. He was their ever-present diversion. Player of panpipes; God of wine; their much-needed anarchic spirit. He was the one who, back in the early years, had always insisted they should do shrooms and consummate the obvious tensions between them in some sort of orgy. They'd laughed, but he'd been perfectly serious. He'd wanted George, and George had wanted Irene, and Irene had been in love with Sara and George too, probably, so why not? Everybody had been in love with everybody—except him. And now that they were there, sitting in a hot tub on the top floor of one of Manhattan's most exclusive hotels, he was steadily feeling less and less like a child left home alone without the grown-ups around and more like they _were_ the grown-ups. All that glorious sexual tension had petered out. They sat there as platonically as brothers and sisters sharing a bathtub. And now George was going to propose? Of course Jacob had known this would happen eventually. It had been coming for years now—the end of all this. No more drinking champagne in hot tubs at three in the morning or joking about fox hunts. The end of the years that they'd spent discovering this city like strangers in a strange land. Now they were just here. Now half of them would be married—hopelessly monogamous. Why would anyone do such a thing? Now they'd be just another lame, sexless couple and he'd be left with Irene. George was trying to make the story of his commute sound exciting, again, and Irene was telling William and the others about her day—about the car rides with the art. And William was saying how much he really liked some of it—how he'd taken an elective at Yale called "Art After Warhol." Jacob found himself laughing uncontrollably. "Art?" he was saying, shouting, spitting. "This crap isn't art. This is what happens when people who _hate_ art try to make art." Irene was nodding. William felt emboldened. "But what does _art_ even mean today in an age of commercialization—when the drinks we're having all night are named after poems and poets, just to make a buck?" Jacob snorted. " _The Waste Land_ is the fucking _Waste Land_ no matter who misnames a drink after it. Fuck it. Two words or one, you can't cheapen it after the fact." "Hear, hear!" cried Sara. William rose. "Well, that moldy yam in a box makes you ask yourself, what is art really? Ultimately it's a question that we can never really answer." "Sure we can. I'll answer it right now," Jacob said. "But—" Irene began. "No! No _buts_!" he was crying, and to illustrate his point, he lifted his great white rear out of the water. "It's always but, but, but, but, but." There were shrieks and groans as Jacob reseized the watery floor. "Real art obliterates artifice. _The Night Watchmen_ doesn't jump out at you and say 'Hey! I'm just a bunch of paint!' No. It makes you forget that it ever had to be created in the first place. It makes you tremble before it. If anyone's trembling in front of a yam-in-a-box, it's because they're laughing. Or puking." Nobody was arguing with Jacob at this point, but he was all revved up and couldn't stop. "Art makes you feel things nobody ever taught you to feel before, because you're feeling what some stranger felt when he, or you'd better bet _she_ , made it. It's living vicariously. It makes you love from inside someone else's heart and hate with the acid in someone else's guts. It's the only thing on this planet that can make us leave the pathetic smallness of our insignificant speckness and not just connect but _become_ someone else. It's got to be metamorphic, or it's just fucking television." Then Jacob stood, triumphant, and exposed himself to everyone. The snow swirled around his head as he brought his hand to his lips and cried, "TOOO DOOO! TOOO DOOO!" He saluted George, marched out of the tub, went inside, and passed out facedown on the couch. "William," Irene said, "come help me get a towel over him so he doesn't die of pneumonia or something." William looked away until Irene was in her robe, then climbed out to join her. They went inside together, and it was the last that George or Sara saw of either of them until morning. Alone together at last, George moved around to Sara's side of the hot tub and put his arms around her. She laid her head against his firm shoulder, and they sat that way, in silence. The sky above was pink-gray and starless, as it always was in the city. They gazed across Lexington at the office windows. Far below were taxi horns and car alarms and the rumble of the M102, going south from Harlem to the East Village. These were the noises of their great, unsleeping city. The familiar creaks and groans of their home. George hoped he looked calm, even though he was cursing himself for not bringing the ring back outside. He didn't know where he would have hidden it, exactly, but this seemed like the moment he'd been waiting for. But how to get back inside and come out again? Could he say he had to go to the bathroom? That'd kill the mood. He was overcome with a feeling of rightness, as if for once his outside matched his in—and yet he was stuck. To get up would be to ruin it. And as they sat there, the silence lengthened, and he began to worry it had gotten too long, and so he tried to think of something to say—but the only thing he could think of was the accident he'd seen on the way back from Long Island. He didn't want to think about it, but there it was. A perverse pricking began on his lips. He had to say _something,_ and the only thing he wanted to say would, again, most assuredly ruin everything. "I saw a dead body today." God, the relief to say it out loud. Sara gasped and squirmed around to look him in the eye. "At work?" George shook his head. "No. On the LIE. That accident I told you about. A guy died." He had nearly missed it. He'd been sitting in traffic, thinking about Sara and what he would say to her that night at the party. He'd been watching the snow start to fall and checking the ring in his pocket every few minutes. Then at long last, he'd come to the head of the bottleneck. Having been sitting in the car that whole time absolutely fuming about rubberneckers, he was eager to speed angrily ahead. He wasn't going to look. He wanted to prove that he was above such petty gawking. But then he had. At first all he had seen was a green Isuzu with a great big hole in the windshield. He had been taken in by the size of the hole, and then he'd noticed that there was no one in the car. _Of course_ , he'd thought, _they've gotten him out by now_. _He's back by the ambulance getting insurance forms filled out._ But then George thought—what if? What if he had sailed through the glass—headfirst—the initial impact almost certainly knocking him out, if not killing him instantly? What if he had gone straight through the glass and been launched into the air (George could see it happening in slow motion, as in a terrible soap opera), and then had landed on the pavement and crumpled— And then George had seen it. The body. Not his imagination's pale little TV version but real, there, on the pavement. Right where the horrid calculator in his brain intuited it should be, given the weight of a grown man versus the resistance of a windshield versus the momentum of sixty-five miles per hour rapidly become zero, launching him into flight while gravity, that sick constant, pulled him to the pavement. Right there. The man was there and not there at all. Thank God the man's face had been turned away; the body was hunched over, head bent to the pavement as if he were merely praying. All this had happened in just three or four seconds. Soon the honking of the other impatient drivers brought George back to reality, and he'd sped off. But in that brief instant, he'd felt that man's impact with the glass as if it had been his own. He'd felt his own knees hitting the pavement—his own face coming down, hard. He had been trying to shake that feeling the whole night, and only now that he'd mentioned it to Sara was the feeling easing. He stroked her neck gently with the side of his hand. It was a moment before he realized that she was looking down. Long, dark tendrils of hair fell around her face. George could see that she was crying. "What's the matter?" "Nothing." "Is it about the accident?" Sara shook her head. He began to panic. "Did Jacob say something to you?" She sobbed. "Irene went back to the doctor." George shushed her gently. "It's going to be nothing. She's young. She's practically a vegan. She's basically Wonder Woman. Don't worry." But Sara _would_ worry; George knew that. In fact he loved it when she worried about things, because it made him confident for the both of them. That was the best part of love, he thought. Better than sex or not waking up alone or cooking without having to halve all the ingredients. Sara made him braver, and George made her calmer. Vicarious. That was what love could do. This was the reason he wished he'd thought of, before. A few light nudges with his nose made Sara turn up and close her eyes to kiss him. The snow was really picking up now. Sleepily, they watched the flakes dancing down across the street into the rising steam above St. Bartholomew's and all across Midtown. Down it came, over the Village and the Bronx, blowing across both dark rivers and along the whole of Long Island. Piling high on the steel guardrails and concrete medians, and the roads that ran through the city and out in all directions. George knew the time had come. Ring or no ring, this was his moment, and it would never be quite like this again. He loved this woman, and he knew he would never stop loving her—first, better, always, most. He could see Sara's heart pounding. Somehow she always knew what he was about to say. ## FIVE IN A MILLION ### 1 On Tuesday, George Murphy arrived at the office to discover that his star was on the verge of collapse. Perhaps in some metaphorical way, but also actually—237 Lyrae V, a prestellar core in the Ring Nebula that George had been studying for the past four years was experiencing a highly unexpected gravitational collapse. This, at least, according to the note he'd found on his desk that morning from Allen Ling, his cubicle mate at the astrophysics department of Brookhaven University. He had scrawled " _She's gonna blow!_ " at the top of a spreadsheet whose rows and columns—much to George's annoyance—did appear to delineate the variations in temperature and density that might characterize the beginning of a collapse. Not looking up, George said, "You are a delight to work with." Allen, who was on the phone with someone at the European Space Agency, paused from speaking rapid-fire Spanish just long enough to flip George the bird and spin toward his computer, where he was seriously bungling a game of Snood. George felt it all slipping fast away. All throughout his two-hour commute on the icy LIE, he'd been thinking of exactly how to tell his coworkers that he had finally proposed to Sara. Fatherly Dr. Cokonis had certainly been asking long enough when he would finally "make an honest woman out of her" or, as Allen preferred, "put some bling on that shit." But now this would be the main business of the day—hell, if not the month. George's doctoral and now postdoctoral research centered on what were called prestellar cores, essentially huge clusters of cosmic gases that sometimes collapsed into young protostars. Allen had been predicting this fate for 237 Lyrae V all year, despite George's lovingly constructed models that suggested the contrary. Privately, George imagined himself as a sort of astronomical Darwin, creating algorithms that could hypothetically be used to better predict the stellar landscape millennia from now. The earliest results had led him to identify dozens of cores that were on the verge of becoming stars—but discouragingly, none of them yet had. His formulas had also revealed several highly stable cores, like 237 Lyrae V, in the Ring Nebula, which were statistically unlikely to ever reach T Tauri status, with orbiting planetary bodies and asteroid belts and all the rest. It was these predictions on which his entire project was based, but if Allen was right, it was all about to be disproven on a grand scale. It took George a half hour to confirm Allen's data, and another hour to rerun the numbers through a series of algorithms on the computer, which spat out even more numbers, which then had to be rechecked. None of them looked hopeful. George simply willed it not to be true, and after another hour he could think of nothing to do but call Sara. As he dialed, he anticipated the relief he'd feel in complaining about this devastating development—but as her phone rang, he hesitated. He didn't particularly relish the idea of Allen overhearing such a breakdown, and he didn't see how he could ruin Sara's day with worrying. She'd been so excited to tell everyone at the _Journal_ about the proposal— "Hey, you!" her voice came on the line. "Hey, yourself," George said, more smoothly and cheerily than he felt by a mile. In the background he could hear the busy hum of Bistro 19, one of their group's go-to spots. Sara was cutting out of work early to have lunch with Irene to keep her mind off the fact that the doctor might call with the biopsy results. According to Irene, they had said they'd know something "later next week," which made George think there'd be no word until Thursday or Friday, or else they'd have said _We'll call first thing_. But he knew it was important to Sara, even if not to Irene, to be the sort of friend who insisted on having lunch with you when the doctor was probably not going to call. George cleared his throat. "So, some stuff came up over the weekend. I'll have to stay late tonight to get it straightened out." He could hear her disappointment as she said, "But Irene got us all tickets to see _The Death of Eurydice_ tonight." "Oh, right. Well, the thing is that one of the most important prestellar cores in my research is undergoing some pretty surprising shifts." "Sweetie, your star will still be shifting tomorrow. It's not like you can stop it." George wanted to argue, but at the same time he realized that she was right—if the prestellar core really _was_ collapsing, that really meant it had already collapsed, more than two thousand years ago, because all the information they were collecting right now had actually been traveling at light speed across space for two millennia, and so whatever was happening was all over and done already, one way or the other . . . but that didn't change the fact that his research, here and now, might all be a complete and total waste of time. Four years of his life shot—a blink in the existence of 237 Lyrae V, but a long time to him, especially at the start of his career— Sara broke in on his long silence. "Fine, I'll see if William can take your ticket then." "Don't be mad." "I'm not mad." "Good. And see if you can find out what happened with him and Irene on Friday." "I _can't_ ask him that." A pause and then, "Though I might ask _her_ if she ever shows up." "There you go. You're a reporter. Do some digging!" "I'm an _editor_. I edit _other_ people's reporting. If you can call it that." "Just a joke," he said. There was a long sigh. "Everyone's really excited about our big news," George lied, his voice low so Allen wouldn't hear. Then a happy noise. "Here too! I'm already making up a guest list. You should get the home addresses of anyone you want to invite from the department." "Let's invite everyone but Allen," George said, louder now, earning another middle finger from his office mate. "Good luck with your star. There's an after-party thing. Meet us there, okay?" He released a long sigh. "Just text me the address?" "It's in Greenpoint." Long sigh, _redux_. "Love you." "Love you too." He got off the phone. He didn't know what to do next. He closed his eyes. How could this be happening? He had to remind himself that Allen wasn't capable of collapsing a giant molecular cloud of gas, a hundred times larger than their solar system. But that didn't stop him from resenting his colleague, who had been ascending with Machiavellian precision through the department by subtly undermining the research of others. George had fallen in love, thirteen years ago, with the dream of all the infinite things in the universe still to be discovered, of theories to be pieced together and daring connections made. The Allens of the world, however, seemed to outnumber him at every turn . . . researchers who didn't look out into the universe, pondering, but instead busied themselves attending conferences and reading abstracts, looking for flawed research to tease apart or supposed discoveries to disprove. George knew, in theory, that the world—the universe—needed these doubting Allens to check the ideas of the dreamers, but he wished they didn't enjoy it quite so much. George called Jacob, whom he could usually count on for sympathy in these matters, but his friend didn't answer. If he was up at the asylum, he couldn't usually pick up. "Kaaaaaaa"—George heard Allen shouting behind him—"BLOOEY!" "Are you in the third grade?" George asked without turning around. "I wish. Okay. So I just got off with the guys in Madrid. They're getting us some time on the Messier Telescope tonight to get the last of the data." "Us? Don't you have the Phoenix-13 all afternoon?" "That weakass telescope can't get us the readings we need. Come on." "Again, who is this _us_?" Allen shouted, "You and me, G-man! I'm telling you—this is exciting shit!" "This is a catastrophe, Allen." George pointed to the shelf full of black three-ring binders, identical except for the steady fading plastic, moving leftward, as they went back in time toward his first research years. "Four years in those. Two thirty-seven Lyrae V was supposed to be _stable_." "That's what makes it so interesting, G-man. She ought to be one of the most stable cores in the Ring Nebula, right? I mean, from what you've found so far, it should take a goddamn supernova to collapse two thirty-seven. Only there's not one. So we've got to ask ourselves, in the words of our great scientific forebears—what the fuck?" "Allen—" "I'm saying, George. It's not too late to get on board with this paper I'm writing." " _You're_ writing?" "Okay, okay—we're writing. We're going to watch the collapse in real time, G-man. That's rare as shit. We're talking 'target of opportunity.' We're talking you and me are going to get time on the motherfucking _Hubble_ ," Allen said, standing quickly. "Look, I've got a lunch with Cokonis. I'm going to catch him up on all this. Think it over. If this is what I think it is, you don't have a lot of time to start writing grants." He was practically skipping as he left the cubicle. "Oh, and by the way, I'm getting married . . ." George said to the empty air. There was a long quiet, and then steadily he heard the clack of keyboards and the squeak of chairs from the other cubicles all up and down the hallway. The click of phones being put back into their cradles, the hum of fluorescent lights, the scuffing of rubber soles on carpeting. Allen was right. George knew it. He had been massively wrong about everything leading up to it, but aside from that fact, 237 Lyrae V's collapse could actually be huge for them. Shouldn't he want that? George rolled his chair over to Allen's computer, where he'd left the interface open for the Phoenix-13 telescope. Pausing the data stream Allen was downloading, George's fingers typed in the set of complex coordinates without conscious thought: Right ascension of 18h 53m 35.079s. Declination of +33° 01' 45.03. There was a long pause as the telescope, twenty-five hundred miles away in Arizona, adjusted its mechanized gaze to a completely different part of the universe. The sheer scale of these little keystrokes still floored George some days and still briefly distracted him from the heinous particulars of his job—that morning consisting of ten e-mails in two hours from Cokonis about getting the next round of grants written up, about publishing his next paper, about presenting at a conference in Wichita. The images began to come up on the screen. The Ring Nebula, aka Messier 57, aka NGC 6720. A planetary nebula in the constellation Lyra, a great reddish ring of fire surrounding an iris of blue-green like ocean water. On the sad little computer monitor, George couldn't see much detail, but he knew it glowed like an ember on the big infrareds . . . and that it was, in its way, an ember, left over when a star exhausted its supply of hydrogen and the outer layers pushed outward and it became a red giant. He zoomed the telescope to its maximum point and found his little core inside the nebula. Just a hundred thousand years old. Practically an infant in cosmic terms, emitting no light, only heat and gas, but he knew it was there. He'd first seen the Ring Nebula in AP Physics C. Mr. Pix had put it up on a color transparency, explaining, "Every once in a while, a dusty red giant star can become a nebulae, like M fifty-seven, here, which contains an unknown number of nebulosities, and in this way, one dying star becomes a kind of breeding ground for new ones." George had been stunned. Until then they'd been so fixated on heat death and entropy and black holes that he'd never stopped to think about the fact that the universe was constantly generating new stars. Against all the data it now seemed as if 237 would become one of them. But, as Sara had reminded him, its fate was sealed. Whatever was happening had happened already. The weak light he could see had left the star two millennia ago. It had all been over and done with back in the days of Babylon and Plato, when the first astronomers had turned their lenses toward the black sea above them and ventured to look more closely at those white shining spirits. His little dot was just one in 400 billion, but George didn't care. It was his, and he whispered to it, there in his cubicle, "Don't you die on me." ### 2 How exactly like George, Sara thought, to ask someone to marry him at three in the morning, when she couldn't call everyone she knew. She considered this while waiting for Irene to arrive for lunch—already twenty-five minutes late. Maybe there had been news, and Irene had decided to bail. She was a disappearance artist, Irene was. Days or weeks could go by without contact, either because she was working on a new piece or because of something personal. She could be maddeningly private. Evading the circling of an impatient waiter, Sara pretended to be on her phone while she replayed the weekend's events in her mind. For the first two minutes after George had asked, she'd said almost nothing but "Oh my God" until George reminded her she technically hadn't said yes yet, and so then she said yes for the two minutes that followed. But after those four minutes were over, she had wanted nothing more than to burst into the bedroom Irene and William had vanished into, except maybe to call her parents in Gloucester, except maybe to call her sister in Vancouver, except maybe to call Sue, her best friend from third grade, and then there were her grandparents in Sacramento and Austin . . . but it was still after midnight there and everywhere else. "Let's call your cousin Peg in London!" Sara had shouted, leaping from the hot tub and hardly pausing to wrap herself in a towel before rushing to find a phone. "It's only eight there," George had said. "Call her, call her, callllllll her!" Sara had screeched happily. While George hunted down his phone, she continued to make erratic squeaking noises. "I don't have her new number," George concluded after investigating his contacts list. Sara grabbed the phone and began flipping through, looking for people to call. "Do you ever clean this thing out? You still have your RA's number from freshman year." Then she clapped. "Jacob! Let's tell Jacob!" She was inside the hotel again before George could catch up to her. There they found Jacob wearing nothing but couch cushions. "Wake him up!" Sara insisted. "He's your friend." "You've known him practically as long as I have!" "But you knew him first," she insisted. "So technically he's your friend." George thought about this. "Does that mean I get to tell Irene too?" "Don't be ridiculous. She's a girl. It's completely different." "Completely different according to who?" "Polite society," she insisted. "And it's 'according to _whom._ ' _"_ George looked dubiously downward at their naked, snoring friend and begrudgingly poked him in the shoulder. Sara had to hand it to him—Jacob seemed neither polite nor social as he made a half-snarl and shifted, exposing one gigantic pale buttock. She sighed and gave Jacob a hearty slap on the back of the head. When this succeeded in opening just one of the boy's bleary eyes, she looked at him squarely and said, "George has something to tell you." The bloodshot pupil had swiveled in its socket toward George, who stammered at it, "We're . . . um. We're engaged!" There'd been a short silence, and then, in a growl from deep beneath a throw pillow, Jacob had said, "Engaged in what exactly?" "To be married, you ass!" Sara shouted happily, bouncing on the couch beside him. Jacob snorted, closed his eye, and said, "Does this mean Sara'll finally stop being a puritan priss and move into your place?" "Obviously," George said, just as Sara said, " _George's_ place?" They paused, each sure the other was joking. "Who's moving in with who?" George had asked. "With _whom_ ," Jacob and Sara both corrected him at once. That matter had still not been settled. And Jacob hadn't been the last to ask. Her parents had asked almost immediately, as had his. It was ridiculous that George imagined she could move into _his_ place. It was hardly big enough for even one person to move around in. Granted it was on Riverside, in a beautiful prewar building, a stone's throw from the park and close to Zabar's. And of course it was insanely cheap, which was why George had remained in this prison cell, with its single sad window that wasn't wide enough for an air conditioner. And people never believed her when she said this, but his shower was inside his kitchen! The toilet, then, was in another room the size of a coat closet, with no sink. But the worst thing by far was that his bed folded up into the wall. Yes. George Murphy, her soon-to-be husband, slept on a Murphy bed. Sara's apartment, all the way across the island on York Avenue, was vastly superior. The railroad style wasn't all that convenient for living with Karen, a former coworker whose boyfriend, Troy, now spent every night and most of every weekend there. But it would be perfect for her and George, if Karen could be convinced it was high time she moved out to Westchester, where she and Troy both worked now anyway. The waiter was circling Sara like a shark now, trying to get her to give up the table. He was new and didn't know that she was there practically all the time. He kept asking if perhaps she'd like to wait at the bar until her friend arrived. Sara pretended to take important calls from the office when he approached, her thoughts flitting to _The Death of Eurydice_. Some artsy friends of Irene's were in it and had given them all tickets. But now Irene was saying she was too busy, and George couldn't make it, and Jacob flat-out said he could make it if he'd wanted to but didn't want to. Rude. Well, William had already written back to say he'd be delighted to come, and Sara could hardly wait to see him. She hoped he might inject a bit of civility into the group. Sara came out of her reverie to find the waiter hovering again. She coughed and ordered another coffee, though she was jittery enough from the first two cups. It was strange being there alone. Since they'd come to the city, this had been where they'd all gathered by default for brunches, lunch breaks, and late-night bull sessions. They'd last been there a week ago, though actually—no, they hadn't all been there. Jacob hadn't been able to make it. And it had been trouble, as it always was, when one of them was missing. Whenever all of them were anywhere together—picnics down at the Battery, visits to see a new exhibit of Edwardian Court costumes at the Met, an investigatory meal at a new restaurant—no one said a cross word. If anyone did (most often Jacob), it was seen as genuinely good-natured . . . However, whenever someone was missing, that person almost instantly became the subject of speculation, criticism, and suspicion. It was as if the person's absence left a hole in their mutual fabric, and the others couldn't help but pull at the fraying threads around the hole, as if to say _Something ought to be here. How has this happened?_ Just last week they'd been right here in Bistro 19, without Jacob, because he was out on a date with a new boy. _Isn't he still secretly dating his boss?_ Irene wanted to know, even though his arrangement with the boss had been open from the get-go and they all knew it. Then George had started calling the new boy "Siddhartha," because Jacob had mentioned that he lived this, like, monastic lifestyle, though not for religious reasons but just because he was sort of OCD about clutter and—here was the worst part—were they ready? They'd met at a coffee shop when Jacob had seen him finish reading a copy of _Angela's Ashes_ , get up, wipe down his table, clear his cup, and then _throw the book in the trash can._ Irene couldn't believe it. What George wanted to know was, had Jacob seen the Siddhartha guy's place yet, and was it, like, completely spotless? Sara hadn't been able to help herself from asking if Siddhartha had seen _Jacob's_ place yet, and Irene and George had almost lost it. None of them, not once in six years, had seen Jacob's apartment. It was somewhere way up in East Harlem, and as far as they could tell, he never stayed there. Either he slept with a current or past boyfriend, or he stayed up in Stamford with his boss and took the train in as if nothing were at all strange. But it was strange. For one thing, he wouldn't tell any of them where the apartment actually was. Sara thought it was because he'd bitten off more than he could chew in terms of the neighborhood, all blustery and believing that he could fit right in, only to find, as she'd explicitly told him a hundred times, that he didn't feel safe, but of course he couldn't admit that, and kept renewing the lease just to make the point. She checked her phone again. Still no message from Irene. She texted Jacob to see if he'd heard from her. She texted Irene a question mark. She texted George a smiley face and admitted to herself, then and there, that of course she'd move in with him in a heartbeat—even into that tiny closet-toilet apartment. She'd live with him in a refrigerator box, in a nursery rhyme shoe, a teepee, an igloo, or a fortress made of couch cushions. Let the doubters doubt. Let the future be unsure. In a city of eight million, they'd always be two, together, and that was the beginning and the end of it. Then, just as she was about to get up and head back to the office, Irene rushed into the restaurant, her hands up high in breathless apology. ### 3 Jacob lay in bed with a poem wadded up inside his mouth. A dry, papery obstruction. The toxic stinging of ink along the ridge of his tongue. He reached in with two fingers and tried to pull it out, even as his throat, in some sort of horrible reverse gag reflex, tried to contract and swallow the poem whole. Just as his fingers hooked onto one pulpy piece of it, he felt his esophagus swell and take the whole thing in like Jonah's whale. He pulled, gagging, on the edge of the paper, but it ripped, leaving just a scrap pressed between his fingers. His nightmare ended with a gasping breath, the poem ingested again— _again! every fucking night!—_ and his bleary eyes staring down at the ripped fragment of paper he'd torn free. On it was the first line, in handwriting so messy he couldn't read it. And then he'd woken up, and that too, had vanished. It took him a moment to be sure he wasn't really choking. He could still _feel_ the lump in his throat. As he got his breath back, he tried to think of where he was. _Pete's apartment_ , he thought, when he saw Pete snoozing on the right edge of the mattress. _He worked from home on Tuesdays and Fridays. Which means that I am in Morningside Heights. Again._ Moving softly so as not to wake the slumbering Pete, Jacob found his pants on the floor, next to the copy of _Breakfast at Tiffany's_ that Pete was _still_ finishing. What was it, like a hundred pages? He squeezed himself out of bed and slipped into the bathroom with the blue jeans, button-down Oxford, and brown tweed sports jacket he had worn the night before. He looked out the window at the white light of early afternoon. He remembered he had a night shift up at Anchorage House. He closed his eyes and tried to see the words from his dream. It was _there_ somewhere; he could hear its footsteps just around the corners of his head. Impulsively, he grabbed his cell phone and texted Dr. Boujedra. _Oliver—Under the weather. Won't make it up tonight._ It was a message he sent at least once a week. One of the perks of his relationship with his boss was that he could usually get away with playing hooky when inspiration seemed about to strike—or even on days when he just couldn't handle spending eight hours in the presence of hallucinating, drug-withdrawn, suicidal teenagers. Back in Pete's bedroom, Jacob picked up the Capote. It was the only book in the apartment—practically the only thing in the apartment. Pete owned one pot, one frying pan, one plate and one cup and one fork, a tacky lamp made out of conch shells, the mattress he slept on, one set of sheets—sky blue, with white puffy clouds—a yellow towel, and a cardboard box that contained his three outfits. One dressy, one for loafing around, and one to wear while washing the other two. He had a refrigerator and a stove, only because they'd come with the place, and both were always empty. His apartment was really quite large for a Manhattan studio, and Pete made good money working at Eco-Finance Apps or iPod Banking or something like that. He didn't belong to any cult or ascetic belief system that Jacob could discern. _You're such a weirdo_ , thought Jacob as he kissed sleeping Pete's cheek goodbye. Then he slipped out through the blank white door, which locked behind him with a click. Jacob hurried down chilly Broadway and bustled up the icy iron ziggurat of the 125th Street station, just as the downtown number 1 train groaned onto the aboveground platform. He hardly had time to admire the view as he blew aboard just before the doors cinched shut. Morningside Heights yawned before him, and he tried to feel the immensity of the entire island, of the steel tonnage beneath his feet. He willed the whole labyrinthine mess of it to vibrate up his calves and forearms. He had the first line— _he had it_ —of an epic poem. Or at least it was nibbling on the little gleaming hook that dangled from his spinal cord. He reeled all the way in and recast, way out into the deep white city: the literal soul of a thousand poets who'd come before him; the fishing grounds of two thousand others who'd gotten up earlier, read longer, worked harder, breathed deeper. Still, couldn't he just snare a little Langston? Snag some Allen or Frank? He barely dared dream of angling for Walt or for Hart—those two slippery silver sturgeons, each eighteen feet long and weighing, together, a metric ton. Guarding their salty eggs, that humble caviar. Walt, the monstrous Methuselah, with his prehistoric whiskers in the murky bottom. And Hart, the lithe Leviathan, his steel-cabled fins propelling him through the upper currents. Jacob blinked twice as the ground outside the windows rose upward on each side, and in an instant he was underground. Though the 1 train was quiet in an early-afternoon sort of way, Jacob transferred to the express 2 train at 96th Street, hoping to move even more swiftly south to Fourteenth Street and the coffee shop that he required to sit in and write this poem. It was the only place he could breathe easily enough to tease it out. The challenge, as always, was to hold this impish idea in his threadbare net until he could get there. Jacob's mind traveled back to a high school biology class where, eighty pounds lighter and half as hairy, he had seen an article in a _National Geographic_ magazine showing an African tribesman extracting a deadly parasitic worm from one of his legs. He grinned with blindingly clean teeth at the camera, as he displayed his affected leg. The onyx flesh was powdered with whitish dust, except for a circle about the size of a quarter that he'd been keeping clean. From a tiny, oozing wound emerged the freeloading worm, thick as a spaghetti strand and, according to the caption, more than _four feet long_ , curled inside the man just beneath the flesh. The only way to extract it was to coax its little exposed wormy tail around a piece of twig. Then at a rate of one quarter-turn per day, the worm could be slowly spooled out of the wound. Any faster than this, and the alarmed worm would break its captured tail off, and the whole thing had to be started over. Between turnings, the twig and its wormy passenger had to be taped down onto the man's leg so that he could continue to run and hunt and live. Disgusted, fourteen-year-old Jacob had been unable to rid his mind of the image and, worse, of the idea. Ten years later he found himself haunted by it nearly every day. For this was what writing poetry had become: a delicate extraction, done in quarter-turns, where the slightest jostling meant starting all over. It hadn't always been that way, Jacob thought, as he slipped out of the 2 train. He hurried now, as he traversed the long white corridor between the 1-2-3 and the Brooklyn-bound L. In high school he'd written like blinking. On the backs of napkins. In textbook margins. On the edges of his desks. On the dividers in the bathroom stalls. On the chalkboards of empty classrooms. He wrote so easily that he hardly minded giving his little quatrains and sonnets away. He imagined them being found someday by younger versions of himself, who would then be inspired to continue the tradition of guerrilla poetry at Moses Maimonides Elementary School. In college, he wrote only after four a.m., an hour he'd known intimately. He had to wait until everyone he knew fell asleep—when all excitement was over. With his friends falling down into couches and onto curbs and against the springs of others' beds, Jacob would scramble up the nearest sturdy tree. It didn't matter how drunk or how high he'd managed to get. He liked the feel of bark against his palms, the brush of branches on his stubbled cheeks. He liked to imagine that it was his way of tapping into his most primal self—a Paleo-Jacob who still hunted with spears and made fires with flint. But the truer reason was that he'd discovered that the fear of falling was just enough to keep him from going to sleep. More than once his friends had woken up to find him snoring in the embrace of an old oak tree's roots on the North Quad, having barely made it down before losing consciousness but with a completed poem safe there in the tweed pocket. In this city without climbable trees, he'd taken to early rising and writing on boyfriends' fire escapes. And it was this way, just on the other side of four a.m., that he'd penned his great epic, _In the Eye of the Shitstorm_ , and that, really, had been the beginning of all the trouble. Looking back on it all now, Jacob could hardly believe he'd even attempted it. One thousand, nine hundred and thirty-two lines (in honor of the year that All Real Literature had died inside of Hart Crane, when he'd jumped into the Gulf of Mexico) and told in thirty-three sections (one for each year that Walt Whitman had worked on _Leaves of Grass_ ). _God,_ Jacob thought, _what a pretentious little ass you were_. It didn't matter; he missed the confidence that had permitted it. Missed the fury that had blinded him to all paying of bills, all feeding of self, all sleeping at night until it was finished. It had taken him two weeks, and he'd begun to believe he'd never really recovered. The poem had come after the suicide of his uncle Miles, a man from St. Louis who at forty-five had been able to fix anything motorized or mechanical. He had taken Jacob fishing for the first time when he was a boy out on the Missouri River. He had also been the first gay man Jacob had known. Miles had been thought to be just a happy bachelor by the rest of the Blaumann family. Only Jacob, at eight, had known the truth, after seeing his uncle embracing the shadow of another man behind a boathouse. It was their secret and Jacob had kept it, even after Miles swallowed a pharmaceutical cornucopia in the back of a Dodge Dart parked near the river. His poem, _In the Eye of the Shitstorm_ , was about his other great childhood idol, the only other superhero he'd ever believed in: Michael Jordan, hanging himself from the backboard of a basketball net in a Brooklyn schoolyard. The poem dipped in and out of the troubled life of the iconic athlete, circling the legend but never landing. The main character, in fact, wasn't the great Number Twenty-three at all. Jacob's "stroke of genius" (according to his editors at the Roebling Press) was beginning the poem just _after_ the paparazzi and police had cleared the court of the body. They have, in their thoughtless hurry, left behind the enormous pile of, well, _shit_ that Number Twenty-three left beneath the basket when he'd strung himself up. A nameless janitor is brought in on a Sunday morning to remove the excrement. Most of the thirty-three epic sections, and the 1,932 lines, detailed the life of this nobody, as he makes various attempts to clean the famous man's fecal matter from the tarmac. He eventually settles on using his hose to steadily wash it all toward a drain on the edge of the court, where the crap begins to spiral in great Coriolis circles, forming a veritable hurricane of shit, the central image of the poem. The Mariani Prize committee had particularly loved the "deft handling of pop-cultural allusions" (fearing litigation, Jacob had referred to Jordan throughout only as "Number Twenty-three") and his "unblinking insight into modern racial discourse" (Jacob had never quite figured out what that meant). Among the other accolades they'd heaped upon the poem were that it was "unabashedly obscene" and that he was "a man's poet like none since Bukowski"—misguided sentiments that made Jacob retch. Four years later these praises were braided together into the strands of a noose that he'd cinched around his own neck. Reading _Shitstorm_ sickened him now. He'd been angry as hell those two weeks when it had poured out of him. At the time he thought it honest, full of pure rage. A mirror held up to the sickness of the world. But as time had passed, he had come to realize that under all the sly references and ballsy profanity, his poem had only one monotonous undertone—the same shrill buzzing that had been in his head that whole week, in the wake of his uncle Miles. Beneath all the rest was only one sound. It went _fuck you and fuck you and fuck you and fuck you and fuck you and fuck you._ And that was all. Jacob tried to shake all this from his head as people poured onto the train at Union Square. The car was crowded, and the swell of Brooklyn-bound bodies began to prick at something inside him. He felt hot and sick and shaky. He felt the worm begin to break, but with his eyes squeezed tight, he thought he might make it. He was so close. Just two quick stops, and he'd be free. He would coax it all out at last. "Ladies and gentlemen," came a quaking voice behind him. _Not now_ , Jacob begged, keeping his eyes shut tight. But he could smell unwashed skin. He could feel hot breath passing his ear. "Ladies and gentlemen, I'm sorry to bother you," the voice continued. "I need some money so that I can get something to eat. I'm really sorry to bother you, but I'm very hungry." It wasn't the usual affectless mumbling that Jacob and most city residents had adjusted their internal dials to ignore. It wasn't the drone he'd heard a million times before, on sidewalks and street corners and in subway cars just like this. This man sounded really awful. This man sounded dead already. "Ladies and gentlemen, I need your help. I don't know what I'm going to do. I swear to God, I'm really scared, everybody. I really don't know what I'm going to do." Somehow Jacob felt the ugly twinge in the man's tone. It wasn't "I don't know what I'm going to do to survive" but "I don't know what I'm going to do next." It wasn't desperation to live; it was a fear of knowing the only options he had left. These weren't the pleadings of a man just trying to make it to tomorrow. They were the quaking last words of a man headed for the nearest bridge unless he got a dollar. But Jacob's wallet was empty. He didn't even have a quarter. He'd spent his last ten on a bottle of cheap wine, which he and Pete had barely touched, and which Pete had emptied down the drain last night before sending the bottle shuddering down the trash chute. Jacob winced. If all he'd had were a hundred-dollar bill, he'd have given it to the man just to make him be quiet. "Please," the man begged, "I swear to God I don't know what I'm going to do." The doors opened at Third Avenue and Jacob moved toward the platform—it wasn't his stop, but he didn't care. He'd walk across the state to get away. As he got out onto the platform, he heard the doors closing behind him, and momentarily seized by some perverse imp, he turned to get a look at the man. His dark skin was powdered with some strange white grime. Jacob looked into his eyes. The worm snapped. The train pulled away from the station and left Jacob there. The lump in his throat had sunk deep down into his guts now, and he was sure it was never coming out. ### 4 The call had come just after lunch, thank God, as Irene knew there'd have been no keeping Sara from joining her for the appointment if she'd known about it. The gallery was closed for two weeks heading into the holidays, and so Irene had been wandering around the Village, getting lost in the nexus of Bleecker and Christopher Streets and Sixth and Seventh Avenues, ostensibly doing some holiday shopping. She'd already found nice leather boots for Sara, though Irene wasn't going to tell her they had been purchased at the Pleasure Chest. At her favorite vintage store, Mel's Secondhand Shop, she found, for George, a thermos with Einstein's face on it that said REALITY IS MERELY AN ILLUSION, so that his coffee would stay warm on his way out to the observatory. She thought about William when she saw a scarf like the one Bob Dylan wore on the cover of _Blonde on Blonde_ that she could see him in, that is, if she ever actually did see him again. Sara had gone on and on about William at lunch, and about fate and how seeing him again after so long meant that it was. Fate. Irene said she preferred to make her own fate, but secretly she was glad that, in this case, the forces of fate, via Sara, would certainly throw her back into his path again soon. So she got the scarf and had them wrap it. Heart beating heavier then, she went to the back where they had a lot of old books and found an illustrated book of Italian fairy tales for Jacob. They'd first met in an Italian class that she'd been sitting in on and that he'd failed spectacularly. It was just after this, having wandered into a pet shop down the street, that the woman called from Dr. Atoosa Zarrani's office at Mount Sinai Hospital to say that the results were in and the doctor could see her that afternoon to go over them. "Unless you're busy? Are you at the zoo? In this cold?" "Oh no," Irene had answered. "I'm in a pet shop. I was thinking about buying a bird." The woman had laughed. "Birds can be a lot of work. I have two sulfur-crested cockatoos at home." "Is that a good kind?" "I wouldn't recommend them to a beginner." "It's just that I have this beautiful bird cage," Irene confessed. "It was there when I moved into my apartment. I guess the last tenant left it behind. Anyway I just keep my jewelry and things in it, but sometimes I think to myself—I don't know, maybe I'd like having a pet." "Well," the woman had said, "you think about it. And if you need some time, I'm sure we can find you an appointment tomorrow." Irene had taken this as a good sign. Surely if there was something wrong, the woman would have orders to get her there pronto. Plus, the woman wouldn't be telling her to buy a bird if she thought she was dying. That'd be irresponsible. So nothing to worry about. And that was how Irene came to find herself, a few hours later, sitting in a little room at Mount Sinai Hospital with bare walls and a table bolted to the floor. Her shopping bags were at her feet, and she tried to keep the one with the purple silhouette of a dominatrix with a cracking whip facing the wall. To kill time, she flipped through the book of Italian fairy tales and thought happily about what type of bird she might get, until she looked up to see a tall Persian woman in a lab coat coming into the room. "Richmond? Irene?" They shook hands, and the doctor sat down and began leafing through the report she was carrying. Irene recognized the jagged, illegible signature of Dr. Von Hatter at Park Avenue Pathology, where she'd gone for the biopsy. Irene noticed the clear, commanding letters beneath it: DR. ATOOSA ZARRANI. _Not. Messing. Around._ "You came by yourself?" the doctor said, looking around as if someone were hiding. Irene looked around too, as if she couldn't remember, then shrugged. Why didn't the doctor just get on with it? She felt sick. That couldn't be a good sign. "Usually people bring a friend, or a family member." Irene nodded as if taking this under advisement for next time. She searched the doctor's large dark eyes for some clue as to what she knew that Irene did not. Dr. Zarrani smiled and then laughed a little to herself. "This morning a woman brought her doorman—a little Hungarian gentleman with red epaulets and a hat." Irene smiled, feeling almost at ease, just as Dr. Zarrani cleared her throat and said, "Ms. Richmond, you have cancer." Irene looked down quietly. She reached across herself and adjusted the sleeve of her shirt. Her first complete thought was that she shouldn't get a bird after all. Eventually she said, "Well, shit." Dr. Zarrani continued in a calm and even tone. "The biopsy revealed that the lump under your eye is a malignant osteosarcoma, which is the most common form of primary bone cancer. Tumors in the arm are most likely, but they can also present in the legs and skull. We'll have to do a more thorough scan to be sure that this is the only tumor, but it's small, and we're optimistic that this hasn't metastasized yet. Of course we'll need to do more testing to be sure. Very likely a CT and a bone scan, probably an MRI of your head and neck." Irene felt dizzy. "Where did it come from?" she asked. Then she rolled her eyes and said, "Wow, sorry. That's a pretty stupid question, right?" Dr. Zarrani shook her head, a little dark hair falling in front of her eyes before she quickly brushed it back. "Not at all. Some cancers do have known causes, although you're correct that we don't know for sure what causes this type. There have been a lot of studies. We don't know if it has a genetic component. Environmental causes are possible. We've looked at fluoridation in the water, dietary factors, dyes, preservatives, too much red meat, exposure to radiation, pesticides, BPA in plastics, artificial sweeteners, certain types of viruses, high tension wires, using cell phones . . ." "And nothing?" "Nothing conclusive." Irene looked away at the blank wall. She wanted to just climb into it and disappear. "The long-term survival rate for osteosarcoma is fairly high. Sixty-eight percent." "Sixty-eight percent doesn't _sound_ fairly high." "Sixty-eight percent isn't bad. And you're lucky in a sense. Because you're so young." Irene took a deep breath and shifted her gaze to the floor now. It, too, offered nothing. "See, now to me that seems distinctly _un_ lucky." Dr. Zarrani smiled a little. "Sixty-eight percent is taken across the board, over all cases. Including very young children whose immune systems aren't anywhere near strong enough to handle the treatment. Osteosarcoma affects children quite often, actually. Again, we don't know why. And then there are the elderly, who generally don't have the strength to pull through either. What I'm saying is, because you're young and otherwise healthy, if we take this thing head on and act quickly, your chances are going to be very good." A weight that Irene hadn't quite noticed suddenly seemed to lift from her shoulders, even as the knotting in her stomach got worse. She leaned forward as if she were at a board meeting—arms bent at the elbows, fingers pressed together. "So what do we do?" "A team of specialists will review your case." "Oh, but I like _you_ ," Irene said, smiling crookedly. Was she really flirting with this woman who was telling her that she was maybe dying? Used to being confused, Irene was completely bewildered now. Dr. Zarrani seemed about to say something but stopped herself before it came out. "I'll be head of your team, but you'll need a plastic surgeon, a chemotherapist, a radiologist—" "Radiation?" Irene said, touching her eye. "It helps to kill the tumor. Though this is delicate because radiation will likely permanently affect your vision in the eye, because the tumor is so close." Irene stared blankly down at the table, bracing herself for tears that were not coming. "No. That's not going to work," she said. "I'm a painter. Well, more sculpture lately. Doesn't matter. Thing is, I'm really going to need both my eyes." "I see," Dr. Zarrani said softly. "Well, as I said, we'll have a specialist take a look." "That's nonnegotiable," Irene said, even as she intuited from Dr. Zarrani's gaze that this wasn't a negotiation. "Oh fuck," she sighed finally, easing back and looking up at the blank ceiling. After a moment she peeked back again. "What are the odds?" "Well, as I said earlier, around sixty-eight percent generally—" "No, I'm sorry," Irene said, shaking her head. "I mean what the odds are that I'd . . . I mean, why me? Is this, like, super rare? How many people get this?" Dr. Zarrani nodded. "Extremely rare particularly for someone your age. As I've said, it's most often seen in very young patients or the elderly. It—well, it isn't the sort of thing you see often in healthy twentysomethings." Irene laughed. "So I'm just lucky then?" "You could look at it that way." "I really couldn't," Irene said. "I guess my mother always said I was one in a million." Dr. Zarrani smiled. "Osteosarcoma affects about five people in a million, across the whole population." "You know that off the top of your head?" "I'm very good at what I do. Which is why I'm confident that we can get through this together." Irene nodded, scanning the bare walls again. "You know, you should really put some art on the walls in here. Everywhere else in this hospital there are, like, banal _Water Lilies_ prints and that sort of thing. You know? Stuff that can kind of fade into the background. But then if you really _need_ some art to look at—like if you've just been told you have a thirty-two percent chance of dying—then there'd at least be a Monet print to distract you." "Perhaps you could paint—or sculpt—us something," Dr. Zarrani said. Irene smiled. "If you can cure me without ruining my eyes, I'll paint this whole hospital." Dr. Zarrani stuck her hand out, over the open file, across the table, and Irene shook it. "We'll begin in a week. It may take a few hours. And do bring someone with you next time," Dr. Zarrani suggested. Irene shook her head. "I'm not close with my family," she explained. "Actually, I left home when I was sixteen, and I haven't spoken to them since. But don't worry. I can handle this on my own." Dr. Zarrani shook her head slowly, and Irene couldn't escape her sharp disapproval. "I'm sorry, Ms. Richmond, but I've seen Navy SEALs who couldn't handle this on their own. You're going to have to have some help. You'll need people to get you to treatments and take you back again. You're going to feel sick all the time. Someone's got to make you eat because you won't want to. You're going to need prescriptions filled and insurance claims filed and dressings changed. You see those Lifetime movies with cute little children and pretty ladies who are always stoic and brave and solemn. They might throw up once or twice, some hair falls out, they get a little thinner . . . but that's nothing. That's just for starters. Listen to me when I say this. You are about to go to war with your own body. That's the best way to describe it." Irene felt every fiber of herself, sick and well, tight with fear. What the hell did she know about going to war? Metaphorically or otherwise. She nodded and the doctor seemed satisfied. "If you don't have friends you can trust with something like this, we can arrange—" Irene stopped her quickly. "No, it's not that. It's—you know, my friends are great—" Surely Sara would let them take out both her own eyes to save one of hers. Jacob and George would carry her to and from chemo appointments on their backs if she asked. Dr. Zarrani seemed to know already. "Ms. Richmond, you can't save them from this, I'm sorry." And that was when Irene, finally, began to cry. Embarrassed, she looked down into her lap, the book of fairy tales still open to the page she'd been on when the doctor had entered. There was a beautiful silvery illustration of an enormous cloud over a still gray sea. It caught her so suddenly that for a second she forgot where she was and what she now knew. In the fairy tale, the North Wind was speaking to a Shining Fish who had no courage. " _La speranza è l'ultima a morire_ ," the North Wind said. Unlike Jacob she hadn't failed the class. In fact she'd been one of the best students in the room, according to their teacher, Mrs. Marzocco, even though she'd gotten no credit for it or for any class. The wind was telling the fish that hope is the last thing to die. ### 5 William, for the second time in four days, found himself at a party where he knew practically no one. First a suite at the Waldorf, now a basement apartment in Greenpoint that was jammed with actors. The ceiling was two inches above his head, and several others had to stoop. After the show, before William quite realized what was happening, Sara had whisked him onto the 7 train and then onto the G. William never felt comfortable being back in the boroughs. He'd grown up out here, after all, in Flushing. This felt like returning to dry land after months at sea. The buildings were too short; the streets too quiet. Driveways and fences! They'd followed the chummy cast members past Polish restaurants and a pencil factory and an odd, freestanding water tower like the sort you'd see in Kansas somewhere by the highway—to a little basement apartment with a hobbit-size door. One by one the actors had piled in and now were sitting around on the bare floor in a circle, drinking warm white wine from plastic cups and leaving periodically to smoke skunky weed in the back alley. "I've recently begun listening to my whole hip-hop collection again," one of them said to William. "Grandmaster Flash is a _whole_ different experience on vinyl." The stranger wore a corduroy jacket and was drinking beer out of a brandy snifter, which William suspected he'd brought from home. Everyone else had plastic Solo cups and not, like, the nice ones. He reeked of pot and he kept smacking his lips together as if his beer were sawdust. "I'm sorry," William replied politely, "I don't think we've met." The boy's red eyes widened. "I thought you were someone else." Then he backed away in a hurry and moved off across the room, before William could say that, once upon a time, he'd had a Run-DMC record himself. George and the surly Jacob weren't talking to anyone else either, but at least they had each other. They sat by the host's bookshelves looking utterly exhausted and talking as if they'd been parted for weeks by dreadful battles. They exchanged stories of office politics, writer's block, graduate research, and homeless panhandlers, all while wincing at the warm PBR cans in their hands. Every few minutes one of them would pull a hardcover down, remove the dust jacket and swap it with another from elsewhere on the shelf. Neither offered an explanation. William kept trying to excuse himself, but they were too engrossed in their talk of poems and planets to even look at him. He could have left, and they'd never have noticed, but he was still holding out that Irene would show up. They had slept together three nights ago, after the last party with Sara and her friends. It was unusual for William. Not just to sleep with someone he'd met hours earlier, but to sleep with someone like Irene. He'd known while it was still happening that he'd never get over it. And things had gone well—at least he'd felt so at the time. But then in the morning he got the impression that perhaps it—no, that _he_ had been a mistake. Not an error or a lapse so much, because neither of them had been very drunk. There had been no impairment. But a mistake and the sex had been merely a miscommunication, like a game of telephone played badly. The next morning the excitement had been all about Sara's engagement, and Irene had left after breakfast without even a kiss or a phone number. Now William guessed he was somehow supposed to act as if nothing had happened. As if he didn't remember every microsecond of the evening, as if he hadn't been replaying it on the 35mm film reels of his mind ever since. It felt a little shameful, really, as he'd watched it that afternoon right through a meeting with the partners and during a Sunday phone call with the London office, and on the walk home as he passed thousands of people on the sidewalks. But they couldn't see it, he reminded himself—even if it were projected as high as the Empire State Building and as wide as the Battery. It was all in his head, and in the head of one other, who remained a ghost. All weekend he'd been miserable and afraid to return Sara's calls. He drank deeply from his cup of warm wine and wished the red plastic container would, instead, swallow him up. He looked around the party and wondered if anyone would even notice if he spontaneously disappeared. It was a bit like watching the play. He was still there, in their audience, almost as if, hours ago, the curtain had gone down, the bows had been taken, the cheers had risen, and everyone in the orchestra and all the people in the mezzanine had gone home . . . but for the actors, the whole thing just went on and on. "How was the show then?" George was asking. It took William a moment to realize that he was speaking to him. "It was fine," William lied, thinking that it would be rude to say otherwise in such a small room, filled with the very people who'd produced the play. They'd clearly worked hard and created something from nothing—wasn't that praiseworthy? Both George and Jacob stared at him, clearly expecting some elaboration. But William simply couldn't think of a positive thing to say. He swayed a bit and tried looking at the ceiling where a bare bulb in a fixture dangled with great intent. But when he looked back, the boys were still waiting for him to speak. And William, exasperated at the party, at the days of waiting for Irene to call, at the bad wine—finally snapped. "It was really, really awful. Really. God. Awful," he confessed in a whisper. George and Jacob looked both delighted and not surprised. As William described the awfulness in detail, he tried to keep his voice down, but he soon realized it was utterly unnecessary—the actors were all so loud that they wouldn't have heard him with a bullhorn in hand. "All the dialogue was in rhyming couplets. Not sure _why_. Or why there was line dancing. And the guy who played Hades shouted all his lines. And, well, Eurydice couldn't sing, so I have no idea why they put her in the lead role . . ." George and Jacob each looked over at the girl in question, the frightfully thin hostess of the party, with breasts so enormous that her every movement seemed a complex balancing act. Jacob commented wryly, "I can't imagine." "You could count her ribs through a parka." George concurred. William went on to describe the highlight of the play: the moment when the actor playing Orpheus had slipped and crashed into Cerberus, whose three papier-mâché heads had gone flying into the wings. George began telling them all about his star, collapsing two thousand light-years away, but then got distracted by the skinny actress as she rotated a tray of Bagel Bites in her tiny toaster oven. George left to go see if they were almost ready and then Jacob began telling _him_ —William!—about the homeless man he'd seen on the subway that day and about how he felt silly now for getting so worked up about it. William was vaguely aware of a buzzing sound on the chair beside him. He looked down and saw Irene's smiling face on the cell phone that lay there. "Oh, get that?" Jacob said quickly. "That's George's. Irene probably got lost coming out of the subway again." William lifted the phone, almost not wanting to answer it because if he did, her smiling face would vanish from the display. And he'd have to think of something to say to this girl, who'd slept beneath him last week and awakened a total stranger. He hit the green button to answer the call. "Yes? George Murphy's phone. This is William Cho." There was a silence on the other end. Then, static. Then, "William?" "Irene? Can you hear me?" More static. Then a strange sound he couldn't identify. "William?" she said again. William thought Jacob must be right. She sounded lost—scared. "Hello? Irene?" he said, louder. The actors were all so _loud._ And the hot-water pipes were clanking above them—how could the skinny girl ever manage to sleep? Jacob pointed to the street. "You'll never get reception in the alley. Head out front." William hurried to the little hobbit door and ducked out onto the quiet sidewalk. " . . . William? . . . Are . . . there?" William raced out, past the trash cans, lined up for the morning, and the tightly bundled stacks of newspapers that were ready for recycling. He eased between the cars, parked neatly in their rows. He was desperate to hear Irene. He fought the urge to tell her _insane_ things: that he had been missing her all weekend; that he hadn't washed his shirt from that night because it still smelled like her. He wanted to tell her that he was sure he loved her, even though he'd only known her for eight hours, during five of which he'd been asleep. He ran out into the dark street without even looking—if a truck had been going by, he wouldn't have noticed until ten seconds after it had hit him. Finally he could hear her clearly. Finally he could make out the strange noises on the other end. Full-on, reckless sobbing, more painful than any in the songs in the musical. "Irene, where are you? What's wrong?" He ran down the street to the corner, so he could figure out exactly where in the enormous city he was. He wished it all away. He wished every borough, block, and street away. "William, I—William, I'm at a coffee shop across from Mount Sinai." William kept running. He looked around, as if maybe the hospital were nearby. And then he remembered he was in Brooklyn and it was on the East Side of Manhattan. "Are you okay? Were you in an accident? Hold on, I'll find a cab—" The crying stopped, and he heard her clear her throat. "William, I've got cancer. I've got . . . osteosus . . . I forget the name of it already. Bone cancer. This lump under my eye. Only five people in a million have it." He knew he ought to turn around—go back to the party and tell her friends. That was what she wanted probably. After all, they'd known her for years. He hardly knew her at all. "You're going to be fine!" he yelled into the phone. Not even his phone. He knew he should go back to the party and tell George. But he was still racing down the street. As long as he could hear Irene there on the other end, he knew she'd be all right. He ran past the water tower, past the pencil factory, past the Polish restaurants. He ran all the way to the water's edge to a dark wooden pier. Black as the Styx, the East River rushed by. "Don't tell anyone," she said. He realized she was still sobbing into the phone. "I don't know why I even called. Don't say anything to Sara or George or Jacob or anyone, all right?" "I won't, I won't," he was saying. "Shush." He didn't make a _shhhhhh_ sound, just said, "Shush." It took him a second to realize that she'd begun laughing, softly. "What's so funny?" he wheezed. "Nothing," she said. "It doesn't matter." He didn't understand. He tried to catch his breath, but each inhalation was like battery acid, each exhalation like cumulus clouds leaving his lips. "Where are you?" Irene asked, her voice a bit steadier. He gazed across at the dark skyline. Hundreds of thousands of feet of glass and steel rose up into the blackness like a great Necropolis, and she was in there, somewhere. "William? You know, this is stupid. I'm just going to go home." "No, I can't really hear you," he said, turning from the river to run back toward the party. "Hold on." Irene's breath was in his ear again. He looked back over his shoulder at the water and the majestic city beyond it. Holding the phone tight to his ear, he ran three and a half more blocks before he realized that the signal had dropped. ## FISH EYES AND NO EARS At first, having cancer seemed to be largely a matter of paperwork. Irene tried to remain composed as the grandmotherly clerks at Mount Sinai looked crossly at her forms, their expressions never failing to falter as they handed her fresh ones. Irene wondered if they were having an interdepartmental Ugly Christmas Sweater contest or if the drop-stitched Rudolphs, Frostys, and Kringles had perhaps been knitted by their cats. She reminded herself to not get snippy. These people were trying to help her. With some pharmaceutical-sponsored clipboard on her lap, Irene attempted to hold her head high without getting it in the tinsel of the plastic fir trees, or knocking the light-up snowmen from the wire branches. Christmas was consuming Mount Sinai Hospital with virulent glee. Everywhere Irene looked, she could see prickly wreaths, looping garlands, and glitzy ornaments. Stockings were hung with care in every single elevator. Toy trains looped through banks of fake snow. Handsomely wrapped gifts with oversize bows were stacked neatly in hallway corners, although these were just for show. Irene had kicked one accidentally, and the hollow tower had toppled. The décor had seemed laughable at first, and then depressing, but now, after spending an entire morning filling out forms, she was coming around to it. Who was she to judge what it took to bring a little cheer to those stuck at the hospital over the holidays? After all, she was about to number among them. Eventually Irene was shuffled onto the sixth floor: Head and Neck Cancers. Though it seemed apropos, considering the location of her tumor, she found the little sign above the waiting area annoyingly absurd. _I've got head cancer_ , she thought to herself. _Cancer of the head. Just all this up here is no good at all. I'll get myself right on the head transplant list. Pop on the head of a nice quiet schoolteacher from Ann Arbor and be done with it._ Grace, Irene had always believed, was a double-edged blade to be kept laced at her hip at all times. To appear unperturbed by all that was perturbing you eased both your own mind and the minds of those around you. So she wished to appear the cool lieutenant, marshaling the harried hospital staff as they hammered keyboard keys and strategized the times and locations for her first two chemotherapy appointments. This worked, until she caught a glimpse of her reflection in the glasses of one of the old ladies behind the counter and was thrown by how stretched and blurry she appeared: precisely the way she felt. The woman's great gray head swayed from side to side and her tongue clucked behind fuchsia-painted lips. "Oh dear," they all seemed fond of saying, as they reached for their telephones, "let me just call someone and see about this." The problem was the question marks. Irene was full of them. Allergic reactions to medications: _?_ Name of previous primary care physician: _?_ List previous hospital visits, in order, and by purpose: 1. _Tonsils removed, 1992 or 1991?_ 2. _Fell down and hit head on a brass Dalmatian statue. I was 5 or 6? No concussion._ 3. _Horrible stomachaches, turned out to be lactose intolerance, which went away suddenly. Not sure when._ Immunizations and vaccinations: _Probably all the standard ones for kids? Nothing after 1998._ Father's medical history: _Male-pattern baldness, rosacea, near-sighted, ???_ Mother's medical history: _???_ "I have primary bone cancer." She tried to get used to the way these words felt on her tongue, and she'd point to the small lump below her left eye socket. "I have a malignant osteosarcoma." It wasn't at all noticeable until you noticed it. The day passed in excruciating baby steps. By the time darkness fell, Irene had visited practically every floor in the hospital, never once escaping the sight of glittering snowflakes. Finally cleared to begin her first two-day chemo dose the following morning, Irene walked across the dark street and broke down crying in the back corner of a MetroStop Bakery over a bowl of scalded corn chowder. None of the servers seemed to find this odd. She looked down at the mascara smudges she'd left on the edge of the paper tablecloth. She'd expected to get a bit farther than _this_. She hadn't even seen a single needle, scalpel, or IV! To quiver in the face of medieval instruments seemed reasonable; to be undone by grainy Xeroxes did not. At eight a.m., she was to report to the twelfth floor for chemotherapy, which would take a few hours to be infused through a vein in her arm. Irene waited for the mascara stains to dry a little. Then she carefully tore a perimeter of paper around them and slipped the scrap into her purse, not yet sure how or if she'd use it in some new piece she'd been constructing late at night in her apartment. While her fingers were in her purse, they pulled out her phone, even as she forbade them to do it. _Everyone's gone for the holidays,_ she reminded them _._ Still, they thumbed through her contacts. Sara was at George's parents' place in Ohio for Christmas. Jacob was in Tampa, or as he called it, "the land of decrepitude," with his mother and father for the final few days of Hanukah. She hadn't wanted to ruin anyone's holidays, so she hadn't told any of them about her diagnosis yet. The only person who knew was William Cho. Irene studied his picture. Her phone had downloaded it on its own, from where she didn't know. Dressed in a black suit and black tie, William looked somewhat startled against a blue Sears background. She wished she knew how to change it; this puzzled man was nothing like the delicate and curious boy she'd spent the night with a few days ago. The more she looked at this un-William, the more she wanted to see the real one again. She had bought him that Dylan scarf, but it was still back in her apartment. They hadn't spoken since the last time she'd sat in this same café right after the diagnosis. He would probably still be in the city; his parents lived in Queens. She tapped the star key every so often to keep the screen from going dark and taking him away. • • • 867 Video was dead, and from the owner's stares, William got the distinct impression that he was the sole reason the store hadn't closed up yet. Perhaps William was keeping it open in a larger sense as well, for the trend among his coworkers was to have DVDs—no, Blu-rays now—conveniently delivered to their doors, or better yet, streamed to their TVs. "How do you have time to go to a store?" they asked him at work, when they saw his rentals sitting on his desk waiting to be brought back. "Didn't they all close?" But William had nothing _but_ time to go to the store, even so close to Christmas. Especially now, as his office was closed. He loved stores because he never knew what he wanted. He had to touch everything until his fingers selected the right one, generally without his permission. He was doing just this when his phone rang. The owner, Arturo, whose left eye was lifeless and listing, called out to William as he set down the copy of Alfred Hitchcock's _Suspicion_ so he could answer the call. "Forty-nine cents I got that for! Not a scratch on the disc! Stupid teenagers that ran the Blockbuster on Seventy-eighth Street didn't even know who Cary Grant was. I told them, 'This is an American god, you cretins! This man could act circles around your Bin Diesel, your Channing Tater, your Catrina Gomez!'" Expecting a call from his mother, William answered the phone without glancing at the screen. " _Annyeonghaseyo, eomeoni_." "William? Is that you?" At the sound of Irene's voice, he gripped the rack of classics unsteadily. "William," she continued cheerfully. "Sorry to bother you. I'm sure you must be busy right now, but I was hoping I could ask you a favor." "No," he said quickly. "I mean, no, it isn't any bother. How are you feeling?" "I'm feeling fine. No change. But it's my building. Practically in the middle of the night, the super came around just now to tell us we have to e _vac_ uate because of some kind of infestation. Pill flies or sharp beetles or something like that. Thank god it's not bedbugs, but anyways, I just ran out—stupid me—without packing a thing, and I'm terrified to go back. Everyone's out of town, and I need a place to sleep if it's not too much to ask. Just on the couch or somewhere, I'm not picky. I don't want you to think I have the wrong idea _—"_ _Wrong idea?_ William wanted to ask. Which idea was wrong, exactly? The idea of them sleeping together again? Or the equally ineradicable idea that they were nothing more than two more people who ought never to have slept together in the first place? He kept his mouth shut, which was about all he trusted himself to do. "I know that things have been—well, I don't know _what_ they've been. Sorry for babbling on like this. I know it's—shit." "No," William blurted. He instantly wished he'd just let her keep going; he wanted nothing more than her babbling on and on. But now she'd fallen silent and clearly expected him to say something. Panicked, he stared down at Cary Grant on the _Suspicion_ DVD cover. _Each time they kissed,_ the tagline read, _there was the thrill of love . . . The threat of murder!_ Cary Grant's lowered eyebrows bespoke a smoothness that William wished he possessed. "Good," he said, trying to sound Grant-like, "I'll let the doorman know you're coming." "William, you're the best," she sighed. "Don't mention it," he said, lifting the DVD. Irene sighed happily and ended the call. William texted his address to her phone and then rushed over to Arturo with the DVD in hand, hoping that if he hurried, he might be able to study a scene or two before Irene buzzed up. "One of Hitchcock's best," Arturo said, looking adoringly down at Joan Fontaine in her low-cut red dress. "Except for the ending, which RKO made him change—" But William could hardly hear him. He paid and left the store, thinking at first he'd buy some of the Bollinger Blanc she'd liked last time—or get a bouquet of roses that he could throw into a vase, only he didn't think he owned a vase—and moreover, this wasn't what Cary Grant would do, he was fairly certain. Cary Grant would never be so presumptuous. She said she didn't want him to think she had the wrong idea. Whatever else, that probably meant he ought to play it cool. Cool like Cary Grant. William left the video store feeling stone-jawed. This lasted two thirds of his way home, when he slipped on a patch of ice and slid into the branches of one of those Christmas trees out for sale on the sidewalk. • • • Irene went over immediately. She'd thought about going back to her place for his scarf, but she didn't want to waste time and risk him losing interest. William greeted her at the door and said he had just been watching an old movie and asked how she was feeling. But she cut him off—she didn't want to talk about that. She instead gushed that she _loved_ old movies and that she would have to insist they watch the rest together. She hated to interrupt when he was being so generous. But after an hour passed, sitting there on the couch watching Grant and Fontaine flirting, Irene found it difficult to focus. William's apartment distressed her. More and more, Irene felt as if she were watching the movie from the set of another movie. Not only was his place achingly coordinated in maroons and teals and mahogany leather, but it was filled with showroom-style homey touches. On one wall above a sideboard hung a gigantic bronze architect's compass, surrounded by framed black-and-white photos: a medieval cathedral apse, a Roman atrium, the gable of a seaside cottage. She was positive these were not vacation photos but the kind of black-and-white "art" pictures that you could get twelve for ten at IKEA. She was grateful that he didn't have a single Christmas decoration up, but she'd have preferred an evergreen to the inexplicable basket of neatly arranged branches that sat in the corner. It was like something you saw in a magazine, not anything that a real person owned. Steadily, she became convinced that she was sitting in the completely fabricated living room of a completely fabricated person. Irene excused herself to use the restroom, and William paused the movie. On the way down the hall she looked for evidence of a personality, photographs of friends or kitschy mementos, but she found nothing. William's family was Korean, yet she couldn't spot a single piece of art with any Asian influence whatsoever. She knew that he had studied classics in college, but the only Greek object she saw was a small urn, filled not with significant ashes but with potpourri that didn't smell of anything anymore. What sort of self-respecting bachelor owned potpourri? In the bathroom Irene found a mirror whose frame was strategically flaked of its paint, and a little soap dispenser adorned with tiny, irregular mosaic tiles, as if some artisan a millennium ago had carefully glued them onto a Crate & Barrel sanitizer pump. On the way back to the couch, she checked his bookshelf to be sure the spines had been cracked. She was relieved to find that, at least, William wasn't the full Gatsby. It didn't help that he himself was speaking like a movie character. "Could I pour you another glass of wine?" he asked when she got back. Once he did, he looked up as if he'd just surprised himself with the thought and said, "Pass me the clicker, if it's not too much trouble. The sound is a little _dim_ , wouldn't you say?" "You smell like pinesap," Irene said as she passed him the clicker. "Ah, yes. I had a run-in with a tree salesman out on the street. Nice fellow, though he shouted a bit when I ran off." "Are you being British?" she asked. That seemed to catch him somewhat, and his cheeks reddened in the way that she remembered. "Not intentionally, no. I suppose I should take that as a compliment." "Should you?" Irene asked under a sigh. William didn't hear, now the volume was up. When the movie was over, Irene was tired but too uncomfortable to sleep. She didn't want to stay in the false-living room. Nor did she want to go to bed with this false-William. "I think maybe I should go," she said finally. William looked sad. "Oh! Well. All right then. Wait here. I'll call for a car." "The city's full of cabs, William," she said. "Cabs and sidewalks and trains. Christ, what I wouldn't give to be on a _train_ right now." "Sorry if you didn't like the film," he said stiffly. "The _film_ was fine," she said. "You're upset." He frowned without quite pouting. "No, not at all," Irene said, getting up to leave. She didn't know just what sort of coaxing it was going to take to get him to relax, but she was pretty sure she had 68 percent less time for it now than she'd had a few weeks ago. It had been a ridiculous idea to come in the first place. "Where are you going?" he asked, as she was putting her boots back on. "Look, William—" "No, I mean, I get that you're leaving. It's just, you said you couldn't stay at your apartment tonight, and I know Sara said everyone was going out of town. I was worried that—well, do you have anywhere else to go?" Irene tossed her coat over her shoulders angrily. "You don't need to look after me, all right? I have _lots_ of places to go." This always happened. Guys—especially nice ones like William—were always trying to persuade her she needed to be taken care of. It was only the losers and fuck-ups who left her to take care of herself. She tried to remind herself that William didn't know her whole history. All the worse places she'd slept than a bug-bombed apartment, which hers wasn't even, though again he didn't know that. Her left arm kept getting jammed in the sleeve. She couldn't bend her elbow after all the blood they'd taken that afternoon, which only made her more upset. "I've got friends all over! I'm serious. I could walk over to Penn Station right now, get on any train at all, and I'd be _fine_." William was standing there, nodding, rocking a little on his heels. Irene had her coat on and was at the door. Was he really just going to stare at the floor and not say anything? "Well," Irene said finally, "what?" He looked up at her. "Well, what what?" "What are you _doing_?" she specified. He stopped rocking. "Sorry. Just thinking. Sorry." "What about?" "The film. Movie. The ending," he sighed. "Originally Hitchcock wanted Fontaine to write a letter to her mother saying she knows Grant's a killer but she loves him so much that she'll die for him. Then she drinks the poison, and it _would_ have ended with Grant mailing the letter. But the studio felt that it should end with a killer being brought to justice—so they forced Hitchcock to change it so Grant attempts suicide." Irene couldn't believe he was still talking about the film—movie. Whatever. "That's completely absurd," she said. "Right. I agree. Someone that confident and controlled would never consider suicide—" "No, _that's_ not absurd," Irene interrupted. "He's an arrogant prick. And killing yourself like that would be the ultimate act of arrogance." This brought out the red in William's cheeks again. "What I meant is it's absurd to think he could really kill _her_." The flush spread; Irene stepped closer to him and the couch. "In that first scene, right after I came in, where they're walking outside together and it's all very romantic and then he calls her Monkeyface, and she gets angry? No self-respecting murderer would call a woman Monkeyface like that. Hitchcock must have known that." Suddenly Mount Sinai felt miles and miles away. Irene looked into his dark eyes and said, "So I think you should hurry up and give me a nickname like that right away, so I'll be sure you're not a murderer." William laughed. "I can't! You're, well, um—too beautiful to make fun of." She stepped back a little. She hated that word. _Beautiful_. It meant nothing; it was too unreliable. What if they took out her eye? If her hair fell out in chunks? If her facial muscles lost their grip? Would he still say she was beautiful? But William kept going. "I guess, if you pressed me, I'd say your face is a little . . ." "What?" Irene urged. "Come on, I can take it." "Well, it's your ears, actually. They're really tiny. It's almost like they're trying to climb back into your head." "They are not!" she shouted, jumping up to find a mirror. "They are too. You've basically got no ears." " _No ears?_ " she shrieked at her reflection in a black-framed mirror without any discernable character, but it wasn't her ears she stared at. It was him, behind her, smiling shyly. She turned and he grabbed her, and they collapsed together against the couch. "Don't worry," he said, pushing her hair back as if to study her more closely. "It's really very becoming, No Ears." "You take it back!" she shrieked. Gently he brushed her hair back and kissed one of her allegedly nonexistent ears. "There they are!" he exclaimed. "There _you_ are," she said. At last. • • • Irene slept heavily on top of William, right there on the mahogany leather couch, and he didn't dare budge for fear of waking her. She'd told him all about her day at the hospital and the first treatment, which would begin in just a few hours. Just before she'd nodded off, he'd made the mistake of asking why she didn't have any family to visit for the holidays, or to take her to the hospital, for that matter. _I left home when I was sixteen,_ she'd explained. _I won't get into all the reasons I had to go. I just never belonged there. People get born into the wrong families sometimes. Just like souls wind up in the wrong bodies occasionally. I have a very old soul. I think my soul belongs in the body of someone who's already a hundred and ninety-five._ William couldn't quite tell if she was kidding, but in the shadows, he could imagine her on top of him, all wrinkled and bird-boned, with hair as gray as moonlight. _Not like you_ , she'd continued. _Your soul's very young. It's a boy's soul. Now don't be angry—see, that's just what I mean—there's no reason to be angry. Your body's plenty manly. But inside you're boyish. The way you took my clothes off, for one example. Kind of awestruck. Slow. It's what I like most about you. Your soul is so boyish actually that it is almost girlish._ He hadn't reacted especially well to this comment, and he regretted it now, as he lay there, replaying it all, and watching her dreaming. _So?_ she'd replied, _I like a girlish soul. And a girlish body too, if we're going to be honest. In fact, you should feel special because I haven't slept with many boys. Far more girls than boys. _ William hadn't covered his surprise at this well either, and he was so flustered that he didn't shift his lap away from Irene in time to cover his inevitable reaction to the idea of Irene with another woman. _You see?_ she had teased. _Boyish._ Later, he asked again about her real family, and why she'd left them, but she was either pretending to be falling asleep or really nodding off. _I left them because they weren't my family_ , she mumbled. _I thought Alis-ahh was my family, but she said I was always leaving her._ These were the last words to fall from her mouth before she slept. William wasn't sure he'd heard her right. What sort of a name was "Alis-ahh"? Had she said _Alissa_ or _Alicia_? Had he misheard? So he sat, awake and unwilling to move, until the sun rose up over Queens. • • • Irene woke up at seven, vaguely aware she had only an hour to get to the hospital to begin her first day of treatment. She'd had one of the strangest dreams of her life—Dr. Zarrani had said it wasn't uncommon for cancer patients to get them. Dreams like full-on acid trips. Surreal visions that didn't always end right away when she woke up. The doctor had called them "healing dreams" but hadn't explained what exactly was healing about them. Irene barely had time to think about it, however. She was hectically running around the apartment. When William asked why, she told him she had to get ready for her first infusion. "Just wear what you had on yesterday," he said. "That's—don't be ridiculous." She thought about taking back what she'd said about him being girlish, but she thought that might please him too much, and besides, when she opened up his wardrobe (made of real wood that was faux-weathered), she discovered that his closet was filled with clothes that she could easily wear. A pair of jeans that must not have fit William since college were a bit torn in the knees but looked quite good on her with the cuffs rolled and a yellow necktie as a belt. She spotted a pink dress shirt and rolled the sleeves around her elbows, cinched it in the back with a rubber band, and tucked that into the waistline of the jeans. "If I didn't know any better, I'd think you had a girl living here with you," she said, detaching a silvery pull cord from his window shade and retying it as a necklace. "We're going to a hospital, No Ears. What does it matter what you look like?" William groaned. She saw his eyes were sunken and bleary. "It's my first day, I have to make a good impression! Do you have any makeup?" "Why would I? Let's go! You look beautiful!" "What did I say about that word?" she chided. "Come on, you don't have anything? Who doesn't have some concealer lying around for bad skin days? Or some lipstick a girlfriend left somewhere?" She eyed him curiously as she lifted a white panama hat down from his hat rack. "I know you've had girlfriends. Don't tell me you bought this for yourself." William placed it on her head. "It was a gift from my mother." Irene took the hat off and studied it. "It's excellent. I'd like to meet this woman." "If you will hurry up and get to your appointment, you can meet her tonight." Her eyes widened. She hadn't expected him to take her up on it, but suddenly she wanted to meet Mrs. Cho very badly—if anyone could help uncover the real William beneath all this showroom furniture, it would be her. He went on. "We're having a big family dinner for Christmas Eve. You'll love it. It's like my own personal circle of hell." Irene clapped eagerly. William began to say firmly, "If you keep delaying and we miss your appointment, then we'll never get there in time . . ." but Irene was already halfway out the door. • • • They made it into the hospital just in time, and Irene enjoyed the holiday decorations much more now that William was there to look aghast alongside her. After filling out some more paperwork, they met with Dr. Zarrani, who guided them around the chemotherapy suite as if it were an apartment they might be interested in buying. "No elves or reindeer in here!" Irene said. "The design was done around the concept of a Japanese Zen garden," she said. "You come in over here past the waterfall sculpture to check in each morning." All the light came from great brass lanterns, and to one side of the waiting area was an actual sandbox filled with rocks and little rakes, which two children were busy attempting to demolish. The tables, covered in magazines and catalogs, were all made of polished stone, and trimmed bonsai trees divided the waiting area to make it more peaceful. Dr. Zarrani stood stiffly. "I know it seems silly, but studies have shown an improvement in patient recoveries." William balked. "What, like through some ancient Shinto magic or something?" The doctor led them back into the infusion area. "It has to do with the patient being more relaxed and inspired to face the hard work ahead." "Aesthetics are important, William," Irene snapped. "Hence, why I wanted to look nice." "You look _very_ nice," Dr. Zarrani said to her as William raised his hands in apology. "Now take a seat here by this blue . . . pagoda thing. The nurses will be out soon to begin you on doxorubicin and cisplatin. It takes a few hours, so I hope you brought a good book." Irene eyed the nearby _Vogue_ s and _Cosmopolitan_ s suspiciously. She'd read the same ones yesterday in the waiting room. "I can run out to a bookstore and find you something," William offered. "Well . . . ," Irene said, looking mischievous as she pulled a heavy volume out of her purse. "I took this off your shelf this morning. I hope that's all right." He did look a bit startled at the sight of his copy of the _Iliad_ , the Jacob-disapproved-of Lattimore translation, surely filled with old college notes and underlinings, but he shrugged, not knowing, Irene was sure, that the notes and underlinings were precisely why she wanted to read it. "Can I wait here with her?" William asked the doctor. "For eight hours? Don't be absurd. Go buy your mother something for Christmas. And get some sleep. I know you were wide awake all night." William wanted to stay until they started, but Irene wouldn't hear of it. "You go or I go," she said. So William went. Dr. Zarrani came in to start the drip. "The doxorubicin distorts the shape of the helix, which prevents it from replicating, and then the cisplatin binds the DNA to itself, which triggers a kind of self-destruct order inside your cells." Irene felt her nervousness quieting in the comforting hands of the doctor, as she scrubbed the crook of Irene's elbow with a cotton ball soaked in yellow antiseptic. Irene had thought that they'd inject something into her face, not her arm. "How do the drugs know to go from there all the way up to my eye?" "Unfortunately, they don't," Dr. Zarrani explained. "Normally we'd do surgery first, but in the interest of not damaging your eye, we'll start with this and hope it shrinks the tumor a little. The chemo drugs go into your bloodstream and go everywhere. They'll get the tumor but also everything else." Irene sat up straighter in her chair. Not a surgical strike then, she thought, just a full-on scorched-earth policy. And then she remembered her dream from the night before. She'd been crawling, for what seemed like hours and hours, through a barren desert. Finally she'd come across a great black leaf, and she'd hidden in its shade. But once there, safe, something very strange happened. She'd begun to spit, uncontrollably. Great threads of saliva flowed uncontrollably from her mouth, and she'd felt drier than ever as she'd writhed about, trying to stop. Only when she'd thought she'd desiccate completely like a mummy in a tomb did she realize the great threads she'd released weren't saliva but silk. And while she'd been writhing, she'd inadvertently, or perhaps instinctually, woven this silk into a great shimmering womb, its walls glistening with cool dew. She'd been just about to climb inside and sleep for a thousand years, when she'd woken up on top of William. "Now this will sting a little bit," the doctor said. There was a terrific pinch, and then Irene could feel something alien inside her arm. It would be there for hours, and she would keep on feeling it there, long after. • • • William had already found gifts for everyone in his family except his mother. So he stopped at a Salvation Army a few blocks from the hospital, where he spotted an enormous and truly heinous pink vase covered in golden chrysanthemum blossoms, on sale for five dollars. The gift itself wasn't as important as how little he'd paid for it. Any present that came from a retail store she'd return later and then complain about how much money he'd spent. Always she had seen the _exact same item_ for a tenth of the price at some church sale just a few weeks earlier. As a boy, he had once spotted a beautiful silk kimono on sale at the gift shop of the Guggenheim, where he was taken on a class trip to see an exhibit on Eastern Art. He'd sold his collection of Aqualad comic books to Mi-cha Yu so he could buy it. But then Christmas morning arrived and his mother opened the gift. "What is this?" she'd asked, so he'd told her, "A kimono" and she'd given him a withering look. "Kimonos are Japanese. We are _Korean_." She'd dragged him all the way back to the Upper East Side to return it, but since the Eastern Art had gone out and the Monets had come in, they no longer stocked the kimonos. Furious, his mother had flung it deep into a guest-room closet, where it hung still. William walked down Third Avenue with the vase under one arm for blocks and blocks, trudging over the snow that was still unshoveled in many places. As cold as he was, William kept on walking without fully thinking about just where he was heading, though his feet seemed to have some idea. The storefronts were quiet; the roads were empty. It wasn't often, he thought, that you got to have the city to yourself. By the time he realized where his feet were taking him, he was far closer to Fourth Street than to the hospital, where he knew he ought to turn around and go. Something about the way that she had taken his _Iliad_ off the shelf had struck him, as if it actually belonged to her. Without thinking, he had found himself lifting the keys from her purse while the doctor had been explaining the chemotherapy to her. He'd thought he could surprise her—run inside, despite the bug-bombing, and bravely grab a bag of clothes to wear to dinner that evening. She couldn't show up wearing William's old blue jeans and a necklace made from a curtain chain. As he came down Avenue A toward her block, he told himself that she'd be delighted. But by the time he got to her building, he knew he was kidding himself. Irene would surely _not_ appreciate what he was about to do, but his mind was unquiet with questions. Where was she from, and why had she run away? The thought that maybe she had been abused, or worse, was difficult to push aside—even though she'd assured him it hadn't been that. Who was "Alis-ahh"? Had he even heard her properly? Was she one of these girls that she claimed to have slept with? Irene's building was a crumbling brownstone with trash cans around the entrance that were chained up and overflowing. The ground floor windows were covered with boards, and the boards were covered in long-faded concert posters. He opened the door and walked up three flights of crooked stairs; the railing became more bent the higher he climbed. Hadn't she said her whole building was being fumigated? There was no sign on the front door, and he could hear people in the other apartments. He climbed all the way to the fifth floor and came to her door, expecting to find a department of health sticker, or caution tape on the knob, but there was nothing out of the ordinary. The cheap vase still tucked under his left arm, he slowly unlocked the door and stepped into Irene's apartment. Looking around, William could see haphazardly discarded blankets and workout clothes heaped on the floors and over the top of the bathroom door. The apartment was filthy, from the overfilled sink to the paint-peeled ceiling. He stepped over the remains of a Sunday _Observer_ and several brown boxes filled with flea market objects: glittering marbles, rusty doorknobs, a tangle of wiring, old movable type letters, several novelty wristwatches, bookends shaped like cartoon faces, dozens of Barbie dolls still in their individual packages, empty mirror frames, children's soccer trophies, and a plethora of silk flowers. He was just about to ask himself what on earth it was all for when he saw the far end of the room. The end nearest the window was relatively cleared of junk. It seemed to be a working area. Sketch pads lay open on a low coffee table, with pages covered by rough lines of blue ink. Against the paint-flecked walls of the apartment were perhaps a dozen paintings of different cities and landscapes, neatly stacked from smallest to largest. Badlands and prairie grass. Arching, shadowy bridges and marshes at twilight. An Albuquerque desert and an icy Alaskan plateau. Against the opposite wall were several half-finished collages and combines, made from odds and ends. Marbles, painted like eyeballs, were pressed into putty, numbers and bits of maps were connected by hairy bits of yarn, above a backdrop of still, mounted butterflies and gigantic death's-head moths. It was all assembled on a heavy plywood base. William thought it looked like a corkboard belonging to an elegant serial killer. William looked through a few of the dresses on the floor but couldn't tell which, if any, were clean. He noted her size on one of the labels, thinking that if he just bought her a new one, he wouldn't have to admit he'd broken in. Didn't you have to put things away if someone was spraying for bugs? Wouldn't it smell weird, only half a day later? The more he thought about it, the surer he was there had never been a pill fly infestation. But why had she lied to him? If she had just wanted to come over, she hardly had to make up a reason. She must have known that. Just then he saw a box wrapped in white ribbon, with a card on top that said "For William." He picked it up and gently shook it, but there was no rattling inside. What could it be? Should he have bought something for her? He wanted to open the box, but then she'd surely know he'd broken into her apartment, so he set it back down where he'd found it. His eyes fell on a brass birdcage by the window that was filled with jewelry boxes. He stepped lightly over to the cage and carefully searched for any kind of door. Puzzled, he reached through the bars, but they were barely spaced enough for a single finger to go in and fish out an earring or a necklace. "How the hell did you get the boxes inside?" he asked the empty room. Then, just as he was about to back up again, he noticed a small book covered with soft black leather, wedged between two of the jewelry boxes. He tried to snag the book, but no matter how he tipped or turned it, it wouldn't pass between the cage's bars. Sweating despite the pervasive chill in the apartment, he stood on his tiptoes to try to make out what was inside. If he squinted, he could just see what appeared to be—yes, names and addresses! An address book! Perhaps, somewhere inside there was an entry for an _Alissa_ or an _Alicia_ or an _Alis-ahh_. _Where on Earth are you from?_ he asked as he tried to flip the pages through the bars. _Who_ are _you?_ Then the book slipped a bit from his hand, and a half-dozen black-and-white photographs slipped out and fluttered to the bottom of the cage. There were some old train ticket stubs in there too. William felt around to gather them. Baby photos? Old school photos? A bucktoothed, no-eared middle-schooler, not yet run away from home? William had to crane his neck awkwardly in order to see clearly, but by bracing his foot against the windowsill, he was able to inch upward a little further and get a good look at—Irene's naked body. William dropped the photos in his surprise, and they fell again, some now outside the birdcage, getting utterly and hopelessly out of order. Extracting his hand from the cage door, he bent over to scoop up the risqué photographs. Irene's body was ethereal and light against dark sheets. The poses were seminatural and rather unpornographic. In one, her breasts were exposed but blurry, the focus on her lips and the tip of her nose, her eyes crossed daringly as she studied the ash trembling at a cigarette's end. In another, she twisted sideways in a black river of sheets as if it were carrying her off. In a third, Irene lay with her back to the camera, eyes fixed out of a window, as if she were planning an escape. William could see the photographer's apparently female hand reaching out at the bottom of the frame, as if trying to coax her back. He flipped the photograph over and saw handwriting—not Irene's: _Tu es toujours sur le point de me quitter. —Alisanne_ Alisanne! That was the thing, the name she'd been saying as she fell asleep. He fumbled with his phone a minute, typing the inscription into Google. It struggled a little until he found a second bar of signal closer to the window, at which point it spat out the result. "You are always about to leave me," he said aloud to no one. William had had enough. He stacked the photographs together again as neatly as he could, slipped them into the back pages of the address book, and wedged the whole thing between the jewelry boxes again. _It's too much,_ he told himself, as he stepped out of the apartment. "It's too much," he said to himself. _It's too much._ Shutting it all behind him, he trudged back down the half-collapsed staircase and pushed out onto the snowy sidewalks of East Fourth Street. He made it all the way to Fifty-third Street before he changed his mind again. By Seventy-eighth, he saw a high-necked red dress in a shop window. He bought it and had it gift-wrapped. • • • Irene thought she'd never been happier than she was walking down the streets of suburban Flushing with William's arm on her recently bandaged one, heading toward the home of Mr. and Mrs. Cho. William was flustered, she imagined because they were late. Still, she didn't even mind that he'd asked her "How do you feel?" five times and "Are you feeling all right?" six times since she'd checked out of the hospital. For she was telling him the truth: she felt _spectacular_. In the eight hours she'd been stuck in the chemotherapy chair, she'd done five preliminary sketches for new sculptures, read six chapters of the _Iliad_ (and William's touching accompanying thoughts), and—the pièce de résistance!—had found a certain page twelve of the fall 2007 Pottery Barn catalog. " _J'accuse!_ " she'd cried, when he'd come to collect her at the end of the day. She'd flung the open catalog into his worried-looking face. "How do you feel?" he'd asked, batting it away. "I feel," she said with a deep breath, " _incredible_." William looked confused and studied the catalog a moment. "I don't understand." "This is _your_ apartment, William! What—did you just pick up the phone and call the eight hundred number and say, 'Give me a page twelve, please'?" He blushed again. "Not exactly _,_ I—" "William!" she cried, pulling at her hair with both hands. The other patients in the room were staring at them, delighted for a bit of real drama after several dull hours of talk shows. "William, you are a _person_! You possess, within you, a person _ality_. A personality that can—no, which _must_ —be expressed in the things that surround you!" She lifted up his copy of the _Iliad_ like a battle-ax. "Listen to this, Mr. Cho! 'If the gods actually know our fates and still try to meddle and wage their wars in us, then there must be some purpose in our _choosing_ one of the many paths to that end. Man must have free will, or else why would the gods themselves bother?'" "So?" he'd said. "Just some notes. They don't mean anything." "They mean," Irene shouted happily, "that you aren't a page twelve, William Cho!" This victorious cry still rang in her ears as she rushed arm in arm with William over the icy pavement, wearing the new red dress that he had bought for her as a Christmas gift. Somehow he had managed not only to select something she might have bought herself but also to get the proper size. She wondered if he had slyly checked the label on her clothes the night before as he'd undressed her, already planning this gracious surprise. And as he fumbled with the stack of gifts beneath his arm and hurriedly tried to warn her about his parents, she felt that he was her very own dark horse—that she would bring him out of himself and into the world, just as she had been herself, once. "My father is quiet. Silent, generally, so don't be offended if he doesn't say anything. And my mother is—strange. She works in the community here as a sort of a healer, I guess. Not like a doctor. It's a family thing—back in Korea her mother was a _mudang . . ._ like a shaman-kind-of-medicine-woman-kind-of-thing. So she's bonkers, basically. I don't know. She thinks she talks to spirits and gods, and people pay her to, like, channel—" "William. Everyone's got a crazy family. Take a breath." "Well, not all of them speak to the dead, that's all I'm saying. Actually there's one other thing," he whispered as he stood awkwardly a few inches from her. "My parents won't like it if they think we're dating. Because you aren't Korean. Not that we are dating. But we should make sure they don't think we are." Irene knew she ought to be upset at this but simply couldn't feel it. She looked at him mischievously. "You know I'm just using you for your body." Again William turned six shades of red. She dragged him up the steps of his own house and rang his doorbell. In moments they were greeted by a tall woman who studied them from behind the screen door. "Come in, hurry!" she said. "You'll get caught in the storm!" "It's beautiful out!" William said as she took the presents from him and bustled them both inside. Irene looked up at the sky, which was soft and pink from the cast-off light of their city. There wasn't a dark cloud anywhere in sight. Inside, they took off their coats and laid them on top of an old washer and dryer, atop a heap of others. Irene shook Mrs. Cho's hand, which was covered in large rings. As the woman turned to address her son in stern Korean, Irene was delighted to see that the woman's hair was dotted with more of these tiny rings, glinting like silver salmon backs leaping upstream. "Mom, this is Irene." William said. Mrs. Cho looked up at her. "We are so glad you could come. It's always good when William has a friend." He blushed. "I love your hair," Irene said to Mrs. Cho. She blushed, a slighter shade than her son, and gripped Irene's hands between her own pair, giving them a shake. She seemed about to say something when she pulled away, her eyes filling with curiosity and worry. "Not feeling well?" she asked. Irene tried to smile. "I've never felt better, Mrs. Cho. Honestly." But Mrs. Cho stood there, lips pursed, inspecting Irene as if she were a thin crack in a wall that might get larger. William hissed something at her in Korean, which she ignored, and then he hissed again, and she sharply spoke back to him without taking her eyes off Irene. Something about it made Irene feel as if she were back at the hospital, being scanned in the echo chamber of the MRI machine. She felt a quick dizziness, as if the tiles beneath their feet had lurched an inch upward, and then it was gone. Mrs. Cho reached up with one ringed hand and seemed about to clap Irene on the shoulder, when her thumb flicked higher, passing directly below her left eye. Irene's hand jumped up nervously and brushed Mrs. Cho's hand away. Awkwardly, Irene pretended to be picking at an errant eyelash, as William barked at his mother, and she finally stepped back. "I hope we haven't missed dinner. It smells incredible." Something about the look in Mrs. Cho's spectacled eyes continued to make Irene uncomfortable as she said, "We are just sitting down!" and graciously led them into the next room. Irene tried to settle herself, cooing over a hung portrait in the family room of young William and his brother, dressed in some sort of ceremonial garb, but the deeper into the home that she got, the harder she felt it was to draw in a proper breath. Following the glinting rings in Mrs. Cho's hair, Irene had the oddest sensation of descent, as if the room were on a slight slope, and they were all leaning a bit against it in order to stay upright. They paused at an open double door, through which Irene saw a great library filled with books, and a Christmas tree in the far corner surrounded by presents. Mrs. Cho stepped inside to leave the presents that William had brought, while they both spoke more amiably, in their private singsong language. Irene closed her eyes a moment and tried to pierce through the spicy, strange scents that were coming from the dining room and breathe in the evergreen. But all she could make out was dry sawdust. In the dining room they found the rest of the Cho family, and Irene was quickly introduced to Mr. Cho (who gave a warm grunt but spoke not at all) and William's older brother, Charles, who sat with his wife, Kyung-Soon, and their daughters, Charlotte and Emily. The girls chirped to each other as Irene was seated beside them. Emily seemed not quite able to look at her without immediately looking back down at her coloring book, whereas Charlotte couldn't seem to look at anything else. Irene shook everyone's hands, and there was jubilation as William and his brother began to catch up on something or other. Spread out on the table was a colorful and strange feast. Irene had ordered Korean takeout food before—kimchi and bibimbap and rice cakes—but she had never seen any of these dishes. Crispy brown pieces of grilled pork, cucumbers stuffed with something crimson, and a plate of spongy-looking squid caked in sesame seeds. In the center of the table was an enormous snapper, its red scales seared brown from careful grilling, but its head still on and staring slack-jawed at Irene as she tried to get comfortable. Ordinarily, Irene loved trying new foods, and everything smelled mysteriously delicious, but the uneasiness grew inside her gut as she sat there at the table. Before she could quite get talking to anyone, Mr. Cho looked backward and began addressing a painting of Christ on the cross that hung on the wall above his chair. Irene wasn't quite sure what was happening until she saw everyone lowering their heads, and the shy hand of little Emily gripping the edge of hers. Mr. Cho began to pray in a croaky tongue. Irene closed her eyes and tried to feel grateful—for the food, for the company, for the dress even, but somehow these thoughts were hard in coming. She never felt comfortable praying. She always felt like a liar, afterward. Once Mr. Cho was finished, they all continued to chatter in Korean. Irene could barely detect the tone, let alone the meaning. It made her a little dizzy at first—and then a lot. Just minutes ago she'd never been happier; she tried to trace her steps back to it, but the way was lost. The crook of her elbow stung where the IV tube had been. There were still little black smudges outlining the places where the tape had held it down. She picked at the sticky edges. The lump beneath her eye was sore, and it made her wonder if the cisplatin and the doxorubicin were already binding with the tiniest and most intimate fibers of her being. It was _surely_ in there and in everywhere, from the roots of her hair to the soles of her feet. The nurses had warned her of dizziness, irritability, and nausea. She tried to look delighted as she was at last introduced to Charles and Kyung-Soon. "Charles is my older brother, and of course, he's a doctor, so my parents like him best," William explained. "It's true," Mrs. Cho shrugged mischievously Charles tried to wave this away. "William's the one who got into Yale." "You went to medical school!" Kyung-Soon squeaked, as she passed Irene a bowl of a magenta soup filled with clams, shrimp, and tofu delicately carved in the shape of small fish. "In Rochester," Charles teased. "Irene, if you ever want to see a fish out of water, find a Korean in Rochester." She politely stirred her soup, watching the fish swirl around in their lava sea. "I spent a little time near Rochester, actually. On this farm just outside New Hope?" "New Hope! Christ, what were you doing out there?" There was a quick volley of Korean as, Irene gathered, Mrs. Cho reprimanded her oldest son for taking her Lord's name in vain. Mr. Cho said nothing but gestured emphatically to the painting of Jesus. Charles raised his hands again in defense against the barrage of strange words, fired at him like pleasant bullets. "My stars," Charles corrected himself in a genteel falsetto, "whatever were you doing on a farm outside of New Hope?" "Farming?" Irene grinned, despite the faint but blinding halo that was forming around the chandelier above the table. "William said you were an artist of some sort?" Kyung-Soon piped sharply. William explained, "Irene's a bit of a Jack-of-all-trades." "A Jane-of-all-trades," she offered, and was met with a rapid-fire exchange in Korean. Irene couldn't tell what they were saying, but brotherly teasing was the same in any language. Mrs. Cho's mouth opened, and she began to smack her fork in the direction of her two sons, trying to get them to behave. "What's going on?" Irene whispered to Emily, who was scribbling with crayons. Charlotte whispered, "Daddy says you are Uncle William's girlfriend." Irene raised her hand to her mouth playfully. "Uh-oh!" Emily began to giggle but still wouldn't look at Irene directly. In her coloring book was a blue Santa with a golden hat. The rest of the family was still arguing, and Irene was trying to remain composed as best she could. Outside, the wind was picking up, and the girls watched eagerly as fresh snow began to fall. A few flakes at first, and then great curtains of white. "Have you been good? Have you asked Santa Claus for anything?" Charlotte immediately began to tick off a grand list of the things she'd requested of Harabeoji Santa in exchange for her sterling behavior: several dolls of very specific brand and style, nail polish like her mother's, a big-girl bicycle, skis, an elephant (of what size, she didn't explain), and a dress like Jill in her homeroom had. The list went on and on, and Irene pretended to be very interested as she ate her soup and watched Emily shading delicately in her coloring book. She sang softly to the crayons as she plucked them from the flimsy box and inserted lilac trees and ghosts into a sleepy, snowy town of Bethlehem. "Could I?" Irene said slowly, taking a red crayon out of the box. Emily studied her with eyes like her grandmother's, penetrating and large. Then she allowed Irene to shade in a small barn on the edge of town. It was only when she looked up and noticed William staring at her that Irene began to feel dizzy again. "Are you okay?" he mouthed, not subtly. She waved, even as she felt the room lurch a few degrees clockwise and back again. "I call a cheek!" Charles shouted eagerly. Irene looked over in time to see that Mr. Cho was carving up the gigantic snapper and passing portions out to his sons. William protested. "The cheek's the best part! Irene should get one—she's a guest!" "She's _your_ girlfriend. Give her yours." They began to bicker again in Korean, and Irene graciously accepted the delicate cheek meat that Mr. Cho placed on her plate. It was only then that Irene noticed Mrs. Cho was leaning over the carved fish, rolling her ringed fingers lightly over the bony carcass, and _singing_ something. "What is she doing?" she asked Emily breathlessly. "She's a witch," Emily whispered, the first words she'd spoken aloud all night. Irene was about to say that it wasn't nice to say such things about one's grandmother, when Mrs. Cho ran the tip of her knife along the scaled, pink face of the fish and, with a gasping sound, plunged her fingertip into the small gap behind its eyeball and popped it out. Irene lost her balance, just for an instant, but that was all it took. She felt her whole stomach heave inside her, a ship tossed in a tempest of bile. The pink, glassy fish eye rolled an inch or two like a wobbling marble, leaving a translucent trail behind it. Irene tried to clamp her mouth shut. She felt something rising inside her, boiling against gravity, up her esophagus. She grabbed her napkin and held it to her lips, her throat flexing and seizing. Charlotte shrieked, "Groooooossssssss!" Irene was able to keep herself from vomiting all over the table, catching a little with the napkin and choking the rest hotly back. William was shouting at his mother, who was still singing and going for the other eye now. Charles and Kyung-Soon were shouting at Charlotte. Even Mr. Cho was barking something, apparently back at the sympathetic Christ above his head. Irene felt Emily's small hand squeezing on her wrist, not in panic but in comfort. She had a look, as if Irene were her doll and Emily meant to drag her to the other room to safety. But Irene couldn't keep her eyes off the fish, from Mrs. Cho's knife as it fumbled at the edge of the other pink eye. The tip of the knife again slipped into the space between ball and fish skull, and with a squishy _pop_ , the second eye was loose and everyone was silent. Calmly, Mrs. Cho plucked the two eyeballs off the tablecloth and placed them onto a small white side plate. She looked up at Irene and politely offered her the plate. Irene took a deep breath, feeling a bit steadier as she stared down at the plate's two gelatinous passengers. "Eat these," she urged kindly. Then, as if confused that Irene didn't understand, Mrs. Cho added, "They'll make your eye better." Irene covered the spot under her eye and looked over at William with no small amount of horror. William, speechless, just waved his hand at his mother to put the plate down. "Ew. _Total VOM_!" Charlotte snapped. "That's like the grossest thing ever." "They're considered a delicacy," Charles said, trying to lighten the moment. Irene knew she was a guest in the home of another, but surely this was something beyond grace. And why exactly was she wasting so much time and energy trying to be gracious anyway? She was exhausted. She could feel wet splotches on her red dress, where drips of vomit had gotten past the napkin. Now she would have to spend the whole ride home marked with stains. What had she done to deserve this? This, which was the cure? What had she done, even, to deserve the disease? So why was _she_ sorry? She should be alone in her apartment with no tree and no fireplace and no presents and no family. She was full of poison. She wanted to be quarantined, sent to Siberia, put out on an ice floe. She'd stayed too long in the city. She'd forgotten to keep running, and now Death had caught up to her. Now He stared at her, from the surface of a porcelain plate, through these two roseate eyes. Irene reached out and plucked the fish eyes off the plate. She held them in the open palm of her hand like a pair of dice. Then she popped them both into her mouth and bit down against their jellied circumference. A bursting of fishy goop clung to the back of her tongue. Charlotte screeched again, and William stared in horror. For a moment, Irene thought she might throw up again, but something about Mrs. Cho's gaze kept her stomach still. Just then she felt a small hand, Emily's, patting the belly of Irene's dress. _There, there,_ she seemed to be saying. _Isn't that better?_ • • • The storm outside was far too heavy for anyone to leave that night, so William set Irene up on the pullout couch in the study. They waited until the girls had placed a bowl of black bean noodles on the edge of the fireplace for Harabeoji Santa, and then when they were safely asleep, Charles helped William build a fire in the fireplace. William apologized for the five hundredth time since dinner. Irene was back to acting normally, back to pretending that everything was "Fine! Absolutely fine!" but William knew better. He could see the panic behind her eyes, even after his mother brought down some old clothes for her to change into. "I wish you could sleep down here with me tonight," Irene said, pouting. But William could feel it—she was lying. There was this imposter look about her; it was hard for him to put his finger on. It was the way she'd sounded when she'd first called. Like Joan Fontaine in the movie. "We'll have to leave tomorrow for the hospital before the girls are even up to open presents. But I have something for you," William said, taking a rectangular pile of silk out from the pile of extra clothes that his mother had given him for Irene. "Merry Christmas." "Oh, William," she moaned, touching it. She unfolded the parcel, and it became a beautiful silk kimono, covered in butterflies and weeping trees and winding rivers. "It's—" "It's a little old," he apologized. "But I promise it's never been worn." Irene began to cry a little, and William couldn't think why. He moved in to comfort her, but she pulled away, as if she were contagious and might infect him. "I feel awful," she said. "I bought you something but I left it at my apartment." Irene slipped the loose kimono on over the billowing pajamas that Mrs. Cho had given her. William was stunned at how beautiful she looked in its folds. There were tears in her eyes. "I'm sorry," she said, kissing him on the forehead tentatively, as if she weren't sure it wouldn't leave a mark. "What for?" William asked. And though she had lied to him over and over, and though she had refused, again and again, to tell him the truths he wanted her to tell, he said, "You've done absolutely nothing wrong." "Give me time," she said lightly, as if it could be a joke. He left her there and went up to his old bedroom to sleep. In the morning, she was gone. The only sign of her was a little water on the floor by the front door where the snow had blown in on her way out and then melted. William took the subway back down to her apartment, but the main entrance was locked and no one answered. He followed someone through the front door, went upstairs, and pressed his ear up against her door. It was ice cold, and there wasn't a single sound inside. He called the hospital, hoping, but the nurses there said she hadn't shown up yet for her appointment. Dr. Zarrani called back, worried, and told William that if Irene didn't come in for the second half of her dose, they'd have to start all over again. She asked him if he might know where she would go. Was there anyone else she might be staying with? William said he didn't know, that he didn't really know that much about her. He didn't know where she was from. Would she go to Sara's, up north? Then he thought about the photograph and its inscription. He hopped in a cab and asked the driver to take him to Penn Station. The train station was empty on Christmas morning. Silence hung in the open terminal like a kind of fog. Most of the shops and restaurants were closed, their grates rolled down and locked tight, garlands hanging heavy above the archways, as if they knew that by the next morning they would be taken down and thrown away. William found Irene sitting on a bench, still wearing the stained red dress. She sat by the big clapboard train schedule, reading William's copy of the _Iliad_. She looked up at him when she saw him coming. "Can't you leave me alone?" "Dr. Zarrani said you have to come in before noon today or they'll need to start over." Irene shook her head and clapped the heavy book shut. "I'll call her." "To tell her what exactly?" "That I'm going away for at least a month, maybe more. I'm sorry, William, we both know it wasn't going to work out with us. I can't explain. I'm just like this. I'm—" William looked down at his phone and read off the words he'd translated the day before. _"Tu es toujours sur le point de me quitter."_ Irene frowned as William sat down on the bench next to her. He knew he had badly mispronounced the line. "I went by your apartment to get you a dress the other day. There weren't any bugs. And I saw the gift you got me . . ." "It's a scarf," she said softly. "And I saw the dirty pictures in your birdcage. I saw what that girl wrote to you." Irene didn't seem upset or violated. She just looked tired. "See? It's not just you, William." "I actually wouldn't have thought that it was." She looked up at him. "Oh, no?" "No," William said, and then kissed her forehead once before patting the book as if to say goodbye to it. "I didn't think I mattered that much to you, No Ears." He hadn't really meant it to be cruel, only true. There was nothing about her that belonged to him. Everything he knew about her, he'd stolen. • • • Irene watched William walk away, and then for several more minutes she watched train after train departing. There was one heading for San Francisco, but she didn't want to go there, not really. She didn't want to go to Boston, St. Louis, Raleigh, or Chicago either. She'd been to all those places before, and there were other Williams in each of them. Irene kept reading about Ajax and Hector and Priam. Warriors lacing their armor on for battle in one refrain, only to lie slain and forgotten in the sands of the next. All for some "beautiful" woman whom none of them really cared about at all. Irene flipped backward and forward. The men all died and died again. Trains arrived; trains departed. Irene flipped to the page where William had written his note. Was there some God or gods who knew her fate? She stared up at the wide empty space above the clapboard. Bakersfield. Albuquerque. Pittsburgh. Burlington. Two dozen tracks to the end. Twenty-four places to die. _Man must have free will,_ William had written, _or else why would the gods themselves bother?_ She sat up straight and closed the book. She rested her hand on her hip. There was still a faint fishy taste on the back of her tongue. She stood up and walked past the tracks to the tunnel for the subway. She rode to the hospital. She apologized to Dr. Zarrani and said there had been an accident on the 5 train and she'd been stuck, underground, for an hour. The doctor said she'd make some adjustments, but they hadn't lost too much time. Before the nurses hooked her up to the IV, Irene changed into the kimono. Its loose arms fell gently over the elbow where the tube went in, and she felt a great freedom as she drew and drew, nothing but fish eyes. Cold, with dead black pupils staring out at her. When the dose was over, Irene took the subway home, and was so flushed she had to pull her coat open with only the kimono underneath. People stared, but she didn't care. It was New York, and there were stranger people than her in every neighboring car. The thought comforted her. She had already arrived in the place she belonged. Once she was safely inside her apartment, she turned on the heater. There was a loose thread at the sleeve of the kimono that had been tickling her all day long. She tugged, and more silk came away in her hand without breaking. She pulled and pulled at the thread for minutes, until there was no cuff, and then only half a sleeve, and then no sleeve at all. She let the thread fall around her feet. William called. She didn't answer. Sara called. She didn't answer. In a week Sara would be back in the city and she would have to tell her everything, but not yet. She kept pulling until the collar and the bodice and the hem and the other sleeve were all entirely unraveled. Soon the silk thread was piling up to her naked waist. She unraveled the rivers and trees and the carp that swam in circles. At last she unraveled the final stitch. She felt safe and warm as she burrowed into the nest of silk. She had eaten almost nothing since the fish eyes, but she wasn't hungry. She closed her eyes as she pulled the silk in around her. She wanted nothing more than to rest there in that enormous cocoon, for days and weeks, and then emerge—free of poisons and tumors and heartsickness. _With wings_ , she thought to herself, as sleep finally came. ## A SUBJUNCTIVE MARCH Sara could no longer tell one day from the last or the next. Irene had told her about the biopsy results right after she and George had returned from New Year's, and now it was March. What had happened to the intervening weeks was a mystery worthy of study by George's counterparts at the theoretical physics laboratory. Sara suspected that something had happened to the very fabric of time itself. It was always March. Sara didn't even need to see the gray dawn outside the one tiny window in George's apartment to know it was out there, dismal and petulant. She woke up each morning to the sound of her husband-to-be trying to extract himself from the Murphy bed without waking her. She dreamed of it closing up like a Venus flytrap with her inside. With her eyes nine-tenths shut, she breathed heavily so George would believe she was still dozing as he moved around the tiny apartment, from the toilet-in-the-closet to the shower-in-the-kitchen. Coffee dripped behind the spray of the shower. She peeked when George emerged, sopping wet, and proceeded to barrel about the apartment in his towel, trying to simultaneously pour the coffee, check the weather on his phone, and (on alternate days) water the plant. There was a hard deadline, always, of seven o'clock, because that was when George's car was due for ticketing, and his panic grew and grew as the minute hand worked its way around. Already there were four parking tickets that George was fighting, plus a speeding ticket he'd gotten on the LIE, another from Riverside Drive, and a third he hadn't yet told her about but that she'd seen hiding under a notebook and seemed to involve driving the wrong way down a one-way block in Tribeca. Lying in bed, she imagined how much more smoothly things would go if people just listened to her. If her roommate, Karen, saw reason and moved out of their bigger apartment, regardless of whose name was technically on the lease. If Irene would not always wait until the last possible minute to text to say if she needed someone to take her to the hospital or pick her up. If Jacob would read the book she'd bought him for Hanukah. If Irene would hurry up and tell Jacob about the whole cancer thing, instead of always waiting for the "right time," which was clearly never. If she and George would find the perfect glamorous yet intimate place to hold their wedding so she could finally mail the save-the-date cards she'd already bought and addressed. If William would sign on to Facebook again because even though she was mad at him for leaving Irene at the train station, she was also sure that they would make a great couple once she was all better. Sara snapped to as George, showered and dressed at last, kissed her cheek to say goodbye. "Hey. When will I see you?" he whispered in her ear. She opened her eyes. It was nearly seven. How had that happened? "Irene's meeting me to see an apartment in Morningside Heights during my lunch break, and then I'm going to try and get down to Battery Park tonight to see a place for the wedding. But I still have the 'Hip Spring Break Destinations' column to edit. Sheldon quit last week, so it got reassigned." "You're already doing the six articles that Meegan left behind when _she_ quit." Sara was too tired to get into that. "So I might just do that at the coffee shop until they close." George nodded, "Allen got us time on the Gerber satellite tonight, and he wants to go over the materials for the conference next month. And somewhere in there I have to find ten minutes to talk to that guy at Cornell. Someone's on leave and might not come back. They don't know when they'll know." "You want to move back to Ithaca?" "I don't want to move anywhere. I just want a job." "Okay. We'll just live in this closet forever then." "I like this closet. As closets go, this is a good one." Sara arched an eyebrow. "Oh yeah? Why's that?" "Well, I've been checking, but so far, this is the only closet in the city that has you in it." She couldn't help laughing at the thought of George bursting into an apartment, opening the closet doors, and doing an apologetic about-face. "Run away with me," Sara said suddenly. George laughed. "You want to elope?" "I want to go to France." "Oh, is that all?" "Come on. I'm serious. We've been talking about this forever! You, me, Irene, Jacob. Freshman year we found those berets at the Salvation Army, and we _promised_ we would go someday. Remember? We watched all those Godard movies." George groaned, still pained by the memory. "We've put this off for a third of our lives already. And I'm saying we should really think about going while we still have the—while we all still can." George checked his watch nervously. "Well, okay, but only if you have a few thousand dollars lying around I don't know about." The thing was, she did. And while she loved that George always forgot, he _did_ know she did. Before her grandfather, C. F. Sherman, had completely lost his marbles, his accountants had set up various accounts for her and her sisters. Trust funds, essentially, though she never called them that because it gave people the wrong idea: snobby and spoiled were immediate conclusions. In college, even though she'd worked part time every single semester and interned in the summers and paid for all her own books and meals, the fact that she didn't _have_ to, technically, had still occasionally caused friction when Jacob panicked about his loans and Irene had needed to sometimes sleep on their couches or raid their pantries when her latest fling had kicked her out. Sara found it much easier to simply pretend the money wasn't real and to live paycheck to paycheck like everyone else. Her mother kept telling her to just get a broker, hire a wedding planner, get a cleaning service, go to the tailor. But Sara refused to pay others to do what she could manage to do herself. If everyone else could do it, then she could too. Twice as much of it, even. And meanwhile she always looked forward to the days ahead of them, when everyone's hard work would pay off, and George would have tenure somewhere, and Jacob would get a Fulbright, and Irene would sell her art for thousands, and they could all finally travel together, with all their future children tagging along behind them. Sara stroked George's cheek. "Hurry up. You're going to get a ticket." He groaned. "See you at the end of time, then." "See you at the end of time," she replied, with another quick kiss before he dashed out the door. When the door finally closed behind him, Sara cautiously untangled herself from the sheets, closed the bed, fixed her hair, brushed her teeth, and pulled on the clothes she had laid out carefully the night before. • • • Sara had learned of Irene's cancer in the back of a taxi, sandwiched between the door and a human-sized cocoon made of iridescent silk. She had come down to Fourth Street to help extract Irene's latest artistic creation from the living room and transport it to the K Gallery, where Irene intended to hide it in the back of the storeroom until she figured out just what the hell to _do_ with it. They had been heading up Sixth Avenue when Sara observed that it was an unusually large piece for Irene. She had sighed. "I know. Any bigger, and it'd be installation art." Sara had complimented the cocoon, which really was quite stunning and had an almost wet texture somehow, from the way the silk shone in the murky January daylight. "So what happened?" Sara had asked. "What do you mean?" Irene had replied. "I mean what came over you? Why'd you make it?" Sara realized now (knowing what she knew by March) that Irene must have been about to tell her the story of Mrs. Cho's kimono, but couldn't do so without explaining how she'd spent Christmas Eve at the Cho household, and that she couldn't explain that without first explaining how she'd broken down and called William from the MetroStop Bakery by the hospital, and that she couldn't explain that without first explaining why she'd been in the hospital. Irene had traced this long invisible thread of events back and had landed where she needed to begin, which was to say, "Well, the biopsy results came back positive." Sara ignored the apparent non sequitur and hugged Irene firmly. She had been ready for this since before the holiday party. "Everything's going to be okay. We're going to beat this thing, no problem." She pulled her phone from her purse to start hunting for the relevant numbers. "Luther said he knows someone at Sloan Kettering and someone else at Montefiore. We should make appointments right away for a second opinion, and then our health columnist, Dr. Sammy, he said he'd talk to us about treatment options anytime." But Irene had actually seemed annoyed by this. "Actually," she said, "I started chemo a few weeks ago. At Mount Sinai." "A few _weeks_ ago?" "It only took a few hours for three days. Now I've got a little time off before the next round. It wasn't so bad. I feel pretty good, and they're very optimistic. I just didn't want to ruin everyone's holiday. It's silly." " _Silly_? Irene, this is serious." "Don't you think I know that?" "Who else knows? Does Jacob know?" "No," Irene sighed. "William's the only one who knows." "But you barely know him!" "He was here, and I got scared, I guess," Irene had said matter-of-factly. "It doesn't matter. He sort of left me at Penn Station. He's probably waiting for me to call him, but—" "You told him you had cancer and he—what?" It had then taken a good twenty minutes to back up and get the whole story before the cab driver deposited them, and Sara helped Irene navigate the cocoon into the storeroom. And though it had all seemed fine at the end of the day, Sara continued dwelling on it. They had always told each other everything. So why hadn't Irene told her right away? It killed her that when it was all said and done and Irene had been cured, this would still be there between them. All Sara wanted was to take care of Irene: shuttle her to and from her doctor's appointments, make her chicken soup from scratch, sit with her on the couch watching _¡Vámonos, Muchachos!,_ and wait until Irene fell asleep to pick her hair off the pillows. But Irene refused to allow any of this. She insisted on acting as if nothing were any different than before, like the rest of the world. For instance, it was insane that Sara still had to wake up and get to the _New York Journal_ on time and spend the bulk of her day in a gray cubicle, covered in orderly columns of Post-it Notes and tacked-up newspaper clippings. While her friend _had cancer._ She just _had_ it. "I mean, hello?" she felt like saying to her dry-erase calendar. "Are you serious with this shit?" It was still totally full of precise, centimeter-tall lettering and meticulous color coding: red appointments, green deadlines, blue editorial board meetings, purple social engagements, yellow holidays, and intern schedules in brown. Even though Irene had been adamant about sticking with Dr. Zarrani at Mount Sinai, Sara still went in to discuss the situation with her boss, Luther Halles, the editorial director. He gave her a few numbers—well, actually he told her to look the numbers up in his Contacts list—and said she could use his name, of course, for anything anytime. "You could do a piece on this," he said, rolling his Mont Blanc pen between his fingers. She did a quick mental check of whether she needed to order him more ink. "Even a multipart thing, you know? Young, invulnerable people with cancer. It's compelling stuff." Sara hummed. "I'm not sure my friend would go for that." Luther got up and began pacing. The way he walked, he sort of led with his head, which whipped this way and that, tugging through his neck as if pulling the rest of his low, reluctant frame behind him. "Tell her this is important. Others can learn from her." She wasn't sure that was on Irene's list of current priorities. "Hey. Does she have health insurance?" Sara nodded. Juliette and Abeba were keeping Irene on the payroll. "She works at this gallery in Chelsea." Luther made a face; it would be a better story if she didn't have insurance, Sara supposed, with all the headlines about the legions of young people who were coming off their parents' plans into part-time work and their parents' basements. There was no room now for them here, with her whole graduating class on idle, waiting for this financial crisis thing to end. Now the people above them couldn't retire and wouldn't be promoted and so she and everyone else were stuck in assistant purgatory. Still it was better than being back home. "The other thing is that I might need to take three weeks off," Sara said as seriously as she could. She knew he knew she had the days saved up and he'd been dreading she'd try and use them. "Once she's finally feeling better, I'm taking her to France." Luther didn't reply, and didn't really need to, as his eyes alone suggested that this wasn't happening. She knew she'd be better off asking him to rename the paper _The Daily Sara_ than asking for multiple weeks off. She was the paper's unofficial closer. Whenever someone quit or was fired (which happened every other week), their abandoned projects were usually given to her to finish. Meanwhile she represented the paper in the Classroom Journalism Initiative and served on a steering committee for the new Web interface. When Luther traveled, Sara was the one trusted to book his hotels, dinners, cars, and flights and to find people to take his unused Knicks tickets if there was going to be a game. She spoke to Mrs. Sigrid Halles (a former Miss Norway runner-up) at least three times a day and kept track of the major life events of their children Laetitia and Laurence. He seemed aware that this was a lot of work for one person, or at least he had given her a 5 percent raise last summer when she'd complained about it and given her a new title as head of the mentorship program, which meant she had use of the two interns. But using them was far more work than doing it herself, for both were clueless. They were only six years younger, but they were hopeless. God knew what they would do to the place if she were gone for three weeks. Luther sat back down and pushed a stack of files toward her, which he'd finally signed after a week's delay. "Why don't you all go use my beach house? Shelter Island is great this time of year. It's absolutely beautiful." "In March?" "Oh, totally. I wouldn't go swimming, but there are some excellent vineyards, and you'll have the town to yourselves. It's primal, I'm telling you. It's so relaxing. I go out there some weekends just to think. Be in nature. Commune with the pounding surf and the wide-open sky. Check with Sigrid about it. We're lending it to her nephews until early April, but you can have it for a couple days after that. It'll be perfect. A long weekend on Long Island! On me." Sara thanked him with enough false gratitude that he'd be satisfied and promised she'd think about it, even though the idea of staying in her boss's house—even his vacation house—made her feel awkward. On her lunch break Sara went up to check out the Morningside Heights apartment. Since they'd arrived six years ago, the rents had climbed far faster than their pitiful raises. She found herself feeling grateful the housing market had just spectacularly collapsed (though she knew this was awful) because the rents weren't increasing for the first time in six years. But they weren't going _down_ either. Occasionally she and George did find places that seemed within reach, but the listing would disappear before they finished their application. No matter, they had always already begun to get cold feet. Because George couldn't realistically come in from the observatory on his lunch break, Irene joined Sara to see apartments sometimes during the week. Most of the time she was either just coming from or going to an appointment at Mount Sinai, but she never said more than "It was fine" or "They don't know if it's working yet," when Sara asked how it was going. Nothing would be determined until April, when this latest round of chemotherapy would be finished and new scans would be taken. That day they met by the steps of St. John the Divine and hugged, and Sara thought she noticed Irene wince a little from her light touch through her red pea coat. She looked pale, for sure, but then so did everyone; the sun hadn't been out in weeks. "Have you spoken to Jacob yet?" Sara asked, as they walked past the sculpture garden and down to the corner of 110th and Amsterdam. "I saw him yesterday. He yakked my ears off about his stupid boss for an hour. They have this rule, apparently, where they don't talk at work, except Jacob has to always wave hello to Oliver when he walks by his office, because everyone else does and so it might look suspicious if Jacob didn't. But Jacob says that he'd rather just never say hello to anybody ever, _including_ Oliver—" This wasn't what Sara had meant, but then a tour bus roared by, its double-decker top filled with elderly Europeans wearing complementary ponchos just in case the solid gray sheet of a sky made up its mind to rain. The tourists snapped photos of the cathedral as the bus idled at a red light, and then the light went green and they roared along toward Columbia University and the Apollo Theater beyond. "Here's the building!" Irene shouted. A hand-drawn sign taped to the door announced the open house, and the door itself was propped open with some wadded-up coupon circulars. Sara wrinkled her nose—the front hall was badly lit, the mailboxes were covered in permanent graffiti scrawl, and there was a distinct M. C. Escher lilting to the stairs as they walked in. At the first floor they knocked on the appropriate door and waited. A moment passed, and then the door swung open to reveal an elderly man wearing mascara, rouge, and a blond beehive wig. He wore a cerulean silk Ralph Lauren bathrobe that was tied just loosely enough to make his biological sex undebatable. "Oh!" Sara almost knocked Irene backward down the rickety staircase. "Yes?" he asked, as if nothing were odd at all, looking them up and down eagerly. "We're here to see the apartment?" Sara managed, eyes flitting from the wig to the open bottom of the robe, to the side of the doorframe. "Come on in," he said. "You know it's only a one-bedroom, don't you?" Sara had to purse her lips to stop giggling as Irene slipped an arm around her waist. "Oh, we'll only need the one bed." The man laughed, and the gruffness gave away his masculinity even more than the powdered-over Adam's apple. "Let's come back another time," Sara said, trying to wriggle gently away from Irene. "Come on," Irene said, reaching up to brush some of Sara's raven hair from her forehead. "I'm sure Ms. . . ." "Daphne." "I'm sure Ms. Daphne doesn't have all day to show us around." But Irene took her sweet time poking around the closets and the kitchen, seeming to relish the way Sara kept close at all times. "Oh, your mother would _hate_ this wallpaper. It's so perfect!" Irene said as she ran a hand over the velvety-floral patterns in the living room. "It's all original," Ms. Daphne explained. "At least since the sixties." "You've lived here that long?" Sara asked. "Oh, honey," he exclaimed. "You're making me feel old now." Irene dragged Sara through the door into the bedroom, where an old armoire hung open, revealing an assortment of beautiful gowns. Sara's eyes wandered instead toward the mirrored vanity, which was overflowing with heavy-duty makeup. Ms. Daphne blew into the room after them and then eased himself onto the low-slung bed, which rippled unnaturally as he stretched out on it. Irene hooted. "There's a water bed! Sara, come try this out." Sara stifled a laugh as Irene bounded toward a spot on the bed, then felt a pang. How could Irene have cancer and be goofing around like this? There she was, making herself comfortable on the water bed and wiggling her eyebrows suggestively at Sara. Ms. Daphne clapped his hands together. "For another three hundred I'll leave the bed. Don't worry, it's very sturdy!" This offer seemed to, finally, break Irene. She began giggling uncontrollably, which made Sara start to giggle as they excused themselves and rushed out, nearly tripping down the stairs. The girls didn't stop running until they were back in the park, winded. For just a moment it felt like nothing had changed at all. "I could kill you!" Sara shouted, as Irene leaned against a low rock wall for support. "He . . . was this close to getting us in the bed!" Irene was practically crying, she was laughing so hard. Then she leaned over the wall and threw up what looked and smelled like a grapefruit that she'd had for breakfast. Sara rushed off to a nearby kebab truck for napkins. When she got back, Irene was cleaning herself with a fistful of snow she'd scraped off the wall. They each caught their breath. Finally, Irene stood and threw one arm around Sara. "Totally worth it," she declared. • • • Sometimes Sara called George without even realizing, on afternoons like that one when she was wandering through Times Square on her way back to the office after a late lunch. She just found her phone against her ear, ringing. Then when George picked up, she didn't know what to say. "What's up, buttercup?" he asked brightly from the other end of the phone. In the background she could hear Allen playing a loud video game, blowing up aliens with rocket launchers. "Could you turn that down?" she heard George say. "We're taking Irene to France. I've decided." George laughed. "Did you also decide to rob a bank, because—" "No," Sara said. "I'm going to pay for it. I'll call my mother after work and tell her I'm taking it out of my grandfather's money." This was what she called it to George, and even to herself, though it wasn't really her grandfather's anymore and hadn't been since she was fifteen and his great decline had begun. Slowly he had lost the ability to form cogent sentences, to walk, to lift a spoon to his mouth. Sara's mother had set up the pool house for him and his nurse, and at night she'd sometimes heard him howling out there. Her parents and sisters never talked about it, then or now. Then one day Sara had come home from school to find a note on the refrigerator saying that they'd all be going to his funeral on Saturday. She had tried to tell George all of this, but he didn't really understand. How could he? And so now it was just she who knew firsthand what happened when the human body began to come apart at the seams. Who knew there wasn't time to waste. That illness cared nothing about money or fairness or the things you planned to do later. George hummed over the phone. "You think Irene's going to be comfortable with that?" "People have done worse things to other people than buy them trips to France." He laughed and didn't take it further. "Hey, did we ever think about the New York Public Library for the wedding?" "They're booked solid." Sara was hovering under the low blue marquee for the Letterman show, a block from her office. "For when?" "Forever." "How about Disney World?" George offered. "Don't say that unless you're serious." "I'm _not_ serious." "Because you can't joke with a girl about getting married in Cinderella's castle, mister." "I'm not serious! I'm not serious!" George shouted. "You can get the character of your choice to officiate." George thought a second. "I want Quasimodo then." "You would." "Hey, next to Quasimodo I'm going to look _good_." "You always look good," Sara said, leaning into the receiver as if she could kiss him through the mouthpiece. The smell of the pizza at Angelo's filled her nostrils as a street sweeper swarmed by, picking up the torn ticket stubs and the spilled salads of the afternoon's tourists; the shows would be opening in only a few hours, but the sidewalks were already teeming with high school classes and church groups and seniors who'd been bused in from New Jersey. They were all clinging tightly to one another, looking overwhelmed, scared to walk too far in any direction. Everyone kept checking phones and wristwatches. _How much time before dinner? Let's not be late. How long will_ that _line take? How many blocks is it? Let's just stay here and stare at the American Eagle billboard. I heart New York._ "Gotta run," George said. "Cokonis is calling on the other line." "See you at the end of time," she said. • • • Back in the office she killed an hour Googling "osteosarcoma causes." She always came up with nothing, even after going up to the thirty-eighth page of hits. She was amazed how many different ways there seemed to be to say it: _unknown_. Does not have a concrete cause. Little is known about the etiology. The causes are not known. Scientists have not found the exact causes. The cause is not yet established. There are no known or apparent causes. One time she found, "While the causes are still unclear, doctors believe that his type of cancer starts with a DNA error in the body's cells." She'd thought she was on to something until she looked up "DNA error" and was met again with _unknown_. The causes are not known. Etc., etc. She got up to make a cup of coffee in the pod machine in the kitchen. As it gurgled and spat, she lifted a sunflower-yellow packet of zero-calorie sugar and snapped it back and forth with her finger to compact the crystals inside. She imagined, in thirty years, opening a newspaper and seeing the headline: CANCER CAUSE CONCLUSIVELY DETERMINED. And everyone would go, "Damn, it was _riboflavin_ the whole time! How did we miss _that_?" She ripped open the pack of sugar substitute, emptied it into the coffee, and threw away the paper. Then she returned to her desk to find one of the interns waiting to confess that she'd broken the copier by forgetting to remove a staple from a three-page memo. These were the winners who'd gotten this chance while others their age sat at home. These were the people whose parents were too important for them to be fired. Dealing with the copier would take up what remained of the hour, just as the afternoon before had been lost to the other intern forgetting P came before Q and an hour's filing needing to be redone. What was another hour? What was another afternoon? Sara wanted to waste as many as it took to get through this awful month. • • • At seven o'clock Sara changed into a strapless sea foam dress that she'd had tailored from a bridesmaid's dress used during the previous summer and headed downtown to meet Jacob. They were scheduled to check out a high-end seafood restaurant in Battery Park as a potential wedding venue. The planners hadn't been able to get her in on a weekend day but had gotten the members of the Marcuso-Gerber Wedding to permit them to come see the space in action that night. Ordinarily Sara would have warned Jacob that they were only slipping in and out without bothering anyone, but given the oppressive weight of this March on her shoulders, she rather hoped he would get her out on the dance floor, or maybe start several fights with Marcuso cousins, or at least swipe her a slice of wedding cake that she could sink her troubles into. Walking down Broadway, past the line outside Letterman and past the smells of Angelo's once again, Sara dug her phone out of her purse and called her mother, only to discover that she had already missed a call from "Home." No matter how many times she tried to impress upon her parents and her sisters that, between the hours of eight and six, she "worked," that is, "had a job," and therefore couldn't take personal phone calls, they always, always called then and seemed annoyed and surprised that she was ignoring them. Such was the tone exactly of the voicemail then from Sara's mother. "Sara sweetheart, we _really_ need to know the date for the wedding. We're supposed to go to Ireland for three weeks in June next year and we have to book the flights now, but we can't until we know if we should be in New York. You can still do it in Boston, by the way. Are you going to get a block of rooms? Hotels in New York are so expensive, we really want to reserve those right away, especially if you're thinking about September, because that's move-in for colleges and . . ." Sara jammed on the delete button so hard that she thought she felt the glass crack on her phone screen, though George kept telling her this wasn't possible. How exactly was she supposed to worry about wedding planning? She didn't care at all. All she needed was enough space to successfully fit two hundred friends and family members, a five-piece band, a Unitarian minister, four steaming tables, and a three-tiered cake covered in vanilla buttercream—and yet nothing felt right. She and George went to place after place. The rooftop of the NoHo Hotel and then an old ironworks called The Smithy, which had been converted into a medieval-looking space. The elegant Russian Dance Hall, the slick and seedy Club 99, and the Bronx Botanical Gardens. George had vetoed Guillermo's on the Water in Hoboken ("I'm _not_ getting married in New Jersey") and a huge ballroom inside one of the former World's Fair buildings in Flushing. ("Really? Your mother is going to let you get married in Queens?") There was brief talk of being married in the Lower East Side Tenement Museum and doing a kind of Dickensian thing. There was a short investigation into what it would take to join the Rosicrucian Order, because Sara liked the Grand Lodge but it was only available for qualifying Masons. In one weekend alone, they had toured the Central Park Boathouse, a church converted into an artist's collective, the Morgan Library, and NYU's South Asian Institute. As with the apartment search, she was overwhelmed by a plurality of possible futures, each of which seemed as impossible to reach as April. While she waited for Jacob to come down on the bus, Sara milled around the far-downtown neighborhood. Even under a heavy coat, she was freezing in her dress. She paced up and down Bowling Green and up past the mouth of the Battery Tunnel. Her face felt heavy with makeup, her hair tight in its twist. She willed herself to stop craning her neck every ten seconds looking for Jacob, and to stop checking her text messages and to just take that particular moment in. To hold on to the lingering crust smell of French bread still emanating from the closed Au Bon Pain up the block and to keep the resilient greenness of the grass in front of her. Keep the prickly chicken-skin bumps on her arms and the way they felt under her palms as she rubbed to stay warm. Keep the angle of the shadow that belonged to the elevated walkway, which was closed and dark, and the stairwell leading up to it was chained off. Keep the chains clanking in the cold gusts of a passing black town car. _It's too quiet down here_ , Sara thought. She could feel the particular wet chill of the Hudson from a block away, but she couldn't see it. The buildings were too new even though this was the oldest part of the city. Finally she saw Jacob coming from up the block wearing a black top hat and tails, which he'd rented from God knew where. He had on the patent leather shoes and a little cane thing with white tips. He looked like a pudgy Fred Astaire. "Oh my god, you look amazing!" she yelled. "I know!" he said. "I mean, so do you!" He hugged her and felt her shivering. "Why didn't you meet me inside somewhere?" She lifted up her arms as if to say that she had no idea, but Jacob thought she was pointing across the street, toward the high fences that marked off the construction site there, and the hundred-story cranes that stood sentinel overhead. "Oh, I know. Can you believe it? Eight years later and still just a fucking hole in the ground?" Sara didn't know what he meant, until she realized that she'd been standing there—trying to live in the moment and to be observant and aware—for twenty minutes directly across the street from Ground Zero without having even the slightest idea that this was where she was standing. The shame of this made her slump into Jacob's shoulder. She'd never really known the city before the towers had fallen—just one class trip in high school to the Natural History Museum and a family excursion to see _Cats._ It had happened the third week of Junior year, two years of eager progress suddenly derailed into twenty-four-hour coverage of gray ash and bafflement. Her parents calling to report that so-and-so's father was all right and that so-and-so's father was missing, and weepy firefighters, and angry men in suits on CNN, and then shock, and then awe, and then tough and solemn boys in desert camouflage on FOX. And for years after it had felt like progress could be measured only in how much closer they were to rebuilding that wide and brilliant world and then gradually accepting that it would never be rebuilt—that it, too, remained a hole in the landscape. They walked a little farther and came up to the railing and looked out over the Hudson. A thin crescent of silver moon hung above Jersey City, and Sara tried to squint enough to see the time on the Colgate clock, glowing like an ember at the foot of the huge skyscraper there. "What's up with you lately?" he asked. "Every time I see you or Irene it's like you're trading off periods or something. At least let George and I have a turn." Sara paused, ready to tell Jacob everything and deal with Irene later. "I'm stuck in a subjunctive mood," she said finally. "A what?" "Come on. You're a poet. The subjunctive. Indicating that everything is possible and contingent. Hypothetical. I'm just having a subjunctive month." "A subjunctive March," Jacob agreed. Sara looked down. There beneath her three-inch heels was the cold white concrete of Manhattan. An inch beyond them, on the other side of the railing, was the cold, dark roiling river. Here was city, and there was not. Ever shifting though it might be, there was an edge to the city in every given moment. Its beginning and its end. It was a finite thing, after all. And inside the city was _one_ apartment for her and George. And _one_ place where they would exchange their vows and cut a cake and dance to a cover of Bon Jovi. And Irene would tell Jacob at _one_ moment, just as there had been indeed _one_ moment when Irene's DNA had erred, and just as this very moment now the chemotherapy was either repairing this error or the cancer was growing. Time would tell, as sure as it would also pass. It could not be March forever. "Come on," Jacob said, "let's go crash this wedding. It'll give me a chance to explain why you don't really want to get married." Sara giggled, though she knew he wasn't entirely kidding. "First . . . you really just can't tie down a guy like George. He's got insatiable appetites. He's got the soul of a rock-and-roll legend inside that nerdy shell. He's like . . . you know who he's like? He's like Meat Loaf in there. That's right, there's a four-hundred-pound, sweaty animal locked up in there who would do _any_ thing for love." Sara was laughing so hard, she could hardly breathe. "Thank you," she said, giving Jacob a kiss on the cheek. "Let's make out," Jacob said. "I'm in love with you. Don't marry that other guy." "Sorry. You missed your chance," Sara sighed. "Can I at least sleep in your attic once you get all lame and have a billion kids? Maybe make a little den, up above the garage." "Nope," Sara said. "I won't have you coming and going at all hours of the night, bringing your conquests to breakfast. What would my billion children think?" They went on like that for hours. And they did go to the wedding, and they did drink themselves sick on champagne cocktails until they were escorted out by the bride's brother, a greaser named Mikey who tried to get Sara's number even as Jacob was attempting to kick him in the shins. And Jacob promised, he _promised_ , he'd come to Long Island for a long weekend at Luther's beach house in April. Just the idea filled Sara with happiness all the way home, where she burrowed into the Murphy bed beside George, already sound asleep. ## SHELTER ISLAND George liked solving problems. Finding the square root of _x_ using the Babylonian method. Unjamming the printer in the department office. Determining the number of Sun-like stars in a Brightest Cluster Galaxy based on the ratio of their luminosities. Tracing the most efficient possible route between his parking spot on Riverside between Seventy-second and Seventy-third, and the Borders outside Grand Central from which Jacob had consented to being (in his words) "kidnapped," and down to East Fourth Street for Irene. Then back up through the Queens Midtown Tunnel and the Long Island Expressway, in early Saturday morning traffic, with a quick detour around an accident near Hauppage, and then onward until exit 70 brought them to the Sunrise Highway. Then Route 51 and the North Fork, where they'd take the ferry over to Shelter Island where Sara's boss Luther took his family in the summertime, but which for this one weekend belonged to them, for nothing. It was important to appreciate nice things when you could. Fine wines, good friends, free beach homes. It would be just like old times, back in the dorms. They'd be up all night talking, playing charades and gin rummy, counting stars from the rooftop. George had a slight headache, the likely result of the whiskey he'd had at one that morning to celebrate the e-mail he'd gotten from an AAS committee member in Belgium inviting him and Allen to speak at the June conference in Pasadena about their mounting discoveries in the Ring Nebula. People were talking about it. Physicists anyway. Terabytes of new data every day that he and Allen were gathering on 237 Lyrae V's collapse. He took a long sip from his Einstein thermos, its contents still warm after almost two hours. It was a relief to be leaving the city at last. Get the past few months behind them. Sara had been up half the night, packing and repacking, and now she was asleep in the passenger seat. In the rearview mirror he could see that Irene was texting on her phone and Jacob was dozing. George was glad that they could finally start focusing on what lay ahead. Jacob had booked tastings at some vineyards Oliver had recommended, and Sara had researched the best local seafood spots. Best of all, Irene had been steadily improving since her fourth chemo treatment at the end of March. Dr. Zarrani had seemed to feel things were going well when George had picked her up from the last infusion. "You may see the lump under her eye getting smaller, although don't overinterpret this," Dr. Zarrani had urged. "Sometimes there is some shrinkage due to liquid loss, but that isn't necessarily indicative of cancerous cell death. Call me immediately if she feels swelling beneath her arms or an ache in her jaw, as this could indicate spreading to the lymphatic systems." How on earth could Irene's jaw possibly be connected to her armpits? George wished he'd paid better attention in AP Bio. "Obviously changes of any kind could be relevant," Dr. Zarrani stressed to Irene. "Call the office anytime, and we'll see you next week for fresh scans. Then we'll know where we are." He and Irene had celebrated with a pint of Cherry Garcia on the sidewalk, followed by two pints of Guinness and a round of Big Buck Hunter at McIntosh's Bar on the corner. Back at home that night, George had done something he hadn't done since college. He'd waited until Sara was asleep and then got up to pray. That Irene would soon be herself again, and that by extension Sara would be herself again and that he could be himself again. It had been a long time since he'd prayed, and it didn't feel right, but maybe his words were getting through, because here they were, all together as planned, in a car headed to the end of Long Island, to meet the ocean at the horizon. • • • Luther's house wouldn't be available for another hour, because a cleaning service was coming to get things ready for them after Sigrid's nephews' departure for Norway that morning. So George decided their first stop should be at The Blue Anchor, where they kicked things off with raw oysters and Bloody Marys made of freshly juiced heirloom tomatoes from the hothouse garden out back. They sidled up along a long bar facing the bay and the still-rising sun. There was hardly anyone else there. "Isn't this fun?" George said, raising his oyster shell up until everyone did the same. "Cheers!" Sara forced a smile as she slurped the slimy, briny creature from its shell. Something was clearly still bothering her. Jacob belched as he set his own shell down and said, "Delicious. Now, would anyone mind telling me what we're doing out here? In April?" Sara half-choked. "Sorry. Horseradish." She was trying very hard not to look at Irene, who had _promised_ that at some point that weekend she'd finally tell Jacob what had been going on. George wasn't holding his breath. "Do we always need to have a reason?" Irene asked. "Think of it like spring break," George chimed in. "Sure," Jacob said. "All those times we went on spring break. Remember Cancún? When I did that body shot off of Mark McGrath? No? _Me neither_." George knew Jacob would just keep pushing until something snapped. The only hope was diverting him. "Don't look but I think the oyster shucker is staring at you." They all turned cautiously—except for Jacob, who half stood and craned his neck just to get a look. There indeed the burly, bearded man was looking back at them, not that there were many others to look at. Giant tattooed tentacles wound around his muscled arms, curling out from the white straps of his apron and disappearing down into his gauzy white gloves, which never stopped moving, automatically maneuvering a knife blade between the closed shells. Jacob grunted dismissively. "You'd think by now you'd know my type." "He's breathing," George pointed out helpfully. "He's _adorable_ ," Irene corrected. "And he's staring right at you." She swiveled on her stool, and the morning light glanced off her cheekbones such that George could just make out the reddish lump under her eye. Was he just imagining it, or was Jacob looking at it too? Sara definitely was. "I'll go talk to him," George offered. He'd had plenty of practice being Jacob's wingman when Jacob didn't want him to be. Over Irene's cheers and Jacob's protesting, George slid back from his seat and marched confidently across the room. He had successfully solved the problem of the foul mood; now he hoped to begin phase two, beginning a memorable story that they could tell each other over and over again that weekend and always. They had just begun their second round of Bloody Marys, and he was feeling very good after the long drive. A second drink always suffused his worries in the pleasant buzz of uvula and the sting of nostrils. Painted a little haze on everything. Amplified the timbre of Irene's delight as George smiled at the oyster shucker as they began to chat. "Sorry, but where are these oysters from? They're excellent." "We farm them just out there by the Shelter Island ferry. Can't get 'em fresher." He held one up to show George. It was about the size of his open palm, dark and stony and still alive when the man slipped his knife into the thin slit and gave it a firm twist, cracking the shells apart before cleaning grit off the meat and placing it still in the pearly shell on a silver platter covered in crushed ice. George pointed back at Jacob. "My friend was just wondering . . . we passed all these vineyards on the way over. But we don't want to just drink the tourist stuff, you know? What do _you_ drink around here?" He watched as he momentarily looked up at Jacob, his knife slipping for the first time, just catching the glove. A small red splotch appeared on the glove, amid the dried, darker blotches of past slip-ups. He dipped the blade down again into the shell and in one swift motion flipped it straight up into the air. Like lightning, his other hand came around and caught the oyster in an empty glass. He repeated this trick and then poured a shot of vodka over each. Then he scooped a little cocktail sauce onto each and squeezed a lemon over them. "For me?" George asked. "You asked what I drink around here. Plus your friend looks like the jealous type." George winked and tapped the side of his glass against the shucker's. He wasn't wrong: no sooner had they each swallowed their oyster shots than George heard Jacob calling from the other side of the room, "When you and your new best friend are done over there, could you get us another round?" The man looked over at Jacob as he began to crack open a fresh oyster. "Tell your friend to open his mouth." " _That_ is never a problem," George replied, and called over. "Hey, Jacob, open wide!" Jacob turned on the stool and opened his mouth. Without breaking eye contact, the man loosened the gray bivalve and positioned his knife underneath. Then in a fluid motion he flipped the oyster again, this time in a long arc, fifteen feet across the floor of the restaurant. Jacob had to lean back just slightly, enough to make Irene shriek in fear he'd fall, before, in one spectacular moment, he caught the projectile in his mouth and swallowed it whole. The girls cheered as Jacob stood up and walked over, grinning. "You've got my attention," he said. • • • Jacob took his sweet time getting the phone number of the oyster shucker, and Irene took a detour down to the docks, claiming she needed to collect some loose shells and gull feathers that he imagined might find their way into a painting sometime in the near future. George soon saw her walking around with phone out, frowning and trying to catch a signal. But he didn't care, so long as everyone was happy. Sara pulled him aside as they approached the car. "Did you see Irene take her Neulasta this morning?" George hadn't, but he said, "I'm sure she did. She's fine." "I should have reminded her before we left." "I'm sure she remembered." "I just have a bad feeling. We don't even know where the nearest hospital is." "Nothing is going to happen. Dr. Zarrani even said a trip would be good for her." "She also said Irene should have had the tumor removed." "No, she said she thought it would be _better_ to be thorough, but it probably wasn't necessary, and considering that it would possibly permanently ruin her vision in that eye, it'd be better not to do anything until we know if the chemo is working." "I know. I'm just worried." "It's going to be fine. The scans are going to come back clean." "Don't _say_ that!" "What? You think I'm going to jinx it? That bump under her eye is basically _gone_." "But you told me she said that doesn't mean anything! I wish you'd take this seriously." George sighed. "I am." He tried to put his hand on her shoulder to pull her close, but she remained firmly planted just a bit too far away from him, her eyes narrowed. "How much did you have to drink in there?" "I thought we were supposed to be celebrating, for God's sake." She crossed her arms—a bad sign. "All you've had to eat today are oysters, and you had the two Bloody Marys plus a shot at the bar. Maybe you want to let someone else drive?" "I'm fine," he said, trying to sound nonchalant. "Don't worry so much, okay?" "I'm just saying Jacob's a lot heavier than you are. It doesn't affect him as quickly." "He has the tolerance of a nun. He hardly ever drinks unless we're all out together." He realized too late that he wasn't helping his case exactly by reminding Sara that, in contrast, he had at least two drinks every night, whether they were out together or home alone. He was about to take it back, to try and explain what he'd meant, when he heard Jacob and Irene coming back over the gravel. "Who does she keep texting?" George asked. "We're all here." "Don't ask," Sara said. "What's the problem?" Jacob called out. "No problem," George said loudly, unlocking the car. "Let's go." • • • They only had to go around the corner to find the ferry that went to Shelter Island. George drove the car up onto the prow of a beautiful, barnacled service boat that went back and forth across the gray water all day long, buoying Benzes and Lexuses to the otherwise unreachable shore. As they moved out across the water, George stared at the spot their oysters had come from and wished that they weren't now churning around quite so unpleasantly in his stomach. Fortunately the ride was soon over, and they only had to go a half mile up the hill to reach Luther's beach house at last. From the end of the driveway, they could only see how enormous it was. Three stories, shingled in impressive gray wood, with white trim. It had two garages and a kidney-shaped pool on one side. It was only when they got closer that they realized the pool was covered in thick green algae. The yard was scorched dead in patches and overgrown in others, littered from one end to the other with crumpled silver and blue Michelob Ultra cans and the jagged remains of two twenty-four packs of Dos Equis bottles. The cardboard boxes these had come in, presumably, were also in the yard, as were about a hundred red Solo cups, some used BIC razors, half-empty Herbal Essences shampoo and conditioner bottles, several cans of spilled paint thinner, and a wheelbarrow filled with what appeared to be the past century's collection of withered _Redbook_ magazines. A grimy hammock hung limply from a bolt in a leafless tree; the pole that had once supported its other end was, for some reason, sunning up on the garage roof. "Was there a hurricane or something we didn't hear about?" Irene asked. Jacob whistled. "What, was Abu Ghraib all booked?" Sara had both hands on her cheeks, jaw open. "The nephews," was all she could say. "The nephews. The nephews." George trudged carefully up the walk, leading the way through the shattered glass and scattered cigarette butts to the door, which was slightly open. It was too much to hope that the inside would be unmolested, as it turned out. Everywhere he looked were more empties, more dead houseplants whose pots had been repurposed as ashtrays, more greasy pizza boxes, more melted plastic forks and spoons. Every single inch of the kitchen counter was taken up by liquor bottles. Fat ones, tall ones, green ones, brown ones. Handles of vodka with plastic screw tops. Liters of soda bottles used for mixers. Buckets of dirty water, perhaps once ice. A folding card table lay in three pieces on the floor, streaked with crusted white powder. Chairs were overturned, lightbulbs were broken in their sockets, molding Chinese food containers stood open. Either the cleaning people had never come, or they had arrived and done an abrupt about-face. "It's like Hunter S. Thompson, the Marquis de Sade, and Amy Winehouse hung out in here for a month!" Jacob seemed to be nearly in awe. Irene reached down into a pile of sheets and pulled out a silver-sequined bra, each cup of which she could have sat inside of. "Oh. My," she said. "Looks like the nephews made some friends in town." Jacob trudged over to look at it more closely, crunching down on the brim of a straw hat as he did. "Hope there's not a thong in there too." Sara was supremely annoyed. "Luther's going to think _we_ did this! What the hell? We're going to have to clean all this shit up." Jacob kicked an open can of Spaghetti O's across the room. "How about we just set the place on fire and tell him it got hit by lightning?" Sara looked around again. "Why does _every_ thing always have to be a disaster?" • • • A disaster. Jacob was soon telling them how this word came from the old Greek: _dis_ , meaning "bad," and _aster_ , meaning "star." Bad star. From back in the good old days when such misfortune could be attributed to the continual and predictable realignments of the cosmos. It was soon agreed that they'd go wine tasting first and deal with the mess when they got back. Swiftly they were back on the ferry. Sara was trying not to seem furious behind a pair of round retro sunglasses. Jacob hung out the window like a loyal hound dog, his ears all but flopping around. Irene kicked at the back of his seat as she sifted through the bag of shells she'd gathered. George hunted for a radio station everyone liked, which was impossible because Jacob hated everything, so finally they settled on a country station that nobody liked, just to punish him. The outing at least got off to a decent start. At Raphael Vineyards they did the tasting and then split a bottle of First Label Merlot on the back porch, while Jacob talked to the server about skydiving and ended up with another phone number. After that it was Bedell Cellars, where Sara thought to mention that she and George were looking for a wedding venue, which got them a twenty-dollar discount on a bottle of blanc de blancs. They soldiered on to Shinn Estates, then made one last stab at a nice time at Paumanok, but by then it was midafternoon and they were all exhausted, having forgotten everything they'd tasted except that there had been an awful lot of it. George had felt himself slipping deeper into a fuzzy warmth with each visit, a sense of all being right with the world, with the exception of Jacob, who kept reeling him back into dissatisfaction. At some point they all agreed that lunch was in order, and so they got some cheese and bread and cured meats and set out to have a picnic in the green expanse overlooking the vineyard. Sara had picked out the cheeses for each of them from a glass-enclosed aging cabinet. As she handed them to George, she explained her thinking. "You get a triple crème brie. For me, an Alpine . . . nutty, but firm." For Jacob she went with the cheese with the most pretentious description: a Romano the color of earwax and with a "dry, granite texture" with a "saltiness hiding its butterscotch undertones." Finally, for Irene, an Auvergne Blue—punchy and velvety, streaked with dazzlingly beautiful molds. George almost regretted that in a few minutes they would all be devoured, except that nothing was making Sara happier than seeing her companions lying on her mother's enormous old Scotch-patterned picnic blanket—he knew she'd packed it with just this tableau in mind. She took out a camera and began taking pictures of first the cheeses, and then of all of them on the blanket, and then the fields of grapevines beyond. It was perfect. Except Jacob, naturally, was on about something. "Look at all this old machinery and shit they have on display out here. Like they need to make this place seem more _real_? Like . . . oh, well _now_ we use giant machines to plow our fields and squeeze our grapes, and our bottles are made for ten cents apiece in a factory in Mexico, and our corks are made of plastic . . . but we're in touch with our heritage, gosh durn it!" George looked over at Sara. She looked annoyed again. He felt a heat rising up all around his temples, the warm suffusion of his wine-buzz beginning to feel like real drunkenness, and he shot Jacob a cease-and-desist look. George reached for Sara, wanting suddenly to kiss her deeply and blot out their friend's forever blathering, but she eased him off before he could do more than peck her quickly on the lips. "Here it is! Shellacked, of course, to preserve that rusty veneer forever and ever! In a hundred years I wonder what people will stand around staring at, thinking it's so quaint and authentic? Oh, look at that cute little cellular phone! Look at that funny hybrid car! Just imagine how hardworking and pure-hearted people must have been back then!" "Christ. Do you have to be such a snob?" George shouted. This came out a bit meaner than George had intended. Jacob returned the sentiment. "Do you have to be such a wet blanket?" George was about to reply when Sara tried to grab his hand. "Come take a walk." "He thinks because he got one poetry prize, he knows better than other people." "I _do_ know better than other people," Jacob snapped. "Most people can't do math in their heads, much less write a poem." Ordinarily George would have backed down. He knew there was no getting Jacob to apologize. It was just his nature. But George's head hurt and he knew there was nothing left between him and the inevitable evening spent cleaning someone else's house. "You know you don't get a medal on your deathbed for having been right most often. You just lie there alone because everyone you ever loved hates your superior guts." His friend held up his hands to call for peace. George couldn't remember a time Jacob had ever backed down before. Irene stood up and pulled her phone back out of her pocket again, walking around with it stretched out toward some phantom signal. George was finally about to ask Irene who she was texting when Sara, finished with her cheese, took George's keys from his jacket and walked over to the driver's side door without a word. She leaned twice, sharply, on the horn to announce that they were moving on. • • • The final stop was Lenz Winery, and it seemed pleasant enough from the front—wide swaths of brown vines being forced to grow straight up, and a building with huge oak doors that hung invitingly open. Inside were a half dozen other visitors, milling about the long bar in the back and wandering off occasionally to sample chutneys, mustards, and vinegars that were displayed along the walls. George bought five tastings for the group, and soon a white-bearded man was easing a bottle over each and pouring out a perfect mouthful of something the color of sunlight. He and Irene both took sips and swished them around in their mouths. "We're supposed to taste ginger and apricots," Sara read. "That's ridiculous," Jacob said, downing his tasting in one gulp. "It says it right here," Irene said, pointing to the card in Sara's hand. "They just make that stuff up to make it sound fancier," Jacob snorted. "Wine is wine." "Well, it doesn't taste like any Chardonnay I've ever had before," Sara said, leaning over the counter to catch the man's attention. "I want to ask him how they do that." "Oh, like he's going to tell you the truth," Jacob scoffed, before wandering off to admire some salami hanging in a nearby display. "This one's wonderful," Irene said, reading the card, "'Tastes like bluegrass with notes of honeysuckle and hominy'? Well. I don't know about that, but I like it." George took a sip and was inclined to agree. He was about to suggest they buy a bottle of it when he noticed Sara nudging the silver spittoon toward him. "This is so good!" Irene sighed. "Let's get a bottle of it," George said, taking another sip and pointedly swallowing. "It's only the second thing we've tried here!" Sara replied. "Let's have the others and then see which we like the most." "But Irene likes this one," George said. "Yeah, I like this one," Irene agreed. "But you might like the next one even more." Just then Sara finally got the attention of the man behind the counter. "Why does this taste so different? I usually don't like Chardonnay." "Well, you're used to California Chardonnay," the man behind the counter answered with a smirk. "It's much cooler over here, so I can harvest the fruit over the period of a couple of weeks. There's time for different flavors to develop, and we can mix them together to create a much more complex wine. California is much hotter, so they don't have time to let the fruit mature in stages. It's all simpler, more one-note over there, whereas here the wine's got real complexity and sophistication." "Like a true New Yorker!" George quipped as Jacob wandered back over. The man behind the counter stooped below a low crossbeam as he fetched up a bottle for George. "You're joking, I get it, but there's truth to it. The people are part of the wine. The wine is part of the people." "It's the circle of life . . ." Jacob began to sing, before Irene stepped on his toe. The man continued. "We call it the _terroir_." "That sounds fancy," Sara said. "It's how we speak about the soil it's grown in. The weather. Out here we're surrounded on three sides by water, so that affects the vines. We get less sunshine than California, but we also get a greater variety of climates throughout the year. And we're part of the terroir too, if you get my drift. Let's say one year I'm standing there in the dirt in New Zealand, and the mud that's still on my shoes from the Rhineland the year before becomes part of the next year's harvest. We had this big brass band out here last summer during one of the weddings, and, well, those vibrations carried through the air and got into the soil and the vines. That music is in the grapes now. Everything is connected, and everything has a lasting impact, no matter how briefly it's here." George felt Sara's hand gripping his tightly as the man finished his speech. Even Jacob was silent as they toasted again. He stayed silent right up until the end, when he approached the man and asked for four bottles of the Chardonnay made from "bluegrass, hogwash, and fairy wings." • • • The sun was heading down, and there was no more avoiding it. For the third time that day, they boarded the Shelter Island ferry and crossed the water. Nobody spoke as they got out of the car and faced the mess, which seemed even more humongous in the waning light. Sara found some buckets and brooms in a hall closet and sent George and Jacob down to the basement to see if they could locate some trash bags. They climbed down the old stairs together, saying nothing, moving through the dark with George's cell phone screen up as they hunted along the cinderblock walls for a light switch. "There's a pull-chain thingy here I think," Jacob said from somewhere behind him. George moved closer with the white rectangle of light in his hand. "Sorry," he said, "about before. I guess I had a little more than I realized." Jacob grunted in what George guessed was an acknowledgment, if not an acceptance, of his apology. George could admit he had crossed the line, but there was no reason anyone had to be worried about him. He always suspected it was because none of the others had ever seen a real drunk before. George had known plenty. Bad alcoholics, back home in Ohio, at the bar his grandfather had owned and where he'd spent a few hours every day after school. Those shapeless men. Hard, but helpless, leaning low down on their stools. Nothing like him. "It's no big deal," he said. "It's not like I have to be drunk all the time. It just makes me happier when I'm already happy, you know?" This statement hung there in the dark basement for a moment. With a defiant click, the chain in Jacob's hand snapped down and the basement lights came on. They found themselves standing in front of a network of shelves, where the tiny colored noses of bottle after bottle peeked out from the shadows of perfectly fitted boxes. There had to be hundreds. It was hard to see how far back it went. A fur of dust lay over everything. Jacob's cries of glee bounced off the high, curving stone ceiling as he pulled bottles out two at a time. "1991 Cabernet Franc. 1961 Grand Cru. 1984 Bordeaux . . . 1944 Cuvée . . . Holy shit, this bottle's older than my father." George breathed in deeply as he ran a gentle hand over the smooth curve of the glass. He imagined all that had gone into the air and the soil and the vines. 1944. In the middle of a world war, some farmer had harvested his grapes and split his oak trees and dried and charred the wood and forced the slats together with bands of metal. Outside there had been horror and fear, but in this bottle he'd hidden something made from holy sweat. Someone had corked it and set the bottle down with a prayer, knowing he'd never drink it. It was for sons and grandsons. It was waiting for some future, for someone. George wished that it had been waiting for him. Reluctantly he slid the bottle back into its place. When he looked back again, Jacob was bearing down on him. "All right. Enough. Are you going to tell me what the hell is wrong with Irene or not?" George froze. "What do you mean?" "She's been texting that psycho ex of hers, Alisanne. I looked at her phone." "She is?" "Yeah, all this shit about how they need to talk and there isn't time to waste." "Damn it," George cursed. "She's not writing back, thank God, but clearly something's going on. The last couple of months you three have all been on another planet. So what is it? Did William do something to her?" "No, no," George said. "I can't—I'm not supposed to say anything." "Enough drama—. This is too much. Even for her. It's not like she's _dying_." George felt as if his heart had stopped, and he must have looked like it had. Jacob glared at him for another minute, then suddenly his face went slack. Without another word he turned and marched up the stairs. George followed after him and came up just as Jacob reached the top of the stairs and pointed at the girls, who were scraping dried eggs off the stovetop. "—the fuck didn't you tell me?" Jacob shouted. For a moment everything was frozen. Then Irene threw her sponge down and walked out through the sliding-glass door that led onto the porch and began running at top speed into the spiky, sandy-colored grass that stretched between them and the foggy bay. Jacob went after Irene—stubby legs tripping and stumbling with every step over the uneven terrain. George was about to follow when Sara grabbed his wrist. "Let's give them a minute." "I swear I didn't say anything," George said lamely. "It doesn't matter." Sara looked relieved, and suddenly George realized that he had— _eureka!_ —solved the problem. The truth was finally out, and Irene could blame it on him. But it would be forgiven, as it always was. They cleaned in silence for a few more minutes. Then they walked along the path where they found Jacob embracing Irene in a low trench of dune grass that stretched long and empty in either direction. The surf pounded against ancient black rocks and loosed a white spray that danced in the air for just a moment before falling into the sea again. "It's just not fair," he heard Jacob saying as they got closer. "There's no such thing as fair," Irene said softly. "Why didn't you tell me?" he asked. "I didn't want you getting all moody about it." "I don't get _moody_." George watched the waves pounding the shore, each surge of salty water carving another molecule off the stones. In a hundred years the shoreline would be ever so slightly nearer. A hundred years ago, it had been ever so slightly farther out. A hundred years before that, it had been farther still. Hundreds of years from now it would carve in so far that it collapsed the house. Two hundred and fifty million years before, the continents had been fused. Maybe in another two hundred and fifty million years they'd all smash back together again. George and Sara sat down next to their friends. Irene smiled at him and he took a deep breath. Sometimes it paid to take the blame. Now there would be peace at last, and they could get on with their fun weekend. They'd clean for a few hours until the house looked better than new. He'd make jokes about hazmat suits, and they'd find more plus-size underwear, and Irene would begin sifting through the junk looking for sculpture pieces that complemented her seashells, and Jacob would call up Billy Budd from the oyster place and they'd talk, long into the night, just like they used to. "If I don't make it—" Irene said slowly. Sara immediately cut her off. "Don't say that." "Seriously, Irene. You seem _much_ better—" George began, but stopped as she shook her head. His stomach turned to lead as Irene slowly lifted the left sleeve of her shirt to reveal another lump. It was the size of a golf ball. He didn't know what to say, but Sara seemed to have it covered. "Has that been there since before we left? Irene, I swear to _fucking Christ_ —" George knew Sara was right. Irene had known it. Probably she'd even known it that day in Dr. Zarrani's office. She'd hidden it so she wouldn't spoil the trip. He wanted to run into the ocean and pound back at the waves until they were still. He looked into the wide gray sky _._ For what reason—what reason could possibly exist for this? What plan could it be part of? And if there _was_ Something out there that had known about this, well then fuck Him and fuck His plan and fuck whatever it had all been written on. "I'm just saying. If I don't make it," Irene repeated, "heaven had better look like this. It's absolutely mythic." George wished he could believe in it, but just then he couldn't. Sara looked ashen. "I wouldn't like it by myself. Just me here all alone," Irene went on. "But I guess you and George would be along soon enough." She put her arm around Sara, and Sara fell into her, leaning on Irene's shoulder—on the good side. Irene kissed Sara's forehead and reached her hand out for George. "Jacob, I don't know. I guess we'd visit." He laughed. "Jews don't believe in hell. Though we're not too sold on heaven either." "Good thing you're a terrible Jew then." Irene smiled. They sat there for a while, quiet in each other's company. George ran his fingers through the dune grass. Then, all at once, another solution came to him. "Fuck it," he said suddenly, "I'll be right back." He turned and stumbled back through the sand toward the house. Inside he went through the messy kitchen, past a table filled with sticky, half-empty liquor bottles, to the basement door. Taking the rickety steps three at a time, he came to the bottom and soon located the dusty green bottle that Jacob had picked up earlier. He ran his fingertips over the year. 1944. The glass was cold against his palm as he went back upstairs and returned to his friends on the beach. "What's that?" Sara asked immediately. "Is that Luther's?" "Yes," George said. "Or Luther's father's. Or his father's father." "So we're just stealing it?" Irene asked. "No," George grinned. "The Norwegian nephews did." Jacob laughed, deep and proud, and then took out a pocketknife and started prying the cork loose. It came out in several pieces. Sara didn't object as Jacob took a long drag from the bottle and sighed. "Now _that_ is a terroir." George raised the bottle to his wetted lips and tipped back. God. It was the most incredible thing he had ever tasted. The taste grew in his mouth, pulling on an alternation of taste buds. It made no sense, but he thought he could _hear_ its taste. It tasted like a requiem he'd heard as a boy in the Basilica of the Sacred Heart. A priest his father had known at Notre Dame had died, and they'd driven five hours to South Bend for the service. God, it was still going. A few notes at first, gradually swelling in sequence to an offertory, and then Communion—every flavor at once, until it was almost too much. The retreat then was welcome, sweet. And then, just at the very end something new—an aftertaste bound to linger deep in his memory. Like sitting in the basilica, the sound of the requiem in his ears, and the sure feeling that his father's friend had been a good man, and was in a better place now. Up on the ceiling there were angels with outstretched wings, perfect golden circles haloing their heads. Some floating on clouds against the light, and others hovering, weightless, against the dark of night. It was the same dark of the sea beyond them, the same as the clouds that passed above. They passed the bottle around until it was drained. After a long time they all walked back to the car again. Irene agreed to call Dr. Zarrani's emergency line on the way back. They'd set up an appointment to have the new tumor looked at as soon as possible. As for the house, they would leave it as it stood, minus one very expensive, very empty bottle of wine, which was now nestled under Jacob's armpit as he climbed into his seat. Sara looked back one more time before they left. "We were never here," she announced. George drove slowly up the darkening highway, back to the city. The girls whispered for a while, and Jacob stared out the window. Before long everyone else fell asleep and seemed so peaceful. George drove on. It occurred to him that everything he was experiencing now, they were missing. Sadness waited for them, just past the edge of their dreams. It would be patient for hours yet to come, just as his own sadness seemed to hover just beyond the magnificent afterglow of the wine. Great patterns of light streamed across the window like red and white comets. He was unworried, and he didn't know why. It was just so much easier for him to believe, when he felt this way, that there _was_ some reason, and that there was another reason just alongside it why he didn't need to know what it was. ## JACOB IN THE WASTE LAND They returned to the city, and in three days Shelter Island seemed as distant to Jacob as Tierra del Fuego. He closed his eyes on the train up to Anchorage House in the morning and tried to summon a vision of that sandy shore reaching out toward the ocean, but all he could see was the alien lettering in the tunnels south of the Wakefield stop. He tried to remember the dark smell of the sea, but its scent had already been overwritten in his memory by the puke he'd had to wipe off the face of a nineteen-year-old psychotic named Thomas who believed himself to be a submarine. "HMS _Sybil_ , lowering periscope!" the kid had shrieked. "Dive! Dive!" before losing his lunch all over the television set in the common room. "You forgot to shut your hatch," Jacob had reminded him, as they passed arm in arm down the hall to the nurse's station. He tried to recall the feel of sand beneath his feet and the taste of oysters. "It's dark down here," Thomas had whispered, until finally the HMS _Sybil_ had gone quiet. A dry heat welcomed them back. By the first week of May, it was approaching eighty-five degrees in late afternoon. Still, Jacob persisted in wearing his tweed jacket up to Anchorage House each day and back to Irene's at night. "It's very breathable," he told her when he arrived at her door, drenched in sweat. He passed several evenings helping her shuttle some of her older paintings into storage at the gallery and trying to clear space in the living room by sorting through the piles of odd crap that she'd amassed. "Keep that Baggie of tulip bulbs, but get rid of that Oktoberfest hat—no, keep the feather, actually. Do you think you could pry just the runners off that toy sled for me? I know there's a screwdriver here somewhere." Jacob didn't mind. He wanted to help, and he was no good talking to doctors. He kept sending Irene into hysterics at inappropriate moments. Once an MRI had to be redone because he was making her giggle so much. Irene sweet-talked the technician into printing the blurred scan anyway, and she'd given it to Jacob as a thank-you. His other main contribution was trying to get George to unclench, but whenever Jacob called him out for moping around, mute and worried, George acted utterly surprised that anyone would be worried about _him_. He stared at the _New Yorker_ articles that Jacob thrust at him in the waiting room and then minutes later looked up in complete confusion. "Was this—what? I'm sorry, which article? Just a second, I have to go to the bathroom." Jacob had never seen anything like it—the man had to pee practically every half hour. He wanted the doctors to check George out for Nervous Dachshund Syndrome. (That was the one that got to Irene so badly that the MRI had to be done over.) George claimed all the fluorescent lighting was giving him headaches, but Jacob didn't buy it. The last two visits Sara had wound up asking him to simply take George to a bar somewhere so he'd stop agitating everyone. The date for Irene's surgery arrived as abruptly as a summer thunderstorm. Sara had been through three hundred hoops to make sure they had permission to wait in the recovery room, when regulations permitted only family. Jacob appreciated the effort but politely declined. The thought of sitting around in a sterile room for ten hours on a Saturday, watching _¡Vámonos, Muchachos!_ reruns on her laptop and waiting for an update was just about the worst thing he could imagine. Irene said she understood, and instead he took the day before off and stocked her apartment with half a Rite-Aid's worth of gauze, Chicken & Stars soup, Assure milkshakes, instant mashed potatoes, and a case of bottled ginger soda in case of nausea. That night after dinner, Irene snuggled into his arm while Jacob read her his favorite poems with his Patrick Stewart impression, which always made her laugh. He watched as her eyelashes brushed the bump below. In a few hours the lump would be sitting in a stainless steel tray, and below Irene's eye would be a raw abscess. He read much of the night and took the train up to work in the morning, while Irene headed to the hospital to meet Sara, George, and the scalpel. After a long shift, Jacob tried to take his mind off the situation by going out with Oliver for dinner at Szechuan Garden in Stamford. Oliver wouldn't pry into what was going on with Irene. He had that singular gift among therapists of getting patients chatting about the weather or the rising price of stamps. Then suddenly they would crack open like walnuts, exposing their deepest secrets. Jacob suspected this was why Oliver liked him, because while Jacob never kept his thoughts to himself, he persistently refused to be cracked. Oliver was telling a story about growing up in East India. "When I was a boy, my father and I used to go on these long walks through the banyan forests, and we'd play games to see who could correctly identify the greatest number of trees." Even though Oliver got away with telling most people he was in his early forties, he'd really be turning fifty in a year. He didn't look it, which was all Jacob cared about. A high forehead that was still topped with bristly black hair and eyebrows to match. Talking about his father always resulted in a goofy grin that made him look adorably younger still. His father, a native Algerian, had brought their family to Kolkata when Oliver was still young, to join the staff at a major hospital there. He had lived there for only a few years before being sent off to boarding school in England, but he spoke, often, about those golden days with unflagging sentimentality, which annoyed Jacob almost enough to discount all the grinning that came along with it. He waited for a pause and then said, _"My_ father used to pay me a dollar a day to massage his feet after work. He had terrible arches and was too stubborn to get the right sort of shoes. He'd get these hard corns the size of quarters. I don't know how he got them sitting at a desk selling supplemental life insurance all day. He'd make me scrub them off with a pumice stone." He loved to watch the quick rise of Oliver's right eyebrow when he received surprising information like this. It was as if the information were being weighed on an old mechanical scale. "You must have been very close then, at that age," Oliver said. "About as close as a king and his court jester. An inch from applause or beheading, any given day." Oliver stroked his chin, "And why didn't the queen do the massaging?" A bit too quickly, Jacob said, "The queen did _more_ than enough." "Had you always wanted to be a poet?" Oliver asked, changing tacks quickly and startling Jacob with his aim. This was how it worked—score a point and then veer away. "Nope," he said. Oliver now had only two options, the first being to press him "Well, what then?" but he'd go with the second, a long, tense silence. A _Stille Nacht_ in the trench warfare of their conversation. Jacob would be damned if he'd cave, like a patient on his couch, and answer the question. Jacob had never told _anyone_ what he'd wanted to be as a child. Oliver's intuition had led him to the right spot. It wasn't a typical embarrassing juvenile wish, like wanting to be a fireman or a professional wrestler or a helicopter pilot. No, it was far weirder than that. Long ago he had sworn he wouldn't tell, and he never had. Not to his mother and not, in all his nights of drunkenness, to Sara or Irene. Not even George knew this particular secret, and he knew Jacob's ATM pin (3825, spelling FUCK on the keypad), the music video he'd first gotten off to (Aerosmith's "Love in an Elevator" on MTV late one night at his grandparents' place in Daytona Beach), and the name of every boy Jacob had ever slept with—or at least the ones whose names he'd known. Never being hung up about anything was a source of pride for Jacob, but this secret he'd sworn he'd never tell. He'd sworn it to God. And even though he didn't believe in God anymore, thinking about saying it still made him sweat. Jacob switched from the tea to a _large_ glass of red wine and though he was still picking at his own food, reached over to grab the menu wedged between the soy sauce bottles and began counting up the available items. Fifteen appetizers. Nineteen special items. Eight vegetable dishes, including "dynasty shyimp," which he didn't think was a vegetable, typo or no. Four chow meins, nine diet items, and twelve dim sum options. Five kinds of egg foo yong and six fried rices. Four lo meins, five mei funs, and four side order options. Seven items marked "our most popolur enteree," distinct on the menu from the "top ten best sellers !!" Twelve kinds of soup, and twenty-three special combination platters. "There are one hundred and thirty-four different things you could eat here," Jacob announced to Oliver, who was finishing his beef and scallops combo, the number-two special. "That seems like quite a lot," Oliver replied, as he dabbed brown sauce from his lips. "It _is_ a lot," Jacob said. "But it is still a _finite_ number of things. And yet you eat here _every_ night. And I'm not being hyperbolic. I mean, I'm not exaggerating—" "Yes, Jacob. I went to Oxford, and I know what _hyperbolic_ means. And I know—" Jacob knew he knew. They'd had countless meals together at Szechuan Garden and had this same argument practically as many times. "You eat here _every_ night. You don't eat at any of the hundreds of other restaurants in Stamford. Nor do you ever go to eat in Manhattan, which is just a train ride away—" "If you'd ever let me come over to your apartment . . ." "—where there are literally thousands of restaurants. And Brooklyn and Queens, which are, as we speak, in the midst of a dawn-of-the-century culinary renaissance where Michelin-starred chefs are grilling foie gras in aluminum-sided diner cars! No. You choose to eat every meal in this one place." "You're really very fixated sometimes," Oliver said in his best therapist's tone, pressing the tips of his fingers together in the same way as always, so that his hands became a little cage over his heart. "Consistency can be as much a virtue as variety. Besides, I like it here. These people feel like family. And the restaurant is only four doors down from my flat. But since you know that already, I have to conclude that this isn't what's really bothering you. Is it?" "What do you think it's about then?" Jacob fired back. He was simply dying for Oliver to bring up Irene. To say something idiotic like "you know she'll be fine" or "she's lucky she's so young" or "I'm sure your companionship means so much to her." But instead Oliver said, "I think maybe you're feeling some guilt about the lopsided shape the commitment in our relationship has taken." _What a passive-fucking-aggressive way of saying_ that, Jacob thought. Feeling competitive, he skipped the _passive_ in his own response. "You mean how you sit around in your flat listening to Beethoven and watching _Animal Planet_ while I fuck other people?" The words drew just a drop of psychic blood before Oliver regained his maddening calm. "I'm a monogamous person," Oliver said calmly. "You know this about me." It was true. Throughout his boarding school years, Oliver had pined away for the same allegedly straight classmate, except for Saturday mornings, when he'd come over to Oliver's to fool around. Adopting this same confusion, Oliver had actually married a woman at age twenty, whom he hadn't cheated on once in the three years before they'd separated. "Moreover I know that you are not, and you also know that this is perfectly fine with me. You're young—" "I'm not _saying_ that right now. Aren't you listening to me? That's not my point!" "Then what _is_ your point?" Jacob thought he might rip his hair out by the roots. "My point is that you are a _mental health professional_!" he shouted, so loudly that it jolted a nearby couple from their cell phone screens. He imagined the fish in the tank rushing behind their fake, red rocks— Oliver didn't raise his voice even a decibel. "And?" "The owner here bought you a tie clip on your birthday this year!" "It's your own choice to order the Dragon & Phoenix every single time." "Actually I get the ' _Dargon_ & Phoenix' every time, thank you very much." Oliver rubbed his eyebrows. "My point is that I never order the same thing twice." "But you _do_! There are three hundred sixty-five days in a year and one hundred forty-six menu items, which means that you _must_ eat the same thing at least two and a half times every year." "And you never eat the same thing two and half times in a year? You've probably had 'Dargon & Phoenix' at least twenty or thirty times with me here by now." "Yes, but I have also eaten a Guaco-Taco from San Lupe and spanakopita from the Olympic Flame Diner and chicken à la king from Bistro 19! This week alone I've had _three_ kinds of frozen yogurt!" Oliver grinned the way he always did when he was sure he was about to win. "But that's what you _always_ get at those places." "Meaning?" But Jacob could already feel the point sliding away from him. "Meaning why is it wrong that I order different things from the same restaurant every night, and _right_ that you order the same things from different ones?" Jacob opened his mouth, but no fire came forth. Why _should_ it be wrong? Wasn't it more wrong that they had such a glut of dining options that they could eat somewhere different every night of the year, without repeating? That morning on the train Jacob had read an article in the _New Yorker_ about a mountainous area of China roughly the size of France; its slopes were dust, and its citizens were malnourished if they weren't starving. What sort of God created all men equal but then said _fuck it_ when it came to the corners of the earth? What did the old lady mopping the floor in the back think about him leaving a third of his "Dargon & Phoenix" on his plate? The look she was giving him was the same sort that the crones in the cafeteria of Moses Maimonides Elementary had once cast his way when he'd eaten only the Hydrox and ignored the rest of his lunch. And how had the rabbis explained it? _Because we are the chosen ones, beloved of God_ , had been the line until about third grade, at which point they began to add _Because we were slaves for centuries, and then we wandered in the desert for forty years, and then we lived in unfriendly lands for more centuries. Always strangers, always scapegoats. Killed in Crusades and Holocausts that everyone else has forgotten._ For their ancestors being forever fucked over, then, the logic seemed to go, it was okay for the Blaumann family to be better off now. There was often the suggestion that probably it would be only a short while before someone figured out how to take it all away again. This interpretation had reigned until he'd been bar mitzvahed and begun taking practical accounting and economics, at which point the reasoning became nonsecular: _Because you are a participant in a prosperous free economy, in which the work your parents do is valued at a certain amount by the invisible hand of the market, and soon you will take your place in this grand system yourself, and through savings, investments, and avoiding the temptations of credit, you too will deserve privileges and comforts that others do not._ " _Hazan et hakol_ ," Jacob muttered. "A rabbi?" Oliver asked. "Is that what you wanted to be when you were a child?" Jacob shook his head. He half wanted to tell him—it was just nonsense and stupid superstition. So he'd sworn. So what? Was he going to be struck down there in Szechuan Garden? He opened his mouth to just _say it_ after all this time, but the instant he did, he felt the phone in his pocket buzzing. He took it out and saw Irene's picture on the screen. "Hello?" he said, almost before he'd actually answered it. "It's Sara" came the voice on the other end, the sound of an ambulance backing up somewhere in the distance. "Irene's fine. I took her phone because I get no reception in here." "Did she go under all right?" Jacob asked softly. "We should know something in a couple of hours," Sara said, and Jacob could tell she was at the end of her rope. "But George is losing it over here. He needs to go for a walk, and I have to finish these articles by Friday." "You want me to take him to the park or something? Let him play in the dog run?" Jacob smiled, just long enough that Oliver smiled. Sara, however, sighed short and sharp. "I don't care _what_ you do with him, but if he stays here another minute, I'm asking the nurses to sedate him." "Tell him to meet me at the Bistro in an hour," Jacob said, as Oliver called for the check. They walked back to the flat. Kissed and made up. Oliver insisted he take an umbrella and called him a cab down to the train station. • • • From the Hell Gate Bridge, Jacob saw his city, lit up and unreal, as ever. The tip of the Empire State Building was the electric blue of a urinal cake. It was half obscured by the fat clouds above, smoke thick, soot black, but reflecting everything beneath it. Broadway's streetlights, the Times Square spotlights, the postgraduate apartment $4.99 IKEA track lights, the cigarette embers leaning out the windows of the Frederick Douglass Houses. A trail of white headlights flowing over the Triborough Bridge into town, and the ghostly trail of red brakelights limping back out through the jam. At Grand Central, Jacob clutched Oliver's umbrella in front of him like a shield, pushing past the crowds on the stairs and in the station and then on the sidewalks, under a white wash of streetlights, past the pale hordes in Bryant Park and Rockefeller Center. He tried to visualize what must be happening to Irene. He held it in his head like a poem, words and images and process. Awesome, in the old-fashioned sense of the word: inspiring of awe, to the point of humbling. The things they knew now, the things they could do. Less than fifty blocks away, in a sterile room, Irene was dressed in a loose white gown, laid out like a drowsy queen, the doctors circling around her like humble servants. According to what Sara had relayed to him from Dr. Zarrani, a tube would deliver pure oxygen through a mask, attached by an elastic strap. Clips would be attached to her fingertips and beige cups suctioned to her breastbone to measure the rate of her heart beating, the pressure of her blood. Lower down, a squid of electrode wires would creep across her thorax and out to her wrists, taking pulses back to the electrocardiogram—the EKG—while a pulse oximeter and a capnograph measured the oxygen and carbon dioxide in her blood. The first tumor would be removed via a periorbital excision, during which an invasion of her eyeball itself could—ideally—be ruled out. If not, they'd have to remove the eye itself, but the doctors had said there was essentially zero chance of this happening. Then, while a plastic surgeon began an ophthalmic reconstruction, the surgeons would move to the left arm, where the second tumor could be removed—along with a significant portion of the ulna to ensure that the cancer was fully contained. The extracted bone would be replaced by a graft from the iliac crest, this being the superior border of the "wing of ilium" (Jacob liked the delicate, angelic sound of that) along the superolateral margin of the pelvis. The truly good news here, according to Sara—who had taken on the role of interpreter between Irene's doctors and the rest of them—was that the preliminary lymph node biopsy had come back clean, and the doctors believed there was a far superior chance that the postsurgical radiation and the second round of chemotherapy would have a lasting effect on the cancer, now that they were in the—again, less-than-ideal—situation of metastasis. Irene had progressed from stage one to stage two, which meant that the initial lump had sent off phalanxes in search of new territories. It had come down the mountainsides and into the valley of her elbow. But it hadn't yet gotten to the ports. The lymph nodes, which traversed her whole body, were still unconquered. If only he could write it, somehow. If only they were words on paper, not facts in Irene's body. • • • At Bistro 19, Jacob found George right where he expected, on the burnished brass stool at the far right, leaning heavily against the gray marble bar top. His top two buttons were undone, and his powder-blue sleeves rolled to the elbows. His dusty brown hair showed traces of fingered agitation, though now his hands were clasped as if in prayer around his whiskey glass. Jacob thought he looked like an off-duty priest having a word with his heavenly employer. Or he was only staring up at the grape-stained light coming through the old Tiffany chandelier, which hung elegantly above the bar with its leaded-glass vines and little winged cupids. George loved the ugly thing. To him, they conjured up the old New York—European money, Cole Porter, high style. "I'm gonna have one of these in my study someday," he'd say in awe, when the third or fourth whiskey had hit him. In the back of his mind, Jacob planned to buy George a lamp like it someday, whenever their ships came in. Jacob decided to keep his jacket on but stowed the oversize umbrella in the stand near the door. George hadn't even noticed him entering, he was so absorbed by the lamp. "Bless me, Father Murphy," Jacob sighed as he flung his weight onto the stool, "for I have sinned." George looked down at his watch. "All right, but let's save some time, and you just tell me the ones you _haven't_ committed." "I'm fine on graven images," Jacob said after a second's thought. "Never killed anybody. And I suppose I don't exactly covet my neighbor's _wife._ " George clicked his tongue. "Nuh uh-uh! 'Nor his manservant, nor his maidservant, nor his ox, nor his ass . . .'" "Oh well, if you want to get into the fine print." "I just know how you can be around oxen, that's all." George downed his whiskey and motioned for another from Flo, the no-nonsense French grandmother who worked behind the bar, whose hair had been dyed to a fire it had never known in youth. She topped off George's glass with J&B and then began making Jacob his usual—a gin martini with two onions. "I can sing all the books of the Old Testament to the tune of 'Ten Little Indians.'" "Please don't," Jacob said, as George began to lift an imaginary microphone to his mouth. "I've had enough flashbacks to Hebrew school for one night already, thanks." "Awww. Did Dr. Oliver try to get you on the couch again?" George joked. "Metaphorically, I mean. Not literally. I mean, literally's fine too, but—oh! Hey, guess who's here? Look over in the corner there." Jacob turned casually in his chair and looked into the dark, rear corner of the restaurant, where he recognized the narrow profile of William Cho. He was wearing a well-tailored gray suit with a dark wool tie. He had clearly just had his hair cut, perhaps at the request of the girl seated across from him, sharing his order of the mahi-mahi. She was maybe a few years younger, also Korean, with liquid black hair that spilled over her bare shoulders. Her great dark eyes were fixed lovingly on William. His were looking back. "It's William, right?" George was saying. Jacob saw William swivel slightly in his chair, noticing them at the bar and stiffening, twisting around to keep his back to them and his face toward his date. George looked annoyed. "It's pretty ballsy of him to bring a date here. He knows this is one of Irene's—I mean, he knows this is our place." Jacob hummed in agreement. It _was_ ballsy of William. Uncharacteristically ballsy. He watched William, who was clearly pretending to listen attentively to his date while not so slyly looking at the two of them in the reflection of the mirror on the far wall. George did a few quick twists on his stool and nearly slid off. "So. You were saying. About Oliver? He's been picking your brain again, has he?" "What did you want to be when you were a child?" Jacob sighed, but George thought he was asking, not answering. "The winner of the Nathan's hot-dog-eating competition. What did you want to be?" "A carpenter," Jacob lied. "What, like you wanted to build houses?" "No," Jacob said, "I mean I wanted to be Karen Carpenter." George made an inaudible crack about bell-bottoms. Jacob shook his head. "I really need to break this thing off with Oliver." "Never a good idea to date the guy who signs your paychecks, I've always said." "You're marrying a woman who shares your bank account," Jacob reminded him, as Flo finally came back and pushed his martini toward him. He pulled the tiny cocktail sword from the onions and let them settle into the conical bottom of the glass. "A man's got to have his secrets," Jacob continued. "How are you going to pay off all your mistresses if you don't have any money of your own?" George hummed for a moment, as if considering the possibility. "I can't think of anything more terrifying than having a mistress," he said finally. "I can barely keep track of Sara. You ever watch that show about that Mormon guy with all the wives? He's got three wives, and he spends the whole time trying to keep them from killing each other. No thanks." "You don't _marry_ all of them! That's the whole—have I taught you nothing?" "You taught me how to make chili once." Jacob sipped at his drink as he launched into a long tirade about the antiquated concept of marriage, how it had originated as a way of transferring property, a means of arranging for the exchange of goats and camels. How in the twenty-first century women especially ought to be fighting this old-fashioned way of thinking, this imperialism of the heart and the sex organs. He was hardly feeling drunk at all yet. He wished he hadn't had coffee on the train. But how else was a man supposed to stay awake long enough to get properly obliterated? Then George went on about Sara, and the wedding planning, and God knew what else, Jacob stared down into his martini glass. The two little onions stared back up at him. He was exhausted, and his stomach was a great un-Pacific ocean of alcohol and caffeine. His bones ached in a way that he could feel them, independent of his flesh, and it made him feel like a skeleton in a Jacob suit. God. He didn't want to be pain-in-the-ass Jacob. Not tonight. He wanted to be fun-and-funny Jacob. Court-jester Jacob! Did other people get as tired of being themselves as he did? How could they manage it, when most of them seemed so goddamn dull? What were William and his date talking about? _What did anyone actually talk about?_ The dry weather? His boring job? Her ambitions to someday work in fashion? George leaned back a bit too far on his stool and nearly fell. "Be right back. Going to hit the loo. Keep an eye on our friend over there. I want to be able to give Irene a full report on Mr. Cho's hot date when she gets up." Jacob sighed and took advantage of George's absence to check his phone for messages from Sara. But there was nothing. He saw that William and his date were pretending to squabble over who paid the check. _Oh my goodness, who will win?_ Jacob wondered, rolling his eyes as she acquiesced and permitted him to pay. _And what did you want to be when you were a child, William?_ A spineless, self-important, soulless jerk? A hypocrite who studied literature before going into finance? Someone who beds the finest woman in all of Manhattan and then ditches her the second she needs help? Jacob had half a mind to stalk over there and lay him out, right onto the plate full of obsessively picked-over fish bones. But he remained seated, tracing something out on the surface of the marble bar, writing the ancient characters in the sweat from his drink: . Once Jacob had been forced to write it five hundred times in a notebook. _What did you want to be when you were a child?_ It was the day he knew he could never become this thing. The two ladies began to count out their bills and fish through their change purses for the _exact_ right amounts. Jacob's father had done the same after every meal, as if a penny wasted here or there might be the difference between starvation and survival. Never tipping—not even when they'd gone to the Gramercy Tavern and Jacob had dipped his jacket sleeve in mustard, and the waiter had scrubbed it out with club soda for them—even then his father had left the exact bill, down to the rotten penny, and left without a word. Sometimes Jacob's mother would still pretend to forget an umbrella or pen, then rush back to find it and slip a few dollars onto the table—a few dollars of the pitiful allowance that Jacob's father gave her each week to cover the costs of groceries and housekeeping . . . not because he couldn't afford more—a lot more—but because he didn't trust her with it. "Get you anything else?" Flo was asking. "Just the check," Jacob said. He didn't feel drunk at all, but it seemed like George had had enough. He looked over and saw that William and his date had left. The bill came, and he almost sent it back. How could there be only three drinks on it? From George's slump and dreamy eyes, Jacob would have sworn that he'd tossed back three on his own before he'd even arrived. When everything was settled, Jacob got up off the stool and went back to the men's room to see what had become of his fine feathered friend. The little door marked _Hommes_ was locked, however, from the inside. "You fall in?" Jacob called. "No, no," George called back. "Sorry. Just a minute. Texting Sara something." Jacob thought he sounded drunker than when he'd left. "That's disgusting, George. That's how people get parasites." He could hear George shuffling around clumsily. Jacob sighed. "We're all settled up. I'm going outside for some air." • • • Jacob stepped out onto the sidewalk. It was a few moments before he realized that he had left Oliver's umbrella inside, and so against all his principles, he texted George to please grab it out of the bin before he came out. Great winds rushed down the valley between the dark buildings. It was surprisingly quiet, there on the cross street. In fact, Jacob couldn't see another person all the way down the block in either direction. How often did that happen in Manhattan, he wondered, even at this hour? Both lanes of Fiftieth Street were being ripped up, so traffic was being diverted around the block. No construction crews were working so late, but the lanes were still closed off by fat barrels, striped in orange and reflective white. Somewhere several young women were screeching about something or another, but only an echo reached Jacob's ears. The wind blew westerly, carrying empty soda bottles and discarded Subway sandwich wrappers. A chewed-up looking scarf. A mashed-down cardboard box. Swarms of cigarette butts. He watched them scatter over the broken blacktop, heading out toward the avenue. Far off, by the old Lehman Brothers building, he watched two tall men in dark coats with briefcases exit a gleaming white revolving door. Glass, of course. They were all glass these days, the doors, the buildings too. Transparent but tinted. Delicate but impenetrable. Lessons learned, after 1929, were limited to making sure the windows no longer opened. No one liked to see their stockbroker sailing down past their thirtieth-story window. Jacob remembered the time Irene had taught him to press his hand against the building glass. It vibrated, alive. They built them to be slightly flexible, she'd explained, so they could lean this way and that, in high winds. Then, at his back, Jacob felt a rush of cool air. He turned, expecting to see George at last, but instead it was William Cho. "Were you still in there?" Jacob asked. William nodded cautiously. "Yeah. I bumped into George in the bathroom. Or I mean, he bumped into me. Then he locked himself in a stall." "He's pissed," Jacob said coolly. "You broke up with our friend when she was sick." He expected William to make some excuse, but the boy made no motion to deny anything. "So she finally told you she's sick?" Jacob's face twisted. He hated that he'd been the last to know, but especially that William had been the first. "And I guess you hate me too now?" William asked. Jacob coughed. "Well, that's not really fair. I hated you before." William nervously kicked at the wall. "How is she doing?" Jacob didn't feel like telling him anything. "What happened to your date?" "I put her in a cab," he said, extending his thumb over toward the avenue. "Seemed like she'd have been happy to go home with you." "She's the daughter of a woman my mother knows through her church," William explained. "I tell her I'm not interested, but they don't care. 'But Sung-Lee went to Harvard to study art history! And now she works for an important pharmaceutical company,' and I say, 'Good for her.' She says, 'But Sung-Lee's father owns four spa complexes in Passaic County.' Eventually it's easier to go on the date than to explain to my mother that I'm in love with a white girl with no family who's dying of cancer and won't return my calls." Jacob didn't want to laugh but couldn't help himself. Then the door to Bistro 19 squeaked open again, and out spilled a very drunk George, his arms wrapped tightly around a dozen umbrellas. He looked up in surprise at William, then at Jacob, then back down at the umbrellas in his own arms. There were floral patterned ones and small beige ones and green ones, and there in the middle of them all was Oliver's black one, from Harrods. George didn't quite seem to know how he'd come by them all. "Which was yours?" he asked. Jacob broke down and laughed until he thought he'd cry. William, not sure what else to do, laughed too, and George laughed so hard, he dropped the umbrellas onto the sidewalk. The two boys hurried to help him pick them up, and then it seemed like they ought to book it before anyone realized what George had done. Suddenly the night seemed young, and before any of them quite knew it, they were in a cab, umbrellas stuffed in every pocket, the sounds of horns and motors bringing them down and east. The driver let them out below Union Square, which was mobbed with the usual late-night crowds of skateboarders and spectators. Little brunette girls in wool caps emerged from Whole Foods, burdened down with reusable bags. Yuppie couples headed out of Craftbar and into karaoke bars. Kids trying to look dangerous while sipping Jamba Juice outside the Best Buy. An old man lingered by the windows of an antique emporium, looking at an $8,000 Louis XV armchair—if he was worth a million bucks or homeless, Jacob couldn't tell. "Here's what I propose," William said. "We're going to get royally smashed. And I'm going to tell my bosses that you're looking for legal advice about your investments. And they'll pay for it. Tell me something, George. Are you looking for new ways to invest your money?" "Am I ever!" he cheered. "You know, I've got this bottle-cap collection back home in Ohio, but I really hate having all my assets tied up in beverage futures." William grinned. "What if I told you I could turn those bottle caps into a triple-tax-free retirement account? Let's discuss it further over drinks." "Let's!" George shouted, as if Willy Wonka had just invited him into the chocolate factory. Jacob raised his hands to the full moon. "You know, with this sort of responsible behavior, it's hard to fathom how you all managed to destroy the American economy." "Rats to the economy," William said. "I hope we all end up on breadlines." George was already half inside the bodega. He emerged in a moment with three cans of Red Bull, which tasted to Jacob like an emulsion of toothpaste and motor oil but provided a jolt sufficient to make them feel like college freshmen once again. _This shit's going to give us all cancer_, he nearly said, but realized it wouldn't have been funny even under other circumstances. They began at a quiet Greek place called Smyrna, more or less because it was the nearest visible restaurant with a bar in front. William's AmEx had soon procured them a round of cocktails involving metaxa and brandy, plus an order of braised baby octopuses to share. Jacob grew listless as William and George actually _did_ become deeply engaged in a conversation about the capital gains tax, SEP accounts, and something to do with paying for Sara's contact lenses with pretax dollars. Boring. Jacob gulped at the brandy concoction but only felt further lost inside the brown fog of his own head. Oliver, Irene, Rabbi Kantrowitz, the scent of his father's corn-riddled feet—everything he had intended to obliterate came crowding in. The bartender, a hipster kid in a peasant vest whose mustache and goatee were devilishly curly, brought them all a round of complimentary ouzo shots. They downed them all in one, with a cry of _Opa!_ at the bartender's gleeful count. Jacob felt the kid's eyes lingering on him afterward, and so when he excused himself to the closet-size restroom a minute or two later, he wasn't entirely surprised when the kid followed him in. "Won't your friends miss you?" he asked mischievously. The single hanging light in the bathroom was dim against the deep, violet wallpaper but cast handsome shadows over his face. "Those two?" Jacob said. "They're not my friends. The Asian guy's actually a Shaolin monk. Don't let the suit fool you." "And the other one?" the bartender giggled, as he closed his eyes and eased close enough to graze his mustache against the bridge of Jacob's nose. "He's my priest," Jacob said, breathing in deeply, letting the smell of his cologne fill his nostrils . . . something vaguely like currant jam that lifted away the smells of the restroom, and the memory of worse smells: of his father's feet, of Thomas's puke. "I was guessing you were Jewish," he said, opening one eye as if to check. "I'm a rabbi, actually," Jacob said. "We walk into bars looking for a punchline." He pressed his lips to Jacob's. The brown fog began to clear as Jacob turned his eyes up to the ceiling and arched his back. Something started up in his guts like a four-stroke engine, throbbing, waiting. "My name's Jeff," the bartender murmured. "Nice to meet you, Jeff." "This is where you tell me your name," he breathed. "I—I—" Jacob tried. He tried to say his name, or maybe he did; he was past knowing or caring. With eyes clamped shut, he felt the quickening of his heart and let its echo mix with his own breathing to fill his ears. He felt Jeff's hands move down over his chest and then lower. As the sensations rose up his spine, he tried to intercept them at the base of his skull, to convince himself that they weren't being induced by the hands and lips of a total stranger but by someone else. What came instead was the long-lost memory of a boy named Isaac. Jacob's first kiss, during swim class at school. Jacob was uncomfortable enough at this but then, unwilled, the image changed in his mind to that of George, and feeling loathsome enough already, he finally settled on the one person he knew he could keep in mind: Oliver. _How awful,_ he thought, _to cheat on your boyfriend and then imagine you're with him._ He shuddered, half at Jeff's touch and half at his own mental use of the word _boyfriend_. And it wasn't cheating, was it, when just a few hours ago they'd been discussing the openness of their arrangement? Jacob began to imagine what might be happening if Sara hadn't called. If George could have held his shit together a little better. He wouldn't be there, in the violet restroom of a Greek restaurant with hipster-bartender Jeff, but home. Well, Oliver's home . . . which by now felt more like home to Jacob than his own. They'd be in the cradling softness of the cracked leather divan, smelling the faint perfume of the laundry Oliver had carefully laid out on all the windowsills to dry throughout the day. Oliver didn't trust dryers and preferred to do the washing by hand, as he'd done at school. Up on the wall, the blowup of an old French magazine cover of a gentleman in a silk top hat, rakishly low on his head. Jacob tried to hear the music in Oliver's study. He'd have on something familiar. The Eighth Symphony . . . just loud enough to mask the sound of an Animal Channel special on the elm bark beetle, which had introduced Dutch elm disease to North America. Not the beetle's fault really, but a fungus it carried. Jacob had liked the name of the fungus— _Ophiostoma ulmi. Ophiostoma ulmi. Ophiostoma—_ It all came swiftly to an end. Jacob swayed, low, and felt everything ebbing away. Jeff moved his head away to one side, and Jacob felt cold. _La petite mort_ , Jacob remembered every time. _The little death_. What better way to describe it? When he got back to the table, George and William had moved on from IRAs to the topic of Irene, barely noticing his absence. Jacob quickly got their bill from the other bartender—Jeff was no longer anywhere to be seen—and slid it to William, who signed it and pocketed the receipt wordlessly, while George detailed the trip to Shelter Island and the discovery of Irene's second tumor. He paused just long enough to bequeath a tall beige umbrella to a shaggy-haired gentleman next to him, and by the time they'd gotten back out onto Twelfth Street, the current surgeries had been outlined, and William was looking green-gilled. They ambled along the sidewalk, past the Strand and down Fourth Avenue, looking for a bar called Queen Elizabeth's that William had heard about. Not finding it, they ended up in a Brazilian restaurant, mostly because George had to pee again, and in the meantime Jacob and William had two caipirinhas apiece and made pleasant small talk. Then, in exchange for a scarlet umbrella, their server told them where to find Queen Elizabeth's, through an unmarked door in the back of an Indian restaurant named Shantih. They had a few drinks there, which all seemed to involve egg-white foam, and after that Jacob couldn't remember much. A sports bar. Some New Zealanders. George handing out umbrellas like party favors. They had called Sara at some point, to check in. No news. Was George okay? she asked. Depended on what she meant by okay. Don't be cute. Can't help it. So she'd be sleeping in a hospital chair all night while they gallivanted around the city? He'd offered to send George back there, and she'd hung up. Jacob remembered mostly feeling as if his feet were stuck with tar to the sidewalk, although at other times as if he were drifting like a loose barge through Greenwich Village. And he remembered thinking he'd never been happier in his life. He'd long forgotten whatever beef he'd had with William, and whatever worries he'd felt for George. He'd obliterated the name Oliver from his mind and thought he had no father on this earth. Who Irene was or where, or what might be being pumped into her or carved out of her—all were questions he'd forgotten how to pose. That which was Jacob was coming apart. His last, hazy memory was of standing out on the sidewalk, staring in confusion at the flooded street. He remembered George asking, "Hey, when did they put a river through here?" as Jacob had felt a sopping wetness in his socks. Passing cars were throwing up black waves in confusion. "A water main burst on Sullivan!" someone—he thought it was William—was saying. George had opened up the last of his umbrellas—a huge yellow one—and was attempting to climb into it so as to sail home again. Jacob pitched backward and all he could see were the tops of buildings and a starless sky. The last thing he remembered feeling that night was William's surprisingly strong arm around his shoulder. Jacob was already half dreaming that George was now rowing them downstream in the yellow umbrella. The things he thought and saw were connecting nothing with nothing, and everywhere there was the roar and flash of fire trucks. • • • The boy lived in a "not very Jewy" part of Westchester. At least that's what his mother said when his father wasn't around, which, thank God, was fairly often. Things had a way of working out like this for the boy. His father sold supplemental life insurance and was generally best avoided. His mother did everything for him, and as far as the boy could tell, his father never did anything for her. She had even become Jewish for him, something she brought up a lot, which was why the boy was Jewish, but his father acted as if this were no skin off her back at all. The boy did as many nice things for her as he could think of, to try to make up for it all. His mother told him how special he was at least once a day and sometimes more often. Every morning his mother drove him thirty-five minutes up 684 to go to Moses Maimonides, the school his father had picked out for him to attend. He was in the third grade. He asked if he could attend the school right down at the end of their street, and his mother said no; it was just for Catholics. He didn't know what that was, so she explained that a Catholic is a kind of Christian, which is someone who believes in Jesus, who lived a long time ago and who Christians thought was the Messiah. That last part was in the Torah, which he had at school, about a man who would come to bring all the sinners on earth up to heaven. Anyway, they thought it was Jesus, who'd be back later, but other people, like them, disagreed and thought whoever it was hadn't come around yet. The boy asked why it mattered if he'd come and gone or not come yet, and his mother said that this was a good question. When he asked his teacher, though, he got sent to Rabbi Kantrowitz's office. But Rabbi Kantrowitz agreed it was a very good question, and then took out a big, dusty book called the Talmud and showed the boy where another rabbi from a long time ago named Maimonides, whose name was now on the side of the boy's school, had written about what the world would be like when the Messiah finally showed up. "'And in that time there will be no hunger or war, no jealousy or rivalry. For the good will be plentiful, and all delicacies available as dust. The occupation of the entire world will be only to know G-d . . . the people Israel will be of great wisdom; they will perceive the esoteric truths and comprehend their Creator's wisdom as is the capacity of man. As it is written, _For the earth shall be filled with the knowledge of God, as the waters cover the sea_.'" This sounded pretty good to the boy. He asked if Rabbi Kantrowitz was the Messiah, and the rabbi said no, the Messiah would be a very, very special person. The boy was about to ask, _Could_ I _be the Messiah?_ when he was shooed off to class. The more he thought it, the more he was sure it could be him. He was the best in the whole grade at math, reading, _and_ history. He knew every possible statistic about the Chicago Bulls by heart. He had won a prize for the best essay about what the world of 2010 would be like (undersea villages, connected with tunnels). He was patient with all the other boys, despite them being stupid when it came to subtracting large numbers, and sticking their fingers up their nostrils, and forgetting how to spell _pepper_ or what the capital of France was. There were other things too. The boy had once, when no one else was around, levitated a spoon with his mind. He couldn't do it again later, when his mother was there, although she said she'd definitely seen it vibrating. The boy could sometimes make his favorite songs come on the radio just by thinking about them. Every day the evidence grew more impressive. He began looking forward to the day when he'd fix all of mankind's problems. But it was hard to know that he was the Messiah and not be able to tell anyone else. The only boy he thought he might be able to trust with his secret identity was Isaac Schechter, who sat up front in all the classes and nearly always got the answers right, except when it came to long division. The boy had wanted to be friends with Isaac for a while, but his father wouldn't allow the boy to invite Isaac over after school because he said Isaac was a "sissy." At school, Isaac had speech therapy during normal lunch hour, so the boy couldn't sit with him, and he already had Zeke as a lab partner. Finally, during swimming at gym class, his prayers were answered (of course), and the boy and Isaac were paired up. God had made it happen. For three wonderful weeks, during swim class, he and Isaac covered the same position in water polo games. They changed in the same corner of the locker room. They always compared how pruny their fingers would get in the water. When Isaac got cold, his lips turned a little blue. Isaac didn't mind sharing his towel if the boys got splashed near the pool. Secretly, the boy splashed his towel on purpose, just so they could share. He didn't really know why. He just knew that he liked knowing the towel had been on Isaac's skin just before it was on his. The final day of swimming came, and the boy gave Isaac a special signal they'd devised, which meant to dive when the teacher wasn't looking. Underwater, sound traveled better than in the air, and more important, all the people up on the surface couldn't hear you. "I HAVE TO TELL YOU A SECRET!" the boy shouted. Isaac pointed to the top. Both boys went up to the surface and took really deep breaths. Then the boy put his hands onto Isaac's shoulders, and Isaac put his hands on the boy's, and they pushed back down under the water. All around them it was blue and still. This was what it would be like in heaven, the boy thought. When God covered the whole world with the sea. Warm water covered him like a blanket. His hair lifted lightly from his scalp. Far away, the other boy's legs were kicking and swirling up white tornadoes of bubbles. Isaac's hair was floating like a halo around his head. They were gripping each other's arms to stop from rising up. Isaac's dark eyes were searching, and then the boy saw his blue lips open to release a big brilliant bubble. And then they were kissing. The boy wasn't sure if he'd started it or if Isaac had, but he never wanted to stop. He felt dizzy, and the water around him began to burn with an intense white light, and he thought he could hear the voice of God from all around him, calling his name— Then in an instant it was all over. Mrs. Cogen, the gym teacher, had pulled them both to the surface. She was very angry. She marched him straight to Rabbi Kantrowitz's office before he'd even dried off or changed his clothes. There he sat, damp and shivering, in an old cantor's robe, until she finished telling the rabbi what had happened. When Rabbi Kantrowitz took the boy into his office, he asked why the hell he had tried to drown poor Isaac. The boy didn't realize, and wouldn't realize until he was older, that neither the rabbi nor Mrs. Cogen knew that they had kissed. The boy explained that he had only been trying to tell Isaac something important. A secret. And the rabbi had demanded to know what it was, so the boy tried to tell him that he wasn't like the other boys. That he was special. He wanted to cry out, _I'm the Messiah! I was sent to unite the tribes of Israel! I am_ _the one who wrestles with the angels. I am the one who will prevail with God._ But these things all seemed silly the moment he considered them out loud. The rabbi took the boy to an empty classroom and handed him an empty pad of paper. Carefully, he wrote something in Hebrew at the very top of the first page. The rabbi said that it meant "I am not special" and that the boy would write it on every line on every page until it was full. This took the rest of the afternoon, long past the time when the other boys were sent home. His hands ached and ached. He thought maybe his mother would rescue him from this punishment, but she didn't come. When he finally finished, his father came to take him home. He didn't say a single word to the boy. When the boy looked up at his father, he saw that he looked a lot like him—a little large, the same bristly hair, the same big hands. He thought about Isaac's blue lips. His hands still throbbed, but it was his heart that ached worse than anything else. _I am not special,_ it beat. _I am not special. I am not special_. The words were stuck in his mouth like a piece of paper, all wadded up. They were like the first line in a long, long poem that might take a lifetime to finish writing. • • • Jacob woke up to George's snoring. Very slowly he came to the conclusion that he and George were lying side by side on the blue pullout couch they'd bought at the Toronto IKEA during their junior year of college, when they'd lived in a row house off campus. However, as Jacob slowly recalled, he and George were no longer in college, and they no longer lived on East Street in Ithaca. The blue pullout resided now in _his_ apartment, which meant that he was _also_ in his apartment, which meant that _George_ was in his apartment as well. This would have been bad enough, but then, very slowly, Jacob gathered from the sound of dishes being washed that someone else was there too. A third person. William Cho. Jacob's first instinct was to rise, thunderous from the bed, kicking and swearing until William was halfway back to Queens. But his body was in no condition for thundering. His throat was Death Valley dry, and even trying to form swear words was taxing his bruised brain. He remembered that William had still been there at the end of the night, his face sweaty in the flashing red lights of the fire trucks. William had been supporting him and carrying George on his other arm. Jacob could still hear the echo in his ears: water, roaring behind the buildings. "Coffee," Jacob rasped, his vocal cords raw. He tried again, raising his voice above the rushing of the sink. "COFFEE!" "Shush," William said. Jacob found it superbly irritating that he actually _said_ the word instead of making a shushing noise, but then he figured there wasn't much he wouldn't find superbly irritating in his current condition. William came over with a glass of water. "This isn't coffee," Jacob croaked. "Coffee's just going to dehydrate you more," William said. "You should have had water last night when I was trying to make you." Slowly Jacob remembered being in the back of the cab, trying to cool his sweaty cheek against the cold passenger-side window. "Were you in the cab last night?" he finally asked, slowly rising to his feet. Carefully, he crossed the treacherously piled floor to get to William by the sink. "You and me and George. Who you're going to wake up, by the way, if you keep shouting like that. This place has a hell of an echo . . . I've never seen ceilings this high. You've got more fly space than floor space in here. What is this, like ten by twelve by thirty?" "Twenty-eight and a half," Jacob corrected, and though he knew full well it was a bad idea, he still craned his neck back to look up at the thick oak beams in the ceiling. The act made him so dizzy, he had to sit down on the floor and lean his head against the fridge. The plastic door was wonderfully cold and smooth. He closed his eyes and thought he might just go back to sleep, but then a baby outside began wailing, so close that he could also hear its mother, crying back at the child to "please _, for the love of God, stop crying!_ " "Lot of people out there," William observed, pointing up to the barred windows, which were halfway up the high walls—too far up to see out of, but they could see the people's shadows drifting like ghosts through the apartment. They could hear little bits and pieces of their voices—muffled and sounding like a confusion of other languages. Their shadows crawled upside down the walls, and somewhere above them, Jacob and William heard the insistent pealing of bells. It was Sunday. "You live in the basement of a church," William stated. "Thank you, Captain Obvious," Jacob replied, eyes slitted. "When we came in last night, I thought we had to be in the wrong spot. But then your key fit the side door. I couldn't believe it. Is this even legal?" Jacob groaned and moved his mouth fruitlessly. Far too much effort to explain that he was sort of unofficially subletting it from the priest, the brother of a Greek Orthodox guy he'd slept with (off and on) in college who'd hooked him up with the keys when Jacob had announced that after graduation he'd be moving to the big city. What had seemed at first like Divine Providence (avoiding the months of craigslist ads and fleabag brokers that George and Sara and Irene had dealt with that first summer) had quickly become a sort of hell. The place came to feel like the kind of dungeon people got thrown into during the Spanish Inquisition. Jacob felt at times like a boy who'd fallen into a well and decided he might as well decorate. Though _decorate_ was a term best used loosely if at all. Jacob chewed his lip and looked around at the disheveled heaps that were his worldly possessions. The blue pullout couch, a flimsy bookshelf, and a desk made of milk cartons and an old door he'd found in the alley. These were the only pieces of furniture he possessed. The walls were bare except for a few rough starts of poems that he'd stapled, in haste and at odd angles, onto the flat surfaces around the desk. On the bookshelf was one framed photograph, of himself in a tuxedo posing alongside George, Sara, and Irene at the prize ceremony for _In the Eye of the Shitstorm_. The jittery MRI printout that Irene had given him was held to the fridge with a magnet from Szechuan Garden. The apartment was boiling in the summer and freezing in the winter. His every noise echoed, making him supremely self-conscious of every movement. He had recurring dreams of being trapped at the bottom of an enormous empty swimming pool, only to wake up and find that in a sense, he was. And yet it was so cheap and peculiar that he couldn't justify leaving. He'd settled instead on two rules: he'd spend as many nights as possible in other people's beds, and he'd never allow George or the others to see the place—knowing full well that they'd force him to admit he'd made a terrible mistake. Jacob felt an odd pinching in his stomach, distinct from the unease of its still containing half a liquor cabinet's worth of booze. "We've got to get George out of here." "Why not let him sleep it off?" "George hasn't ever been here. _No one's_ ever been here." He tried to rush back over to the couch and promptly hip-checked the bookshelf, which teetered unsettlingly. William shut the water off and shook his hands to dry them off. "You pulled your pants off in front of me the night we met, but no one's allowed in your apartment?" As anxious as Jacob was, he couldn't deny this. "How'd you even know where I lived?" "It's on your old Blockbuster card. Though I notice you don't seem to have a television." "It had an abrupt meeting with a thrown remote control during the 2004 Oscars." "Not a fan of _The Return of the King_?" "I was pulling for _Seabiscuit_. Look, why the hell didn't you just take us to _your_ place?" William's face reddened a little, and he squinted at the adjacent wall, which was badly cracked through the plaster. "You'd just have made fun of it," he said at last. Jacob snickered happily. "Your page twelve?" William almost dropped the cup he'd been washing. "She _told_ you?" "No, she told Sara. Who told George, who told me." A flash, like lightning, flickered over William's face, and Jacob was for the first time frightened of what was about to come forth. But before William could erupt, the entire room was filled with a thundering noise from outside—the sound of a garbage truck hitting the curb, then the lighter sound of the men opening the bins' heavy iron lids, designed to keep the rats out. Jacob had been so grateful when they'd finally been installed, two years ago, and he'd no longer had to scramble past vermin to get to the door. But as with everything, there were trade-offs. Now the lids clanged loud enough to wake the dead or, failing that, an extremely hung-over astronomer. George jolted up, looking around for the noise. "Where—?" Jacob watched as his oldest friend made the same mistake of staring up too quickly. He could actually _see_ the blood rushing from his head. George rolled over and planted his face into the soft dark safety of the couch cushions. "—the hell are we?" George managed, his eyes darting above the cushions accusingly. Jacob sighed and faced the humiliating prospect of surrender. _I am not special_ , he thought. He just liked that they had always thought he was. Even if he'd known, years earlier than the rest of them, that it wasn't true. "My brother's apartment," William said quickly. "A friend of our father's runs this church, and he rents Charles the room under the table." While George took another try at inspecting the ceilings, William wandered casually to the bookshelf and set the photograph of them all at the awards ceremony facedown so it was out of sight. Jacob stood still, not really sure what to say. "I thought your brother was a doctor," George said to William. "With kids and stuff." "Let me guess," William said. "Irene told Sara, who told you, who told Jacob? Yeah, well, he works over at Columbia Presbyterian, so he crashes here between shifts." Jacob was a bit stunned—George seemed to be buying it. "Hey! Jacob and I bought this same couch, back in the day." Smiling like a fool, George eased himself from the bed, stretched like a sandy-furred cat, and released a long sigh. "I am going to go throw up," he announced as he padded off to the bathroom in his dress socks, undershirt, and a pair of blue boxer shorts with sandwiches on them. From the bathroom they could hear the seat of the toilet as George knocked it back against the basin, followed by the sound of him emptying his stomach. "You didn't have to do that," Jacob said to William, who returned to washing the last of Jacob's dishes. "Really. You didn't have to do any of this. You could have left us down there in the Village." "I suppose," William agreed, cheerful now for some reason. "But then you wouldn't owe me one, and I couldn't make you take me to see Irene." William passed him a sudsy beer stein. Jacob dried it off. "And here I thought you were just doing all this out of the goodness of your heart." "Hell, Jacob. It's not like I'm the Messiah or anything." Jacob froze, nearly dropping the stein on the counter. "How'd you—did I, um—did I say something last night?" William smiled cryptically. "You were pretty drunk. I doubt it'll hold up in court." Jacob felt a fury rising, but when he opened his mouth to release it, what came out was a sigh of relief. Hearing it out loud wasn't as terrible as he'd thought. And who'd believe that he'd confided in William, of all people, if he ever were to repeat it? "Well," Jacob said, "you're the one who went to Yale." A gruff vibration came from a pile of clothes near the couch. Jacob fished around in George's discarded pants and thought, for a second, he had found a phone in the back pocket. Only the object he extracted wasn't a phone at all but a slim silver flask with an engraving on the side: _Coriolanus Crew 1967 League Champions_. Jacob vaguely recalled being with George when he'd picked it up at the Salvation Army their freshman year. The flask was not quite empty. Jacob unscrewed the cap and caught the scent of J&B—George's favorite. With a sinking in his heart, he at last understood why George had kept rushing off to the bathroom in the hospital and at Bistro 19. He couldn't decide if he wanted to smack him or crush him in his bare arms. Whatever ambitions Jacob had held as a boy—to hear the voice of God, to wrestle with angels, to unite everything—he knew now that he'd become too selfish, too discontent, too upset. Maybe that had always been true, but especially after Isaac, he'd known for sure that Jacob Blaumann was no Messiah. He'd never been as good as the boy he thought he'd been. Nobody he knew was that good. Nobody could possibly be. Then on his first day of freshman year he'd walked into a small room with bunked beds and shaken hands with George Murphy, who in ten years had proved to be the kindest and most generous person Jacob had ever known. And for all his griping, he'd needed George to be the good things that he'd long ago given up believing in. Only now his savior had been holing up in men's rooms, sipping scotch, trying to numb the world's unfairness. "I think it's your dad calling?" William said, lifting up Jacob's phone. Jacob almost laughed—why would his father be calling? He stared down at Oliver's picture on the phone, feeling the buzz in his hand until the screen grew dark. "I'll call him back later," Jacob lied. William seemed about to say something, when they heard the buzzing again now, not from Jacob's phone but from inside George's shoe, down near William's foot. On the screen was Irene's lovely face, framed in black. Jacob motioned for William to answer it. William pressed the big green button on the screen and held it to his ear. "Sara? It's William Cho. George is just in the bathroom—what's the matter? Did something happen?" Jacob felt the rush of a hundred voices all at once, his blood vessels and neurons and toenails and eyelashes all screaming in every language at once. He heard the sound of the toilet flushing in the bathroom as William tried to calm Sara down on the other end of the line. "Shushhhhh," he said, "Shushhhhh. Shushhhh." ## THE DISAPPOINTMENTS ### JULY William counted his disappointments on both hands. There was, one, the ninety-eight-degree heat burning through the window of the bus, as it, two, crawled through Staten Island traffic. Three. He was there, on a weekday afternoon, because, four, he had finally been laid off at Joyce, Bennett, and Salzmann. At first he'd been almost glad to have it over with, but then, five, none of the other firms had been hiring. Six, his severance and savings were being so rapidly consumed by his rent that it seemed like only a matter of time before he would be forced to move back home again. He was vexed by a peculiar curdled milk smell, seven, emanating from the woman in the row ahead. Also, the periodic vibration of his phone alarm in his right pants pocket, which he couldn't reach to disable, eight, reminded him that he and Irene were now a half hour late, nine, for their appointment with a guy named Skeevo, ten, whom she had been buying pot from lately (it helped with the nausea, as well as her overall mood), but who today had called about something else that he wanted her to see, all the way in Staten Island, down near the Fresh Kills Solid Waste Transfer Station. And yet, despite two hands' worth of disappointments, William caught a reflection of himself grinning like an idiot, all the fingers in his reflection's left hand holding all the fingers in the reflection of Irene's hand, and all the fingers in his reflection's right hand playing gently with the reflection of her hair. William was aware, at least as long as Irene was around. Aware of the faint burned smell that always got jumbled up in her hair, postradiation. He'd gotten used to it after a month. How many more weeks of treatments did she have left? One? Two? Time was rushing laughably by. Not like the past several months, when he'd buried himself in work (for all the good it had done him) and rerouted his heart on dates with the Society of Korean Daughters of His Mother's Friends. But now William was sitting beside Irene, aware of the vibrations of her throat against his shoulder as she awwed at a little baby in the next row, happily gumming the leg of a Barbie, naked except for one black glove. His phone buzzed again; it was wedged directly against Irene's outer thigh. She looked away from the baby, craned her head up at him, and whispered, "Is that your mother calling again, or are you just happy to see me?" She looked so damned ridiculous trying to give him sexy eyes while the left one was covered with a black felt eye patch. She'd bedazzled it with rhinestones in the shape of a skull, claiming it was an ironic statement about Damien Hirst. William said it made her look _more_ like a pirate than the eye patch alone. Irene said that was the irony. William didn't understand, or care. He didn't care about a lot of things far more important than that. He didn't care that he was unemployed. He didn't care that he'd forgotten to make his June credit card payment and would now be charged a one-hundred-dollar fee, the first time this had happened in his life. He was actually a little excited. Ordinarily, he would have carried the guilt of that hundred dollars around in his gut like a bullet for the rest of the year. He'd have cared that the socks he put on that morning were not only two different shades of blue but of different thicknesses, such that his right foot ached and sweated while the left was fine. He'd have been distraught that Irene was still sick—worse, maybe, even than before. He _did_ care, of course. It was just that these cares, like all the others, were wiped from his mind now that she was holding his hand. In moments when he was alone, the circuits in his brain containing these ordinary cares and fears overwhelmed all others, and he couldn't even sleep. But when Irene was around, even the disappointment he felt about her big surgery not going smoothly seemed to clear. The morning after their epic night of barhopping, Jacob, true to his word, had brought William back to the hospital. While Sara had been dealing with the still jelly-legged George, William had slipped around the cheap curtain that hung around Irene's recovery bed. He had been worrying about what to say: that he was sorry for leaving her in the train station; that he had woken up every day since then thinking of her before even remembering what planet he was on; that he had tried to call her dozens of times; that he had compulsively been donating to the American Cancer Society online at work; that he had run in a 5k to raise money but it turned out that he was a lot more out of shape than he expected and had limped the last 3k on a strained ankle. But the second he'd seen her lying there, these worries began to evaporate from the inside of his head. She'd looked nearly concave, with thick bandages wrapped over the area surrounding her left eye, and her right eye fixed on the TV high up in the corner. But that right eye had swiveled to him. The lid around it had snapped up like a cheap blind. She'd seized his hand, pulled him to her, and locked her lips onto his. An alarm went off; she'd pulled off her pulse monitor clip and yanked her IV stand half over. A squat Dominican nurse had rushed in and threatened to put Irene into restraints. William had had to walk two laps around the ER. When they released Irene, the two of them had gone directly back to his apartment—actually no, they'd made one stop, back to her place to pick up some clothes and the scarf she'd bought for him at Christmas, which had remained wrapped and on the counter. _Then_ back to his place, where she'd stayed every night since. In a week she'd sold her bed on craigslist and rid herself of every other unneeded belonging, so she could maximize the work space in her East Fourth Street apartment. Every day she worked there but refused to show William, or anyone, what she was making. She never even spoke about it—but she always arrived at William's itchy to return, talking only vaguely about working on something larger, something that she and Skeevo seemed to be into together. Even now, Irene seemed quietly elsewhere as she and William followed the other passengers off the first bus and toward the next, an S62. She looked down and said, "You don't need to hold my hand." But she didn't pull away. "But I like holding your hand. 'I wanna hold your ha-a-a-a-and . . .'" William tried to sing. She screeched and tried to cover his mouth with her other hand, but he persisted. "'Oh, please . . . say to me-e-e-e-e. You'll let me be your man . . .'" He finally had to stop when, on the held-note, Irene got most of her fingers into his mouth, and he could no longer form words. "OKKK FWINE YLOOOU WIHHN." Irene let him go and shot him another look that was difficult for William to decode without being able to see her eyebrows. The second bus smelled refreshingly of burned Dunkin' Donuts coffee. Once seated, Irene turned to William to explain. "I can still see out of the other eye. I'm not going to wander into traffic." "I didn't think you were." The eye was fine. They had gotten the tumor out from beneath it without any damage to the nerves. It was still swollen, though, and with the thick black stitches there, it freaked people out. Hence the eyepatch, which still freaked them out but in a kinder way. After the first tumor had been removed, the doctors had planned to head in for the one on her elbow, when one of them had noticed some swelling under her armpit. Thinking it might be a reaction to the anesthesia, they'd run a fresh scan, only to find suspicious shading on one of her lymph nodes. Just days earlier they'd done a complete battery of PET scans and found everything clean, but now there was definitely something. They stopped before beginning the surgery on her arm. Now she had a "compromised lymph node." This was, as Dr. Zarrani put it, "a big disappointment." The cancer had gone off the skeletal rails and passed into her glands, from whence it could travel, fluid borne, to distant organs. It meant that the first rounds of chemotherapy had done very little, possibly nothing, and that they'd have to "really crank it up a notch now." It meant adding ifosfamide and etoposide to the poisons they were secreting into her veins each day in the chemo lounge. But William wasn't thinking about that now, only about the coconut smell of her hand lotion and of Irene's relief when she learned she wouldn't to have keep her arm in a cast all summer—and so would still be able to work on her sculptures. The S62 bus squealed to a halt just to one side of the Staten Island Mall. William followed Irene off the bus into the mall parking lot. Steadily, the rest of the people headed toward the forty-foot-high signs for JC Penney's and Loews Cinemas. Irene pulled William in the opposite direction, crossing one vast parking lot after another—each a little less crowded than the last—until they seemed to be a half mile from the actual mall. Irene danced over the cracks in the pavement, as if to not break the back of some mother somewhere. That was another mystery that William had a hard time thinking about. Where was her family in all of this? He became preoccupied by the light glinting on her legs as she leaped. Far off in the distance, William spotted a red pickup truck parked by a chain-link fence. Hitched up behind it was a little two-wheeled U-Haul trailer with its orange rolltop up. A man who William presumed to be Skeevo was rifling through the odd items inside. He was tall and wore a grease-stained flannel shirt buttoned to the top and to the wrists. His pants were ripped, revealing kneecaps the same mocha-tan color as his neck and hands. Despite the July heat, he was wearing a half-disintegrated hand-knit winter cap. Irene let go of William's hand. Disappointment settled in as she moved farther away, and it grew measurably along a neat curve in his mind, like a once-meager debt accruing interest. He walked faster, trying to reduce the distance between them. With each stride he felt the load leveling off. By the time he got to her side again he was out of breath, but happy again. He shook Skeevo's hand as if they, too, went way back. William didn't even mind that his grip felt like a car door closing on his hand. "What'd you bring me?" Irene asked, moving around to the back of the U-Haul and beginning to sort through the scrap. Things clanged and scraped. Keeping his eyes on her, William shook Skeevo's hand and introduced himself. "You work over at the dump?" he asked. "Kind of," Skeevo replied. "It's not really a dump anymore." "The Staten Island dump isn't a dump?" Skeevo cast his eyes out past the fence, across the busy highway, toward several enormous green hills. "The Fresh Kills Landfill's been closed for, like, ten years. It was supposed be temporary—you believe that? Back in 1947 . . . then you know, one thing leads to another, and soon enough it's the biggest landfill in the world." Irene had fully disappeared inside the U-Haul, and William was feeling at an utter loss. Then she emerged with a single ski under one arm, looked at it a moment in the light, dropped it to the asphalt, and dove back in again. Skeevo was still going on about the not dump. "When they finally shut this thing down, it was taller than the Statue of Fucking Liberty. Back in the sixties, when the astronauts went up into orbit, the only man-made objects they could see from space were the Great Wall of China and _this_." "That's . . . distressing," William said, although he didn't feel distressed at all, because Irene was pulling half a child's stroller out of the U-Haul with a quizzical look. She placed it in a pile to one side, which William took to mean she was considering it. "So what, um, what is going on with the landfill now? They've finally closed it?" "They're turning it into a park," Skeevo announced proudly. "Going to be three times the size of Central Park." William hummed. "And _Skeevo_ —is that a . . . Polish name?" He took his wallet out and thrust an ID in William's face. "Skeevington Monkeylips McBalzac the Third," he said. "I changed it when I left home. Got the idea from Reeny here, actually. I think everybody should be able to pick their own name, don't you?" William looked nervously for "Reeny," but she was deep inside the trailer. How exactly did she know this very possibly insane person? And what did he mean he'd gotten the idea from her? Was Irene Richmond _not_ her real name? But then Irene began shrieking from the back of the U-Haul. William rushed over, imagining a collapsing wall of sharp objects and broken glass. Instead he found Irene straddling a segment of a large steel I-beam—running her hands wildly over its ridges and warps. Something had clearly happened to it, for the thing looked, William supposed, more like a T-beam now. The bottom edge was melted to nearly nothing. He wondered what could have done that. "I knew you'd like it," Skeevo grinned. "Help me get this into the light!" Irene cried. It took the three of them shoving as hard as they could to get it closer to the open door of the U-Haul. William guessed it weighed over four hundred pounds. He sniffed his hands after pulling them away and recoiled at the harsh, burned-chemical odor. Irene was acting as if she had uncovered the Treasure of the Sierra Madre. What did she see in it? She was _so_ happy—he hadn't seen her like this since they'd kissed at the hospital, not even when they were in bed together. She was like a child, overtaken by a joy far exceeding her total volume. William closed his eyes a moment. He'd spent his whole life avoiding drinking or smoking cigarettes or pot, for fear of being addicted, and now here he was hooked on a drug that was in desperately short supply. He opened his eyes again and saw Irene and felt no doubts at all. "We found it up in the northwest quadrant of the old landfill. They'd been relandscaping it, trying to do something about the grade for the spill-off. One of the bulldozers snagged this thing. They let me have it before anyone important figured out what it really was." "What _is_ it?" William asked. "My guy there tipped me off. It's from one of the Twin Towers," Skeevo whispered. "Some of the rubble they cleared from there got dumped in the landfill before they closed it up again." William found himself taking a quick step backward, but Irene was bending down closer so she could study it better. Then, without warning, she lifted the patch from her eye to reveal the red, puffy mess beneath it. Back in the apartment she kept the patch on, even when they slept together and even when she was actually sleeping. She took it off only in the bathroom to clean the black network of stitches. They ran around her eye socket like narrow railroad tracks. "Jesus," Skeevo said, a crack in his voice as he looked away. But William didn't mind. He was too busy watching her brilliant blue iris working behind the lid, nearly swollen over it. He watched as she studied its corners and edges, running her hands up and down its length. "Can we get this back to the city?" she asked softly. Skeevo agreed to give them a lift in his truck. Irene squeezed between him and William in the front seat, navigating them to the K Gallery, where she had access to Abeba's welding tools. As they drove out of the parking lot and back up through Staten Island, Skeevo and Irene caught up on old times while they shared a joint. He didn't ask about her eye. Instead, he wanted to know how she and William had met, and William liked how she relayed the story of meeting him at the Christmas party. The way she stroked his cheekbones as she described first seeing him. Maybe it was just the pot smoke getting to him, but it seemed like a hundred years ago. William stared dreamily out the window as Skeevo told them all about his own fantastic-sounding life. He'd gotten married, had a child. He and Irene complained about traffic and global warming and capitalism as they drove up and over the glorious gray Verrazano-Narrows Bridge. Eventually Skeevo fished a cell phone out of his pocket and thumbed-up a video he wanted Irene to watch. It was of his wife—a pretty young Chinese woman—sitting in a plane seat somewhere, holding a baby boy with an enormous head. The head was so enormous, it seemed to be all this woman could do to support it in two hands. Skeevington Monkeylips McBalzac the Fourth—at least for now. "Skeevs! He's adorable! William, did you look like that when you were a baby?" "That baby is Chinese," William said. "I'm Korean." "Technically he's _half_ Chinese," Skeevo said. Irene shook her head, and even without seeing her second eyelid droop, William knew that she was sad. "Babies aren't anything yet," she said. "You can't be one thing or the other until you get old enough to know what you are and what you aren't." William wanted to argue, but she slumped into his shoulder. He could feel her body tensing as she tried not to cry. Fortunately Skeevo was too busy dodging traffic to notice a tear leaking out from under her eye patch. William wiped it away. Then he caught the one falling from her good eye and wiped that one away too. Infertility, Dr. Zarrani had said, was a likely long-term side effect of the chemo. So was ototoxicity (a sensitivity to high-pitched sounds), neuropathy (numbing of the fingers), heart damage, and most ironic of all, greater susceptibility to cancer in the future. Irene didn't seem to care about anything except losing the ability to have a child. "How do you feel about adoption, William?" she asked. "I've always wanted to adopt a baby. I'm basically adopted myself, you know." "I'm for it," William said. The video ended with Skeevo's son chewing merrily on his mother's hair. "That'd really drive my mother off the wall." Irene sighed. "She's so sweet. You should be nicer to her." William turned away and looked out the window at the dingy Brooklyn boulevard they were heading down. He took in a deep lungful of fresh air. It was difficult, but he needed to be ordinary again for a while. He needed to feel how he felt, late at night, while he lay awake next to her in bed, unable to sleep. In those dark hours with his eyes shut, he had been counting disappointments on a hundred imaginary fingers. Not things that he was disappointed _by_ but disappointments of his own making. Things like having made more money than he deserved, doing mergers for companies with questionable ethics, being a terrible son—anything he felt the universe might be punishing him for by making the woman that he loved so sick. He knew it was egotistical to believe it was somehow his fault, but this made more sense than trying to imagine it was her fault. All she ever did was turn ordinary things unordinary. Lying next to her, at home on the bed, or there on the truck seat, with her hair smelling burned and her arms feeling thin, with her skin red and her eye mutilated, he couldn't bring himself to imagine what she could've done to deserve this. ### AUGUST The steps of the Metropolitan Museum of Art burned through the seat of Jacob's pants as he stared out at Fifth Avenue, waiting for Irene. He'd arrived early and was annoyed because he didn't know exactly how early he was. He had given up wearing watches, and when his phone display broke, he'd refused to get a new one, because technically it still made calls—if he could remember the number to dial. Text messages were a lost cause, of course. He had been wanting to call Irene all morning to insist that they bag this whole thing, but the only person's number he could ever remember was George's, and George had grown tired of Jacob calling him every ten minutes, asking him to look up someone else's number. It didn't matter. Jacob knew Irene would have insisted anyway. If he'd canceled on her, she'd have come by herself, just to prove she could. It was their tradition to get dressed up and go to a museum on the second Sunday of every month. They had only missed one before, during a hurricane—but for God's sake, she was supposed to be taking it easy, not going around in hundred-degree heat, and not spending all week at the gallery learning to arc weld. How was she supposed to operate a blowtorch when she had trouble lifting her purse? One of these days she was going to set herself on fire. Whatever admiration he'd felt back in July for her dedication and energy was now, in August, a distant hallucination. Now he just wished she'd ease up. Allegedly July's treatments had been much harsher than the previous rounds— _allegedly_ , of course, because Jacob hadn't been informed about the previous round—but the others had filled him in on the pattern: she'd feel queasy during the days of treatment but not totally awful. And then, just when the inconvenience of the hospital visits was over and she began fantasizing about getting her life back, the aggregated chemo drugs and radiation side effects would hit all at once. She looked airless half the time, as if instead of putting something into her, they were siphoning something out. Jacob peered over the shoulder of a man on the step below him and saw on his phone that it was 12:19, which meant Irene _was_ a little late—they'd agreed to meet at 12:15. The man was reading a story on Gawker about some handsome actor that Jacob recognized but couldn't remember the name of, who had tried, and failed, to kill himself. The man kept looking up and making audible, dramatic gasping sounds, as if to make sure everyone nearby knew that he was _shocked_. Several steps down from him were three orderly rows of squatting grade-school children, their teachers lazily circling them, looking up the avenue for their school bus. The rows of schoolkids began to get restless with the barber shop quartet busking on the corner, singing old standards like "I Got a Gal in Kalamazoo" and "You Make Me Feel So Young." At some point the teachers responded. "Let's do our song, kids. Come on!" Jacob eased back, curious if they'd be singing a little "Fr _è_ re Jacques" or "The Farmer in the Dell"—but no, as he listened through the din of high-pitched voices, he could tell it wasn't any of those childhood classics. "'Baby, baby, baby, oh!'" the kids sang, "'Baby, baby, baby, oh . . .'" Jacob saw to his horror that the teachers were actually encouraging this atrocity—recording it on their cell phones. Surely it would be on YouTube before their bus arrived. Jacob thought he'd never live to see the day he missed Barney the Purple Dinosaur, but now here he was. He was sore from the steps and could feel sweat over every inch of him. People rudely trampled by just inches from his spot, though there was plenty of room to go around. He couldn't stop wiping at his forehead and knew it was turning all red. Then, just when he thought he might actually implode from unexpressed venom, there around the corner, past the hot dog vendors, he saw Irene coming at last. She wore a long, flowing white dress, and her hair was pulled up in an elegant twist that hid how thin it had become after all the treatments. She was fully made up, as she usually was now that the eye patch had come off. She'd figured out how to cover the scars with foundation and eye shadow. She'd put on a bit of blush. Her cheeks, like the rest of her these days, were colorless. "You look like a million bucks," he said eerily. "Why didn't you wait for me inside? You look like hell." • • • They went up the steps and through the revolving doors into the crowded Great Hall. Irene tilted her head back to stare up at the vaulted ceiling, and Jacob noticed her lurch back. He moved quickly, as if to catch her, but she righted herself without a word. They got in line. "One student," Jacob said, flashing his faded college ID. "You need to get a sticker to show you're still enrolled," the old man said. "Sticker?" Jacob feigned ignorance. "What are you talking about?" Normally they went through a round or two of this, but Irene stepped in before it could escalate. "Twenty-five dollars is only a suggested price. Just say you want to pay twelve." "They'll think I'm cheap!" "You _are_ cheap." The old man began his spiel. "Sir, every dollar you spend goes directly to the museum's collection, which is unparalleled in the country in terms of its variety and excellent—" "Where are the dinosaurs?" Jacob asked, peering around as he pushed his ten and two singles across the counter. "Sir, that's at the Natural History Museum across the—" "Honey pie," he whined to Irene, "I thought you said we were going to see the dinosaurs. We didn't come out here all the way from Tacoma just to see some _art_." "You hush," Irene snapped, as she took a pair of little sky-blue M-buttons from the man. She clamped her hand around Jacob's wrist and jammed the button into his lapel. " _Ferme la bouche_ ," she said, then marched off into the Egyptian Wing. Jacob doffed an imaginary hat. "I _could_ be from Tacoma," he said, mostly to himself, as he walked after her. Normally, Irene liked to start by the mummies in the ancient Near Eastern art section, but this time she kept her back to them as she passed by the long, opposite wall, which displayed the scrolls for the Egyptian Book of the Dead. "Can you read this?" she asked Jacob, pointing to the hieroglyphics. He'd taken two semesters of Middle Egyptian in college, since he'd done Latin and Greek in high school and needed six "ancient language" credits for his classics major. He hardly remembered any of it, but usually Irene liked it when he ad-libbed. "Ah yes," he said. "This here is a pilot script for an ancient Egyptian police procedural called . . . let's see here . . . yes. _CSI: Akhetaten_." Irene didn't smile but ran her fingers along the English text on the glass as if she were blind and it was Braille. "'A spell to keep the heat within the body of the deceased until resurrection. Which must be recited over the figure of a heavenly cow.'" Jacob scratched an invisible beard. "Never have a figure of a heavenly cow when you need one, though. That's the trouble." The next panel described the Hereafter. "Each of the seven gates of Osiris is monitored by an attendant, a guardian, and an announcer." "Well, sure. Under union rules, you can't attend, guard, and announce without three separate contracts." Still no smile. "The Egyptians believed the dead lived in a Field of Peace, which they were taken to either on a ferryboat or aboard the solar bark of Ra." "Solar _bark_?" "It says 'solar bark.'" "Like a dog bark or a tree bark?" "Unclear. And here's a spell to—interesting—a spell to transform someone into a swallow that can travel freely between the real world and the Hereafter." "Yeah, but then you're a swallow," Jacob sighed. "Ew. It says the guardian of the third gate is the Eater of His Own Excrement. That guy better at least be getting paid scale." He was sure this was one of his better performances, but Irene was drifting silently into the next room. She breezed through groups of Asian tourists while Jacob found himself shuffling left, right, and left again, trying not to knock two Hasidim into the five-thousand year-old Kneeling Bull Holding a Spouted Vessel. He caught up with her inside the enormous greenhouse that enclosed the Temple of Dendur. "Are we racing?" he asked as they crossed the moat. "I'm looking for something," she said. "Sorry, I don't need the whole Jacob Show today." She got like this when she was in the middle of a new piece in her studio. He liked it; he missed feeling that way himself, but he understood. She was the only other person he knew who had artistic impulses. Ordinarily this made her eager to pick his brain, seeking advice and context, but she had said nothing to him at all about her recent projects, not for months. Soon she was leaning into the archway where a nineteenth-century soldier had carved his name into its gray foot: LEONARDO 1820 PS GORDE o. "You're looking for ancient graffiti?" "I'm looking for something"—she sighed, then sighed again with the last bit of breath—"disappointing." Extending his arms in mock-heroic pride, Jacob stood in front of her. "Behold! _Portrait of a Profound Disappointment._ Jewish-American in Origin. Circa 2009. Oil on Skin. Meat on Bone. Tweed on Meat." Ignoring him, she stepped into the cool antechamber at the center of the temple. There two small children were fighting over a handful of playing cards with hieroglyphics on them and trying to match them to the ones on the walls. "Careful! Don't trip on the wire!" Irene cautioned the kids, as they tried to climb over and under it at the same time. The little girl stamped her feet on the tile floor and looked up at Jacob, with an accusing finger pointed at her brother. "He's taking all the cards!" "Where are your parents?" Jacob asked. "Here," Irene said, picking a card up off the floor that the girl's brother had dropped. "Jacob, what's this one?" The little girl looked glumly down at the funny golden cross. "That's an ankh," Jacob explained. "Honk!" the girl shouted. "Ankh," Jacob repeated. "Less _h_ , more _ank_." "Ankh!" she tried again. Her brother chimed in, eager to see what was going on. "It was a symbol of eternal life." "What's a symbol?" the boy asked. "It's like a big brass disk." "Whaaaaaat?" the boy asked nervously. "Go find your parents," Jacob said, standing aside so the pair of them could rush off. "And hold on to that card. You'll live forever!" The children bolted around his legs, back out to the main room, and when Jacob looked back, Irene was smiling, two tears on her cheeks. Other people were trying to get into the temple now, but Jacob held a big hand out toward them and shifted his frame to block the door again. "Sorry. Private party." Irene turned back to the graffiti etched in the wall again: A L Corry RN 1817. She moved her hand over the carved letters, and a little dust came off on them. "What's going on?" he said, stepping over to her. "You're going to be such a good dad," she sniffed. "I want to be around to see that." _Don't be ridiculous_ , Jacob wanted to say. _In ten years we'll all be sitting around George and Sara's tacky living room somewhere, with their rug rats and yours all crawling up the goddamn walls, and we'll think back on this whole year, and we'll tell the older kids about how Aunt Irene had cancer once, and they'll never even believe it._ All this, he wanted to say. Instead he said, "Ew. You know, procreative sex is against my religion." "Just be serious for a minute, would you?" Jacob stood silently, mouth open, no words coming. Finally he said, "If you want to be disappointed, let's go look at the Warhols." They made their way out of the Temple of Dendur, bypassing the American Wing altogether and squirming through the Medieval and Greek sections on their way to the second floor Contemporary galleries. As they walked, Jacob tried to tell her about the movie he'd gone to see with Oliver the week before. "Which movie?" "Some stupid thing. Title from an Elvis song." " _Can't Help Falling in Love_? With Stone Culligan?" her eyes lit up. "You _know_ he tried to kill himself yesterday." "Who did?" Jacob asked. "Stone Culligan! It was all over the news. He and that supermodel, Branca, broke up, and he slammed his Jet Ski into a bridge. They say he bruised his spine and he's lucky to be alive!" "Lucky to . . . you're _damn_ right he's lucky to be alive. He's got the face of the _David_ , and he's worth a quajillion dollars. Doesn't even have any talent, not that _that_ matters to this fucking planetful of philistines." "Keep your voice down, okay? You're scaring people." But Jacob didn't care about the gaggle of Floridian women pretending to appreciate some Monet painting they probably had hanging up in their pastel-painted bathrooms. "How dare he? How _dare_ he? How dare he try to fucking kill himself when there are—when there are people who are legitimately—" Irene arched an eyebrow at him. "Dying?" Jacob scratched his arms furiously. "That's not what I was going to say." "Yes, it is," she hissed. "Yes, it is, Jacob, and you know what? That's—that's the worst thing you've ever said to me." "It isn't what I was going to say," he insisted—but of course it was. "Fine, it _is_ what I was going to say, but that's not how I meant it." She crossed her arms, and her eyes went black. "You're not dying, Irene. I don't believe that. Really, I—" "Let's drop it," she snapped. "If you'd just—" "I said DROP IT!" She was so furious that Jacob stayed several feet behind her the rest of the way across the museum. As hard as it was, he remained silent as they came up to the Contemporary Wing. Then they came to the Warhols. In better times, they had sat for hours there on the floor, talking smack about Pop Art and Anti-Art and Anti-Anti-Art and _can't we for fuck's sake just make ART-ART?_ —but now Irene wasn't interested when Jacob pretended not to be able to see the enormous camouflage-patterned self-portrait of Warhol. "Where did he go? Isn't there supposed to be a painting here?" She was transfixed by a huge painting at the end of the aisle—Anselm Kiefer's _Bohemia Lies by the Sea._ Twenty feet long and seven feet high, it showed a wild field of pink and orange poppies with a rutted road going up the center. It was one of their favorites—but this time it was familiar in a wholly different way. "Looks just like Shelter Island," Irene said quietly. As soon as she said it, it brought a hollow ache to Jacob's throat, and he knew why. He hadn't thought of the painting while they'd been out there—but now he saw that it did resemble the shoreline where she had first confessed to him that she'd been sick. Where they'd drunk the bottle of wine. Down in his gut he knew it was the last time he'd been happy—right there, after she'd told him, but before he'd really believed it. "I've got to sit down a second," Irene said. Jacob looked all around, but there were no benches. He couldn't stand the sight of her hunching down on the ground in her beautiful white dress—the sort of dress you could get married in, on a beach anyway. He looked around for a guard. "Hold on. Maybe—maybe someone can get you a wheelchair or something?" "Just let me catch my breath," she warned, as she stared at her reflection in the floor. "Irene," he tried again. "For Christ's sake, you look like a ghost's ghost. You can't—" She wrenched herself back up off the floor without a word. For the first time he wished she still had the eye patch on. Her gaze was Gorgon-like, petrifying, unbearable. He stood rooted to the ground as she stalked off. In the white marble floor, he saw a miserable fuck staring up at him. What a pretentious prick he was. How could he ever have thought he could save anyone from anything? He turned and looked up at the gigantic self-portrait and knew, deep down, that he was nothing but a Warhol in his soul. By the time he'd hurried after her into the dark room full of Josef Albers squares, lit only by the sickening Robert Irwin fluorescent bulbs on the far wall, she was nowhere to be found. He expected to find her sitting on the stairs that led down into the Modern galleries, but she wasn't there either. Nor was she by the Klees, nor by the Mirós, and then—fuck—not among the O'Keeffes (which she still nursed a little junior high crush on). He spat, swore, spun around, and backtracked a little—sure that he'd just missed her and that, as exhausted as she was, she couldn't have gone far—but she was nowhere. He dashed into Arts of Africa and Oceania and the Americas _,_ peering behind the Ethiopian totem poles and Filipino longboats and Eskimo death shrouds. He thought he spotted her studying a Korwar ancestor figure and then, a moment later, bending down to examine a Peruvian funerary mask—but no. Was she in a ladies' room somewhere? Was she hiding in with the European Furniture? Jacob knew that all those decorative armoires bored her to tears, but if she wanted to get away from him, where better to go? He searched high and low amid the gilt caskets and marble funerary portraits. Never before had it occurred to him how much _death_ there was in museums. Paintings of dead people. Sculptures of people who'd died forever and ever ago. Ornate vases and chairs and mirrors made by some dead guy who had sold them at some point to someone, who'd then gone and died and left them to someone else who'd died, and on and on until the great undying museum got its hands on these _remains_. And every wing, every bench, every window had some dead person's name on it. The dead Robert Lehman Collection. The dead Sackler Wing. The dead Grace Rainey Rogers Auditorium. The dead Thomas J. Watson Library. Oh, let's all grab a quick bite at the dead Petrie Court Café before heading down to the dead Ruth and dead Harold Uris Center for Education. It wasn't a museum so much as a mausoleum. He rushed into the Branch Bank, with all that bland American furniture behind the facade, and then back out again on his way up to the Tiffany stained glass and then back down again toward Arms and Armor _._ Wall after wall of deathly instruments—swords and axes and crossbows and harquebuses. She wasn't by the fifth-century red-figured vases from Greece or the twelfth-century bronze spearheads from the Trojan War. He ventured back into the Medieval Wing. There was nothing left to do but cover ground he'd been through already, in case she'd circled back. Having been everywhere else, he came back to the Warhols, past _Bohemia Lies by the Sea_ , and there, at the bottom of the stairs he'd first come down, was Irene. She was just sitting there, staring out into the room. Had she been there the whole time? Had he blown right by her? She was looking at a pair of Klee paintings. On the left was a round-edged, purple and pink fantasy—little houses all in rows with fat little windows and doors. _Oriental Pleasure Garden,_ it was called. Beside it, _Stricken City_. A brown and sooty monstrosity, a jagged bolt of death through its center. "Jesus," he said, sitting down beside her. "I was running all over looking for you." Her eyes peered up from behind the veil of her let-down hair, and he could see they were cloudy. Looking almost right through him. Her skin had turned so white and bloodless that it no longer blended with her makeup. She looked like someone wearing an Irene mask made in a knock-off factory. "Fuck," he said. "Let's get you up. Come on, walk with me, okay? Can you?" With his arm around Irene, Jacob was able to coax her to her feet and then slowly through the crowded aisles of the modern art exhibits and out through the atrium of marble Greeks. One step at a time he guided her toward the lobby and the exit beyond—hoping that everyone would just think they were two lovers unable to be an inch apart. He wanted, so badly, for her to exit under her own power. "This was nice," she said as they came to the revolving doors. "I had a really nice time." "You're delirious. You had a terrible time. I fucked it all up. But that's okay." Jacob smiled as he eased past the security guards, trying to seem nonchalant. They stepped out into the blazing heat. Crowds milled down below them, pushed back from behind them. Traffic crawled along Fifth Avenue. He just had to get her into one of the cabs. He just had to get her down the steps. "It's hot," she said, surprised. "Hang on. I'm going to carry you," he said. "The hell you are," she whispered, but he wasn't listening. He reached down with his free arm to the clammy space behind her knees and eased her up off the ground. She was lighter than a book bag. He could feel her bones through her legs and her white dress, which he was careful to make sure didn't ride up as he came toward the line of yellow cabs at the bottom. One at a time, slow and steady, he carried her down the steps. "Hey!" someone yelled. "These two kids just got married!" Jacob didn't have the wherewithal to answer, much less to explain. "Look, he's bringing her to the car!" someone else shouted. Just a few people at first, but then more and more, with each step they went down, turned and raised their phones to snap a picture of the young newlyweds. The barbershop quartet looked over and transitioned, sweetly, into a new tune. An old Elvis song. "'Wise men say . . .'" the four men sang in splendid harmony. "'Only fools rush in . . .'" Jacob looked down at his would-be bride, blond hair flowing over her face as her eyes locked onto his: afraid, exhausted, resigned, indignant, confused. She threw her head back and began laughing. At the bottom of the sidewalk, the crowds parted and clapped. Irene reached up and kissed Jacob's sweaty, stubbled cheek. A cab pulled to a stop at the curb, and the driver rushed out and came around to open the door for them. Jacob eased the beaming Irene onto the cool leather seats inside, the air-conditioning on sweet and loud. She clasped her hands over her sweating chest. "Where to, lovebirds?" the driver asked. "Mount Sinai Hospital," Jacob said, "and step on it." ### SEPTEMBER Sara hurried down the middle of a Duane Reade pharmacy, her empty _New York Journal_ tote bag dangling from her right hand, the cheap gray linoleum squeaking beneath her worn ballet flats, and an Internet coupon folded in her left hand. _Hosiery, Shaving Needs, Incontinence_. _Greeting Cards, Tacky Crap, Well-Picked-Over Back-to-School Supplies. Fun-Size Bags of Candy Out Way Too Soon for Halloween._ Her shoes, like twin missiles, guided her to the same aisle that she went to every other day, just after giving Irene her afternoon dose of Prednicen-M at four o'clock. It knocked Irene out for one hour, allowing Sara this small window to pick up the supplies that she didn't trust William or George or Jacob to obtain properly. _Adult_ _Diapers, Orthopedics, Dietary Supplements_. As she came into aisle two, she saw immediately that the store had not gotten in a new shipment of Assure high-calorie meal-supplement milkshakes since her last visit. Dr. Zarrani had said Irene needed to keep gaining weight or she'd end up back in the hospital. Getting her released had been hard enough the first time. After Jacob had literally carried her to the emergency room, the nurses had treated her for dehydration and malnourishment as if she were just one more idiot off the street who had forgotten to drink water despite the heat wave. "Didn't you tell them she's a patient here?" Sara had demanded of Jacob when she'd finally gotten there. When a nurse finally wandered over, Sara asked, "Doesn't it say in your system that she's got cancer?" The nurse stared down at the chart. "Who? _Her?_ " It had then taken two hours to get her charts sent down from oncology. Nobody could find the paperwork that said Sara was to be treated like family and allowed to know what was going on. Not that she didn't ask Irene to call her father twice a day. Then three more hours before Dr. Zarrani had been able to get her transferred upstairs to the twelfth floor east—not the nice, peaceful Zen garden part where they did the chemo treatments, but the other side of the building where there were beds for patients who needed to be admitted. _Admitted_. That was a joke. Irene was still insisting none of this was at all serious. "Sara, relax. Jacob overreacted. I just keep forgetting to eat." An RN had come to tell them that the doctors (invisible, apparently) wanted to run a litany of new scans. A nurse manager came by, listened gravely to Sara's concerns for less than three minutes, then disappeared. No one but the nurses came by all night, and Sara stayed, if only to make sure Irene didn't get up and walk out. Finally around seven a.m., five doctors all buzzed in at once while Sara was half conscious. They chirped about scan results and potassium levels and speaking to researchers in Georgia. "When is Dr. Zarrani coming in?" Sara asked. "He'll be here at ten a.m.," one said, and then they all vanished before Sara could explain that Dr. Zarrani was a she. It took five more hours to run the paperwork to clear and release Irene, on the condition that she stop the long walks and the heavy lifting and eat three square meals a day. Irene had lost six pounds in the two weeks since the last chemo treatment. And it wasn't like she had that much weight to lose in the first place. She was five foot ten and 107 pounds. Sara had hoped she would be scared enough to not want to be carried to the curb again. She'd trusted that when William brought her back to his apartment, he'd make sure she ate something once in a while, even if the chemo nauseated her and nothing seemed to taste right anymore. Well. Those were mistakes Sara wasn't about to make again. Irene had made it exactly one week on her own recognizance. She'd promised William she'd stay in his apartment while he went out on interviews, relaxing and watching movies and eating takeout. Instead, she'd waited in her pajamas until William left, then changed into a T-shirt and jeans and gone to the gallery. She'd sculpted there until a half hour before William was due to return, then rush back, change into her PJs, and nuke the same three half-empty moo-shu pork containers that she fished back out of the trash every morning. What had she _thought_ was going to happen? One day Irene collapsed at the gallery. Of course, nearly ten minutes had passed before Abeba realized she wasn't meditating. "In a heap on the floor?" Sara had shouted, when she got to the ER again. "Please tell me someone told them this time that she's already a patient here?" Different nurse, same story. "Cancer? This girl?" Irene had lost eight more pounds. Sara couldn't recall the last time she herself had weighed only ninety-nine pounds—middle school? Dr. Zarrani's examination revealed that Irene's mouth and throat were peppered with stinging canker sores—a common side effect of the chemo and a likely reason Irene hadn't been eating. Why Irene hadn't mentioned that she was having trouble swallowing was entirely beyond Sara's comprehension. Probably a hundred times a day, Sara asked her how she was feeling, and every time all she would say was "Fine!" Why did she have to make it so difficult for everyone? It was too much, Sara had said. They needed some backup. At least _one_ real adult besides herself. Irene did claim to be _trying_ to reach her father but said she wasn't getting through to him. Where the hell was he? Mongolia? Not as if they didn't have phones there. But no, of course, when Irene nodded off and Sara checked her phone log, it showed no outgoing calls to Mongolia or anywhere. So it was still only Sara in charge when Dr. Zarrani insisted on inserting a "percutaneous endoscopic gastrostomy tube" into Irene's stomach—the only way to make sure she got vital nutrients. Four full days at the hospital this time, getting the surgery, recovering, while Sara learned how to rig an IV bag full of Assure milkshakes so that it would drip slowly through the PEG tube and into Irene's stomach. What else could she do? The boys were too obtuse to handle it, and Irene couldn't be trusted to do it herself. The next day Sara had come to William's door with suitcases in hand. "You can go live with George if you want," she had told him, "but either way I'm staying here." William had not argued, smart boy, and within minutes had set up an air mattress for her in the dining nook. Sara had three weeks of unused vacation time saved up. She promised Luther that she'd edit five stories a day from home and answer the forwarded calls when the new intern was out or in meetings. She canceled appointments with caterers and bands and florists. She and George still hadn't picked a place, much less set a date. The apartment search was likewise forgotten. But none of that mattered now. She'd stay through Christmas if she had to, no matter how much Irene hated it, filling IV bags with the Assure she'd come to Duane Reade to buy. She scoured the shelves, looking for Double Boost, which was always in short supply, since one Double gave you twice as many vitamins and minerals as a Regular. Why did they even make the regular? Who'd rather drink two of these instead of one? The last set of scans had come back during the second hospital stay. The tumors still weren't shrinking. They weren't growing either, but they soon would be, now that the chemo and radiation treatments had ended. And the doctors couldn't just keep stepping up the treatments forever. It was time to try something experimental, like drug trials. Sara tried not to think about the estimated odds of success. 22 percent 16 percent 9.2 percent Irene was like a child. She took every opportunity to stall in taking her medications—pretending to nap or to be busy in the bathroom. Saying, "Let's do it in a few minutes," when a few minutes rapidly became an hour, or two, even when these things had to be done strictly according to the color-coded Excel spreadsheet schedule that Sara had taped up in every room of the apartment. The Prednicen-M had to be taken four times a day with an Assure. Irene had to apply a 1 percent hydrocortisone cream three times a day to the rash that was being caused by her denosumab injections. Actually, _Sara_ had to apply the cream, because there were some spots on her middle back that Irene couldn't quite reach. Then every morning, thirty minutes before her first meal, Irene had to have one Fosimax pill with water, after which she had to stand upright for thirty minutes to prevent heartburn. For the canker sores, Irene had to rinse with a mouthwash of milk of magnesia and Benadryl liquid five times per day, and it had to be mixed fresh each time. Four times a day she had to take amphotericin B, for thrush. Zofran as needed for nausea; Vicoprofen as needed for pain. Because it was hard for Irene to swallow, Sara had been quartering these pills every day, then grinding the pieces up with a mortar and pestle like some sort of apothecary. After a week of this, Sara had deep-red calluses all over her palm, so George went back to Sur la Table and bought a battery-powered spice mill that worked much better. The milkshakes had to be poured into the IV bags, which could then be hung from the standing lamp by the couch, the cabinet knobs in the kitchen, the shower rod in the bathroom, and the coat hook in the bedroom. Jacob had affixed a 3M Command utensil hook behind every chair in every room that Irene might conceivably use. The hospital had given them only two IV bags, and these had to be washed after each use or the chalky residue clogged the opening. William was there most of the time, but he was hopelessly disappointing at these tasks. George and Jacob came by nearly every day to help out for a few hours, and this gave Sara some time to do her editing and to sleep and to take anxious walks around Madison Square Park—but there were things the boys truly couldn't do: Irene's urine output had to be measured, so Dr. Zarrani could be sure that she was retaining enough fluids. This involved Irene putting a plastic measuring device on the toilet seat (which she forgot if Sara didn't remind her), peeing into it, and then calling the results out to Sara, who was keeping a record down to the milliliter. There were programmed cell phone alerts. There were laminated lists of hospital phone numbers for each of them to keep in their wallets in case there were questions. And still it felt like they were losing this fight. Poor George had been on duty when Irene began having horrible cramps and had made a complete hash of everything while he tried to help without waking up Sara. Very sweet, but it meant three hours of agony for Irene while George tried to follow Internet instructions for a lower back massage that would ease her cramps. When Sara finally woke up, it had taken her ten minutes to get on the horn to three different people, who eventually concluded that, because of her all-liquid diet, Irene needed to have some senna tea twice a day to make sure she also had a regular bowel movement. That was another thing to log and another thing the boys didn't keep track of, along with cleaning the area around the PEG tube carefully with antibiotics and dealing with the mess that resulted that time when the cap came off Irene's tube in her sleep and the contents of her stomach dribbled out all over the couch. "Why isn't she fighting this?" Sara had cried to Dr. Zarrani. "She may be very depressed," Dr. Zarrani had said. "But she wants to get better." Sara wasn't convinced. Irene seemed pissed off _,_ not depressed _._ "This is so goddamn demoralizing!" Irene shouted at least once a day, as if it were all Sara's fault. She was cranky not to have time to get to the studio anymore. She sketched in bed and on the couch while they watched endless reruns of _¡Vámonos, Muchachos!_ , but half the time she fell asleep after drawing just a few lines. Then she'd wake up in an even fouler mood, as if she'd just been cheated out of valuable time. "This is fucking torture!" she screamed, throwing her charcoals across the room. Sara wanted to tell her that she'd get on the phone to the UN right away. File briefs under the Geneva Conventions. She'd throw one in for herself while she was at it. Because it was torture for Sara to see her best friend in this state. Torture to be barely sleeping, to be missing work, to hardly ever sleep in the same bed as George or have a meal that wasn't takeout. Her only social interactions, besides complaining to the boys and yelling at her interns over the phone, were during the brief times she walked to Duane Reade. Lately she'd begun lingering, just to have the breathing room. Sara stared at the cardboard sleeve that held the six individual Assure bottles together. It had a nice picture of an elderly woman on it, looking full of life and ready for a hot night down at the Old Folks' Home Ballroom, doing the Buffalo Shuffle with a nice half-blind Vietnam War veteran with some Viagra squirreled away among the cataract medications on the nightstand. Sara pushed pack after pack to the side, looking for the Double Boost, muttering to herself, _Good for you, Grandma. Go down swinging. Young at heart. Golden years and all that jazz. But if you could just leave a little Double Boost for my friend here, who is young at heart and young at body, still quite squarely in her Regular years, that'd be swell._ At the pharmacy window, there was just one man in line, an older man wearing a ridiculous green spandex unitard, propping up a bicycle. Magnanimously, he gestured for Sara to go ahead of him to the counter—the pharmacist was somewhere in the back. "She's getting my things already," he explained, as Sara thanked him. Setting her heavy bag down on the counter, she checked her wristwatch. Good. She would make it back by four-thirty. "Aren't you a little young for those things?" the man said, gesturing to the Assures. Sara looked down at Grandma Golden Years, then back up at him. He looked a little as if he'd rolled right out of an Assure commercial: _Senior citizens, on the go!_ "Picking them up for my nana," Sara lied. She didn't quite know why she felt the need to lie—she didn't even call her grandmother nana, and she lived in Marblehead, two hundred miles away. "Don't ask me why, but she loves these things." The man cringed, cutely. "There's a café near here that makes wheatgrass shakes. I'm totally addicted. I'm there three times a day. Drinking _grass,_ for God's sake!" Sara laughed because his teeth were tinged a faint wintergreen color, and his breath smelled faintly like a lawn mower. "Picking up?" the pharmacist asked her, a round-faced Polynesian woman with black, unmoving, implacable eyes. BETTIE, said her ID badge. _Bettie_ , Sara thought miserably. "Bettie!" she said cheerfully, "Could you ring these up for me?" Bettie's face was immovable, as it had been the Thursday before, as it had been the Thursday before that. "If you're not picking up a prescription, then you have to take your purchase to the front." Sara spoke sweetly, though under her breath she cursed all the Betties that ever were. "They're a little backed up right now, and my—my nana, really needs these." She wasn't beyond pulling out the cancer card when it might help in this type of situation—the cancer card had gotten her into it, after all. But she didn't want the nice bicycle man to know she'd lied about her nana. "Doctor Von Hatter? Your total comes to thirty-four fifty with the Big Apple discount card." But the bicycle man made no move to take his bag from Bettie. "Why don't you help this nice young lady first? There's no one else waiting." Sara smiled appreciatively, but Bettie just stared at the doctor. "Thirty-four dollars and fifty cents." "Charles _always_ rings me up back here," Sara insisted. "Charles isn't here on Thursdays." "Yes, but—look. I pick up prescriptions here twice a week for Irene Richmond. You remember me? Prednicen-M? Zofran? Vicoprofen? The one percent hydrocortisone cream?" Bettie stretched a hand toward her. "If you have an authorization to pick up for Richmond, I can check to see if she's due for a refill." Sara knew Irene wasn't due for a refill on anything until Sunday. "This is ridiculous," the old man said. "There's no one on line here but me. Zofran and Prednicen? Why don't you help this young lady so she can take care of her nana?" Bettie shook her head. "She's not special. She can take her purchases to the front." Even as the bicycler continued to try to reason with the pharmacist, those three words stuck in Sara's side like tiny prickers. For she was special, and had always believed it. She was more punctual, and she was better prepared. Driven harder and by purer purpose. Kinder to others and more loyal. Always recycling and never littering. Better behaved and never hypocritical. Harder working at the office, tipping more generously, and possessing of a thousand pardons. And yet she couldn't save Irene just by trying hardest or being best. Because no one was immune to tragedy. No matter how respectfully Sara lived, death could not respect her in return. She, Irene, _all_ of them were susceptible to collapse, regardless of preparations or punctuality or propriety. None of them were special. Doctor bicycle man was getting angry now. He'd seemed so nice, and now here was this _rage_ bubbling up. Even he was just another angry person in this claustrophobic fucking city— Like her. She was furious all the time now. At Dr. Zarrani, who had seemed so on top of things initially but was now proving hard to reach and sounding hapless in the face of the usual treatments failing. At Luther, for allowing one of the city's greatest newspapers to become a purveyor of garbage, and at the people who preferred escaping into garbage to caring about real news. At herself, for editing said garbage as if it mattered how uncluttered its sentences were. At Jacob, for refusing to settle down and forever distracting himself from the beautiful poetry she knew he could write if he would allow even a sliver of joy into his worldview. And even at Irene, for her completely unacceptable, irrational, disrespectful, nonsensical, whatever-may-come attitude toward absolutely everything in her life, right down to dying— And there, standing at the back of a Duane Reade while a spandex-clad septuagenarian argued with an apple-faced pharmacist, Sara first realized that Irene was going to die. She wasn't getting better, no matter how many pills Sara crushed, no matter how rigidly she held to the color-coded schedule, no matter how she arranged the cells in the Excel spreadsheet. Their final tally was always the same: Irene was dying—and _fast_ —and to Sara, knowing this was like seeing the line at the bottom of the bill. The balance, to be paid in full, for all the disappointments listed above. "Never mind," Sara said, picking up her bag back again from the counter. The bicycle doctor looked as if he were going to try to convince her to stand her ground against this abuse of power—but Sara's ever-patient smile disarmed him, "Really, no problem." _For I am not special_ , she thought, as she turned her back on Bettie, who was again asking the doctor for the $34.50 he owed for the prescription co-pay. Sara passed back up the _Makeup, Travel Size Shampoo, Children's Toy_ aisle toward the front of the store, and she even intended to do just as she'd said—wait in the line in the front like everybody else. But her feet guided her instead toward the door. She slipped the Internet coupon into the tote bag and pulled out her sunglasses. A stock boy paused as he dutifully unloaded tubes of toothpaste from a gray box onto the shelves. Did he know what she was about to do? She smiled at him and—so easy—he smiled back and stepped out of her way. She walked directly out the front door, not pausing to look back when the little door alarm went off. The harried cashier in the front, dealing with the still-long line, didn't look up, and neither did the stock boy. Her heart pounded; she felt wonderfully dizzy. There was sidewalk beneath her feet, and she felt like herself again. At the corner she had to pause for the WALK signal to come on. She'd never stolen so much as a Chapstick in her entire life. The tote-bag straps strained against her clenched fingers, yet it seemed to weigh nothing at all. It was only three more blocks to William's apartment, but something caught her eye: an M5 bus going downtown to South Street/Whitehall Station. Before she quite knew what they were doing, her feet angled away from their initial target and carried her to the bus doors just before they sighed shut. She pulled off her sunglasses so as not to seem rude when she smiled at the driver. She set the bag down on the ground and pulled her wallet out while he closed the doors and began accelerating out into the spotty traffic along Fifth Avenue. "Oh!" she said, as she looked into the wrong pocket in the wallet. "Oh no! My card fell out!" And she looked up at the driver; it took him barely a heartbeat to reassure her. He handed her a little pamphlet from the side panel. "Go on in. It's okay, miss. If it was a monthly, you just call this number, and they'll replace it." "Thank you _so_ much." She felt a snug sensation, low in her throat. The driver was pleased to help a damsel in distress, and she was pleased to have pleased him, and also pleased not to have paid for the ride. She sat down and looked out the window, past her reflection at the city rushing by. Windows reaching up into the stratosphere. Tunnels under the pavement, ferrying trains at breakneck speeds. And everywhere in between people walking every which way, wanting every which thing, all living and dying in some mysterious measure. Sara closed her eyes and shut the city out. Her phone buzzed in her pocket, but she didn't answer it. Either it was Irene, or George, wondering where she was. _I don't know,_ Sara thought. When she'd get back. _I don't know._ Where the medicine was. How to measure the urine or how to get the gunk out of the tube. _I don't know._ The phone stopped buzzing. Sara didn't check the message. Letting go of that last thing she thought was under her control was a high like no other. Realizing it never was. That nobody ever had control over anything. Sara rode the bus all the way down to Whitehall Station. There, it went around the block and began to carry her back up again. ### OCTOBER George stared at his smooth white coffee cup, determined that, by the time he finished it, his life would be forever changed. Before this burned Starbucks coffee, he'd been George Murphy, jovial drinker, perhaps at times a little weak willed, not just with alcohol but with many things: sleeping past his alarm, eating at the McDonald's drive-through when he was in a hurry (and also when he wasn't), spending too much money on things he didn't need (at this he glanced guiltily toward the bulging Barnes & Noble bag on the seat beside him), and listening to the same rock music he liked in college, even though he _knew_ it put him in an angry mood. Before this cup of burned coffee, yes, he'd been a man of bad, unbreakable habits. And yes, he, like the rest of them, had begun to go a little crazy with everything that was going on lately. But _after_ this cup, an entirely new George would emerge. A George more like these other productive and wholesome people at the bookstore café! A George who listened to peaceful, acoustic, harmonious songs like the one playing overhead, "Not Worth Fighting" by Envoy. This would be the soundtrack of the new, punctual, in-shape, fiscally responsible George. Most important, the _sober_ George. He wouldn't have another drink. These days it brought him little of the weightless joy it once had. More often than not, now, it just weighed him down more. It made him hazy and slow-witted. It was hard to admit it, even just to himself, but it had cost him a potential job at Harvard. He'd been lucky enough they'd called him, but now it had been weeks. Who was he kidding? He'd been so wretchedly nervous before the interview that he'd popped into a bar to calm down, thinking it might help to be around some people. He'd just had one beer. Full of confidence, he'd walked into the room where Drs. McManus and Schwartz from the physics department were waiting to interview him. Then, paralyzed by the certainty that the men could smell the suds on his breath, George had found himself barely able to answer even their simplest questions about the collapse of 237 Lyrae V. Well, no more. That was the old George Murphy. Forever he would look back on _that_ moment as the turning point—well, as a turning point that had then led to _this_ turning point—to _this_ cup of burned coffee, after which nothing would ever be the same. Because now he had a reason to turn it all around. And screw his own well-being and his own future—those had been proven to be woefully inadequate to the task. That's why he'd been put between this rock and a hard place. Thank God it wasn't Sara. "Thank you," he said out loud. No one in the café even turned their head as he spoke to himself. They were all busily tapping away on their laptops, earbuds shoved halfway down their eustachian tubes. He heard no clinking of glasses or gurgling of taps, just the occasional bulldozer burping of the milk frother, and the jackhammer grinding of the Frappuccino machine. Otherwise, eerie silence prevailed throughout the café. When you said a prayer from a barstool, you could count on the guy two down from you to raise his glass and say "Amen." Drunks were just polite that way. George's mother had always believed that a prayer had to be said out loud to really warrant heavenly attention. As a boy, he had said his nightly "Now I lay me down to sleep" at a normal volume, as if speaking to someone on the other side of the bed. The habit had stayed on at college. Jacob was a night showerer, and so George had been able to keep it up without him realizing. Once Jacob had come back for a forgotten razor blade and come quite close to catching him. "Talking to yourself, Georgie-boy? You know some people would say that's a bad sign, but I recommend you really _engage_ with those voices in your head. It's important to listen. You really want to do exactly what they say." What a bastard! But God, how George loved him. No one else made him laugh so hard. He and Irene were like the siblings George had never had. And now God was taking her away from him, from all of them, and George hated His ever-living guts for it. But he had to do it. He had to give Him what He wanted. In the end, Jacob hadn't been the reason George stopped praying. Nor had he been at all persuaded by the "evil liberal atheist communist professors" Grandpa Earl had warned him about. No, when the professors spoke about the cosmos being big and him being infinitesimally small, it had only reassured George of his irrelevance before forces he could never hope to control or understand. First Darwin and then Nietzsche had failed to kill his God. And then, during a seminar on Einstein and relativity, George had had a real epiphany: for every observable phenomenon, there were a million unobservable ones. So many things that his senses told him were true were only illusory: the straightness of time's arrow; the existence of only three dimensions; the solidity of rocks and the fluidity of water. Every simple, rational phenomenon was eventually unexplained by something wildly problematic and complex. He had no trouble believing that God and heaven could exist within the vastness that his brilliant professors couldn't define with formulas and hypotheses. And George believed in miracles and coincidences and mysterious ways. But he also believed that no matter how good a person he'd tried to be in every other respect, God had no mercy on he who'd begun having a nip of J&B each night while his roommate showered, instead of praying the Lord his soul to keep. Now it was time to make a new bet. Now it was all on _his_ shoulders. Irene needed him, and George had been stone-cold sober for three days. Not such a long time, but it was a start. He slapped his palm on the little café table. Then he said a quick Hail Mary, successfully spooking an old Chinese couple sitting at the table next to him. He polished off the last of his coffee and crushed the white paper cup in his hand. He lifted his shopping bag, and the plastic dug into his hand as he carried it across the street between the honking, blaring cars trying to get onto Queens Boulevard. By the time he got to the other side, he'd be a new man. Across the street Irene and Mrs. Cho spoke amiably on the steps outside Super-Wellness Spa & Nails! _,_ owned by one of William's aunts. George approached with a wave, hoping they hadn't been waiting long. Spiritual revelations were important and all, but Irene couldn't risk getting the flu, and September had ended with an unsparing cold front coming down from Canada, sending everyone scrambling for air-conditioner covers and pulling wool sweaters out of deep storage. Everyone George encountered seemed to be coming down with something, and Sara was Purell-ing everyone's hands every five seconds, so Irene wouldn't catch pneumonia. Irene, at least, seemed to be glad about the sudden need for extra layers, as loose sweaters were gratefully _in_ that fall—at least this was what she'd told George when he'd taken her to Anthropologie after her appointment last Saturday—and perfectly suited to covering the nub of the PEG tube that was taped flat against her stomach. She'd managed to keep her weight steady, and Dr. Zarrani had seen "positive signs" from the latest scans. The tumors seemed to be responding to these new experimental drugs. No one knew what tipped the scales for one person and not for the next. A PET scan could only see so much. So there was cause for hope. George wasn't too proud to beg God for help. Better men than him had done it, and plenty worse had seen mercy. "How was the session?" he asked Irene. "Good," she said, "I really think it's making a difference. I know you think it's stupid." "I don't at all!" George protested. Irene winked at Mrs. Cho, who shook her head as if to say there was nothing to be done about cynics like him. George jogged a bit on the step, trying not to be annoyed. Why did everyone think he was so skeptical? And yet he still couldn't stop himself from twinging, just a little, when Mrs. Cho took Irene's head firmly between her two hands and rubbed her temples in tight, concentric circles. She murmured in Korean and began to sweep her hands down Irene's neck. "Good work today. Remember, feel the mysterious essence. The transcendental spirit. Everything has a vital life force: your body, your tumors, the ants on the pavement, the trees that the ants climb toward the light from the sun, which is alive, just like the moon." George took a deep breath. Once a week, for three weeks now, Irene had been coming here, to a storage room full of bronze jars of GiGi bikini wax and crimson bottles of OPI Nail Lacquer, so that Mrs. Cho could perform this laying-on-hands ritual, lighting rosehip candles and stretching Irene out on a folding table so that Mrs. Cho could throw powders in the air and mutter Korean incantations. Mrs. Cho had invited him to sit in on the first session, provided he could do something about all his negative energy. But as it turned out, his negative energy was persistent—and so George had begun excusing himself to the bar across the street. A nice place with a good atmosphere and—never mind. The nearby bookstore wasn't so bad. Mrs. Cho moved her hands about a half an inch above Irene's body, not actually touching her. Her voice shook as she said, "Everything which is living radiates this essential force which animates all life throughout the universe. It is the electricity flowing in your nerve endings. It is the magnetism of your blood, which encircles your organs, and gushes throughout your veins and pumps inside of your heart." George grimaced. True, the human body contained weak magnetic fields created by iron-bearing nanoparticles and the rotational states of protein molecules and free radical reactions. But it was on the order of one tenth of one _milli_ tesla—perhaps enough to help homing pigeons and bats and sea turtles get around, but not enough to kill cancer cells. Mrs. Cho claimed this energy could be harnessed through chanting to create a healing warmth and realign the walls of Irene's cells. Well, who knows? Maybe it could. "We can measure this great and powerful energy with the life within ourselves, within our hands and our breath. Your body holds everything of the earth and everything of the universe within it. This air that you are breathing contains the dust of distant stars collapsing. _Remember_. Doubt is only the denial of happiness." Was George imagining it, or was she staring at him? "Happiness must be invited. You must allow happiness to enter into you, for happiness is the cure for all disease." George felt that happiness was kind of a tall order when the disease involved the total humiliation of the diseased. Unbearable headaches and constant nausea and aching joints and loss of bowel control and thinning hair and fingernails so soft that Irene had lost two of them just trying to sharpen a pencil. Still, maybe Mrs. Cho had a point, because fingernails or no, Irene still sketched happily for hours on end—beautiful, intricate designs that he studied when Irene inevitably conked out at some point. Were these finished pieces? It knotted George's throat to think of these pages and pages of plans that might never be executed. Mrs. Cho was glaring at him again, so he faked a huge sunflower of a smile, lest his doubt emanate from his _chi_ or something and deny Irene any curative happiness. He had to admit that, as Irene gave Mrs. Cho a parting hug, she did seem a lot happier. "Remember," Mrs. Cho advised as she let go of Irene, "just for today, you will not be upset. You will not be afraid. You will be thankful and attentive. Kindness to all those around you, and whether you open your eyes or close them, clasp your fingers in prayer and contemplate with your whole heart. Say it out loud, and believe it, inside. Just for today." George tried so hard not to laugh. They said goodbye to Mrs. Cho and went on their way, back toward the E train. "How do you feel?" he asked. " _Really_ good," Irene said. She spoke softly, as usual these days. George strained to hear her over the sporadic honking of the backed-up cars. What sounded like a stadium's worth of voices echoed off the twin-level brick mall that lined the block. Ahead, at the corner, he could see a long stream of people crossing the road and heading toward the train. George supposed it might be a store's grand opening, or perhaps they were protesting something. Maybe some celebrity was, inexplicably, dining at the Garcia's Mexican Restaurant on the corner. With a jolt he realized that Irene was still speaking. ". . . get incredibly _hot_ all over whichever part of me she puts her hands over. Most of the time it's like a warm, soothing heat, like a bath or sunshine. I swear, it's weird, but when she moves over my eye or my elbow, it gets _very_ intense. Almost to the point that I feel like I _am_ actually burning up—like I have a _fever_ or something." _Fifty years ago we'd have just given you sugar pills_ , George thought to himself as they followed the pack of people down into the subway station—where was everyone going? Irene went on, quietly, about the shaman ritual stuff, and how she was sleeping better and feeling more alert and less nauseous. Down at the bottom of the stairs at last, he saw the problem. MTA workers were cross-honoring people's Long Island Rail Road tickets because LIRR service to Manhattan was apparently disrupted—and so there was general bedlam and endless echoing down around the turnstiles, as people who had lost their tickets argued with transit employees. But still, _why_ would so many people be coming into the city from Long Island on a Saturday afternoon in October? Ordinarily if there was a service disruption, passengers would be impatient, hurried, angry. But most of these people seemed downright exuberant. Giddy. Drunk, even. Had a Yankees or Mets game just let out? No, neither of the stadiums was on this line, and besides, practically everyone here was under thirty, and most looked under twenty. And not a foam finger in sight! As they got through the turnstile onto the jam-packed subway platform, George noticed that many of the horde were wearing rock concert T-shirts. George had never heard of a single one of the bands. He was worried that Irene was already looking completely exhausted when the E train finally arrived. They squeezed inside, but it was filled wall to wall with rock fans. A rather confused-looking older man in a gray suit and glasses offered his seat to Irene. George thanked him and hung somewhat oddly off the bar over her. "Let me take your bag," she insisted. "No, no," he urged. "It's really heavy." She said something else, but very softly again, and George, distracted by the jostling of several loud concert fans behind him, didn't hear her at all. "What?" "I said, what on earth did you buy?" Irene rubbed at her throat, which clearly was sore. "Just some books for work," George lied. He was a bad liar, and what's more, he knew Irene knew it. She arched a thin eyebrow at him, but he turned away to glare at the concert-shirted people behind him, who were shouting much, much louder now. The train was crawling through the tunnel. George watched the dark wall sliding past behind Irene's head, the spray-paint rising and falling like an antic heartbeat. They could have walked to Manhattan faster! Looking over his shoulder, George was soon able to size up the people making the most noise. Three high-school-age girls were hanging on the same pole as a humongous boy who was drinking directly from a bottle of Jack Daniel's. Each time he took a huge gulp from the bottle—God, George could _smell_ it—he would release a roar like Simba at the end of _The Lion King_ , and the pack of girls would collapse into hysterical giggling. George glared at them, but they were oblivious to everyone else in the train car. He could see immediately that the boy was very drunk—past a point that George knew, but only really by inference. Past the point where he wouldn't remember whatever things occurred between that point and the next morning. Simba was wearing Birkenstocks, trendy skater shorts, and a North Face fleece. His hair was longer and more feathered than the hair of the girls surrounding him. These girls were rail thin and tanned, still, in mid-October. Instead of concert T-shirts, they were wearing tight dark jeans and the sort of wide-necked sweaters designed to show off carefully selected bra straps, which were, from left to right: fuschia, neon green, and black velvet. George sniffed. Irene, with her white sweater and her golden scarf, looked like something out of another world. He tried smiling at her, but her eyes were shut tight against the sight of Simba, belching to the applause of the girls. "What do these assholes think they're doing?" George whispered. "Oh, they're probably going to that Envoy concert at Madison Square Garden," Irene said. "Don't you remember Sara was saying she wanted to go?" George couldn't believe it. "An _Envoy_ concert? Come on. Seriously? They're like a stoner pacifist love-in granola peace-sign band! This jerk's acting like he's going to Megadeth!" Irene spoke out of the left half of her mouth. "We were young once too." Jesus, what was he doing now? Swinging the bottle of Jack around and nearly clocking a scared-looking old lady in the head! George looked around furiously at all the other people on the subway—was no one going to do something? No, of course not. Everyone was just standing around rolling their eyes at one another. George gritted his teeth. "Hey! Just ignore him, okay? We'll be at Fifty-ninth soon, and we'll transfer to the six anyway." George watched Irene, sitting there choking down green sludge. He knew she was right. "Just put your head back," George said softly. "I'll wake you when we get to the stop." She shook her head, flinching as Mr. Jack Daniel's released yet another roar. "HEY!" George found himself saying. "Come on. Keep it down!" The boy staggered into the pole and bounced off again. This sent the three girls into fits of laughter, one of them backing up right into George. "Hey, seriously, watch it!" he said, louder. The girl sneered at him, then looked away. "Cut it out!" Irene kicked him gently with her foot. "You're just going to piss them off." George was clenching his fists already but felt them go even tighter at Irene's soft-spoken implication that this guy would surely clobber mild-mannered George into next week. "It's just you're here, trying to rest, and these assholes are—" "George!" Irene had a look on her face that he knew well. It was a get-your-shit-together face. He looked around for someone else who might intervene—where the hell was Jacob when you needed him? By this point, Jacob would be cramming the bottle of Jack down Simba's throat, and what's more, Irene would be clapping him on the back for it! Why did he get to rant and rave and fly off the handle all the time, but whenever George raised his voice even a little, Sara or Irene clucked at him? The train made a sudden sideways move, and George watched the boy lurch forward and unwittingly spill his Jack. The splash hit George's arm, and then a fine constellation of brown dots appeared all over Irene's white sweater. That's when George heard himself screaming. "WHAT THE FUCK IS THE MATTER WITH YOU?" Just like that there was silence in car. Outside, just the slow grinding on the tracks. "IS YOUR BRAIN SO FUCKING SMALL THAT YOU ACTUALLY BELIEVE YOU ARE THE ONLY PERSON ON THE GODDAMN PLANET?" The hulking kid stared, but it was impossible to tell if he really understood the words coming out of George's mouth. "Hey, hey," one girl was saying, "don't freak out, okay? We're just having a good time." George couldn't stand the offended expression on her face, as if she'd simply been behaving as anyone would. He felt cold all over. "What about that old lady standing over there, who your friend almost hit with his whiskey bottle? That's somebody's grandmother. How would you like it if some clown like this guy walked up to your grandmother and hit her in the head? But you're having a _good time,_ so who cares, right? My friend's got cancer, and this asshole gets to just spill booze all over her. But that's fair, right? That's totally fucking fair." "Look, we're sorry, okay?" the third girl said. "Don't cry." "I'm _not!_ " George shouted, though he knew he was. He knew it was over, and he knew that Irene was crying too, and not because of them. The girls went back to ignoring George, and now so did Irene. When they finally got off at 59th Street and transferred to the 6, Irene wouldn't say a word to him. Finally, stepping out into the chilly air of Madison Square together, she walked, with George following, to a quiet corner of the park, and there she stopped. "Sorry," George said. "I'm sorry." And he was. Sorry and sweating from all his pores. Sorry and wishing he could lock himself in a bathroom. Sorry and shaking like a leaf. "Don't tell Sara, okay?" Irene put her hand on his and waited for him to calm down. It took a long time, and when he finally had himself together, they were both too cold and embarrassed to keep fighting. "It's kind of nice to know you can't always keep it together." Then before George quite realized what Irene was doing, she was tugging the overloaded bag of books from his throbbing hand. "That's really heavy—" he tried to say, but it was too late. Irene tried to dead-lift the bag to her shoulder for more support but stumbled backward, and the bag fell to the pavement. "FUCK!" George bellowed, so loudly that a second later he heard it echo back to him from across the park. Irene was turned around on the ground and trying to say something, but he couldn't hear it until he bent down to help her up. "I fell down _,_ George. It's not the end of the world. What is all this anyway?" The Barnes & Noble bag had split open, and books had scattered across the walkway. Irene read off the titles, one after the other. "The Dorling Kindersley _Complete & Illustrated Guide to Herbal Medicine_ . . . _Healing the Soul: Optimize Your Mind with This Proven System!_ . . . _Kicking Cancer's Ass: A Memoir_." "That's an authorized account by WWE champion Barbarous Bobby Blake." "Oh, is it?" Irene laughed. " _Acids and Alkalines: A Chemical Guide to Cancer Curing_. And seriously, _Yoga, Yoghurt, and Yurts_?" She read from the back. "'One woman's triumph over breast cancer while traveling the Serengeti in search of love, inner peace, and _bifidobacteria_.' George, there's got to be thirty books here! Did you buy out the whole Crackpot Cures section?" He shrugged. It had been called Alternative Medicine, but yes, he had. He'd gone there looking for a juicing cookbook that Sara had mentioned—as a sign of his goodwill and his determination to support the whole wheatgrass-algae-pomegranate idiocy—and once he'd found it, he'd started looking at one book, and then another and another. What if the secret to curing Irene was there, inside one of them? What if he bought twenty of them, and the answer was in the twenty-first? Buying every single title seemed the only reasonable option. The girl at the register had looked at him in abject confusion. He'd wanted to say, _Look, if you were in my shoes, you'd try anything too. What's $239.57 in exchange for Irene's life? What's a hundred or a thousand times as much? Is there any amount I shouldn't spend?_ What he'd actually said was, "It's for a paper I'm writing." Irene bent over and helped George pick the books up. She could grab only one at a time, using both hands. "You're so funny asking me not to tell Sara about your little flip-out. Like you won't tell her yourself the second she gets you alone." George knew she was right. When the books were all gathered, they slowly made their way to William's apartment. "I'm going to haunt your wedding, you know that," Irene said. "Come on, don't joke about that," George said. "I'm not joking!" she said. "You can count on it, buster. I'm going to be up there hurling rice in the air whether you like it or not." "I think Sara wants rose petals." "She would." "Rice is bad for the pigeons!" "They have this pigeon-safe kind now." "Pigeon-safe rice." George hummed to himself. "So glad someone spent time on that." They kept talking as they rode the elevator up together, heavy stacks of useless books crooked under each arm, a half-empty bottle of green sludge sticking up above the mother-of-pearl handle of Irene's purse. Sara must have heard them from all the way down the hall, because she flung the door to William's apartment open before they could even knock at it. "Where have you _been_?" "We were waylaid by violent criminals!" Irene announced as she tottered in, transferring the armful of books into Sara's hands. She made a beeline for William's wide, white couch—where he and Jacob were drinking cocktails. "George had to beat them off with his fists!" "Ha _ha_ ," Sara said flatly, as George planted a kiss on her cheek. He moved past her and dropped his armfuls of books onto William's end table. "You are in serious trouble, mister!" Jacob shouted. "For buying a bunch of nonsense books?" William asked, studying the titles. "Fuck that. I mean he's in big trouble with _me_!" George gave him a puzzled look, as he turned to Sara for explanation. "What's he—? Why's everyone drinking?" Sara's eyes were brimming, and she was smiling widely. George was sure there must be some great news from Dr. Zarrani about Irene. After all this! After his panic attack at the bookstore, and his revelation, and his thunderstorm in the subway . . . but this was it! The sign he'd been waiting for! And now Irene was going to be _fine_. George felt a swell of gratitude in his chest; he would never, ever doubt again. "Dr. mmmm and Dr. hmmmm called," she was saying. "They tried your cell and your office. They got Allen, and when they told him the news, Allen gave them my number, and they called me, thinking it might be our home number." "Why . . . wait, why would the hospital tell Allen anything?" Sara was confused. "Drs. _McManus_ and Schwartz _._ From Harvard." "WHICH IS IN FUCKING BOSTON IN CASE YOU FORGOT!" Jacob bellowed. "Hush," Irene said, nuzzling her head into the itchy fabric of his tweed coat. George still didn't understand. "What?" "The lectureship," Sara said, beaming proudly. "They're offering you the job." George didn't know if he ought to cry or faint or cheer. He settled on an extremely awkward mix of all four reactions, which sounded—Jacob would later tell him—like a dolphin choking on an orange. Then Sara was hugging him, and Irene was clapping as hard as she could—which wasn't hard—and William was heading over from the couch with his hand outstretched. In an instant, George forgot all about the subway ride and Mrs. Cho and the $239.56 and the books. He forgot who he was and where he came from. "Cheers!" William raised his glass. "To Professor Murphy!" George lifted his left hand instinctively—his hand knew what it was holding before his brain did. Before he could quite stop himself, George clinked the glass against William's and raised it to his lips. He took a deep gulp and swallowed. It burned every inch of the way down. ### NOVEMBER Irene liked that Dr. Zarrani delivered the bad news herself. For the first time in months, it was just the two of them sitting together again, no nurses popping in and out, and no friends hovering in the hallway. Irene was lying in a hospital bed, tubes running out of her arms and legs and torso. Only the IV machine made noise, beeping like a metronome on the stand. Dr. Zarrani had walked in looking tough, but barely a moment into the discussion, she'd had to sit down in the pink reclining chair in the corner. Irene appreciated this. What could be kinder, really, under the falling shadow of devastation, than for someone to pull up a chair? The experimental treatment _was_ having some impact, but only enough to stop the progress of the cancer. Upping the dosage might lead to some gains, but Irene was too weak to survive the side effects of such an increase, even with 24/7 care. Dr. Zarrani explained that this put them in a no-win situation. Either the cancer would kill her, or the treatment would. Irene knew she was right. Already, she needed help getting in and out of the gigantic hospital bed. Her arms were as long and thin as kitchen tongs. Her hair was like pillow stuffing. The sores in her mouth and throat stung even through the perpetual morphine haze. Her body's natural defense for this was to generate biblical floods of mucus, which Irene had to spit into a beige plastic tub every two or three minutes. Nurses had to wake her every thirty minutes so she wouldn't choke in her sleep. Meanwhile Irene could feel tumors everywhere now—bumps on her legs and shoulders, one behind her ear. The ones on her bones were weakening her skeleton such that a simple trip to the bathroom was alleged to be a grave risk for shattering a femur or a foot. There were others in places she couldn't feel, but the CAT scans could see them: one in her kidney, one in her small intestine, and worst of all, one the size of a baseball in her left lung, which made it hard to take a deep breath. They had her on an oxygen tank most of the time. All of this, in just under a month. Dr. Zarrani went on to explain a few more details, but Irene wasn't really listening. She was watching as the woman raised her hands to support her heavy head. She was watching Dr. Zarrani begin to cry. She'd never done this before. The quickening of breath. The flush of cheeks. The shaking of jaw, and the slow filling up of the corners of each eye until, with a bursting, the drops couldn't hang there anymore. Each tear seemed to inspire ten more. Soon the doctor was weeping, full on. "Shush," Irene said. "It's okay. Really. It's okay." "You're smiling," Dr. Zarrani said after a minute. Mascara shot down like dark lightning from both her eyes. "I'm glad you're crying," Irene said. "I'm glad—I don't know why I'm glad about that." "Nothing wrong with crying," Dr. Zarrani sniffed, wiping her cheeks with tissues from Irene's bedside. The mascara came off in long, gorgeous smudges. Neither of them said anything for a few minutes, and then finally Irene said, "Is it—is it weird that I'm kind of relieved? Like, just to know. You know?" Dr. Zarrani shook her head. "You've been in a lot of pain for a long time. It's natural to feel relief." Irene looked up at the cracked ceiling. "Should've run away when I had the chance." "We'd like to get you well enough to go home for a little while before—well, before." After a minute Irene said, "Do me one favor?" "Anything." "Tell Sara while I'm asleep." Dr. Zarrani said she'd be glad to and to page the nurse when she gets here. Then she hugged Irene firmly, like an aunt, and excused herself. When she was gone, Irene leaned over to the side table and scooped up the mascara-stained tissues. She slipped them into a Baggie and hid them deep down inside her overnight bag. Irene wasn't disappointed. It reminded her of when she'd signed up to run a half marathon and was limping and staggering through the tenth mile alone when it had begun to pour torrentially, and an organizer pulled her aside to say that the race had been called off. To not have to finish, in that moment, was more than Irene could have thanked him for. When Sara arrived an hour later, Irene paged the nurse and then pretended to fall asleep. At some point she must have actually fallen asleep, or slipped into the haze of the morphine drip, for she awoke with a start to the sound of Sara's voice, demanding explanations. What had gone wrong? How could it have been avoided? What could they have done differently? Already conducting the postmortem. Irene knew that for herself, there were too many what-ifs to count. If she hadn't ignored it for so long. If she hadn't hidden the second tumor before the trip. If she had made more of an effort to keep her strength up. If, if, if, if . . . Of course Sara still refused to give up the fight. "We'll see another doctor. We should have done that months ago. She's going to beat this. I know you think it's all bullshit, but we're in the middle of a very promising alternative therapy." Irene nearly snorted. No way in hell was she still drinking that wheatgrass-algae juice. The week before, William had brought her another bottle of Bollinger Blanc under his coat (paid for, this time), but she hadn't been able to taste it at all. The same with the bowl of pasta George had brought, covered in Momma Murphy's marinara sauce (shipped on dry ice, special). That had actually scalded every sore in her esophagus. It all made her wish she'd known it was hopeless back in June. Then she might have really enjoyed those last, disappointing months instead of wasting them trying to make the inevitable evitable. Irene waited until Sara finished a series of tearful phone calls to George, Jacob, and William before she pretended to wake up. She'd hoped that, maybe by that point, Sara would be cried out. But of course Sara started all over again when she saw Irene's eyes open. _Nice try_ , Irene thought to herself, as she sat there, consoling her friend over the fact of her own death. George came later and, like Sara, urged Irene not to give up. And so began the process of getting Irene well enough to go home for a little while before beginning the work of dying in earnest. Though she had more trouble moving or breathing with each passing day, George encouraged her to walk laps around the eleventh floor at seven a.m. It took twenty minutes to do one lap: about fifty yards up the hall and another fifty back. They could usually get two in before he had to kiss her goodbye and report to work. Only as the residual chemistry of the treatments left her system did Irene feel a bit better but also a little shorter of breath. Sara came every morning at eight and sat by Irene's bedside until eleven-thirty p.m _._ They watched TV, and mostly Irene tried to sleep or read William's copy of _The Iliad,_ which she was still hoping to finish. On that last, chilly Wednesday morning before Thanksgiving, William brought her a pumpkin latte. He had gotten up at five and gone all the way down to East Fourth Street to get one from Irene's old coffee shop there—because she had mentioned once how it was always the start of fall to her, and she liked to celebrate by taking the first cold day in November to put on her winter coat and buy a pumpkin latte and wander through the West Village looking for Christmas presents for everyone, always eventually getting hopelessly lost in one of those terrible diagonal intersections, where Sixth somehow crosses Bleecker and Downing and Minetta—or in the nexus between Seventh and Barrow and Commerce. It was her favorite part of the city, messy because it was original, made before the orderly grid above it had been imagined. Blocks of triangular madness in the otherwise rectangular city. "I got lost for about ten minutes on Perry," William told her, putting the paper cup on a tray near her hand. "It's all loose ends down there." He kissed her clammy forehead and held her hand. She felt a wave of sleep about to come over her, the likes of which no pumpkin latte could fend off, if she'd even been able to swallow anything in the first place. "Where's my birdcage?" she asked him suddenly. "Your . . . we put that in storage, remember?" Her eyes would barely stay open. She had to think very hard about the shape her lips should take to form the words. She tried to say something else, but it was no good. A moment later she couldn't remember what she had wanted to say anyway. "The nurses are saying that if you're up for it, they'll let you leave for a few hours so you can come over for Thanksgiving. Sara's doing a thing at my place." For days Sara had been flipping through _Cook's Illustrated_ and _Martha Stewart_ and _The Joy of Cooking_ , describing mouthwatering dishes to Irene to try to motivate her: a crown roast of lamb chops with whipped potatoes and slivered green beans. An icebox zebra cake for dessert. Irene didn't begrudge Sara this. She had been desperate to keep busy, now that Irene's needs were being met by the nurses at Mount Sinai, and she and George had officially given up thinking about the wedding until things "got settled." She'd given notice at the _Journal_ , planning to look for a new job in Boston after the spring semester started and George became a genuine Harvard professor. That day—the day before Thanksgiving—Sara had shown up at eight in the morning. She had to leave at noon, she told Irene. "But don't worry, George as always is coming for the whole afternoon. I need him out of the kitchen anyway." "I don't need babysitting," Irene said. "He should help you carry bags at least." "Oh, he'd only slow me down. And I'll be back by nine and stay until eleven. Don't worry." Irene hadn't been worried. In fact, she wished that Sara would _not_ come back at nine or stay until eleven. She wished they'd all go on with their own lives and not spend their own precious hours sitting there waiting for her to die. It was while George was watching her that afternoon that Irene made up her mind to save them all from any more trouble. He'd been reading to her from the _Iliad,_ getting pretty animated as he sipped contraband bourbon from a hospital Dixie cup. Irene promised not to tell Sara on the condition that he let her have a sip. It burned her throat like a forest fire, but it was a refreshing pinch against the sweet, steady stream of morphine that kept easing her further out. As George read the final battle between Achilles and Hector, he got sweaty and loud. When it was over and Hector was defeated, Irene began to cry. She hadn't cried since well before Dr. Zarrani had told her the treatments were a bust. Somehow she found it far easier to weep over poor Hector, and the way Achilles was pulling his corpse around the camp with his chariot before leaving it face-down in the dust until he felt like dragging it around again. A better description of her own recent weeks Irene couldn't imagine. George read about Apollo coming down and wrapping Hector in his golden shield so that his skin wouldn't rip . . . and then swearing at his fellow gods (and here George got up on his chair and shook his hand up at the drop ceiling), "'Hard-hearted you are, you gods, you live for cruelty! Did Hector never burn in your honor thighs of oxen and flawless, full-grown goats? Now you cannot bring yourselves to save him—even his corpse—'" and then George dropped the book when Nurse Darren came in and told him to get down or go the hell home. He resumed, more quietly, a moment later. "'But murderous Achilles—you gods, you _choose_ to help Achilles. That man without a shred of decency in his heart . . . his temper can never bend and change—like some lion going his own barbaric way.'" There Irene lost the words for what felt like just a moment in the river of morphine. "At last when young Dawn with her rose-red fingers shone once more, the people massed around illustrious Hector's pyre . . . they collected the white bones of Hector . . . shrouding them round and round in soft purple cloths. They quickly lowered the chest in a deep, hollow grave and over it piled a cope of huge stones closely set." And then George was closing the book, and Irene knew sleepily that he had reached the end. With a great sigh he sipped from his cup and said, "'And so the Trojans buried Hector breaker of horses.'" Irene tried to say thank you, but it came out as just a slurred sob. George seemed to get the idea, though, and he gave her a warm kiss on her forehead. Then he set the book on her nightstand and went to use the restroom. She dozed off and woke up, it was dark outside, and Sara was there too, flipping through a magazine article about festive votive centerpieces made out of branches of yellow and orange bittersweet. "Am I going to get buried?" Irene asked. Sara looked up at her quickly, then looked out the window. "Let's not worry about that right now," George said to her. "When am I supposed to worry about it?" Tears in her eyes, Sara said, "After Thanksgiving. Let's talk about it then." Irene left it alone. She coughed up some more mucus and drifted off. She woke up again at eleven-thirty as Sara and George were leaving. "We'll be back again at eight. And the nurses said that if your numbers are good in the morning, they'll arrange for you to come back with us for dinner." Irene nodded, even though she felt sure that her numbers would _not_ be good in the morning. She couldn't say why exactly—nothing hurt more than it had the day before, but it was slightly harder to take a breath, even with the oxygen mask. Slightly harder to lift herself up off the pillow to receive George's hug goodbye. She felt her heart pumping just a quarter-beat slower. She closed her eyes for a minute, knowing that Jacob would be there soon. He had been telling everyone that he had to work double shifts at the asylum, but Irene knew he was just angry with George for moving to Boston. He arrived at Irene's bedside just minutes after the others left. "Do you just hang around on the street until you see them leave?" she asked. Jacob rolled his eyes and said nothing. "Just go to Boston with them then. Nothing's keeping you here." Jacob flinched. "Don't be absurd." It occurred to Irene that she'd never get to see the end of it. "He finished the book today," she said. "The Hector part." "'So now I meet my doom.'" Jacob closed his eyes, speaking softly so as not to bring the nurses over. "'Well let me die—but not without struggle, not without glory, no, in some great clash of arms that even men to come will hear of down the years!'" "Do they still bury people?" Irene asked. Jacob thought about it. "I think you have to have bought a plot somewhere. I don't know if you can just do it last minute. There must not be a lot of space left in the city. It'd be all the way out in _Queens_ somewhere. Cemeteries are always in terrible neighborhoods." "So I'll be cremated?" she sighed. Jacob spoke softly. "That's how I'd want to do it. Cleansed by fire and all that. Plus I hear it's very eco-friendly." "And then what?" she asked. "Sara keeps me on her mantel in an urn? In Boston?" Jacob lightly pounded the arm of the chair. "Not on my watch! I'll make sure you're scattered." Irene purred. "I never did get to France." So many things she never got to do or see. It seemed impossible, even now that she knew. Jacob patted her hand. "Then to France you shall go." "I'm trusting you then." "Well, that was always your first mistake. Now get some rest, or those nurses will never let you out tomorrow, and Sara will have a meltdown." Jacob leaned down, and Irene kissed him goodbye. She watched his frame fill the hospital doorway and recede down the hall. It had always been his first mistake too. For Irene had no designs on making it to Thanksgiving, for a crown roast she couldn't chew and an icebox cake that she couldn't taste. No, she had only one wish left—and that was not to die in a hospital room with pink walls and teal plastic trim. If she was going to go, then she was going to _go_. All week she'd been working on the plan. Around two a.m. Nurse Moira began her rounds, beginning with the rooms down the hall, and Nurse Darren entered prescriptions into the computer at the main desk. Nurse Bethany would still be changing into her scrubs. Irene had been watching, carefully, as they adjusted the IV pumps and monitors all day, to learn how they could be switched off without sounding any alarms. It took about thirty seconds to get free, including plugging up the PEG tube and locking it down flat with some medical tape. Then she put on her red coat and some booties that Sara had knit for her. They had been in the closet covering a large pile of medical supplies that Irene had been gathering that week, in preparation for a final art project. She wouldn't get the chance to finish it, but there was a detailed sketch on top of the pile so Juliette and Abeba could assemble it after she'd gone. Irene smoothed her hair in the reflection of the elevator door. When the elevator came, it was empty. The doors shut, and she began to descend through the hospital. _What gives out first?_ she wondered. Heart, lungs, or legs? She didn't particularly care so long as it happened before they dragged her back to that plastic room. She wouldn't die on 11 East. She simply would not. "'Night," she said pleasantly as she breezed by the guard at the front. He looked up at her for a moment, and then she was past him. Cold, fresh air blasted her face like a frozen kiss. She crossed the slippery street, and from there it was just a few steps to Central Park. Soon she was in a dark, open meadow, the individual icicles of grass pushing up through the loose weave of the booties and crunching under her heels. On the far side of the meadow was an oval patch of dirt, still reddish beneath the gray frost. She went a little farther and then paused under a tree, taking time to watch the shadows dancing there in the dark, unlit heart of the city. Trudging into the chilly valley between two baseball diamonds, she thought back on the years she'd lived with her grandmother Fiona—the only time she'd ever really felt at home as a girl. An inveterate smoker, Gramma Fee had developed emphysema (to no one's surprise) just after Irene turned fifteen. For a year Irene had watched her grandmother dying, bird thin and wisp haired, an oxygen tube hooked beneath her nose. Each time she saw the doctor she'd swear to them she'd never smoke another cigarette, so help her God . . . but by the next day she'd be puffing away, tugging the little wheeled oxygen tank behind her like an impolite puppy. Irene remembered the big diamond-shaped warning sticker on the side of the tank: WARNING: HIGHLY FLAMMABLE. DO NOT OPERATE THIS TANK NEAR ANY OPEN FLAME. Every day she'd watch the cigarette burn slowly down until it was barely an inch from the little nozzles that stuck up into her Grandmother's nostrils. It was like living next to a bomb that might go off any second. It had been good practice, Irene thought, as she came up the other side of the valley and toward a grove of dark trees, feeling all the while as if Gramma Fee were just beside her. She could almost hear the creak of the little wheels on her tank. Smell the sweet, forbidden smoke. See the outline of white hair and white nightgown at the edge of the dark. • • • Nurse Moira stood at the main nurses' station with Irene Richmond's forms in front of her. The emergency contact number was for Sara Sherman. She punched the numbers into the phone and checked her watch again, hoping she could wrap up the call in time to do her rounds before her boyfriend called. Someone half-asleep answered. "Ms. Sherman?" she asked. "I'm very sorry to wake you, but Irene has slipped into a deep sleep. She's only breathing now with the help of a respirator." They could keep her on it and she would remain alive, but she wouldn't wake up. "My advice is to go back to bed," the nurse said. "She'll be the same in the morning." • • • Sara hung up without saying goodbye. Go back to sleep? Her whole body was shaking as she got up and threw her clothes on. She was already half dressed by the time George realized what was going on. "It's happening?" he asked her. She didn't respond, but he knew it was. He was still getting his shoes on when he saw her running out the door. It took him a moment to realize that she wasn't waiting for him. He made it down to the street just in time to see her get into a cab. She was gone before he could shout for her. • • • Irene wandered up and down the hills of the park. In the winter wind that whistled by her ears, she heard whispering. In the gusts that came this way and that, she felt a firm hand on her back. In the city, the wind usually blew in an easterly direction, out to sea, but strange cross-currents were pushing her west, to the far edge of the park. Maybe the dead became winds, just areas of pressure, moving this way or that. Sometimes a breeze, sometimes a whole continental front or a wicked storm. Sometimes a great and sticky stillness. Traveling the globe by indiscernible patterns. Clumping into clouds and vanishing through the ozone layer. Maybe heaven was just the air all around. Maybe this cold wind around her was her grandmother. Maybe it was some other ghostly presence. Maybe it was Achilles, though she hoped it was Hector. The city was so alive that simply walking around in it was a life-support system. Its pulsing avenues flooded her veins; its streets flushed her arteries; its people burst this way and that like the valves of her heart. On the other side of Broadway, the road sloped sharply downward, and it became even easier to go on. She felt as she had wanted to feel all along. As if she were falling, steadily, toward the wide, dark river. • • • George caught a second cab, and from there he called William, and William called Jacob. Afterwards, with nothing else to do he stared out the window at Central Park, its paths and lawns shadowed and quiet. Then, just as he was thinking of trying Sara, he saw, bobbing above the treeline, the outline of Spiderman, and—he wasn't sure if he was dreaming—Ronald McDonald. It took him several minutes to piece together that these must be for tomorrow's big parade. They arrived at the hospital just a few minutes apart, sometime past three-thirty. Sara had already set Nurse Moira straight. They wouldn't be waiting until morning. They wanted to go to the ICU immediately, where Irene had been taken for closer monitoring. Nurse Moira said she'd get it figured out and then disappeared. They waited a long time. George found some coffee. William and Jacob watched an infomercial about a new device that ensured your socks would never again be separated in the wash. Eventually Nurse Moira came back with forms for Sara to sign, and a doctor had to sign off, and though they'd been through it already six or seven times before, there was the usual confusion over why Sara, no relation to Irene, was the one listed on all the forms. Finally, someone named Dr. Ramos took them to see Irene in the ICU. She was laid out under some white sheets, fast asleep, mouth stretched open around a plastic breathing tube as thick as a tennis ball. Sara began crying immediately, and George barely registered that Dr. Ramos was quietly explaining to him that they would need to wait a bit longer. He couldn't actually take her off the respirator. He was Catholic, and while he in no way judged them, he couldn't morally take a living woman off life support. Sara and Jacob and George all yelled at him at once. William watched, silently, as their raised voices registered no movement whatsoever on Irene's still face. Dr. Ramos left, and everyone cooled down. They waited almost another hour until the second doctor could be found. Dr. Hanks came around five a.m. to begin the proceedings. • • • Irene entered the long, thin park along the river, not sure exactly how to get across the West Side Highway on the far side. There the Hudson coursed mightily, its purpled surface forever lit by the coast of New Jersey. _Near_ the river, the winds began to push in different all directions. Up toward the distant spire of a cathedral by Columbia. Back toward Broadway. Deeper into the park. Then up on the hill, she spotted something. Tall, white Greek columns reached up through the night, supporting a great marble dome on the top. It looked like some kind of lighthouse, or a tomb. Had she been here before? A long time ago, maybe? She thought she'd have remembered it better if she had. Though it was only fifty or so feet up in the air, it looked like Mount Olympus with the Pantheon on top. All the winds now seemed to be pushing her this way, as if they too wanted to have a word with the gods. She wasn't alone. Not far away, on the ring of benches around the memorial, a man lay buried beneath a mass of unfolded cardboard boxes. He wasn't moving, and Irene knew well that this night was too cold to sleep in, no matter the number of boxes you made into blankets. Her red coat was a muddy, stained mess now. If she couldn't get up, then she too would freeze to death before morning. It seemed fitting, she guessed. To die in the cold like a homeless person, which was what she had always been, in a way. One of the thousands of people who were everywhere and nowhere all the time. To die here would seal it. And at the foot of this beautiful monument, in this stolen coat, in these soggy excuses for shoes—it seemed like an honorable place to lie down. • • • Nurse Moira stayed with them the whole time, but William couldn't take it. He said his goodbyes and left just as they were about to begin removing her breathing tube. George and Sara went up together, hugging and squeezing and kissing her, but she barely moved. It was only when Jacob went up and whispered something in Irene's ear that they all saw her smile slightly, around the sides of the tube. George and Sara demanded to know what he'd said, but he wouldn't tell. Eventually Nurse Moira helped Dr. Hanks remove the tube from Irene's throat. They all watched to see if she'd open her eyes again. If she did, they wanted her to see them there, stationed by her side. • • • Except death didn't come. She tried to slow her breath and just let it happen, but it didn't. She found herself staring up at the tarnished plaque embedded in the stone wall of the monument, which read: ERECTED BY THE CITY OF NEW YORK TO COMMEMORATE THE VALOR OF THE SOLDIERS AND SAILORS WHO IN THE CIVIL WAR FOUGHT IN DEFENSE OF THE UNION Suddenly it seemed all wrong. She was no sailor; she was no soldier. She wasn't Hector, and this was no war that she'd been fighting. On each side of her stood a marble plinth, carved with the names of fathers and sons who'd sunk along with their ships. Boys and men who'd drowned in icy waters, far from home. _Must be nice_ , she thought, _to die next to your brothers_. What did they always say? Born alone, die alone? But who was ever really born alone? And why die alone if you didn't have to? She had caught her breath again. She got up and began to walk back across the street, past an idling truck dropping off stacks of the morning's newspapers. The sky above was just turning to faintest blue. The family who had been there at her birth was now far away, but her other family, her real family, was there inside the warm heart of the city, asleep in an apartment that looked like a catalog page, with the table already set for Thanksgiving dinner. • • • Her chest rose and fell as she tried to breathe, but her eyes never opened. Little by little she changed. Her breaths became shorter until they could barely tell if she was breathing at all. It was like seeing a person walking away on a wide city street. Becoming smaller, and finally not disappearing so much as becoming the horizon. In the end none of them could put their finger on the exact moment it happened. But afterward they knew they'd all seen it happen together. # II This is just the way of mortals when we die. Sinews no longer bind the flesh and bones together— the fire in all its fury burns the body down to ashes once life slips from the white bones, and the spirit, rustling, flitters away . . . flown like a dream. —Homer, _The Odyssey_ (trans. Robert Fagles) Everything takes longer than you expect. —Murphy's Second Law ## WHY WE LEFT THE CITY We left the city for good reasons, or at least they seemed good at the time. We had more lives to live and couldn't spare another hour waiting for the G train. We couldn't keep paying more and more for the same square inches. We couldn't keep asking the landlord to fix the same refrigerator. We couldn't move into a twelfth apartment. We left over bridges and through tunnels, still hoping for our security deposits. Be gone, oboe practicer in the next apartment! Be gone, old couple across the street without curtains or clothes. Anywhere else we could own property. Anywhere else we could own cars! Anywhere else we might be anyone else, or maybe our long lost best selves were only a U-Haul ride away. We lay up at night, wondering, _What sorts of people would we be if we were no longer nervous and frayed?_ Some of us tried to fight it, desperately ordering more drinks past last call. We divided and subdivided, putting up drywall to turn one bedroom into two. Taking second jobs and thirds. We pushed farther out. Greenpoint was the new Lower East Side, until Bushwick became the new Greenpoint and BedStuy became the new Bushwick. All the people we'd displaced on our way out there looked up to find us coming for them again. _When does it end?_ they asked. _We're sorry,_ we answered. _We don't know how to stop_. Then we looked back over our own shoulders and said, _Already?_ We spoke knowingly about interest rates. We asked no one in particular what the value of our time was. Anywhere else, it seemed, it would be more. Other cities, other towns promised us benefits, made better offers. We could always come back, couldn't we? We'd had everything we wanted here, once. Hadn't we been told that now we'd made it here, we could make it anywhere? Only none of us could say, exactly, what it was we'd made. So desperate to succeed and in such hasty enterprises! Once we knew someone who worked at the same place for nine years. Another had nine jobs in one year. We dreamed of being fired. _Let us go!_ we cried. There were so many things that we would do differently next time. We began to hurt each other and insult everyone else. Black clouds moved with us wherever we went, and friends recommended a new yoga studio, less gluten, window-box gardening. Doctors prescribed things to help us sleep, smile, function. We were afraid to go on vacation because we didn't know if we could take coming back. It was time. Time when our bartender knew our turtles' names. Time when a girl on Franklin Avenue threw up kale tacos on our shoes. Time when a panel of tin fell from the bar ceiling and smashed our pitcher of Negronis. Time when we recognized the opening act's lead guitarist from where he panhandled by the Met Foods. Time when that eighteenth stroller pinned us in at brunch and refused to let us out. They were finding bloody sheep's heads in the park. In Midtown there was a place where a burger cost twenty-nine dollars. Now we knew our flood zones. Our boss had joined CrossFit. There was another new old museum and another new Disney musical and another convention for home picklers. The L train wouldn't be running for the next nine weekends. The price of a MetroCard was going up again. We hardly noticed, and that scared us more than anything. It was remarkable how easily and insensibly we'd fallen into routines, beating the same track from apartment door to office elevator, stopping midway only for the same _pain au chocolat_ and coffee and the same café with an ever-rotating staff. For lunch there were the same endless salad bars and armies of chilled sandwiches. Now we ordered our dinners with the click of a button. The same button, the same dinners. No need to speak to anyone. The bars were the same, the drinks were the same, even the new ones (especially the new ones), and afterward we took cabs home and didn't even look out the window. There were parts of the city we hadn't seen in years. They reminded us of people who had left us, and we excised them from our maps before they could spread. _It's not the same_ , we said, _it's just not the same. It's not like it was, before_. We never said before what, but it was understood. We resented those who left almost as much as we hated those who stayed, because they weren't enough. Like old wood, we splintered apart at the slightest touch until we were nothing but slivers stuck in each other's fingertips. How worn and dusty were the places we had been holding on to. Deep in the ruts where everything settled. We wanted to rise up and out. See the moonlight amid the mountains. Breathe dry air and drink soft water. We began to build our castles in the air, hoping sooner or later they'd carry us off. New days came like clockwork without becoming tomorrows. We slept less and less, dipped in darkness through the daytime and heated by burning light in the endless evening. And only when we finally got up, threw on our clothes and walked away, did we realize that we had all been gone for years already. ## ZUGZWANG, WARD III, 2010 ### JANUARY During his first year working at Anchorage House, Jacob had stepped off the bus each day in front of Winston, the daytime guard, with satisfaction. While others rode on to their frictionless white office towers, he had but to give Winston a quick sarcastic salute to make the imposing wrought-iron gates creak open. Up and up the gravel driveway he'd climbed, past semicollapsed stables and yawning gray oaks. In a former life it had been a convent to the Bonnes Sœurs de la Grande Miséricorde with a giant statue of Jesus on the front lawn. Now it was a 125-bed private psychiatric facility accepting Blue Cross/Blue Shield, United Healthcare, and Medicaid, for adolescents who were persistently suffering from a host of mental ailments or required rapid stabilization in a "secure twenty-four-hour therapeutic sphere." Jesus had been hauled around to the back, near where the nuns were still buried. That first year Jacob had come in early just to spend an hour outside under the big willow tree by the duck pond, feeling like Keats, gazing up at the haunted spires and the patched, leaky roofs that were home to hunchbacks and gargoyles of his mind. At night he'd ducked out during moonless evening shifts and paced the snowy graveyard that still claimed the bodies of three dozen Wives of Christ, his heart stinging in his ribcage as the shadows whispered poems in his freezing ears. But now the great gray fortress stood indifferent to Jacob's return. He kept his eyes downcast on the slush-eaten driveway, wary of slipping and breaking his neck. The ducks had all gone south, and the iced-over pond was an opaque prison to last year's leaves and the trash that had blown over from the Chinese Boys Academy across the way. Jacob paused beside it, trying not to feel cold and trying to think how exactly it had all come to this. He'd gotten the job mainly because of his size—of that he was certain—and he'd accepted because being a poet wasn't exactly lucrative. He remembered a professor, the hoary poet Penn Hazelwood, once telling their class, "Stop any guy on the street and ask him for the name of any living poet. Nine out of ten of them will say 'Robert Frost' or 'Shakespeare' or someone who's been dead for decades or centuries. The other one will say 'Billy Collins.' And that's the ball game, chowderheads. Sorry to drag you into this mess." From his spot beside the pond, Jacob closed his eyes and with no effort at all, summoned an image of Irene just seconds after she'd died. He'd never seen that kind of pale before. What skin looks like without any blood left beneath it. Easy to remember, hard to think about. But from this memory he could rewind to the moments just before she'd died, when he had, true to form, gotten the last word in. He'd sneaked up to her bedside while the nurses were increasing her morphine drip and preparing to remove the breathing tube, and he'd whispered in her ear before "they" eased him out of the way again. He swore he'd seen the corners of her lips creak up. To Sara, he reported that he'd told Irene that, in her hospital gown, she was the spitting image of Grace Kelly in _Rear Window._ To George, he'd said that he had finally confessed to completely forgetting to water her plants when she'd gone upstate three summers earlier. But these had both been lies. As far as he was concerned, only two people needed to know what he'd actually said, and he was the only one left. Inside, at least, Anchorage House was warm, and the combination wheel to his locker felt familiar under his fingertips: 3–8–25. Orderly whites had been hanging there since November. Still a faint smell of bleach. In the men's room, the same old graffiti—a three-inch hirsute penis, a misspelled Young Jeezy lyric, an offer for a good time if bibjguy4you@msn.com was contacted. In his clean white uniform, he felt like a new person, freshly born, rather than someone who had, forty days ago, watched his friend die. The door to Ward III was keycard-locked, but just past it the door to Oliver's office was always open to both patients and staff. Because no one at work knew they were dating, Jacob fired off a casual "Hey, Dr. B," while barely tapping the door frame. Inside, Oliver was chatting with Sissy Coltrane, head of art therapy, but instead of repeating Jacob's "Hey!" Oliver froze as if he'd seen a ghost. Sissy turned, eyes wide. Jacob had spent enough time talking crap behind other people's backs to see he'd just caught them speaking about him. "You're back!" Sissy chirped, rushing to the door, her arms extended inside a scratchy, sleeveless wool sweater. It was like being hugged by a bird's nest. "We've missed you! Oliver said you were with your poor friend in the hospital! That can be _so tough._ My mother had this operation on her rotator cuff once, and she was in bed for six weeks. I mean, I'm _still_ reliving it. Terrible. Anyway, I hope everything worked out okay—" She kept talking, but Jacob was more intent on glaring at Oliver than listening. He had told Sissy about Irene, this much was clear. But had he _not_ then also told her that Irene had died? Oliver mouthed a helpless apology behind Sissy's back, making that look he always made. _For how would he know that kind of personal information?_ Jacob didn't know what to say. Sara had been the one to call people, afterward. Then she'd posted this kind of creepy announcement onto Irene's Facebook wall, prompting distraught replies from "friends" who hadn't actually spoken to her in half a decade. Long, memorial messages filled with frowny faces and little hearts. Jacob had read every entry, waiting to be really nailed. Why not? Everyone else was crying all over the place. Even George was sniffling as he'd helped him snip obituaries out of all the newspapers Sara had notified. But Jacob had just sat there scissoring, quietly inhuman, as he stood now in Oliver's doorway, Sissy's eyes already beginning to leak. "Yeah. It wasn't—it didn't—she didn't end up making it." At least Sissy released him from her hug, as she turned to Oliver, horrified. Oliver looked worried, as if Jacob were a giant mess of wires and plastic explosives that he'd just deliberately kicked. But Jacob had been getting this look from nearly everyone since it happened. They expected him, of _all_ people, to lose his ever-loving shit. It was, after all, what Jacob Blaumann always did _._ But they didn't see—there was no "always" anymore. Sara, George, Oliver, his own mother—everyone had told him once or a dozen times to just _let it out_. _It's okay to be upset! Pitch a fit, pound some walls, you'll feel better._ But surely he owed Irene more than that. He could hold on to this thing for however many years he had left. Long, long after everyone else had forgotten, he would remain Irene's cold, stone memorial. So all he did was say thank you politely—and, he hoped, not crazily—before walking away. ### FEBRUARY Jacob was assigned to monitor Dr. Feingold's eight-thirty a.m. group, which met in the common area—a few worn couches facing each other, a couple of easy chairs facing the windows. Jacob sat in the corner by the board games as the assembled patients named their greatest fears. "Being alone," said Jane with the Seconal-dead eyes. "Polka dots," called Annabeth, bulimic, at one point down to a mere eighty-seven pounds. Jamal coughed and said, "Falling? Like off of a really high building or something?" Dr. Feingold nodded in amicable fascination at each offering, as if it were both astute and deeply informative. He pointed his pen tip at a girl with glasses so thick they looked as if they could melt pennies in strong sunlight. Dr. Feingold always went around the circle in group therapy counterclockwise. Yet her hand was raised—five bitten fingernails confidently aimed at the ceiling. Jacob didn't recognize her, but that didn't mean she was new. Corporate policy advised against fraternizing with the patients. A patient might try to use personal information. They were always wheeling and dealing for better food, private rooms, supervised trips outside. He couldn't be bonding with them over their favorite films one minute and the next tackling them to the floor when they became gripped in a delusion that gorillas sent by their stepfathers had come to sell their kidneys on the black market. But this girl didn't seem _that_ crazy. With seriousness that Jacob didn't doubt, she said, "My greatest fear is dying without accomplishing anything important at all." Others in the group rolled their eyes quietly. "Thank you, Ella. That's very brave," the doctor said kindly. Ella lowered her hand and folded it in her lap calmly. She turned politely toward the boy next to her, as he began speaking about his fear of scorpions. Something about the girl bothered Jacob. Normally it was easy to pinpoint, as everyone in Anchorage House was off in some fairly obvious way: train-track scars on their wrists, vomit-stained yellow teeth, hair patchier in places where it had once been pulled out. Jacob knew whose tired eyes came from the morning's dose of Xanax and which type of arm itching was a bad reaction to Ativan. But he couldn't see anything obviously broken about this girl—Ella Yorke _,_ according to his roster. She was sitting up straight, while everyone else slumped. She was smiling patiently, but not with the halcyon glistening of antianxiety drugs or the defensive smirking of the sarcastically imprisoned. As she nodded her head in empathy with the scorpion boy, the realization rolled slowly toward Jacob like a Tiananmen tank: hers was an actual smile. It felt like years since he had seen one. Just before she turned to catch Jacob's eye, he looked down, studying a chessboard, which had been abandoned midgame. He tried to work out who was winning. Black's king was in a much safer position, but White was outflanking along the left side. He studied the board a little longer, trying to see what moves were coming up, but became stuck. He didn't know whose turn it actually was. If it was White's move, then White was in trouble, as both bishops were being threatened. But if it was Black's turn, even if he did take either of the bishops, there was no move that wouldn't leave his queen exposed to the White knight . . . Jacob felt his phone buzz twice. Sara texted him now three or four times a week. _When are you coming up to Boston? Write me a poem! Are you still dating that doctor? Why don't you quit that stupid job and come up here to be a lobsterman?_ His responses were absolutely minimal. _Where? No. Yes. Gross._ She was very excited about the U.S. team's chances for gold in Vancouver, wasn't he? He'd typed a reply about how he'd been boycotting the Olympics since A.D. 393 when Emperor Theodosius had kicked out the pagans, but then he deleted it. How could she be bubbly? How could she be watching sports? He was still annoyed that Sara had flipped out at him for not showing up at Irene's wake last month (even though he'd _said_ he wouldn't come several times). Jacob hadn't seen the point in getting drunk with a lot of arty scenesters who didn't even know Irene except as the girl who took their coats at events. Jacob imagined them all standing around with their cocktails, sweating under layers of wool, wondering _where is the damn coat-check girl_? When the pictures went up on Facebook the next day, he was glad he hadn't gone. How dare everyone be smiling? How dare they stand around in their Louboutin shoes, clutching their Michael Kors clutches with fucking lipstick smears on the rims of their goddamn plastic cups, playing a bunch of upbeat songs off Irene's iPod? Who _were_ all these people? If these were her friends, where had they been all year? How dare they enjoy themselves while what was left of Irene sat on a back wall shelf in that monstrous, tacky metal urn that George had picked out from the funeral home catalog? A room full of artists, and nobody could sculpt a goddamn urn to put her in? Knowing that crowd, it was probably lucky her ashes weren't suspended ironically in a bottle of urine. What a seismic waste of time, money, talent, and life. Now Sara was talking about working with Juliette and Abeba to open a big show of all the artwork that Irene had left behind. To Jacob, this was the most unbearable. Not that he would expect them to understand. She'd made these things because she loved making them. For her, it had never been about getting recognition or selling pieces to collectors. Her work belonged in a museum. In its _own_ museum. He ought to do it himself. Hang it all up somewhere in perfect spotlighting and then padlock the door before any else could ever see it. Sara just wanted to let it all go. Paste it into scrapbooks and move on. Start a new life in Boston as Mrs. George Murphy, a woman unpained. She kept bugging him about meeting her to go through the storage units and Irene's old books to figure out which should be kept and which should be donated. She kept asking if he'd reach out to William, who hadn't been heard from since the wake. At least in the photos he had the decency to look as if he hadn't eaten all month. Sara and George, on the other hand, had been radiant—and Sara, with her new haircut! An edgy flapper bob to go along with her new job as social media director for _The New Bostonian_. George with his stupid _Harvard Crimson_ bowtie. Jacob couldn't stand it. They, of all people, ought to understand. _Irene cuts our hair!_ he'd wanted to write in the comments section. _George, what'd you do with the suit Irene hemmed?_ But he wouldn't snap. Let them wonder why. "Wouldn't have pegged you as a chess fan, Jacob," Dr. Feingold said. "You any good?" Jacob looked up and realized that he was alone in the room with the doctor. "I'm actually Bobby Fischer in disguise," he said. "Don't tell anybody." "I think Bobby Fischer died." Jacob held his finger to his lips. Dr. Feingold stroked his bald spot for a moment. "Listen. You're Jewish, aren't you?" "Jacob Blaumann?" he laughed. "Irish Catholic, through and through." He grinned. "Hey. Sissy mentioned what happened to your friend." "Did she?" "She sort of brought it up in our last doctor's meeting." "I thought Sissy just had like an MFA in knitting or whatever." Dr. Feingold smirked. "Look, I was just wondering if you'd been to synagogue. I thought you might not know of a good one up here." "Thanks, but I'm not a templegoer, really." Still, Dr. Feingold looked quite serious. "You should go. Be with other people. Say the Mourner's Kaddish and all that. Sure it's all a little dusty, but they wouldn't be traditions if they didn't do something for the people who say them. My father passed away a few years ago. Pancreatic cancer. Brutally painful, but at least it's fast, since there's nothing you can do for it." "Sure," Jacob said, fishing his phone out of his pocket as if it had just buzzed. The text message he'd received was indeed from Sara. _I'm sending out Save the Date cards . . ._ He jammed the phone back into his pocket. It buzzed again, but he already knew what the second message would say: _What's your address?_ Jacob hadn't even been to his apartment under the church since December, nor to the city at all. He didn't know anybody there anymore. "Anyway, after my father passed, my rabbi told me I should take the year off. No big life decisions. No changing jobs, no starting new relationships, no moving to a new city." "Sure. That seems smart. Wait for everything to settle. Well, that seems—sure." But the last thing Jacob wanted to do was stay in this dead-end job. It was long past time to move on. Ever since Irene, he'd entertained a thousand escape routes. Heading up to Boston to be closer to George and Sara. Backpacking the Appalachian Trail. Joining a cult in Costa Mesa. Dusting off his old thesis and reapplying to Yale. Like crying, it seemed nice in theory, he was just out of practice. "So?" Jacob asked. "So what?" "So how'd it go?" Dr. Feingold thought about it. Finally he said, "Well, I'm still here." ### MARCH Ward III was where patients came after being at Anchorage House for more than thirty days. Most kids were in and out in under a week, referred via psych consults and crisis managers and social workers and court orders. Oftentimes they just needed a break: an orderly schedule, a little counseling, an empathetic group session, and the usual medications. Lots of kids came in on stuff; lots had stopped taking whatever they were meant to be on. A couple of days, a week, and most had their heads screwed back on again. In Ward II, they could chill for twenty-one additional days. There the docs did what they could for the kids and then either released them, transferred them to special clinics, or moved them up to Dr. Boujedra's group on Ward III. Long-term parking. The Ward III kids were neither well enough to go home nor sick enough to be shipped out. Languid, world-weary, they sat wistfully in psychiatric purgatory while others came and went. A few kids had been there for over a year, their parents happy to foot the bill and keep them safe, not to mention out of their own hair. Some had even come to feel at home, waiting for their Godots while trained professionals took a daily interest in their thoughts and feelings. Not like the real world was so fantastic anyway. Jacob sometimes saw the appeal; who wouldn't want to be constantly around people who were always hoping you'd soon be well? He suspected that Ella Yorke was in this last camp. She seemed almost happy to be there, raising her hand in group sessions, standing around by the sorry excuse for a library, earnestly staring out windows, always annoyingly smiling and _meaning_ it. Jacob found himself passing the hours imagining how she'd ended up there: bad breakup, penned some dramatic Plath-esque ode to sharp cutlery in an English class somewhere, meeting with perplexed teacher, misfired hysterics, a call to campus security . . . et cetera, et cetera? Or was she more the shut-in type? Cutting class to watch SOAP Network, first a few hours a day, then eight, then twelve, then twenty? Who knew? She could be utterly batshit. Secretly collecting the tabs off soda cans to trade with the Plutonians when they came to harvest everyone's earlobes for fuel. But Jacob had a hard time believing it was anything like that. Her biggest aberration was that she seemed so damn sincere about everything. He kept expecting to come in to find she had been released, but every time she was still there. And it began to be a strange reminder that _he_ was still there, too. He hadn't exactly decided to take Dr. Feingold's advice to take the year off and _avoid_ major life changes, yet every time the idea arose of actively pursuing something, he'd beg off. "Why don't you go back and get your master's degree?" Oliver asked him one weekend as he lay in bed beside Jacob. "Don't you think Irene would have wanted you to?" Jacob stared up at the clean white carpet of Connecticut sky. What Irene would have wanted for him—he could answer ten different ways at ten different hours of the day. "Or try something new, if you want. Jacob Blaumann," he said dreamily, " _master_ of law! You could do your own television serial." "We just call them shows here," Jacob said. "Cereal's for eating." Jacob had actually grown fond of the schoolboy Briticisms. He liked to imagine Oliver as a young boarding-school student, lounging around like this on Saturdays and enjoying the occasional company of men. During the week he was hardly ever in the mood, but on Saturdays he was like a giggly teenager who'd stumbled onto this new, secret activity. "I'll be Jacob Blaumann, Master and Commander!" Jacob said, stretching his arms to frame the opening titles. "A master . . . piece!" Oliver clapped and Jacob left to take a shower. Minutes later he tried hard not to hear Oliver whispering on the phone to someone through the tiled wall. "No, he's seeming better, I think." Toward the end of March, Jacob was reassigned to afternoons, and this involved watching over Sissy Coltrane's group in the art therapy "laboratory" (her term). Sissy led the group through middle-school-level exercises: sketching their shoes, sculpting little bowls, banging out campfire songs on tambourines. Ordinarily it was the sort of rotation that Jacob would have begged Oliver to get him out of, but Jacob didn't complain. Through a haze of clay dust drifting up from misshapen pottery, he kept half an eye on Ella Yorke. It wasn't as if he was seeking out information on her, just taking note when something appeared. Paul, one of the other orderlies, told him she was seventeen and had been in and out of Anchorage House four times over the past two years. This time she'd been admitted during the Christmas rush and after her thirty-day evaluation had been cleared to stay. She was supposedly so smart that, despite having missed portions of her junior and senior years, she had graduated in the top 5 percent of her class and been accepted at Columbia. But after one semester she was back on medical leave. This week Sissy had them work on self-portraits in acrylic paint. Everyone was given a little two-by-one-foot canvas and a hand mirror to work with. Ella had worked on her self-portrait, spending two whole days endlessly erasing lines and redrawing them, walking a few paces away to see how it looked from a distance, then rushing back to make some tiny adjustment. Once she spent the entire hour just mixing brown paint, adding a little more umber, a little more ochre, a little jet black, to get the shade right. She'd hold the brush up to her own hair for comparison. Jane and Annabeth snickered. They had plastic garbage bags over their smocks and held their brushes far away, as if they were CDC agents and the paint were a deadly pathogen. Jacob had a terrible urge to paint polka dots all over Annabeth's picture. The boys made slapdash efforts: cartoonish versions of themselves with stick-figure arms, carrying hockey sticks or driving race cars. There was an epic game of paper football flicking they were always trying to resume. When everyone else was washing out their paintbrushes in the sink, Ella sat at the table, daubing paint onto the canvas, then stabbing it repeatedly into the jar of milky brown-black water. Then she took a final, displeased look at her painting and slumped forward, mashing her cheek silently into the moonscape of dried paint that covered the table. Sissy was occupied by the girls at the sink, so Jacob went over to see if she was all right. "It doesn't have to end up in the Met," he said. "It's all out of proportion," she replied. "These stupid plastic mirrors are so warped." Indeed, the cheap hand mirrors were rippled like puddles frozen in midbreeze. "They won't give us glass ones," Ella muttered. "Somebody might, you know—" Jacob nodded knowingly. "Try to find out who's the fairest of them all?" Ella laughed so loudly she seemed to even surprise herself. She lifted her head up and clamped one hand over her mouth, but Sissy wasn't even looking. Jacob leaned forward to examine the portrait more closely. The warping wasn't the problem so much as the hollow grin—teeth gritted and lips pursed, as if the girl in the picture had just sucked a Warhead. "Here's your problem. _This_ is not what a smile looks like. This is what it looks like when someone is being operated on without anesthesia." Ella's smile grew so large that it overpowered her face, launching her cheeks up so high that they all but hid her dark brown eyes. "See, there you go. Draw that." Ella froze, picked up her mirror quickly and looked into it. "I look like a . . . like a . . ." "What?" "Like a mental patient." Jacob laughed so fast that he had to cover his mouth. He couldn't remember the last time he had laughed like that at work, or even alone with Oliver. But Ella didn't seem to see the humor in it. She dropped her head back onto the table. "No wonder my love life's such a drag." "Well, you really can't judge a smile in captivity like that," Jacob said. "They're much nicer in the wild. See, there. Like that." Ella stared into the mirror again. "It's a vicious cycle. I look in the mirror, hate what I see, then paint what I see, hate what I paint, look back in the mirror at myself hating what I painted. It's actually a perfect analogue for the major depressive experience." "The major depressive experience? You make it sound like a semester in Spain." "This basically _is_ my study abroad." Jacob looked over at Sissy, who was now showing someone the proper way to Saran Wrap a paint palette to keep it fresh for the next day. "I had a friend who was an artist," he said, immediately annoyed at himself for using the past tense, "and she told me self-portraits aren't really about faces but what's going on behind the faces." Ella considered this. "If I painted _that_ , they'd seriously freak." "So?" "So then they'll think I'm still depressed, and I won't be able to start school again in the summer session so I can catch up on all the bullshit that I'm missing every stupid awful second that I'm stuck in here trying to get myself to be fucking _normal_." And with that Ella grabbed the jar of painty water and dumped its bilious contents directly over her self-portrait. The murky black water tidal-waved in all directions, mostly back onto her own lap, and she jumped up, as startled as if it hadn't been she who'd poured it out. Shadows leaked into the paper, thick drops running down the length of the self-portrait and off the edge. Already it was pooling heavily under her stool on the floor. "What _happened_?" Sissy shouted, rushing over. Ella gently lifted the soggy edges of the portrait. Its agonized smile now peered out from behind a thick gray fog, but the smile on Ella's own face was nothing short of spectacular—cheeks rising so high that they fully engulfed her eyes. "Darling, what happened?" Sissy asked again. "Clumsy me," Jacob said quickly. "My fault." Which, he supposed, in a way, it was. ### APRIL After that, Jacob began noticing Ella almost everywhere. She seemed to have only one friend—Maura, a mousy girl with greasy hair who wedged herself across from Ella during mealtimes. Ella seemed to politely tolerate her presence, though something told Jacob that she'd be far happier sitting alone with her book than discussing the weather, the ABC primetime lineup, and what nail polish they'd wear again when they finally got home. But steadily Jacob noticed that Ella (and often Maura) was looking at him, then quickly away. During group sessions with Dr. Feingold, Ella began to sit in the chair closest to the chessboard where Jacob stationed himself. When he led the patients down the hall after sessions, she invariably walked at the front of the line. In the common room, he would rotate positions periodically, to try to keep an eye on the rowdiest groups of patients. Slowly he became aware that whenever he moved locations, she followed, orbiting him like a moon. During meals Jacob would sit with the other orderlies at a long table near the side of the room, and wherever he sat, whichever direction he faced, Ella would sit one table over, no more than a few feet away. "Someone's got a little crush on you," remarked Paul. "What?" Jacob asked. "A what?" Paul smirked and made rapping motions with his hands. "A little infatuation with your situation. A yen for your zen, man. Some uncomplicated admiration. Some pokey little puppy love. A hankering for your—" Jacob didn't want to know how he'd finish that rhyme. "Die in a fire, Paul." He stood to leave despite Paul's assurances he'd only been kidding. It was pouring outside, and Jacob didn't feel much like a walk anyway, so he spent the rest of the break in his bathroom stall, quiet except for the echoes of his sandwich being eaten. Not that she didn't seem, well, _better_ since he'd spoken to her in the art lab that day. Her "Portrait of Ella in Gray" was now hanging up in the common room to everyone's frank admiration. And he hadn't done anything wrong. He'd never laid a finger on her, even when she'd jumped up from spilling the jar—and this was more than he could say for some of the actual doctors. Little Dr. Rutherford, with his gross mustache, had allegedly had a three-year affair with a former patient, a gifted trombonist with a drinking problem, yet he was still working down on Ward II as if nothing had ever happened. Dr. Parker, a behaviorist with a husband and kids at home, had last year started sleeping with a janitor in the little-used fourth-floor library. And Dr. Harrison, who still _ran_ Ward I, had actually married a former patient of his from another hospital where he'd worked in the early 1970s. Everybody knew about it. They had an annual Christmas party at their house in Greenwich; Oliver had gone many times. It always seemed to Jacob that Oliver lived vicariously through these stories at the same time that he lived in constant terror of them—a good lawsuit being all that stood between Anchorage House and total collapse. In honest moments, Jacob even wondered if Oliver didn't enjoy sleeping with him so much as doing so beneath a Sword of Damocles. For the hundredth time, Jacob thought about walking out on the job, on Oliver, on this life. Of decking Paul in the mouth before he did. Of calling Sara, only he had no idea where to begin. She was still after him about his address for the Save the Date card. She wanted to know if she could mail it to Oliver's place, or to Anchorage House—did he have a mailbox there? Jacob just said he was looking into it. As he passed by the art room, he checked to see that Sissy wasn't inside, then walked slowly around the room, pausing in the far corner by the bowls, pencil cups, and coffee mugs that the patients had made last month. They couldn't keep them in their rooms, now that they'd been fired, because they might shatter them and harm themselves with the jagged bits, so these eminently functional artworks sat here, functionless, until their makers headed home. Jacob casually inspected Ella's mug. He smiled proudly. What a perfectly sane mug! A golden pattern was carved around the top edge—no, not a pattern but some kind of incoherent lettering. At first he thought maybe she was insane after all, but upon closer inspection, he realized that it wasn't merely Greek to him. It _was_ Greek, Όλυσσεύ, repeated all the way around. Jacob hadn't read those ancient letters in years, but he knew the name of the epic hero of the _Odyssey_ when he saw it. Odysseus. There had been a time in his life when he'd been able to recite whole sections of it from memory ( _Sing to me of the man, Muse, the man of twists and turns driven time and again off course_ ), usually while quite drunk at the sort of jugular parties that nobody ever threw anymore. Four semesters of Attic Greek, studying crumbling dusty books in forgotten corners of the library, translating words that had been translated a million times before. Words that were meaningless claptrap to everyone else in his universe, as if poetry alone weren't a dead-enough, lost-enough language. Sometimes it seemed as if he'd spent twenty-some years working his ass off to ensure he'd have practically nothing in common with anyone. "Jacob?" The lights came buzzing on as Sissy Coltrane blew into the room. "Hey there," he said with a forced wave, well aware that he was holding Ella's mug awkwardly in his other hand. "Looking for something?" "Pencils," Jacob blurted out. "We're all out. Over in the lounge. Dr. Boujedra said I should come in here to see if you had any extra." Sissy fished around in a drawer until she produced a fistful of pencils. "Oliver's usually so good at keeping the supplies on order," she said. "That's Ella's mug there. She's got quite an eye. Smart, too. Oliver told me she got some kind of Presidential Scholarship last year, right before she came back." She had called Oliver "Oliver" twice now. "What's her deal?" Jacob asked, while Sissy crossed to a refrigerator in the corner where she kept open paint jars. She pulled out a brown paper bag with a greasy spot on one side. "She's so smiley most of the time. You sure she's not kind of coo-coo?" Sissy pulled out a fat, cold egg roll. "Jacob, you know I can't discuss that kind of thing." Jacob rolled his eyes. As if she and "Oliver" and Paul and everyone else didn't spend half their lives gossiping about which patients saw chartreuse elephants and which had been arrested for pulling the emergency brakes on the subway and which had been found naked on the roof, covered in glue and feathers torn from pillows, trying to fly to Mars. "Not such a strange case. We've tried all kinds of medications, but she still becomes severely depressed by the strangest things. Oliver described it really well the other day—what did he call it? Oh yes, he said it's like a hypersensitivity. An 'extreme adjustment disorder.' Like an acute stress disorder, only the stressors aren't unreasonable or unidentifiable things." "So they're just— _actually_ stressful?" He hated the way she kept saying "we." "Yes, but not stressful to the extent that she experiences them. For instance, going into a deep depressive funk for weeks because—I don't know, a houseplant dies. Or she saw a Christian Children's Fund commercial on TV. Those ones with Sally Struthers?" "Finding Sally Struthers depressing is cause for rehabilitation?" Sissy eyed him warily. "Well, yes. If you can't get out of bed for three days afterward. You or me, we'd feel bad for a minute, maybe two, and we'd move on. With Ella? Well, you know what brought her back here this time, after doing terrifically for six months without trouble? She saw one of those St. Jude's posters on a bus. You know, with the little bald chemo children? Apparently she just lost it. Began weeping and didn't stop for two days, even after her boyfriend drove her back up here." Jacob hoped his eyes hadn't widened too much on the word _boyfriend_. "So how long before she goes home?" Sissy set her egg roll down and pulled out a white carton full of lo mein. Then she snapped apart a pair of chopsticks, and then to get the stray splinters of wood off, she rubbed them against each other like a Cub Scout trying to start a fire. "You know how it works. She can stay here until someone stops paying for it. Or until she's ready for the world, I guess." "Who's ever _ready_ for it?" Sissy looked exasperated, its own reward. "Why are you so interested?" "I'm not really. Just, she talked to me the other day, and she seemed—I don't know—she seemed fine. Made me wonder what she's doing here is all. Hey, where'd you order from?" "Pardon?" "Is that from Szechuan Garden, in Stamford?" She looked down at her half-chewed roll. Jacob glanced at the colorful assortment of cabbage and carrot inside, and the smooth brown spiraling of the wrapper. "Stamford? No. Of course not. I live in Katonah," she said. "I don't know. I just order off the menu on my fridge. Hunan Palace? Dynasty Pagoda? I can't remember." ### MAY Then one day Ella was gone. Not in Feingold's group and not in art therapy. Not lining up for decaf coffee at seven on the dot. Jacob overheard a despondent Maura mumbling to another girl that Ella's parents had come over the weekend to pick her up and take her on a Wonderland Cruise for two weeks before going back to start the summer session at Columbia. Her mug was gone from the rack, though "Self-Portrait in Gray" still hung on the wall in the common room—left behind, perhaps overlooked in her rush to get back to her real life. He liked to think she'd left it there for him. A way of saying thank you. Goodbye. "There, there," Paul said, when he saw Jacob moping over his roast beef sandwich, "plenty of other crazy fish in the sea." Jacob wanted to lay into him—tell him that for one thing he was gay, and for another not everything always had to be about sex, despite what _The Real World: San Diego_ and the CW's _Vampire Hookups_ might suggest. Not everyone was so lonely and desperate that they leaped into bed with the first willing partner. Sometimes a cigar was just a cigar, and sometimes a skyscraper was just an efficient way of arranging offices given limited surface area. But Jacob barely mustered a good eye roll before heading off to eat his lunch in the bathroom again. He hadn't meant to look Ella up on Facebook. He didn't even have a Facebook _account_. He felt this was important to stress. When he had to—when he really _had_ to—he used Irene's account, which she had hardly used herself, never even bothering to upload a profile picture, so that now it displayed just a ghostly outline of a woman's head. She had given him her password, and he used it only in cases of emergency. As he looked at messages for her, he wondered who else might have been there. Then he thought of Ella and couldn't remember—was it York or Yorke? So he'd tried typing it out, there in the little search bar— _Ella York_ . . . no, no . . . _Ella Yorke_. Yes. That was it. And without thinking, he emphatically hit the enter key. And there she was. Smiling like a girl in a toothpaste commercial, in a blue high school graduation gown. Eating tacos in a college cafeteria with a couple other girls. Unwrapping a present in front of a fake Christmas tree. Eating mozzarella sticks in Washington Square Park with a girlfriend, wearing churchgoing hats at a Salvation Army. He realized what a difference just a few years made. Facebook, the Internet, all this had been a part of her youth, while for him, now, it hardly existed. He paused on a picture of her wearing a cranberry prom dress and pinning a corsage onto the tuxedo lapel of an earnest-looking young man—when he hovered the pointer over the boy's face, his name popped up, unrequested. Francis U. Williams. _Francis and Ella._ Then Jacob signed off, almost immediately. It had been only a tiny, accidental lapse in professionalism. This was how Jacob planned on explaining it all to Oliver, as he walked quickly through the halls of Anchorage House to Oliver's office, where he had been abruptly summoned over the PA system, midway through his shift in Dr. Feingold's group. He knew he was in deep shit even before he saw that the door to Oliver's office was, unusually, closed. "Dr. Boujedra?" he said, knocking quickly on his way in. "You wanted me to come—" Inside the office, Jacob saw Oliver's elbows on his desk, his hands gripping the sides of his balding head. A police officer stood a few feet behind the door, fiddling with the dispatch radio on his belt. Jacob froze. Surely not because of him? "Thanks for coming in. Unfortunately, my father just had a stroke behind the wheel of a car. He's been killed. This officer needs me to go and identify his body." Jacob didn't understand. "What? All the way to _India_?" The police officer looked confused. "Jake—you know—" Oliver paused to collect himself. "My father has been in a senior citizens' community in Mount Kisco for a few months. Before that he lived in New Jersey." Jacob _had_ known this. It was just the way Oliver spoke about his father—always reminiscing, always in the past tense, made it seem like Dr. Boujedra, Sr., still lived far away. But yes, now that he thought about it, he remembered that the man had been widowed six years ago and had then retired to the United States. He began remembering snippets of conversations with Oliver—anecdotes of how Dr. B. Sr. had been behaving erratically. The diagnosis was Alzheimer's, and Oliver had gone down to Jersey to bring him up to the Glendale Retirement Center. Jacob thought of something. "Where'd he get a _car_?" Oliver looked embarrassed. The officer spoke up. "He pocketed a set of keys belonging to the assistant director of the facility. Nice little blue Porsche. Cayenne model?" "Yes," Oliver said bitterly. "Which he totaled. Drove it into a water hazard at the Sunningdale Country Club." Jacob tried to cover his snort of amusement with a fake sneeze. Oliver didn't seem overly convinced. He sighed. "I suppose I should be happy he didn't kill anybody. Anybody else." All Jacob wanted to do was throw his arms around Oliver, but he kept pretending that he was just a dutiful employee. "How can I help?" Dr. Boujedra cleared his throat. "Officer Himmel is giving me a ride to the morgue. I was hoping you could drop my truck off by my flat later this evening on your way home from work. If it isn't too far out of your way. I don't think I'm in any condition to drive, and I'd—I'd leave it here but the Glendale people have asked me to come by in the morning to pick up his things." Jacob could barely hear himself saying, "Sure, sure. Of course." Oliver was standing, arms folded against himself, his face turned away. Coldly, he sorted papers into his bag to take home. Then he handed Jacob the keys to the truck and walked off with Officer Himmel. Jacob went into the bathroom to stick his face under the tap, slurping coppery water until his mouth was numb and his stomach was full and sick. He fumbled his way into the stall. It was like being hung over—or still drunk from a week ago. Fuzzy sheet over his eyes, cotton in his mouth and ears. He'd never had a panic attack before. He'd always figured it would be like being out of breath, but he was breathing fine, even though his nostrils stung as if he'd been huffing Sriracha. He ground the heels of his palms against his eyeballs, which felt as if they'd been turned to marbles inside their sockets. When he felt like he could walk again, he went straight to Oliver's parking spot and jumped into the truck. At first he intended to just head back to Oliver's early—maybe lie down for a while and flip through one of the pretentious little green leather-bound Poetry Classics volumes that he kept way up on the top shelf in his study, so no one could see they'd come through some Time-Life subscription service back in the 1980s. But as Jacob went out the back way and got onto the Hutchinson River Parkway, he began to dread the idea of lying there alone in the _flat_. Waiting for the sound of keys in the door and knowing it would be Oliver, all sad and depressed, or maybe still aloof and despondent as he'd been in the office. Steadily, Jacob accelerated. The trees along the parkway were brilliant green and moving lightly in the breeze. He rolled the window down a little and set the radio dial to seek. He'd never even met the elder Dr. B. Probably Oliver had known this was coming. He was probably more annoyed about having to pay for the Porsche. Jacob wondered what he'd do if his own father died. Probably drink heavily. Certainly be extra rude to people like Oliver. And he didn't even _like_ his father—Oliver and his dad had been quite close. Well, no, not that close. The real problem was that Jacob was dating a man in his late fifties who was still basically in the closet. The old man had gone to his grave believing that his son was straight. Still asking when he and his ex-wife would finally get back together. Now Jacob wondered if, somewhere deep down, Oliver wasn't relieved: both his parents had died without knowing their son slept with men. Jacob remembered coming out to his own parents at age fifteen to Royal Shakespeare Company–level hysterics. His father had sworn solemn oaths, and his mother had literally beat her breast. Oliver had never lived through such a scene. True, post-fallout had been better—he got a rare apology from his father and had gotten to watch him reading, in extreme discomfort, self-help books with titles like _Love Is All: Accepting Your Gay Son_. That had been pretty priceless; there had been illustrations. Plus, he'd got to check out men at the mall with his mother after school. Jacob hardly called his parents now and only visited on his birthday. He wondered how it would feel to be an orphan. The radio came onto a classic rock station, and Jacob punched the button to hold it there on the tail end of "Paradise City." He cranked it as high as it would go, rolling both the windows down so that the wind roared back and forth across the bench seat. "'Oh won't you please oh take me hooooooome . . .'" He recalled nights in dark Ithaca basements, lost in the strobing of jury-rigged lights, voices all around him shouting this anthem from before their time. Jacob sped up, sailing around each bend, tacking between lanes around sad little Hondas and Kias and Scions. His heart thundered, and cool air pummeled his face with tiny fists. The music crescendoed and crashed into silence, and Jacob felt as if his whole body might burst. Just then a little prerecorded promo came on: _Two for. Two for. Two for Tuesday._ Jacob remembered loving this as a kid, when they'd play a second song by the same artist, right after the first. And softly, the rising return of Axl's moan, knock knock knocking on heaven's door and Jacob pounded his fists against the steering wheel, lost in a joy greater than he'd felt in over a year, ecstatic—filled up like this by not just one song but a second, just when it ought to be over. Like a multiple orgasm—a subject of intense debate once between himself and George—whether guys could ever have one. Sting claimed it was possible. Back at school Jacob had wanted to sign up for a course in "orgasmic mastery" taught by a Dr. Koolhaus downtown. Sara had said it was God's way of making it up to women for childbirth. Then Irene told stories about nights she'd spent with a woman in Detroit who could wrap her tongue around a Coke can. He could remember how George squirmed, trying not to lose his mind thinking about that—hopeless. Even Jacob had taken a cold shower. He noticed that he'd gone past the exit that cut over to Stamford. Way past it. He was seeing signs for Meriden, still heading north toward Hartford. From there, he vaguely knew, he must be able to take something else east toward Boston. It all seemed so simple, he didn't know why he hadn't seriously considered it before. He'd crash on the couch at George's for a week or two. It would be good to see them again. It had been petty of him, not uncharacteristically so, but now it had gone on long enough. Of course George should go to Boston and work at fucking _Harvard_ if he got the chance—and just because he looked happy in Facebook photos didn't mean he actually was. George was just unflappable—that was what everyone liked so much about him. Jacob wondered how he would get Oliver his truck back. Probably stealing it wasn't the nicest thing to do to someone who'd just lost his father. Now the classic rock station had on some Joni Mitchell bullshit. He wanted something angry. Less Bob Dylan, more Dylan Thomas. To Dr. Sr.!—Jacob raised an imaginary glass to the windshield. Driving around a Westchester Country Club golf course in a stolen Porsche. He had to hand it to Dr. B.—at least he'd gone out on his own terms. _Rage, rage against the dying of the light_. Maybe that was why it had been so brutal, at the end, to see Irene lying there in the bed all morphined and breathing on a machine and, well, going gentle. If old age ought to burn and rave, then youth ought to be downright atomic. There shouldn't have been anything spared for miles after Irene went out. She should have decimated the entire city, with no one left standing. Soon Jacob grew tired of driving, tired of the trees, and tired of the second Joni Mitchell song on the radio. "Two for Tuesday" could cut both ways. He was tired of never knowing how he'd be feeling next: panicked, annoyed, orgasmic, weepy, worn out. Traffic had slowed to a crawl in the right lane and was barely faster in the left. He inched along, following a red snake of brakelights around the winding curves, until at last he saw the cause of the holdup. About ten cars with their flashers on, moving slowly as one through the right lane, and the left clogged with people trying to get around. One by one Jacob passed the cars in the right lane line until at last he pulled up ahead of the chain, to the black hearse with purple zinnias ornamenting the hood. PAULSON & PETERSON FUNERAL HOMES was written discreetly along the side. Just as he was about to pass it, the traffic ahead of them slowed down, then stopped. Jacob tried not to look over at the hearse through the passenger-side window. He pictured Oliver down in some hospital basement, like where they must have kept Irene, afterward. Some creep balding doctor opening a metal drawer in a refrigerated wall. Inside, at first, just a pile of white sheets, as if someone had forgotten to make the bed. Just have a look, and we'll be all done here. Underneath, a life-size-doll version of the man who raised him. Made of something cold and white that isn't skin. How hard it would be to believe it—to say, _Yes, this is my father_ —when you didn't see it happen. Jacob took the first exit and looped around on an overpass, getting back on the parkway heading south again, the way he'd come. He turned the radio off and rolled up the windows. Again, he blew right by Stamford. By the time he got back to Anchorage House and parked in the director's spot, he'd been gone just over one hour, and there were only two left in his shift. Dr. Givens and Dr. Berg were down by the little trash-filled pond, smoking cigarettes. They definitely noticed Jacob climbing out of Oliver's truck, but he was finished caring. Life was too fucking short. He wasn't going to give two fucks about what everyone else thought. Inside, he walked back into the bathroom stall and sat down on the closed toilet seat. He lifted the truck keys to the cold metal wall and scratched lightly, a little surprised how easy it was to leave a mark. Back in high school he'd done it all the time, leaving cryptic poetry, but he didn't quite feel up to that yet. He would go to Boston in a few weeks, once Oliver was feeling better. His feet were steady on the tiled ground. His legs didn't shake on the edge of the seat. His hand scraped at the paint. A little less-than sign and the number three beside it: <3. It made a little heart, just like the ones people had written on Irene's Facebook wall. Then he got up and went straight to his assignment in the common area. The patients were playing board games and doing puzzles and watching _Judge Judy_ on the TV. Paul patted his palm against the wall, as if to coolly invite him over. "Hey la, hey la, your girlfriend's back. I just saw Jorge from Ward One sneaking a cigarette in the back stairway. Said they readmitted Ella Yorke this morning." Jacob wanted to just throttle him. "Fuck. Is she all right?" "Said she looked kind of sunburned." "No, I mean what the hell happened?" "Guess you'll have to ask her. Even money she'll be up here again in thirty days." "Shit." "Well, you know what they say," Paul grinned. "Fourth time's the charm." ### JUNE The Ward III library was set into an old linen closet off the common area, which had been fitted with shelves and the sort of partly shredded paperbacks found on the racks outside bookshops for a dollar, or for free in a laundry room. A collection of castaways, curated only to the extent that anything vaguely interesting had been chucked. There were a handful of feminine empowerment books for teens and a few pop-psychology favorites: _The Road Less Traveled_ and _In Search of Self._ The sprawling oeuvre of Dr. Phil. Jacob had noticed that Ella, during her previous stay, had been working through the odd classics, Charles Dickens and Jane Austen, but the library mainly carried the B-side stuff. _Pickwick Papers_. _Northanger Abbey_. She had plowed through these in the span of a few days. It had taken Jacob a year in college to trudge through _Middlemarch,_ but Ella had it back on the shelf in under a week. There was really nothing much written after 1890, and when he asked Oliver why they'd omitted anything written after Freud bought his first couch, Oliver had answered that the selection hadn't been updated since before his arrival, ten years earlier, but that he had once spoken to Dr. Dorothy about it. She was on the committee that oversaw purchasing of books, games, DVDs, etc. Basically everything had to be assuredly harmless. Nothing too scary or too bleak. This explained a lot. After the Industrial Age things got a bit dicey, didn't they? But most kids wouldn't slit their wrists after reading _Mansfield Park_. Jacob argued they might, when faced with the prospect of reading it over and over again all summer. There was no poetry of any era, which Jacob took as a compliment. Nonstandard line breaks were mighty suspicious. Enjambment, slant rhyme, lack of punctuation? They could easily send anyone over the edge. Keats died young, Shelley drowned. Sylvia Plath, obviously, was strictly _verboten._ How many girls came in there saying _The Bell Jar_ (practically a suicide manual!) was their favorite book? Jacob had always wanted to give them a copy of "The Colossus" and say "there, there." And good old Frost had never killed anyone, had he? Why not at least give them the sort of stuff that made the days worth passing? Finally he volunteered his services to Oliver, saying he'd be happy to sift through the anthologies for life-affirming poetry, but he got the answer he'd expected. Safer not to. Anchorage House couldn't afford to be sued just because some patient had a bad reaction to _Les Fleurs du mal._ Oliver seemed to be doing okay. Distracted more than anything else. Jumpy sometimes. What was more bothersome was how eager he was to use his newfound grief to reach into Jacob's. "Now that my father's gone," he'd said once, as they showered together one Sunday, "I feel like I have the chance to really sum up what we meant to each other. You must know what I'm talking about." Or the night after, going through the magazines for recycling, Oliver had fondled a bit of the rough twine and said, "The funniest things remind me of him. What is it for you?" Jacob supposed he could have answered truthfully: girls in red coats, Spanish-language television, hot tubs, almond croissants, that stupid Plain White T's song, the entire Metropolitan Museum of Art (which he hadn't been back to). Jacob resented the implication that these things were equivalent to Oliver's twine. Fine if he legitimately missed his father, but it wasn't the same. Like when Oliver recalled little racist things his dad had said when he was a boy. "Well, he wasn't perfect! Makes it worse, in a way, remembering all his flaws. _You_ know what I mean." Jacob thought of Irene's compulsion for girls who treated her like shit. How she'd loved getting wasted on champagne and spending Midas amounts of money on vintage clothes and how she'd been notoriously bad about paying people back what they'd loaned her. She'd been fierce about her secrets, as if believing that without them they'd have long ago gotten bored with her. None of them even knew where she'd come from or how she'd ended up in Ithaca. It felt like a lack of faith in _them_ , when you came right down to it. But everyone had dumb flaws when they were twenty-six years old. Oliver's father had had _fifty_ _years_ to climb beyond those early shortcomings. He'd had decades to regret his bad choices and outgrow his habits. And what would Jacob regret if his bus were to sail over a guardrail the next day? He didn't think more time watching Oliver "processing" would be on the list. No, what he'd regret was not being there when Ella's thirty days were up. Oliver he couldn't help, but Ella—well, he had begun to formulate a plan. If she couldn't get to her summer session, then he could bring it to her. After work he holed himself up in Oliver's study, ostensibly working on some new poems but actually quietly climbing up and down the swanky bookshelf ladder, digging through his green Time-Life poetry volumes. Working carefully, using a ruler and half a scissor, he sliced out one poem after another. Once, he'd gone up looking for Elizabeth Bishop. "The Fish" was one of those poems he'd remembered reading, around Ella's age, that had just turned his blood cold. _While his gills were breathing in / the terrible oxygen_. Who knew you could rhyme things like that? Slice went that page, and he watched it flutter down to the floor. Then he'd spotted Blake just after it. (Oliver's books were alphabetized within an inch of their lives.) He guessed that Ella had probably read "The Tyger" in high school, in some tissue-paper-paged Norton Anthology, but had she ever read "London"? Probably not. Had she ever been to London? he wondered. Jacob had done Europe in high school on a class trip: the Jewish quarters of Rome, Paris, London, Madrid—with bonus stops in Dachau, Auschwitz, and Buchenwald. He'd always meant to go back without chaperones, but what poet could afford the jet fuel these days to cross the ocean? Ooh! Wordsworth. "Daffodils" was good stuff, but was it the right thing? It was tricky. On the day Ella finally came up to Ward III, Jacob was all set. Barely acknowledging her presence in the group sessions or the art room, each morning he would find his way over to the closet library and slip one poem into the middle of whichever book he'd seen her reading the day before. Then in the afternoon, when she went over to reclaim her book, he'd watch from the windowsill as she found the poem tucked inside. Anne Sexton one day, Keats the next. He tried to avoid any chronology. "Is there a W theme?" she wrote on the inside cover of one book after the first few days, when she'd gotten William Carlos Williams, Wislawa Szymborska, and Wallace Stevens. The next day she got Wang Wei and a note that said, "Theme = Poems That Do Not Suck." At first he'd been wary of writing on the poems, because anyone who found one lying around her room was bound to get the wrong idea. But then he realized it wasn't like anyone would recognize his handwriting, except maybe Oliver, and what was he going to do about it? Anyone else would just assume it was a by-product of some interpatient romance (which were just about always going on). Teenagers were teenagers, especially crazy ones. After one week, Ella wrote a poem back. He found it folded up under the edge of the chessboard during Dr. Feingold's group. While the patients went around discussing their relationships with their parents in advance of that afternoon's visitation, Jacob quietly unfolded the neatly hand-printed page. "The Whole Ball of Wax" described a ten-year-old girl who eats every crayon in a box of sixty-four, vividly imagining the flavors of Brick Red ("too salty by a mile") and Caribbean Green ("like pea soup turned up the dial") and "Outer Space" which "vanishes between my teeth / refusing to exist in me." After the final crayon, a Yellow Orange, sets her "intestines roiling" (not bad, for a rhyme with orange), the girl eases her own belly button open with two fingers and extracts the titular ball of wax—"a lump / indigestible and indefensible. / A Crayola cortex / slick with slime / my parents shriek / and jam it down the disposal / with two ounces of vegetable oil. // They hit the switch. / Colors fly into the air / settling like snowflakes / in their shirt collars / and hair." He could feel her eyes on him, searching for approval. Without supplying any visual cues, he took his pen and began circling weaker words, underlining a few tremendously good ones. There needed to be another syllable here, one removed there. Rhymes weren't really in vogue anymore, but they were tolerable until you turned into Dr. Seuss. He noted this in the margin and slipped the poem back beside the chessboard and listened to the group's discussion again. "My parents are both so in love with themselves, it's disgusting," Anne Marie was saying. "When they look at me, they're just seeing themselves, and if I'm not doing a good job with their half, they get pissed." "Mine are divorced," John agreed. "So they each just see the shit they can't stand about the other." Dr. Feingold nodded. "There is a mirror effect there, yes, but it goes two ways. Parents see their own faults in us. We see our own fears in them." Jacob didn't think this was particularly true, as a rule, at least not in his case. A prim girl, Karen, announced, "My parents think the president was born in Kenya." Dr. Feingold was trying hard not to smile as she continued. "Last Christmas my dad bought everyone in the family guns. Mine and my brother's they're going to keep in the attic until we're older, but he said he can't wait until because by then the government will have outlawed the Second Commandment." Jacob listened as the group described mothers who lived at Bed Bath & Beyond, racking up credit card bills with purchases of window treatments, pod coffeemakers, and slow cookers that were never even unboxed. Fathers who drank a six-pack a night while watching _Three Stooges_ reruns. Some loved too much, others not enough. They had stuck them in here, though no one gave any sign they were happy to be away from these alleged monsters, who embarrassed them in public, didn't understand, had no idea what it was like to be a kid these days. They were overbearing, underbearing, and bared too much skin at summer swim parties. They slept with teachers, secretaries, neighbors, or the parents of friends, or else they desperately needed to get laid. They had gotten divorced too fast or had stayed together too long. They had married too young or too late. They had irresponsible numbers of children, or they had focused all their energy and attention on just one. They were untrusting, unsupportive, manic, drunk, cheap, anal, bullying, balding, varicose veined, miserable, fucked-up, saggy-armed, Botoxed. The list was endless. Jacob waited to hear what Ella would say, if anything. What had happened to make her this way? Why did she need to be kept safe here, like him? Had her parents raised her in some kind of protective bubble? Was she, like some zoo-born animal, incapable of reentering the jungle? He heard the other kids talking about their big plans. All eager to get out and join some startup. Or marketing their own lines of purses or building an Etsy empire. But Ella never seemed interested. "Ella. You've been very quiet," Dr. Feingold pressed. "My parents are—" She took her glasses off as if to clean them, then set them back. Jacob realized he had both feet wrapped around the legs of his chair. "My parents are such . . . stupid—" Ella began. Dr. Feingold gestured for her to continue. "Such stupidly happy people." Jacob spotted them later at the family visitation, held biweekly in the sanctuary of the former chapel. The stained-glass windows here were the last real building features that remained from the convent days, deemed too beautiful to be torn out, even if they did depict horn-tooting angels and sword-wielding saints. Jacob couldn't actually get close enough to hear how the visit was going, but he watched: mother just like Ella but with hair up in a twist, chin doubled, and cheeks red with capillaries; father pudgy with a street-sweeper mustache, spiffy spectacles, and a Livestrong bracelet. Still? Jacob wondered if his own parents looked this way to other people. Like better-padded versions of their offspring. They were both beaming vacuously. Not that they appeared unintelligent, just that their enthusiasm didn't seem to be merited by the circumstances. Other parents had the decency to seem uncomfortable, worried, or even put out by their journeys. Lots of them spent the majority of the hour looking around, trying to get Oliver's attention so they could discuss his sense of their child's progress, rather than actually visiting said child. Mr. Yorke was looking around all right, but not for a consult—seemingly, he was admiring the stained glass, squinting up at a depiction of the Lamb of God on a purple hillside. Jacob thought at first, maybe he was a religious nut of some kind, but then Mr. Yorke scrunched his face up in an imitation of the lamb's and made a little _baaaaaaaaaah_ noise to get Ella to laugh. She didn't, but Jacob did. He watched them say their goodbyes and wrap her in bear hugs before they left. "What's so funny?" Paul asked. "Your _mom's_ so funny," Jacob replied. "Hey, I gotta take a leak." Paul was always happy to uphold the sacred brotherhood of pee breaks. "I'll cover you." So while Oliver was busy with Karen's parents (who indeed wore matching PALADINO FOR GOVERNOR buttons on their shirts), Jacob ducked out the main doors a little ahead of Ella, then pretended to be just coming back from the restroom when she came through. "Where are you headed?" he asked. "Back to the common." "Let's go the long way." Without really thinking about it, he held the doors open to the outside. Ella looked warily at him and then, just as he was about to apologize and explain he'd only wanted to get some air, she walked boldly past him and out into the world. They walked quickly, neither saying anything about the fact that they were hurrying to avoid being seen, and they didn't slow down until they were back by the relocated Christ statue. "Your folks left early?" "They got us all tickets to a movie, but I told them I couldn't—" She glanced at him sideways, knowing that he knew she'd been cleared for an afternoon outing. That he'd know that it wasn't what she'd meant by _couldn't_. Jacob thought about it a moment. "What movie?" "That new one with Stone Culligan." She noticed his scowling. Jacob wished he could explain why the star annoyed him, and the argument he'd forever be reminded of by him, but bringing up Irene at all felt wildly inappropriate. It might even send Ella into a tailspin. He couldn't reconcile it all himself. How could he explain what had happened to a girl who found telethons depressing? "Check the _DSM_ , but I think not wanting to see a Stone Culligan movie is proof of sanity." She sighed. "They were so disappointed! They never show it, but I know they were." "Why didn't you want to go?" "It looks _sad_." Jacob had seen a few commercials for it over Oliver's shoulder, and there had been a review in the latest _New Yorker_. Fresh from rehab and now dating a different Israeli supermodel, Culligan was taking on substantial material for the first time. Playing one of four brothers uniting for their mother's funeral, Culligan arrives sexily disfigured from a recent ATV accident, which in a fit of art-imitating-life turns out to be _not an accident at all, oh my god!_ "I take it you're not a fan." "He's not my type." It was hard to tell if his implication had landed. Ella did get very quiet and remained so as they stepped around a half-dozen headstones. "I don't get it," she said. "Why do people pay fifteen bucks to sit in a dark room with a bunch of strangers so they can watch actors pretend to be miserable for two hours when they can see it for free if they just open their eyes? And anyway, how do they get up afterward and just go across the mall and buy sensible shoes at Ann Taylor Loft?" "Why do you like poetry then? At least in movies sometimes things explode." "Poetry makes things look more beautiful. That's okay." Jacob checked his watch but made no effort to turn back. It would take them a few more minutes to realize Ella wasn't where she was supposed to be. "Shitty movies can make things more beautiful too. If Stone Culligan felt how you feel once and turned that into something, then that's one less thing to keep to yourself all the time." Ella looked at him through fogged glasses, then removed them as if to wipe them clean but instead just waved them around. "I wasn't going to jump. Off the cruise ship. I don't know what you heard, but I wasn't." Jacob shook his head. "I hadn't heard anything. Who thought you were going to jump?" She crossed her arms over her chest and walked ahead. "My parents. The stupid deckhand guy who saw me on the railing. The asshole ship doctor—who becomes a doctor on a goddamn cruise ship? That's what I want to know. That's not a reputable career, you know? That's not, like, a sign of excellence in doctoring, to spend your life bandaging kids' skinned knees and—and—" "Worrying a lot about Legionnaires' disease, I imagine." "Exactly. Who would choose to do that? Who would work on one of those floating prisons all year long? Someone like that shouldn't be taken seriously, is all I mean." Jacob didn't say anything, though he was thinking that at least if he'd signed up for a year on a cruise ship, he could practice his backstroke once in a while. Ella was stepping widely to avoid the ground in front of the nun's headstones. "'Here Lies Sister Mary Sullivan.' 'Here Lies Sister Alice McNally,'" she read as she leaped over the graves. Jacob decided to try one too. "'Here Lies _Sister, Sister_ , American TV sitcom.'" She laughed, and he wondered if she even got the joke. But then she said, "TGIF," as she crossed herself and went along to the next. "'Here Lies Twisted Sister, who really aren't going to take it anymore.'" "You're too young to know about them." "My dad still has all his old records." "And terrible taste, apparently." "Hey, speaking of taste, what'd you really think about my poem?" Jacob had been wondering if she'd have the nerve to ask him face to face. He felt another small swell of pride that she had. "Just what I wrote." "But what do you _really_ think? Like, do you think I've got what it takes? To be a poet?" Jacob examined her closely. "You're going to need a _thing_. Like white-person dreadlocks. Or a ponytail that goes down to your shins. Or wear a lot of rings maybe. Like an insane, abnormal number of rings." Ella frowned. "I was thinking about getting a tattoo." "You don't have a _tattoo_ yet? Oh, God. I'm not sure I can be seen with you, actually." Ella looked around perfunctorily to see if the coast was clear. "Do you have one?" "I have the Chinese symbol for love tattooed on my left ankle." "You do not." "I can't show it to you though, because these socks are really complicated." "Be serious." Jacob quietly used a headstone to scrape a bit of mud off his shoe. There was a poem engraved on it that he had never seen before, though he had been out in the graveyard a number of times and had, in his boredom, looked at all the sisters' headstones plenty of times before. Somehow he must have missed this one. Or rather he felt as if he had read it before, ages ago in some anthology, for he half-remembered it even as he scanned the simple lines. It is a fearful thing to love what death can touch. A fearful thing to love, hope, dream: to be— to be, And oh! to lose. A thing for fools, this, and a holy thing, a holy thing to love. At some point as he looked at the inscription, Ella had come over and begun reading it too. She waited for him to say something. He thought about simply saying that he had no way of knowing if she'd be a great poet or not, and that the odds were heavily stacked in the "or not" column, and that even if she managed to find her way to the other side, it meant doing a lot of work for nearly no compensation or recognition whatsoever. But standing there, reading those words on the headstone, he found himself unable to give his usual answer. "I'll tell you if you answer one thing for me first. In all seriousness. Why were you on the railing if you weren't going to jump?" Ella took a sudden interest in the twigs around her feet, kicking them this way and that. "It was like being a little kid again. Like not being afraid, at all, of anything. I don't know if you've ever been way out in the ocean like that. I never had been before. But when you're out there far enough that you can't see land from any side? It's just incredible. Like being on a new planet. There's nothing man-made, just the sun setting and these clouds that are just on _fire_. Every color imaginable. The whole crayon box. And when the wind picked up, I couldn't even hear the engines going, or the kids crying down by the pool, or the birds shrieking down by the snack bar . . . it was just all gone, and I felt like I was in heaven. I wasn't afraid of anything. It was like I was weightless. But I swear to God, I didn't want to jump." Jacob wanted to hug her, or at least pat her shoulder or rub her head. He settled for holding a hand out and helping her to her feet. "Did you try telling Dr. McDisney on the boat about it? Or anyone here?" Ella shrugged. "I didn't know how to describe it." Jacob motioned for her to follow him back. "It is one of the hardest things there is to describe, in my experience." "What is?" "Happiness. All these poems I'm digging up. That's the theme—that's what they are." Ella spoke slowly, as if worried about mispronouncing something. "I was happy." They walked back, slower this time, not afraid of being seen, right up to the side door. Jacob deposited Ella safely back in the common area without a single raised eyebrow (except from Paul, and who cared?). She went and played a game of backgammon with Maura, and the two of them spoke about daytime TV, and while Paul was distracted by a boy attempting to watercolor the windows, Jacob made his way over to the bookshelf and pulled out _Tess of the D'Urbervilles_. He felt Ella's eyes on him as he wrote on a blank page in the back. "Okay, chowderhead, you're a poet. Write me a poem. 'Orange Peels.' Five stanzas. Free verse. Due Friday." ### JULY Dr. Dorothy Zelig was in charge of the widely advertised new pet therapy program at Anchorage House, which involved taking exceptionally high-strung patients (like Maura) and helping them to relax by playing with dogs. Children who had suffered various abuses at the hands of grown-ups learned to accept love and to care for living creatures. Even if it sounded like hippie-dippy hogwash to him, Jacob had never had any issue with Dr. Dorothy personally until he was once again summoned to Oliver's office in the middle of the day—this time for exactly the reasons he'd feared. He didn't know how he'd missed spotting her, and he suspected she'd been hiding down behind some shrubbery on the far end of the graveyard and not at all walking one of the therapy dogs and minding her own business, as she claimed during the meeting in Oliver's office. "Gosford had to take a tinkle," Dr. Dorothy declared, "and that's when I saw Mr. Blaumann here and the patient Ella Yorke talking suspiciously out by the old statue." She spoke as if she were a witness in an episode of _Law & Order: Pedantic Bullshit Unit_. "I wasn't aware," Jacob said, "that I was talking in an especially suspicious manner." Oliver, sitting behind his desk in full-on, serious Dr. Boujedra mode, eyed Jacob wearily. "So you don't deny that you were with the patient outside the building?" Jacob considered that it was essentially Dr. Dorothy's word against his, and that Ella would probably deny everything if they spoke to her about it. But he didn't _want_ them talking to her about their chat, and giving her the impression that she had committed some sin just by having a conversation. And for another thing, fuck Dr. Dorothy. "Yeah, no. I don't deny it. Ella was clearly upset, and it was a nice day, and I thought some fresh air would put things in perspective. Legend has it that nice weather has a calming effect on human beings, but I'm just an orderly so I couldn't say for sure. Obviously I'd have to do a longitudinal study with multiple placebo groups and write a seven-hundred-page dissertation to be qualified to say so in an official capacity." Oliver was upset, but Dr. Dorothy beat him to it. " _This_ is what I'm talking about. A real lack of respect among the staff for the hard work and expertise represented by the doctors, and it is undermining the authority that we have among the patients." Jacob rolled his eyes. "Oh, please. You got a D.O. from the University of Barbados, and you teach kids how to pet dogs." "Mr. Blaumann, I won't tolerate disrespect toward the doctors here," snapped Oliver. "Clearly you _are_ aware that the code of conduct expressly forbids venturing outside the building in the company of a patient. So why did you feel it was within your rights to do so?" Jacob had never heard him shout before—it gave him chills, how much it sounded like his father. He knew he had no chance here. Despite the fact that he hadn't said anything inappropriate to Ella, and certainly hadn't _done_ anything, he had legitimately broken the rules in letting her outside without permission. It was definitely a fireable offense, and it wasn't like his record was sterling otherwise. For years he'd worn his contempt for this place on his sleeve—talking back to the doctors, calling in sick, cutting corners, arriving late, leaving early. He'd been daring them to fire him almost since he started working there. Losing the job now wouldn't keep him up at night exactly, but if he told Dr. Dorothy to shove it, then he'd be gone and Ella would be on her own. On the other hand if he promised to give Ella a wide berth from here on out, there wasn't much point either. "Ella Yorke," he began, much more flushed than he felt he had any reason to be, "is a very bright girl. We had a conversation one afternoon in Sissy Coltrane's art room—" " _Dr_. Coltrane," Dr. Dorothy stressed. "Okay, but she's _not_ a doctor though, she's—" "Mr. Blaumann, please," Oliver urged. "I've just got to say, all this doctor this, doctor that crap is getting kind of Second Commandment. 'I am the Lord your doctor, thou shalt have no other doctors before me!'" Dr. Dorothy nearly spit on the carpet. "Is he serious? He's really out of his mind. Oliver, he's—this kid needs help." "He's not a kid, Dorothy, he's twenty-eight years old. And as I understand it he's having a difficult year, but _Jacob_ , as a sign of respect in _this_ workplace, you will refer to the doctors by their proper title, and that is final. Am I understood?" "Does that mean I'm not fired then?" There was a little flirtatious hint in Oliver's eye as he said, finally, "You have to promise me that you will not engage Ms. Yorke any further without guidance from professionals. From _doctors_. My door is always open." Jacob reluctantly promised, and Oliver called the meeting to a close. But as they were all standing up, Jacob turned to them both. "Can I just ask? Have you seen any kind of improvement, therapeutically speaking, in Ella Yorke since she came back?" Dr. Dorothy gave him a dirty look. "That's not something we can discuss with you." "Oh, come on. You tell us all the time which patients are doing worse, so we can keep a closer eye on them. What's wrong with saying if one is doing better?" Oliver, surprisingly, accepted this logic. "Ella's actually been improving a lot since she came back. Her dosage of Prozac has been reduced. Dr. Feingold notes that she's been participating more in her group work, and Dr. Coltrane has nothing but good things to report. In our sessions she is . . . optimistic. It's a big improvement. In fact, if things stay positive, we all think she's going to be ready to leave by the end of the summer so she can start school again." At this, Jacob smiled widely, and it seemed to confuse both psychiatrists—and even himself. Was he smiling smugly? Cryptically, sarcastically, menacingly? No. It was just an actual smile. A natural reaction to hearing something he'd been hoping to hear. "Is there something—Jacob? Is there something we should be aware of?" _No end of things_ , he thought. • • • As punishment for the incident, he was put onto night shifts for the remainder of July, beginning the very next evening. After riding in on a bus packed with people heading home after a long day at work, Jacob arrived at Anchorage House just as the sun was setting behind the main gates. He'd been up since morning, spending the day alone in Oliver's flat, watching television in his underwear. It was vaguely boring but hardly a punishment. More like a punishment for Oliver, for now Jacob would hardly ever see him except on weekends. He was still in a fine mood when he went to the bathroom to change. He had been eyeing a few of the longer novels in the common area library. _Anna Karenina_? Did they assume the kids would simply never finish it? Not like there were _trains_ around, but still. Either way he was rather looking forward to the solitude. Only as he stood up, about to leave, did he notice something on the stall a few inches above his head where he'd etched his heart a month ago. Someone had turned it into the top of the letter R, in the word PRAY. Whatever. Probably one of the visitors had done it. No big deal. He left the bathroom. By midnight he'd abandoned the Tolstoy with barely ten pages read. Anchorage House was practically silent with all the patients in their beds. After another hour he was desperate for _some_ kind of incident: nightmares or insomnia were common, but only rarely did they erupt into anything that required an orderly's help. The doctor on staff was Patrick Limon, a slow-moving man in his seventies whose white hair burst Koosh-like from his skull and flowed seamlessly from his nostrils to his mustache and beard. In his white lab coat he glided from room to room, administering the odd night dosage and then sliding off again. Jacob walked the length of every hallway. Then he walked them all backward. Then he tried the stairs backward and nearly broke his neck. Finally he marched back to the bathroom, looked again at the defacement of his graffiti. PRAY. So imperative! He took out his keys and scratched a response beneath it, in gigantic letters: WHAT FOR? But he didn't feel better. He checked his watch again. Four in the morning, and nothing left to do but tackle Dr. Limon and demand to be given a sedative. Something—anything—to stop the running commentary in his own head. Once he'd heard beautiful whispering, poems begging him to write them down. He still heard whispering, only now it was considerably nastier. _All you've done is get her hopes up. Why? So she can head on back out into the world only to find that it is exactly as twisted and black and sick and fucked up as she thought it was? She isn't depressed, she's just thinking fucking clearly. Mind your own business. Haven't you learned anything? You can't save her. You are not special._ He couldn't handle another hour, let alone another month, of this solitary confinement—which is what it was. How did these kids do it? Two hours left to go. There was no way. He was never going to make it. After another twenty minutes he'd decided to just leave. It was long overdue. He could probably walk to the bus station in an hour and then just go right on up to Boston. He sure as hell couldn't stay here. He went to his locker and took his real clothes—not even bothering to change into them—and then went back to the common area and grabbed _Anna Karenina_ , thinking that if he got picked up by some creepy trucker, he could at least club the guy with it if he tried to get fresh. As he shoved it into his bag, he spotted Ella's portrait still hanging, gray, on the wall in the dark. She'd be back at school soon, and not even too far behind schedule. He worried, though, that she might get depressed again when she found out he'd quit. He figured he had better leave some kind of goodbye, so he tore a page out of the back of the Tolstoy and went over to the chessboard, thinking he'd write something and leave it there for Ella to find the next day. Only when he sat down he found there was already a piece of paper wedged under there. He'd sworn he'd checked earlier, and there was no way Ella had left her room, but there it was—not a poem this time, but a letter, which read: Hope you get back on your old schedule soon! Paul was up here watching group as usual. Did you know he picks his nose? There was a guy in here last year with OCD who picked his nose so much that they had to actually put mittens on his hands. I asked Dr. Wilkins about it. Rhinotillexomania. It's a real thing! Before Maura, I had a roommate with OCD, and when she got nervous, she would pluck out her eyebrow hairs. The doctors warned her that it wasn't like when you shave your leg hair. It doesn't just grow back, but she couldn't help it. After a week she didn't have any eyebrows left! She tried to draw them back on with eyeliner, but it looked totally deranged, so I found a pen and shaded them a little, and that looked a little better, but then it came off in the shower a few days later. I told her we could just do it again . . . it wasn't like I had anything better to do, but she said it was pointless. I heard they sent her someplace down in Florida that specializes in OCD. I kept thinking, "She's right. It is pointless." Was she going to spend her whole life drawing her eyebrows back on every time she showered? Someone told me they can tattoo them back on again, but that's got to be pretty obvious. And if they ever did grow back, wouldn't she pluck them out again? It wasn't like walking around eyebrow-less was making her less anxious. So it was doubly pointless. Pointless squared. Just a pointlessness spiral, and then I got stuck in it. That's how I get about things. That's why I'm here. That's what my parents don't see. For them it's easy to just say, "Well, it could be worse! She could have plucked out her eyelashes too!" and they'll actually laugh about it and then go eat soup. I mean, hypothetically. They don't eat, like, odd amounts of soup. It's just that they do soup things. They do normal everyday soup things instead of, I don't know, caring. You're the first person I've met here, or really anywhere, who doesn't just go eat soup. I hope that's not weird to say. That day you talked to me about my picture was the first time anybody in this whole place ever asked me about something like that. Nobody looks closely. Not the other kids here. Not even doctors whose job it is to look. Everybody's just got their nose in their own soup. They say they care, but they don't put poems in books for me to read. They don't tell me I can be a poet or call me chowderhead. They talk to me about "adjusting my expectations for the world." And how I need to be realistic and just accept that this is how things work and that life is unfair and some people just don't get to have eyebrows, which is at least better than being a baby who is born starving and sick which is at least better than being raped and murdered and I ought to be happy that I am smart and well-fed and have loving parents and clothes and a house and all that means I won't have to think about those other things which aren't in my control anyway so that's why I've just got to "work on me" and stop worrying so much so I can get better and get out of here and do something with my life, which is a precious gift I never asked for. I know, I know, I know. Anyways, I hope you get back to your old shift again soon because Paul is the worst. Jacob sat there a long time, reading the note twice more in the dark. He stared down at the pieces on the chessboard, both sides still trapped in their zugzwang, equally poised to lose. But then what was so bad about losing? he wondered. At least then you could start a new game. Worse to stand there forever. Idly by. Taking time off when there was so little time in the first place. On the page from the book he'd ripped out, he wrote first in huge letters, "MAKE THE WORLD ADJUST ITS EXPECTATIONS OF YOU." Then he added, in smaller letters, "Assignment: Write me a sestina about soup for Tuesday. And a sonnet about eyebrows for Sunday." Then he folded it up and placed it back under the chessboard. ### AUGUST Solitude, it turned out, was something you could get used to, like anything else. Jacob finished _Anna Karenina_ in two weeks and came up with a complete lesson plan for Ella. He continued to communicate with her via the chessboard, discussing poems along with whatever was going on during the daylight hours: Maura had a crush on one of the new patients named Roy, Paul's nose-picking was continuing, and Sissy was teaching them all to crochet, though they had to use cumbersome plastic hooks that nobody could hurt themselves with and they were forbidden from making scarves or anything with long sleeves. There were a lot of potholders happening. Ella was attempting a beret. Also word must have somehow gotten out that Dr. Dorothy was the one who had ratted on Jacob, because someone (Maura) had apparently stolen her glasses during a dog-petting session (not even at Ella's behest) and dropped the pieces into a vent. Oliver had promised to get Jacob back on days just as soon as things quieted down (i.e., when Ella went back to school). Jacob didn't hold it against him, but he worried that their time apart didn't seem to be doing Oliver much good. He was increasingly despondent even on weekends. They still had sex in the morning on Saturday, and after that he seemed interested only in the television. Jacob sat through some political chatter about the Chelsea Clinton wedding. Oliver got a little choked up at the "candid" photos of old family moments: Bill and Chelsea and Socks watching a movie at the White House, Chelsea walking through an African village with her mother and making funny fish faces at her father. "They're so sweet together," Oliver said. "I guess," Jacob replied. He wasn't really paying much attention, flipping openly through the collected Keats, trying to choose which poem to excise when Oliver next went to the bathroom. "I always wanted to have a daughter," Oliver said, searching the cracks in the ceiling. "Hmmm," Jacob said, temporarily distracted by a commercial for the Stone Culligan movie. Had they really named it "Death Be Not Proud"? There ought to be a law. Oliver trimmed his toenails, which he knew Jacob disliked witnessing, then changed the channel to BBC America, where an episode of _Coupling_ was on. Jacob watched as much as he could stand of the perilous minutiae of modern quirky relationships—about ten minutes—before he complained. "Can we watch something else?" "I like this show." "You're not even laughing!" "I don't laugh at everything I like." "It's a situation comedy. You're supposed to laugh at the _hilarious_ situations they're in." "I'm laughing on the inside." "Hilarity isn't a cerebral thing, Oliver. You can't wryly observe hilarity." " _I_ can," he said simply. Someone on the show walked out of a closet without clothes on. "HA HA HA HA HA," Oliver said. Jacob smacked him with a pillow, and Oliver pinned him against the mattress, and they ended up having sex again. Afterward Oliver changed the channel to a nature show—a peace offering that kept Jacob in bed through lunchtime (cold cereal and half a banana, still in bed)—and they talked for a while about the oceans. Stunning, alien creatures that inhabited the depths. The British documentarian explained the reproductive cycle of the common Sydney, or gloomy, octopus. A little baby octopus floated there on the screen, about the size of a quarter, with pinkish flesh so translucent that a red lump of a brain was visible, floating behind its eyes. Oliver began sniffling. "It looks like a Martian from some crap B movie! Why on earth are you crying?" "Look how _small_ it is. You can literally see the big black ocean right through it! And the parents don't stick around to teach them how to survive out there. They just _know_." "It's an arthropod, Oliver. You are projecting onto an arthropod." "Octopuses," Oliver sniffed, "are _ceph_ alopods. And they are highly intelligent creatures. They are one of the only other creatures with the ability to empathize." Jacob had to agree that, by this logic, octopuses were above a lot of humans he could think of. Paul, for one. Still, he thought crying over them was excessive. "They have what are called episodic personalities," Oliver added. "What's that?" "They behave consistently over the span of a few hours or even a day, but inconsistently over longer time frames." "Is that why they call them gloomy octopuses?" "No, that's because when they're mature, they turn gray colored. He's going to explain it in just a minute. Wait." "Hang on. You've _seen_ this before?" Oliver didn't reply. He always got this way after he'd been caught crying. Jacob knew he probably could respond more kindly or at least bite his tongue but—an octopus? "Are we just going to stay in bed all day?" "You can go out if you want to." Jacob went. He took the keys to the truck and drove out into Stamford, knowing that a good boyfriend would have talked it all out with Oliver. Listened to him pontificate about cephalopods and empathy and episodic personalities and how his dead father had sometimes been gloomy—and a good boyfriend would have loved him for all of it. Jacob didn't know how Oliver did it—sat around listening to people being sad all the time. He wished to hell that Oliver and all the others would just _do_ something with all that disillusionment, as he'd done with Ella. You didn't have to limit it to poetry. Maybe the world wouldn't be so depressing if depressed people were more productive. There should be a whole Works Progress Administration for the clinically depressed. The DPA! Rise up, ye who are down and out! Tear up the rusting bridges and rip out the cracking highways and build new cities out of the rubble! He drove to Borders, fifteen minutes down the road. When he got to the store, he ambled through the current releases, the magazines, and the café and eventually located the poetry section—half of one shelf. Paranormal Teen Romance had four. But no matter. He ran his fingers along the spines, searching for the one he'd been thinking about breaking his "no epics" rule for—one that he felt would tell Ella everything he needed to tell her himself but couldn't begin to say. He'd been debating translations in his mind—hoping there might be an edition available with the original Greek on the alternating pages. But all this proved to be grossly premature, for the store didn't seem to have a single copy of any edition of _The Odyssey_. "Excuse me," he asked the clerk behind the information counter, a teenage girl who seemed as bored as any six Anchorage House patients. "I'm looking for _The Odyssey_. Is there maybe a classics section somewhere?" She shook her head. "Author's name?" "Homer," Jacob said. "Homer what?" "Just Homer." "Like Madonna?" "Yes, exactly." Her black-polished nails clacked at her keyboard, and she looked up, puzzled. "Nothing under 'Homer.' You sure you don't mean like the guy on _The Simpsons_?" "No, I don't mean like the guy on _The Simpsons_." "Because then I could look it up under Simpsons." Jacob sighed, wanting so badly to go off his rails, but for the first time in his life he wasn't sure of his ability to get back onto them again afterward. He settled on taking a deep breath and spelling the title out for her, slowly. After a minute she shook her head. "I can put it on order for you if you want." "Do you have it at another store?" She checked and after consulting a manager was able to give Jacob directions to the other store where they had a copy. But when he got there, it turned out they didn't actually have one. A middle-aged man, as bored as his younger counterpart at the first store, was happy to redirect Jacob to a third store, and there, finally, Jacob did find a copy of the Fagles translation. As he paid for it at the front, he joked to the cashier that he had driven nearly four hours now trying to find the book. "Sounds like you've had quite an odyssey," the cashier said with a smirk. Jacob could have kissed him on the mouth. But he settled for asking if he might know how to get back to Stamford. When he finally returned to the flat, it was already getting dark. "What happened to you?" Oliver called. "Dinner got here an hour ago!" "Let me _tell_ you—" Jacob began, thrusting his hard-won copy of _The Odyssey_ out in front of him like a trophy. But he stopped, midsentence, when he came to the coffee table. Oliver was back to watching the BBC America channel. And there on the screen was Sally Struthers herself, in grainy 1980s VHS quality, surrounded by tiny, emaciated African children, chewing on their thumbnails and staring wide-eyed into the camera, through the decades, out into the living room where Oliver was far more attentive to the huge spread of Chinese food that he had ordered. Jacob had the fleeting feeling that those pale little shrouds of children were actually looking _at_ the Chinese food—waiting for their moment to reach through the glass and steal a wonton. He forgot all about the book in his hand for a minute as the commercial continued—the 800 number flashing on the bottom. _Should I call?_ he wondered. He had always thought these things were scams, or fronts for religious organizations. The sane, human thing to do was to change the channel. To take up club-league kickball. To read all the cartoons in the _New Yorker_ and stuff the rest. To sit down and have some lo mein and talk about his epic journey to find an epic poem about an epic journey. In other words, to live. "It's cold, but you can heat it up," Oliver said, turning back to the television screen just long enough to confirm that his show wasn't back on yet. • • • Jacob carried the book everywhere: under his arm up and down the Stamford antiques district as he and Oliver searched for new light fixtures; on the seat beside him on the bus, underlining passages during red lights; just inside his duffel bag with an Attic Greek dictionary so that he could retranslate stanzas late at night in the common room. He worked on it so obsessively that he nearly forgot that he had promised to fly home to see his parents for his birthday the week before Ella would be leaving. He'd have missed the flight entirely if Oliver hadn't noticed it on the schedule—months ago Oliver had requested that Friday off so that he could catch a less crowded midday flight and get down to Florida before night fell. (His parents now refused to drive after dark.) "I need a day off anyway," Oliver said. "Let me drive you to the airport." Jacob didn't need to pack. They kept a drawer full of warm weather clothes for him down there, and his mother always had a new toothbrush waiting in the holder in the guest bathroom. So he carried the book with him out to Oliver's truck, slid in beside it, and immediately resumed underlining. After several weeks he was still only on Book 15, where the goddess Athena is urging Odysseus's son, Telemachus, to hurry home before his mother, Penelope, weds one of her many suitors, and there were still _nine_ books, plus a lot of conclusions he meant to draw at the end. If he was going to get it to Ella before she left Anchorage House, he'd have to really dig deep. "It's good to see you studying again," Oliver commented as they drove over the Whitestone Bridge. Out the passenger-side window, Jacob could see Queens rising up across the river, and somewhere beyond it, he knew, was Manhattan. His old apartment and his old notes and his old life, all waiting there for him to return. "Are you thinking about going back for your doctorate?" "Is there something like art therapy but with poetry and books? Is that a thing?" It had been some time since he'd seen Oliver look pleasantly surprised. "Bibliotherapy! Yes, there have been some good articles written about it. I could pull a few together for you if you'd like." "Thanks. I've been thinking I'd like to try it." "You mean start therapy?" He actually shouted this, utterly delighted, as if he'd been waiting ages for Jacob to say it. Annoyed, Jacob explained, "No, I want to _give_ therapy. I mean, I minored in psychology. I think I'd be good at it. If Sissy Coltrane can do it, I can too." They rolled on past the _New York Times_ building, and soon Jacob could just spot the remnants of the old World's Fair. "Sissy has a certification in art therapy," Oliver said after a while. Jacob snorted. "What Sissy has is an alpaca muumuu and a sense of entitlement." Oliver groaned. "This is about Ella Yorke, isn't it?" Jacob didn't answer but went back to annotating the book until soon they were winding along the terminals of Kennedy Airport, heading for Delta. When they finally got to the curb where all the bag handlers were waiting, Oliver forced a smile. "Well," he said, handing Jacob a small silver case, "if you want to get certified in bibliotherapy, I think it'd be brilliant. But in the meantime, maybe you can use these." Inside the silver case were twenty or thirty business cards that in gilt letters read, JACOB BLAUMANN. MASTER AND COMMANDER OF POETRY. SPECIALIZING IN EPIC WORKS _._ Jacob turned one over in his hands once or twice and then slid the case into his breast pocket. They were beautiful. "These are perfect," he said. "Oliver, really. Thank you." He couldn't think of the last time he'd bought Oliver a present, and certainly not out of the blue, and he considered apologizing until he realized that Oliver was trying to segue into something else. "Jacob," he began, "I understand how rough this past year's been on you, but honestly, we might need to face the fact that this isn't . . . I mean perhaps we ought to—" But Jacob hurriedly kissed him on the lips and pushed the side door open. Once he was out, he tried to close the door, only it got stuck, and he had to stop and open it again. "It's jammed on the seat belt there," Oliver said. "I can see that." "Just push it back inside." "I'm—" He bit his tongue and knocked the belt back inside. Then he closed the door again and waved goodbye. Oliver drove the truck off past the police officers, who were directing everyone away. The door was still wobbling. Way down near the very end of the lane, he watched as Oliver stopped, got out, came around, and with a firm hand this time, convinced the door to stay shut. Jacob kept notating while he was standing in the security line. When the time came, he placed the book into the little gray bucket, set the notepad on top, and sent it off into the X-ray machine. The business card case he placed, with his keys, belt, three pens, shoes, and cell phone, in a separate bucket. "Excuse me, sir?" the security guard asked him on the other side, as he reassembled himself. The guard looked at the book and thumbed through the notepad at the scribbled foreign lettering and sketched boat diagrams and maps of routes, as if they might contain secret codes or be some kind of blueprint for a bomb. "Is this everything?" "Yes," Jacob affirmed. "This is all I have." Progress. One whole book finished between boarding and taxiing, and Telemachus and his father were reunited at last, but then about an hour into the plane ride, the pen that Jacob was using to mark up the book began to leak. Cursing, he tried to mop up the spill with the back side of one of Oliver's business cards. "Do you need to borrow a pen?" asked the woman next to him. Jacob looked at her for the first time since she'd sat down beside him. With long red nails, she dog-eared her place in _Heaven Exists!_ , a book about a boy who allegedly died, went to heaven, and returned to report about it. Jacob thanked the lady for the offer. She fished in her purse a moment, until she pulled out a ballpoint BIC. "Oh," he said, hesitating, "it's blue." "Sorry?" "It's a blue pen. I've been writing all my notes in black. Does that sound crazy?" The woman didn't say but looked a little nervous as she tucked her pen back away. "How is that?" Jacob asked, thumbing toward her book. She made an unmistakable _eh_ face before asking, "What's that about?" "This jerk who gets lost at sea for thirty years." "Do you have a big test on it coming up?" she pointed to his notebook, which Jacob then covered slightly with his hand. "No. It's a gift for someone." "Lucky someone," the woman said. Jacob went back to his work. By alternating his leaky pens every five minutes, and mopping up the ink spills in between with the backs of the business cards, he made it through the rest of the section just before the wheels touched down in Tampa. ### SEPTEMBER He hardly recognized his parents. It was like _Close Encounters_ down there in Tampa, as if aliens had abducted the weary, grumpy people who had raised him, leaving behind these revitalized, reprogrammed retirees. His father and mother had once sleepwalked through the first half of the day. Now they woke up every morning at five a.m. and ran three miles together. They split a grapefruit for breakfast, and to cool down they swam laps. And they weren't alone. The predawn world of Tampa was alive with octogenarians in DayGlo tracksuits, power walking down the little fake streets. Their retirement community was twenty acres lost in time, polished Cadillacs and Oldsmobiles parked in every driveway. Men wearing hats. Women stopping to chat on the corner. In the afternoons his father had tennis lessons with a coach who had formerly trained Tennessee teens for the pro circuit. "He's got trophies in a case in his living room," Jacob's mother exclaimed when he joined her for a cucumber peel in the spa. "He thinks he's Mr. Big Shot." His mother had befriended a woman named Lydia in the condo next to theirs, who had been a chef in Chicago for many years and was now showing his mother how to make cheese soufflés and teaching her about wine. "We're taking a trip out to the Loire Valley next year. Have you ever been to a real vineyard before?" Jacob found himself saying he hadn't, already mourning a whole childhood of nonexistent soufflés. Weirdest yet was how they'd both become more Jewish. They'd stopped going to synagogue when he was a kid, thanks to Gene Blaumann's compulsion to debate the rabbi every Shabbat before they'd even consecrated the challah. When you were too argumentative for Westchester Jews, you were in pathological territory. But now Gene Blaumann was going to Saturday-morning services? His mother was involved in an outreach program, focused on what she called the "next generation crisis." The problem was no longer that good Jewish boys (like Gene Blaumann) married shiksa women but that even children of two natural-born Jews were less often devout, to the extent that fewer and fewer were bar or bat mitzvahed. "Better not let them meet your gay son then," Jacob said. But his mother shook her head. "Oh, who cares? They all watch _Will and Grace_ now. Nobody cares you're gay. Just do me a favor and tell them you go to services for Shabbat." Fortunately between the exercising, the culinary lessons, the services, and the card games, his parents were almost too busy to notice he was there. He indexed _The Odyssey_ by the pool most of the day before they dragged him out to Amici's, the local Italian place that "everybody" went to, for dinner. Nobody was interested in his complaint that it seemed ludicrous to use an English possessive with a plural Italian noun. "We got you an iPhone," his father said as antipasto came. "Give it to him, Anjelica." His mother dropped her knife on the fried artichoke. "Let him open it and find out!" "What's the surprise?" his dad said. "That's what everybody gets now. Coach told me the 3GS is really good. I got one for me too." And before Jacob's very eyes, his own father produced an iPhone from his pocket. "You can put all your songs on here. Books too! Don't have to lug that huge thing around with you all the time. You're going to mess up your back. Take it from me." Jacob clutched the book on the bench beside him as if it were a life vest and Amici's Family Restaurant were about to get hit with a tidal wave. "Thanks so much," he said, taking the gift without unwrapping it. "And you can get Facebook on it too," his mother said. "Are you on Facebook?" "No, I am not on Facebook. Tell me you aren't." "Oh, you have to see. Gene, show him how you put all your people in it." And Jacob watched as his father held the phone up over the bowl of calamari and scrolled, slowly, through a list of contacts with his thumb. Jacob watched as his mother craned her neck to see who was coming into the restaurant and if it was anyone she needed to wave at. Maybe they were still his parents after all. "So are you meeting any nice men up there?" she asked. Not that Jacob was going to answer, but for fear that he might, his father quickly changed the subject. "Why don't you quit that stupid job and call Phil Jalasko's son at Sony Records? Poetry's kind of like music, and I bet you they could use someone smart like you to fix up some of those lyrics. 'You and me could write a bad romance'—is that English?" "Please tell me you don't have Lady Gaga on that thing." His father sighed and mashed some buttons. "Phil's son put some stuff on there. I don't—I can't tell how to take things off." "Here," Jacob said, "let me show you." The next morning they drove him back to the airport and dropped him off at the curb, his father waving his phone in the air, smiling, and his mother crying as she did every time they did this. "When you get there, if you don't mind, just let us know you made it, all right?" she asked as she hugged him by the curb. Begrudgingly, Jacob had to admit that it was somewhat pleasant to listen to _West Side Story_ and Fleetwood Mac's _Rumours_ over and over again on the flight back (the only two withstandable CDs of his mother's that he could find). And with a fresh set of pens and a pack of Kleenex, he managed to get all the way through Book 24 before they touched down in New York. That night, after Oliver fell asleep watching another nature program, Jacob got up and finished the concluding notes in the study. He worked all night without sleeping, and during the ride to Anchorage House, he read and reread the notes. It was the hardest he'd worked on anything since _Shitstorm,_ and he wasn't even a little sad to be giving it away. That morning, before the wake-up rounds began, Jacob slipped the annotated copy of _The_ _Odyssey_ onto the bookshelf in Ward III. By lunchtime, it was gone. As he patrolled the outer hallway, he saw Ella in the cafeteria in deep-reading mode. Maura's chatter from the other end of the table wasn't causing even the slightest distraction. Ella's eyes flew between the book and the notebook. In Feingold's group, everything about her demeanor suggested that she was no longer present, besides bodily, in this universe. And as Sissy tried to get everyone to make hand puppets out of paper bags that afternoon, Ella glued on eyes and ribbons idly, her smile stretching and collapsing like the bellows of an accordion playing inaudible notes. At last, in the afternoon Jacob had the chance to talk with her briefly in the common room. Paul was watching, he could tell, and so were Dr. Dorothy and Dr. Wilkens, from where they were conferencing next door, but Jacob had no reason left to care. Whatever happened, this thing was hers. Ella clutched the book as if it might run away. "You did this?" "That?" Jacob looked carefully. "Appears to be the work of a fellow named 'Ho-mer.'" Ella looked at the ceiling, as if the right words might be up there. "Well. Thank you. I mean. I don't know how to thank you." "You did already. Just before there . . . when you said 'thank you.'" She got a look as if contemplating many, many things that she couldn't possibly find the time to say. At last she settled on "Okay, this time you have to explain though. Why?" "Just something to take with you when you go." "No, I mean, why _this_ book? Not that I'm—not that I don't love it. I _love_ it." Jacob wanted to tell her that it was something he'd needed to reclaim; something someone else hadn't been able to finish; a journey he'd needed to take, vicariously. He wished there was time to sit and explain it all. But she was due to be picked up just after his shift. "A while ago I saw your mug in the art room. You wrote 'Odysseus' around the rim." "Uh, yeah. In _Greek,_ " Ella said. She could hardly keep from laughing. "My boyfriend—" She had to try again. "My ex. I don't know what he is. Anyway, his middle name is Ulysses." Jacob felt himself blush and wondered if this was the guy he'd seen in her prom photos. "Ulysses? What, is he from Brooklyn or something?" She danced backward a little. "No, his parents are big Civil War nuts. They do those re-creations and things? He _hates_ it. But I always thought it was kind of sweet. I was going to get it tattooed on my wrist. Anyway, I learned to write it in Greek like that so nobody would figure it out." Then, moving up onto the window ledge for a moment, she lowered her voice. "We were still dating the first time I was here, and I was kind of obsessed, talking about him all the time and doing stupid stuff like weaving his initials into these Native American dream catchers that Sissy was having us make. She told me I had to knock it off. Said it wasn't healthy." He was sure his face was red now. "Sorry. I guess I thought it was your favorite book." "Well. It is now," she said. Jacob, who hadn't been nervous talking to a girl since around the third grade, found himself at a loss. "You always looked as if you were trying so hard at everything here. You're a smart kid, and you're going to do great things with your life, and I guess it sucks that it's always going to be a little harder for you than for other people, and you'll have to stay on your medication, and sometimes you're still going to see a homeless guy on the street or something and it's going to break your heart, and you'll want to crawl under a rock somewhere and hide everything good that you've got to offer from the world because it's going to seem like the world doesn't deserve it, but I promise it does—" Jacob was talking so fast and gesticulating so wildly that he was running out of breath. Paul was staring at him now like he had three ears. He was glad that he couldn't see Dr. Dorothy out in the hallway, and he hoped she couldn't see him. His lungs felt like rocks in his chest, and it was as if a great swarm of bees were building a honeycombed hive inside his skull. He felt the whole room wobble like the door to Oliver's pickup truck, and then Ella was grabbing something—it looked like a paper bag for him to breathe into. He snatched it and held it up to his mouth, forcing out a deep breath that inflated the bag before either of them realized that it was, in fact, her hand-puppet from art therapy. Its googly eyes rattled as he inhaled, and the green pom-pom that had been its nose fell silently onto the rug. Ella laughed first—a shocked and delighted giggle that she seemed unable to settle—and as Jacob mimed a little defensive stamping on the offending clown-puppet, that set her off even more. The other patients were all cracking up, and in a moment he felt Dr. Wilkens's hand on his shoulder, coaxing him to head over to the nurse to get checked out. Jacob tried to say he was fine, but it didn't come out. He gave Ella a farewell salute, and she clutched the book to her chest again, mouthing the words _thank you_ as he took shaky steps, backward, out of the room. After getting a little orange juice into his system, the nurse said she thought he'd be all right, but Oliver sent him home early just to be sure. It was only as he rode the bus back that he remembered the other thing he'd meant to write in the front of the book—that he'd signed up for Facebook, using his new phone. But in his haste to leave he'd left it in his locker. He thought, maybe in the morning, then, he'd send her an invitation, so they could be friends. Sometime later that night, with no book to annotate, cold ginger beef in a takeout container at the foot of the bed, and more hilarity on the television, Jacob decided he'd wait another day or two. Tomorrow he'd get up and go through those gates again to Anchorage House. And she'd be off in her real life, and maybe it was all just better if he left it that way. ### OCTOBER October arrived, and with it the golden leaves around Anchorage House began to fall into the duck pond where Jacob, once again, resumed his daily vigil. Under the willow tree he would stand and think about what he'd said to Irene in the hospital, her smile, their conversation the night before about Hector, and the way Irene had felt in his arms when he carried her down the steps of the Met. He thought about the way she'd bent down before the pyramid walls and how she'd looked standing in front of the painted field of poppies. He remembered her on Shelter Island and how, out of everyone, she'd told him last because she'd known that of all of them, he was the one it would break. He'd always thought that being a cynic would prepare him for something like this, but she'd known that only made it worse, because it made you think you wouldn't care, and yet of course you would. He thought even further back, to the way she'd looked in the hot tub that night on the roof of the Waldorf Astoria, opaque bra against the snow-blown skyline of Manhattan. He hadn't gone to her wake, wasn't planning on going to see the show Sara was organizing, of all the things Irene had been working on that year—not because she'd wasted herself on them but because he didn't see how any of them could be more powerful than her simple being. Jacob waited for the old routines at Anchorage House to resume their comfort, but week after week he found no trace of the numbness he'd known before Ella. There were more hellos at Oliver's office door and the same old snide remarks from Paul, this time about the new behavioral therapist—Dr. Patricia Cain, whose bosom seemed to occupy Paul's every waking thought. Jacob was ready to find him a pacifier to suck on. About the only real change was with Sissy Coltrane. She'd gone from being oddly friendly around him to being downright chummy—acting as if they were old buddies, asking if he was thinking about getting some different job soon. At the height of it, she even handed him an assortment of brochures to continuing education programs that she claimed to have stumbled upon one day in a public library somewhere. The programs ranged from nursing to publishing to information technology. "Oliver told me you were thinking about going back to school. You know, I just feel like you can't ever underestimate the value of a nice change. I lived out in the Midwest for a while after college. I worked on a ranch. Can you believe it?" "I can, actually, believe that," Jacob said. "You'd love it." "I wouldn't." "Oh, come on," she said. "Just think about the poetry you could write in the mountains, the prairies. You know there are still places in this country that no human feet have ever touched? I miss the horses. Fishing in an icy stream on a summer's day, blackbirds and locusts and all that. I'm telling you, the poems will practically write themselves." Jacob gagged. "That's good, because I sure wouldn't want to write them." Instead of getting annoyed, she slapped his shoulder, as if this were just typical Jacob. It _was_ , but there wasn't any typical anything between them, so why would she be acting like it? "Where _would_ you go, if you could go anywhere?" she asked. After a little thought he said, "Think I'd really like to be a goatherd." "Brilliant!" Sissy clapped her hands as if he'd correctly identified a shape in a kindergartner's lineup. "I'd live way up on the side of a mountain with a long winding path down to the bottom. There'd be a river there, full of nymphs and woods nearby haunted by panpipes. And people from the town on the other side of the valley would cross the river and hike up the path and buy my goats whenever they needed to make sacrifices to the gods. I'd be known, mountain-wide, for having the best goats for currying godly favor." He could tell Sissy was mentally fitting him for a straitjacket. He just didn't care. "And there'd be this little cave on the far side of the mountain, at the right edge of the known world, where some horrific monster was rumored to dwell. The kind that spits acid and devours children whole. And anytime something went wrong, we'd all blame it on the monster. Bad weather, dead crops, sick relatives. Can you imagine? If evil was just this thing that lived down the road? Not some North Korean Napoleon or Afghani fundamentalist fanatic. Not some—some all-pervading uneasiness. Not some malignant cell on a mission. Imagine if you could point to a spot on a map and say, _There—that's where bad things come from._ " The phone rang on Sissy's desk. Dropping her pencils in a pile onto the table, she swooshed over to pick it up. "Sissy Coltrane? . . . Oh _hi,_ Oliver! You're— . . . Oh yes, he's here. Would you like me to send him over? . . . Oh. Sure. All right. Okay, bye now! Talk to you later." "Whither shall I wander?" Jacob asked, raising his arms to the ceiling. "He says you've got a surprise visitor waiting out by the gates!" Jacob felt the sudden weightlessness, the vanishing of all walls and floors and tables, the fresh new world of the top deck of a cruise liner. Had Ella really come back to visit him? Wasting no time at all, he charged back to his locker, threw his jacket on over his work clothes, and marched outside and down the gravel driveway. A little green Prius was idling on the other side, its driver half hidden behind an enormous and fashionable pair of rounded orange sunglasses, hair trimmed short. He wondered what Ella could be saying to Winston that was cracking him up so much that he could hear him laughing all the way up by the old, disused, and slouching stables. But then she whipped the sunglasses off and Jacob saw her face. It was Sara. He'd never seen her behind the wheel of a car before—back in college, George had driven them everywhere in his old beat-up station wagon. Now he recognized the haircut, and the glasses, from the Facebook photos of her and George at fancy cocktail gatherings in Boston, at the mahogany Harvard Faculty Club, at Tresca in the North End, in _The New Bostonian_ 's corporate suite at Fenway Park. Wishing the nuns had thought to dig a moat around the place, he waved as Winston opened the gates so Sara could drive in. She jumped out of the puttering car and ran to him—some feat in the cream-colored heels she was wearing. Mud splashed all over the old-lace bows on the toes as she tackled him in a slender-armed bear hug. He remembered the shoes had been Irene's once—she'd blown almost two hundred dollars on them at Mel's. "Jacob!" she shouted, melting into his shoulders as she hugged him. Then, straightening herself up, she pulled a gold-embossed envelope from an orange ostrich-skin handbag that matched her sunglasses. "So _this_ is where you work? Wait. I have to move my car before this nice man gets in trouble." He followed her back to the green Prius and climbed in. He was about to ask what she was doing here when she threw the gear into reverse. A black-and-white screen flickered on in the dashboard to show that the driveway behind them was clear, and a sensor went off when she got too close to one of the brick walls as she K-turned around. "Um, my shift isn't over for another hour, crazy." Sara flashed her eyes at him mischievously. "You're being kidnapped! I'm sorry, but it was the only way. This morning I called Oliver, and he agreed wholeheartedly that you needed to be taken down to the city for a belated birthday bacchanal." "He said that?" "Well, no, he said you'd become a 'first-class mope,' and I said you always _were_ a first-class mope but that if you'd recently reached platinum mope status, something had to be done." They were speeding down the street toward the southbound Hutchinson River Parkway. Jacob knew that the more he resisted, the more Sara would insist. "Could we make a quick stop at Oliver's? I'm still in my uniform." Sara appeared delighted. "I get to see the _flat_?" It took Jacob a moment to remember that he had told Irene all about "the flat" last year and that, as with everything in their circle, it had soon been repeated. "How would you like to see _the_ Szechuan Garden?" Even after all this time, he knew her far too well. Before long they were seated across from each other in his usual spot, just back from the side window. Jacob had changed his clothes at Oliver's and now looked "dashing" according to Sara, in a blue striped shirt and dark wool pants. As they had their first round of Tsingtaos, she outlined the epic evening that she had planned for them: they were to eat nothing _too_ filling here at the old Szechuan Garden, because she had a seven-thirty appointment with a caterer at Seventeen Madison, which meant they'd feast on free samples of passed hors d'oeuvres (including the chef's famous pickled radishes), minted lamb lollipops, rock shrimp served on Himalayan salt blocks, and of course the signature sirloin Sriracha sliders. After that there would be a cake tasting at Happy Puppy Wonder Cakes, down in SoHo, which had _the_ best lavender buttercream frosting and the infamous "crack" cookie pie filling that had been deemed the "city's crackiest" by _New York_ magazine that summer. After that, dancing was possible, depending on the crowd at Niagara, to be followed by drinks at an Oscar Wilde–themed speakeasy called Dorian Gray's, which was "secretly" located behind a full-length portrait of a French cavalier in an otherwise excellent _crêperie_ on Allen Street. You had to pull on one of the light fixtures next to the painting and then tell the painting how many in your party, and if there was room, the picture would slide over to let you in. If not, you wrote your cell-phone number on a piece of paper and slipped it through a small crack in the wall, and someone would text you when there was a booth available. Jacob didn't know where to begin: perhaps that there'd never been prohibition on alcohol in Ireland, where Oscar Wilde had been born, or in London or France where he'd later lived, and that he'd died more than twenty years before there was any need for speakeasies here in America. But he listened to Sara gush about these places she'd been _dying_ to go ever since leaving the city. It was as if nothing had changed for her. She thought she could walk back in, and it would all be the same. She told him he was welcome to crash that night in her hotel room, where George would meet them in the morning. Jacob didn't see the point in arguing, seeing as he had absolutely no intention of doing any of this. They were on their second round of Tsingtaos, and it wasn't quite five o'clock. He'd never seen Sara have more than three before needing to curl up and take a nap somewhere. Already he was planning on persuading her to come back to Oliver's. He found himself only half listening to her as she spoke. Scarlet leaves scattered as the bus rolled up and sighed to a stop outside the window. Needlessly, he ran his eyes down the familiar columns of misspelled food items and pointed out his favorites to Sara. She reached across the table and took his hand in hers. "I'm so glad to see you're okay, Jake. We've all been worried about you." Her eyes were red underneath heavier-than-usual mascara. _We all?_ Who did she mean, besides herself and George? Was she still talking to William, even? He thought about telling her that he'd nearly driven up last month, after Oliver's dad died, but instead he asked, "How is Georgina doing?" She let her eyelids flutter shut as if she couldn't bear to look at him as she said it. "He's hanging in there. He's—you know. I think of all of us, he was probably the least ready for what happened." Jacob paused, surprised to hear her say this. "He's been distracted," she concluded, and began braiding the wrapper from her chopsticks, tapping her toe on the linoleum, looking about four inches from him when she spoke. Unlike George, as Sara got more anxious, she drank less. _Happy families are all alike; every unhappy family is unhappy in its own way._ Damn, that was a good line. He had never liked it before, mainly because he felt that his own family was unhappy in a generic kind of way. But Gene and Anjelica Blaumann weren't his only family. Now it seemed undeniable to him that, whereas his New York family had indeed been happy in the way that all groups of young dreamers are happy before they've given up, they were all quite unhappy now, each in their own special ways. That was what made it all the more miserable: they couldn't even be unhappy together. "Speaking of the wedding!" Sara said abruptly, though they hadn't been speaking of it at all. She dug around in her purse and produced a lovely cream-colored envelope. He read it out loud. "'Mr. Jacob A. Blaumann. Of question mark street. Apartment number question mark. NYC, NY. Question mark, question mark, question mark, question mark, question mark, dash, four more question marks.' " "I take my postal codes very seriously," Sara said. "Open it already!" He did. "'Please save the date of March 20, 2011, for the wedding of'"— he paused and then shouted her name across the room—"'MS. SARA SHERMAN AMPERSAND MR. GEORGE MURPHY'—that's a commendably bold font choice there—'New York, New York. Invitation to follow.' Don't you need to tell people where it is?" Jacob asked, flipping the card over. "Where's the place I check off chicken or fish?" "That comes on the invitation." "This isn't an invitation?" "No, this is a save-the-date card. The invitation comes—well, soon now actually, but I've been trying to get this to you since June." "I've been swamped." "I know. It's hard to—I know it isn't the same. Look. George and I wanted to ask you—we were wondering if you'd read something at the wedding. You pick. Something from _The Bridge_ if you want. Of course, an original Blaumann would be fantastic, but—" Before Jacob could refuse, the little jingle bells on the front door sounded. He glanced around just in time to see Sissy Coltrane walking in, her bony arm hooked around Oliver's. They were laughing and paused to punctuate their happiness with a soft kiss. Even the servers seemed to realize this was awkward, as in midconversation Oliver began strolling directly to his usual table, which was apparently also _their_ usual table, and where Jacob and Sara were already sitting. "Oh! Jacob!" he shouted, loud enough to scare the fish in the tank in the back. "Funny to find you here! Sissy and I were just having a meeting. Sorry. You must be Sara. We spoke on the phone? I thought—I thought you two were heading for a big night out in the city." Jacob watched as deep red shame soaked through the baggy skin of Sissy's cheeks, and she looked as if she wanted to bolt out of Szechuan Garden and the entire state of Connecticut. Oliver did a very nice job of looking vaguely off at the window, as if the situation might disappear if he didn't acknowledge it. Fortunately Sara wasn't as ambivalent. She pulled Jacob to his feet, and they were out the door before anyone realized they were dining and dashing. It was like a scene in a movie—too exciting to be real. Or to be part of _his_ life, at any rate. But the longer he sat there, mute, in the passenger's seat of the Prius, the more sense it made. His secret, older boyfriend had a secret, older girlfriend. Sara, on the other hand, was fuming. She sped down the parkway ranting, like the Jacob of old. _How dare he_ this and _how dare he_ that. Jacob didn't argue. She had a valid point. But what shocked Jacob the most wasn't Sissy's age or gender, or even the fact that Oliver was sleeping with another of his subordinates, but that he'd _dared_ , period. How could someone who only ever ate at one restaurant juggle two love lives at once? Jacob was almost impressed. As the skyscrapers emerged on the horizon, and the city noises grew in his ears, and the world outside the car filled up with people, rushing around with such purpose, Jacob felt like no part of it at all. He couldn't shake the feeling all through the night as Sara dragged him through the streets, outraged and leery the whole time, to the caterer and the cupcakes (they skipped the dancing) and to the speakeasy, where they really did pass through a secret passage to sit at a narrow bar and sip twenty-dollar cocktails made with Carpano Antica and house-made ginger syrup and yellow chartreuse. He let the night happen to him, moving through it all like a ghost. At the end of the night, he stood at the foot of the hotel escalators and kissed Sara goodbye on both cheeks and said he had to get back home. He promised to meet her and George for brunch in the morning, though he already knew he would not go. She promised him it was going to get better, that he didn't need Oliver—and Jacob knew that that was true. He wasn't feeling like this because of Oliver. This was how he'd felt all along, but Oliver, Anchorage House, and even Ella had been distracting him from it. He was absolutely lost. Jacob walked all the way to Columbus Circle. He'd been gone so long, the old MetroCard in his wallet had expired. He bought a new one and went down to the 1 train, waiting at the very end of the platform, trying to get as far as he could from the fiddler and the guy with a washboard who were playing something intolerably cheerful. He closed his eyes and waited to feel the faint breeze—the front end of the gust of wind before the train—the first signal to every real New Yorker that a train was coming, before you could lean out and see the headlights on the tracks or hear any noise at all. He still knew just where to stand to have the doors open right in front of him. When they did, he stepped into the back of the train and for the first time in his life found himself in a car that was completely empty. His heart pounded as he studied the vacant yellow and orange seats. He stood, in the very center, as the doors closed, and he began to fly along beneath the ground. He shut his eyes and tried to feel as if he were weightless, on a new planet, lost in the sound of the tunnels. Instead he felt himself underwater, unable to breathe, as if the car were packed with a thousand people. And then, with no one there to see, Jacob wept for the first time since Irene had died. And he kept weeping, even after he transferred to a 2 train at 72nd Street. Nobody minded much. It wasn't so odd, in the city, to see a grown man crying in the middle of a whole lot of people. He got off at 110th, with the dark void of Central Park at his back, and walked the rest of the way to his old apartment—some thirty blocks through Harlem, lurid and alive, all brassy horns and endless green lights arching above the avenues. Everyone seemed younger than they had been a year ago; everything felt bigger. It was always the same city, only more so, and this was why he'd had to subtract himself from it. He couldn't stand to see it not being less so: the bums and the bridges and the bodegas and the bottles that overflowed the trash cans on the corner. She wasn't there, and it seemed impossible that all this could still be going on. ### NOVEMBER Either Oliver felt guilty enough or Jacob's cold shoulder wore him down, because at the beginning of November the paperwork was completed to have Jacob join the staff part time as an assistant art therapist. This meant he'd work an extra shift per week, which barely helped cover his train ride each day up and back from Harlem, but he didn't mind. Under the auspices of this "special pilot program," he was even able to get permission to walk with patients around the property. He had a budget to buy books (one copy of _The Odyssey_ , which had to be shared) and an hour a week to meet with patients to discuss readings on an individual basis. Maura signed up, and then so did Roy (they were "dating" now, whatever that meant when you were both stuck in a mental institution), and then Jane and Annabeth joined. It was slow going. A lot of them protested the choice of material. Many seemed to be hoping they'd talk about _The Hunger Games,_ but Jacob encouraged them to read slowly and out loud if a passage didn't make sense at first. They discussed history and geography as they hiked around in the crisp, late autumn fog. Around the overgrown foundations of the original manor house, they dissected the Lotus Eaters, and down in the graveyard they went over the cannibalistic Laestrygonians. Under the drip of mossy overgrown trees, Jacob began to recall some of the Gothic creepiness that had appealed to him about this place not so long ago. They walked to the farthest north side of the property, past the stables with the collapsed roof, where they could stand amid the rubble and read from "Nausicaa" while the clean-suited men and women of Discover Card waited for the bus across the highway. Down by the duck pond they watched the Chinese Academy boys soccer team practicing their goal kicks. Jacob and Maura spoke about the Cyclops. "Odysseus is kind of obnoxious," Maura observed. "He manages to get away from Polyphemus and instead of being, I don't know, _grateful_ , he's got to stand on his ship and call him a 'shameless cannibal' and a 'coward.' No wonder the poor thing decides to hurl half a mountain at him. And then Poseidon makes him get lost for another ten years or whatever?" "Hubris," Jacob said. "Arrogance. Pride. Everybody's got a bit of it in them somewhere." Maura looked as if she might prefer to just jump into the duck pond. Jacob had never paid much attention to her before, but she was a sweet kid, shyer than Ella and twice as anxious. "Well, think about it this way," he said. "If Odysseus hadn't been so high on his own superior intelligence, he'd have gotten home to Ithaca in weeks, not years. He wouldn't have lived with the sorceress Circe or seen the land of the dead or bested Scylla and Charybdis. That's half the story, and the better half too. Literature is really just the documentation of human struggling." This seemed to perk her spirits up more than a little. Jacob was happy to be outside, talking about poetry. The ducks hadn't yet flown south, and the boys across the way were running comically in place, cotton socks pulled up to their knees. Thanksgiving was coming up. He couldn't believe it had been a year already. "I wish we still had gods," Maura said eventually. "I've never been very religious myself," Jacob admitted. "No, I mean _gods_ , plural. What I love about this book is that there's all these monsters just sort of going about their evil business. And there are _twelve_ gods running around up there on Mount Olympus, fighting, getting in each other's way, hopping down to mess with the mortals whenever the mood strikes them. It all just makes a lot more sense to me. None of them are all-powerful or all-knowing, not even Zeus. They're constantly getting stuff wrong. It explains all the evil stuff that gets missed, like these monsters on their islands. Makes more sense than there being just this one God up there, supposedly completely understanding everything and _intending_ everything—even, like, plagues and assault rifles and starvation and AIDS and homeless veterans and just plain old sadness." Jacob tried to step in, but Maura wasn't nearly finished. "And, like, everyone seems to think that this must be proof that there is no God. Or that if there ever _was_ a guy up there smiting sinners and sending angels off to grace the faithful, He's packed his bags and headed off for greener pastures. But what if the Greeks had it right, and there are just too _many_ of them. Bumping around up there, trying to get things right and not always doing such a great job—forgetting monsters, getting too drunk, and running off with the wives of other gods, but still coming through with a nice miracle now and then? I think we need _more_ gods. That's what I think. One isn't enough." Jacob clapped. It was a rant he'd be proud to call his own. Maura grinned. "Oh, by the way, I got a letter from Ella last week! She's making the dean's list at school and dating some new guy named Fred. Seems nice, if you like guys named Fred. Everything's going really well. She asked about you." Jacob looked off at the lake. He wondered how a diaper had managed to get in there, and he watched as the bloated, grimy thing floated back and forth in the breeze. "You know, before _The_ _Odyssey_ , before the Trojan War even started, Odysseus didn't want to go?" Maura shook her head. "He didn't want to be a hero or get into a huge war over Helen of Troy, even though he'd sworn an oath to Menelaus that he would. The poor guy just wanted to stay home. So he pretended he'd gone insane, thinking it would get him excused from military service. He ran around plowing his fields, day and night, with salt instead of grain and, I imagine, ranting and raving like a lunatic for any and all to see. And everybody bought it—he almost got away with it. But then Agamemnon came by and decided to test Odysseus to see if he was truly crazy. He put Odysseus's infant son down in the field in front of the plow. He reasoned that if Odysseus were really insane, or _really_ wanted to stay safe at home, he'd plow right over his son. But of course, he didn't." "What a jerk," she said. "The other guy, I mean." "Oh, well. He gets hacked to death later on," Jacob grinned. This didn't seem to comfort her as much as it did him. "My point is that Odysseus knew he had to choose," he said. "He knew that even though the gods favored him, they weren't going to get him out of the jam. He knew he was going to have to stop pretending and get out there and _fight_ , not just because he loved his son but because he had made an oath and was bound to keep it. And so he went off to the longest, bloodiest, most absurd war that had been fought in the history of mankind. And _he_ was the one who cleverly dreamed up the Trojan horse and finally ended it. "If he had never gone—if he had stayed home with his son as any sane man would want to do—well, who knows? For sure, Homer wouldn't have written one book about him, let alone two, and half of Western literature wouldn't have been based on the trials and tribulations of this crafty, arrogant guy and all the good and all the evil he saw. This guy who won a war and spoke to gods. This guy who dined at distant palaces and sailed to corners of the globe that no one had yet set foot on. This guy who crossed over into the land of the dead and returned to tell about it. There wasn't a man alive then who'd seen so much of the world as Odysseus, good and bad, and _that_ is the point. "You've got to entrust yourself to the waves, lash yourself to the mast, pray the gods are on your side, and rely on cunning to survive the rest. The seas are full of forgotten monsters, yes, but they're full of forgotten glories too. And the people who stay home and sit out the war never get to see them. That's what I think, anyway." Maura beamed up at the clouds rolling busily across the wide gray sky. And for a little while, until the November chill won out, they both believed there was a heaven out beyond them where a pantheon of gods and goddesses still did their occasional best to keep tabs on a world that had only gotten larger since everyone in it had stopped believing in them. ### DECEMBER It wasn't clear who found out about Oliver and Sissy. Certainly Jacob hadn't told anyone. But the rumor spread overnight, until everyone had heard the news. Allegedly the board was upset. Sissy was Oliver's direct report, and one or the other of them would have to go. Word was that Sissy was taking this as her chance to leave and go out West, with icy streams in summer and horseflies and grand plateaus and blackbirds and whatnot. Oliver called Jacob into his office that afternoon. He kept the door shut and spoke in whispers, as if he might somehow get in more trouble. "Jacob, I don't know what you've heard, but obviously—" Jacob stood back and raised his arms dramatically. "I'm shocked— _shocked!_ —to find out that there is gambling going on in this establishment." "Is that supposed to be funny?" "It's pretty funny in _Casablanca_ at least," Jacob said. "Look, I don't care if you want to try to be straight. I don't think it's going to work, but hey, I get it. After your father and everything." "Jacob, I don't want to talk about that. I'm trying to—damn it, I'm trying to apologize to you here. I tried for months to make it clear that our relationship just wasn't working." "Hell, Oliver, I knew that." "Then why didn't you just end things with me and move on, if you knew?" Oliver looked as if he might cry. Jacob felt terrible. What a way to treat his gloomy octopus. "I think I was sort of taking the year off. I didn't want to make any decisions I'd regret." Oliver's eyes were wet. "You thought you might regret leaving me?" It sounded a lot sweeter than he'd meant it, but Jacob was willing to let him have it. "It was a dumb idea." Oliver looked out his window. "Sissy has agreed to leave. The board will give her a severance for keeping quiet. She's going to move out to Montana and start a community art program there." Jacob whistled. "Well, if I'd known there were payoffs involved . . . you and I shouldn't have been so discreet." But Oliver wasn't laughing. "She has a daughter. Did you know that? She'll be eleven next month. We get along, she and I. Her name's Virginia. I thought maybe it wasn't too late for me to be a father to her." Jacob snorted. "Trying to take a positive role in a young girl's life? I don't know, Oliver. That sounds unhealthy to me." But Oliver didn't laugh. "You must think I'm a fool." "Look, go with her then. Round up cows with Sissy if that's what you want to do. Nothing's stopping you, Oliver. Really. Nothing." Oliver seemed unconvinced, so Jacob clapped his hands and struck a mock-triumphant pose: "'Therefore, take me and bind me to the crosspiece half way up the mast; bind me as I stand upright, with a bond so fast that I cannot possibly break away, and lash the rope's ends to the mast itself. If I beg and pray you to set me free, then bind me more tightly still.'" Oliver seemed torn between laughing and rolling his eyes. Laughing won out in the end. "You seriously need some help, my love." Jacob shrugged. "I don't want to know anyone who doesn't." They shared one last embrace of the old kind. ### JANUARY The year had passed, and Jacob went to Manhattan and walked into a synagogue. He took a yarmulke from the wicker basket. He put it on his head as he had, as a boy, on countless torturous Friday evenings, which stretched a dotted line back to some of his earliest resentments. He took a prayer book from the woman, and in minutes he was in the back of a big blue chamber, singing along to the same songs his Hebrew school days had tattooed onto his brain stem. The Jews of the Upper West Side were assembled around him—Jacob had expected them all to be old. He was surprised how many people his own age were there, and how many children, some dozing and some stretching and some turned around in their seats to stare at him with their big dinner-plate eyes. And, too, there were old men and ladies who could hardly heave themselves up when the time came to rise. Jacob only mouthed along at first, not sure he wanted to pray, not to this God who'd taken Irene, and who'd taken over for all those other gods. But if once there was a god of the sun and a goddess of harvest and a god of war and a goddess of wisdom, then maybe this Consolidated Entity was still all those many things. Within this One Him, capital-G God, all the lowercase ones still existed. There was still a grim god of the underworld in there, and a tempestuous god of thunder. A sprightly messenger god and a raucous god of wine. Maybe He was still squabbling amongst Himself, still getting drunk and cheating on Himself (with Himself) and messing a thing or two up. So maybe He didn't always wind up rewarding the best or punishing the wickedest. So maybe sometimes He took the wrong ones and let the right ones stay long past their due. Jacob could forgive Him for that. After all, it was a humongous world, and there used to be twelve of Him. Even then it hadn't ever gone smoothly. The rabbi and the cantor stood up in the front of the room and led the congregation in songs written nearly as long ago as the epics of Homer. They stood in front of the lighted closet that held the ark. Jacob remembered how much he liked that—the centrality of this document, the most sacred thing in the building, adorned with gold and readable only read by those who'd mastered the long-forgotten languages. It was what tied them all together. When they read the Mourner's Kaddish and called on those who knew someone who was seriously ill, or who had lost someone in the previous week, a dozen or more people stood up all around the crowd and spoke the names of their departed or their departing. Then the rabbi called out the list of congregants' names who had passed away in that week in years past, and as their loved ones heard the names, they stood for a moment and then sat down again. There were so many. "Are there any names that anyone would like to add?" Jacob stood up, and he wasn't alone. Three people came up on his left and four to his right. He said Irene's name out loud, and the others spoke their names, and the rabbi asked them all to sit down again. Jacob felt scared and warm all over. He was both emptier and more satisfied. More alone and less, as if he'd just said goodbye and hello in the same breath. The service ended, and various board members began making announcements about food drives and outreach programs, and Jacob found himself thinking about an article Ella had recently posted to his Facebook wall. A scientist had a semiridiculous theory that as clay was being shaped on a wheel, it absorbed the sound waves of the people speaking around it, and these vibrations were then trapped within the earth and air and water. And this terrific madman thought he could figure out how to play this record back again, even through ancient ceramic vases and urns, and hear the conversations of people who had been dead and gone and forgotten for _five thousand years_. Perhaps, Jacob thought, the scientist would find a way. He wished there had been a potter making a vase in Irene's hospital room, so the vibrations of his last words to her would have been caught in its wet clay, and that this scientist someday would queue up his machines and point them at the little vase. Years from now someone else would hear him whispering the words that had made Irene smile in that last minute. _When you get there, just let me know you made it, all right?_ ## WILLIAM ON THE BRIDGE ### 1 Exiting the gallery doors, William saw the Brooklyn Bridge: two mammoth trunks straddling the East River, water blacker than the sky above. Over the surface a second, silver river of reflected light flowed the opposite way. Pale yellow headlights crossed the bridge's span, departing Manhattan at the end of a long, cold Tuesday, while Brooklyn issued her own red taillights back against the tide. From where he stood, they were all just little points of light, proceeding and receding toward friends, meals, televisions, sins, solitude, sleep. The bridge appeared to dwarf the skyscrapers on the far shore. Aortal and ventral, a pair of vaulting, twinned cathedral arches, roped together by a drape of cables. Slow troughs and sharp peaks, like a heartbeat on a monitor. True, William didn't know much about architecture, couldn't tell a keystone from a cornerstone. But he knew it was extraordinary. Particularly after what he'd seen inside the gallery, and after having just finished the second half of a joint he'd begun before arriving. Particularly with the little piece of Irene he now carried in his jacket pocket. After a year in her wake, he felt her close again, hovering over his shoulder, two or three steps behind. Everything was louder and brighter, as if some knob on his dashboard had been cranked up after countless months on low. Living back at home, in his same old bedroom, smoking in the same old bathroom with the same old shower on, having the same old dinners and listening to his parents have the same old arguments. But now all the lights burned brighter, and he loosened his favorite red scarf, despite the chill in the air. Hearing a sudden whoosh, William wheeled around to see a passing tour bus. The sightseers leaned over the railing to photograph the bridge, their flashes firing off uselessly in the dark, the glowing of their phone screens glowing back onto their smiling faces. He was glad to have someone to share the moment with, but even after the bus rolled away, he didn't feel alone. Who was out there? Sara and George and everyone else were still at the opening. _Irene Richmond: The Disappointments_. It was an awful title—she had never decided on one herself. But no matter. _BOMB_ and _Artforum_ were calling it one of the biggest shows of 2011 (even though it was only February), and thanks to them it was a mob scene. Juliette and Abeba had organized it with Sara, who was treating it like a rehearsal for the upcoming wedding. The same lighting designers, the same printer for the programs, the same caterers, who were now bringing around chocolate mousse served in marzipan-speckled eggs. Special Ethiopian coffee had been roasted. George had selected five North Fork wines. The soon-to-be-married couple were the only people William had really known inside, and they were circling around like guppies, too quick to be caught. George was asking everyone if they'd seen Jacob, unclear if he was simply late (as always) or not showing up. The ironic thing was that William had actually mistaken George for Jacob at first. He didn't look well. Heavier set, hairline receding. All the wedding planning, George had joked, fully aware of the looks he was getting. Sara, too, looked altered. Impatient. Missing twenty pounds she hadn't needed to lose in the first place. Everyone was giving toasts and making a big show of looking at the show. William didn't see anyone else looking as he was looking. For the past two hours, he had religiously documented every sculpture, painting, and sketch, using his phone to record every inch from every angle. Already private dealers were bidding through back channels (or so Juliette and Abeba claimed). By week's end, the pieces would be dispersed across America, maybe the world. Stationed in collectors' foyers and bedrooms and on mantels above fireplaces. Tying rooms together. Creating atmosphere. Disappointment everywhere! The proceeds were going to the Richmond Memorial Fund—an art school scholarship that Sara had organized. (Never mind that Irene had gotten her education gratis, sitting in the backs of lecture halls.) She was talking about getting into nonprofit work full time if this got enough attention from the right sorts of people. Certainly there had been a few photographers, snapping away. William had deliberately avoided their flashes and, once he could, ducked away before Sara or George could introduce him to anyone. They hadn't spoken to him more than a few times all year, and he was surprised to have even gotten an invitation to the show. When he'd called Sara to accept, she'd acted as if they'd always been old friends, but he knew they hadn't been and soon wouldn't be again. Quietly he was editing himself out of their story. He hated everything about it. He hated that Irene wasn't at her own show. He hated that he kept thinking she was around the party somewhere, trying to pretend she wasn't nervous about the coming reviews. Certainly there was buzz—possibly too much. Abeba seemed to fear there could be a backlash because people tended to think anything they'd been hearing a lot about was overrated. Better to be the underdog, to be plucked from obscurity. No, Juliette argued, because then why had you been so plucked and not them? They'd hate you worse for that. It was all a big catch-22. No way to win. Sell too little, and nobody cared. Sell too much, and you were a sellout. Unless you made selling out part of your shtick. But it didn't really matter, William supposed. Irene's show was a one-shot affair. First and last. By a dead girl, about dying. It was both unusual and confusing, two things that typically sent buyers reaching for checkbooks. But William didn't care about that. As far as he was concerned, the work was perfect in and of itself. Who else could have come up with something like _Patient R5691414510_? Irene's last known sculpture, a life-sized effigy constructed out of the clear plastic bags the hospital gave out to hold personal items. Irene had entrusted the assembly instructions and sketches (all scribbled down during her last good days at Mount Sinai) to Sara, along with an inventory of the parts she had piled up under her red coat in that tiny closet, so that the cleaning staff wouldn't discard them: bags stuffed with used gauze from her surgical dressings, tissues covered in other unidentifiable fluids, empty IV bags, balled-up pamphlets that the nurses left behind to advise on wound care and whatnot. She'd even salvaged an old PEG tube, and there it was in the gallery, running right into the "torso" and off toward an IV stand that Juliette and Abeba had set up alongside the piece. (The bag had been filled with neon-pink acrylic paint, meant to resemble a strawberry-flavored Assure milkshake.) By Irene's instructions, Juliette and Abeba had suspended _Patient R5691414510_ in the air with a series of clear fishing wires, so that she appeared to be levitating or maybe lying in an invisible hospital bed, her left arm dangling off the side, with Irene's actual patient ID bracelet delicately looped around the "wrist" of an inflated rubber glove. Abeba was running around telling everyone what a challenge it had all been to preserve, and the headaches Irene had caused them all with the permits needed to present these potentially unsanitary items in public. William wondered who the new assistant was, who'd _actually_ had to deal with all that, as Irene once had. The real purpose of the little narrative was, of course, all about stirring up some controversy and tacking another zero onto the price tag. Irene had never cared about that, and neither would he. What he cared about was that she'd made a dozen intricate pieces in the year following the diagnosis. It was remarkable what she'd been able to do with the little she'd had on hand. Sculptures made out of glued-together orange prescription bottles and empty Assure bottles and Chinese food containers studded with little colored pills. There were several sketches she'd done after moving in with William, when she didn't have access to her supplies. _Stricken City II_ was the view out of his old apartment's window, done in sumptuous simple charcoal. As in briquettes from a bag in his hall closet. "Stark and serene," the critic at _BOMB_ had written. The _Times_ had preferred the three-dimensional _Portrait of a Profound Disappointment_ —fashioned from chicken drumsticks (courtesy of Hill Country delivery), which Irene had Mod Podged and which did look eerily human when draped in a tweed that was clearly meant to resemble Jacob's coat, though it was actually fabric taken from an old hat of William's that he had only just then realized was missing. _Artforum_ had deemed it "hauntingly decayed" and complimented the "blooms of rich, saturated pigments" in _West of Eden,_ with its unreal landscape of seashells and vineyards and trash. Someone at _Salon_ had felt this piece was "anodyne and dogged" and that the whole show was a "sheer visual confusion" full of "mundane flotsam and jetsam," which was "erratic to the point of solipsism." To each their own, he thought. William remembered how Irene and her friends had made fun of the "so-called art" at the Christmas party the night they met. He wondered if, to someone else, the moldy yam had meant as much as all this did to him. Maybe. But he wanted to believe that there was something here that would carry these feckless people inside Irene's heart and guts. That it would be—how had Jacob put it?—metamorphic. Not just fucking television. There was a crowd around _Ms. Daphne_ , a painting of a transvestite reclining on a waterbed _à la_ Modigliani, with startlingly hideous wallpaper in the background. This hung beside _Man in Crooked Necktie, _a portrait of George in a suit, holding a vanilla cupcake in one hand. And of course William recognized his Christmas gift to her (formerly his own Christmas gift to his mother), now unraveled and carefully molded into the stunning _Kimono Cocoon_. Certainly the most popular piece in the show was the I-beam from the World Trade Center. _The Iron Queen_. She had done nothing whatsoever to the steel itself, leaving every bit of rust and dirt that had accumulated along its length, but through some alchemy William didn't quite understand, she had affixed seventy-seven nude Barbie dolls to it. Beige plastic crawled, climbed, and sprawled all across the girder, in places so twisted up on top of one another that you could barely see the metal underneath. Something about seeing that same, painted-on smile over and over was tremendously unsettling. From certain angles William thought it was some kind of Elysian orgy. From others it seemed like a hellscape worthy of Hieronymus Bosch. This had been, apparently, the piece that she'd been sneaking off to work on at the gallery right up to her collapse at the museum last summer. As far as he, or anyone, seemed to be able to tell, it was finished. Every strand of fake hair harmoniously and horribly in place. William kept thinking about that last day. The day before the end. She had been pretty drugged-up. But she had asked about the birdcage. And she had tried to say something else after that, but it hadn't been clear—these, her last words to him. He told himself that they had just been nonsense, pointless pain-killer koans. But he couldn't shake the thought that maybe she had been asking him to do something for her. He wasn't sure at first, but the more he'd thought about it, he was convinced that she'd said the words "Tell my father." William had been thinking of how to find him, and now he had finally come up with an idea. William looked up as Sara called the crowd over to _Patient R5691414510_ so that she and Juliette and Abeba could thank them all for coming. He had quietly headed the other way, toward the "piece" that he had been eyeing all night. _Jewelry Box, Bird Cage_. It was hanging in the corner exactly as it had hung in Irene's apartment. Had she intended it to be sold as a piece of art? Unclear, and possibly irrelevant. As Sara began to retell a story about meeting Irene while they'd been interns at the university press (Sara had been charged with finding out if Irene was stealing toner—she was), William got up on his tiptoes and reached his slender fingers toward the thin bars of the birdcage. This time he found the hidden door that he'd seen Irene open to retrieve a necklace before leaving for William's apartment. He opened the cage and grabbed the little black address book that he'd first seen there more than two years earlier. Then he'd shoved it into his breast pocket and stepped out into the night, where, after lighting the other half of the joint, he'd caught sight of the bridge. He knew the fastest way home was on the subway. But instead he trudged up the icy lanes to the foot of the Brooklyn Bridge and thought back to the morning, a year ago, when he'd left Irene's hospital room. Typical William. Early exit. He just couldn't handle the very end. He'd needed to walk up that corridor toward the elevators knowing she was still alive. Out on the street, and later on the bus, he hadn't been sure one way or the other. By the time he got back to his apartment, he reasoned that it was probably over. But he still didn't know. He'd felt so numb and yet not nearly numb enough. That was when he'd dug out the shoebox where she'd been keeping the last half ounce of Northern Lights premium indica that she'd bought from Skeevo. He'd never tried it before, but now he did, in the same careful way she'd taught him to roll it for her. With each hour that passed, he figured the likelihood was a little less that she was still alive. The probability approached zero, but even the next day and the day after, it didn't reach the asymptote. It felt instead like those months when they'd been broken up. Weeks went by, and then months. In the rational gray matter of his brain, William knew she was gone, but there was no convincing the irrational spaces inside it. Little sparks flew from synapse to synapse carrying the words _She Is Dead_ across the gaps that kept insisting _She Is Here_. The pathway over the bridge was steeped in soft tea-brown light. He felt Irene as a gambler feels his luck at a certain seat at the table. The way a sculptor feels something besides her own will moving her hands. It was like seeing out of a second set of eyes and hearing with another pair of ears. Walking a hundred feet above the water, between two worlds that were also one. He didn't know how else to describe it, except to say it felt as if she were walking just behind him. ### 2 At eight the next morning, he stood in front of a glass wall, the smell of fresh bread coming from the bakery behind him. He stared out at the traffic circumnavigating Columbus Circle, from inside the Time Warner Center. He'd spent half the night at a back table at Veselka, studying the address book, where he'd found Skeevo's number scribbled down and had sent him a text message: _Hi, this is William Cho, Irene's friend. We met in Staten Island that day._ To his amazement, there had been a reply after only moments. _Cool. How are you?_ And after a few quick pleasantries they had agreed to meet the following morning at the bakery, where Skeevo was washing dishes part time and learning the mysterious art of bread making. William hadn't seen much point in going home, and he'd been afraid to sleep, for fear he'd wake up and find the feeling had gone. He'd spent the rest of the night wandering around, and it had left him with quite an appetite, so he was glad to see Skeevo bring over a few fresh loaves of something called _pan de horno_ , which was heavenly. "People think it's all about the starters, or the yeast," Skeevo explained. "But just as with a lot of things, there's an art to it. You form a relationship with the dough as you knead it. Too much or too little, and you get flat, dead crap. Not enough air in there. It's a living thing, bread." Steam rose off the bread as William ripped into it. Light glinted off the ever-rising escalator steps. A red sunburst of fabric was being hung in the window of a store across the way. He kept thinking he might see Irene stepping out of the entrance to the Mandarin Oriental Hotel, on the arm of some man in a better suit than he'd ever own. Skeevo wore an ADVENTURE TIME T-shirt, ripped jeans, and a pair of sneakers with silhouettes of Questlove on the tongues. His cheeks were reddish and rough. "I guess you heard what happened with Irene," Skeevo said. William nodded. "I was with her at the hospital when it happened," he lied. Skeevo didn't say anything but sipped his double espresso and scratched his cheek. "How did you hear?" William asked. "Facebook," Skeevo replied. "Fucking shame." William cleared his throat. "How well would you say you knew her?" Skeevo shrugged. "Better than most customers. Which isn't to say very well. But you learn a lot about people when you smoke with them enough." "Like what?" This earned him a suspicious look, and William stared at his bread, flushed. "I'm—I'm just trying to find her father. She asked me to—I think she asked me to make sure he knew what happened." Skeevo toyed with the neck of his T-shirt and laughed. "Wow. I guess dying really changes people. She told me she never wanted to see or hear from that piece of flyshit again." William frowned. "What about her mother?" "Left when Reeny was little. Ran off with some other woman and left her with the dad and the soon-to-be wicked stepmother. Guess they were pretty much a treat in and of themselves, but it wasn't until Daddy Dearest pissed away her college fund at the track that she actually took off." With that, they sipped in silence again. William checked his phone and saw there was a voicemail from his mother, which he deleted unheard, and a text from Sara, inviting him to brunch at the Harbor Grand Hotel. William saw Skeevo was staring up at the snow-capped statue of Christopher Columbus in the center of the circle. Remembering a random fact he'd learned about it at school, he said, "Did you know that every official distance in New York City is measured from that statue? It's the center of the center of the universe." Skeevo laughed. "I've learned in my travels, William, that the universe has no center. No center, no limits. We live in the midst of infinity." Just as William was about to agree and thank Skeevo for his time, he caught sight of something—someone—familiar out of the corner of his eye. A streak of blond hair and a red coat passing the Sunglass Hut. "Irene?" William shouted, and jumped up so quickly that he slammed his knee into the flimsy table. Whirling as he tried to stop it from tipping, he wound up instead sending espresso and _pan de horno_ everywhere, landing on his back on the marble, his eyes fixed on a crown of lights high above. "Whoa, whoa, whoa!" Skeevo moved to help. "You okay, man?" Blood rushed back into William's cheeks as he felt clear air fill his lungs. When he looked up again, the woman in red was gone. "Sorry." William breathed deep. "I—it's like I keep forgetting." Skeevo grabbed some napkins and helped mop up the mess. "Hey, no sweat. Happens to me too. Last week I saw her standing on the F platform heading uptown when I was heading down. A week before that it was twice in the same day." "It's crazy," William apologized. "I'm so sorry." "Don't be. Listen. This is _love_. It's far more powerful than death. It's like I was saying. In an infinite universe, in an infinite number of infinite universes, all things exist simultaneously. Anything that can be, is." William got up and stood by the glass. "Are you saying you believe in ghosts?" Skeevo folded his fingers. "I once saw three ghosts in a single afternoon." Stifling a groan, William pressed his hot forehead against the cool glass of the window. He felt faint vibrations from a bus downshifting in the circle. It eased around the southern curve and curled around to head north along the park. An endless river of traffic wound counterclockwise around Columbus Circle, all roads leading away from this point, like the cross of two axes on a piece of graph paper. _This is love._ He drew two zeroes in the condensation, with a comma between. 0, 0. Then he traced a cartoon ghost around it. "I didn't even know her," William sighed. "It's so stupid." Two one-night stands. An awkward Christmas dinner at his parents'. A few months of silence. And then what? A couple of awful summer months when she'd been either ducking out to the studio, stuck in the hospital, or forcibly convalescing in his apartment. A year later and William still didn't have the faintest idea what Irene had been doing with him. ### 3 Before leaving the mall, William showed Skeevo the address book, but he didn't recognize any of the names or places in it. He seemed only moderately surprised when, afterward, William awkwardly asked if he could buy an eighth ounce of the same stuff Irene used to get, which he'd been increasingly nostalgic for, especially after the awful weed he'd been buying off a neighbor's teenaged son. Skeevo met him in the men's room ten minutes later with a small, pillowy paper bag that smelled like what he remembered. He told William to call anytime and to punch Irene's dad in the throat if he ever did track him down. Then he went off to resume kneading. William tied his scarf back on and caught an E train to the Harbor Grand Hotel, which was down near Wall Street, but on the opposite end from where he used to work and not anywhere he knew well. He had to plug the address into his phone, the new Cobalt 7 with TrueVoice technology; his brother had bought it for him for Christmas, and thankfully it had a supercharged battery. As soon as he sat down on the train, he took the address book out again and flipped through it one more time. Each name, street, state, and zip code brought him an ounce of peace. They were like elements in an epic equation, in which X equaled Irene. Who she'd been, before anyone had known her. There was no entry for "Mom and Dad," but that didn't mean they weren't in there. One hundred and twelve names in fifteen states. All night he had been ruling out the ones he recognized. This had narrowed the list down to just a dozen people. They could be clients or friends or weirdos she'd met on the subway. But maybe one of them was her family. William got off the train at Church Street, where he noticed a new voicemail from his own mother and decided to ignore it until after he'd gotten a chance to smoke, which he'd found considerably helpful in dealing with her general lack of sanity. He walked past the eternal construction around the World Trade Center site to the Harbor Grand: a gorgeous hotel built above an old colonial inn that supposedly had been there since shortly after the natives had sold Manhattan to Peter Minuit for sixty guilders and some loose beads. Inside, he found less of a restaurant, more of a tavern, furnished with antique chairs and silver gaslights. He didn't see Sara anywhere but did spot George, sitting at the head of a long table, regaling people from the opening the night before. "Mr. Cho!" George said, standing up with a mimosa in each hand. William could see that he hadn't slept either, and after a congenial hug, George sat back down somewhat absentmindedly, still with both drinks. "Sara had to duck out. Thanks for coming by last night. You really should have stayed! You missed all the drama." "There was drama?" George practically licked his lips. "One of Irene's exes showed up right after the toasts." William considered he might remind George that _he_ was one of Irene's exes as well, but there was no chance for a word in edgewise. "Yeah. You probably never met her. She used to come visit sometimes up in Ithaca. She's the _worst_. When Sara saw her come into the gallery, she nearly lost her mind, I swear to God. The last time she came around, she ran off with Irene in what turned out to be a stolen pickup truck. One minute the two of them were doing it on Sara's roommate's chaise longue, and the next minute the cops were calling from _Pittsburgh,_ and the two of them were gone, along with all the Percocet I had left over from getting my wisdom teeth out." William tried to look both impressed and concerned. "What was her name?" "Alisanne. Alisanne Des Rochers." William tugged awkwardly at the end of his scarf, a strange heat creeping up the small of his back. He had looked last night for Alisanne in the book and not found her, but now he recalled some jagged evidence of pages torn out in the D section. "What did she want?" "Who knows? She's a maniac, I'm telling you. Sara caught her poking around Irene's birdcage piece and totally flipped. She had Abeba make her leave. It was intense." After two mimosas, William excused himself to the bathroom where he went to the sink to splash some water on his face. He came out and sat down on an old Windsor bench in the reception area that creaked miserably under his weight. He took the address book out of his suit pocket and thumbed to the back, where there were a few loose photographs. There were the naughty Polaroids, of course, but also several PG-rated pictures taken in college days. George and Jacob dancing with Irene in the student center under a disco ball. Sara and Irene collapsed under shopping bags at a food court, sharing a root beer float the size of their heads. Irene standing ankle deep in a creek, arms stretched to a brilliant sun just out of the frame. Her face in the glow of twenty birthday candles on what appeared to be a penis cake honoring Jacob's birthday. In another she and Sara and George were covered in white paint, and Irene was sticking her tongue out. Her shirt said I GOT RIPPED AT VAN WINKLE'S—NYC, NY. They all looked younger and happier. Just then George stopped in from his own trip to the bathroom. "Thought we lost you," he said. With a loud thump, George landed on the bench beside him, which complained but didn't break. William tried to tuck the photos away, but George had already seen them. "Looks like sophomore year maybe? Habitat for Humanity." "You should probably have these," William said, pushing them toward George. He only pushed them back. "No, that's all right. I've had enough nostalgia for a week. Sara just finally finished going through everything from her stuff we put into storage. Photos, dishes, jewelry, books . . . all those clothes. God. We took most of it back to that secondhand shop she liked so much with the vintage shoes. Mel's? I guess now it's thirdhand." He seemed to regret this observation almost right away, and William ignored it. "I've been thinking—well, right before she— . . . I think she wanted me to get in touch with her father and stepmother. I think someone should, you know? It doesn't have to be me, but . . . I just want to know who she was. Where she came from. You know, I don't even know why she—why she liked me." George sighed and raised his hands into the air as if offering something to the heavens. After a moment William wondered if he hadn't begun calculating field equations in his head, but then he finished with a stretch and a loud yawn. "There's a kind of apocryphal physics story," George said finally. "Someone's giving a cosmology lecture about how the sun is just one star in three hundred billion in the Milky Way galaxy, which is just one galaxy in two hundred billion in the universe, which is just one universe in the whatever-it-all-is—and this woman stands up and says something like 'That's crazy! Everyone knows the Earth is flat and rides around on the back of a giant tortoise.' And the lecturer says, 'Well, ma'am, in that case, what is the tortoise standing on?' and she replies, 'Another tortoise, of course!' and he says, 'Well, so what is _that_ tortoise standing on?' and she says, 'Another tortoise, of course!' and he says—" "George!" "Right. Sorry. So he says—he says, 'And what is _that_ tortoise standing on?' and she says, 'Sir, I'm telling you, it's tortoises all the way down!'" William got the sense that this was the punch line, and he gave George a perfunctory laugh before saying, "I don't understand." "That's Irene. She's just tortoises all the way down. Mysteries on top of mysteries, however far down you go." William felt something seizing up in his chest and hurriedly tried to pay George for the mimosas, which he refused, of course. He looked about ready to fall asleep on the bench. "My love to Sara," William said quickly, before walking off to the men's room. There he locked the door and rolled a joint on the counter by the sink, carefully, just the way she had taught him. Then he stepped outside and walked down into the Battery, where he could smoke it in relative peace and quiet. He stared out across the gray skies toward the Statue of Liberty, cold and alone in the open harbor, and thought about calling his mother. They hadn't exactly been getting along lately. Shortly after Irene died, she had asked him to join her for a _Seoul Jinogwigut—_ a ceremony to usher the last of Irene's seven souls to paradise. He didn't expect her to understand that he didn't _want_ Irene's seventh soul ushered to paradise, just as he didn't want to hear her theories about how Irene's cancer had been caused by _jabkwi_ , wandering malicious spirits, who had nestled into the psychic hole Irene had created by turning her back on her family—her ancestors were pissed, in other words, and misfortune was sure to befall those who pissed off the ancestors. Whatever. Let her stand around shaking jujube sticks and burning paper effigies of horses and invoking the spirits. But now it had been a year, and his mother was still trying to come up with ways to help Irene's soul reach the next world. When the tightness in his chest finally dulled to a weak throb and he felt sleepy, he walked to the street and hailed a cab. It was only when he sat down in the backseat that he realized he had absolutely no idea where he wanted to go. "You know a bar called Van Winkle's?" William asked. The driver nodded. "Up on Avenue B." William said that was the place, even though he didn't have the faintest idea. He clutched Irene's address book in his hand like a holy book as they headed uptown. Pressing one cheek against the cold window, he listened to the other cars. Their sounds began to overlap, repeat, and blur together. The foggy voice of the radio tuned to sports. A faint, charred coffee smell came from the front seat. The door hummed and the road sang, and soon everything was lost in a white wall of shrouded air slipping past the window. Ice was quickly covering the windowpane. Strange—though not as strange as the warm hand he felt on his. Without looking, he knew it was Irene's hand. It just _was_. And she just _was there_ , as if she had always been. Not ghostly, not cold, nothing spectral or apparitional at all. Her hand on his arm and on the back of his neck. Her head pressed onto his shoulder. Fat snowflakes were falling outside the window. William could feel her fingers sliding between his, looking for a comfortable grip, as she sighed lightly and kissed the side of his neck and then a slightly firmer one, pecking at a spot she always liked. He was afraid to look directly at her. _Are you a ghost?_ he asked. _No._ She giggled. _I'm a bird. A very special, rare type of seagull._ _What makes you so special and rare, Madame Seagull?_ _I hate the sea_ , she said. _That's pretty inconvenient._ A long sigh that tickled his neck. _I'll admit, it's a problem._ _So where do you live then?_ She jabbed her nose into his neck a half dozen times as he squirmed. _I'm practicing to be a William-pecker. So I can make my nest inside Williams._ Outside a beam of blond sunlight fell onto the frosty window, and William watched as a million fine, symmetrical crystals of ice melted and condensed into steam, filling the backseat of the cab. He turned to try to kiss Irene, but she pressed his cheek the other way. He could almost see her hair out of the corner of his eye, falling down over the white shoulder of his shirt, spilling thick and golden. Then he pushed her hand away, turning the rest of the way—and woke up alone. ### 4 Van Winkle's turned out to be a seedy dive bar, covered from ceiling to floor in stickers for punk rock bands, half of which, William imagined, had long ago ceased to exist. There was a stage in the very back, and as he sat at the bar sipping a cup of burned coffee, he tried to imagine a teenage Irene, pink streaks in her hair, diving the stage. He imagined her there with a group of forgotten friends, on whose couches she'd once crashed, making the pilgrimage from wherever they'd come from originally to the anonymous Lower East Side, doing what she had to do to forget the home she'd left behind. Not exactly eager to go back home (having now received a third message from his mother), William pulled out the address book and, feeling invigorated, began to dial. First he tried someone named Geoffrey Irving, in Tarrytown, but he wasn't available. According to his half brother, who answered the phone, Geoffrey was serving ten years in Sing Sing. Maybe he had known an Irene or a "Reeny" once, but William would have to go up there to ask him. He thought he probably would not. Instead he ordered a fresh coffee and asked the Cobalt 7 to look up Geoffrey Irving's record, which seemed to involve stolen cars and an arrest in 2002, which was at least a year after Irene had ended up in Ithaca. In any case, he was their age and thus too young to be Irene's father. William moved on to Ed Simpson of St. Louis, Missouri, a retired train engineer who was happy to pause _The Price Is Right_ to talk a moment. Mr. Simpson remembered a girl named Renee who had once dated his son, Ed Simpson, Jr., now Colonel Ed Simpson, Jr., presently off completing his third tour in Afghanistan. William thanked the man and asked him to thank his son for his service before moving on to the next name in the book. No one picked up the phone at the home of Sally Paulson of Rochester, but when he looked her up on the Cobalt 7, he found a picture on the staff page of the Maquokeeta Farm in New Hope. He remembered Irene mentioning once working on a farm there. But Sally was African American and so probably not likely to be Irene's mother. He couldn't get through to anyone at the number listed for Anthony Lemon, of Antwerp, Ohio. Then he had three more dead ends in a row with Evelyn Cross of Key West; Mary Winter of Mary Winter's Garden Center in Houston; and finally Poppy Daniels (gender unknown) of West Virginia. William was just about to give up and surrender to the fourth call from his mother, when he tried Mr. Bernard Wyckoff, of the Pruder Pools and Aquatic Center in nearby Brighton Beach, who picked up the phone and said that, yes, he had an outstanding order for someone named Irene Richmond, but he was going to need to come down and pick it up himself. With no other leads, William gladly got into another cab by the bottom of Tompkins Square Park and headed for Brooklyn. On the way he, more reluctantly, decided to call his mother back to let her know he wasn't dead, lest she start trying to send his own soul abroad. She sounded strange when she answered. "William, I have to go. Something happened." "What is it? Is Dad okay?" "Your father is fine." There was a short silence. "Do you remember Chongso Kim?" William vaguely recalled a pudgy eight-year-old from his father's congregation, who had thrown up a metric ton of yellow cake at the Annunciation potluck luncheon. "This morning he snuck out of his room to buy a comic book and was killed by a car crossing Northern Boulevard. Hit and run. Everyone here is very upset. I made _sam gae tang_ to bring over to Mrs. Kim's." William closed his eyes, feeling suddenly sick and trying not to imagine what it would be like to be out on the road in front of the cab he was in, hitting the front fender. "God. That's awful. I'm—so sorry. Please tell her I'm sorry." He knew his mother would be in a rush now, on her way to a room full of weeping women, carrying her big bowl of stew: Cornish hens stuffed with rice and chestnuts, in a ginseng and garlic broth. She'd add it to the mounting pile of Tupperware in the kitchen and then do what she could, perform the rituals that might comfort the grieving mother, finding the shadow of her son in the haze of incense. "You didn't come home last night?" "Yeah, sorry. I'm—staying with friends in Manhattan. You remember George and Sara?" Then his mother spoke softly. "She is lost on the road from This World to That World." "Who? Sara? No, she's in the financial district." But his mother only said, "You call me back later," and hung up. ### 5 William was a little surprised to find the Pruder Pools and Aquatic Center still open in February. Half the other stores along the seaside stretch that he'd walked down had been shuttered for the season. There were only three customers inside when William entered, under a thick yellow haze of cigarette smoke, which not even the chlorine in the air could mask. He approached the only person he could positively identify as an employee, a man whose face was hidden behind a massive, wiry white beard. He was sitting in a deck chair in the back sipping from an orange plastic mug that said LIFE'S A BEACH on the side and reading a historical thriller about the Civil War. When William introduced himself as a friend of Irene Richmond's, the man extended his hand, then barked, "Aqualad?" "Sorry?" With a huge heave, the man rose up out of the deck chair—his giant hand setting down his book so as not to lose his place—and then shifted gears with a flickering smile. "He's in the original packaging. Near mint condition. I was going to just ship him, separate from the other stuff, but then her first check bounced and I never heard anything." Confused, William followed the man to a door on the side wall by the pool floats, marked PRIVATE, and opened it. Inside, the only light came from eerie, dim halogen spotlights above a long row of display cases. Neatly arranged inside were action figures and dolls of all sorts and sizes, still entombed in original packaging. Maybe a thousand caped, muscular superheroes. Lithe, peach-skinned Barbies. Original Raggedy Anns and Andys. Babies with porcelain faces and glass eyes behind lids that seemed to flutter. The six original American Girls in their boxes. _Let us out_ , their tiny trapped faces seemed to implore. Mr. Wyckoff tapped a heavy knuckle into one of the cases, at a figure of a boy wearing a tight orange shirt and impossibly tiny green swim trunks. Just like in the comics William had read as a child, he had deep, purple eyes. _Aqualad_ , the packaging announced, _Prince of Atlantis._ In the background was a wide white beach, spotted with futuristic crystal towers and huge cliffs of diamond. "You'll never destroy Hidden Valley, Garn Daanuth!" he declared in a flat white speech bubble. _Endowed with the Martian power of the Metagene!_ the corny, 1970s-era packaging promised. What Martians had to do with Atlantis, William could not remember anymore. "Like I told her, there's a small crease on the corner of the package." William squinted but he barely saw this tiny imperfection. Before he could say anything, Bernard took the boxed figurine out of the case and handed it to him. William turned it over in his hands a moment before he realized it was for him. Right after they'd gotten back together he'd told her the whole story about the kimono and Mi-cha. He noticed Bernard's face was practically glowing, now that he was standing so close to the halogen lights. Cheeks, nose, forehead—all were blazing. Long jaggy capillaries branched like rivers. What'd they call that? Gin Blossoms. Like the band. He recalled the blotches Irene had sometimes gotten in harsh sun, or after a second drink, and once upon eating a strong vegetable curry. It started to get especially noticeable after the chemo. "Rosacea," she had said. "Runs in the family." William took a deep breath and, keeping his eyes on the action figure, found the courage to ask, "What was the rest of the order? You said you sent Irene the rest already." "Yeah," he said, "seventy-seven identical, unboxed Barbie dolls. Don't know what the hell she wanted to _do_ with them." William's heart pounded. He knew exactly what she had done with them. Slowly he thought he was beginning to understand. He turned to the man's desk and saw a framed photo. There was the enormous, smiling Bernard with an arm around a tiny woman with dark short hair. They were in the stands at the racetrack, pointing excitedly to a picture of a chestnut-colored horse under a blanket of white carnations. They appeared to be celebrating a happy moment with a bottle of champagne. "That's my wife, Maggie," Bernard said proudly, "just after I won five grand at the 2009 Belmont Stakes." William tried to look impressed. Beneath this were two school photographs, each taken against a familiar blue Sears background. Mr. Wyckoff tapped the edge of the photo of a heavyset girl, maybe ten years old, with braces, hair back in a ponytail. "That's Lorraine, my youngest. And here's Greg. He's three-A most outstanding wrestler, 2010 eighth-grade individual champion." William looked for any resemblance in Greg, whose buzzed hair did seem to be blond, but whose heavy jaw and high forehead looked nothing like Irene's. "Nice. Just the two kids?" William asked. Did he detect a slight hesitation as Mr. Wyckoff turned to lock the display again? "Well, Greg eats enough for three. And Lorraine's sweet as a dozen daughters." "They must have had a good time, growing up with all these great toys." Now William saw clear displeasure in the man's eyes. "These are not _toys_ ," he said. "These are _not_ to be played with. These are collectible figurines, for serious hobbyists only." William looked back up at the man. If he was Irene's father, then in her final weeks of life, she'd conned him out of seventy-seven Barbie dolls, which she'd then melted onto a two-foot-section of an I-beam from the World Trade Center site. William thought, with all respect due to Skeevo, he would rather not punch him in the neck. "So look. Let's not have any trouble. You can pay me the full amount now, and we'll be done with it. Like I said, the check she wrote bounced. I am this close to calling my lawyer." Maybe Irene had, in fact, been taunting Wyckoff. Hoping even that he or some lawyer would someday stumble upon the truth: that Irene was his daughter, and that she'd had the last laugh. William almost laughed himself. Talk about unfinished business. No wonder her soul wasn't moving on! Then he remembered that this, of course, was totally insane. And yet somehow he felt compelled to say what he said next: "Actually, she died." Bernard's eyes widened, and then he groaned. "Just perfect." William took another deep breath, terrified but suddenly sure that this was why Irene had asked him to find her father. Just one second, and it would all be over. "I think—sir, I'm sorry. But I think—I think she might have been your daughter." Bernard glanced at the photograph of Lorraine, then back at William, confused. "The hell are you talking about?" "Did you—sorry, but did you ever have another daughter?" The man's red-veined face went white, and his lips seemed to move without orders. "Carrie Ann?" "Carrie Ann?" William echoed. And that was when he saw every red line on Bernard's face tighten. William's eyes shut in fear, and he tried to lurch toward the door. Then he felt a stone fist crushing into his temple, and his whole body twisted around. One foot lost contact with the floor, then the other. His uninjured eye opened to see the dolls in their glass prisons lurch and spin around until they were below him and the ground was above. His legs still kicked toward the door. There was a flash of white, blinding light, and then darkness everywhere, like deep, deep water. ### 6 William's head ached, just above his eye, and his jaw was in agony. Had he actually been punched in the face? He had never been in a fight before, but he realized, slowly, that this was what had happened. And that now he was lying in the damp sand of a very cold beach. There was dried blood on his lip and all down his shirt. He vaguely recalled staggering out of the store, trying to get away from Mr. Wyckoff and then blacking out. Carrie Ann Wyckoff? He couldn't seem to reconcile this. It couldn't be her name. Faintly he could hear the voice of the Cobalt 7 inside his pocket, and he pulled it out to find its screen badly cracked. _Hello. Where can I guide you today?_ it asked, over and over in a woman's pleasant voice. For a while William cried without getting up or moving. Everything hurt, and worse, he couldn't feel her anywhere anymore. What was there left to do now but go home? Allow this defeat to mark the beginning of the rest of the long defeat of his life. Alone and in ten kinds of pain. Then he noticed he wasn't exactly alone. He had, apparently, escaped the store still clutching the Aqualad package, which now lay a few feet away in the damp sand. He studied bright blocky colors of another age, the vaguely homoerotic outfitting, and the cheesy fists-on-hips posture of a teenage superhero. In one violent motion, he reached out, grabbed it, and tore the plastic housing from the cardboard—feeling some pleasure at the separation of the long-sealed glue. He took the little boy out and studied him closely. _Hello. Where can I guide you today?_ his phone asked again. William stared at the caped figure and had no answer. _Hello. Where can I guide you today?_ Something in him snapped. "WHERE IS SHE?" he howled. "WHERE'S IRENE?" He saw a burst of purple behind his eyelids. He thought he might throw up. And then— Then the phone replied, in the same stiff but agreeable tone, _Finding Irene._ William set the doll down and studied the spider-webbed screen of his phone. He watched a map forming behind the cracked glass. For a moment he almost believed that it might actually locate her. Eventually a picture of her old East Fourth Street apartment emerged, the address still stored in his contacts list somewhere. He lay there cradling Aqualad in one hand, the phone in the other, thinking about the day he'd broken into that apartment. How he had felt an odd peace there among her things—pasta strainer on a hook near the kitchen, overgrown spider plant on the windowsill, a stack of magazines stolen out of the downstairs recycling bin, a blanket from the Met with a Monet print on it. Her things, without her. At first he'd thought it was just the adrenaline of being where he wasn't supposed to be, but soon he'd realized it was something else. He was with her, without her. What did it say, that he'd always felt closest to her when she wasn't there? In her apartment, by himself. By her side as she slept. In the hospital while the morphine carried her off in a Stygian stream. Looking at a picture of her, taken by somebody else— Of course. He slowly got up and brushed himself off. As head-aching blots of pink stopped moving in front of his eyes, he turned to the phone and asked for the person that he knew he should have started with. "Cobalt. Find Alisanne Des Rochers." It turned out that Alisanne Des Rochers, owner of a Web design company based in Paris, was prompt on e-mail. Before William had even fully pulled himself together, thrown the action figure into his pocket with the weed and the address book, she'd responded to his query, saying she was still in town and could meet him at her hotel, The Quaker, in Long Island City. The driver who picked William up expressed mild concern for him with a perfunctory "Are you okay, sir?" before returning to his phone call in some West African–sounding language. William said nothing. He closed his eyes and did not open them again until they'd arrived. • • • When William stepped into the glass and steel lobby of the hotel every eye was on him. How bad did he really look? Fortunately, before the porters could swoop in on him, a woman approached him from the bar area. "You are William Cho?" She wasn't what he expected. Since he'd first seen her name written on the back of Irene's dirty Polaroids, he'd been envisioning a regal French beauty. Leslie Caron from _An American in Paris_ or María Casares from _Les Enfants du paradis_. In his mind she'd existed in black and white. But here was Alisanne, in the somewhat-acned flesh. Thick eyebrows. Greasy, dark hair cut in a childish bob. Lips wide, flat, and pink, parted slightly, as if she were about to chew something. Her hands were blue and veiny, her nails polished black. Her nose looked as if it had been broken and then rebroken a few times for good measure. She had a wart on her neck the size of a pencil eraser with thick black hairs springing out of it. The black hood she was wearing was part of a denim coat and her black boots were laced up to her knees. The porters looked displeased as he trudged inside, leaving sand behind on the dark carpet. He apologized, but Alisanne didn't appear to care. The hotel seemed to be constructed of different-sized panels of glass in interlocking square frames. Some were frosted to the point of complete opacity and others were crystal clear. Behind the desk was a waterfall, flowing somehow up and not down. An enormous sculpture of a spider eating a wasp sat in the middle of an otherwise pleasant-looking garden. There were four oversize gnome statues in the mailroom. Were they part of the building decor? Or had someone ordered them? William tried not to stare into the adjacent yoga studio, where people were bending themselves into holistic pretzels. They went wordlessly to the sixth floor, where Alisanne opened her door with a keycard and invited him to remove his wet clothes. "Take a shower. I'll find you dry clothes. And some tea." William hesitated, seeing that the shower was divided from the main room only by a pane of frosted glass that didn't reach the black-tiled floor. "You are—not my type," she said flatly. Reluctantly he removed his wet pants and shirt. Alisanne dropped them into a plastic bag and ordered some tea while he showered and washed what felt like an entire sandbar from his hair. Clean and warm at last, he stepped out in a towel, and Alisanne handed him a pair of ripped black jeans and a T-shirt for a band called MALADROIT. He was a little embarrassed to find that they were almost exactly the same size. She poured him a cup of tea. William sat with it on the edge of the bed, thinking he should let her have the chair, but she sat down cross-legged on the floor. "Your eye will be very swollen by tomorrow," she said. William nodded. It hurt like hell, but he wasn't about to let her see that. "So you live in Paris?" "Sometimes," she said. "And you came all the way here for the show?" She stared at him, almost curiously. "I came to get something that belonged to me." "Oh," William said. "Me too." She laughed and spat something from her teacup onto the floor. "No. You want to know who she was." William frowned. "I guess." Alisanne smiled, cryptically. "Who did this to you?" "Her father." She seemed almost impressed. "Horrible little man." "Not so little," William winced. "I thought she wanted me to tell him what happened. She asked me, I think, before she died." But now suddenly he wondered if what she'd meant was that he should make sure her father _didn't_ find out. If she had, in the final hours, regretted her plan. If it had even been her plan. William felt utterly foolish. He didn't know what he'd been thinking. He didn't know why he'd thought he knew anything about her at all. "And you called me because . . . ?" "You knew Irene better than me. I was hoping you could—shed some light?" Alisanne considered this a moment. "Why?" "Why what?" "Why would you want me to 'shed light'?" "Look," he said, "we should—we should help each other out. I've been—Christ, just look at my face, okay? I've been through a lot already, so please just _tell_ me." "Tell you what?" William realized he didn't know what he wanted to know. Who she was? Where she'd been? What she'd done? "How about where you met?" he said finally. "We met in San Francisco." "And?" "And she was a terribly stupid girl. Away from home one week and already broke. Sleeping in the park, selling all the things she took from her nice grandmother. Trying to buy a sandwich. She fainted on the sidewalk in front of me. So I brought her home and let her stay with me. And what does she do? Reads all my Camus and messes up my sheets and kills my balsamine plant and makes me fall in love with her. So then one day I go out. I come home. She is gone. Stole an expensive first-edition book that my father bought me. Does that—how did you say it—shed light?" William rubbed his head. It didn't. "I keep thinking if I knew who she _was_ , I could . . ." But after all this time he didn't know what he wanted to do. Let her go? Keep her close? Somehow do both things at once. Be free, and haunted, forever. If only he could keep her inside a box, safely stashed away in a closet or a drawer, to be taken out only when he wanted. In the pit of his stomach he knew that Irene would have hated this more than anything. "I just want to know if she really loved me," he said. Alisanne shrugged. "She loved everyone." "I want to know that she loved me best." "She loved you last." "But not on purpose." "Yes, on purpose." William considered this. "She would have left me eventually." "Yes," Alisanne agreed, "sooner or later." William sighed. "I wanted it to be later." "You think later you would have said, 'Okay, this was good. I've had enough. Please die now. Excellent loving you.'" He supposed she had a point. Whatever might have happened between him and Irene in the long run—had there been a long run—if, at ninety-nine years old, he'd seen her slipping away on that hospital bed, something told him that he'd still have looked away before the last moment. He'd still have wound up lying next to a mound of sheets wishing she were underneath. He'd still be feeling her cool breath on his wrinkled neck. "Maybe there are people who live together eighty years who don't love each other as much as you two did in one year. Maybe others spend a single night together and love each other more than you'll ever love anyone. But what does that matter now?" William glared at her. Then he picked up his still-damp coat and said, "Come on. I bet I know what happened to your book." ### 7 Alisanne had a rental car, so she drove him back into Manhattan through the Midtown Tunnel. On the way, she told him what little she knew about Irene's mother. Her name was Mary, and she'd come from Texas, where her first husband had worked on an oil rig in the Gulf of Mexico. There'd been some sort of accident—a fire, she thought—and he'd died and Mary had gotten some insurance money out of it. She met Bernard Wyckoff somewhere outside New Orleans and got knocked up and married him. Irene, or Carrie Ann, had been born somewhere in the Florida panhandle, where Bernard's family was from. The Wyckoffs operated several local strip clubs, including one where Mary wound up waitressing part time while Bernard gambled away what was left of the insurance money and his parents raised little Carrie Ann. It was there that Mary met a dancer named Izzy, whose real name turned out to be Mary as well. At some point one of the Marys seduced the other, and they ran away together. Irene was never entirely clear on why they left her behind. Possibly they thought she'd be better off with Grandma and Grandpa Wyckoff. Possibly they worried that Bernard, or his gambling buddies, would come after them if they took her along. Maybe there was a calculation: no judge in the Florida panhandle in the late 1980s was going to grant custody to an exotic dancer and her lesbian lover. Alisanne didn't know, because Irene had never known. Bernard wound up marrying a woman he worked with, Maggie Pruder, and moving them all up to Brighton Beach to take over her family's pool supply store. Mary and Mary had ended up in Virginia where now, both middle-aged, they worked for the department of public utilities in—and Alisanne seemed smug to have figured this out before William—a little town called "Irene." Locked in a line of bumper-to-bumper traffic, somewhere down under the river, as the fluorescent green light of the tunnel cast a pallor over everything, William felt another piece go into the puzzle. Irene. Of course. And yet it didn't feel finished. The puzzle didn't match any image on any jigsaw box. No cityscape or field of sunflowers. No kittens with balls of yarn. Just another tortoise under the one above it, and on and on. William said nothing, focusing instead on rolling another joint without spilling weed all over the car. Alisanne watched him wordlessly as she drove them toward Mel's Secondhand Shop, where Sara had taken the last of Irene's things from the storage unit earlier that week. Alisanne parked just off Washington Square Park. They walked through together, sharing the joint as they avoided tourists holding bags from boutique shops, and stepped quickly past dreadlocked students on benches. It struck William suddenly that it was the first part of the city he'd been in all day that he recognized. A girl played the violin in hopes of spare change. A pair of bearded middle-aged men smoked cigarettes while playing chess. A trio of heavyset Germans stood under the great Arch and made peace signs with their fingers, while a man in an orange ski cap changed his pants a few feet from them. William couldn't stop looking for Irene behind every lowered hood and winter cap. But he didn't feel her anywhere. "You roll these like her," Alisanne said, passing the last of the joint back to him. William took the last tiny hit and tossed it to the sidewalk. "Well, she taught me." "Me too." Mel's was hot and crowded. Australian women walked up and down a maze of cramped aisles, examining denim jackets and mod-patterned dresses. Paisley and flowers burst everywhere like fireworks. Technicolor angle-striped dresses and jumpsuits with bell-bottoms. Pictures of Twiggy and Audrey Hepburn, torn from old _Vogue_ s, now framed on the walls. Two men were having a contentious debate over a pair of silk pajamas. A fourteen-year-old girl was trying on a pair of pale mint-green shoes, yelling at her mother that she _needed_ them. They were _only_ three hundred and nineteen dollars. They were from the _sixties_! The mother, who didn't look old enough to have owned shoes in the sixties, was ignoring her, checking an e-mail on her phone as the girl pitched a fit. "Excuse me?" William asked a harried-looking man in bubblegum-pink pants who seemed to work there. His cheeks were sunken like those of a corpse and made his eyes bug out. "We're looking for an old book that someone might have sold you recently." The man was already shaking his head. "No returns, no refunds." "Oh that's not—no problem. We'll pay for it." The man sighed and tapped the sides of his alligator shoes together, his hands still busy tugging things uselessly into temporary order, soon to be undone by the browsing customers. He looked at Alisanne, then back at William, and registered a fair amount of concern. "Before we get to books, sweetheart, you need a hat worse than anyone I've ever met." William blinked. "I do?" The man balled his hands and looked William in the eye. "Your forehead looks like an eggplant. Come here. When I'm done people will think you're Don Draper." The man climbed a small ladder to retrieve a man's hat from a high shelf, up above a rack of kipper ties. He pulled down a charcoal-gray one and pointed William toward a mirror. Not only did it hide the lump above his eye, but it also looked awfully good. More Sam Spade than Don Draper, but he liked it. And he couldn't explain why, but he had the strangest feeling that Irene would have liked it too. "Can you wear a hat to a wedding?" he asked Alisanne. "Is it outside?" she asked. "I don't know," William said. "Just take it off during the ceremony. Don't be vulgar." William promised, and the man pointed them back toward the used books. There were hundreds, all piled up and in no particular order. Alisanne began sifting through the stacks. William didn't even know what they were looking for. He opened books at random looking for handwriting or doodles that looked like Irene's, but it was tough to tell. Was that her 7 in the phone number scrawled in the margin of _The Count of Monte Cristo_? Was that her lazy spiral on the back page of _The Little House on the Prairie_? Just then William's finger paused on a green volume that seemed familiar. _The Iliad_. Homer. He picked it up and opened it slowly. Its pages were covered in familiar handwriting. His own. But also in hers. He'd forgotten all about the book. He'd last seen it in her hospital room, before she was moved to the ICU. Afterward it had been the last thing on his mind. Sara had surely brought it home and put it into storage with the rest of her things. And now it was here. "Aha!" he heard Alisanne shouting from just around the corner. She emerged with a plain, if somewhat beaten-up white book by Albert Camus. In plain red lettering, it said _L'Etranger_ and beneath that, simply, _Roman_. The shop, apparently unaware that it was a rare first edition, was selling it for $1.50, which Alisanne paid gladly. "I have to go now," she said. "Thank you, William." He moved in, suddenly, to hug her. She tried to jump back. Then, having failed to escape the embrace, she surrendered. "Who knows," she said, "what she ever saw in either of us." But now that they had met, William, somehow, thought he did know. There was something about Alisanne that felt familiar. She was too blunt where he was too polite, but underneath was a kindness so strange that they both usually hid it away. And he supposed that must have been what it was. What Irene alone had been able to see. The thing she'd loved. After paying for his new hat and his own former book, he stepped outside and returned to the park, where he sat down on the icy bench not far from the silent fountain. He opened the book carefully. He remembered that first night, how she'd defended, in a way, his preferred translation when Jacob had tried to mock it. Lattimore. _Richmond_ Lattimore. She had underlined his first name in blue ink, on the title page. William smiled. He wondered how many more of these moments he might have in his lifetime. Suddenly he hoped that he'd never find all the pieces. He was glad there was nothing but tortoises all the way down. The air smelled of vegetable curry, and there was a frenzy of branches up in the trees above him. Only then did he remember he was still wearing Alisanne's clothes. Sitting there in them, and in his new hat and the scarf from Irene, he felt almost like another person entirely. So this was what it was like. This was what Irene had learned. How to be someone new. Just then he saw a hint of color on the edge in the back of the book. Carefully he turned to find a beautiful scene on the back leaf done in watercolors. Grays. Purples. Yellows. Blues. A busy street. Cars moving around a traffic circle while tall buildings gleam in the sunlight. White towers rising up into the blue heaven of a new day. The red neon on a Chinatown restaurant, still lit in the daytime. Sunlight gleaming off a water tower. The hushed, holy green that crept into the brown skeletons of city trees. Asphalt meridians curving through. Far away, the line of towers forming a horizon at the river. And rising up behind it all—the Brooklyn Bridge. No doubt it was hers. Her colors, her lines, her trembling wavelength. It was titled only "View from 4R," but there on the opposite page was a note, in her handwriting. William—Thank you for the book. I hope Sara gets it back to you! And I hope you don't mind I did a picture on the other page, back when we were broken up and I thought I'd probably never see you again. I should explain, I guess, since you'll want it back now. That's the view from my bedroom at my grandmother Fiona's apartment, 12 Spruce Street, where I went away to live when I was a girl and, let's just say, not the most darling granddaughter ever. I loved it there, but then she got sick and passed away. I took some money and ran off because I didn't want to have to go back home again. Once I told you how I was born into the wrong family. For a long time I looked for my right one, and now I know I found it. Sorry I stole your mother's kimono. We should have been friends a long time ago, William. I would have liked that. Since we met, I've been wondering if this is fate, you know? Not in a cheesy way, but what if, no matter what I did all these years, I'd still be dying, just somewhere else? But then I think that maybe the where is what's important. If the gods bother, then man must have free will. _Je suis toujours sur le point de te quitter._ All my love, Irene. William sat there a long time. So she was from—well, just where he was from. He studied the picture again. Irene's childhood kingdom. Like him, she'd stared out at this at night and fallen asleep in the same womb of street noises. Who knew? Maybe they had passed each other on field trips, or crawled under the same turnstiles. Surely they'd both gotten up early on snow days to watch NY1 to check for school closings, and on the Fourth of July they'd both watched the same fireworks in the same sky. They had skinned their knees on the same sidewalks and answered the same essay questions on the same Regents Exam. And when everyone else had left home to come here, they had been leaving there to come home. ### 8 After a while William left and started walking toward the closest train that would take him home. He called his mother on the way, but she didn't pick up, and then he remembered she would still be with Chongso's mother, wearing red _mudang_ robes in their living room, with all the shades down and curtains drawn, while the assembled members of the Kim family sat on the couches and watched her do a dance that their grandparents' grandparents had done. There would be howling and shouting and crying. The ghostly ancestors, lacking the proper equipment for speech, would be invited to borrow her vocal cords and tongue and lips. And the Kims would gradually allow themselves to believe what they needed to believe. That Chongso was fine. Locatable. Watching over them in the company of a hundred generations of Kims. William wanted to believe in this too; he was so tired of pretending that he didn't. He picked up his phone and, through its cracked screen, sent a text message to Sung-Lee, the girl he had gone out with twice while he and Irene had been broken up. _Did you hear about Chongso?_ _I kno! So sad! How r u?_ _I'm good. How are you?_ _Really good. Drink sometime?_ His thumb hovered over the screen. Staring down at the penumbra of green light, he felt an odd sensation running up his arm. He moved his thumb gently to the keyboard and replied. _Now?_ They met near South Street Seaport, where she knew a place that had good drinks and wasn't too noisy. William soon found himself walking down Fulton Street, staring up at the Brooklyn Bridge again, which from this side seemed almost made of light. He felt the shadow of something close behind him. He passed dark window displays full of faceless mannequins. A saxophone cried out from the footsteps of the church. Everyone, everywhere was drunk. William moved through crowd after crowd, seeking her silhouette. As he crossed under the FDR Drive, he heard Sung-Lee calling his name from the opposite corner. It took him a moment to spot her: in a navy blue coat with white trim, stepping out of a cab. She expertly navigated the cobblestones in stiletto ankle boots. She kissed him lightly on the cheek when he got close. "I almost didn't recognize you," she said. " _Love_ what you're wearing." "You do?" William knew he was blushing. Sung-Lee looked far more beautiful than he'd remembered, at least in the soft light of the street. She wore a glittering necklace of silver sharks' teeth. Her eyes were shadowed by a soft green. "I hear your mother's looking for you." William tried to explain. "Oh. Well. I was just—" "Bad boy," she teased. "Call your mother." Did she wink at him? Yes. He tried to laugh, as if it had been a joke, but something in her tone seemed off. She'd been so shy the last time they'd gone out. She'd worn flats. She hadn't kissed his cheek unprompted or said anything along the lines of "bad boy." He wondered if she was already drunk. The last time they'd gotten together, she'd had half a glass of wine and almost fallen asleep. Nothing like this. "So they're searching, like, the whole tristate area to find the guy who hit Chongso. Once they do, I hope they run _him_ over." Then she rolled her shoulders. "Anyways, how's life?" "Life's . . . life," he said. "How's yours?" " _Really_ great," she said. "I'm having a lot of fun." "Fun. I think I had that once," he joked. She laughed. A lot. And grabbed his hand and said, "I'll remind you. Come on." She led him down the street like a puppy dog to the Cutty Sark. A jaunty little ironwork clipper ship dangled from the sign at the entrance. Windows were festooned with ropes as thick as his wrists and aged canvas sails. A chandelier made from a ship's wheel hung from a rusty block and tackle in the center of the room. At the many wooden tables along the decking sat men and women drinking beer and eating fish and chips. William and Sung-Lee took a seat at a table beside a man in a red wool cap, who was splitting a bowl of chowder with a man with sideburns and a porkpie hat. She flagged down a passing waitress and ordered two Manhattans, one with five brandied cherries. "They rinse the glass with absinthe," she explained. "Really makes the flavors pop." "Yeah, but doesn't it eat holes in your brain?" William asked. "Buzzzzzzzzz," she lifted a pointer finger to the side of William's skull. Then she ran a hand over the lump on his head. "So, what, did you get into a fight?" William smiled. "Actually, yes." She seemed—surprised? No. Impressed. He kept looking around, as if someone might see him with her. Not like he was cheating, even if that was how it felt. "I can't be out _too_ late," she announced, withdrawing her hand. "I've got a six a.m. flight to Istanbul for a conference." Some very loud song thumped its beat on the speakers across the way. She was sort of singing along and shifting her hips. At the chorus she sang along, "'O . . . oh . . . oh. Dreams weave the rose . . .' Have you seen this music video? It's _so_ awful. But I love the song." She shrugged as if this were one more of life's unresolvable little mysteries. "What kind of conference?" William asked. The drinks arrived, and he wondered how fast he could finish his and get the hell out of there. She fished one of her five cherries out and began to nibble on it. "Mifamurtide. It's this new drug that just finished a phase three trial. They're approving it soon in Europe. It's _got_ to go well because we really fucking blew it last month in Copenhagen. It wasn't _my_ fault, of course. It was this idiot, Parker, who screwed up the goddamn time zones or hit his snooze button or something and didn't show up, and of course we left all the materials with him. I had to get up there with _nothing_ and do the presentation from memory. I mean, it was the worst thing ever to happen to anyone. You don't even know." William nodded agreeably. He couldn't decide if he was being polite or pathetic, but either way he sensed he'd regret it. "I just hate it when people waste my time, you know?" He couldn't decide if this was a veiled dig at him, or if she was just too obtuse to realize how it could come across. "Thank _god_ it all worked out. And my boss was so impressed, he took me on his jet to stay at his villa in Panama. It's, like, on the top of a private mountain that used to be a volcano. The only way to get there is to, like, take a helicopter? And the whole thing is, like, fucking glass walls so we'd be just, like, sitting in the kitchen, and you can see whales out in the ocean, like, blowing water a hundred feet in the air. Out of those blowholes?" William tried his hardest to seem impressed and jealous, which he assumed was the point. "'Atlantis ROSE,'" she burst out, singing along to the same song. "'Drums wreathe . . .'" "Sounds like things are great then," William said. " _So_ great," she replied, again doing a little dance in her seat to the song as it ended. "Are things . . . serious between you and your boss?" Sung-Lee burst out laughing. "Him? No. He's, like, married or whatever. It's not even a thing. And—" Then as if it were a big secret, she leaned in to say, "He's got the grossest back hair? I had to just tell him at some point—keep your shirt on, you know?" Last time they'd gone out, she'd been insufferably demure. Now she was like her own evil twin sister, and it was no improvement, except that, he supposed, she did seem much happier. He couldn't stop watching her fingers fiddling with the edge of her navy lapel. "You seem different," he said at last. "I mean, in a good way. I mean, I guess, I'm impressed when people can do that. Just take on a whole new attitude." Sung-Lee again leaned in. "I started doing _Entrance_. Have you heard of it?" "No. Is it some kind of drug?" She shook her head and then stared up at the ceiling as if searching there for the words to explain it. "It's like— _so_ incredible. It's all about the radical reinvention of your brain's whole structure through hypnosis. Well, it's _not_ hypnosis. It's a semiconscious state induced by rhythmic motion and chanting. At first it's sort of like yoga almost, but then you go into this full-on trance state. That's why they call it that. En-Trance. Right? And while you're in the trance state, you can just _unlock_ all these things. It's all about realizing what you're doing to hold yourself back, like through hatred or fear or nihilism or eating gluten. You identify the things you want, and you finally allow yourself to take them—" William lost the end of her diatribe as a garbage truck rolled by outside, thudding and crashing and beeping and flashing its lights as men in neon vests hopped off to collect black bags of trash that gleamed in the streetlights. He looked back up at Sung-Lee, coaxing the last of the cherries between her lips. Was he a thing that she had decided to allow herself to take? Or was he something to unlock? Some kind of shackle; the gluten of her love life. He watched the men outside throwing bags of trash as if they were nothing but black air. He could see Sung-Lee following his gaze to the door. What did _he_ want? "Let's go up onto the bridge," William said. • • • On the very edge he stood with Sung-Lee under a wash of golden light, watching boats cutting through the darkness hundreds of feet below their feet. Her hair blew up into his face, and her arm pressed against his as she pointed excitedly at a pair of helicopters going wing and wing, only feet from each other. Surely it was no accident that she was crushing her butt into his thigh. His hands seemed to remember, as he pressed one against the small of her back. This was what a real body felt like. When he turned to kiss her, she didn't disappear. Her lips opened, even greedily, at his touch. Tongue behind savage little teeth. Her chest heaving up, and her hands weaving, rising, up his spine. A powerful wind enveloped them, pushing downriver. She smelled like poppies and Earl Grey—had she just bitten his tongue? Yes. He tasted pennies. His hands whipped around her waist and down the back of her skirt. Her hips swayed, danced a little, as she had in the bar. _O_ . . . _oh_ . . . _oh. Dreams weave the rose._ Her cheekbones were glowing. He stopped, not sure of himself now. Her dark, heavy lashes lifted, and the soft brown pupils beneath studied him, twitching. He'd forgotten, almost, what it was like to really _see_ a person. And to see someone seeing you. She traced a finger along the horn of his nose and the line of his lips. She shouted over a passing UPS truck, "When the fuck did you learn to kiss like that?" William watched the corners of her lips rise up into the folds of her cheeks. A smile like a perfect parabola. The tips of her fingers ranging . . . "Did she teach you? The girl you left me for. Last time." "I'm so sorry about that," William yelled back. "I know I should have called." But she grabbed him and kissed him even harder. There was a lull in the traffic as she whispered now, right into his ear, "Don't hold grudges. That's fear and hate, William. And besides I definitely don't stand in the way of true fucking love." "I mean, I don't know if I'd—" Except he would. It was. Or had been. True fucking love. She looked in his eyes. "You're still in love with her." "She—died," William said. He knew she knew this; their mothers talked. "Like that matters," she said. Then very seriously, she asked him, "Have you kissed anyone else since she died?" "I don't want to talk about it," he said. Then he added, "No." This seemed to be the right answer. She began kissing his neck, and he could feel her hands on him again. He turned away and looked at the other people on the walkway. Families. Couples. Faces, waists, feet. Hair on shoulders. But none were the ones he wanted. "Let's go back to your apartment," she said. "I can't," he said. "Why not?" He paused, pretty sure he didn't want to tell her he'd moved back home with his mother a year ago. He was surprised, actually, that she didn't already know, which meant that his mother hadn't been telling people about it. "They're spraying it actually. Pill flies." She kissed him again, almost angrily, "Then let's go to my place." William whispered okay, and she melted against him, and he gripped her tightly, knuckles white. They didn't speak again about Irene as they walked back to Manhattan and caught a cab to the Upper East Side. Instead she talked to him about her annoying coworkers, her ex-boyfriend Jeremy. William felt himself sweating. He wondered why he was doing this. Because he was scared of her? Yes, but there was something else. The more she touched him and the more he touched her back, the more he felt something else. Someone else. Inside her apartment, Sung-Lee was tearing William's coat off before the door had shut behind them. He liked the way her hands felt against his sore jaw. The way her teeth nipped at his ear. His tongue throbbed a little where she'd bitten it, but this pain, along with the familiar ache above his eye, was lost in the whole ache of his body now. It was dark in the room, and he couldn't see her very well, only shadows and the warm feel of her skin against his. She pulled her dress up and off, and beneath there was only cinnamon flesh and pink underwear, no bra, the silver sharks' teeth falling down between her breasts. He buried his head there and filled his lungs. Poppies and Earl Grey. Her hands were tussling with his belt buckle, fingers hooking through the loops, steering him into the room. Her black hair whipped around her head like something self-possessed, and she demanded, "On the couch." William looked longingly over toward the other side of the room, at her bed, but there was no reaching it. She almost hurled him onto the couch. Increasingly it was all William could do to simply hang on and do as he was being told—loudly and repeatedly—not sparing on the _fucks_ and the _shits_ and other things. She was purposefully screaming. There was no way he was _that_ good. Not that it wasn't kind of incredible, though. Even if it felt a bit like he was being used. Even if it was a relief on several levels when it was over. "That was nice," she said, though little about it had been anything like nice at all. He woke up a few hours later to the sound of her in the bathroom, and watched through slit eyelids as she came out, fully dressed, and quietly left the room. Six a.m. flight to Istanbul. Business class, nonstop. William walked over to the bed, finally, and pressed his face into the cool pillows. Just as he began to slip back to sleep, he felt a warm hand on his back, and the tip of a nose on his neck. Had she come back? Changed her mind or gotten a later flight? _How was that?_ came a whisper in his ear. _What was that like?_ William started up and began to roll over, but just as before, he felt a hand press against his cheek as if to stop him. He felt a flood of guilt, of stomach sick. As if she'd seen the whole thing. _Oh please_ , she said. _Don't be ridiculous. It's just sex. And if I thought you'd fall in love with Sung-Lee and forget all about me, I'd say go for it._ William felt his face go hot. He wouldn't cry in front of her, whether or not she was really there. She was quiet a moment, and he thought maybe she'd gone. _I have to say, I really miss sex_. _Ghosts can't have sex?_ _No bodies, no nerve endings._ _No fair._ _You don't know the half of it._ William felt her hand lift from his back, and he reached around to grab it but found only air and his own warm skin. _I'll find you_ , he promised. As he fell asleep, he thought he heard her saying, _I'm not lost_. ### 9 Twelve Spruce was a prewar building made of clean white brick. William located the dusty buzzer near the door and tentatively pressed 4R. He knew it was crazy, but he wanted to try. If no one was home, then fine. But to his surprise, the door shook and unlocked. Across a dark lobby, he climbed into a creaking old elevator that took him slowly to the fourth floor. There he soon found 4R, with a mat out front that said WELCOME. William knocked at the door and waited. A few moments later someone answered. An old Hispanic woman with wide wrinkled circles around her eyes. For a brief moment, though he knew she was long dead, William imagined it was Grandma Fiona. Behind her the sound of rapid gunfire and shouting in Arabic came from the television, followed by a trumpeting of transition music and the opinions of an unseen news anchor. He took off his hat. "Hi. I'm sorry. You don't know me, but a friend of mine used to live here in your apartment. And I was wondering. Could I come in for just a minute?" There was, he knew, no earthly reason this woman should allow him, a total stranger in a slightly disturbing French punk rock T-shirt, to enter her home, but to his surprise she moved away from the door without a word. "My name is William. Um . . . _Mi nombre es_ William?" She nodded and walked back over to the big white couch in front of her TV. The floor was covered in scattered trucks and balls and other children's toys. There were religious paintings on the wall, a Madonna and Child and a few Christs on crosses. Everything seemed to have been recently remodeled. The floorboards were new and fitted together. The walls were white and bumpy, in the way of all New York apartment walls, painted over with each new tenant. If only he could peel it back and see underneath. Would there be smudges and tea stains and fingerprints and stray flecks of oil paint that had once been Irene's? William moved lightly into the apartment, wondering which of the rooms had been her bedroom. He passed a sideboard table that was being used as an altar. There were photographs of children and grandchildren to be prayed for, and in front of those an arrangement of candles and little statues. A bowl for holy water, and a smaller one with something grainy inside like salt. There was a very nice set of rosary beads carved from a red wood, just next to a little incense burner covered in ash marks. William stood there and thought about his mother, who would be back at home by now, putting away the tools of her ancient trade: apples and rice cakes and money and tiny paper figures. Iron chains and small boats that she'd waved in the air. Drums and pieces of paper drawn now with letters and symbols. Science and medicine were good things, his mother had told him, growing up. To heal diseases, to mend bones, to tend to the sick, the elderly, and the newly born. To do research on AIDS, as Charles did, and to peddle pills and vaccines like Sung-Lee—these were noble things. And lucrative, not to forget that. But a _mudang_ treated something else. Something that couldn't be reached with chemicals or seen on X-rays. The thing that causes illness, the thing that comes before viruses and bacteria, even DNA. _Uhwan._ What she called "misfortune" and others might think of as simple "bad luck," though it was far worse than that when _uhwan_ began to creep into your life. Just a few things would go wrong at first, but well within the realm of expectations. A setback here, a letdown there, but you keep up, mostly. Bad things happen, but don't they happen to everyone sometimes? Only like in an undertow at the beach, you are being pulled gradually in the wrong direction. You correct, but you overcorrect. You flail, but this makes it worse. Things fall apart, and you hurriedly glue the pieces back together and cannot ignore the resulting cracks. There isn't time to do more because other, larger things are going wrong already. Medicine cannot cure the problem. Psychology cannot resolve it. One day you wake up to discover that where once there was one thing wrong, there are now hundreds. Far more is wrong than right. Because misfortune is a plague that begets plagues. What starts as a tiny imbalance creates a ripple effect that can take down empires. What string of ever-worsening misfortunes preceded Chongso's accident? What had made Mrs. Kim decide to punish him that morning? What had led him to dare to sneak out on his own to buy the comic book? What had the driver been doing instead of watching the road? No disaster is a singular incident. It is the tsunami that follows the swelling tide. It is the nuclear meltdown that begins when a dozen fail-safes have failed. Before the chemo, before the cancer, before the cell mutation, there is the misfortune. _Uhwan_. William felt for the small lump in his back pocket, beneath the address book, and fished out the little Aqualad figurine. One final time he studied. He liked to think it was part of some thirteenth art piece that she'd never gotten to make. He liked to think it would have had something to do with him. Only then he thought that, really, as much as all the pieces had to do with death and disappointment and her friends, they also had something to do with him, her last love. Gently, he set the little superhero down on the altar beside the candles, and said a quiet prayer for Chongso Kim. William moved through the apartment, half expecting some dog or husband to appear and kill him. He had hoped—he didn't know. That he'd walk in and find Irene there, sitting on the couch beside Grandma Fiona, book on her lap, twirling her hair, paint on her arms. That she would ease her body around his as he lay down and touch his hair. That he would call her No Ears and they would talk about Yesterday and Today, with no mention of that foul uninvited guest Tomorrow. If he could have just one more day, he thought, like the first one. Before she'd heard back from the doctors and begun dying. If he could just have one more day when nothing was wrong, when time could be wasted, because there had still been so, so much of it out there. And then he saw, through the window in what was now a room filled with old boxes. It was the exact view painted in the back of his old book. The Brooklyn Bridge. Cables arching up like the frame of a great harp, vibrating with the whispered secrets of its crossers. This was the window she'd looked out of each night as she fell asleep and each morning when she'd woken up. As he lay there, he imagined he could hear voices traveling up the strings and through the steel, flickering between the cars and in the thump of the bicycle wheels against the wood. He saw the roadway rising and falling, like a wave out on the sea. It took him a moment to remember that he hadn't smoked anything all morning. This wasn't that. All those voices, all those wheels and feet were coming together into a harmony. A simple, perfect note that resonated with the bridge itself and the churning river beneath. Echoing with the cries of the captains of the great wooden ships, just setting sail from South Street, casting off for the seven oceans, to journey in dreams. William watched in awe as the notes moved through the roadway like a sine curve, an octave that caused bricks to detach one at a time from the towers, a flat foot on each shore. Into the blue sky, cars and people flew like a peppering of seagulls, up and up and never down. Up into the crystal cotton of the clouds. Light gleamed off their wristwatches and hubcaps and handlebars. They became fins in the ocean of sky. Brick by brick, the bridge rose into the air, pulling the river with it, drop by drop. Atlantis rose. Land of tomorrows and yesteryears. Once there was a continent that sank into the sea. _Farewell!_ he cried to the people as they vanished. Trillions of them, it seemed, as the entire bridge fell into the sky. ## THE WEDDING OF SARA SHERMAN AND GEORGE MURPHY Sara Sherman ran between the rooms of the bridal suite, lifting her dress so it wouldn't sweep the Waldorf's tapestry rugs. The dress was still an eighth of an inch too long, even after she'd told the lady at Nelson's to shorten it at both the six-week and the one-month fittings. So now the lace along the edge had accumulated a faint grayness as she rushed from the front door—where she'd just received an update from Zacharie, the hotel's event coordinator, about the situation with the chairs—back into the bedroom where her sisters, Adeline and Eddy, were converging on George's mother, intent on taking down the hair that the stylist, Erikah, had spent two hours putting up that morning. Barely had that been handled when she caught her own mother plucking "excess" baby's breath from the bouquets. Sara redirected her into checking on whether the Krazy Glue was setting properly on George's Grandma Pertie's snapped heel. And did anyone have an approximate GPS location on his older brother, Clarence? Who, despite having strict orders to stay in Midtown, had sneaked off that morning to visit the Cloisters near Fort Tryon Park, only to wind up getting stuck in a cab on the West Side Highway behind some kind of gubernatorial motorcade? For all Sara cared, Clarence could rot on the asphalt overlooking the Boat Basin, but of course, this actual Mensa member had decided it would be a good idea to take the two wedding bands with him. She was interrupted by George's little niece, Beth, the seven-year-old daughter of George's younger brother, Franklin (who at sixteen had been absentminded about protection at a post-prom party). Sara liked Beth immensely, for she was apparently the only other responsible human being in the entire bridal suite. Beth had been fully set in her flower-girl dress, with hair done and shoes on, for over two hours now. Now she held Sara's phone in the air calmly and said, "It's ringing." Beth was in charge of fielding calls and beating level twenty in _Plants vs. Zombies_. Sara looked at the phone: it was Minister Thaw, who had already left two messages that morning. He had conducted their required premarital counseling sessions, where they'd had plenty of time to delve into the minutiae of Episcopalian dogma and how it differed from George's Catholicism and "What about the children?"—and _now_ he was bringing up reordering all the readings, even though the programs had already been printed and the whole thing had been successfully rehearsed the night before. _Stay the course!_ she wanted to yell into his fuzzy little ears. _We're almost through this!_ Instead she rejected the call, handed the phone back to Beth, and called out to the bridal suite, "Does anyone have the chalk?" Again, only Beth knew the location of the Crayola box and began helpfully whitening the gray hem of the wedding dress. "Thank you, sweetie. And do you know where Adeline is?" Beth didn't. No one nearby knew. Perfect. Not only had their mother guilted Sara into asking her uptight older sister to fill the maid of honor post, and not only had Adeline then thrown a spectacularly dull bachelorette party (appletinis and feather boas), but she had already abandoned Sara and the day's proceedings. As unhappy as Adeline was to leave the safety of Gloucester for even one weekend, their younger sister Eddy (short, since always, for Edwina) was being no better about being away from her ashram. Eddy had come to town with the uninvited George-Harrison Zimmerman (first name, legally, "George-Harrison"), whose hair was both longer and shinier than Sara's had been at any point in her life and who had brought his guitar "just in case." Sara had a hard time not fixating on how much easier all this would have been with Irene at her side. She didn't trust anyone else's opinions on jewelry, decorations, or invitations. At every turn in the planning, she'd wanted to call up Irene about the wisdom of champagne-colored heels, or get her input on calligraphers. And of course, here she had two perfectly good sisters, only the two of them combined couldn't begin to fill the opening left by her absent best friend. "I hope you don't think you're wearing Grandma's pearls" was Adeline's only contribution, while Eddy wanted only to remind Sara that the tuna on the reception menu was being dangerously overfished. Sara had found herself talking, half to herself, half to the absence of Irene, all throughout the planning process—and now that it was over, and the wedding was happening, it seemed inconceivable that Irene wasn't there to see it all through. Irene's aesthetic was the driving force behind the whole event. In going through her things, Sara had found a few of the old guidebooks they'd bought in college when first planning their trip to the Côte d'Azur. Boom—here was the color scheme: the turquoise waters off St. Tropez, and the rose rooftops of Monaco. Bam—there was the font: a vintage script used by the Hotel Negresco on its dinner menu. Sara found it impossible to believe that she and George would be there, for real, in just twenty-four hours: reading under the bold-blue-striped beach umbrellas at Cannes, climbing the spiral stairs of the elegant fairytale castles of Antibes, tossing a pair of dice at a craps table in Monte Carlo. All of the Shermans had chipped in to send them first class. Sara tried hard to remember this, and to let her gratitude balance out Irene's absence. She had already planned out every detail of the trip, from what she would order for dinner at Le Chantecler in Nice, to where she could rent a sun umbrella in Théoule-sur-Mer, and the rules for baccarat when they visited the Place du Casino in Monte Carlo. And up on the very top of a mountain, in a sun-drenched spot called Pointe Sublime, she and George would scatter Irene's ashes as she'd asked them to, and it would be done at last. Sara couldn't stop dreaming about it. Adeline called from the next room, "The photographer says he's ready for you!" "Is George up there already?" Sara shouted back. "He didn't say!" "Has anyone heard from him yet?" Silence. Sara gathered her gown and moved slowly toward the front door, with the sisters and mothers all rushing over to send her off enthusiastically, to tell her she looked beautiful, to remind her how lucky she was. Sara made sure Beth had the folder with the marriage license in it and headed to the freight elevator (the only one with roof access). She was sure her sisters were already pulling bobby pins out of Mrs. Murphy's hair and her mother was back to editing the bouquets. She turned back to the crowd of turquoise-satin bridesmaids at the door. "I need everyone else up there in _ten minutes_. Moms, aunts, cousins, brothers, _sisters_. _Both_ families. Bouquets and boutonnières. _Shoes_ on." That one was for Eddy, who seemed to feel that wearing closed-toed heels somehow made her a party to systemic gender marginalization. "Aye-aye, captain!" Eddy saluted back. "Go, go, go!" Sara did a last check of her hair and makeup in the reflection of the closed elevator doors. Who _was_ this girl in the cold steel with the cupid's bow lips and the Clara Bow eyebrows? It was all wrong. Why had she let the lady do it that way? The elevator doors opened. Inside, a small Hispanic woman hid behind a cart filled with fresh towels and cleaning products. A little radio was blaring some sort of sermon on a tinny Spanish station. "¿Dónde está, oh muerte, tu aguijón? ¿Dónde, oh sepulcro, tu victoria?" "Oh!" the maid screeched happily, covering her mouth with both hands, in the universal language of bride excitement. "¡Eres tan bella!" "Gracias," Sara managed. In just an hour Sara would be standing up there, holding George's hands in front of Minister Thaw and listening to him read from First Corinthians. _Love is patient, love is kind._ And she would nod mindfully as Thaw rattled off his list, of all the things that Love Was Not: envious, boastful, proud. And with her wearing the most beautiful dress she'd ever worn, on the most expensive single afternoon of her entire life. The rest of the verse was practically a checklist of how Sara had been feeling all year. Love was not: dishonoring others, being self-seeking, or angering easily. Check, check, and check. Love keeps no record of wrongs? Sara had a whole spreadsheet of them. Who hadn't sent a gift, and who had brought a plus-one without asking, and who had demanded that they be married in a church in the first place, and which cousin wasn't coming despite living less than three hours away, and which aunt had to be cut off after two by the bartender and . . . Love doesn't delight in evil but rejoices with the truth. It always protects, always trusts, always hopes, always perseveres. Love never fails. The radio piece ended, and soon a commercial began. Sara recognized it from the first somber piano chord. She had been hearing it everywhere all week: in cabs, at her dentist's office, at the gym. At this point she could practically recite it from memory. "At Mount Sinai Cancer Center . . . the patient is the center of our universe. Like Sue, who thought it was all over when her liver cancer came back. 'I came to Mount Sinai, and right away I was working with a team of specialists in _my_ type of cancer. Providing the very latest options, including personalized therapies, just for _me_.' Today Sue is cancer-free, thanks to specialists like Dr. Atoosa Zarrani . . . 'We live for the chance to help people like Sue. My colleagues and I worked hard and together . . . we cured her.'" _Well, good for fucking Sue_. Sara wanted to snap the antenna off the piece-of-crap radio and drive it through the speakers. Then there was a hand on hers. "No cry," the maid was saying. "You look so beautiful! _Happy_ day!" Sara coughed as the elevator came to the twentieth floor at last, and the maid pushed the cart away, smiling and crossing herself and wishing her well in Spanish. The doors closed, and as Sara went alone up the last few floors, she tried to fix her mascara in the reflection of the emergency call box. Steadily she felt the elevator easing its ascent, and she looked up expectantly at the sound of its cheerful ding. The doors stayed shut as things settled. She held her breath. Crazy how, after almost ten years together, just a day away from George, and she was as excited to see him again as she had been that first day, waiting for him to come down from his dorm to pick her up for the movies. At last the doors opened onto the roof of the Waldorf Astoria Hotel. For the first time all morning, she smiled, as she scanned the wide blue cloudless sky and all the rooftops of midtown Manhattan for George. • • • In George's dreams he saw a spinning wheel of hydrogen gas, thirty-six billion miles across, beginning to collapse under its own immense weight. Though it had been spinning for over one hundred thousand years, its end had come. Seismic shocks ripped through the icy disk, just ten degrees above absolute zero. He watched it radiating microwaves and great streams of plasma—solar winds that emanated in all directions at once. Ninety-nine point ninety-nine percent of these rays traveled on through emptiness forever, reflecting off no other planets or asteroids or matter of any kind, being sucked into no black holes or other gravitational fields, crossing paths with no other particle. Turbulent storms moved along the circumference at speeds greater than sound, as the wheel contracted like a great iris in space, years passing in moments, the core becoming hotter and brighter as it shrank. Faster and faster, the humongous orbit of gaseous molecules, ten times larger than our whole solar system, caving further and further in on itself—until in one spectacular and sudden stabilizing moment, it all stopped. And everything became still in the space around this new, glorious star. And then George woke up alone on an unfamiliar couch, vaguely aware of being completely naked. Feathers of all colors drifted through the air. Hot pinks, neon greens, and bruised purples danced a lazy _pas de trois_ around the martini glasses on the coffee table, sticky with the day-old residue of sour apple Pucker. The television was on, but muted. George's arms were wrapped around a gray lamp that seemed to belong on the side table. He'd heard of waking up with lampshades on your head but never cuddling with the lamp itself. Slowly he remembered that he was in the hotel room that Sara and her sisters had used the night of the bachelorette party. After their spa day, they had come back here to throw on their slinky dresses and high heels and feather boas before the big bar crawl. The boys had thrown George's bachelor party that same night down in Atlantic City and had been so late getting back the next day that they had gone directly to the rehearsal dinner without stopping into the room to see that it had, clearly, never been cleaned. George set the lamp down on the ground and looked around the room, to the extent that he could without moving his head. Clarence and Franklin, his two brothers, weren't in view—presumably they'd taken the bed in the next room. And Sara's sister's boyfriend George-Harrison, whose idea it had been to go out for a few more after the rehearsal dinner, had his own room down the hall. Which left only Jacob. Had he gone home, or was he around somewhere? George still couldn't shake the feeling that Jacob was only acting as if nothing were wrong, but maybe nothing _was_ wrong. Supposedly he was turning over a lot of new leaves. He was taking night courses at Pratt on Tuesdays and Thursdays to earn his master's in art therapy. Sara claimed he was writing again; she had been badgering him to read something at the wedding, but he insisted he had nothing new. Taking a deep breath, George lurched up from the couch—just like ripping off a Band-Aid, he thought. As with a Band-Aid, he immediately felt a searing pain. It was behind his eyes, in his ears, and climbing up his brain stem. The entire room pulsed and blurred. It took almost everything he had to keep himself from lying back down again—but no, he had to get up. This was his _wedding day_. Everything would finally change. Sara would ease up on the interval training. He'd be able to focus his energies on the future—their real future—and make mornings like this (was it morning?) a distant memory. Tomorrow they would be on their honeymoon, and afterward these yesterdays would be well behind him. Yesterday. What an odd kind of hell that had been, to return from three sweaty hours in traffic on the Garden State Parkway, smelling vaguely of the baby powder that the strippers (apparently) used to keep themselves from sweating on the poles, finding glitter that had once been attached to the nipple of a woman named Roxxxy and was now somehow (he knew how) _in_ side his left nostril. Man truly was a disgusting animal. He'd never felt more so than he had that afternoon, changing in the moving car in front of George-Harrison and walking directly into a Michelin-starred restaurant to dine with his parents, for whom a racy evening was watching a Robert Redford movie on cable, and all his soon-to-be in-laws, and to look the woman he loved right in her lovely, dark eyes as she asked with a knowing smirk just what exactly he'd gotten up to. Bless her. Absent any shred of doubt that the debauchery would mean anything to him. Knowing that whatever occurred couldn't touch what they shared. He watched a purple feather creep along the ceiling and get caught in a downdraft near the balcony and go surfing down the drawn shade toward a corner on the floor. He took a deep breath and tried to walk. Amazingly, he didn't fall over. Now he could see the clock in the kitchenette—and that he had just under forty minutes to clean himself off and get to the roof for the photographers. He grimaced. Not a lot of time—but he just needed to put one foot in front of the other. Sip some of the ginger ale from the minibar. Maybe eat a cracker if he could. Keep a couple of aspirin down. Get to a shower. As he set about these tasks, he felt sick in every conceivable way. He was used to hangovers, of course, but lately they had been different. Now the hangovers started during the fun. It used to be that only with the coming of the morning did he have any regrets. But steadily the distance between the during and the after had collapsed. Now he regretted things even as they were happening or even _before_ —knowing that they would happen, because he lacked the will to stop himself. George hunted for the remote control but couldn't find it, so he eventually walked over to the TV and turned it off by hand. No mystery as to what he'd been trying to watch, drunk and butt-naked in the middle of the night, cuddling with a lamp. He'd left it on Televisión Española, which aired three reruns of _¡Vámonos, Muchachos!_ every night beginning at one a.m. The girls had discovered the show on their own, years ago, though back then he had never really understood the appeal. It was a multicamera sitcom featuring a group of six twentysomething friends in downtown Mexico City. Nobody else he knew seemed to have ever heard of the show. It didn't even broadcast in HD, further contributing to George's sensation that he was traveling back in time by watching it. It felt unmistakably like a 1990s show, in the vein of classic NBC Must See TV. Mostly the _Muchachos_ characters seemed to have no jobs to prevent them bantering at the spacious Torrefacto café, with its pink and blue mod-style couches and patterned orange walls. The muchachos were Santiago, a nerdy orthopedic surgeon who had trouble talking to women, despite being a born romantic; his handsome roommate, Tomás, who worked at Torrefacto (though he was rarely seen actually working); the beautiful Constanza, a high-maintenance TV weathergirl who was in a tumultuous relationship with Tomás; Isidora, the architecture graduate student who shared Constanza's loft, an utter and charming mess of a girl, perpetually disorganized and overwhelmed by life; her brother Aarón, who played guitar with a struggling band called La Palabra that was always about to get its big break; and Renata, by far the quirkiest of the gang, a speech therapist with her own sporadic practice, though she was so childish at heart that George wondered how she stayed in business. She and Santiago had a will-they-or-won't-they tension that couldn't really be characterized as sexual. The humor was all very PG: gags involving talking parrots and lost purses and cases of mistaken identity and sinks overflowing and letters being misaddressed. Someone was always getting locked out of an apartment while wearing nearly nothing. They were all always running out of minutes on their cell phones at _just_ the wrong time. There had to be hundreds of episodes, and from what little George could find online about it, the show was still being made, airing in Mexico a year before rerunning in America. George had first come across it while trying to clean up the DVR. Sara had left the series on the record list, and over the course of the first six months, they'd amassed _fifty_ _hours_ of episodes. She couldn't bring herself to watch it anymore and had asked him to delete them all, but George found himself unable to. Instead he began watching them, late at night, alone. He guessed he was sleeping only three or four hours a night, most times. He didn't see how it was possible to still be alive on so little sleep, but he managed to get through the day, bleary and exhausted, only to get into bed and find himself wide awake. He would lie there in the dark until sound-sleeper Sara was out, and then get up and wash dishes, make himself an Old-Fashioned, reorganize the books and DVDs, water the houseplants, and watch an episode of _¡Vámonos, Muchachos!_ while drinking a second Old-Fashioned. Trying to settle his stomach, George chewed some stale crackers he'd found in the hotel kitchenette. His phone was ringing on the counter. A miracle he had drunkenly managed to plug in his charger. Allen's face appeared on the screen, and George rejected the call. He couldn't believe Sara had insisted on inviting him. Not only that, but she'd also made Rob bring him to the bachelor party! It was during that evening, when George had drunkenly done all the things that passed for bonding—playing blackjack together, stopping at Gary's SuperLiquor to buy enough Pabst to drown a team of oxen—that Allen had asked him point-blank if he'd ever been with a woman other than Sara. (Where was Jacob when you needed someone to throw a little cold water on the situation?) George had been too obliterated by cheap beer and the relentless throb of the synthesizers to lie. Knowing it was all over his face, he shook his head. "That's so _fifties_ , yo!" Allen had screamed. "Shit, you're like my fucking _grandparents_." Like George's fucking grandparents, too, he supposed, or even like his sleeping-in-separate-bedrooms-for-the-last-twenty-years parents. Allen didn't seem likely to drop it. "What if there's something weird down there, and you don't even know it because you've never seen any other ones?" George made a face. "I took AP Biology, Allen. I have an Internet connection." Then he gestured up to the stage at the current dancer, who was bottomless, just as advertised. "I know what a—I know what one's supposed to look like." After briefly clutching his head in his hands, Allen threw an arm around George. "That's craziness. I mean, I just couldn't. It's—evolutionarily counterproductive!" "Oh, you're a biologist now?" "Look. The male of the species is naturally drawn to polyamorous behavior, and the female is _structurally_ inclined toward birthing and child care . . ." George didn't hear much after that, partly because of the bass coming off the stage and partly because he had heard this all before from Allen, who was fond of sharing stories of his conquests, late at night when they were up editing grants, or poring over thousands of data points in the lab, sometimes even in the middle of the day just walking down the halls at the institute. Allen was an aficionado of all the new online dating sites: Match.com, OKCupid, Chemistry .com, ScienceConnect. He even had an app for his phone that let him scroll through the profiles of nearby available women and indicate with a swipe of his finger if he was interested in them, as if he were seated at some sort of sex buffet. Sara said she couldn't figure what on earth these women saw in him, but according to his locker-room talk, Allen was getting laid left, right, and center. George suddenly felt a profound desire to know: "Is it really so great sleeping with all these different people?" Allen paused as if, for an instant, he couldn't comprehend the question. Then, incredulous, he responded. "Man, it's _awesome_. I—George . . . you're making me sad. I'm sorry. This is your night, and I'm happy for you and Sara and all but—what a question!" George stopped listening. Jumping into bed with some woman he'd only just met seemed pleasant in theory but awful in practice. Not just being naked in front of a stranger, not just having his anatomy and performance evaluated by someone whose standards were unknown, not even the awkwardness of what to do with all that you'd used up in one another afterward, but mainly just the idea of being that close to someone he didn't know crucial things about: Middle name. Best friend's name in middle school. County of birth. Number of siblings. Feelings about Elvis. Preference for or against nuts in brownies. Ability to ride a bicycle. Major allergies. Burial locations of childhood pets. Most embarrassing moment of adulthood. Approximate number of pairs of shoes owned. Use of contact lenses. Song to be played at their funeral. George supposed he had always been a monogamist. Even back in kindergarten he had gotten in trouble. A meeting had been called with his mother and Mrs. Remington. Young George had been systematically working his way through the girls in the class, asking them each to marry him under the swing set, with a ring made out of a twisted juice-box straw. And as an adult, now, when he did spot a beautiful stranger, riding home on the T at night, he never fantasized about jumping into the empty conductor's cab for eleven anonymous minutes in heaven. No, he'd imagine beginning some awkward conversation: she'd drop something, or he'd trip over someone else's umbrella, and they'd chat amiably for a few stops about something in the news. They'd discover some shared love of something—the fresh berry crème brûlée at Finale, or how the Gardner Museum still left blank spaces on the walls where a half dozen paintings had been stolen in the 1990s, or the six-story fish tank at the New England Aquarium. And then the fantasy would fast-forward. Some weeks or months would go by and, by chance, George would find himself alone one rainy afternoon, walking by Finale, or the Gardner, or the Aquarium. And there she'd be. They'd see each other by accident. Remember. Laugh. Act like old friends. Go to grab a cup of coffee. But this wasn't the weirdest part of the fantasy. Not in the least. The weirdest part was that always, he'd imagine that somewhere in those intervening weeks or months, something would have happened to Sara. She'd have left him or been in a terrible accident. It was usually nothing specific, just that she was gone, and he was sad. The whole thing was awful—but it was the only way he could clear his conscience so the fantasy could continue. Even in his wildest dreams, he couldn't fathom cheating. George tried to forget all this as he climbed into the hot shower. Fifteen minutes left to go. Shampoo. Conditioner. He couldn't find his toothbrush, so he used a fingertip to scrub his teeth. He knew Sara would tell him to just throw up. He considered jabbing his finger back a little farther and seeing what happened, but the thought of it was somehow even worse than the thought of his belly remaining full of last night's post-rehearsal tequila shots. If she'd been there, he would have done it. To show her that, despite his poor decision making the night before, he was now, that morning, 100 percent committed to getting things back on track. But without her there, he couldn't manage it. There was so much he couldn't manage without her. He bent down right there under the stream of water and prayed that he would never have to. Sick unto death, he thanked God that he was going to marry Sara in just a couple of hours. Through the fog in the bathroom, he could see the clock on the wall. Ten minutes left. He closed his eyes, let the hot water run over him, and tried to picture her body—they had been so busy in the lead-up to the wedding that it had been a few weeks since they'd slept together. She'd been working so hard to fit into her dress that he'd begun to almost not recognize her. Truth be told, in the past two years things had slowed down considerably in that department. Which was his fault, not hers. Just as he couldn't bring himself to relax and enjoy a cold drink or a long walk or a night out, he had been struggling to keep his head in the room when he was alone with Sara as well. Clothes off or on, really. When they were having dinner or watching TV, he was aware of always being halfway somewhere else. It used to be the other way around—whenever he was away from her, she was all he thought about. Of course he knew that these things changed over time. People went from being lovers to companions over the course of a relationship. He just didn't think that would start to happen before he turned thirty, before they'd even said, "I do." But after what they'd been through—essentially managing a hospice out of William's living room—he felt as if his twenties were already far behind him. What still felt right on top of him was the loss. Irene's absence. At night, while _¡Vámonos, Muchachos!_ was on commercial breaks, he would sometimes stumble over to her urn on the mantelpiece and clink his drink against the curved metal handles as if to say hello. Occasionally he'd lift it off the fireplace and carry it over to the couch so it could watch with him. Sara had _not_ been happy, the first morning she'd found him there like that. Soon after this incident, they'd agreed it was time to scatter the ashes. Jacob had told Sara how Irene had asked to be scattered in France, and she'd agreed they ought to do it on the honeymoon. There was a spot in the mountains nearby where the cliffs rose two thousand feet above the most beautiful turquoise water. Sara knew that one of Irene's greatest regrets was never having left the country, and here was their chance to rectify that. George didn't know if it was really the right move, but he wanted to make Sara happy, and he wanted to get things back on track. There would be the wedding night, in the bridal suite, and there would be ten more beautiful days in a French seaside paradise, where absolutely nothing could go wrong. He turned the shower off and stepped out, getting his breath back, beginning to feel again, the top layers of his sickness lifting, leaving only the deeper part behind for him to live with. Towel around his waist, he sneaked into the bedroom, only to find that his brothers weren't there. The bed was made. Their tuxedos were gone from the closet, and there was a note on the dresser saying that they were going to find some breakfast and would meet him on the roof. The note ended with _Where's Jacob?_ George grabbed his tuxedo out of the bag and began to assemble everything. He had seven minutes. He slipped on the boxer shorts with hearts on them that he'd bought for the wedding, followed by a pair of thin black socks, and then he got his arms into the starched white shirt. As he did the buttons, he roamed around the hotel room, watching the molted boa feathers dancing. It was as if a whole cast of _Sesame Street_ characters had disintegrated in there. George wafted his arm in the thin space, sending a flurry of colors up into the air again. They fell like confetti. He slipped on the tuxedo jacket and looked at himself in the mirror. It was perfect. As if nothing had ever happened. He walked to the shade that he'd drawn over the balcony doors, wanting to let some light in before he left. There was an explosion of reds, purples, yellows, greens, and blues as the shade pushed the air away. And there, on the other side of the glass, he saw Jacob, sitting at the patio table, already groomed and fully dressed in his tuxedo. He looked vaguely miserable, tapping the tip of his pen at the corner of a piece of hotel stationery like a crazed woodpecker. He looked up at George and mouthed, "What time is it?" George slid the door open. "Five minutes to one." "You're supposed to go up for photos." "Yeah, I know," George said, standing back and turning around for Jacob to admire. Jacob tapped the pen again. "I was supposed to wake you up an hour ago." "It's okay. I got up." "Sorry." "What?" George couldn't remember ever hearing Jacob say that word before. "Sorry," Jacob repeated, looking down at the paper. "I got caught up in this." There on the paper, he could see a poem—or the rough guts of a poem at least—covered in cross-outs and inserts and arrows shifting things from here to there. Jacob looked at the page in annoyance. "What's a word that rhymes with _fellatio_?" George grinned and, before taking off for the elevators, reminded Jacob to be up on the roof in fifteen minutes for the group photos. He had three minutes to spare. Sara would be coming up just behind him. He hadn't felt this happy all year, knowing he wouldn't disappoint her. • • • Everything came together just as it was supposed to. The rooftop of the Waldorf was wide and clear, and the views of the city in all directions were nothing short of jaw-dropping. It wasn't too windy or too cold. One of the first warm breezes of the year blew through the assembled Murphys and Shermans that day. Everyone behaved. Brothers and sisters fell in line; mothers hugged each other; everyone smiled. Whatever problems and dramas and concerns had existed before were forgotten. Later the photos would show George holding a glowing Sara in his arms and she looking up at him with absolute, pure adoration. They kissed with a sea of high rise towers behind them. They danced to invisible music; she spun weightlessly. Hand in hand they walked away, smiling back over their shoulders. Her dress was white all the way down to the hem, where it appeared to float just above the ground, as if by magic. She buried her nose in the bouquet of white roses, the shadow on her eyelids echoing the turquoise in the peony buds. In the group photographs, all six bow ties were straight, and every heel and hem was the right height, and everyone's hair stayed where it was meant to stay. The photographer told jokes like "How many tickles does it take to make an octopus laugh?" ("Ten tickles"), which were so terrible, they actually were funny. And when it was all over, they crowded into the elevators and went down to the front of the lobby, where two white limousines were waiting for them. Every parent, aunt, sister, brother, grandparent, and friend was ferried to the church in under two minutes. Enormous, majestic flags rippled over the church entrance as everyone piled out of the limousines and moved to their stations. The guests, who had been arriving for the past half hour, were being ushered in smooth rotation, each oohing and aahing over the programs, especially the floral trellis detailing that Sara had created with the designer, based on a 1920s Heiligenstein vase. The lettering on the inside wasn't, as George had feared, unreadable in the dimmer light inside the church. In fact, it exactly matched the brick face inside the sanctuary—and the Oldenburg font choice was a real winner. And there was Clarence! Made it with ten minutes to spare. He'd actually climbed out of the cab he'd been stuck in on the southbound lanes of the West Side Highway, crossed the northbound lanes on foot, and scaled the six-foot retaining wall along the park so he could catch another cab going south along Riverside Drive. He arrived with both wedding bands in his pocket, as safe as could be, and when the organ began to play the processional, he walked calmly up the aisle with Adeline on his arm, followed by the rest of the wedding party. St. Bartholomew's organ pipes—the oldest in the city—were imperious and soft at the same time. George could feel their vibrations in the air around him. His mother looked lovely, not unlike Audrey Hepburn, with her hair still up in its twist, as she walked him to the altar. There George felt something overhead that he hadn't felt in some time, hard to describe as anything but a not-aloneness. As if the George beneath the George that everyone could see were in good company. It was like tasting that bottle of wine on Shelter Island, or even like seeing that dead body for the first time. A flicker of something beyond what was known and measurable in the universe. But soon all thought of it was gone, as he saw Sara coming down the aisle with her father. Warm sunlight washed across her face, the stained glass glinting up above her. Her father was crying a little, just the right amount. She willed herself not to look over again, knowing she would immediately begin crying also. She fixed her gaze on George, who looked magnificent at the end of the aisle, towering over the hunched and sleepy-eyed Minister Thaw. Minister Thaw had some things to say. Sara could barely hear them. Something about there being this small village in Italy somewhere that had a silver statue of Saint Bartholomew. During his feast they routinely carried the statue around the village. One day it became mysteriously heavy and the villagers were forced to set it down. Just then the rocks ahead of them collapsed into the valley. The very ground they had been about to pass over completely disappeared. Had it not been for the sudden miracle of the statue's weight, everyone in the village would have died. Then many years later, the village was captured by enemy raiders who sought to pillage anything of value. When they came to the statue, however, they found it was light as a feather. Thinking it was a fake, they let it be. This, according to the minister, was a perfect metaphor for the miracles of marriage. It could sometimes be surprisingly heavy, keeping the couple grounded—and yet at other times it could be as light as air—invisible, unfettering, even uplifting. And just as God had protected the faithful villagers, so would He protect his faithfully wed. Sara could _see_ George almost wanting to argue with the man right then and there—how could he claim that God, with any great consistency, protected true believers? You couldn't cherry-pick miracles when they made for a nice homily. That was just bad methodology. But no, he was letting it go—just a cute little eye roll to Sara, as if to say _they_ knew better, and nothing else mattered. She squeezed his hands. This was happening. This was really happening. Her sister was standing up and reading the passage from _The Velveteen Rabbit_ : "'Real isn't how you are made,' said the Skin Horse. 'It's a thing that happens to you. When a child loves you for a long, long time, not just to play with, but REALLY loves you, then you become Real.' 'Does it hurt?' asked the Rabbit. 'Sometimes,' said the Skin Horse, for he was always truthful. 'When you are Real you don't mind being hurt.'" Franklin was next, with good old Psalm 121. "I will lift up mine eyes unto the hills, from whence cometh my help. My help cometh from the LORD, which made heaven and earth. He will not suffer thy foot to be moved: He that keepeth thee will not slumber. Behold, He that keepeth Israel shall neither slumber nor sleep. The LORD is thy keeper: the LORD is thy shade upon thy right hand . . ." Now Minister Thaw was recounting Christ's first miracle, performed at a wedding in Galilee. That word always made George think of the song, "Puff the Magic Dragon" who had "frolicked in an autumn mist in a land called 'Honah Lee'"—but as a boy he had misheard it and had for some time believed that Puff was from northern Israel. He looked up at Sara, and he could see her lips were moving, mouthing the words to the song she _knew_ was in his head in that moment. They smiled, and Sara wished, a little, that they could recite the song instead of the vows that the church required, and she hoped this wasn't as sacrilegious a wish as it felt. George's eyes bugged a little, as if to ask if she could believe this was all really happening, and hers bugged back as if to say that she couldn't, but it was, and that through everything that had happened, over all the years, they had made it here. Of course none of the guests could see any of this happening. They fanned themselves with programs, strained to hear, and subtly adjusted their clothing. Grandma Pertie unwrapped a lozenge midway through the vows, irritating more than a few people nearby, but it was quickly forgotten. There was an audible buzz when Franklin Murphy got a text message from American Express, concerned about that morning's suspicious $103.22 breakfast charge—he hadn't notified them that he would be traveling out of the Midwest. Beth forgot herself at one point and could be heard softly humming the theme to _SpongeBob_. Jacob, standing to one side in the front with the other groomsmen, was mentally rewriting his poem and wondering what the hell William was doing wearing a fedora in the back row. Then there was a sudden blasting on the organ pipes, and a cheer that rose through the pews, with people flying to their feet in applause, for Minister Thaw had just told George that he could kiss his bride, and (with gusto) he was doing so. Beaming, proud, resilient: they came then down the aisle arm in arm, waving and smiling at everyone. Both of them had assumed that since they had known each other so long and had lived together for years already, the moment would feel no different, really, than a million prior moments—but it did. They both were a little surprised, but there it was. A strange sense of having expanded. As if they had been, until now, living in two neighboring apartments and finally had knocked down the wall between them. They had no receiving line—no time! It was right on back to the limousines, where the first round of champagne awaited them. Sara had arranged for four bottles of the more expensive Krug NV Grande Cuvée Brut, to be shared by the wedding party members only, then stepping down to the more reasonably priced Moët. They went around the corner and up the three blocks and back around to the gorgeous Palm Ballroom at the Waldorf Astoria. The crème marble floors were polished, and the mahogany wood was gleaming in the chandelier light. The band was playing something light and jazzy that everyone could talk over. The cocktail hour flew by, with people steadily arriving from the church, met by a steady revolution of servers with hors d'oeuvres: crostini with duck confit and rhubarb marmalade, green tomatoes with balsamic and crispy serrano ham, elegant mini mac-and-brie cheeses, a festive French play on pigs-in-a-blanket that involved tiny croissants wrapped around an authentic andoulliette, and the coup de grâce, a gloriously orange spoon made out of Mimolette cheese that contained a single scoop of Prishibeyev caviar topped with crème fraiche. These were passed out with shots of Gray Goose, but there were also blood orange gin and tonics, a ginger bourbon lemonade, and George's newly refined blackberry sages. There were thick lines at both bars at first, probably because of the hand-carved ice cubes, but within fifteen minutes, at the most, everyone had a glass in hand. They were young but once. For one night and one night only, let there be no heartburn, no traffic, no bedtime, no chafing, no fears. George and Sara wanted to create not just a moment but a memory—a moment that lives beyond its borders—and the usual shrimp cocktail and steely Chardonnay wouldn't cut it. There would be nights ahead (oh yes, there would be) as there had been nights before, where nothing would go right, where the memory of a tulip and sea grass centerpiece on a perfectly set table would be needed. Where a turmeric-flavored butter would be remembered. Where a spring vegetable salad could be recalled, along with the way the dressing perfectly prepared the tongue for the truffle in the wild mushroom soup that followed. The earthy quality of which was then met and cleansed from the palate by the perfect purple scoop of beet sorbet that followed. And the steam released from the phyllo-dough parcel containing juicy red lamb loin encrusted with macadamia nuts and a swirl of potatoes mashed with Roquefort . . . Father danced with daughter; mother danced with son. Sisters made tearful speeches in which they both spoke the truth and lied through their teeth in wishing the happily couple nothing but the very best. Brothers told what light-blue stories they could of George's love life before Sara (the story of his serial kindergarten proposals came up in both their speeches). And then Jacob unfolded his hotel stationery and smoothed the wrinkles out against his sleeve. A big cough, a steadying look in George's direction, and a good throat-clearing. "This is just something—Sara asked if I'd read something brief. A poem. Anyway. This is part one, of, I think, three parts, about what was maybe the greatest thing that ever happened to me. Which was meeting these two people and following them here. Anyway." And he began to read, "'We came to the city because we wished to live haphazardly, to reach for only the least realistic of our desires, and to see if we could not learn what our failures had to teach, and not, when we came to live, discover that we had never died . . .'" He went on and on. George had never heard anything like it from Jacob before. Was it technically even poetry? It wasn't exactly brief. His mother was looking around as if someone were supposed to flash the lights, but others were laughing, and Sara was crying for the first time all night—oh well, she'd almost made it. The poem (if it was a poem) was about them (all of them) as they had been before. She could hardly remember when it had been like that. When Jacob finished, no one quite seemed to know what to do, so George stood up and loudly cheered and clapped, and it being his day, everyone else followed his lead. Jacob took a bow, and then a drink, and dessert was served. Six tiers of alternating Opera and St. Honoré Cakes with a vintage topper from the 1920s, obtained on eBay after a vicious auction in which Sara had left several competitors eBleeding on the virtual floor. The cake was served with the special-roasted coffee (with a shot of Napoleon brandy added by those in the know) and then a series of passed postdessert munchies: champagne wine gelée, a sour cherry-filled soufflé, and a perfect madeleine stamped with an _M_. Dancing late into the night, for hours without slowing down, as the older folks steadily said their goodbyes and returned to their rooms, the young folks felt more and more free. All past time seemed to disappear, and friends who had long ago dated and ended things awkwardly were seen boogying to the band's cover of Sisqo's "Thong Song" in utter violation of all normal rules of engagement. At one point Jacob somehow successfully swung Sara between his legs during "Take the A Train," and he and George got up and did their old air guitar routine to "Paradise City," and when the lights, finally, blasphemously, came up after Zacharie's fifth warning that they were past their contracted usage of the space, there were cries from all around to keep the party moving—to grab their wedding favors (custom-monogrammed shot glasses) and take the action down the road to the Turtle Bay Saloon or the new Midtown 3015 nightclub. But George and Sara knew it was time for them to call it a night and let the others go on without them. She got out her bouquet, and all the single women crowded around to play catch, but Sara expertly rocketed the flowers right where she wanted them to go: over Eddy's head and into Beth's waiting hands. Bull's-eye. Then Sara grabbed George's hand, and they left: barraged in their exit by catcalls, cheers, well-wishes, and charmingly lewd comments. Someone (top suspect: Jacob) threw a condom at George, which missed and got lost in a chandelier. It was up there with William's hat, flung excitely during "Under Pressure." Zacharie was on it already. Sara had already made both Jacob and William agree they'd all get together soon after the honeymoon so she could give them their souvenirs. There was talk of brunch, and George knew she would make it happen. Then alone together at last in the elevator, George and Sara fell into each other's arms, kissing rhapsodic and hungry, chasing the tail end of the evening's high, fumbling with the cuff links and hairpins that still restrained them. They managed to find their way blindly into the bridal suite, which had been cleaned and filled with fruit baskets and flowers and chocolates and two more bottles of champagne in ice buckets. They bypassed these and found, finally, the enormously wide bed; the last hook on her gown; the buckle on his vest; the wedding night underwear, so carefully picked out by Sara's sisters—soon removed and flung far in their flurry. Grasping, giddy, they pawed at each other's bodies as if they were brand-new. Floating on an ocean of down comfort and the scent of lilacs and the wide constellation of city lights outside their flagrantly opened curtains, George and Sara made love as they hadn't in months—or honestly, years—love like neither of them could specifically recall having made in the early days of their relationship but that they were equally certain they had made. And as they pressed their heads together on the pillow and closed their eyes and lost sight of the other for the first time since the morning, they both felt that things were right and good, and that everything they'd been through had led them to this place at last. • • • It was still dark in the room when Sara woke up. Lights from the neighboring buildings shone through the open curtains and made gray shapes upon the bed. Which was empty, except for her. She rose slowly and walked to the door, which had been carefully closed just to the point where the latch didn't spring into the hole and make a noise that might wake her. She eased it slowly open. A flickering light cast on her bare toes and the rug beneath them. She looked up, knowing what she was about to see because she had seen it before so many times. The television was on, volume down low to a commercial for dish soap in Spanish. There on the couch, completely naked, empty bottle of complimentary champagne beside him, was George—her husband, George—sound asleep. And on the couch beside him, under one of his arms, was the dull metal urn containing Irene's ashes. Just as she did most nights, Sara tiptoed into the room, willing herself not to cry, and gently lifted George's arm from the urn. In the morning he wouldn't remember taking it out of the bowling ball bag, just as most mornings he didn't remember taking it off the mantel and putting it on the couch cushion beside him, as if she were somehow watching. • • • From his blue beach towel, George spent hours watching the yachts and cruise ships moving back and forth across the glassy surface of the Golfe de la Napoule. Every fifteen minutes Sara's cell phone would vibrate, and over on her own adjacent blue towel, she would rotate. Once an hour she would sit up and apply a fresh coat of lotion to her arms and legs, wordlessly leaning over toward George so that he could do her back. That morning she had gone for a five-mile run on the beach, except she'd gotten caught up in it and done seven. After a quick dip she'd eaten half a sandwich for lunch and plopped down onto the towel to rest and try to get some color. George tried not to stare at the topless French women just down the beach. The white sand was almost polka-dotted with rosy little nipples. You sort of got used to it, after a while. Sara wondered how many more lavender lemonade spritzers the waiter boy would have to bring before she'd unhook her bikini top. "I don't see the problem," George had said an hour earlier, maybe two, as he'd reapplied her lotion. "Personally I like a nice tan line." "Oh you do, do you?" "Yes," he said decisively. "Like a frame around a painting. Makes them look official." "I think I might take my top off," Sara said. "Okay." George reached to the hook. "Not yet," she said, batting his hand away. "I meant later." "Okay," George said, capping the lotion and watching Sara flop down again. Up and down the beach, George saw other couples sitting just as he and Sara were, some talking, some not talking. It was early in the travel season, and the beach wasn't crowded. Little tables sat empty, with umbrellas open to shade the vacancies beneath them. Everyone was quiet, except once in a while a group of students would pass by, at least five or six speaking loudly in Czech or Swedish or Polish. Sara thought it was probably Europe's spring break. There had been a lot more of them around last night, wearing cheap wristbands and neon-banded sunglasses and sneakers without socks or laces. Suddenly Sara sat up, businesslike, a good ten minutes before her timer would go off. "Hi," George said quickly. "This is nice, isn't it?" "I think we should take our hike to scatter Irene's ashes tomorrow." He was surprised. "I thought—we had it planned for the, um, end of the week, after Monte Carlo and all that." "I think we need to get it out of the way. Don't you feel like it's sort of hanging over us? As nice as this all is, I can't quite relax." She could tell that George was annoyed, possibly even a little upset. Which was just as she'd suspected all along—he really didn't _want_ to scatter her ashes. Maybe even he was hoping that by the end of their ten days in France, he'd be able to persuade Sara to abandon the plan. Here he was, trying to wallow in the waist-deep water, and she was going to make him go right ahead and cannonball into the deep end of the pool? But she couldn't take it anymore. The sulking, the despondency, the pondering. He was a born problem solver, a doer of puzzles. And she believed in him. She believed he would comb through the data on 237 Lyrae V and correctly identify the variables and reengineer his hypotheses until they were tested and proven. He would discover great things, but this—this couldn't be solved. The answer to grief didn't lie in the appendix of a philosophy book or even in Ecclesiastes. He would never be able to drink enough scotch, or stay up late enough on the couch, to unravel it. _X_ equaled nothing. Not zero, nothing. _X_ equaled a waste of time. But what could make him see that? What could make him let it—her—go? Day by day she tried to make their love the greater problem to be solved. "Let's do it," George agreed. "Tomorrow first thing." Sara leaned her back against his chest and felt his arms wrap tight around her and his chin rest firmly on top of her head. Together, at last, they stared out at the waves at the shoreline. One of the bands of roving students was passing by. Someone with green streaks in her hair did a cartwheel and fell backward into the water, laughing. Another grabbed a cigarette from the hand of a third, and a game of keep-away began, with the red-hot ember flying around like a sparkler. George wondered if they had ever been that young; Sara remembered that they had been. Slipping one of her arms behind her back, in the space between it and George's chest, she thought for the first time that even if being married meant that she would spend every day from here forward watching George grow older (as he would watch her), then she was extremely lucky that the two of them _had_ known each other when they were young. No matter how they changed from here on, they would still have that between them. She'd be able to see behind the bags under George's eyes and find that spark of still-twenty because she'd seen it before. They could always save that for each other. Gingerly, she unhooked the top of her bikini and let the straps fall down. George's hands instinctively rose to cover her up, but she gently nudged them higher to her shoulders. In her whole life she'd never been naked in public. There were so many first times left to come. • • • That evening they took a cab into Cannes to dine at the famous La Palme d'Or, and between Michelin-starred courses, they strategized the next day's hike. On the way, Sara had contacted their tour operators and made arrangements. The group they'd originally planned to hike with wouldn't start out until the end of the week, and there was nothing scheduled for the upcoming day. But they could make their own way to the Chalet Castellane and pick up some basic supplies and a map of the national preserve. They spent the entire meal talking about the things they expected to see on the hike, getting more excited with each delicious course and each paired wine. They were just coming to the last of three desserts when George looked up and noticed someone familiar sitting across the restaurant from them. "It's Santiago!" he said, a little too loudly. "From _¡_ _Vámonos, Muchachos!_ " Sara squinted and saw George was right. "Wow. He looks _much_ handsomer in person." "We should say hello," he said. "Just that we're fans. You know?" "Do you know his name? You can't go over there unless you know his real name." "It's Victor. Something." And before she could stop him, George was crossing the room with almost frightening speed. She watched, afraid that he would say or do something very drunk and they'd be asked to leave. But to her surprise, with each step, she could see him pulling himself back together. There was her old George! The consummate and confident host. Had he been capable of this all this time? Santiago—Victor—seemed polite and friendly, not at all put out by the intrusion. He gestured to the gorgeous woman next to him, introducing her to George, who in turn, pointed back at Sara, who waved excitedly in their direction. They spoke for a minute or two, and George shook his hand again and returned to the table. "Well?" she squealed. "What did he say?" George stared at his dessert plate and played with his fork. "He said the show's over. He's here celebrating with his wife." "George! What a great story! I can't—" And she had been about to say she couldn't wait to tell everyone, when she remembered that the only someone who cared besides them was back at the hotel in an urn. Which explained the gloomy look she now saw on George's face. "The last episode aired in Mexico a week ago. It won't air in America until next year." She tried to cheer him up. "Well, did he tell you what happens? How does it end?" "Oh, yeah. He gets Renata, and there's a big wedding." Sara clutched her heart. "I knew it!" Neither of them said anything for a minute, and finally Sara said, "Well, I can't wait to watch it!" George took her hand. "Let's get the check. Big day tomorrow." Leaving the restaurant, both of them waved cheerfully at Santiago's table, and then they were quiet all the way back to the hotel, just watching the city lights going by and playing with each other's hands. They were both so full and tired that they went straight to bed. Sara fell asleep almost right away, but George lay awake. He couldn't quite figure out why it made him so sad to know the show was over. Renata and Santiago would be together, married, out there in TV land, forever. It was stupid. Just fucking television. But it bothered him that Irene, who had watched every episode from the beginning, would never know the ending. • • • They left in the morning with everything mapped out: where to find the Styx (the local name for a series of lovely natural bathing pools), as well as spots suitable for kayaking, fly-fishing, or rock climbing if they were interested. They had a tight schedule to keep if they were to get back to their hotel in Antibes by dark and then travel up the coast to Nice as planned. They'd go nine miles through the rocks along the turquoise riverbank to reach Point Sublime, an elevated spot at the far end of the canyon that offered breathtaking views of sheer cliffs and the pristine water, with miles of untouched woodland all around—the perfect spot to scatter Irene's ashes. Carried off by the mountain winds, they would dissipate into a scene of natural and epic beauty that, they agreed, would be beautifully fitting. The skies were clear the next morning after they finished provisioning at the château. The owner, Raif, a Flemish man in loose overalls, said bad weather was expected overnight, lasting probably the rest of the week, so it was good they'd set out early. George couldn't help but feel that this was, in some way, fate. The moment he stepped out there into the fresh air, he felt young again, as if he were still discovering what his body could do. When was the last time he'd worn hiking boots? He'd been a Boy Scout once upon a time, out there in the Senecaville Lake campground. It all came back to him, during the first two hours of the hike. Cutting up worms for a day of failed ice fishing. Canteen at his hip. Flimsy little compass in one hand, a nice hiking stick in the other. Only now instead of his father he had Sara at his side, with a bottle of Côtes de Thongue and an assortment of cheeses wrapped up in her pack for lunchtime. In his own pack he had a bottle of J&B from the hotel, which he thought he'd save to celebrate with after emptying the heavy urn he was carrying. The weight had hardly bothered him at first, but the pack felt heavier and heavier in the third hour. George looked forward to their return to the château, eight pounds lighter and warm with scotch. They were still creeping carefully down into the gorge, advancing toward the little curving line of water at the bottom. There were well-placed footholds in the rock and cables bolted in to grab for safety. For a while Sara was aware of the occasional white and red markings along the trail, but there were so many other hikers making the same trek that day that she hardly noticed when she stopped seeing other people ahead of or behind them. George had brought a map from the chalet, but they hadn't needed to look at it even once. It was simple to follow the trail and the river, which got wider and more powerful, the closer they came. At first they'd been chilly, well shaded by the giant cliffs, but as the sun rose higher in the sky, it became very hot, very quickly. When in the fourth hour they came at last to a little pebble beach by the water's edge, they decided they definitely deserved a break for lunch. George wanted to cool the wine down a little, so he undid one of his bootlaces and made a sort of noose around the neck of the bottle, tying the other end to a branch that had fallen by the bank. While they waited for the wine to cool, he and Sara strolled barefoot through the stream, letting the freezing water soothe their blisters. Light danced down through the leaves. It was like something out of a fairy tale—for the first time, George felt good about their choice for Irene's final resting place. It had that same quality as the shores of Shelter Island. What had she called them? Mythic. "We never do things like this," Sara said. "Back in Ithaca we used to go hiking all the time," he replied. She remembered going hiking exactly once, for about fifteen minutes, before Jacob ran into a spiderweb on the trail and refused to continue. The farther they got from those times, the less she idealized them and the more George seemed to. He didn't remember how often they'd fought and argued. "The wine should be cold enough by now," he said. They'd walked a lot farther than he'd intended. "I say we drink half now and save the rest for the next stop." Sara agreed, and they turned to walk back to where they'd left the bottle cooling. After a few minutes she began to wonder how they'd gotten so far upstream, because they should be back at the pebble beach by now. George was sure it was just a little farther, so they kept going, but still there was no sign of it. "That's crazy. How could we have missed it?" she asked. They decided to walk back a little ways and double-check. So they turned around, and now everything seemed different yet again from what they had seen before. "Did you see any kind of fork in the stream?" George asked for the eighth time. There was no sign of the beach, the wine bottle tied to the branch, or their backpacks, or Irene. Sara wasn't especially worried, sure that if they didn't find it soon, they were bound to find some other hikers who could point them on their way. But as the minutes ticked by, they saw no one and heard no one, and she became aware of something even more distressing. "It's getting kind of dark." "Kind of," George agreed, just as they felt wet drops fall onto their faces. He looked up through the leaves above, thinking maybe this was just some mist or dew from the morning, dripping off of the treetops, but the powerful sound of rain in the distance was unmistakable, and soon it began to pour. "Let's get over by that cliff." George tried not to sound worried. "This will pass by us pretty quickly. You get all kinds of weird weather patterns in canyons. Lots of very fast changes in air pressure when you have altitudes like this." Sara could hear thunder and tried to remember how to count the interval between thunder and lightning to see how far away it was. The trees were swaying wildly as the wind picked up. She couldn't help but worry about their packs, and Irene, out there somewhere. They got their boots back on, though George moved a bit awkwardly with only one of his laces, and they hurried over to a rocky ledge. In an indentation deep enough to slide into and out of the rain, they got out of what clothes they could, shivering, and tried to wring everything out, their wet bodies pressing clumsily against each other in the narrow space. They made jokes to pass the time; they thought back to the dinner of the night before and lying out on the Riviera beach; they imagined what Jacob would say if he were with them. George could just see him, shouting lines from _The Tempest_ or something. But the minutes worryingly ran into an hour, and one hour into two, and the rain only got more intense. They had no flashlights or phones, no blankets or shoes or food. George realized that his watch had stopped and he didn't have his compass. He remembered Raif at the château assuring him that the bad weather wasn't due until nighttime but was likely to last for a while. George prayed—that the rain would stop, that they would find their way back to the pebble beach where their things lay. He hadn't prayed in a long time. Terrifyingly fast and brilliant lightning sparked blue-white down a tree and out along the branches. At first George thought the incredible crackling sound was the earth itself coming apart underneath their feet. By the time he had realized what had happened, it was over—just a burned acid smell in the air and darkness. Sara was scared that it was getting darker, and they were pretty soaked, so finally George agreed that they should move out along the bank of the stream. They went carefully, looking out for bushes, rocks, tree roots, and other hikers as they walked through the storm. The rain pounded around them like bullets; branches slammed their bodies from both sides; the wind twisted in all directions. At first George kept talking, trying to stay upbeat, but before long Sara couldn't hear him. In fact, he couldn't even hear himself, so they fell into a silence. It lasted a long time. Another hour, maybe more. They held hands so tightly that their knuckles began to ache, and their wet palms began wrinkling against each other, so that when they did have to briefly detach—to get a better grip on a rock or to push a branch out of the way—it felt like Velcro wrenching apart. Finally, the rain softened and slowed to a drip. George guessed it was now maybe late afternoon, but the clouds above the trees were still black and heavy. Sara knew they ought to keep searching while they had the chance, but beyond exhausted, she lay down in the first clear area and wondered how they'd survived. "We're going to be fine," George said. "The important thing is we're not hurt." Sara tried to take comfort in this, but to her the important thing seemed more to be that they were still very lost. She couldn't imagine getting up now and starting to look for the trail. If they were missing for a long time, she imagined, it might be in the news. At least locally, back home—which meant 7News Boston now, not NBC 4 New York. She looked over at George, lying on the wet ground beside her, staring up at the edge of the great, gauzy sun, now beginning to beat through the clouds. She could tell it was soon going to be brutally hot. George looked completely shot. And she was sure he hadn't the faintest clue where they were now. "For fuck's sake," she heard him saying. "Irene!" Sara looked over, in the half-hope that Irene was actually _there_ , that she had appeared in the midst of all this madness to lead them out. But George was pointing not to some ghost but to his backpack. It was up ahead, half sticking out of a bush, nowhere near where they had left it. There was no pebble beach or stream anywhere nearby. Someone had found it and tried to walk off with it, then realized it was much too heavy and tossed it into the bush. George's dry clothes, the liquor bottles, and all his other supplies were gone, but Irene, or her urn at any rate, was still there. Sara dug around in the pack and found two granola bars that had fallen to the bottom. They ate them without speaking. The thief had also—thank God—left behind the guidebook, the little gift shop compass and the very soggy map from the chalet. As she shook these carefully to dry them out, George smacked at the compass, which had gotten water inside and was now cloudy. Inside, the needle seemed to spin freely. He paced around as if he were looking for cell reception, then gave up and began studying the map. "Any idea where we've gotten to?" she asked. George laid a finger down on a small bend in the river marked "Bettes," a little ways off the marked path. "This was where we left our stuff. On the pebbly beach. Then we walked this way a little while and came back along here . . ." He traced the path with his thumbnail. "What time is it?" Sara asked. "I have no idea. How long were we walking?" "We couldn't have been going that long," she repeated, looking again at the map. They peered around at the rocky cliffside, hoping to spot one of the red and white trail markers. "Let's say at most we were walking around for an hour. Moving maybe two or three miles an hour, given the conditions?" As Sara watched, he cautiously spread his fingers out to measure three miles. Then he set his thumb down on the pebble beach and rotated his hand around this point. It was a huge area, filled with all kinds of strange squiggles and shapes that she couldn't identify on the map key. "So . . . basically, we could be anywhere in here?" Sara said. "Basically." George climbed up on some nearby rocks to get a better view, but he couldn't make out any significant features. The sun had come out from the clouds between two barren cliffs along the horizon, but neither had any houses or roads that he could see—only some old, falling-down link fences along the white rock shores and the occasional cluster of sun-baked trash. "I think this way is the best option," George said. "Where there's litter, there's bound to be a path, or people." But there were no people, and there was no path. By the third cliff, Sara was beginning to doubt they could even find their way back to the stream. The next set of rocks turned out to be an extension of the previous one, and still there were no signs of civilization. "I don't understand," she cried. "There were dozens of hikers out here with us this morning. Now nobody?" George took out the map again, and scrutinized it. "None of this adds up at all," he shouted. He tried tracing little circles on the map representing the distance to the horizon, as far as the eye could see before the earth curved away. Wherever he saw a clump of rocks, he traced a circle, until it was covered with possibilities. He began to feel dizzy. They had not had their lunch and he could only assume their cheese, the wine, and Sara's pack were all long gone. "Sara, what's left in the canteen?" he shouted. "It's about half full," she said. "Goddammit. We should have refilled it at the stream." George shook his head. "I think we're cursed." He was dying for a real drink. Usually by now he'd have had at least his first of the day, and this had been a far more stressful day than most. He kissed Sara on her sunburned forehead and continued studying the map. There was no key, and he wondered what any of it meant. The small purple triangles marked what he presumed were mountains: la Blache and Clau and Mandarom, with numbers next to them. 1725, 1549, 1667. At first he thought these were dates, but no, more likely altitudes. Only standing where they were, all the mountains loomed equally huge. And there were dozens of them! Some had no names at all, only numbers. "What are you _doing_?" Sara called from where she was resting. "This goddamn map doesn't make sense! Nothing's where it should be." "How can things not be where they should be?" "They can't. But they aren't." Then Sara was screaming. She had spotted someone in a white shirt, moving through the woods down below them, maybe a mile away. George joined her as she hurtled down the slope, trying to get to the only person she'd seen in an hour before they somehow disappeared. It was a person—she was sure of it—a pale, angry man with a voluminous white beard, who as he became aware that they were bearing down on him, rushed quickly in the other direction. George called out to him to "stop, slow down, wait!" When at last they got within a hundred yards of the old man, Sara waved her floppy white hat at him. "Sir! Sir! _S'il vous plaît_. Please! Could you help us? Help . . . um. George, what's the French word for 'help'? How do I say, Which way is it to"—she paused, not sure where they even wanted to get to anymore—"town. _La ville!_ Am I saying that right? Is it 'vil' or 'veal'?" George had no idea, and the little man was yammering in French so quickly that she couldn't even tell when one word ended and the next began. From the way his face pinched up at them, she could guess that he was in no mood to help them. He continued to duck around the trees and scowl. " _Allez-vous en!_ " he shouted, terrified. _"Je veux être laissé seul."_ "Help!" George yelled at him, waving both hands. "We're . . . WE ARE LOST!" "He doesn't understand," Sara shouted. "George! The guidebook has travel phrases. On the back cover. Back cover." As George dug inside the pack to find the guidebook, Sara tried to beg the little man, who shouted at her in French as he tried to get away. "Please. We're Americans. We're lost! Americans? Lost!" The man picked up a rock and hurled it at her, and it fell halfway between them. She screamed and hid behind a tree. "We don't want to hurt you!" she shouted. "We need to find Point Sublime!" "What's that in French?" George shouted. "That is French! Sublime _is_ a French word. Maybe it's 'Pont'? Sub-lime? Subleeem? Suble-me? George, what's 'lost'? How do you say 'We are lost'?" Sara called again to the little man, but it was no use. He was rushing away, flinging rocks at them as he went. "George, hurry up!" she screamed. "I'm looking!" he screamed back. The little man made it to the cliffside and nimbly climbed up the face, turning back occasionally to shout and make obscene and angry gestures. Desperate, Sara tried to climb after him, but it was no use. The tiny man was pulling up onto a ledge that led around to a higher part of the canyon. " _Perdus! Perdus! Perdus!_ " cried George as he rushed over to the cliff, clutching the guidebook in front of him. " _Nous sommes perdus!_ " But as he ran, holding the book up in the air like a flag, he stubbed his toe on a rock, and the book dropped onto the dirt behind him. The man was gone, and the sun beat down on them as they sat there exhausted and miserable, more _perdus_ than ever. "How could you let him get away?" Sara sobbed. "Me?" George yelled. "You were scaring the hell out of him." Neither of them could even look at the other. They were still panting from the climb, shaking with both fear and adrenaline. George wordlessly got out the compass and began his ritual of smacking it and spinning in circles, trying to get the needle to land somewhere. Sara looked for any sign of the little man but saw nothing but wide expanses of woods in front of them, with no paths or mountains. "There's got to be something somewhere, right?" George said after another several hours of walking. "I mean, at some point we'll end up in Italy or Spain or something." Sara didn't answer him—she'd fallen into a dark silence, which put George into his usual jittery-talking mood, which only further fueled her irritation. "We're going north, right?" he said. She didn't reply. She didn't care which way they walked. He peered at the cheap little compass. "It _says_ we're going north," he said, "but then why is the sun setting behind us?" They hadn't been able to see the sun behind the rocks for some time, but now it was visible, dipping below the clouds, big and red. "How can the sun set in the south?" he asked, whacking at the compass. It was then that she snapped. "How in the _hell_ should I know?" "Don't blame me for this, okay? You're the one who was so eager to do this today. If we had waited and gone with the group, this never would have happened. I'm doing the best I can here!" Sara shot him a deadly look. "If we'd waited, you'd have come up with some excuse not to do it! I can't wake up one more time to find you drunk on the couch hugging her ashes." "Well, excuse me if I'd rather go to bed with something that isn't running to the gym every time I turn around. You're always anywhere but next to me!" He gave the compass another heavy whack, but the needle continued to declare they were heading north, when all logic and physics would dictate that they were heading _east_ , away from the setting sun. "My skin is peeling off," Sara sobbed. "I'm starving. And we're going to die out here." "We're not going to die," he insisted, though he was beginning to fear the same. "Forget where the sun is, and think about what we do when it goes _down_ ," she shouted. "We'll be out in the middle of the woods, with no lights, and no food—" He smacked the compass again even harder, but it didn't budge. "Would you cut that out?" she screeched, angrily clawing at his arm. "You're going to break the damn thing, and _then_ what?" "It's already broken!" he shouted. "That's not south!" "Who gives a shit?" she shouted back at him. They hadn't fought like this in—ever. Normally they fought about reasonable things, like what movie to see or whether to have Christmas with his family or hers. One of them would inevitably give in (usually George), and they'd move on without animus. He didn't know how to hold a grudge, and if she did, well, she didn't when it came to him. But here there was no giving in, no moving on. They couldn't escape this. It seemed to her that as furious as she was with him now, it was, in a sense, nothing new. She'd felt this way for a long time now, since he'd stopped being the George she'd always known. She wondered if he knew how much he'd changed, and if he thought she was different now. They'd been together such a long time, and partly they had managed it because they had never demanded very much of each other. Love, faithfulness, kindness: these had all come easily. It had never been very hard to make things easy for each other. But these past few years they had begun to lean harder. When Irene got sick, they had begun needing more from each other. They'd both changed, little by little, and she hadn't minded it because she'd assumed that when it was all over, they'd return to the way they'd been before. But what if there was no way back to before? Now it was as if he couldn't stand unless she were propping him up. Drinking, moping, miserable. And without him, what would become of her? Would she keep running and subtracting from herself and trying to beat her life into lists of manageable tasks? And the worst thing—what she was sickest of—wasn't George or herself at all, but the vast expanse of years ahead of them. Time upon time during which they would surely go on changing and needing each other and being disappointed and losing things they loved and having no control, and she was terrified of it, absolutely terrified, so much that it made her want to throw up. "Who cares?" she screamed. "Who cares?" Then George shrieked and howled like a crazy person. He set his pack down on the ground and fumbled madly with the urn. "Don't! What are you doing?" she yelled. Her words bounced off the trees and vanished into the deep crimson sunset. Orange light cascaded off the clouds, which for a moment looked like great plateaus above them. When she was a girl, she'd believed that was where dead people went, fluttering around on little wings with their harps and white robes. George looked triumphant as he heaved the great iron urn up above his head—and nearly toppled under its weight. "What are you _doing_? Put that _back!_ " she screeched. "Irene! Irene!" he was shouting. Streaks of tears dripped from his pinched eyes. The compass. "She's a magnet!" He was ready to fling the urn at the nearest tree. He hated it with all his might. He wanted to see it crack in half, to watch a gray cloud of soot and sediment mushroom out and disappear onto the forest floor and be gone forever. Lost. _Perdu._ But even as he stood poised at last to be rid of Irene—who had sent them on this insane journey, who had nearly gotten them killed, who he saw now had ruined the past three years of their lives—George couldn't let go. "Stop," Sara said softly. She eased the urn away from him and set it on the ground and held her husband closely. He breathed in and then sobbed. They sat silently and watched quietly as the sun went down and darkness fell. They felt the forest come alive around them. They each felt the other in their arms. They wished Irene were really there. They wanted to close their eyes and sleep and not worry about waking up in the morning. They watched as one by one, tiny pinpoints of stars emerged above them—some brilliant and some barely glowing—but in the darkness there were millions and millions. George looked down at his pale, weak, pained body. Sixty percent of it was indistinguishable from the little drips of water that clung to the sides of the empty canteen. Mostly, he was just a mixture of oxygen and hydrogen. Eighteen percent carbon. Three percent nitrogen. Some calcium and potassium and other salts. All down the line, these were the same elements that he measured every day in the stars of the Ring Nebulae, the same as in the sun, as in all the stars in the universe. On an atomic level, he was constructed from fused leftovers, expelled into the void when these stars inevitably collapsed. In a way it comforted him that he was elementally connected to everyone and everything—even if, as he lay in the dirt, he felt sure there was also something to him beyond atoms. He'd seen something leave Irene, in those final seconds, and it wasn't energy or matter. Back in high school physics he'd learned the cycle of decay and renewal over the course of millennia, and what a small footnote mankind was, when you looked at the entirety. But what he hadn't learned until much later was that for millennia, these stars, perceived by the naked eye, were thought to be, well, what they appeared to be: lonely, single points of light, isolated by billions of miles. But with better telescopes, astronomers in the seventeenth century had first noticed that some of these single dots were really two stars orbiting each other, or some common point, but in any case swirling close together. And now scientists had discovered that the vast majority, over 80 percent, of stars in the universe were these binary systems. Some were even multiple systems, three or more stars bound up in the same complex gravity. He could hear Sara breathing beside him, and he reached over to take her hand. It was surprisingly warm. But he knew he shouldn't be so surprised. She—this woman he loved—was a great inferno of carbon and nitrogen and water, orbiting his own glowing, celestial body as it, in turn, circled hers. "I don't think I've ever seen this many stars," she said, as awed as he was by the wide, bright swath of the Milky Way, stretching above them from one end of the valley to the other. Silently they stood up and, eyes fixed on the heavens, lofted Irene's urn from the damp earth. He held the base while Sara unscrewed the lid. Together they tipped it into the soft wind that remained of the earlier storm. In the dark they could barely see each other or the ashes as they swirled away, but they felt the urn getting lighter as they emptied it. George believed that on some microscopic level the last elemental traces of Irene would change this spot and, even if imperceptibly, affect all that would someday grow from it, just as surely as she had forever changed his life and all their lives. Sara closed her eyes and wished Jacob and William were there with them. She began, silently, ordering all the events of the day into a story that she and George would soon tell many times. She opened her eyes and looked at her husband. He was looking up at the dippers and the North Star. He was staring into the dark place where, though the light hadn't yet reached them, 237 Lyrae V had long ago collapsed and formed a new bright white star. And George, just like the explorers of centuries past, felt the warming chill of knowing just how large it all really was and exactly where he was inside it. "Let's go," he whispered to Sara, taking her hand. "I can find our way back from here." ## THE CITY THAT IS See gray threads of streets, dotted with the green of trees off the lanes. See glass rising, indistinguishable from sky. See aluminum herds coming down the West Side Highway and gulls circling the Battery. The ferry is just easing in. See the firecracker glow of M&M's advertisements on Broadway, where the Levi's are ten stories high. See the pine tar on the telephone poles and the chalk-dusty cobblestones. See where the careful grid begins to go off in angles, because part of this city is from before it was even a city. See, everywhere, there are children here. Everything is two or three times bigger in their eyes. See a takeout bag gusting up into a traffic light. There may be snow there, below, crusted to the curb. Or weeds driving up between the acts, to live an inch, or two, before the parade of dogs and passing feet. We are almost always about to touch. To be hit by bicycle messengers or buses. See how soon we get lost. See soot on silver, Post No Bills, snaking subway cars. Tunnels below tunnels below tunnels. See the copper skeleton city inside of it, all pipes and wires. We have this much in common. These belong to us all, like the blankets of green forests that hold pearl lakes inside and the rivers that cradle us and all that sprawls beyond them. See? It is a different city than the one we knew. It changed while we weren't looking, and while we were. We will never really understand how it changed because of us. Our words and motions moved its air and entered its vines. Still, my city is not your city, and neither of ours is the same as the city that belongs to the rest of them. To all the people elsewhere, remembering, or expecting it. There is a city that none of us knows at all. Why there is a dinosaur on the side of that building. Where all the yoga pants come from. What happened on that street corner fifty years before we were born. How that empty sports bar down the block stays in business. If anyone anywhere owns that bike that's been locked to the speed limit sign for the past nine months. There is the city where we are falling in love, and the city where we have lost all hope, and the city that never lets us down. There is the city that comes at us from all sides and knocks us down into puddles of something (we'd rather not know what). There is the city beneath the paint that coats this city. There is the city we step out into on warm days with no place in particular we have to be. Had you forgotten? There are cities where we are still young and cities where we have become very old. There are cities with just me, and cities with only you. There are cities that have vanished completely. There are cities we speak of very highly. There is a city we can never go back to, and a city we have never left and a city that was never built, and even one city that we all, each of us, believe in, that never fully leaves us. # ACKNOWLEDGMENTS Many thanks are owed to the dozens of supporters, believers, and friends who have helped me to write this book: Chelsea Lindman and everyone at Sanford Greenburger; my editors at Viking, Chris Russell, Beena Kamlani, and, formerly, Maggie Riggs; and my publicist, Angie Messina. Thank you to Leah, Joshua, my parents Dennis and Deborah, Oma, Jonathan, Dennis and Susan, Hanna, Chris, Theodore and all the rest of my family. I owe a great debt to the kind eyes and hearts of Elizabeth Perrella, Andrew Carter Dodds, Neil Bardhan, Jerry Wu, Jill Rafson, Robin Ganek, Rachel Panny, Emily Ethridge, John Proctor, Jordan Dollak, Michael Levy, Andrew Bodenrader, Dongwon Song, Yaron Kaver, Dr. Aaron Prosnitz, Dr. Joel Green of the University of Texas at Austin and the Space Telescope Science Institute, Katie Peyton, and to Tom Mansell and Lenn Thompson of the New York Cork Report. Additional thanks to the good people at Bien Cuit bakery for many vital refills. I am indebted as well to the support and generosity of Columbia University, Sarah Lawrence University, the New York Public Library, my tremendous colleagues at SUNY New Paltz College, the PEN/New England Organization, The UCross Foundation, and the Sherwood Anderson Foundation. This book was written in loving memory of my sister, Jennifer, who pushed me first. # _What's next on your reading list?_ [Discover your next great read!](http://links.penguinrandomhouse.com/type/prhebooklanding/isbn/9780698152137/display/1) * * * Get personalized book picks and up-to-date news about this author. Sign up now. 1. Cover 2. Praise for WHY WE CAME TO THE CITY 3. About the Author 4. Also by the Author 5. Title Page 6. Copyright 7. Dedication 8. Contents 9. PART I 1. Why We Came to the City 2. Living Vicariously 3. Five in a Million 4. Fish Eyes and No Ears 5. A Subjunctive March 6. Shelter Island 7. Jacob in the Waste Land 8. The Disappointments 10. PART II 1. Why We Left the City 2. Zugzwang, Ward III, 2010 3. William on the Bridge 4. The Wedding of Sara Sherman and George Murphy 5. The City That Is 11. Acknowledgments 1. Cover 2. Table of Contents 3. Start 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. 73. 74. 75. 76. 77. 78. 79. 80. 81. 82. 83. 84. 85. 86. 87. 88. 89. 90. 91. 92. 93. 94. 95. 96. 97. 98. 99. 100. 101. 102. 103. 104. 105. 106. 107. 108. 109. 110. 111. 112. 113. 114. 115. 116. 117. 118. 119. 120. 121. 122. 123. 124. 125. 126. 127. 128. 129. 130. 131. 132. 133. 134. 135. 136. 137. 138. 139. 140. 141. 142. 143. 144. 145. 146. 147. 148. 149. 150. 151. 152. 153. 154. 155. 156. 157. 158. 159. 160. 161. 162. 163. 164. 165. 166. 167. 168. 169. 170. 171. 172. 173. 174. 175. 176. 177. 178. 179. 180. 181. 182. 183. 184. 185. 186. 187. 188. 189. 190. 191. 192. 193. 194. 195. 196. 197. 198. 199. 200. 201. 202. 203. 204. 205. 206. 207. 208. 209. 210. 211. 212. 213. 214. 215. 216. 217. 218. 219. 220. 221. 222. 223. 224. 225. 226. 227. 228. 229. 230. 231. 232. 233. 234. 235. 236. 237. 238. 239. 240. 241. 242. 243. 244. 245. 246. 247. 248. 249. 250. 251. 252. 253. 254. 255. 256. 257. 258. 259. 260. 261. 262. 263. 264. 265. 266. 267. 268. 269. 270. 271. 272. 273. 274. 275. 276. 277. 278. 279. 280. 281. 282. 283. 284. 285. 286. 287. 288. 289. 290. 291. 292. 293. 294. 295. 296. 297. 298. 299. 300. 301. 302. 303. 304. 305. 306. 307. 308. 309. 310. 311. 312. 313. 314. 315. 316. 317. 318. 319. 320. 321. 322. 323. 324. 325. 326. 327. 328. 329. 330. 331. 332. 333. 334. 335. 336. 337. 338. 339. 340. 341. 342. 343. 344. 345. 346. 347. 348. 349. 350. 351. 352. 353. 354. 355. 356. 357. 358. 359. 360. 361. 362. 363. 364. 365. 366. 367. 368. 369. 370. 371. 372. 373. 374. 375. 376. 377. 378. 379. 380. 381. 382. 383. 384. 385. 386. 387. 388. 389. 390. 391. 392. 393. 394. 395. 396. 397. 398. 399. 400. 401. 402. 403. 404. 405. 406. 407. 408. 409. 410. 411. 412. 413. 414. 415. 416. 417. 418. 419. 420.
{ "redpajama_set_name": "RedPajamaBook" }
119
Q: Javascript image panel with images the same size What is the best way to display a panel of different sized images as all being the same size. Is there a simple Javascript framework that can handle the resizing and possibly some cropping. For example if you look at Pinterest you will see that all the images have variable sizes (we can use jQuery masonry for this). But then when you look at this page, http://pinterest.com/pin/97249673174024268/ all the images are the same size. Firstly is my question sensible and secondly is there a way we can achieve this with a Javascript library. A: If you want to do this entirely in JavaScript, it's simple enough that you don't need a library. If you have jQuery, it makes it even easier. * *Place the image inside a <div> with the width and height set to your desired size, 'overflow' set to 'hidden', and 'position' is either 'absolute' or 'relative'. *Get the size of the image: var imageWidth = $(image).width(), imageHeight = $(image).height(); (If it was loaded into a JavaScript Image object, you can also just get it from image.width and image.height) *Do a bit of math figure out how much to shrink or enlarge it: var widthScale = divWidth/imageWidth, heightScale = divHeight/imageHeight, scale = Math.max(widthScale, heightScale), newWidth = Math.round(imageWidth*scale), newHeight = Math.round(imageHeight*scale); Essentially,this figures out how much it would need scale the image to make the width fit and to make the height fit, then picks the larger of the two so the image fits on one side and overflows on the other. *Style the image to fit the new size and center it inside the div: $(image).css({ width: newWidth+'px', height: newHeight+'px', position: 'absolute', left: '50%', top: '50%', margin-left: 0-Math.round(newWidth/2)+'px', margin-top: 0-Math.round(newHeight/2)+'px' }); That should do it! A: This plugin here can handle varying image sizes and arrange them like you want.
{ "redpajama_set_name": "RedPajamaStackExchange" }
8,360
# SQL Cookbook ### Anthony Molinaro Beijing • Cambridge • Farnham • Köln • Sebastopol • Tokyo ## Dedication _To my mom_ : _You're the best! Thank you for everything_. ## Special Upgrade Offer If you purchased this ebook directly from oreilly.com, you have the following benefits: * DRM-free ebooks—use your ebooks across devices without restrictions or limitations * Multiple formats—use on your laptop, tablet, or phone * Lifetime access, with free updates * Dropbox syncing—your files, anywhere If you purchased this ebook from another retailer, you can upgrade your ebook to take advantage of all these benefits for just $4.99. Click here to access your ebook upgrade. _Please note that upgrade offers are not available from sample content._ ## A Note Regarding Supplemental Files Supplemental files and examples for this book can be found at <http://examples.oreilly.com/9780596009762/>. Please use a standard desktop web browser to access these files, as they may not be accessible from all ereader devices. All code files or examples referenced in the book will be available online. For physical books that ship with an accompanying disc, whenever possible, we've posted all CD/DVD content. Note that while we provide as much of the media content as we are able via free download, we are sometimes limited by licensing restrictions. Please direct any questions or concerns to booktech@oreilly.com. ## Preface SQL is _the_ language in the database world. If you're developing for or reporting from relational databases, your ability to put data into a database and then get it back out again ultimately comes down to your knowledge of SQL. Yet many practitioners use SQL in a perfunctory manner, and are unaware of the power at their disposal. This book aims to change all that, by opening your eyes to what SQL can really do for you. The book you're holding in your hands is a cookbook. It's a collection of common SQL problems and their solutions that I hope you'll find helpful in your day-to-day work. Recipes are categorized into chapters of related topics. When faced with a new SQL problem that you haven't solved before, find the chapter that best seems to apply, skim through the recipe titles, and hopefully you will find a solution, or at least inspiration for a solution. More than 150 recipes are available in this 600-plus page book, and I've only scratched the surface of what can be done using SQL. The number of different SQL solutions available for solving our daily programming problems is eclipsed only by the number of problems we need to solve. You won't find all possible problems covered in this book. Indeed, such coverage would be impossible. You will, however, find many common problems and their solutions. And in those solutions lie techniques that you'll learn how to expand upon and apply to other, new problems that I never thought to cover. ### Tip My publisher and I are constantly on the lookout for new, cookbook-worthy SQL recipes. If you come across a good or clever SQL solution to a problem, consider sharing it; consider sending it in for inclusion in the next edition of this book. See "Comments and Questions" for our contact information. ## Why I Wrote This Book Queries, queries, queries. My goal from the beginning of this project has not been so much to write a "SQL Cookbook" as to write a "Query Cookbook." I've aimed to create a book comprised of queries ranging from the relatively easy to the relatively difficult in hopes the reader will grasp the techniques behind those queries and use them to solve his own particular business problems. I hope to pass on many of the SQL programming techniques I've used in my career so that you, the reader, will take them, learn from them, and eventually improve upon them; through this cycle we all benefit. Being able to retrieve data from a database seems so simple, yet in the world of Information Technology (IT) it's crucial that the operation of data retrieval be done as efficiently as possible. Techniques for efficient data retrieval should be shared so that we can all be efficient and help each other improve. Consider for a moment the outstanding contribution to mathematics by Georg Cantor, who was the first to realize the vast benefit of studying sets of elements (studying the set itself rather than its constituents). At first, Cantor's work wasn't accepted by many of his peers. In time, though, it was not only accepted, but set theory is now considered the foundation of mathematics! More importantly, however, it was not through Cantor's work alone that set theory became what it is today; rather, by sharing his ideas, others such as Ernst Zermelo, Gottlob Frege, Abraham Fraenkel, Thoralf Skolem, Kurt Gödel, and John von Neumann developed and improved the theory. Such sharing not only provided everyone with a better understanding of the theory, it made for a better set theory than was first conceived. ## Objectives of This Book Ultimately, the goal of this book is to give you, the reader, a glimpse of what can be done using SQL outside of what is considered the typical SQL problem domain. SQL has come a very long way in the last ten years. Problems typically solved using a procedural language such as C or JAVA can now be solved directly in SQL, but many developers are simply unaware of this fact. This book is to help make you aware. Now, before you take what I just said the wrong way, let me state that I am a firm believer in, "If it ain't broke, don't fix it." For example, let's say you have a particular business problem to solve, and you currently use SQL to simply retrieve your data while applying your complex business logic using a language other than SQL. If your code works and performance is acceptable, then great. I am in no way suggesting that you scrap your code for a SQL-only solution; I only ask that you open your mind and realize that the SQL you programmed with in 1995 is not the same SQL being used in 2005. Today's SQL can do so much more. ## Audience for This Book This text is unique in that the target audience is wide, but the quality of the material presented is not compromised. Consider that both complex and simple solutions are provided, and that solutions for five different vendors are available when a common solution does not exist. The target audience is indeed wide: The SQL novice Perhaps you have just purchased a text on learning SQL, or you are fresh into your first semester of a required database course and you want to supplement your new knowledge with some challenging real world examples. Maybe you've seen a query that magically transforms rows to columns, or that parses a serialized string into a result set. The recipes in this book explain techniques for performing these seemingly impossible queries. The non-SQL programmer Perhaps your background is in another language and you've been thrown into the fire at your current job and are expected to support complex SQL written by someone else. The recipes shown in this book, particularly in the later chapters, break down complex queries and provide a gentle walk-through to help you understand complex code that you may have inherited. The SQL journeyman For the intermediate SQL developer, this book is the gold at the end of the rainbow (OK, maybe that's too strong; please forgive an author's enthusiasm for his topic). In particular, if you've been coding SQL for quite some time and have not found your way onto window functions, you're in for a treat. For example, the days of needing temporary tables to store intermediate results are over; window functions can get you to an answer in a single query! Allow me to again state that I have no intention of trying to force-feed my ideas to an already experienced practitioner. Instead, consider this book as a way to update your skill set if you haven't caught on to some of the newer additions to the SQL language. The SQL expert Undoubtedly you've seen these recipes before, and you probably have your own variations. Why, then, is this book useful to you? Perhaps you've been a SQL expert on one platform your whole career, say, SQL Server, and now wish to learn Oracle. Perhaps you've only ever used MySQL, and you wonder what the same solutions in PostgreSQL would look like. This text covers different relational database management systems (RDBMSs) and displays their solutions side by side. Here's your chance to expand your knowledge base. ## How to Use This Book Be sure to read this preface thoroughly. It contains necessary background and other information that you might otherwise miss if you dive into individual recipes. The section on "Platform and Version" tells you what RDBMSs this book covers. Pay special attention to "Tables Used in This Book," so that you become familiar with the example tables used in most of the recipes. You'll also find important coding and font conventions in "Conventions Used in This Book." All these sections come later in this preface. Remember that this is a cookbook, a collection of code examples to use as guidelines for solving similar (or identical) problems that you may have. Do not try to _learn_ SQL from this book, at least not from scratch. This book should act as a supplement to, not a replacement for, a complete text on learning SQL. Additionally, following the tips below will help you use this book more productively: * This book takes advantage of vendor-specific functions. _SQL Pocket Guide_ by Jonathan Gennick has all of them and is convenient to have close to you in case you don't know what some of the functions in my recipes do. * If you've never used window functions, or have had problems with queries using GROUP BY, read Appendix A first. It will define and prove what a group is in SQL. More importantly, it gives a basic idea of how window functions work. Window functions are one of the most important SQL developments of the past decade. * Use common sense! Realize that it is impossible to write a book that provides a solution to every possible business problem in existence. Instead, use the recipes from this book as templates or guidelines to teach yourself the techniques required to solve your own specific problems. If you find yourself saying, "Great, this recipe works for this particular data set, but mine is different and thus the recipe doesn't work quite correctly," that's expected. In that case, try to find commonality between the data in the book and your data. Break down the book's query to its simplest form and add complexity as you go. All queries start with SELECT...FROM..., so in their simplest form, all queries are the same. If you add complexity as you go, "building" a query one step, one function, one join at a time, you will not only understand how those constructs change the result set, but you will see how the recipe is different from what you actually need. And from there you can modify the recipe to work for your particular data set. * Test, test, and test. Undoubtedly any table of yours is bigger than the 14 row EMP table used in this book, so please test the solutions against your data, at the very least to ensure that they perform well. I can't possibly know what your tables look like, what columns are indexed, and what relationships are present in your schema. So please, do not blindly implement these techniques in your production code until you fully understand them and how they will perform against your particular data. * Don't be afraid to experiment. Be creative! Feel free to use techniques different from what I've used. I make it a point to use many of the functions supplied by the different vendors in this book, and often there are several other functions that may work as well as the one I've chosen to use in a particular recipe. Feel free to plug your own variations into the recipes of this book. * Newer does not always mean better. If you're not using some of the more recent features of the SQL language (for example, window functions), that does not necessarily mean your code is not as efficient as it can be. There are many cases in which traditional SQL solutions are as good or better than any new solution. Please keep this in mind, particularly in the Appendix B, _Rozenshtein Revisited_. After reading this book, you should not come away with the idea that you need to update or change all your existing code. Instead, only realize there are many new and extremely efficient features of SQL available now that were not available 10 years ago, and they are worth the time taken to learn them. * Don't be intimidated. When you get to the solution section of a recipe and a query looks impossible to understand, don't fear. I've gone to great lengths to not only break down each query starting from its simplest form, but to show the intermediate results of each portion of a query as we work our way to the complete solution. You may not be able to see the big picture immediately, but once you follow the discussion and see not only how a query is built, but the results of each step, you'll find that even convoluted-looking queries are not hard to grasp. * Program defensively when necessary. In an effort to make the queries in this book as terse as humanly possible without obscuring their meaning, I've removed many "defensive measures" from the recipes. For example, consider a query computing a running total for a number of employee salaries. It could be the case that you have declared the column of type VARCHAR and are (sadly) storing a mix of numeric and string data in one field. You'll find the running total recipe in this book does not check for such a case (and it will fail as the function SUM doesn't know what to do with character data), so if you have this type of "data" ("problem" is a more accurate description), you will need to code around it or (hopefully) fix your data, because the recipes provided do not account for such design practices as the mixing of character and numeric data in the same column. The idea is to focus on the technique; once you understand the technique, sidestepping such problems is trivial. * Repetition is the key. The best way to master the recipes in this book is to sit down and code them. When it comes to code, reading is fine, but actually coding is even better. You must read to understand why things are done a certain way, but only by coding will you be able to create these queries yourself. Be advised that many of the examples in this book are contrived. The problems are not contrived. They are real. However, I've built all examples around a small set of tables containing employee data. I've done that to help you get familiar with the example data, so that, having become familiar with the data, you can focus on the technique that each recipe illustrates. You might look at a specific problem and think: "I would never need to do that with employee data." But try to look past the example data in those cases and focus on the technique that I'm illustrating. The techniques are useful. My colleagues and I use them daily. We think you will too. ## What's Missing from This Book Due to constraints on time and book size, it isn't possible for a single book to provide solutions for all the possible SQL problems you may encounter. That said, here are some additional items that did not make the list: Data Definition Aspects of SQL such as creating indexes, adding constraints, and loading data are not covered in this book. Such tasks typically involve syntax that is highly vendor-specific, so you're best off referring to vendor manuals. In addition, such tasks do not represent the type of "hard" problem for which one would purchase a book to solve. Chapter 4, however, does provide recipes for common problems involving the insertion, updating, and deleting of data. XML It is my strong opinion that XML recipes do not belong in a book on SQL. Storing XML documents in relational databases is becoming increasingly popular, and each RDBMS has their own extensions and tools for retrieving and manipulating such data. XML manipulation often involves code that is procedural and thus outside the scope of this book. Recent developments such as XQUERY represent completely separate topics from SQL and belong in their own book (or books). Object-Oriented Extensions to SQL Until a language more suitable for dealing with objects comes along, I am strongly against using object-oriented features and designs in relational databases. At the present time, the object-oriented features available from some vendors are more suitable for use in procedural programming than in the sort of setoriented problem-solving for which SQL is designed. Debates on Points of Theory You won't find arguments in this book about whether SQL is relational, or about whether NULL values should exist. These sort of theoretical discussions have their place, but not in a book centered on delivering SQL solutions to real-life problems. To solve real-life problems, you simply have to work with the tools available to you at the time. You have to deal with what you have, not what you wish you had. ### Tip If you wish to learn more about theory, any of Chris Date's "Relational Database Writings" books would be a good start. You might also pick up a copy of his most recent book, _Database in Depth_ (O'Reilly). Vendor Politics This text provides solutions for five different RDBMSs. It is only natural to want to know which vendor's solution is "best" or "fastest." There is plenty of information that each vendor would gladly provide to show that their product is "best"; I have no intention of doing so here. ANSI Politics Many texts shy away from the proprietary functions supplied by different vendors. This text embraces proprietary functions. I have no intention of writing convoluted, poorly performing SQL code simply for the sake of portability. I have never worked in an environment where the use of vendor-specific extensions was prohibited. You are paying for these features; why not use them? Vendor extensions exist for a reason, and many times offer better performance and readability than you could otherwise achieve using standard SQL. If you prefer ANSI-only solutions, fine. As I mentioned before, I am not here to tell you to turn all your code upside down. If what you have is strictly ANSI and it works for you, great. When it comes down to it, we all go to work, we all have bills to pay, and we all want to go home at a reasonable time and enjoy what's still left of our days. So, I'm not suggesting that ANSI-only is wrong. Do what works and is best for you. But, I want to make clear that if you're looking for ANSI-only solutions, you should look elsewhere. Legacy Politics The recipes in this text make use of the newest features available at the time of writing. If you are using old versions of the RDBMSs that I cover, many of my solutions will simply not work for you. Technology does not stand still, and neither should you. If you need older solutions, you'll find that many of the SQL texts available from years past have plenty of examples using older versions of the RDBMSs covered in this book. ## Structure of This Book This book is divided into 14 chapters and 2 appendices: * Chapter 1, _Retrieving Records_ , introduces very simple queries. Examples include how to use a WHERE clause to restrict rows from your result set, providing aliases for columns in your result set, using an inline view to reference aliased columns, using simple conditional logic, limiting the number of rows returned by a query, returning random records, and finding NULL values. Most of the examples are very simple, but some of them appear in more complex recipes, so it's a good idea to read this chapter if you're relatively new to SQL or aren't familiar with any of the examples listed for this chapter. * Chapter 2, _Sorting Query Results_ , introduces recipes for sorting query results. The ORDER BY clause is introduced and is used to sort query results. Examples increase in complexity ranging from simple, single-column ordering, to ordering by substrings, to ordering based on conditional expressions. * Chapter 3, _Working with Multiple Tables_ , introduces recipes for combining data from multiple tables. If you are new to SQL or are a bit rusty on joins, I strongly recommend you read this chapter before reading Chapter 5 and later. Joining tables is what SQL is all about; you must understand joins to be successful. Examples in this chapter include performing both inner and outer joins, identifying Cartesian productions, basic set operations (set difference, union, intersection), and the effects of joins on aggregate functions. * Chapter 4, _Inserting, Updating, Deleting_ , introduces recipes for inserting, updating, and deleting data, respectively. Most of the examples are very straightforward (perhaps even pedestrian). Nevertheless, operations such as inserting rows into one table from another table, the use of correlated subqueries in updates, an understanding of the effects of NULLs, and knowledge of new features such as multi-table inserts and the MERGE command are extremely useful for your toolbox. * Chapter 5, _Metadata Queries_ , introduces recipes for getting at your database metadata. It's often very useful to find the indexes, constraints, and tables in your schema. The simple recipes here allow you to gain information about your schema. Additionally, "dynamic" SQL examples are shown here as well, i.e., SQL generated by SQL. * Chapter 6, _Working with Strings_ , introduces recipes for manipulating strings. SQL is not known for its string parsing capabilities, but with a little creativity (usually involving Cartesian products) along with the vast array of vendor-specific functions, you can accomplish quite a bit. This chapter is where the book begins to get interesting. Some of the more interesting examples include counting the occurrences of a character in a string, creating delimited lists from table rows, converting delimited lists and strings into rows, and separating numeric and character data from a string of alphanumeric characters. * Chapter 7, _Working with Numbers_ , introduces recipes for common number crunching. The recipes found here are extremely common and you'll learn how easily window functions solve problems involving moving calculations and aggregations. Examples include creating running totals; finding mean, median, and mode; calculating percentiles; and accounting for NULL while performing aggregations. * Chapter 8, _Date Arithmetic_ , is the first of two chapters dealing with dates. Being able to perform simple date arithmetic is crucial to everyday tasks. Examples include determining the number of business days between two dates, calculating the difference between two dates in different units of time (day, month, year, etc.), and counting occurrences of days in a month. * Chapter 9, _Date Manipulation_ , is the second of the two chapters dealing with dates. In this chapter you will find recipes for some of the most common date operations you will encounter in a typical work day. Examples include returning all days in a year, finding leap years, finding first and last days of a month, creating a calendar, and filling in missing dates for a range of dates. * Chapter 10, _Working with Ranges_ , introduces recipes for identifying values in ranges, and for creating ranges of values. Examples include automatically generating a sequence of rows, filling in missing numeric values for a range of values, locating the beginning and end of a range of values, and locating consecutive values. * Chapter 11, _Advanced Searching_ , introduces recipes that are crucial for everyday development and yet sometimes slip through the cracks. These recipes are not any more difficult than others, yet I see many developers making very inefficient attempts at solving the problems these recipes solve. Examples from this chapter include finding knight values, paginating through a result set, skipping rows from a table, finding reciprocals, selecting the top _n_ records, and ranking results. * Chapter 12, _Reporting and Warehousing_ , introduces queries typically used in warehousing or generating complex reports. This chapter was meant to be the majority of the book as it existed in my original vision. Examples include converting rows into columns and vice versa (cross-tab reports), creating buckets or groups of data, creating histograms, calculating simple and complete subtotals, performing aggregations over a moving window of rows, and grouping rows based on given units of time. * Chapter 13, _Hierarchical Queries_ , introduces hierarchical recipes. Regardless of how your data is modeled, at some point you will be asked to format data such that it represents a tree or parent-child relationship. This chapter provides recipes accomplishing these tasks. Creating tree-structured result sets can be cumbersome with traditional SQL, so vendor-supplied functions are particularly useful in this chapter. Examples include expressing a parent-child relationship, traversing a hierarchy from root to leaf, and rolling up a hierarchy. * Chapter 14, _Odds 'n' Ends_ , is a collection of miscellaneous recipes that didn't seem to fit into any other problem domain, but that nevertheless are interesting and useful. This chapter is different from the rest in that it focuses on vendor-specific solutions only. This is the only chapter of the book where each recipe highlights only one vendor. The reasons are twofold: first, this chapter was meant to serve as more of a fun, geeky chapter. Second, some recipes exist only to highlight a vendor-specific function that has no equivalent in the other RDBMSs (examples include SQL Server's PIVOT/UNPIVOT operators and Oracle's MODEL clause). In some cases, though, you'll be able to easily tweak a solution provided in this chapter to work for a platform not covered in the recipe. * Appendix A, _Window Function Refresher_ , is a window function refresher along with a solid discussion of groups in SQL. Window functions are new to most, so it is appropriate that this appendix serves as a brief tutorial. Additionally, in my experience I have noticed that the use of GROUP BY in queries is a source of confusion for many developers. This chapter defines exactly what a SQL group is, and then proceeds to use various queries as proofs to validate that definition. The chapter then goes into the effects of NULLs on groups, aggregates, and partitions. Lastly, you'll find discussion on the more obscure and yet extremely powerful syntax of the window function's OVER clause (i.e., the "framing" or "windowing" clause). * Appendix B, _Rozenshtein Revisited_ , is a tribute to David Rozenshtein, to whom I owe my success in SQL development. Rozenshtein's book, The _Essence of SQL_ (Coriolis Group Books) was the first book I purchased on SQL that was not required by a class. It was from that book that I learned how to "think in SQL." To this day I attribute much of my understanding of how SQL works to David's book. It truly is different from any other SQL book I've read, and I'm grateful that it was the first one I picked up on my own volition. Appendix B focuses on some of the queries presented in The _Essence of SQL_ , and provides alternative solutions using window functions (which weren't available when The _Essence of SQL_ was written) for those queries. ## Platform and Version SQL is a moving target. Vendors are constantly pumping new features and functionality into their products. Thus you should know up front which versions of the various platforms were used in the preparation of this text: * DB2 v.8 * Oracle Database 10 _g_ (with the exception of a handful of recipes, the solutions will work for Oracle8 _i_ Database and Oracle9 _i_ Database as well) * PostgreSQL 8 * SQL Server 2005 * MySQL 5 ## Tables Used in This Book The majority of the examples in this book involve the use of two tables, EMP and DEPT. The EMP table is a simple 14-row table with only numeric, string, and date fields. The DEPT table is a simple four-row table with only numeric and string fields. These tables appear in many old database texts, and the many-to-one relationship between departments and employees is well understood. While I'm on the topic of the example tables, I want to mention that all but a very few solutions in this book run against these tables. Nowhere do I tweak my example data to set up a solution that you would be unlikely to have a chance of implementing in the real world, as some books do. And while I'm on the topic of solutions, let me just mention that whenever possible I've tried to provide a generic solution that will run on all five RDBMSs covered in this book. Often that's not possible. Even so, in many cases more than one vendor shares a solution. Because of their mutual support for window functions, for example, Oracle and DB2 often share solutions. Whenever solutions are shared, or at least are very similar, discussions are shared as well. The contents of EMP and DEPT are shown below, respectively: **select * from emp;** EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ------ --------- ---- ----------- ---- ---- ------- 7369 SMITH CLERK 7902 17-DEC-1980 800 20 7499 ALLEN SALESMAN 7698 20-FEB-1981 1600 300 30 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 7566 JONES MANAGER 7839 02-APR-1981 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30 7698 BLAKE MANAGER 7839 01-MAY-1981 2850 30 7782 CLARK MANAGER 7839 09-JUN-1981 2450 10 7788 SCOTT ANALYST 7566 09-DEC-1982 3000 20 7839 KING PRESIDENT 17-NOV-1981 5000 10 7844 TURNER SALESMAN 7698 08-SEP-1981 1500 0 30 7876 ADAMS CLERK 7788 12-JAN-1983 1100 20 7900 JAMES CLERK 7698 03-DEC-1981 950 30 7902 FORD ANALYST 7566 03-DEC-1981 3000 20 7934 MILLER CLERK 7782 23-JAN-1982 1300 10 **select * from dept;** DEPTNO DNAME LOC ------ -------------- --------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON Additionally, you will find four pivot tables used in this book; T1, T10, T100, and T500. Because these tables exist only to facilitate pivots, I did not find it necessary to give them clever names. The number following the "T" in each of the pivot tables signifies the number of rows in each table starting from 1. For example, the values for T1 and T10: select id from t1; ID ---------- 1 select id from t10; ID ---------- 1 2 3 4 5 6 7 8 9 10 As an aside, some vendors allow partial SELECT statements. For example, you can have SELECT without a FROM clause. I don't particularly like this, thus I select against a support table, T1, with a single row, rather than using partial queries. Any other tables are specific to particular recipes and chapters, and will be introduced in the text when appropriate. ## Conventions Used in This Book I use a number of typographical and coding conventions in this book. Take time to become familiar with them. Doing so will enhance your understanding of the text. Coding conventions in particular are important, because I can't discuss them anew for each recipe in the book. Instead, I list the important conventions here. ### Typographical Conventions The following typographical conventions are used in this book: UPPERCASE Used to indicate SQL keywords within text lowercase Used for all queries in code examples. Other languages such as C and JAVA use lowercase for most keywords and I find it infinitely more readable than uppercase. Thus all queries will be lowercase. **`Constant width bold`** Indicates user input in examples showing an interaction. ### Tip Indicates a tip, suggestion, or general note. ### Warning Indicates a warning or caution. ### Coding Conventions My preference for case in SQL statements is to always use lowercase, for both keywords and user-specified identifiers. For example: select empno, ename from emp; Your preference may be otherwise. For example, many prefer to uppercase SQL keywords. Use whatever coding style you prefer, or whatever your project requires. Despite my use of lowercase in code examples, I consistently uppercase SQL keywords and identifiers in the text. I do this to make those items stand out as something other than regular prose. For example: > The preceding query represents a SELECT against the EMP table. While this book covers databases from five different vendors, I've decided to use one format for all the output: EMPNO ENAME ----- ------ 7369 SMITH 7499 ALLEN ... Many solutions make use of _inline views_ , or subqueries in the FROM clause. The ANSI SQL standard requires that such views be given table aliases. (Oracle is the only vendor that lets you get away without specifying such aliases.) Thus, my solutions use aliases such as x and y to identify the result sets from inline views: select job, sal from (select job, max(sal) sal from emp group by job) **x** ; Notice the letter X following the final, closing parenthesis. That letter X becomes the name of the "table" returned by the subquery in the FROM clause. While column aliases are a valuable tool for writing self-documenting code, aliases on inline views (for most recipes in this book) are simply formalities. They are typically given trivial names such as X, Y, Z, TMP1, and TMP2. In cases where I feel a better alias will provide more understanding, I do so. You will notice that the SQL in the SOLUTION section of the recipes is typically numbered, for example: 1 select ename 2 from emp 3 where deptno = 10 The number is not part of the syntax; I have included it so I can reference parts of the query by number in the discussion section. ## Using Code Examples This book is here to help you get your job done. In general, you may use the code in this book in your programs and documentation. You do not need to contact O'Reilly for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O'Reilly books _does_ require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product's documentation _does_ require permission. We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: _SQL Cookbook_ , by Anthony Molinaro. Copyright 2006 O'Reilly Media, Inc., 0-596-00976-3. If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at permissions@oreilly.com. ## Comments and Questions We have tested and verified the information in this book to the best of our ability, but you may find that features have changed or that we have made mistakes. If so, please notify us by writing to: O'Reilly Media, Inc. --- 1005 Gravenstein Highway North Sebastopol, CA 95472 (800) 998-9938 (in the United States or Canada) (707) 829-0515 (international or local) (707) 829-0104 (fax) You can also send messages electronically. To be put on the mailing list or request a catalog, send email to: info@oreilly.com --- To ask technical questions or comment on the book, or to suggest additional recipes for future editions, send email to: bookquestions@oreilly.com --- We have a web site for this book where you can find examples and errata (previously reported errors and corrections are available for public view there). You can access this page at: <http://www.oreilly.com/catalog/sqlckbk> --- ## Safari® Enabled When you see a Safari® Enabled icon on the cover of your favorite technology book, it means the book is available online through the O'Reilly Network Safari Bookshelf. Safari offers a solution that's better than e-books. It's a virtual library that lets you easily search thousands of top technology books, cut and paste code samples, download chapters, and find quick answers when you need the most accurate, current information. Try it for free at <http://safari.oreilly.com>. ## Acknowledgments This book would not exist without all the support I've received from a great many people. I would like to thank my mother, Connie, to whom this book is dedicated. Without your hard work and sacrifice I would not be where I am today. Thank you for everything, Mom. I am thankful and appreciative of everything you've done for my brother and me. I have been blessed to have you as my mother. To my brother, Joe: every time I came home from Baltimore to take a break from writing, you were there to remind me how great things are when we're not working, and how I should finish writing so I can get back to the more important things in life. You're a good man and I respect you. I am extremely proud of you, and proud to call you my brother. To my wonderful fiancee, Georgia: Without your support I would not have made it through all 600-plus pages of this book. You were here sharing this experience with me, day after day. I know it was just as hard on you as it was on me. I spent all day working and all night writing, but you were great through it all. You were understanding and supportive and I am forever grateful. Thank you. I love you. To my future in-laws: to my mother-in-law and father-in-law, Kiki and George. Thank you for your support throughout this whole experience. You always made me feel at home whenever I took a break and came to visit, and you made sure Georgia and I were always well fed. To my sister-in-laws, Anna and Kathy, it was always fun coming home and hanging out with you guys, giving Georgia and I a much needed break from the book and from Baltimore. To my editor Jonathan Gennick, without whom this book would not exist. Jonathan, you deserve a tremendous amount of credit for this book. You went above and beyond what an editor would normally do and for that you deserve much thanks. From supplying recipes, to tons of rewrites, to keeping things humorous despite oncoming deadlines, I could not have done it without you. I am grateful to have had you as my editor and grateful for the opportunity you have given me. An experienced DBA and author yourself, it was a pleasure to work with someone of your technical level and expertise. I can't imagine there are too many editors out there that can, if they decided to, stop editing and work practically anywhere as a database administrator (DBA); Jonathan can. Being a DBA certainly gives you an edge as an editor as you usually know what I want to say even when I'm having trouble expressing it. O'Reilly is lucky to have you on staff and I am lucky to have you as an editor. I would like to thank Ales Spetic and Jonathan Gennick for _Transact-SQL Cookbook_. Isaac Newton famously said, "If I have seen a little further it is by standing on the shoulders of giants." In the acknowledgments section of the _Transact-SQL Cookbook_ , Ales Spetic wrote something that is a testament to this famous quote and I feel should be in every SQL book. I include it here: > I hope that this book will complement the exiting opuses of outstanding authors like Joe Celko, David Rozenshtein, Anatoly Abramovich, Eugine Berger, Iztik Ben-Gan, Richard Snodgrass, and others. I spent many nights studying their work, and I learned almost everything I know from their books. As I am writing these lines, I'm aware that for every night I spent discovering their secrets, they must have spent 10 nights putting their knowledge into a consistent and readable form. It is an honor to be able to give something back to the SQL community. I would like to thank Sanjay Mishra for his excellent _Mastering Oracle SQL_ book, and also for putting me in touch with Jonathan. If not for Sanjay, I may have never been in touch with Jonathan and never would have written this book. Amazing how a simple email can change your life. I would like to thank David Rozenshtein, especially, for his _Essence of SQL_ book, which provided me with a solid understanding of how to think and problem solve in sets/SQL. I would like to thank David Rozenshtein, Anatoly Abramovich, and Eugene Birger for their book _Optimizing Transact-SQL_ , from which I learned many of the advanced SQL techniques I use today. I would like to thank the whole team at Wireless Generation, a great company with great people. A big thank you to all of the people who took the time to review, critique, or offer advice to help me complete this book: Jesse Davis, Joel Patterson, Philip Zee, Kevin Marshall, Doug Daniels, Otis Gospodnetic, Ken Gunn, John Stewart, Jim Abramson, Adam Mayer, Susan Lau, Alexis Le-Quoc, and Paul Feuer. I would like to thank Maggie Ho for her careful review of my work and extremely useful feedback regarding the window function refresher. I would like to thank Chuck Van Buren and Gillian Gutenberg for their great advice about running. Early morning workouts helped me clear my mind and unwind. I don't think I would have been able to finish this book without getting out a bit. I would like to thank Steve Kang and Chad Levinson for putting up with all my incessant talk about different SQL techniques on the nights when all they wanted was to head to Union Square to get a beer and a burger at Heartland Brewery after a long day of work. I would like to thank Aaron Boyd for all his support, kind words, and, most importantly, good advice. Aaron is honest, hardworking, and a very straightforward guy; people like him make a company better. I would like to thank Olivier Pomel for his support and help in writing this book, in particular for the DB2 solution for creating delimited lists from rows. Olivier contributed that solution without even having a DB2 system to test it with! I explained to him how the WITH clause worked, and minutes later he came up with the solution you see in this book. Jonah Harris and David Rozenshtein also provided helpful technical review feedback on the manuscript. And Arun Marathe, Nuno Pinto do Souto, and Andrew Odewahn weighed in on the outline and choice of recipes while this book was in its formative stages. Thanks, very much, to all of you. I want to thank John Haydu and the MODEL clause development team at Oracle Corporation for taking the time to review the MODEL clause article I wrote for O'Reilly, and for ultimately giving me a better understanding of how that clause works. I would like to thank Tom Kyte of Oracle Corporation for allowing me to adapt his TO_BASE function into a SQL-only solution. Bruno Denuit of Microsoft answered questions I had regarding the functionality of the window functions introduced in SQL Server 2005. Simon Riggs of PostgreSQL kept me up to date about new SQL features in PostgreSQL (very big thanks: Simon, by knowing what was coming out and when, I was able to incorporate some new SQL features such as the ever-so-cool GENERATE_SERIES function, which I think made for more elegant solutions compared to pivot tables). Last but certainly not least, I'd like to thank Kay Young. When you are talented and passionate about what you do, it is great to be able to work with people who are likewise as talented and passionate. Many of the recipes you see in this text have come from working with Kay and coming up with SQL solutions for everyday problems at Wireless Generation. I want to thank you and let you know I absolutely appreciate all the help you given me throughout all of this; from advice, to grammar corrections, to code, you played an integral role in the writing of this book. It's been great working with you, and Wireless Generation is a better company because you are there. —Anthony Molinaro September 2005 ## Chapter 1. Retrieving Records This chapter focuses on very basic SELECT statements. It is important to have a solid understanding of the basics as many of the topics covered here are not only present in more difficult recipes but also are found in everyday SQL. ## 1.1. Retrieving All Rows and Columns from a Table ### Problem You have a table and want to see all of the data in it. ### Solution Use the special "*" character and issue a SELECT against the table: 1 select * 2 from emp ### Discussion The character "*" has special meaning in SQL. Using it will return every column for the table specified. Since there is no WHERE clause specified, every row will be returned as well. The alternative would be to list each column individually: select empno,ename,job,sal,mgr,hiredate,comm,deptno from emp In ad hoc queries that you execute interactively, it's easier to use SELECT *. However, when writing program code it's better to specify each column individually. The performance will be the same, but by being explicit you will always know what columns you are returning from the query. Likewise, such queries are easier to understand by people other than yourself (who may or may not know all the columns in the tables in the query). ## 1.2. Retrieving a Subset of Rows from a Table ### Problem You have a table and want to see only rows that satisfy a specific condition. ### Solution Use the WHERE clause to specify which rows to keep. For example, to view all employees assigned to department number 10: 1 select * 2 from emp 3 where deptno = 10 ### Discussion The WHERE clause allows you to retrieve only rows you are interested in. If the expression in the WHERE clause is true for any row, then that row is returned. Most vendors support common operators such as: =, <, >, <=, >=, !, <>. Additionally, you may want rows that satisfy multiple conditions; this can be done by specifying AND, OR, and parenthesis, as shown in the next recipe. ## 1.3. Finding Rows That Satisfy Multiple Conditions ### Problem You want to return rows that satisfy multiple conditions. ### Solution Use the WHERE clause along with the OR and AND clauses. For example, if you would like to find all the employees in department 10, along with any employees who earn a commission, along with any employees in department 20 who earn at most $2000: 1 select * 2 from emp 3 where deptno = 10 4 or comm is not null 5 or sal <= 2000 and deptno=20 ### Discussion You can use a combination of AND, OR, and parenthesis to return rows that satisfy multiple conditions. In the solution example, the WHERE clause finds rows such that: * the DEPTNO is 10, or * the COMM is not NULL, or * the salary is $2000 or less for any employee in DEPTNO 20. The presence of parentheses causes conditions within them to be evaluated together. For example, consider how the result set changes if the query was written with the parentheses as shown below: select * from emp where ( deptno = 10 or comm is not null or sal <= 2000 ) and deptno=20 EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ------ ----- ----- ----------- ----- ---------- ------ 7369 SMITH CLERK 7902 17-DEC-1980 800 20 7876 ADAMS CLERK 7788 12-JAN-1983 1100 20 ## 1.4. Retrieving a Subset of Columns from a Table ### Problem You have a table and want to see values for specific columns rather than for all the columns. ### Solution Specify the columns you are interested in. For example, to see only name, department number, and salary for employees: 1 select ename,deptno,sal 2 from emp ### Discussion By specifying the columns in the SELECT clause, you ensure that no extraneous data is returned. This can be especially important when retrieving data across a network, as it avoids the waste of time inherent in retrieving data that you do not need. ## 1.5. Providing Meaningful Names for Columns ### Problem You would like to change the names of the columns that are returned by your query so they are more readable and understandable. Consider this query that returns the salaries and commissions for each employee: 1 select sal,comm 2 from emp What's "sal"? Is it short for "sale"? Is it someone's name? What's "comm"? Is it communication? You want the results to have more meaningful labels. ### Solution To change the names of your query results use the AS keyword in the form: _`original_name AS new_name`_. Some databases do not require AS, but all accept it: **1 select sal as salary, comm as commission** **2 from emp** SALARY COMMISSION ------- ---------- 800 1600 300 1250 500 2975 1250 1400 2850 2450 3000 5000 1500 0 1100 950 3000 1300 ### Discussion Using the AS keyword to give new names to columns returned by your query is known as _aliasing_ those columns. The new names that you give are known as _aliases_. Creating good aliases can go a long way toward making a query and its results understandable to others. ## 1.6. Referencing an Aliased Column in the WHERE Clause ### Problem You have used aliases to provide more meaningful column names for your result set and would like to exclude some of the rows using the WHERE clause. However, your attempt to reference alias names in the WHERE clause fails: select sal as salary, comm as commission from emp where salary < 5000 ### Solution By wrapping your query as an inline view you can reference the aliased columns: 1 select * 2 from ( 3 select sal as salary, comm as commission 4 from emp 5 ) x 6 where salary < 5000 ### Discussion In this simple example, you can avoid the inline view and reference COMM or SAL directly in the WHERE clause to achieve the same result. This solution introduces you to what you would need to do when attempting to reference any of the following in a WHERE clause: * Aggregate functions * Scalar subqueries * Windowing functions * Aliases Placing your query, the one giving aliases, in an inline view gives you the ability to reference the aliased columns in your outer query. Why do you need to do this? The WHERE clause is evaluated before the SELECT, thus, SALARY and COMMISSION do not yet exist when the "Problem" query's WHERE clause is evaluated. Those aliases are not applied until after the WHERE clause processing is complete. However, the FROM clause is evaluated before the WHERE. By placing the original query in a FROM clause, the results from that query are generated before the outermost WHERE clause, and your outermost WHERE clause "sees" the alias names. This technique is particularly useful when the columns in a table are not named particularly well. ### Tip The inline view in this solution is aliased X. Not all databases require an inline view to be explicitly aliased, but some do. All of them accept it. ## 1.7. Concatenating Column Values ### Problem You want to return values in multiple columns as one column. For example, you would like to produce this result set from a query against the EMP table: CLARK WORKS AS A MANAGER KING WORKS AS A PRESIDENT MILLER WORKS AS A CLERK However, the data that you need to generate this result set comes from two different columns, the ENAME and JOB columns in the EMP table: **select ename, job** **from emp** **where deptno = 10** ENAME JOB ---------- --------- CLARK MANAGER KING PRESIDENT MILLER CLERK ### Solution Find and use the built-in function provided by your DBMS to concatenate values from multiple columns. #### DB2, Oracle, PostgreSQL These databases use the double vertical bar as the concatenation operator: 1 select ename||' WORKS AS A '||job as msg 2 from emp 3 where deptno=10 #### MySQL This database supports a function called CONCAT: 1 select concat(ename, ' WORKS AS A ',job) as msg 2 from emp 3 where deptno=10 #### SQL Server Use the "+" operator for concatenation: 1 select ename + ' WORKS AS A ' + job as msg 2 from emp 3 where deptno=10 ### Discussion Use the CONCAT function to concatenate values from multiple columns. The || is a shortcut for the CONCAT function in DB2, Oracle, and PostgreSQL, while + is the shortcut for SQL Server. ## 1.8. Using Conditional Logic in a SELECT Statement ### Problem You want to perform IF-ELSE operations on values in your SELECT statement. For example, you would like to produce a result set such that, if an employee is paid $2000 or less, a message of "UNDERPAID" is returned, if an employee is paid $4000 or more, a message of "OVERPAID" is returned, if they make somewhere in between, then "OK" is returned. The result set should look like this: ENAME SAL STATUS ---------- ---------- --------- SMITH 800 UNDERPAID ALLEN 1600 UNDERPAID WARD 1250 UNDERPAID JONES 2975 OK MARTIN 1250 UNDERPAID BLAKE 2850 OK CLARK 2450 OK SCOTT 3000 OK KING 5000 OVERPAID TURNER 1500 UNDERPAID ADAMS 1100 UNDERPAID JAMES 950 UNDERPAID FORD 3000 OK MILLER 1300 UNDERPAID ### Solution Use the CASE expression to perform conditional logic directly in your SELECT statement: 1 select ename,sal, 2 case when sal <= 2000 then 'UNDERPAID' 3 when sal >= 4000 then 'OVERPAID' 4 else 'OK' 5 end as status 6 from emp ### Discussion The CASE expression allows you to perform condition logic on values returned by a query. You can provide an alias for a CASE expression to return a more readable result set. In the solution, you'll see the alias STATUS given to the result of the CASE expression. The ELSE clause is optional. Omit the ELSE, and the CASE expression will return NULL for any row that does not satisfy the test condition. ## 1.9. Limiting the Number of Rows Returned ### Problem You want to limit the number of rows returned in your query. You are not concerned with order; any _n_ rows will do. ### Solution Use the built-in function provided by your database to control the number of rows returned. #### DB2 In DB2 use the FETCH FIRST clause: 1 select * 2 from emp fetch first 5 rows only #### MySQL and PostgreSQL Do the same thing in MySQL and PostgreSQL using LIMIT: 1 select * 2 from emp limit 5 #### Oracle In Oracle, place a restriction on the number of rows returned by restricting ROWNUM in the WHERE clause: 1 select * 2 from emp 3 where rownum <= 5 #### SQL Server Use the TOP keyword to restrict the number of rows returned: 1 select top 5 * 2 from emp ### Discussion Many vendors provide clauses such as FETCH FIRST and LIMIT that let you specify the number of rows to be returned from a query. Oracle is different, in that you must make use of a function called ROWNUM that returns a number for each row returned (an increasing value starting from 1). Here is what happens when you use ROWNUM <= 5 to return the first five rows: 1. Oracle executes your query. 2. Oracle fetches the first row and calls it row number 1. 3. Have we gotten past row number 5 yet? If no, then Oracle returns the row, because it meets the criteria of being numbered less than or equal to 5. If yes, then Oracle does not return the row. 4. Oracle fetches the next row and advances the row number (to 2, and then to 3, and then to 4, and so forth). 5. Go to step 3. As this process shows, values from Oracle's ROWNUM are assigned _after_ each row is fetched. This is a very important and key point. Many Oracle developers attempt to return only, say, the fifth row returned by a query by specifying ROWNUM = 5. Using an equality condition in conjunction with ROWNUM is a bad idea. Here is what happens when you try to return, say, the fifth row using ROWNUM = 5: 1. Oracle executes your query. 2. Oracle fetches the first row and calls it row number 1. 3. Have we gotten to row number 5 yet? If no, then Oracle discards the row, because it doesn't meet the criteria. If yes, then Oracle returns the row. But the answer will never be yes! 4. Oracle fetches the next row and calls it row number 1. This is because the first row to be returned from the query must be numbered as 1. 5. Go to step 3. Study this process closely, and you can see why the use of ROWNUM = 5 to return the fifth row fails. You can't have a fifth row if you don't first return rows one through four! You may notice that ROWNUM = 1 does, in fact, work to return the first row, which may seem to contradict the explanation thus far. The reason ROWNUM = 1 works to return the first row is that, to determine whether or not there are any rows in the table, Oracle has to attempt to fetch at least once. Read the preceding process carefully, substituting 1 for 5, and you'll understand why it's OK to specify ROWNUM = 1 as a condition (for returning one row). ## 1.10. Returning _n_ Random Records from a Table ### Problem You want to return a specific number of random records from a table. You want to modify the following statement such that successive executions will produce a different set of five rows: select ename, job from emp ### Solution Take any built-in function supported by your DBMS for returning random values. Use that function in an ORDER BY clause to sort rows randomly. Then, use the previous recipe's technique to limit the number of randomly sorted rows to return. #### DB2 Use the built-in function RAND in conjunction with ORDER BY and FETCH: 1 select ename,job 2 from emp 3 order by rand() fetch first 5 rows only #### MySQL Use the built-in RAND function in conjunction with LIMIT and ORDER BY: 1 select ename,job 2 from emp 3 order by rand() limit 5 #### PostgreSQL Use the built-in RANDOM function in conjunction with LIMIT and ORDER BY: 1 select ename,job 2 from emp 3 order by random() limit 5 #### Oracle Use the built-in function VALUE, found in the built-in package DBMS_RANDOM, in conjunction with ORDER BY and the built-in function ROWNUM: 1 select * 2 from ( 3 select ename, job 4 from emp 6 order by dbms_random.value() 7 ) 8 where rownum <= 5 #### SQL Server Use the built-in function NEWID in conjunction with TOP and ORDER BY to return a random result set: 1 select top 5 ename,job 2 from emp 3 order by newid() ### Discussion The ORDER BY clause can accept a function's return value and use it to change the order of the result set. The solution queries all restrict the number of rows to return _after_ the function in the ORDER BY clause is executed. Non-Oracle users may find it helpful to look at the Oracle solution as it shows (conceptually) what is happening under the covers of the other solutions. It is important that you don't confuse using a function in the ORDER BY clause with using a numeric constant. When specifying a numeric constant in the ORDER BY clause, you are requesting that the sort be done according the column in that ordinal position in the SELECT list. When you specify a function in the ORDER BY clause, the sort is performed on the result from the function as it is evaluated for each row. ## 1.11. Finding Null Values ### Problem You want to find all rows that are null for a particular column. ### Solution To determine whether a value is null, you must use IS NULL: 1 select * 2 from emp 3 where comm is null ### Discussion NULL is never equal/not equal to anything, not even itself, therefore you cannot use = or != for testing whether a column is NULL. To determine whether or not a row has NULL values you must use IS NULL. You can also use IS NOT NULL to find rows without a null in a given column. ## 1.12. Transforming Nulls into Real Values ### Problem You have rows that contain nulls and would like to return non-null values in place of those nulls. ### Solution Use the function COALESCE to substitute real values for nulls: 1 select coalesce(comm,0) 2 from emp ### Discussion The COALESCE function takes one or more values as arguments. The function returns the first non-null value in the list. In the solution, the value of COMM is returned whenever COMM is not null. Otherwise, a zero is returned. When working with nulls, it's best to take advantage of the built-in functionality provided by your DBMS; in many cases you'll find several functions work equally as well for this task. COALESCE happens to work for all DBMSs. Additionally, CASE can be used for all DBMSs as well: select case when comm is not null then comm else 0 end from emp While you can use CASE to translate nulls into values, you can see that it's much easier and more succinct to use COALESCE. ## 1.13. Searching for Patterns ### Problem You want to return rows that match a particular substring or pattern. Consider the following query and result set: **select ename, job** **from emp** **where deptno in (10,20)** ENAME JOB ---------- --------- SMITH CLERK JONES MANAGER CLARK MANAGER SCOTT ANALYST KING PRESIDENT ADAMS CLERK FORD ANALYST MILLER CLERK Of the employees in departments 10 and 20, you want to return only those that have either an "I" somewhere in their name or a job title ending with "ER": ENAME JOB ---------- --------- SMITH CLERK JONES MANAGER CLARK MANAGER KING PRESIDENT MILLER CLERK ### Solution Use the LIKE operator in conjunction with the SQL wildcard operator ("%"): 1 select ename, job 2 from emp 3 where deptno in (10,20) 4 and (ename like '%I%' or job like '%ER') ### Discussion When used in a LIKE pattern-match operation, the percent ("%") operator matches any sequence of characters. Most SQL implementations also provide the underscore ("_") operator to match a single character. By enclosing the search pattern "I" with "%" operators, any string that contains an "I" (at any position) will be returned. If you do not enclose the search pattern with "%", then where you place the operator will affect the results of the query. For example, to find job titles that end in "ER", prefix the "%" operator to "ER"; if the requirement is to search for all job titles beginning with "ER", then append the "%" operator to "ER". ## Chapter 2. Sorting Query Results This chapter focuses on customizing how your query results look. By understanding how you can control and modify your result sets, you can provide more readable and meaningful data. ## 2.1. Returning Query Results in a Specified Order ### Problem You want to display the names, job, and salaries of employees in department 10 in order based on their salary (from lowest to highest). You want to return the following result set: ENAME JOB SAL ---------- --------- ---------- MILLER CLERK 1300 CLARK MANAGER 2450 KING PRESIDENT 5000 ### Solution Use the ORDER BY clause: 1 select ename,job,sal 2 from emp 3 where deptno = 10 4 order by sal asc ### Discussion The ORDER BY clause allows you to order the rows of your result set. The solution sorts the rows based on SAL in ascending order. By default, ORDER BY will sort in ascending order, and the ASC clause is therefore optional. Alternatively, specify DESC to sort in descending order: **select ename,job,sal** **from emp** **where deptno = 10** **order by sal desc** ENAME JOB SAL ---------- --------- ---------- KING PRESIDENT 5000 CLARK MANAGER 2450 MILLER CLERK 1300 You need not specify the name of the column on which to sort. You can instead specify a number representing the column. The number starts at 1 and matches the items in the SELECT list from left to right. For example: **select ename,job,sal** **from emp** **where deptno = 10** **order by 3 desc** ENAME JOB SAL ---------- --------- ---------- KING PRESIDENT 5000 CLARK MANAGER 2450 MILLER CLERK 1300 The number 3 in this example's ORDER BY clause corresponds to the third column in the SELECT list, which is SAL. ## 2.2. Sorting by Multiple Fields ### Problem You want to sort the rows from EMP first by DEPTNO ascending, then by salary descending. You want to return the following result set: EMPNO DEPTNO SAL ENAME JOB ---------- ---------- ---------- ---------- --------- 7839 10 5000 KING PRESIDENT 7782 10 2450 CLARK MANAGER 7934 10 1300 MILLER CLERK 7788 20 3000 SCOTT ANALYST 7902 20 3000 FORD ANALYST 7566 20 2975 JONES MANAGER 7876 20 1100 ADAMS CLERK 7369 20 800 SMITH CLERK 7698 30 2850 BLAKE MANAGER 7499 30 1600 ALLEN SALESMAN 7844 30 1500 TURNER SALESMAN 7521 30 1250 WARD SALESMAN 7654 30 1250 MARTIN SALESMAN 7900 30 950 JAMES CLERK ### Solution List the different sort columns in the ORDER BY clause, separated by commas: 1 select empno,deptno,sal,ename,job 2 from emp 3 order by deptno, sal desc ### Discussion The order of precedence in ORDER BY is from left to right. If you are ordering using the numeric position of a column in the SELECT list, then that number must not be greater than the number of items in the SELECT list. You are generally permitted to order by a column not in the SELECT list, but to do so you must explicitly name the column. However, if you are using GROUP BY or DISTINCT in your query, you cannot order by columns that are not in the SELECT list. ## 2.3. Sorting by Substrings ### Problem You want to sort the results of a query by specific parts of a string. For example, you want to return employee names and jobs from table EMP and sort by the last two characters in the job field. The result set should look like the following: ENAME JOB ---------- --------- KING PRESIDENT SMITH CLERK ADAMS CLERK JAMES CLERK MILLER CLERK JONES MANAGER CLARK MANAGER BLAKE MANAGER ALLEN SALESMAN MARTIN SALESMAN WARD SALESMAN TURNER SALESMAN SCOTT ANALYST FORD ANALYST ### Solution #### DB2, MySQL, Oracle, and PostgreSQL Use the SUBSTR function in the ORDER BY clause: select ename,job from emp order by substr(job,length(job)-1) #### SQL Server Use the SUBSTRING function in the ORDER BY clause: select ename,job from emp order by substring(job,len(job)-1,2) ### Discussion Using your DBMS's substring function, you can easily sort by any part of a string. To sort by the last two characters of a string, find the end of the string (which is the length of the string) and subtract 2. The start position will be the second to last character in the string. You then take all characters after that start position. Because SQL Server requires a third parameter in SUBSTRING to specify the number of characters to take. In this example, any number greater than or equal to 2 will work. ## 2.4. Sorting Mixed Alphanumeric Data ### Problem You have mixed alphanumeric data and want to sort by either the numeric or character portion of the data. Consider this view: **create view V** **as** **select ename||' '||deptno as data** **from emp** **select * from V** DATA ------------- SMITH 20 ALLEN 30 WARD 30 JONES 20 MARTIN 30 BLAKE 30 CLARK 10 SCOTT 20 KING 10 TURNER 30 ADAMS 20 JAMES 30 FORD 20 MILLER 10 You want to sort the results by DEPTNO or ENAME. Sorting by DEPTNO produces the following result set: DATA ---------- CLARK 10 KING 10 MILLER 10 SMITH 20 ADAMS 20 FORD 20 SCOTT 20 JONES 20 ALLEN 30 BLAKE 30 MARTIN 30 JAMES 30 TURNER 30 WARD 30 Sorting by ENAME produces the following result set: DATA --------- ADAMS 20 ALLEN 30 BLAKE 30 CLARK 10 FORD 20 JAMES 30 JONES 20 KING 10 MARTIN 30 MILLER 10 SCOTT 20 SMITH 20 TURNER 30 WARD 30 ### Solution #### Oracle and PostgreSQL Use the functions REPLACE and TRANSLATE to modify the string for sorting: /* ORDER BY DEPTNO */ 1 select data 2 from V 3 order by replace(data, 4 replace( 5 translate(data,'0123456789','##########'),'#',''),'') /* ORDER BY ENAME */ 1 select data 2 from emp 3 order by replace( 4 translate(data,'0123456789','##########'),'#','') #### DB2 Implicit type conversion is more strict in DB2 than in Oracle or PostgreSQL, so you will need to cast DEPTNO to a CHAR for view V to be valid. Rather than recreate view V, this solution will simply use an inline view. The solution uses REPLACE and TRANSLATE in the same way as the Oracle and PostrgreSQL solution, but the order of arguments for TRANSLATE is slightly different for DB2: /* ORDER BY DEPTNO */ 1 select * 2 from ( 3 select ename||' '||cast(deptno as char(2)) as data 4 from emp 5 ) v 6 order by replace(data, 7 replace( 8 translate(data,'##########','0123456789'),'#',''),'') /* ORDER BY ENAME */ 1 select * 2 from ( 3 select ename||' '||cast(deptno as char(2)) as data 4 from emp 5 ) v 6 order by replace( 7 translate(data,'##########','0123456789'),'#','') #### MySQL and SQL Server The TRANSLATE function is not currently supported by these platforms, thus a solution for this problem will not be provided. ### Discussion The TRANSLATE and REPLACE functions remove either the numbers or characters from each row, allowing you to easily sort by one or the other. The values passed to ORDER BY are shown in the following query results (using the Oracle solution as the example, as the same technique applies to all three vendors; only the order of parameters passed to TRANSLATE is what sets DB2 apart): **select data,** **replace(data,** **replace(** **translate(data,'0123456789','##########'),'#',''),'') nums,** **replace(** **translate(data,'0123456789','##########'),'#','') chars** **from V** DATA NUMS CHARS ------------ ------ ---------- SMITH 20 20 SMITH ALLEN 30 30 ALLEN WARD 30 30 WARD JONES 20 20 JONES MARTIN 30 30 MARTIN BLAKE 30 30 BLAKE CLARK 10 10 CLARK SCOTT 20 20 SCOTT KING 10 10 KING TURNER 30 30 TURNER ADAMS 20 20 ADAMS JAMES 30 30 JAMES FORD 20 20 FORD MILLER 10 10 MILLER ## 2.5. Dealing with Nulls when Sorting ### Problem You want to sort results from EMP by COMM, but the field is nullable. You need a way to specify whether nulls sort last: ENAME SAL COMM ---------- ---------- ---------- TURNER 1500 0 ALLEN 1600 300 WARD 1250 500 MARTIN 1250 1400 SMITH 800 JONES 2975 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 or whether they sort first: ENAME SAL COMM ---------- ---------- ---------- SMITH 800 JONES 2975 CLARK 2450 BLAKE 2850 SCOTT 3000 KING 5000 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 MARTIN 1250 1400 WARD 1250 500 ALLEN 1600 300 TURNER 1500 0 ### Solution Depending on how you want the data to look (and how your particular RDBMS sorts NULL values), you can sort the nullable column in ascending or descending order: 1 select ename,sal,comm 2 from emp 3 order by 3 1 select ename,sal,comm 2 from emp 3 order by 3 desc This solution puts you in a position such that if the nullable column contains non-NULL values, they will be sorted in ascending or descending order as well, according to what you ask for; this may or may not what you have in mind. If instead you would like to sort NULL values differently than non-NULL values, for example, you want to sort non-NULL values in ascending or descending order and all NULL values last, you can use a CASE expression to conditionally sort the column. #### DB2, MySQL, PostgreSQL, and SQL Server Use a CASE expression to "flag" when a value is NULL. The idea is to have a flag with two values: one to represent NULLs, the other to represent non-NULLs. Once you have that, simply add this flag column to the ORDER BY clause. You'll easily be able to control whether NULL values are sorted first or last without interfering with non-NULL values: /* NON-NULL COMM SORTED ASCENDING, ALL NULLS LAST */ **1 select ename,sal,comm** **2 from (** **3 select ename,sal,comm,** **4 case when comm is null then 0 else 1 end as is_null** **5 from emp** **6 ) x** **7 order by is_null desc,comm** ENAME SAL COMM ------ ----- ---------- TURNER 1500 0 ALLEN 1600 300 WARD 1250 500 MARTIN 1250 1400 SMITH 800 JONES 2975 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 /* NON-NULL COMM SORTED DESCENDING, ALL NULLS LAST */ **1 select ename,sal,comm** **2 from (** **3 select ename,sal,comm,** **4 case when comm is null then 0 else 1 end as is_null** **5 from emp** **6 ) x** **7 order by is_null desc,comm desc** ENAME SAL COMM ------ ----- ---------- MARTIN 1250 1400 WARD 1250 500 ALLEN 1600 300 TURNER 1500 0 SMITH 800 JONES 2975 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 /* NON-NULL COMM SORTED ASCENDING, ALL NULLS FIRST */ **1 select ename,sal,comm** **2 from (** **3 select ename,sal,comm,** **4 case when comm is null then 0 else 1 end as is_null** **5 from emp** **6 ) x** **7 order by is_null,comm** ENAME SAL COMM ------ ----- ---------- SMITH 800 JONES 2975 CLARK 2450 BLAKE 2850 SCOTT 3000 KING 5000 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 TURNER 1500 0 ALLEN 1600 300 WARD 1250 500 MARTIN 1250 1400 /* NON-NULL COMM SORTED DESCENDING, ALL NULLS FIRST */ **1 select ename,sal,comm** **2 from (** **3 select ename,sal,comm,** **4 case when comm is null then 0 else 1 end as is_null** **5 from emp** **6 ) x** **7 order by is_null,comm desc** ENAME SAL COMM ------ ----- ---------- SMITH 800 JONES 2975 CLARK 2450 BLAKE 2850 SCOTT 3000 KING 5000 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 MARTIN 1250 1400 WARD 1250 500 ALLEN 1600 300 TURNER 1500 0 #### Oracle Users on Oracle8 _i_ Database and earlier can use the solution for the other platforms. Users on Oracle9 _i_ Database and later can use the NULLS FIRST and NULLS LAST extension to the ORDER BYclause to ensure NULLs are sorted first or last regardless of how non-NULL values are sorted: /* NON-NULL COMM SORTED ASCENDING, ALL NULLS LAST */ **1 select ename,sal,comm** **2 from emp** **3 order by comm nulls last** ENAME SAL COMM ------ ----- --------- TURNER 1500 0 ALLEN 1600 300 WARD 1250 500 MARTIN 1250 1400 SMITH 800 JONES 2975 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 /* NON-NULL COMM SORTED ASCENDING, ALL NULLS FIRST */ **1 select ename,sal,comm** **2 from emp** **3 order by comm nulls first** ENAME SAL COMM ------ ----- ---------- SMITH 800 JONES 2975 CLARK 2450 BLAKE 2850 SCOTT 3000 KING 5000 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 TURNER 1500 0 ALLEN 1600 300 WARD 1250 500 MARTIN 1250 1400 /* NON-NULL COMM SORTED DESCENDING, ALL NULLS FIRST */ **1 select ename,sal,comm** **2 from emp** **3 order by comm desc nulls first** ENAME SAL COMM ------ ----- ---------- SMITH 800 JONES 2975 CLARK 2450 BLAKE 2850 SCOTT 3000 KING 5000 JAMES 950 MILLER 1300 FORD 3000 ADAMS 1100 MARTIN 1250 1400 WARD 1250 500 ALLEN 1600 300 TURNER 1500 0 ### Discussion Unless your RDBMS provides you with a way to easily sort NULL values first or last without modifying non-NULL values in the same column (such as Oracle does), you'll need an auxiliary column. ### Tip As of the time of this writing, DB2 users can use NULLS FIRST and NULLS LAST in the ORDER BY subclause of the OVER clause in window functions but not in the ORDER BY clause for the entire result set. The purpose of this extra column (in the query only, not in the table) is to allow you to identify NULL values and sort them altogether, first or last. The following query returns the result set for inline view X for the non-Oracle solution: **select ename,sal,comm,** **case when comm is null then 0 else 1 end as is_null** **from emp** ENAME SAL COMM IS_NULL ------ ----- ---------- ---------- SMITH 800 0 ALLEN 1600 300 1 WARD 1250 500 1 JONES 2975 0 MARTIN 1250 1400 1 BLAKE 2850 0 CLARK 2450 0 SCOTT 3000 0 KING 5000 0 TURNER 1500 0 1 ADAMS 1100 0 JAMES 950 0 FORD 3000 0 MILLER 1300 0 By using the values returned by IS_NULL, you can easily sort NULLS first or last without interfering with the sorting of COMM. ## 2.6. Sorting on a Data Dependent Key ### Problem You want to sort based on some conditional logic. For example: if JOB is "SALESMAN" you want to sort on COMM; otherwise, you want to sort by SAL. You want to return the following result set: ENAME SAL JOB COMM ---------- ---------- --------- ---------- TURNER 1500 SALESMAN 0 ALLEN 1600 SALESMAN 300 WARD 1250 SALESMAN 500 SMITH 800 CLERK JAMES 950 CLERK ADAMS 1100 CLERK MILLER 1300 CLERK MARTIN 1250 SALESMAN 1400 CLARK 2450 MANAGER BLAKE 2850 MANAGER JONES 2975 MANAGER SCOTT 3000 ANALYST FORD 3000 ANALYST KING 5000 PRESIDENT ### Solution Use a CASE expression in the ORDER BY clause: 1 select ename,sal,job,comm 2 from emp 3 order by case when job = 'SALESMAN' then comm else sal end ### Discussion You can use the CASE expression to dynamically change how results are sorted. The values passed to the ORDER BY look as follows: **select ename,sal,job,comm,** **case when job = 'SALESMAN' then comm else sal end as ordered** **from emp** **order by 5** ENAME SAL JOB COMM ORDERED ---------- ---------- --------- ---------- ---------- TURNER 1500 SALESMAN 0 0 ALLEN 1600 SALESMAN 300 300 WARD1 250 SALESMAN 500 500 SMITH 800 CLERK 800 JAMES 950 CLERK 950 ADAMS 1100 CLERK 1100 MILLER 1300 CLERK 1300 MARTIN 1250 SALESMAN 1400 1400 CLARK2 450 MANAGER 2450 BLAKE2 850 MANAGER 2850 JONES2 975 MANAGER 2975 SCOTT 3000 ANALYST 3000 FORD 3000 ANALYST 3000 KING 5000 PRESIDENT 5000 ## Chapter 3. Working with Multiple Tables This chapter introduces the use of joins and set operations to combine data from multiple tables. Joins are the foundation of SQL. Set operations are also very important. If you want to master the complex queries found in the later chapters of this book, you must start here, with joins and set operations. ## 3.1. Stacking One Rowset atop Another ### Problem You want to return data stored in more than one table, conceptually stacking one result set atop the other. The tables do not necessarily have a common key, but their columns do have the same data types. For example, you want to display the name and department number of the employees in department 10 in table EMP, along with the name and department number of each department in table DEPT. You want the result set to look like the following: ENAME_AND_DNAME DEPTNO --------------- ---------- CLARK 10 KING 10 MILLER 10 ---------- ACCOUNTING 10 RESEARCH 20 SALES 30 OPERATIONS 40 ### Solution Use the set operation UNION ALL to combine rows from multiple tables: 1 select ename as ename_and_dname, deptno 2 from emp 3 where deptno = 10 4 union all 5 select '----------', null 6 from t1 7union all 8 select dname, deptno 9 from dept ### Discussion UNION ALL combines rows from multiple row sources into one result set. As with all set operations, the items in all the SELECT lists must match in number and data type. For example, both of the following queries will fail: select deptno | select deptno, dname from dept | from dept union all | union select ename | select deptno from emp | from emp It is important to note, UNION ALL will include duplicates if they exist. If you wish to filter out duplicates, use the UNION operator. For example, a UNION between EMP.DEPTNO and DEPT.DEPTNO returns only four rows: **select deptno** **from emp** **union** **select deptno** **from dept** DEPTNO --------- 10 20 30 40 Specifying UNION rather than UNION ALL will most likely result in a sort operation in order to eliminate duplicates. Keep this in mind when working with large result sets. Using UNION is roughly equivalent to the following query, which applies DISTINCT to the output from a UNION ALL: **select distinct deptno** **from (** **select deptno** **from emp** **union all** **select deptno** **from dept** **)** DEPTNO --------- 10 20 30 40 You wouldn't use DISTINCT in a query unless you had to, and the same rule applies for UNION; don't use it instead of UNION ALL unless you have to. ## 3.2. Combining Related Rows ### Problem You want to return rows from multiple tables by joining on a known common column or joining on columns that share common values. For example, you want to display the names of all employees in department 10 along with the location of each employee's department, but that data is stored in two separate tables. You want the result set to be the following: ENAME LOC ---------- ---------- CLARK NEW YORK KING NEW YORK MILLER NEW YORK ### Solution Join table EMP to table DEPT on DEPTNO: 1 select e.ename, d.loc 2 from emp e, dept d 3 where e.deptno = d.deptno 4 and e.deptno = 10 ### Discussion The solution is an example of a _join_ , or more accurately an _equi-join_, which is a type of _inner join_. A join is an operation that combines rows from two tables into one. An equi-join is one in which the join condition is based on an equality condition (e.g., where one department number equals another). An inner join is the original type of join; each row returned contains data from each table. Conceptually, the result set from a join is produced by first creating a Cartesian product (all possible combinations of rows) from the tables listed in the FROM clause, as seen below: **select e.ename, d.loc,** **e.deptno as emp_deptno,** **d.deptno as dept_deptno** **from emp e, dept d** **where e.deptno = 10** ENAME LOC EMP_DEPTNO DEPT_DEPTNO ---------- ------------- ---------- ----------- CLARK NEW YORK 10 10 KING NEW YORK 10 10 MILLER NEW YORK 10 10 CLARK DALLAS 10 20 KING DALLAS 10 20 MILLER DALLAS 10 20 CLARK CHICAGO 10 30 KING CHICAGO 10 30 MILLER CHICAGO 10 30 CLARK BOSTON 10 40 KING BOSTON 10 40 MILLER BOSTON 10 40 Every employee in table EMP (in department 10) is returned along with every department in the table DEPT. Then, the expression in the WHERE clause involving e.deptno and d.deptno (the join) restricts the result set such that the only rows returned are the ones where EMP.DEPTNO and DEPT.DEPTNO are equal: **select e.ename, d.loc,** **e.deptno as emp_deptno,** **d.deptno as dept_deptno** **from emp e, dept d** **where e.deptno = d.deptno** **and e.deptno = 10** ENAME LOC EMP_DEPTNO DEPT_DEPTNO ---------- -------------- ---------- ----------- CLARK NEW YORK 10 10 KING NEW YORK 10 10 MILLER NEW YORK 10 10 An alternative solution makes use of an explicit JOIN clause (the "INNER" keyword is optional): select e.ename, d.loc from emp e inner join dept d on (e.deptno = d.deptno) where e.deptno = 10 Use the JOIN clause if you prefer to have the join logic in the FROM clause rather than the WHERE clause. Both styles are ANSI compliant and work on all the latest versions of the RDBMSs in this book. ## 3.3. Finding Rows in Common Between Two Tables ### Problem You want to find common rows between two tables but there are multiple columns on which you can join. For example, consider the following view V: **create view V** **as** **select ename,job,sal** **from emp** **where job = 'CLERK'** **select * from V** ENAME JOB SAL ---------- --------- ---------- SMITH CLERK 800 ADAMS CLERK 1100 JAMES CLERK 950 MILLER CLERK 1300 Only clerks are returned from view V. However, the view does not show all possible EMP columns. You want to return the EMPNO, ENAME, JOB, SAL, and DEPTNO of all employees in EMP that match the rows from view V. You want the result set to be the following: EMPNO ENAME JOB SAL DEPTNO -------- ---------- --------- ---------- --------- 7369 SMITH CLERK 800 20 7876 ADAMS CLERK 1100 20 7900 JAMES CLERK 950 30 7934 MILLER CLERK 1300 10 ### Solution Join the tables on all the columns necessary to return the correct result. Alternatively, use the set operation INTERSECT to avoid performing a join and instead return the intersection (common rows) of the two tables. #### MySQL and SQL Server Join table EMP to view V using multiple join conditions: 1 select e.empno,e.ename,e.job,e.sal,e.deptno 2 from emp e, V 3 where e.ename = v.ename 4 and e.job = v.job 5 and e.sal = v.sal Alternatively, you can perform the same join via the JOIN clause: 1 select e.empno,e.ename,e.job,e.sal,e.deptno 2 from emp e join V 3 on ( e.ename = v.ename 4 and e.job = v.job 5 and e.sal = v.sal ) #### DB2, Oracle, and PostgreSQL The MySQL and SQL Server solution also works for DB2, Oracle, and PostgreSQL. It's the solution you should use if you need to return values from view V. If you do not actually need to return columns from view V, you may use the set operation INTERSECT along with an IN predicate: 1 select empno,ename,job,sal,deptno 2 from emp 3 where (ename,job,sal) in ( 4 select ename,job,sal from emp 5intersect 6 select ename,job,sal from V 7 ) ### Discussion When performing joins, you must consider the proper columns to join on in order to return correct results. This is especially important when rows can have common values for some columns while having different values for others. The set operation INTERSECT will return rows common to both row sources. When using INTERSECT, you are required to compare the same number of items, having the same data type, from two tables. When working with set operations keep in mind that, by default, duplicate rows will not be returned. ## 3.4. Retrieving Values from One Table That Do Not Exist in Another ### Problem You wish to find those values in one table, call it the source table, that do not also exist in some target table. For example, you want to find which departments (if any) in table DEPT do not exist in table EMP. In the example data, DEPTNO 40 from table DEPT does not exist in table EMP, so the result set should be the following: DEPTNO ---------- 40 ### Solution Having functions that perform set difference is particularly useful for this problem. DB2, PostgreSQL, and Oracle support set difference operations. If your DBMS does not support a set difference function, use a subquery as shown for MySQL and SQL Server. #### DB2 and PostgreSQL Use the set operation EXCEPT: 1 select deptno from dept 2 except 3 select deptno from emp #### Oracle Use the set operation MINUS: 1 select deptno from dept 2 minus 3 select deptno from emp #### MySQL and SQL Server Use a subquery to return all DEPTNOs from table EMP into an outer query that searches table DEPT for rows that are not amongst the rows returned from the subquery: 1 select deptno 2 from dept 3 where deptno not in (select deptno from emp) ### Discussion #### DB2 and PostgreSQL The built-in functions provided by DB2 and PostgreSQL make this operation quite easy. The EXCEPT operator takes the first result set and removes from it all rows found in the second result set. The operation is very much like a subtraction. There are restrictions on the use of set operators, including EXCEPT. Data types and number of values to compare must match in both SELECT lists. Additionally, EXCEPT will not return duplicates and, unlike a subquery using NOT IN, NULLs do not present a problem (see the discussion for MySQL and SQL Server). The EXCEPT operator will return rows from the upper query (the query before the EXCEPT) that do not exist in the lower query (the query after the EXCEPT). #### Oracle The Oracle solution is identical to that for DB2 and PostgreSQL, except that Oracle calls its set difference operator MINUS rather than EXCEPT. Otherwise, the preceding explanation applies to Oracle as well. #### MySQL and SQL Server The subquery will return all DEPTNOs from table EMP. The outer query returns all DEPTNOs from table DEPT that are "not in" or "not included in" the result set returned from the subquery. Duplicate elimination is something you'll want to consider when using the MySQL and SQL Server solutions. The EXCEPT- and MINUS-based solutions used for the other platforms eliminate duplicate rows from the result set, ensuring that each DEPTNO is reported only one time. Of course, that can only be the case anyway, as DEPTNO is a key field in my example data. Were DEPTNO not a key field, you could use DISTINCT as follows to ensure that each DEPTNO value missing from EMP is reported only once: select distinct deptno from dept where deptno not in (select deptno from emp) Be mindful of NULLs when using NOT IN. Consider the following table, NEW_ DEPT: create table new_dept(deptno integer) insert into new_deptvalues (10) insert into new_dept values (50) insert into new_dept values (null) If you try to find the DEPTNOs in table DEPT that do not exist in table NEW_DEPT and use a subquery with NOT IN, you'll find that the query returns no rows: select * from dept where deptno not in (select deptno from new_dept) DEPTNOs 20, 30, and 40 are not in table NEW_DEPT, yet were not returned by the query. Why? The reason is the NULL value present in table NEW_DEPT. Three rows are returned by the subquery, with DEPTNOs of 10, 50, and NULL. IN and NOT IN are essentially OR operations, and will yield different results because of how NULL values are treated by logical OR evaluations. To understand this, examine the truth tables below (Let T=true, F=false, N=null): OR | T | F | N | +----+---+---+----+ | T | T | T | T | | F | T | F | N | | N | T | N | N | +----+---+---+----+ NOT | +-----+---+ | T | F | | F | T | | N | N | +-----+---+ AND | T | F | N | +-----+---+---+---+ | T | T | F | N | | F | F | F | F | | N | N | F | N | +-----+---+---+---+ Now consider the following example using IN and its equivalent using OR: select deptno from dept where deptno in ( 10,50,null ) DEPTNO ------- 10 select deptno from dept where (deptno=10 or deptno=50 or deptno=null) DEPTNO ------- 10 Why was only DEPTNO 10 returned? There are four DEPTNOs in DEPT, (10,20,30,40), each one is evaluated against the predicate (deptno=10 or deptno=50 or deptno=null). According to the truth tables above, for each DEPTNO (10,20,30,40), the predicate yields: DEPTNO=10 (deptno=10 or deptno=50 or deptno=null) = (10=10 or 10=50 or 10=null) = (T or F or N) = (T or N) = (T) DEPTNO=20 (deptno=10 or deptno=50 or deptno=null) = (20=10 or 20=50 or 20=null) = (F or F or N) = (F or N) = (N) DEPTNO=30 (deptno=10 or deptno=50 or deptno=null) = (30=10 or 30=50 or 30=null) = (F or F or N) = (F or N) = (N) DEPTNO=40 (deptno=10 or deptno=50 or deptno=null) = (40=10 or 40=50 or 40=null) = (F or F or N) = (F or N) = (N) Now it is obvious why only DEPTNO 10 was returned when using IN and OR. Now consider the same example using NOT IN and NOT OR: select deptno from dept where deptno not in ( 10,50,null ) ( no rows ) select deptno from dept where not (deptno=10 or deptno=50 or deptno=null) ( no rows ) Why are no rows returned? Let's check the truth tables: DEPTNO=10 NOT (deptno=10 or deptno=50 or deptno=null) = NOT (10=10 or 10=50 or 10=null) = NOT (T or F or N) = NOT (T or N) = NOT (T) = (F) DEPTNO=20 NOT (deptno=10 or deptno=50 or deptno=null) = NOT (20=10 or 20=50 or 20=null) = NOT (F or F or N) = NOT (F or N) = NOT (N) = (N) DEPTNO=30 NOT (deptno=10 or deptno=50 or deptno=null) = NOT (30=10 or 30=50 or 30=null) = NOT (F or F or N) = NOT (F or N) = NOT (N) = (N) DEPTNO=40 NOT (deptno=10 or deptno=50 or deptno=null) = NOT (40=10 or 40=50 or 40=null) = NOT (F or F or N) = NOT (F or N) = NOT (N) = (N) In SQL, "TRUE or NULL" is TRUE, but "FALSE or NULL" is NULL! You must keep this in mind when using IN predicates and when performing logical OR evaluations, and NULL values are involved. To avoid the problem with NOT IN and NULLs, use a correlated subquery in conjunction with NOT EXISTS. The term "correlated subquery" is used because rows from the outer query are referenced in the subquery. The following example is an alternative solution that will not be affected by NULL rows (going back to the original query from the "Problem" section): select d.deptno from dept d where not exists ( select 1 from emp e where d.deptno = e.deptno ) DEPTNO ---------- 40 select d.deptno from dept d where not exists ( select 1 from new_dept nd where d.deptno = nd.deptno ) DEPTNO ---------- 30 40 20 Conceptually, the outer query in this solution considers each row in the DEPT table. For each DEPT row, the following happens: 1. The subquery is executed to see whether the department number exists in the EMP table. Note the condition D.DEPTNO = E.DEPTNO, which brings together the department numbers from the two tables. 2. If the subquery returns results, then EXISTS (...) evaluates to true and NOT EXISTS (...) thus evaluates to FALSE, and the row being considered by the outer query is discarded. 3. If the subquery returns no results, then NOT EXISTS (...) evaluates to TRUE, and the row being considered by the outer query is returned (because it is for a department not represented in the EMP table). The items in the SELECT list of the subquery are unimportant when using a correlated subquery with EXISTS/NOT EXISTS, which is why I chose to select NULL, to force you to focus on the join in the subquery rather than the items in the SELECT list. ## 3.5. Retrieving Rows from One Table That Do Not Correspond to Rows in Another ### Problem You want to find rows that are in one table that do not have a match in another table, for two tables that have common keys. For example, you want to find which departments have no employees. The result set should be the following: DEPTNO DNAME LOC ---------- -------------- ------------- 40 OPERATIONS BOSTON Finding the department each employee works in requires an equi-join on DEPTNO from EMP to DEPT. The DEPTNO column represents the common value between tables. Unfortunately, an equi-join will not show you which department has no employees. That's because by equi-joining EMP and DEPT you are returning all rows that satisfy the join condition. Instead you want only those rows from DEPT that do not satisfy the join condition. This is a subtly different problem than in the preceding recipe, though at first glance they may seem the same. The difference is that the preceding recipe yields only a list of department numbers not represented in table EMP. Using this recipe, however, you can easily return other columns from the DEPT table; you can return more than just department numbers. ### Solution Return all rows from one table along with rows from another that may or may not have a match on the common column. Then, keep only those rows with no match. #### DB2, MySQL, PostgreSQL, SQL Server Use an outer join and filter for NULLs (keyword OUTER is optional): 1 select d.* 2 from dept d left outer join emp e 3 on (d.deptno = e.deptno) 4 where e.deptno is null #### Oracle For users on Oracle9 _i_ Database and later, the preceding solution will work. Alternatively, you can use the proprietary Oracle outer-join syntax: 1 select d.* 2 from dept d, emp e 3 where d.deptno = e.deptno (+) 4 and e.deptno is null This proprietary syntax (note the use of the "+" in parens) is the only outer-join syntax available in Oracle8 _i_ Database and earlier. ### Discussion This solution works by outer joining and then keeping only rows that have no match. This sort of operation is sometimes called an _anti-join_. To get a better idea of how an anti-join works, first examine the result set without filtering for NULLs: **select e.ename, e.deptno as emp_deptno, d.*** **from dept d left join emp e** **on (d.deptno = e.deptno)** ENAME EMP_DEPTNO DEPTNO DNAME LOC ---------- ---------- ---------- -------------- ------------- SMITH 20 20 RESEARCH DALLAS ALLEN 30 30 SALES CHICAGO WARD 30 30 SALES CHICAGO JONES 20 20 RESEARCH DALLAS MARTIN 30 30 SALES CHICAGO BLAKE 30 30 SALES CHICAGO CLARK 10 10 ACCOUNTING NEW YORK SCOTT 20 20 RESEARCH DALLAS KING 10 10 ACCOUNTING NEW YORK TURNER 30 30 SALES CHICAGO ADAMS 20 20 RESEARCH DALLAS JAMES 30 30 SALES CHICAGO FORD 20 20 RESEARCH DALLAS MILLER 10 10 ACCOUNTING NEW YORK 40 OPERATIONS BOSTON Notice, the last row has a NULL value for EMP.ENAME and EMP_DEPTNO. That's because no employees work in department 40. The solution uses the WHERE clause to keep only rows where EMP_DEPTNO is NULL (thus keeping only rows from DEPT that have no match in EMP). ## 3.6. Adding Joins to a Query Without Interfering with Other Joins ### Problem You have a query that returns the results you want. You need additional information, but when trying to get it, you lose data from the original result set. For example, you want to return all employees, the location of the department in which they work, and the date they received a bonus. For this problem, the EMP_BONUS table contains the following data: **select * from emp_bonus** EMPNO RECEIVED TYPE ---------- ----------- ---------- 7369 14-MAR-2005 1 7900 14-MAR-2005 2 7788 14-MAR-2005 3 The query you start with looks like this: **select e.ename, d.loc** **from emp e, dept d** **where e.deptno=d.deptno** ENAME LOC ---------- ------------- SMITH DALLAS ALLEN CHICAGO WARD CHICAGO JONES DALLAS MARTIN CHICAGO BLAKE CHICAGO CLARK NEW YORK SCOTT DALLAS KING NEW YORK TURNER CHICAGO ADAMS DALLAS JAMES CHICAGO FORD DALLAS MILLER NEW YORK You want to add to these results the date a bonus was given to an employee, but joining to the EMP_BONUS table returns fewer rows than you wish because not every employee has a bonus: **select e.ename, d.loc,eb.received** **from emp e, dept d, emp_bonus eb** **where e.deptno=d.deptno** **and e.empno=eb.empno** ENAME LOC RECEIVED ---------- ------------- ----------- SCOTT DALLAS 14-MAR-2005 SMITH DALLAS 14-MAR-2005 JAMES CHICAGO 14-MAR-2005 Your desired result set is the following: ENAME LOC RECEIVED ---------- ------------- ----------- ALLEN CHICAGO WARD CHICAGO MARTIN CHICAGO JAMES CHICAGO 14-MAR-2005 TURNER CHICAGO BLAKE CHICAGO SMITH DALLAS 14-MAR-2005 FORD DALLAS ADAMS DALLAS JONES DALLAS SCOTT DALLAS 14-MAR-2005 CLARK NEW YORK KING NEW YORK MILLER NEW YORK ### Solution You can use an outer join to obtain the additional information without losing the data from the original query. First join table EMP to table DEPT to get all employees and the location of the department they work, then outer join to table EMP_ BONUS to return the date of the bonus if there is one. Following is the DB2, MySQL, PostgreSQL, and SQL Server syntax: 1 select e.ename, d.loc, eb.received 2 from emp e join dept d 3 on (e.deptno=d.deptno) 4 left join emp_bonus eb 5 on (e.empno=eb.empno) 6 order by 2 If you are using Oracle9 _i_ Database or later, the preceding solution will work for you. Alternatively, you can use Oracle's proprietary outer-join syntax, which is your only choice when using Oracle8 _i_ Database and earlier: 1 select e.ename, d.loc, eb.received 2 from emp e, dept d, emp_bonus eb 3 where e.deptno=d.deptno 4 and e.empno=eb.empno (+) 5 order by 2 You can also use a scalar subquery (a subquery placed in the SELECT list) to mimic an outer join: 1 select e.ename, d.loc, 2 (select eb.received from emp_bonus eb 3 where eb.empno=e.empno) as received 4 from emp e, dept d 5 where e.deptno=d.deptno 6 order by 2 The scalar subquery solution will work across all platforms. ### Discussion An outer join will return all rows from one table and matching rows from another. See the previous recipe for another example of such a join. The reason an outer join works to solve this problem is that it does not result in any rows being eliminated that would otherwise be returned. The query will return all the rows it would return without the outer join. And it also returns the received date, if one exists. Use of a scalar subquery is also a convenient technique for this sort of problem, as it does not require you to modify already correct joins in your main query. Using a scalar subquery is an easy way to tack on extra data to a query without compromising the current result set. When working with scalar subqueries, you must ensure they return a scalar (single) value. If a subquery in the SELECT list returns more than one row, you will receive an error. ### See Also See "Converting a Scalar Subquery to a Composite Subquery in Oracle" in Chapter 14 for a workaround to the problem of not being able to return multiple rows from a SELECT-list subquery. ## 3.7. Determining Whether Two Tables Have the Same Data ### Problem You want to know if two tables or views have the same data (cardinality and values). Consider the following view: **create view V** **as** **select * from emp where deptno != 10** **union all** **select * from emp where ename = 'WARD'** **select * from V** EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO ----- ---------- --------- ----- ----------- ----- ----- ------ 7369 SMITH CLERK 7902 17-DEC-1980 800 20 7499 ALLEN SALESMAN 7698 20-FEB-1981 1600 300 30 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 7566 JONES MANAGER 7839 02-APR-1981 2975 20 7654 MARTIN SALESMAN 7698 28-SEP-1981 1250 1400 30 7698 BLAKE MANAGER 7839 01-MAY-1981 2850 30 7788 SCOTT ANALYST 7566 09-DEC-1982 3000 20 7844 TURNER SALESMAN 7698 08-SEP-1981 1500 0 30 7876 ADAMS CLERK 7788 12-JAN-1983 1100 20 7900 JAMES CLERK 7698 03-DEC-1981 950 30 7902 FORD ANALYST 7566 03-DEC-1981 3000 20 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 You want to determine whether or not this view has exactly the same data as table EMP. The row for employee "WARD" is duplicated to show that the solution will reveal not only different data but duplicates as well. Based on the rows in table EMP the difference will be the three rows for employees in department 10 and the two rows for employee "WARD". You want to return the following result set: EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO CNT ----- ---------- --------- ----- ----------- ----- ----- ------ --- 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 1 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 2 7782 CLARK MANAGER 7839 09-JUN-1981 2450 10 1 7839 KING PRESIDENT 17-NOV-1981 5000 10 1 7934 MILLER CLERK 7782 23-JAN-1982 1300 10 1 ### Solution Functions that perform SET difference (MINUS or EXCEPT, depending on your DBMS) make the problem of comparing tables a relatively easy one to solve. If your DBMS does not offer such functions, you can use a correlated subquery. #### DB2 and PostgreSQL Use the set operations EXCEPT and UNION ALL to find the difference between view V and table EMP combined with the difference between table EMP and view V: 1 ( 2 select empno,ename,job,mgr,hiredate,sal,comm,deptno, 3 count(*) as cnt 4 from V 5 group by empno,ename,job,mgr,hiredate,sal,comm,deptno 6 except 7 select empno,ename,job,mgr,hiredate,sal,comm,deptno, 8 count(*) as cnt 9 from emp 10 group by empno,ename,job,mgr,hiredate,sal,comm,deptno 11 ) 12 union all 13 ( 14 select empno,ename,job,mgr,hiredate,sal,comm,deptno, 15 count(*) as cnt 16 from emp 17 group by empno,ename,job,mgr,hiredate,sal,comm,deptno 18 except 19 select empno,ename,job,mgr,hiredate,sal,comm,deptno, 20 count(*) as cnt 21 from v 22 group by empno,ename,job,mgr,hiredate,sal,comm,deptno 23 ) #### Oracle Use the set operations MINUS and UNION ALL to find the difference between view V and table EMP combined with the difference between table EMP and view V: 1 ( 2 select empno,ename,job,mgr,hiredate,sal,comm,deptno, 3 count(*) as cnt 4 from V 5 group by empno,ename,job,mgr,hiredate,sal,comm,deptno 6 minus 7 select empno,ename,job,mgr,hiredate,sal,comm,deptno, 8 count(*) as cnt 9 from emp 10 group by empno,ename,job,mgr,hiredate,sal,comm,deptno 11 ) 12 union all 13 ( 14 select empno,ename,job,mgr,hiredate,sal,comm,deptno, 15 count(*) as cnt 16 from emp 17 group by empno,ename,job,mgr,hiredate,sal,comm,deptno 18 minus 19 select empno,ename,job,mgr,hiredate,sal,comm,deptno, 20 count(*) as cnt 21 from v 22 group by empno,ename,job,mgr,hiredate,sal,comm,deptno 23 ) #### MySQL and SQL Server Use a correlated subquery and UNION ALL to find the rows in view V and not in table EMP combined with the rows in table EMP and not in view V: 1 select * 2 from ( 3 select e.empno,e.ename,e.job,e.mgr,e.hiredate, 4 e.sal,e.comm,e.deptno, count(*) as cnt 5 from emp e 6 group by empno,ename,job,mgr,hiredate, 7 sal,comm,deptno 8 ) e 9 where not exists ( 10 select null 11 from ( 12 select v.empno,v.ename,v.job,v.mgr,v.hiredate, 13 v.sal,v.comm,v.deptno, count(*) as cnt 14 from v 15 group by empno,ename,job,mgr,hiredate, 16 sal,comm,deptno 17 ) v 18 where v.empno = e.empno 19 and v.ename = e.ename 20 and v.job = e.job 21 and coalesce(v.mgr,0) = coalesce(e.mgr,0) 22 and v.hiredate = e.hiredate 23 and v.sal = e.sal 24 and v.deptno = e.deptno 25 and v.cnt = e.cnt 26 and coalesce(v.comm,0) = coalesce(e.comm,0) 27 ) 28 union all 29 select * 30 from ( 31 select v.empno,v.ename,v.job,v.mgr,v.hiredate, 32 v.sal,v.comm,v.deptno, count(*) as cnt 33 from v 34 group by empno,ename,job,mgr,hiredate, 35 sal,comm,deptno 36 ) v 37 where not exists ( 38 select null 39 from ( 40 select e.empno,e.ename,e.job,e.mgr,e.hiredate, 41 e.sal,e.comm,e.deptno, count(*) as cnt 42 from emp e 43 group by empno,ename,job,mgr,hiredate, 44 sal,comm,deptno 45 ) e 46 where v.empno = e.empno 47 and v.ename = e.ename 48 and v.job = e.job 49 and coalesce(v.mgr,0) = coalesce(e.mgr,0) 50 and v.hiredate = e.hiredate 51 and v.sal = e.sal 52 and v.deptno = e.deptno 53 and v.cnt = e.cnt 54 and coalesce(v.comm,0) = coalesce(e.comm,0) 55 ) ### Discussion Despite using different techniques, the concept is the same for all solutions: 1. First, find rows in table EMP that do not exist in view V. 2. Then combine (UNION ALL) those rows with rows from view V that do not exist in table EMP. If the tables in question are equal, then no rows are returned. If the tables are different, the rows causing the difference are returned. As an easy first step when comparing tables, you can compare the cardinalities alone rather than including them with the data comparison. The following query is a simple example of this and will work on all DBMSs: **select count(*)** **from emp** **union** **select count(*)** **from dept** COUNT(*) -------- 4 14 Because UNION will filter out duplicates, only one row will be returned if the tables' cardinalities are the same. Because two rows are returned in this example, you know that the tables do not contain identical rowsets. #### DB2, Oracle, and PostgreSQL MINUS and EXCEPT work in the same way, so I will use EXCEPT for this discussion. The queries before and after the UNION ALL are very similar. So, to understand how the solution works, simply execute the query prior to the UNION ALL by itself. The following result set is produced by executing lines 1–11 in the solution section: **(** **select empno,ename,job,mgr,hiredate,sal,comm,deptno,** **count(*) as cnt** **from V** **group by empno,ename,job,mgr,hiredate,sal,comm,deptno** **except** **select empno,ename,job,mgr,hiredate,sal,comm,deptno,** **count(*) as cnt** **from emp** **group by empno,ename,job,mgr,hiredate,sal,comm,deptno** **)** EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO CNT ----- ---------- --------- ----- ----------- ----- ----- ------ --- 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 2 The result set represents a row found in view V that is either not in table EMP or has a different cardinality than that same row in table EMP. In this case, the duplicate row for employee "WARD" is found and returned. If you're still having trouble understanding how the result set is produced, run each query on either side of EXCEPT individually. You'll notice the only difference between the two result sets is the CNT for employee "WARD" returned by view V. The portion of the query after the UNION ALL does the opposite of the query preceding UNION ALL. The query returns rows in table EMP not in view V: **(** **select empno,ename,job,mgr,hiredate,sal,comm,deptno,** **count(*) as cnt** **from emp** **group by empno,ename,job,mgr,hiredate,sal,comm,deptno** **minus** **select empno,ename,job,mgr,hiredate,sal,comm,deptno,** **count(*) as cnt** **from v** **group by empno,ename,job,mgr,hiredate,sal,comm,deptno** **)** EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO CNT ----- ---------- --------- ----- ----------- ----- ----- ------ --- 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 1 7782 CLARK MANAGER 7839 09-JUN-1981 2450 10 1 7839 KING PRESIDENT 17-NOV-1981 5000 10 1 7934 MILLER CLERK 7782 23-JAN-1982 1300 10 1 The results are then combined by UNION ALL to produce the final result set. #### MySQL and SQL Server The queries before and after the UNION ALL are very similar. To understand how the subquery-based solution works, simply execute the query prior to the UNION ALL by itself. The query below is from lines 1–27 in the solution: **select *** **from (** **select e.empno,e.ename,e.job,e.mgr,e.hiredate,** **e.sal,e.comm,e.deptno, count(*) as cnt** **from emp e** **group by empno,ename,job,mgr,hiredate,** **sal,comm,deptno** **) e** **where not exists (** **select null** **from (** **select v.empno,v.ename,v.job,v.mgr,v.hiredate,** **v.sal,v.comm,v.deptno, count(*) as cnt** **from v** **group by empno,ename,job,mgr,hiredate,** **sal,comm,deptno** **) v** **where v.empno = e.empno** **and v.ename = e.ename** **and v.job = e.job** **and v.mgr = e.mgr** **and v.hiredate = e.hiredate** **and v.sal = e.sal** **and v.deptno = e.deptno** **and v.cnt = e.cnt** **and coalesce(v.comm,0) = coalesce(e.comm,0)** **)** EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO CNT ----- ---------- --------- ----- ----------- ----- ----- ------ --- 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 1 7782 CLARK MANAGER 7839 09-JUN-1981 2450 10 1 7839 KING PRESIDENT 17-NOV-1981 5000 10 1 7934 MILLER CLERK 7782 23-JAN-1982 1300 10 1 Notice that the comparison is not between table EMP and view V, but rather between inline view E and inline view V. The cardinality for each row is found and returned as an attribute for that row. You are comparing each row and its occurrence count. If you are having trouble understanding how the comparison works, run the subqueries independently. The next step is to find all rows (including CNT) in inline view E that do not exist in inline view V. The comparison uses a correlated subquery and NOT EXISTS. The joins will determine which rows are the same, and the result will be all rows from inline view E that are not the rows returned by the join. The query after the UNION ALL does the opposite; it finds all rows in inline view V that do not exist in inline view E: **select *** **from (** **select v.empno,v.ename,v.job,v.mgr,v.hiredate,** **v.sal,v.comm,v.deptno, count(*) as cnt** **from v** **group by empno,ename,job,mgr,hiredate,** **sal,comm,deptno** **) v** **where not exists (** **select null** **from (** **select e.empno,e.ename,e.job,e.mgr,e.hiredate,** **e.sal,e.comm,e.deptno, count(*) as cnt** **from emp e** **group by empno,ename,job,mgr,hiredate,** **sal,comm,deptno** **) e** **where v.empno = e.empno** **and v.ename = e.ename** **and v.job = e.job** **and v.mgr = e.mgr** **and v.hiredate = e.hiredate** **and v.sal = e.sal** **and v.deptno = e.deptno** **and v.cnt = e.cnt** **and coalesce(v.comm,0) = coalesce(e.comm,0)** **)** EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO CNT ----- ---------- --------- ----- ----------- ----- ----- ------ --- 7521 WARD SALESMAN 7698 22-FEB-1981 1250 500 30 2 The results are then combined by UNION ALL to produce the final result set. ### Tip Ales Spectic and Jonathan Gennick give an alternate solution in their book _Transact-SQL Cookbook_ (O'Reilly). See the section "Comparing Two Sets for Equality" in Chapter 2. ## 3.8. Identifying and Avoiding Cartesian Products ### Problem You want to return the name of each employee in department 10 along with the location of the department. The following query is returning incorrect data: **select e.ename, d.loc** **from emp e, dept d** **where e.deptno = 10** ENAME LOC ---------- ------------- CLARK NEW YORK CLARK DALLAS CLARK CHICAGO CLARK BOSTON KING NEW YORK KING DALLAS KING CHICAGO KING BOSTON MILLER NEW YORK MILLER DALLAS MILLER CHICAGO MILLER BOSTON The correct result set is the following: ENAME LOC ---------- --------- CLARK NEW YORK KING NEW YORK MILLER NEW YORK ### Solution Use a join between the tables in the FROM clause to return the correct result set: 1 select e.ename, d.loc 2 from emp e, dept d 3 where e.deptno = 10 4 and d.deptno = e.deptno ### Discussion Looking at the data in the DEPT table: **select * from dept** DEPTNO DNAME LOC ---------- -------------- ------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON You can see that department 10 is in New York, and thus you can know that returning employees with any location other than New York is incorrect. The number of rows returned by the incorrect query is the product of the cardinalities of the two tables in the FROM clause. In the original query, the filter on EMP for department 10 will result in three rows. Because there is no filter for DEPT, all four rows from DEPT are returned. Three multiplied by four is twelve, so the incorrect query returns twelve rows. Generally, to avoid a Cartesian product you would apply the _n_ –1 rule where _n_ represents the number of tables in the FROM clause and _n_ –1 represents the minimum number of joins necessary to avoid a Cartesian product. Depending on what the keys and join columns in your tables are, you may very well need more than _n_ –1 joins, but _n_ –1 is a good place to start when writing queries. ### Tip When used properly, Cartesian products can be very useful. The recipe, , uses a Cartesian product and is used by many other queries. Common uses of Cartesian products include transposing or pivoting (and unpivoting) a result set, generating a sequence of values, and mimicking a loop. ## 3.9. Performing Joins when Using Aggregates ### Problem You want to perform an aggregation but your query involves multiple tables. You want to ensure that joins do not disrupt the aggregation. For example, you want to find the sum of the salaries for employees in department 10 along with the sum of their bonuses. Some employees have more than one bonus and the join between table EMP and table EMP_BONUS is causing incorrect values to be returned by the aggregate function SUM. For this problem, table EMP_BONUS contains the following data: **select * from emp_bonus** EMPNO RECEIVED TYPE ----- ----------- ---------- 7934 17-MAR-2005 1 7934 15-FEB-2005 2 7839 15-FEB-2005 3 7782 15-FEB-2005 1 Now, consider the following query that returns the salary and bonus for all employees in department 10. Table BONUS.TYPE determines the amount of the bonus. A type 1 bonus is 10% of an employee's salary, type 2 is 20%, and type 3 is 30%. **select e.empno,** **e.ename,** **e.sal,** **e.deptno,** **e.sal*case when eb.type = 1 then .1** **when eb.type = 2 then .2** **else .3** **end as bonus** **from emp e, emp_bonus eb** **where e.empno = eb.empno** **and e.deptno = 10** EMPNO ENAME SAL DEPTNO BONUS ------- ---------- ---------- ---------- --------- 7934 MILLER 1300 10 130 7934 MILLER 1300 10 260 7839 KING 5000 10 1500 7782 CLARK 2450 10 245 So far, so good. However, things go awry when you attempt a join to the EMP_ BONUS table in order to sum the bonus amounts: **select deptno,** **sum(sal) as total_sal,** **sum(bonus) as total_bonus** **from (** **select e.empno,** **e.ename,** **e.sal,** **e.deptno,** **e.sal*case when eb.type = 1 then .1** **when eb.type = 2 then .2** **else .3** **end as bonus** **from emp e, emp_bonus eb** **where e.empno = eb.empno** **and e.deptno = 10** **) x** **group by deptno** DEPTNO TOTAL_SAL TOTAL_BONUS ------ ----------- ----------- 10 10050 2135 While the TOTAL_BONUS is correct, the TOTAL_SAL is incorrect. The sum of all salaries in department 10 is 8750, as the following query shows: **select sum(sal) from emp where deptno=10** SUM(SAL) ---------- 8750 Why is TOTAL_SAL incorrect? The reason is the duplicate rows in the SAL column created by the join. Consider the following query, which joins table EMP and EMP_ BONUS: **select e.ename,** **e.sal** **from emp e, emp_bonus eb** **where e.empno = eb.empno** **and e.deptno = 10** ENAME SAL ---------- ---------- CLARK 2450 KING 5000 MILLER 1300 MILLER 1300 Now it is easy to see why the value for TOTAL_SAL is incorrect: MILLER's salary is counted twice. The final result set that you are really after is: DEPTNO TOTAL_SAL TOTAL_BONUS ------ --------- ----------- 10 8750 2135 ### Solution You have to be careful when computing aggregates across joins. Typically when duplicates are returned due to a join, you can avoid miscalculations by aggregate functions in two ways: you can simply use the keyword DISTINCT in the call to the aggregate function, so only unique instances of each value are used in the computation; or you can perform the aggregation first (in an inline view) prior to joining, thus avoiding the incorrect computation by the aggregate function because the aggregate will already be computed before you even join, thus avoiding the problem altogether. The solutions that follow use DISTINCT. The "Discussion" section will discuss the technique of using an inline view to perform the aggregation prior to joining. #### MySQL and PostgreSQL Perform a sum of only the DISTINCT salaries: 1 select deptno, 2 sum(distinct sal) as total_sal, 3 sum(bonus) as total_bonus 4 from ( 5 select e.empno, 6 e.ename, 7 e.sal, 8 e.deptno, 9 e.sal*case when eb.type = 1 then .1 10 when eb.type = 2 then .2 11 else .3 12 end as bonus 13 from emp e, emp_bonus eb 14 where e.empno = eb.empno 15 and e.deptno = 10 16 ) x 17 group by deptno #### DB2, Oracle, and SQL Server These platforms support the preceding solution, but they also support an alternative solution using the window function SUM OVER: 1 select distinct deptno,total_sal,total_bonus 2 from ( 3 select e.empno, 4 e.ename, 5 sum(distinct e.sal) over 6 (partition by e.deptno) as total_sal, 7 e.deptno, 8 sum(e.sal*case when eb.type = 1 then .1 9 when eb.type = 2 then .2 10 else .3 end) over 11 (partition by deptno) as total_bonus 12 from emp e, emp_bonus eb 13 where e.empno = eb.empno 14 and e.deptno = 10 15 ) x ### Discussion #### MySQL and PostgreSQL The second query in the "Problem" section of this recipe joins table EMP and table EMP_BONUS and returns two rows for employee "MILLER", which is what causes the error on the sum of EMP.SAL (the salary is added twice). The solution is to simply sum the distinct EMP.SAL values that are returned by the query. The following query is an alternative solution—necessary if there could be duplicate values in the column you are summing. The sum of all salaries in department 10 is computed first and that row is then joined to table EMP, which is then joined to table EMP_BONUS. The following query works for all DBMSs: **select d.deptno,** **d.total_sal,** **sum(e.sal*case when eb.type = 1 then .1** **when eb.type = 2 then .2** **else .3 end) as total_bonus** **from emp e,** **emp_bonus eb,** **(** **select deptno, sum(sal) as total_sal** **from emp** **where deptno = 10** **group by deptno** **) d** **where e.deptno = d.deptno** **and e.empno = eb.empno** **group by d.deptno,d.total_sal** DEPTNO TOTAL_SAL TOTAL_BONUS --------- ---------- ------------ 10 8750 2135 #### DB2, Oracle, and SQL Server This alternative solution takes advantage of the window function SUM OVER. The following query is taken from lines 3–14 in "Solution" and returns the following result set: **select e.empno,** **e.ename,** **sum(distinct e.sal) over** **(partition by e.deptno) as total_sal,** **e.deptno,** **sum(e.sal*case when eb.type = 1 then .1** **when eb.type = 2 then .2** **else .3 end) over** **(partition by deptno) as total_bonus** **from emp e, emp_bonus eb** **where e.empno = eb.empno** **and e.deptno = 10** EMPNO ENAME TOTAL_SAL DEPTNO TOTAL_BONUS ----- ---------- ---------- ------ ----------- 7934 MILLER 8750 10 2135 7934 MILLER 8750 10 2135 7782 CLARK 8750 10 2135 7839 KING 8750 10 2135 The windowing function, SUM OVER, is called twice, first to compute the sum of the distinct salaries for the defined partition or group. In this case, the partition is DEPTNO 10 and the sum of the distinct salaries for DEPTNO 10 is 8750. The next call to SUM OVER computes the sum of the bonuses for the same defined partition. The final result set is produced by taking the distinct values for TOTAL_SAL, DEPTNO, and TOTAL_BONUS. ## 3.10. Performing Outer Joins when Using Aggregates ### Problem Begin with the same problem as in 3.9, but modify table EMP_BONUS such that the difference in this case is not all employees in department 10 have been given bonuses. Consider the EMP_BONUS table and a query to (ostensibly) find both the sum of all salaries for department 10 and the sum of all bonuses for all employees in department 10: **select * from emp_bonus** EMPNO RECEIVED TYPE ---------- ----------- ---------- 7934 17-MAR-2005 1 7934 15-FEB-2005 2 **select deptno,** **sum(sal) as total_sal,** **sum(bonus) as total_bonus** **from (** **select e.empno,** **e.ename,** **e.sal,** **e.deptno,** **e.sal*case when eb.type = 1 then .1** **when eb.type = 2 then .2** **else .3 end as bonus** **from emp e, emp_bonus eb** **where e.empno = eb.empno** **and e.deptno = 10** **)** **group by deptno** DEPTNO TOTAL_SAL TOTAL_BONUS ------ ---------- ----------- 10 2600 390 The result for TOTAL_BONUS is correct, but the value returned for TOTAL_SAL does not represent the sum of all salaries in department 10. The following query shows why the TOTAL_SAL is incorrect: **select e.empno,** **e.ename,** **e.sal,** **e.deptno,** **e.sal*case when eb.type = 1 then .1** **when eb.type = 2 then .2** **else .3 end as bonus** **from emp e, emp_bonus eb** **where e.empno = eb.empno** **and e.deptno = 10** EMPNO ENAME SAL DEPTNO BONUS --------- --------- ------- ---------- ---------- 7934 MILLER 1300 10 130 7934 MILLER 1300 10 260 Rather than sum all salaries in department 10, only the salary for "MILLER" is summed and it is erroneously summed twice. Ultimately, you would like to return the following result set: DEPTNO TOTAL_SAL TOTAL_BONUS ------ --------- ----------- 10 8750 390 ### Solution The solution is similar to that of 3.9, but here you outer join to EMP_BONUS to ensure all employees from department 10 are included. #### DB2, MySQL, PostgreSQL, SQL Server Outer join to EMP_BONUS, then perform the sum on only distinct salaries from department 10: 1 select deptno, 2 sum(distinct sal) as total_sal, 3 sum(bonus) as total_bonus 4 from ( 5 select e.empno, 6 e.ename, 7 e.sal, 8 e.deptno, 9 e.sal*case when eb.type is null then 0 10 when eb.type = 1 then .1 11 when eb.type = 2 then .2 12 else .3 end as bonus 13 from emp e left outer join emp_bonus eb 14 on (e.empno = eb.empno) 15 where e.deptno = 10 16 ) 17 group by deptno You can also use the window function SUM OVER: 1 select distinct deptno,total_sal,total_bonus 2 from ( 3 select e.empno, 4 e.ename, 5 sum(distinct e.sal) over 6 (partition by e.deptno) as total_sal, 7 e.deptno, 8 sum(e.sal*case when eb.type is null then 0 9 when eb.type = 1 then .1 10 when eb.type = 2 then .2 11 else .3 12 end) over 13 (partition by deptno) as total_bonus 14 from emp e left outer join emp_bonus eb 15 on (e.empno = eb.empno) 16 where e.deptno = 10 17 ) x #### Oracle If you are using Oracle9 _i_ Database or later you can use the preceding solution. Alternatively, you can use the proprietary Oracle outer-join syntax, which is mandatory for users on Oracle8 _i_ Database and earlier: 1 select deptno, 2 sum(distinct sal) as total_sal, 3 sum(bonus) as total_bonus 4 from ( 5 select e.empno, 6 e.ename, 7 e.sal, 8 e.deptno, 9 e.sal*case when eb.type is null then 0 10 when eb.type = 1 then .1 11 when eb.type = 2 then .2 12 else .3 end as bonus 13 from emp e, emp_bonus eb 14 where e.empno = eb.empno (+) 15 and e.deptno = 10 16 ) 17 group by deptno Oracle 8 _i_ Database users can also use the SUM OVER syntaxshown for DB2 and the other databases, but must modify it to use the proprietary Oracle outer-join syntax shown in the preceding query. ### Discussion The second query in the "Problem" section of this recipe joins table EMP and table EMP_BONUS and returns only rows for employee "MILLER", which is what causes the error on the sum of EMP.SAL (the other employees in DEPTNO 10 do not have bonuses and their salaries are not included in the sum). The solution is to outer join table EMP to table EMP_BONUS so even employees without a bonus will be included in the result. If an employee does not have a bonus, NULL will be returned for EMP_BONUS.TYPE. It is important to keep this in mind as the CASE statement has been modified and is slightly different from solution 3.9. If EMP_BONUS.TYPE is NULL, the CASE expression returns zero, which has no effect on the sum. The following query is an alternative solution. The sum of all salaries in department 10 is computed first, then joined to table EMP, which is then joined to table EMP_BONUS (thus avoiding the outer join). The following query works for all DBMSs: **select d.deptno,** **d.total_sal,** **sum(e.sal*case when eb.type = 1 then .1** **when eb.type = 2 then .2** **else .3 end) as total_bonus** **from emp e,** **emp_bonus eb,** **(** **select deptno, sum(sal) as total_sal** **from emp** **where deptno = 10** **group by deptno** **) d** **where e.deptno = d.deptno** **and e.empno = eb.empno** **group by d.deptno,d.total_sal** DEPTNO TOTAL_SAL TOTAL_BONUS --------- ---------- ----------- 10 8750 390 ## 3.11. Returning Missing Data from Multiple Tables ### Problem You want to return missing data from multiple tables simultaneously. Returning rows from table DEPT that do not exist in table EMP (any departments that have no employees) requires an outer join. Consider the following query, which returns all DEPTNOs and DNAMEs from DEPT along with the names of all the employees in each department (if there is an employee in a particular department): **select d.deptno,d.dname,e.ename** **from dept d left outer join emp e** **on (d.deptno=e.deptno)** DEPTNO DNAME ENAME --------- -------------- ---------- 20 RESEARCH SMITH 30 SALES ALLEN 30 SALES WARD 20 RESEARCH JONES 30 SALES MARTIN 30 SALES BLAKE 10 ACCOUNTING CLARK 20 RESEARCH SCOTT 10 ACCOUNTING KING 30 SALES TURNER 20 RESEARCH ADAMS 30 SALES JAMES 20 RESEARCH FORD 10 ACCOUNTING MILLER 40 OPERATIONS The last row, the OPERATIONS department, is returned despite that department not having any employees, because table EMP was outer joined to table DEPT. Now, suppose there was an employee without a department. How would you return the above result set along with a row for the employee having no department? In other words, you want to outer join to both table EMP and table DEPT, and in the same query. After creating the new employee, a first attempt may look like this: insert into emp (empno,ename,job,mgr,hiredate,sal,comm,deptno) select 1111,'YODA','JEDI',null,hiredate,sal,comm,null from emp where ename = 'KING' **select d.deptno,d.dname,e.ename** **from dept d right outer join emp e** **on (d.deptno=e.deptno)** DEPTNO DNAME ENAME ---------- ------------ ---------- 10 ACCOUNTING MILLER 10 ACCOUNTING KING 10 ACCOUNTING CLARK 20 RESEARCH FORD 20 RESEARCH ADAMS 20 RESEARCH SCOTT 20 RESEARCH JONES 20 RESEARCH SMITH 30 SALES JAMES 30 SALES TURNER 30 SALES BLAKE 30 SALES MARTIN 30 SALES WARD 30 SALES ALLEN YODA This outer join manages to return the new employee but lost the OPERATIONS department from the original result set. The final result set should return a row for YODA as well as OPERATIONS, such as the following: DEPTNO DNAME ENAME ---------- ------------ -------- 10 ACCOUNTING CLARK 10 ACCOUNTING KING 10 ACCOUNTING MILLER 20 RESEARCH ADAMS 20 RESEARCH FORD 20 RESEARCH JONES 20 RESEARCH SCOTT 20 RESEARCH SMITH 30 SALES ALLEN 30 SALES BLAKE 30 SALES JAMES 30 SALES MARTIN 30 SALES TURNER 30 SALES WARD 40 OPERATIONS YODA ### Solution Use a full outer join to return missing data from both tables based on a common value. #### DB2, MySQL, PostgreSQL, SQL Server Use the explicit FULL OUTER JOIN command to return missing rows from both tables along with matching rows: 1 select d.deptno,d.dname,e.ename 2 from dept d full outer join emp e 3 on (d.deptno=e.deptno) Alternatively, since MySQL does not yet have a FULL OUTER JOIN, union the results of the two different outer joins: 1 select d.deptno,d.dname,e.ename 2 from dept d right outer join emp e 3 on (d.deptno=e.deptno) 4 union 5 select d.deptno,d.dname,e.ename 6 from dept d left outer join emp e 7 on (d.deptno=e.deptno) #### Oracle If you are on Oracle9 _i_ Database or later, you can use either of the preceding solutions. Alternatively, you can use Oracle's proprietary outer join syntax, which is the only choice for users on Oracle8 _i_ Database and earlier: 1 select d.deptno,d.dname,e.ename 2 from dept d, emp e 3 where d.deptno = e.deptno(+) 4 union 5 select d.deptno,d.dname,e.ename 6 from dept d, emp e 7 where d.deptno(+) = e.deptno ### Discussion The full outer join is simply the combination of outer joins on both tables. To see how a full outer join works "under the covers," simply run each outer join, then union the results. The following query returns rows from table DEPT and any matching rows from table EMP (if any). **select d.deptno,d.dname,e.ename** **from dept d left outer join emp e** **on (d.deptno = e.deptno)** DEPTNO DNAME ENAME ------ -------------- ---------- 20 RESEARCH SMITH 30 SALES ALLEN 30 SALES WARD 20 RESEARCH JONES 30 SALES MARTIN 30 SALES BLAKE 10 ACCOUNTING CLARK 20 RESEARCH SCOTT 10 ACCOUNTING KING 30 SALES TURNER 20 RESEARCH ADAMS 30 SALES JAMES 20 RESEARCH FORD 10 ACCOUNTING MILLER 40 OPERATIONS This next query returns rows from table EMP and any matching rows from table DEPT (if any): **select d.deptno,d.dname,e.ename** **from dept d right outer join emp e** **on (d.deptno = e.deptno)** DEPTNO DNAME ENAME ------ -------------- ---------- 10 ACCOUNTING MILLER 10 ACCOUNTING KING 10 ACCOUNTING CLARK 20 RESEARCH FORD 20 RESEARCH ADAMS 20 RESEARCH SCOTT 20 RESEARCH JONES 20 RESEARCH SMITH 30 SALES JAMES 30 SALES TURNER 30 SALES BLAKE 30 SALES MARTIN 30 SALES WARD 30 SALES ALLEN YODA The results from these two queries are unioned to provide the final result set. ## 3.12. Using NULLs in Operations and Comparisons ### Problem NULL is never equal to or not equal to any value, not even itself, but you want to evaluate values returned by a nullable column like you would evaluate real values. For example, you want to find all employees in EMP whose commission (COMM) is less than the commission of employee "WARD". Employees with a NULL commission should be included as well. ### Solution Use a function such as COALESCE to transform the NULL value into a real value that can be used in standard evaluation: 1 select ename,comm 2 from emp 3 where coalesce(comm,0) < ( select comm 4 from emp 5 where ename = 'WARD' ) ### Discussion The COALESCE function will return the first non-NULL value from the list of values passed to it. When a NULL value is encountered it is replaced by zero, which is then compared with Ward's commission. This can be seen by putting the COALESCE function in the SELECT list: **select ename,comm,coalesce(comm,0)** **from emp** **where coalesce(comm,0)< ( select comm** **from emp** **where ename = 'WARD' )** ENAME COMM COALESCE(COMM,0) ---------- ---------- ---------------- SMITH 0 ALLEN 300 300 JONES 0 BLAKE 0 CLARK 0 SCOTT 0 KING 0 TURNER 0 0 ADAMS 0 JAMES 0 FORD 0 MILLER 0 ## Chapter 4. Inserting, Updating, Deleting The past few chapters have focused on basic query techniques, all centered around the task of getting data out of a database. This chapter turns the tables, and focuses on the following three topic areas: * Inserting new records into your database * Updating existing records * Deleting records that you no longer want For ease in finding them when you need them, recipes in this chapter have been grouped by topic: all the insertion recipes come first, followed by the update recipes, and finally recipes for deleting data. Inserting is usually a straightforward task. It begins with the simple problem of inserting a single row. Many times, however, it is more efficient to use a set-based approach to create new rows. To that end, you'll also find techniques for inserting many rows at a time. Likewise, updating and deleting start out as simple tasks. You can update one record, and you can delete one record. But you can also update whole sets of records at once, and in very powerful ways. And there are many handy ways to delete records. For example, you can delete rows in one table depending on whether or not they exist in another table. SQL even has a way, a relatively new addition to the standard, by which you can insert, update, and delete all at once. That may not sound like too useful a thing now, but the MERGE statement represents a very powerful way to bring a database table into sync with an external source of data (such as a flat file feed from a remote system). Check out Section in this chapter for details. ## 4.1. Inserting a New Record ### Problem You want to insert a new record into a table. For example, you want to insert a new record into the DEPT table. The value for DEPTNO should be 50, DNAME should be "PROGRAMMING", and LOC should be "BALTIMORE". ### Solution Use the INSERT statement with the VALUES clause to insert one row at a time: insert into dept (deptno,dname,loc) values (50,'PROGRAMMING','BALTIMORE') For DB2 and MySQL you have the option of inserting one row at a time or multiple rows at a time by including multiple VALUES lists: /* multi row insert */ insert into dept (deptno,dname,loc) values (1,'A','B'), (2,'B','C') ### Discussion The INSERT statement allows you to create new rows in database tables. The syntax for inserting a single row is consistent across all database brands. As a shortcut, you can omit the column list in an INSERT statement: insert into dept values (50,'PROGRAMMING','BALTIMORE') However, if you do not list your target columns, you must insert into _all_ of the columns in the table, and be mindful of the order of the values in the VALUES list; you must supply values in the same order in which the database displays columns in response to a SELECT * query. ## 4.2. Inserting Default Values ### Problem A table can be defined to take default values for specific columns. You want to insert a row of default values without having to specify those values. Consider the following table: create table D (id integer default 0) You want to insert zero without explicitly specifying zero in the values list of an INSERT statement. You want to explicitly insert the default, whatever that default is. ### Solution All brands support use of the DEFAULT keyword as a way of explicitly specifying the default value for a column. Some brands provide additional ways to solve the problem. The following example illustrates the use of the DEFAULT keyword: insert into D values (default) You may also explicitly specify the column name, which you'll need to do anytime you are not inserting into all columns of a table: insert into D (id) values (default) Oracle8 _i_ Database and prior versions do not support the DEFAULT keyword. Prior to Oracle9 _i_ Database, there was no way to explicitly insert a default column value. MySQL allows you to specify an empty values list if all columns have a default value defined: insert into D values () In this case, all columns will be set to their default values. PostgreSQL and SQL Server support a DEFAULT VALUES clause: insert into D default values The DEFAULT VALUES clause causes all columns to take on their default values. ### Discussion The DEFAULT keyword in the values list will insert the value that was specified as the default for a particular column during table creation. The keyword is available for all DBMSs. MySQL, PostgreSQL, and SQL Server users have another option available if all columns in the table are defined with a default value (as table D is in this case). You may use an empty VALUES list (MySQL) or specify the DEFAULT VALUES clause (PostgreSQL and SQL Server) to create a new row with all default values; otherwise, you need to specify DEFAULT for each column in the table. For tables with a mix of default and non-default columns, inserting default values for a column is as easy as excluding the column from the insert list; you do not need to use the DEFAULT keyword. Say that table D had an additional column that was not defined with a default value: create table D (id integer default 0, foo varchar(10)) You can insert a default for ID by listing only FOO in the insert list: insert into D (name) values ('Bar') This statement will result in a row in which ID is 0 and FOO is "Bar". ID takes on its default value because no other value is specified. ## 4.3. Overriding a Default Value with NULL ### Problem You are inserting into a column having a default value, and you wish to override that default value by setting the column to NULL. Consider the following table: create table D (id integer default 0, foo VARCHAR(10)) You wish to insert a row with a NULL value for ID. ### Solution You can explicitly specify NULL in your values list: insert into d (id, foo) values (null, 'Brighten') ### Discussion Not everyone realizes that you can explicitly specify NULL in the values list of an INSERT statement. Typically, when you do not wish to specify a value for a column, you leave that column out of your column and values lists: insert into d (foo) values ('Brighten') Here, no value for ID is specified. Many would expect the column to taken on the null value, but, alas, a default value was specified at table creation time, so the result of the preceding INSERT is that ID takes on the value 0 (the default). By specifying NULL as the value for a column, you can set the column to NULL despite any default value. ## 4.4. Copying Rows from One Table into Another ### Problem You want to copy rows from one table to another by using a query. The query may be complex or simple, but ultimately you want the result to be inserted into another table. For example, you want to copy rows from the DEPT table to the DEPT_EAST table. The DEPT_EAST table has already been created with the same structure (same columns and data types) as DEPT and is currently empty. ### Solution Use the INSERT statement followed by a query to produce the rows you want: 1 insert into dept_east (deptno,dname,loc) 2 select deptno,dname,loc 3 from dept 4 where loc in ( 'NEW YORK','BOSTON' ) ### Discussion Simply follow the INSERT statement with a query that returns the desired rows. If you want to copy all rows from the source table, exclude the WHERE clause from the query. Like a regular insert, you do not have to explicitly specify which columns you are inserting into. But if you do not specify your target columns, you must insert into _all_ of the table's columns, and you must be mindful of the order of the values in the SELECT list as described earlier in "Inserting a New Record." ## 4.5. Copying a Table Definition ### Problem You want to create a new table having the same set of columns as an existing table. For example, you want to create a copy of the DEPT table and call it DEPT_2. You do not want to copy the rows, only the column structure of the table. ### Solution #### DB2 Use the LIKE clause with the CREATE TABLE command: create table dept_2 like dept #### Oracle, MySQL, and PostgreSQL Use the CREATE TABLE command with a subquery that returns no rows: 1 create table dept_2 2 as 3 select * 4 from dept 5 where 1 = 0 #### SQL Server Use the INTO clause with a subquery that returns no rows: 1 select * 2 into dept_2 3 from dept 4 where 1 = 0 ### Discussion #### DB2 DB2's CREATE TABLE...LIKE command allows you to easily use one table as the pattern for creating another. Simply specify your pattern table's name following the LIKE keyword. #### Oracle, MySQL, and PostgreSQL When using Create Table As Select (CTAS), all rows from your query will be used to populate the new table you are creating unless you specify a false condition in the WHERE clause. In the solution provided, the expression "1 = 0" in the WHERE clause of the query causes no rows to be returned. Thus the result of the CTAS statement is an empty table based on the columns in the SELECT clause of the query. #### SQL Server When using INTO to copy a table, all rows from your query will be used to populate the new table you are creating unless you specify a false condition in the WHERE clause of your query. In the solution provided, the expression "1 = 0" in the predicate of the query causes no rows to be returned. The result is an empty table based on the columns in the SELECT clause of the query. ## 4.6. Inserting into Multiple Tables at Once ### Problem You want to take rows returned by a query and insert those rows into multiple target tables. For example, you want to insert rows from DEPT into tables DEPT_EAST, DEPT_WEST, and DEPT_MID. All three tables have the same structure (same columns and data types) as DEPT and are currently empty. ### Solution The solution is to insert the result of a query into the target tables. The difference from "Copying Rows from One Table into Another" is that for this problem you have multiple target tables. #### Oracle Use either the INSERT ALL or INSERT FIRST statement. Both share the same syntax except for the choice between the ALL and FIRST keywords. The following statement uses INSERT ALL to cause all possible target tables to be considered: 1 insert all 2 when loc in ('NEW YORK','BOSTON') then 3into dept_east (deptno,dname,loc) values (deptno,dname,loc) 4 when loc = 'CHICAGO' then 5 into dept_mid (deptno,dname,loc) values (deptno,dname,loc) 6 else 7 into dept_west (deptno,dname,loc) values (deptno,dname,loc) 8 select deptno,dname,loc 9 from dept #### DB2 Insert into an inline view that performs a UNION ALL on the tables to be inserted. You must also be sure to place constraints on the tables that will ensure each row goes into the correct table: create table dept_east ( deptno integer, dname varchar(10), loc varchar(10) check (loc in ('NEW YORK','BOSTON'))) create table dept_mid ( deptno integer, dname varchar(10), loc varchar(10) check (loc = 'CHICAGO')) create table dept_west ( deptno integer, dname varchar(10), loc varchar(10) check (loc = 'DALLAS')) 1 insert into ( 2 select * from dept_west union all 3 select * from dept_east union all 4 select * from dept_mid 5 ) select * from dept #### MySQL, PostgreSQL, and SQL Server As of the time of this writing, these vendors do not support multi-table inserts. ### Discussion #### Oracle Oracle's multi-table insert uses WHEN-THEN-ELSE clauses to evaluate the rows from the nested SELECT and insert them accordingly. In this recipe's example, INSERT ALL and INSERT FIRST would produce the same result, but there is a difference between the two. INSERT FIRST will break out of the WHEN-THEN-ELSE evaluation as soon as it encounters a condition evaluating to true; INSERT ALL will evaluate all conditions even if prior tests evaluate to true. Thus, you can use INSERT ALL to insert the same row into more than one table. #### DB2 My DB2 solution is a bit of a hack. It requires that the tables to be inserted into have constraints defined to ensure that each row evaluated from the subquery will go into the correct table. The technique is to insert into a view that is defined as the UNION ALL of the tables. If the check constraints are not unique amongst the tables in the INSERT (i.e., multiple tables have the same check constraint), the INSERT statement will not know where to put the rows and it will fail. #### MySQL, PostgreSQL, and SQL Server As of the time of this writing, only Oracle and DB2 currently provide mechanisms to insert rows returned by a query into one or more of several tables within the same statement. ## 4.7. Blocking Inserts to Certain Columns ### Problem You wish to prevent users, or an errant software application, from inserting values into certain table columns. For example, you wish to allow a program to insert into EMP, but only into the EMPNO, ENAME, and JOB columns. ### Solution Create a view on the table exposing only those columns you wish to expose. Then force all inserts to go through that view. For example, to create a view exposing the three columns in EMP: create view new_emps as select empno, ename, job from emp Grant access to this view to those users and programs allowed to populate only the three fields in the view. Do not grant those users insert access to the EMP table. Users may then create new EMP records by inserting into the NEW_EMPS view, but they will not be able to provide values for columns other than the three that are specified in the view definition. ### Discussion When you insert into a simple view such as in the solution, your database server will translate that insert into the underlying table. For example, the following insert: insert into new_emps (empno ename, job) values (1, 'Jonathan', 'Editor') will be translated behind the scenes into: insert into emp (empno ename, job) values (1, 'Jonathan', 'Editor') It is also possible, but perhaps less useful, to insert into an inline view (currently only supported by Oracle): insert into (select empno, ename, job from emp) values (1, 'Jonathan', 'Editor') View insertion is a complex topic. The rules become very complicated very quickly for all but the simplest of views. If you plan to make use of the ability to insert into views, it is imperative that you consult and fully understand your vendor documentation on the matter. ## 4.8. Modifying Records in a Table ### Problem You want to modify values for some or all rows in a table. For example, you might want to increase the salaries of everyone in department 20 by 10%. The following result set shows the DEPTNO, ENAME, and SAL for employees in that department: **select deptno,ename,sal** **from emp** **where deptno = 20** **order by 1,3** DEPTNO ENAME SAL ------ ---------- ---------- 20 SMITH 800 20 ADAMS 1100 20 JONES 2975 20 SCOTT 3000 20 FORD 3000 You want to bump all the SAL values by 10%. ### Solution Use the UPDATE statement to modify existing rows in a database table. For example: 1 update emp 2 set sal = sal*1.10 3 where deptno = 20 ### Discussion Use the UPDATE statement along with a WHERE clause to specify which rows to update; if you exclude a WHERE clause, then all rows are updated. The expression SAL*1.10 in this solution returns the salary increased by 10%. When preparing for a mass update, you may wish to preview the results. You can do that by issuing a SELECT statement that includes the expressions you plan to put into your SET clauses. The following SELECT shows the result of a 10% salary increase: **select deptno,** **ename,** **sal as orig_sal,** **sal*.10 as amt_to_add,** **sal*1.10 as new_sal** **from emp** **where deptno=20** **order by 1,5** DEPTNO ENAME ORIG_SAL AMT_TO_ADD NEW_SAL ------ ------ -------- ---------- ------- 20 SMITH 800 80 880 20 ADAMS 1100 110 1210 20 JONES 2975 298 3273 20 SCOTT 3000 300 3300 20 FORD 3000 300 3300 The salary increase is broken down into two columns: one to show the increase over the old salary, and the other to show the new salary. ## 4.9. Updating when Corresponding Rows Exist ### Problem You want to update rows in one table when corresponding rows exist in another. For example, if an employee appears in table EMP_BONUS, you want to increase that employee's salary (in table EMP) by 20 percent. The following result set represents the data currently in table EMP_BONUS: **select empno, ename** **from emp_bonus** EMPNO ENAME ---------- --------- 7369 SMITH 7900 JAMES 7934 MILLER ### Solution Use a subquery in your UPDATE statement's WHERE clause to find employees in table EMP that are also in table EMP_BONUS. Your UPDATE will then act only on those rows, enabling you to increase their salary by 20 percent: 1 update emp 2 set sal=sal*1.20 3 where empno in ( select empno from emp_bonus ) ### Discussion The results from the subquery represent the rows that will be updated in table EMP. The IN predicate tests values of EMPNO from the EMP table to see whether they are in the list of EMPNO values returned by the subquery. When they are, the corresponding SAL values are updated. Alternatively, you can use EXISTS instead of IN: update emp set sal = sal*1.20 where exists ( select null from emp_bonus where emp.empno=emp_bonus.empno ) You may be surprised to see NULL in the SELECT list of the EXISTS subquery. Fear not, that NULL does not have an adverse effect on the update. In my opinion it increases readability as it reinforces the fact that, unlike the solution using a subquery with an IN operator, what will drive the update (i.e., which rows will be updated) will be controlled by the WHERE clause of the subquery, not the values returned as a result of the subquery's SELECT list. ## 4.10. Updating with Values from Another Table ### Problem You wish to update rows in one table using values from another. For example, you have a table called NEW_SAL, which holds the new salaries for certain employees. The contents of table NEW_SAL are: **select *** **from new_sal** DEPTNO SAL ------ ---------- 10 4000 Column DEPTNO is the primary key of table NEW_SAL. You want to update the salaries and commission of certain employees in table EMP using values table NEW_SAL if there is a match between EMP.DEPTNO and NEW_SAL.DEPTNO, update EMP.SAL to NEW_SAL.SAL, and update EMP.COMM to 50% of NEW_SAL.SAL. The rows in EMP are as follows: **select deptno,ename,sal,comm** **from emp** **order by 1** DEPTNO ENAME SAL COMM ------ ---------- ---------- ---------- 10 CLARK 2450 10 KING 5000 10 MILLER 1300 20 SMITH 800 20 ADAMS 1100 20 FORD 3000 20 SCOTT 3000 20 JONES 2975 30 ALLEN 1600 300 30 BLAKE 2850 30 MARTIN 1250 1400 30 JAMES 950 30 TURNER 1500 0 30 WARD 1250 500 ### Solution Use a join between NEW_SAL and EMP to find and return the new COMM values to the UPDATE statement. It is quite common for updates such as this one to be performed via correlated subquery. Another technique involves creating a view (traditional or inline, depending on what your database supports), then updating that view. #### DB2 Use a correlated subquery to set new SAL and COMM values in EMP. Also use a correlated subquery to identify which rows from EMP should be updated: 1 update emp e set (e.sal,e.comm) = (select ns.sal, ns.sal/2 2 from new_sal ns 3 where ns.deptno=e.deptno) 4 where exists ( select * 5 from new_sal ns 6 where ns.deptno = e.deptno ) #### MySQL Include both EMP and NEW_SAL in the UPDATE clause of the UPDATE statement and join in the WHERE clause: 1 update emp e, new_sal ns 2 set e.sal=ns.sal, 3 e.comm=ns.sal/2 4 where e.deptno=ns.deptno #### Oracle The method for the DB2 solution will certainly work for Oracle, but as an alternative, you can update an inline view: 1 update ( 2 select e.sal as emp_sal, e.comm as emp_comm, 3 ns.sal as ns_sal, ns.sal/2 as ns_comm 4 from emp e, new_sal ns 5 where e.deptno = ns.deptno 6 ) set emp_sal = ns_sal, emp_comm = ns_comm #### PostgreSQL The method used for the DB2 solution will work for PostgreSQL, but as an alternative you can (quite conveniently) join directly in the UPDATE statement: 1 update emp 2 set sal = ns.sal, 3 comm = ns.sal/2 4 from new_sal ns 5 where ns.deptno = emp.deptno #### SQL Server The method used for the DB2 solution will work for SQL Server, but as an alternative you can (similarly to the PostgreSQL solution) join directly in the UPDATE statement: 1 update e 2 set e.sal = ns.sal, 3 e.comm = ns.sal/2 4 from emp e, 5 new_sal ns 6 where ns.deptno = e.deptno ### Discussion Before discussing the different solutions, I'd like to mention something important regarding updates that use queries to supply new values. A WHERE clause in the subquery of a correlated update is not the same as the WHERE clause of the table being updated. If you look at the UPDATE statement in the "Problem" section, the join on DEPTNO between EMP and NEW_SAL is done and returns rows to the SET clause of the UPDATE statement. For employees in DEPTNO 10, valid values are returned because there is a match DEPTNO in table NEW_SAL. But what about employees in the other departments? NEW_SAL does not have any other departments, so the SAL and COMM for employees in DEPTNOs 20 and 30 are set to NULL. Unless you are doing so via LIMIT or TOP or whatever mechanism your vendor supplies for limiting the number of rows returned in a result set, the only way to restrict rows from a table in SQL is to use a WHERE clause. To correctly perform this UPDATE, use a WHERE clause on the table being updated along with a WHERE clause in the correlated subquery. #### DB2 To ensure you do not update every row in table EMP, remember to include a correlated subquery in the WHERE clause of the UPDATE. Performing the join (the correlated subquery) in the SET clause is not enough. By using a WHERE clause in the UPDATE, you ensure that only rows in EMP that match on DEPTNO to table NEW_SAL are updated. This holds true for all RDBMSs. #### Oracle In the Oracle solution using the update join view, you are using equi-joins to determine which rows will be updated. You can confirm which rows are being updated by executing the query independently. To be able to successfully use this type of UPDATE, you must first understand the concept of key-preservation. The DEPTNO column of the table NEW_SAL is the primary key of that table, thus its values are unique within the table. When joining between EMP and NEW_SAL, however, NEW_SAL.DEPTNO is not unique in the result set, as can be seen below: **select e.empno, e.deptno e_dept, ns.sal, ns.deptno ns_deptno** **from emp e, new_sal ns** **where e.deptno = ns.deptno** EMPNO E_DEPT SAL NS_DEPTNO ----- ---------- ---------- ---------- 7782 10 4000 10 7839 10 4000 10 7934 10 4000 10 To enable Oracle to update this join, one of the tables must be key-preserved, meaning that if its values are not unique in the result set, it should at least be unique in the table it comes from. In this case NEW_SAL has a primary key on DEPTNO, which makes it unique in the table. Because it is unique in its table, it may appear multiple times in the result set and will still be considered key-preserved, thus allowing the update to complete successfully. #### PostgreSQL, SQL Server, and MySQL The syntax is a bit different between these platforms, but the technique is the same. Being able to join directly in the UPDATE statement is extremely convenient. Since you specify which table to update (the table listed after the UPDATE keyword) there's no confusion as to which table's rows are modified. Additionally, because you are using joins in the update (since there is an explicit WHERE clause), you can avoid some of the pitfalls when coding correlated subquery updates; in particular, if you missed a join here, it would be very obvious you'd have a problem. ## 4.11. Merging Records ### Problem You want to conditionally insert, update, or delete records in a table depending on whether or not corresponding records exist. (If a record exists, then update; if not,then insert; if after updating a row fails to meet a certain condition, delete it.) For example, you want to modify table EMP_COMMISSION such that: * If any employee in EMP_COMMISSION also exists in table EMP, then update their commission (COMM) to 1000. * For all employees who will potentially have their COMM updated to 1000, if their SAL is less than 2000, delete them (they should not be exist in EMP_COMMISSION). * Otherwise, insert the EMPNO, ENAME, and DEPTNO values from table EMP into table EMP_COMMISSION. Essentially, you wish to execute either an UPDATE or an INSERT depending on whether a given row from EMP has a match in EMP_COMMISSION. Then you wish to execute a DELETE if the result of an UPDATE causes a commission that's too high. The following rows are currently in tables EMP and EMP_COMMISSION, respectively: **select deptno,empno,ename,comm** **from emp** **order by 1** DEPTNO EMPNO ENAME COMM ------ ---------- ------ ---------- 10 7782 CLARK 10 7839 KING 10 7934 MILLER 20 7369 SMITH 20 7876 ADAMS 20 7902 FORD 20 7788 SCOTT 20 7566 JONES 30 7499 ALLEN 300 30 7698 BLAKE 30 7654 MARTIN 1400 30 7900 JAMES 30 7844 TURNER 0 30 7521 WARD 500 **select deptno,empno,ename,comm** **from emp_commission** **order by 1** DEPTNO EMPNO ENAME COMM ---------- ---------- ---------- ---------- 10 7782 CLARK 10 7839 KING 10 7934 MILLER ### Solution Oracle is currently the only RDBMS with a statement designed to solve this problem. That statement is the MERGE statement, and it can perform either an UPDATE or an INSERT, as needed. For example: 1 merge into emp_commission ec 2 using (select * from emp) emp 3 on (ec.empno=emp.empno) 4 when matched then 5 update set ec.comm = 1000 6 delete where (sal < 2000) 7 when not matched then 8 insert (ec.empno,ec.ename,ec.deptno,ec.comm) 9 values (emp.empno,emp.ename,emp.deptno,emp.comm) ### Discussion The join on line 3 of the solution determines what rows already exist and will be updated. The join is between EMP_COMMISSION (aliased as EC) and the subquery (aliased as emp). When the join succeeds, the two rows are considered "matched" and the UPDATE specified in the WHEN MATCHED clause is executed. Otherwise, no match is found and the INSERT in WHEN NOT MATCHED is executed. Thus, rows from table EMP that do not have corresponding rows based on EMPNO in table EMP_COMMISSION will be inserted into EMP_COMMISSION. Of all the employees in table EMP only those in DEPTNO 10 should have their COMM updated in EMP_COMMISSION, while the rest of the employees are inserted. Additionally, since MILLER is in DEPTNO 10 he is a candidate to have his COMM updated, but because his SAL is less than 2000 it is deleted from EMP_COMMISSION. ## 4.12. Deleting All Records from a Table ### Problem You want to delete all the records from a table. ### Solution Use the DELETE command to delete records from a table. For example, to delete all records from EMP: delete from emp ### Discussion When using the DELETE command without a WHERE clause, you will delete all rows from the table specified. ## 4.13. Deleting Specific Records ### Problem You wish to delete records meeting a specific criterion from a table. ### Solution Use the DELETE command with a WHERE clause specifying which rows to delete. For example, to delete all employees in department 10: delete from emp where deptno = 10 ### Discussion By using a WHERE clause with the DELETE command, you can delete a subset of rows in a table rather than all the rows. ## 4.14. Deleting a Single Record ### Problem You wish to delete a single record from a table. ### Solution This is a special case of "Deleting Specific Records." The key is to ensure that your selection criterion is narrow enough to specify only the one record that you wish to delete. Often you will want to delete based on the primary key. For example, to delete employee CLARK (EMPNO 7782): delete from emp where empno = 7782 ### Discussion Deleting is always about identifying the rows to be deleted, and the impact of a DELETE always comes down to its WHERE clause. Omit the WHERE clause and the scope of a DELETE is the entire table. By writing conditions in the WHERE clause, you can narrow the scope to a group of records, or to a single record. When deleting a single record, you should typically be identifying that record based on its primary key or on one of its unique keys. ### Warning If your deletion criterion is based on a primary or unique key, then you can be sure of deleting only one record. (This is because your RDBMS will not allow two rows to contain the same primary or unique key values.) Otherwise, you may want to check first, to be sure you aren't about to inadvertently delete more records than you intend. ## 4.15. Deleting Referential Integrity Violations ### Problem You wish to delete records from a table when those records refer to nonexistent records in some other table. Example: some employees are assigned to departments that do not exist. You wish to delete those employees. ### Solution Use the NOT EXISTS predicate with a subquery to test the validity of department numbers: delete from emp where not exists ( select * from dept where dept.deptno = emp.deptno ) Alternatively, you can write the query using a NOT IN predicate: delete from emp where deptno not in (select deptno from dept) ### Discussion Deleting is really all about selecting: the real work lies in writing WHERE clause conditions to correctly describe those records that you wish to delete. The NOT EXISTS solution uses a correlated subquery to test for the existence of a record in DEPT having a DEPTNO matching that in a given EMP record. If such a record exists, then the EMP record is retained. Otherwise, it is deleted. Each EMP record is checked in this manner. The IN solution uses a subquery to retrieve a list of valid department numbers. DEPTNOs from each EMP record are then checked against that list. When an EMP record is found with a DEPTNO not in the list, the EMP record is deleted. ## 4.16. Deleting Duplicate Records ### Problem You want to delete duplicate records from a table. Consider the following table: **create table dupes (id integer, name varchar(10))** insert into dupes values (1, 'NAPOLEON') insert into dupes values (2, 'DYNAMITE') insert into dupes values (3, 'DYNAMITE') insert into dupes values (4, 'SHE SELLS') insert into dupes values (5, 'SEA SHELLS') insert into dupes values (6, 'SEA SHELLS') insert into dupes values (7, 'SEA SHELLS') **select * from dupes order by 1** ID NAME ---------- ---------- 1 NAPOLEON 2 DYNAMITE 3 DYNAMITE 4 SHE SELLS 5 SEA SHELLS 6 SEA SHELLS 7 SEA SHELLS For each group of duplicate names, such as "SEA SHELLS", you wish to arbitrarily retain one ID and delete the rest. In the case of "SEA SHELLS" you don't care whether you delete 5 and 6, or 5 and 7, or 6 and 7, but in the end you want just one record for "SEA SHELLS". ### Solution Use a subquery with an aggregate function such as MIN to arbitrarily choose the ID to retain (in this case only the NAME with the smallest value for ID is not deleted): 1 delete from dupes 2 where id not in ( select min(id) 3 from dupes 4 group by name ) For MySQL users you will need slightly different syntax because you cannot reference the same table twice in a delete (as of the time of this writing): 1 delete from dupes 2 where id not in 3 (select min(id) 4 from (select id,name from dupes) tmp 5 group by name) ### Discussion The first thing to do when deleting duplicates is to define exactly what it means for two rows to be considered "duplicates" of each other. For my example in this recipe, the definition of "duplicate" is that two records contain the same value in their NAME column. Having that definition in place, you can look to some other column to discriminate among each set of duplicates, to identify those records to retain. It's best if this discriminating column (or columns) is a primary key. I used the ID column, which is a good choice because no two records have the same ID. The key to the solution is that you group by the values that are duplicated (by NAME in this case), and then use an aggregate function to pick off just one key value to retain. The subquery in the "Solution" example will return the smallest ID for each NAME, which represents the row you will not delete: **select min(id)** **from dupes** **group by name** MIN(ID) ----------- 2 1 5 4 The DELETE then deletes any ID in the table that is not returned by the subquery (in this case IDs 3, 6, and 7). If you are having trouble seeing how this works, run the subquery first and include the NAME in the SELECT list: **select name, min(id)** **from dupes** **group by name** NAME MIN(ID) ---------- ---------- DYNAMITE 2 NAPOLEON 1 SEA SHELLS 5 SHE SELLS 4 The rows returned by the subquery represent those to be retained. The NOT IN predicate in the DELETE statement causes all other rows to be deleted. ## 4.17. Deleting Records Referenced from Another Table ### Problem You want to delete records from one table when those records are referenced from some other table. Consider the following table, named DEPT_ACCIDENTS, which contains one row for each accident that occurs in a manufacturing business. Each row records the department in which an accident occurred and also the type of accident. **create table dept_accidents** **( deptno integer,** **accident_name varchar(20) )** **insert into dept_accidents values (10,'BROKEN FOOT')** **insert into dept_accidents values (10,'FLESH WOUND')** **insert into dept_accidents values (20,'FIRE')** **insert into dept_accidents values (20,'FIRE')** **insert into dept_accidents values (20,'FLOOD')** **insert into dept_accidents values (30,'BRUISED GLUTE')** **select * from dept_accidents** DEPTNO ACCIDENT_NAME ---------- -------------------- 10 BROKEN FOOT 10 FLESH WOUND 20 FIRE 20 FIRE 20 FLOOD 30 BRUISED GLUTE You want to delete from EMP the records for those employees working at a department that has three or more accidents. ### Solution Use a subquery and the aggregate function COUNT to find the departments with three or more accidents. Then delete all employees working in those departments: 1 delete from emp 2 where deptno in ( select deptno 3 from dept_accidents 4 group by deptno 5 having count(*) >= 3 ) ### Discussion The subquery will identify which departments have three or more accidents: **select deptno** **from dept_accidents** **group by deptno** **having count(*)>= 3** DEPTNO ---------- 20 The DELETE will then delete any employees in the departments returned by the subquery (in this case, only in department 20). ## Chapter 5. Metadata Queries This chapter presents recipes that allow you to find information about a given schema. For example, you may wish to know what tables you've created or which foreign keys are not indexed. All of the RDBMSs in this book provide tables and views for obtaining such data. The recipes in this chapter will get you started on gleaning information from those tables and views. There is, however, far more information available than the recipes in this chapter can show. Consult your RDBMSs documentation for the complete list of catalog or data dictionary tables/views. ### Tip For purposes of demonstration, all the recipes in this chapter assume the schema name SMEAGOL. ## 5.1. Listing Tables in a Schema ### Problem You want to see a list all the tables you've created in a given schema. ### Solution The solutions that follow all assume you are working with the SMEAGOL schema. The basic approach to a solution is the same for all RDBMSs: you query a system table (or view) containing a row for each table in the database. #### DB2 Query SYSCAT.TABLES: 1 select tabname 2 from syscat.tables 3 where tabschema = 'SMEAGOL' #### Oracle Query SYS.ALL_TABLES: select table_name from all_tables where owner = 'SMEAGOL' #### PostgreSQL, MySQL, and SQL Server Query INFORMATION_SCHEMA.TABLES: 1 select table_name 2 from information_schema.tables 3 where table_schema = 'SMEAGOL' ### Discussion In a delightfully circular manner, databases expose information about themselves through the very mechanisms that you create for your own applications: tables and views. Oracle, for example, maintains an extensive catalog of system views, such as ALL_TABLES, that you can query for information about tables, indexes, grants, and any other database object. ### Tip Oracle's catalog views are just that, views. They are based on an underlying set of tables that contain the information in a very user-unfriendly form. The views put a very usable face on Oracle's catalog data. Oracle's system views and DB2's system tables are each vendor-specific. PostgreSQL, MySQL, and SQL Server, on the other hand, support something called the _information_ schema, which is a set of views defined by the ISO SQL standard. That's why the same query can work for all three of those databases. ## 5.2. Listing a Table's Columns ### Problem You want to list the columns in a table, along with their data types, and their position in the table they are in. ### Solution The following solutions assume that you wish to list columns, their data types, and their numeric position in the table named EMP in the schema SMEAGOL. #### DB2 Query SYSCAT.COLUMNS: 1 select colname, typename, colno 2 from syscat.columns 3 where tabname = 'EMP' 4 and tabschema = 'SMEAGOL' #### Oracle Query ALL_TAB_COLUMNS: 1 select column_name, data_type, column_id 2 from all_tab_columns 3 where owner = 'SMEAGOL' 4 and table_name = 'EMP' #### PostgreSQL, MySQL, and SQL Server Query INFORMATION_SCHEMA.COLUMNS: 1 select column_name, data_type, ordinal_position 2 from information_schema.columns 3 where table_schema = 'SMEAGOL' 4 and table_name = 'EMP' ### Discussion Each vendor provides ways for you to get detailed information about your column data. In the examples above only the column name, data type, and position are returned. Additional useful items of information include length, nullability, and default values. ## 5.3. Listing Indexed Columns for a Table ### Problem You want list indexes, their columns, and the column position (if available) in the index for a given table. ### Solution The vendor-specific solutions that follow all assume that you are listing indexes for the table EMP in the SMEAGOL schema. #### DB2 Query SYSCAT.INDEXES: 1 select a.tabname, b.indname, b.colname, b.colseq 2 from syscat.indexes a, 3 syscat.indexcoluse b 3 where a.tabname = 'EMP' 4 and a.tabschema = 'SMEAGOL' 5 and a.indschema = b.indschema 6 and a.indname = b.indname #### Oracle Query SYS.ALL_IND_COLUMNS: select table_name, index_name, column_name, column_position from sys.all_ind_columns where table_name = 'EMP' and table_owner = 'SMEAGOL' #### PostgreSQL Query PG_CATALOG.PG_INDEXES and INFORMATION_SCHEMA.COLUMNS: 1 select a.tablename,a.indexname,b.column_name 2 from pg_catalog.pg_indexes a, 3 information_schema.columns b 4 where a.schemaname = 'SMEAGOL' 5 and a.tablename = b.table_name #### MySQL Use the SHOW INDEX command: show index from emp #### SQL Server Query SYS.TABLES, SYS.INDEXES, SYS.INDEX_COLUMNS, and SYS.COLUMNS: 1 select a.name table_name, 2 b.name index_name, 3 d.name column_name, 4 c.index_column_id 5 from sys.tables a, 6 sys.indexes b, 7 sys.index_columns c, 8 sys.columns d 9 where a.object_id = b.object_id 10 and b.object_id = c.object_id 11 and b.index_id = c.index_id 12 and c.object_id = d.object_id 13 and c.column_id = d.column_id 14 and a.name = 'EMP' ### Discussion When it comes to queries, it's important to know what columns are/aren't indexed. Indexes can provide good performance for queries against columns that are frequently used in filters and that are fairly selective. Indexes are also useful when joining between tables. By knowing what columns are indexed, you are already one step ahead of performance problems if they should occur. Additionally, you might want to find information about the indexes themselves: how many levels deep they are, how many distinct keys, how many leaf blocks, and so forth. Such information is also available from the views/tables queried in this recipe's solutions. ## 5.4. Listing Constraints on a Table ### Problem You want to list the constraints defined for a table in some schema and the columns they are defined on. For example, you want to find the constraints and the columns they are on for table EMP. ### Solution #### DB2 Query SYSCAT.TABCONST and SYSCAT.COLUMNS: 1 select a.tabname, a.constname, b.colname, a.type 2 from syscat.tabconst a, 3 syscat.columns b 4 where a.tabname = 'EMP' 5 and a.tabschema = 'SMEAGOL' 6 and a.tabname = b.tabname 7 and a.tabschema = b.tabschema #### Oracle Query SYS.ALL_CONSTRAINTS and SYS.ALL_CONS_COLUMNS: 1 select a.table_name, 2 a.constraint_name, 3 b.column_name, 4 a.constraint_type 5 from all_constraints a, 6 all_cons_columns b 7 where a.table_name = 'EMP' 8 and a.owner = 'SMEAGOL' 9 and a.table_name = b.table_name 10 and a.owner = b.owner 11 and a.constraint_name = b.constraint_name #### PostgreSQL, MySQL, and SQL Server Query INFORMATION_SCHEMA.TABLE_CONSTRAINTS and INFORMATION_ SCHEMA.KEY_COLUMN_USAGE: 1 select a.table_name, 2 a.constraint_name, 3 b.column_name, 4 a.constraint_type 5 from information_schema.table_constraints a, 6 information_schema.key_column_usage b 7 where a.table_name = 'EMP' 8 and a.table_schema = 'SMEAGOL' 9 and a.table_name = b.table_name 10 and a.table_schema = b.table_schema 11 and a.constraint_name = b.constraint_name ### Discussion Constraints are such a critical part of relational databases that it should go without saying why you need to know what constraints are on your tables. Listing the constraints on tables is useful for a variety of reasons: you may want to find tables missing a primary key, you may want to find which columns should be foreign keys but are not (i.e., child tables have data different from the parent tables and you want to know how that happened), or you may want to know about check constraints (Are columns nullable? Do they have to satisfy a specific condition? etc.). ## 5.5. Listing Foreign Keys Without Corresponding Indexes ### Problem You want to list tables that have foreign key columns that are not indexed. For example, you want to determine if the foreign keys on table EMP are indexed. ### Solution #### DB2 Query SYSCAT.TABCONST, SYSCAT.KEYCOLUSE, SYSCAT.INDEXES, and SYSCAT.INDEXCOLUSE: 1 select fkeys.tabname, 2 fkeys.constname, 3 fkeys.colname, 4 ind_cols.indname 5 from ( 6 select a.tabschema, a.tabname, a.constname, b.colname 7 from syscat.tabconst a, 8 syscat.keycoluse b 9 where a.tabname = 'EMP' 10 and a.tabschema = 'SMEAGOL' 11 and a.type = 'F' 12 and a.tabname = b.tabname 13 and a.tabschema = b.tabschema 14 ) fkeys 15 left join 16 ( 17 select a.tabschema, 18 a.tabname, 19 a.indname, 20 b.colname 21 from syscat.indexes a, 22 syscat.indexcoluse b 23 where a.indschema = b.indschema 24 and a.indname = b.indname 25 ) ind_cols 26 on (fkeys.tabschema = ind_cols.tabschema 27 and fkeys.tabname = ind_cols.tabname 28 and fkeys.colname = ind_cols.colname ) 29 where ind_cols.indname is null #### Oracle Query SYS.ALL_CONS_COLUMNS, SYS.ALL_CONSTRAINTS, and SYS.ALL_ IND_COLUMNS: 1 select a.table_name, 2 a.constraint_name, 3 a.column_name, 4 c.index_name 5 from all_cons_columns a, 6 all_constraints b, 7 all_ind_columns c 8 where a.table_name = 'EMP' 9 and a.owner = 'SMEAGOL' 10 and b.constraint_type = 'R' 11 and a.owner = b.owner 12 and a.table_name = b.table_name 13 and a.constraint_name = b.constraint_name 14 and a.owner = c.table_owner (+) 15 and a.table_name = c.table_name (+) 16 and a.column_name = c.column_name (+) 17 and c.index_name is null #### PostgreSQL Query INFORMATION_SCHEMA.KEY_COLUMN_USAGE, INFORMATION_ SCHEMA.REFERENTIAL_CONSTRAINTS, INFORMATION_SCHEMA.COL-UMNS, and PG_CATALOG.PG_INDEXES: 1 select fkeys.table_name, 2 fkeys.constraint_name, 3 fkeys.column_name, 4 ind_cols.indexname 5 from ( 6 select a.constraint_schema, 7 a.table_name, 8 a.constraint_name, 9 a.column_name 10 from information_schema.key_column_usage a, 11 information_schema.referential_constraints b 12 where a.constraint_name = b.constraint_name 13 and a.constraint_schema = b.constraint_schema 14 and a.constraint_schema = 'SMEAGOL' 15 and a.table_name = 'EMP' 16 ) fkeys 17 left join 18 ( 19 select a.schemaname, a.tablename, a.indexname, b.column_name 20 from pg_catalog.pg_indexes a, 21 information_schema.columns b 22 where a.tablename = b.table_name 23 and a.schemaname = b.table_schema 24 ) ind_cols 25 on ( fkeys.constraint_schema = ind_cols.schemaname 26 and fkeys.table_name = ind_cols.tablename 27 and fkeys.column_name = ind_cols.column_name ) 28 where ind_cols.indexname is null #### MySQL You can use the SHOW INDEX command to retrieve index information such as index name, columns in the index, and ordinal position of the columns in the index. Additionally, you can query INFORMATION_SCHEMA.KEY_COLUMN_USAGE to list the foreign keys for a given table. In MySQL 5, foreign keys are said to be indexed automatically, but can in fact be dropped. To determine whether a foreign key column's index has been dropped you can execute SHOW INDEX for a particular table and compare the output with that of INFORMATION_SCHEMA.KEY_ COLUMN_USAGE.COLUMN_NAME for the same table. If the COLUMN_NAME is listed in KEY_COLUMN_USAGE but is not returned by SHOW INDEX, you know that column is not indexed. #### SQL Server Query SYS.TABLES, SYS.FOREIGN_KEYS, SYS.COLUMNS, SYS.INDEXES, and SYS.INDEX_COLUMNS: 1 select fkeys.table_name, 2 fkeys.constraint_name, 3 fkeys.column_name, 4 ind_cols.index_name 5 from ( 6 select a.object_id, 7 d.column_id, 8 a.name table_name, 9 b.name constraint_name, 10 d.name column_name 11 from sys.tables a 12 join 13 sys.foreign_keys b 14 on ( a.name = 'EMP' 15 and a.object_id = b.parent_object_id 16 ) 17 join 18 sys.foreign_key_columns c 19 on ( b.object_id = c.constraint_object_id ) 20 join 21 sys.columns d 22 on ( c.constraint_column_id = d.column_id 23 and a.object_id = d.object_id 24 ) 25 ) fkeys 26 left join 27 ( 28 select a.name index_name, 29 b.object_id, 30 b.column_id 31 from sys.indexes a, 32 sys.index_columns b 33 where a.index_id = b.index_id 34 ) ind_cols 35 on ( fkeys.object_id = ind_cols.object_id 36 and fkeys.column_id = ind_cols.column_id ) 37 where ind_cols.index_name is null ### Discussion Each vendor uses its own locking mechanism when modifying rows. In cases where there is a parent-child relationship enforced via foreign key, having indexes on the child column(s) can reducing locking (see your specific RDBMS documentation for details). In other cases, it is common that a child table is joined to a parent table on the foreign key column, so an index may help improve performance in that scenario as well. ## 5.6. Using SQL to Generate SQL ### Problem You want to create dynamic SQL statements, perhaps to automate maintenance tasks. You want to accomplish three tasks in particular: count the number of rows in your tables, disable foreign key constraints defined on your tables, and generate insert scripts from the data in your tables. ### Solution The concept is to use strings to build SQL statements, and the values that need to be filled in (such as the object name the command acts upon) will be supplied by data from the tables you are selecting from. Keep in mind, the queries only generate the statements; you must then run these statements via script, manually, or however you execute your SQL statements. The examples below are queries that would work on an Oracle system. For other RDBMSs the technique is exactly the same, the only difference being things like the names of the data dictionary tables and date formatting. The output shown from the queries below are a portion of the rows returned from an instance of Oracle on my laptop. Your result sets will of course vary. /* generate SQL to count all the rows in all your tables */ **select 'select count(*) from '||table_name||';' cnts** **from user_tables;** CNTS ---------------------------------------- select count(*) from ANT; select count(*) from BONUS; select count(*) from DEMO1; select count(*) from DEMO2; select count(*) from DEPT; select count(*) from DUMMY; select count(*) from EMP; select count(*) from EMP_SALES; select count(*) from EMP_SCORE; select count(*) from PROFESSOR; select count(*) from T; select count(*) from T1; select count(*) from T2; select count(*) from T3; select count(*) from TEACH; select count(*) from TEST; select count(*) from TRX_LOG; select count(*) from X; /* disable foreign keys from all tables */ **select 'alter table '||table_name||** **' disable constraint '||constraint_name||';' cons** **from user_constraints** **where constraint_type = 'R';** CONS ------------------------------------------------ alter table ANT disable constraint ANT_FK; alter table BONUS disable constraint BONUS_FK; alter table DEMO1 disable constraint DEMO1_FK; alter table DEMO2 disable constraint DEMO2_FK; alter table DEPT disable constraint DEPT_FK; alter table DUMMY disable constraint DUMMY_FK; alter table EMP disable constraint EMP_FK; alter table EMP_SALES disable constraint EMP_SALES_FK; alter table EMP_SCORE disable constraint EMP_SCORE_FK; alter table PROFESSOR disable constraint PROFESSOR_FK; /* generate an insert script from some columns in table EMP */ **select 'insert into emp(empno,ename,hiredate) '||chr(10)||** **'values( '||empno||','||''''||ename** **||''',to_date('||''''||hiredate||''') );' inserts** **from emp** **where deptno = 10;** INSERTS -------------------------------------------------- insert into emp(empno,ename,hiredate) values( 7782,'CLARK',to_date('09-JUN-1981 00:00:00') ); insert into emp(empno,ename,hiredate) values( 7839,'KING',to_date('17-NOV-1981 00:00:00') ); insert into emp(empno,ename,hiredate) values( 7934,'MILLER',to_date('23-JAN-1982 00:00:00') ); ### Discussion Using SQL to generate SQL is particularly useful for creating portable scripts such as you might use when testing on multiple environments. Additionally, as can be seen by the examples above, using SQL to generate SQL is useful for performing batch maintenance, and for easily finding out information about multiple objects in one go. Generating SQL with SQL is an extremely simple operation, and the more you experiment with it the easier it will become. The examples provided should give you a nice base on how to build your own "dynamic" SQL scripts because, quite frankly, there's not much to it. Work on it and you'll get it. ## 5.7. Describing the Data Dictionary Views in an Oracle Database ### Problem You are using Oracle. You can't remember what data dictionary views are available to you, nor can you remember their column definitions. Worse yet, you do not have convenient access to vendor documentation. ### Solution This is an Oracle-specific recipe. Oracle not only maintains a robust set of data dictionary views, but there are even data dictionary views to document the data dictionary views. It's all so wonderfully circular. Query the view named DICTIONARY to list data dictionary views and their purposes: select table_name, comments from dictionary order by table_name; TABLE_NAME COMMENTS ------------------------------ -------------------------------------------- ALL_ALL_TABLES Description of all object and relational tables accessible to the user ALL_APPLY Details about each apply process that dequeues from the queue visible to the current user ... Query DICT_COLUMNS to describe the columns in given a data dictionary view: select column_name, comments from dict_columns where table_name = 'ALL_TAB_COLUMNS'; COLUMN_NAME COMMENTS ------------------------------- -------------------------------------------- OWNER TABLE_NAME Table, view or cluster name COLUMN_NAME Column name DATA_TYPE Datatype of the column DATA_TYPE_MOD Datatype modifier of the column DATA_TYPE_OWNER Owner of the datatype of the column DATA_LENGTH Length of the column in bytes DATA_PRECISION Length: decimal digits (NUMBER) or binary digits (FLOAT) ### Discussion Back in the day when Oracle's documentation set wasn't so freely available on the Web, it was incredibly convenient that Oracle made the DICTIONARY and DICT_ COLUMNS views available. Knowing just those two views, you could bootstrap to learning about all the other views, and from thence to learning about your entire database. Even today, it's convenient to know about DICTIONARY and DICT_COLUMNS. Often, if you aren't quite certain which view describes a given object type, you can issue a wildcard query to find out. For example, to get a handle on what views might describe tables in your schema: select table_name, comments from dictionary where table_name LIKE '%TABLE%' order by table_name; This query returns all data dictionary view names that include the term "TABLE". This approach takes advantage of Oracle's fairly consistent data dictionary view naming conventions. Views describing tables are all likely to contain "TABLE" in their name. (Sometimes, as in the case of ALL_TAB_COLUMNS, TABLE is abbreviated TAB.) ## Chapter 6. Working with Strings This chapter focuses on string manipulation in SQL. Keep in mind that SQL is not designed to perform complex string manipulation and you can (and will) find working with strings in SQL to be very cumbersome and frustrating at times. Despite SQL's limitations, there are some very useful built-in functions provided by the different DBMSs, and I've tried to use them in creative ways. This chapter in particular is very representative of the message I tried to convey in the introduction; SQL is the good, the bad, and the ugly. I hope that you take away from this chapter a better appreciation for what can and can't be done in SQL when working with strings. In many cases you'll be surprised by how easy parsing and transforming of strings can be, while at other times you'll be aghast by the kind of SQL that is necessary to accomplish a particular task. The first recipe in this chapter is critically important, as it is leveraged by several of the subsequent solutions. In many cases, you'd like to have the ability to traverse a string by moving through it a character at a time. Unfortunately, SQL does not make this easy. Because there is no loop functionality in SQL (Oracle's MODEL clause excluded), you need to mimic a loop to traverse a string. I call this operation "walking a string" or "walking through a string" and the very first recipe explains the technique. This is a fundamental operation in string parsing when using SQL, and is referenced and used by almost all recipes in this chapter. I strongly suggest becoming comfortable with how the technique works. ## 6.1. Walking a String ### Problem You want to traverse a string to return each character as a row, but SQL lacks a loop operation. For example, you want to display the ENAME "KING" from table EMP as four rows, where each row contains just characters from "KING". ### Solution Use a Cartesian product to generate the number of rows needed to return each character of a string on its own line. Then use your DBMS's built-in string parsing function to extract the characters you are interested in (SQL Server users will use SUBSTRING instead of SUBSTR and DATALENGTH instead of LENGTH): **1 select substr(e.ename,iter.pos,1) as C** **2 from (select ename from emp where ename = 'KING') e,** **3 (select id as pos from t10) iter** **4 where iter.pos<= length(e.ename)** C - K I N G ### Discussion The key to iterating through a string's characters is to join against a table that has enough rows to produce the required number of iterations. This example uses table T10, which contains 10 rows (it has one column, ID, holding the values 1 through 10). The maximum number of rows that can be returned from this query is 10. The following example shows the Cartesian product between E and ITER (i.e., between the specific name and the 10 rows from T10) without parsing ENAME: **select ename, iter.pos** **from (select ename from emp where ename = 'KING') e,** **(select id as pos from t10) iter** ENAME POS ---------- ---------- KING 1 KING 2 KING 3 KING 4 KING 5 KING 6 KING 7 KING 8 KING 9 KING 10 The cardinality of inline view E is 1, and the cardinality of inline view ITER is 10. The Cartesian product is then 10 rows. Generating such a product is the first step in mimicking a loop in SQL. ### Tip It is common practice to refer to table T10 as a "pivot" table. The solution uses a WHERE clause to break out of the loop after four rows have been returned. To restrict the result set to the same number of rows as there are characters in the name, that WHERE clause specifies ITER.POS <= LENGTH(E. ENAME) as the condition: **select ename, iter.pos** **from (select ename from emp where ename = 'KING') e,** **(select id as pos from t10) iter** **where iter.pos<= length(e.ename)** ENAME POS ---------- ---------- KING 1 KING 2 KING 3 KING 4 Now that you have one row for each character in E.ENAME, you can use ITER.POS as a parameter to SUBSTR, allowing you to navigate through the characters in the string. ITER.POS increments with each row, and thus each row can be made to return a successive character from E.ENAME. This is how the solution example works. Depending on what you are trying to accomplish you may or may not need to generate a row for every single character in a string. The following query is an example of walking E.ENAME and exposing different portions (more than a single character) of the string: select substr(e.ename,iter.pos) a, substr(e.ename,length(e.ename)-iter.pos+1) b from (select ename from emp where ename = 'KING') e, (select id pos from t10) iter where iter.pos <= length(e.ename) A B ---------- ------ KING G ING NG NG ING G KING The most common scenarios for the recipes in this chapter involve walking the whole string to generate a row for each character in the string, or walking the string such that the number of rows generated reflects the number of particular characters or delimiters that are present in the string. ## 6.2. Embedding Quotes Within String Literals ### Problem You want to embed quote marks within string literals. You would like to produce results such as the following with SQL: QMARKS -------------- g'day mate beavers' teeth ' ### Solution The following three SELECTs highlight different ways you can create quotes: in the middle of a string and by themselves: 1 select 'g''day mate' qmarks from t1 union all 2 select 'beavers'' teeth' from t1 union all 3 select '''' from t1 ### Discussion When working with quotes, it's often useful to think of them like parentheses. When you have an opening parenthesis, you must always have a closing parenthesis. The same goes for quotes. Keep in mind that you should always have an even number of quotes across any given string. To embed a single quote within a string you need to use two quotes: **select 'apples core', 'apple''s core',** **case when '' is null then 0 else 1 end** **from t1** 'APPLESCORE 'APPLE''SCOR CASEWHEN''ISNULLTHEN0ELSE1END ----------- ------------ ----------------------------- apples core apple's core 0 Following is the solution stripped down to its bare elements. You have two outer quotes defining a string literal, and, within that string literal you have two quotes that together represent just one quote in the string that you actually get: **select '''' as quote from t1** Q - ' When working with quotes, be sure to remember that a string literal comprising two quotes alone, with no intervening characters, is NULL. ## 6.3. Counting the Occurrences of a Character in a String ### Problem You want to count the number of times a character or substring occurs within a given string. Consider the following string: 10,CLARK,MANAGER You want to determine how many commas are in the string. ### Solution Subtract the length of the string without the commas from the original length of the string to determine the number of commas in the string. Each DBMS provides functions for obtaining the length of a string and removing characters from a string. In most cases, these functions are LENGTH and REPLACE, respectively (SQL Server users will use the built-in function LEN rather than LENGTH): 1 select (length('10,CLARK,MANAGER')- 2 length(replace('10,CLARK,MANAGER',',','')))/length(',') 3 as cnt 4 from t1 ### Discussion You arrive at the solution by using simple subtraction. The call to LENGTH on line 1 returns the original size of the string, and the first call to LENGTH on line 2 returns the size of the string without the commas, which are removed by REPLACE. By subtracting the two lengths you obtain the difference in terms of characters, which is the number of commas in the string. The last operation divides the difference by the length of your search string. This division is necessary if the string you are looking for has a length greater than 1. In the following example, counting the occurrence of "LL" in the string "HELLO HELLO" without dividing will return an incorrect result: **select** **(length('HELLO HELLO')-** **length(replace('HELLO HELLO','LL','')))/length('LL')** **as correct_cnt,** **(length('HELLO HELLO')-** **length(replace('HELLO HELLO','LL',''))) as incorrect_cnt** **from t1** CORRECT_CNT INCORRECT_CNT ----------- ------------- 2 4 ## 6.4. Removing Unwanted Characters from a String ### Problem You want to remove specific characters from your data. Consider this result set: ENAME SAL ---------- ---------- SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300 You want to remove all zeros and vowels as shown by the following values in columns STRIPPED1 and STRIPPED2: ENAME STRIPPED1 SAL STRIPPED2 ---------- ---------- ---------- --------- SMITH SMTH 800 8 ALLEN LLN 1600 16 WARD WRD 1250 125 JONES JNS 2975 2975 MARTIN MRTN 1250 125 BLAKE BLK 2850 285 CLARK CLRK 2450 245 SCOTT SCTT 3000 3 KING KNG 5000 5 TURNER TRNR 1500 15 ADAMS DMS 1100 11 JAMES JMS 950 95 FORD FRD 3000 3 MILLER MLLR 1300 13 ### Solution Each DBMS provides functions for removing unwanted characters from a string. The functions REPLACE and TRANSLATE are most useful for this problem. #### DB2 Use the built-in functions TRANSLATE and REPLACE to remove unwanted characters and strings: 1 select ename, 2 replace(translate(ename,'aaaaa','AEIOU'),'a','') stripped1, 3 sal, 4 replace(cast(sal as char(4)),'0','') stripped2 5 from emp #### MySQL and SQL Server MySQL and SQL Server do not offer a TRANSLATE function, so several calls to REPLACE are needed: 1 select ename, 2 replace( 3 replace( 4 replace( 5 replace( 6 replace(ename,'A',''),'E',''),'I',''),'O',''),'U','') 7 as stripped1, 8 sal, 9 replace(sal,0,'') stripped2 10 from emp #### Oracle and PostgreSQL Use the built-in functions TRANSLATE and REPLACE to remove unwanted characters and strings: 1 select ename, 2 replace(translate(ename,'AEIOU','aaaaa'),'a') 3 as stripped1, 4 sal, 5 replace(sal,0,'') as stripped2 6 from emp ### Discussion The built-in function REPLACE removes all occurrences of zeros. To remove the vowels, use TRANSLATE to convert all vowels into one specific character (I used "a"; you can use any character), then use REPLACE to remove all occurrences of that character. ## 6.5. Separating Numeric and Character Data ### Problem You have (unfortunately) stored numeric data along with character data together in one column. You want to separate the character data from the numeric data. Consider the following result set: DATA --------------- SMITH800 ALLEN1600 WARD1250 JONES2975 MARTIN1250 BLAKE2850 CLARK2450 SCOTT3000 KING5000 TURNER1500 ADAMS1100 JAMES950 FORD3000 MILLER1300 You would like the result to be: ENAME SAL ---------- ---------- SMITH 800 ALLEN 1600 WARD 1250 JONES 2975 MARTIN 1250 BLAKE 2850 CLARK 2450 SCOTT 3000 KING 5000 TURNER 1500 ADAMS 1100 JAMES 950 FORD 3000 MILLER 1300 ### Solution Use the built-in functions TRANSLATE and REPLACE to isolate the character from the numeric data. Like other recipes in this chapter, the trick is to use TRANSLATE to transform multiple characters into a single character you can reference. This way you are no longer searching for multiple numbers or characters, rather one character to represent all numbers or one character to represent all characters. #### DB2 Use the functions TRANSLATE and REPLACE to isolate and separate the numeric from the character data: 1 select replace( 2 translate(data,'0000000000','0123456789'),'0','') ename, 3 cast( 4 replace( 5 translate(lower(data),repeat('z',26), 6 'abcdefghijklmnopqrstuvwxyz'),'z','') as integer) sal 7 from ( 8 select ename||cast(sal as char(4)) data 9 from emp 10 ) x #### Oracle Use the functions TRANSLATE and REPLACE to isolate and separate the numeric from the character data: 1 select replace( 2 translate(data,'0123456789','0000000000'),'0') ename, 3 to_number( 5 replace( 6 translate(lower(data), 7 'abcdefghijklmnopqrstuvwxyz', 8 rpad('z',26,'z')),'z')) sal 9 from ( 10 select ename||sal data 11 from emp 12 ) #### PostgreSQL Use the functions TRANSLATE and REPLACE to isolate and separate the numeric from the character data: 1 select replace( 2 translate(data,'0123456789','0000000000'),'0','') as ename, 3 cast( 4 replace( 5 translate(lower(data), 6 'abcdefghijklmnopqrstuvwxyz', 7 rpad('z',26,'z')),'z','') as integer) as sal 8 from ( 9 select ename||sal as data 10 from emp 11 ) x ### Discussion The syntax is a bit different for each DBMS, but the technique is the same. I will use the solution for Oracle in the discussion section. The key to solving this problem is to isolate the numeric and character data. You can use TRANSLATE and REPLACE to do this. To extract the numeric data, first isolate all character data using TRANSLATE: **select data,** **translate(lower(data),** **'abcdefghijklmnopqrstuvwxyz',** **rpad('z',26,'z')) sal** **from (select ename||sal data from emp)** DATA SAL -------------------- ------------------- SMITH800 zzzzz800 ALLEN1600 zzzzz1600 WARD1250 zzzz1250 JONES2975 zzzzz2975 MARTIN1250 zzzzzz1250 BLAKE2850 zzzzz2850 CLARK2450 zzzzz2450 SCOTT3000 zzzzz3000 KING5000 zzzz5000 TURNER1500 zzzzzz1500 ADAMS1100 zzzzz1100 JAMES950 zzzzz950 FORD3000 zzzz3000 MILLER1300 zzzzzz1300 By using TRANSLATE you convert every non-numeric character into a lowercase Z. The next step is to remove all instances of lowercase Z from each record using REPLACE, leaving only numerical characters that can then be cast to a number: **select data,** **to_number(** **replace(** **translate(lower(data),** **'abcdefghijklmnopqrstuvwxyz',** **rpad('z',26,'z')),'z')) sal** **from (select ename||sal data from emp)** DATA SAL -------------------- ---------- SMITH800 800 ALLEN1600 1600 WARD1250 1250 JONES2975 2975 MARTIN1250 1250 BLAKE2850 2850 CLARK2450 2450 SCOTT3000 3000 KING5000 5000 TURNER1500 1500 ADAMS1100 1100 JAMES950 950 FORD3000 3000 MILLER1300 1300 To extract the non-numeric characters, isolate the numeric characters using TRANSLATE: **select data,** **translate(data,'0123456789','0000000000') ename** **from (select ename||sal data from emp)** DATA ENAME -------------------- ---------- SMITH800 SMITH000 ALLEN1600 ALLEN0000 WARD1250 WARD0000 JONES2975 JONES0000 MARTIN1250 MARTIN0000 BLAKE2850 BLAKE0000 CLARK2450 CLARK0000 SCOTT3000 SCOTT0000 KING5000 KING0000 TURNER1500 TURNER0000 ADAMS1100 ADAMS0000 JAMES950 JAMES000 FORD3000 FORD0000 MILLER1300 MILLER0000 By using TRANSLATE you convert every numeric character into a zero. The next step is to remove all instances of zero from each record using REPLACE, leaving only non-numeric characters: **select data,** **replace(translate(data,'0123456789','0000000000'),'0') ename** **from (select ename||sal data from emp)** DATA ENAME -------------------- ------- SMITH800 SMITH ALLEN1600 ALLEN WARD1250 WARD JONES2975 JONES MARTIN1250 MARTIN BLAKE2850 BLAKE CLARK2450 CLARK SCOTT3000 SCOTT KING5000 KING TURNER1500 TURNER ADAMS1100 ADAMS JAMES950 JAMES FORD3000 FORD MILLER1300 MILLER Put the two techniques together and you have your solution. ## 6.6. Determining Whether a String Is Alphanumeric ### Problem You want to return rows from a table only when a column of interest contains no characters other than numbers and letters. Consider the following view V (SQL Server users will use the operator "+" for concatenation instead of "||"): create view V as select ename as data from emp where deptno=10 union all select ename||', $'|| cast(sal as char(4)) ||'.00' as data from emp where deptno=20 union all select ename|| cast(deptno as char(4)) as data from emp where deptno=30 The view V represents your table, and it returns the following: DATA -------------------- CLARK KING MILLER SMITH, $800.00 JONES, $2975.00 SCOTT, $3000.00 ADAMS, $1100.00 FORD, $3000.00 ALLEN30 WARD30 MARTIN30 BLAKE30 TURNER30 JAMES30 However, from the view's data you want to return only the following records: DATA ------------- CLARK KING MILLER ALLEN30 WARD30 MARTIN30 BLAKE30 TURNER30 JAMES30 In short, you wish to omit those rows containing data other than letters and digits. ### Solution It may seem intuitive at first to solve the problem by searching for all the possible non-alphanumeric characters that can be found in a string, but, on the contrary, you will find it easier to do the exact opposite: find all the alphanumeric characters. By doing so, you can treat all the alphanumeric characters as one by converting them to one single character. The reason you want to do this is so the alphanumeric characters can be manipulated together, as a whole. Once you've generated a copy of the string in which all alphanumeric characters are represented by a single character of your choosing, it is easy to isolate the alphanumeric characters from any other characters. #### DB2 Use the function TRANSLATE to convert all alphanumeric characters to a single character, then identify any rows that have characters other than the converted alphanumeric character. For DB2 users, the CAST function calls in view V are necessary; otherwise, the view cannot be created due to type conversion errors. Take extra care when working with casts to CHAR as they are fixed length (padded): 1 select data 2 from V 3 where translate(lower(data), 4 repeat('a',36), 5 '0123456789abcdefghijklmnopqrstuvwxyz') = 6 repeat('a',length(data)) #### MySQL The syntax for view V is slightly different in MySQL: create view V as select ename as data from emp where deptno=10 union all select concat(ename,', $',sal,'.00') as data from emp where deptno=20 union all select concat(ename,deptno) as data from emp where deptno=30 Use a regular expression to easily find rows that contain non-alphanumeric data: 1 select data 2 from V 3 where data regexp '[^0-9a-zA-Z]' = 0 #### Oracle and PostgreSQL Use the function TRANSLATE to convert all alphanumeric characters to a single character, then identify any rows that have characters other than the converted alphanumeric character. The CAST function calls in view V are not needed for Oracle and PostgreSQL. Take extra care when working with casts to CHAR as they are fixed length (padded). If you decide to cast, cast to VARCHAR or VARCHAR2: 1 select data 2 from V 3 where translate(lower(data), 4 '0123456789abcdefghijklmnopqrstuvwxyz', 5 rpad('a',36,'a')) = rpad('a',length(data),'a') #### SQL Server Because SQL Server does not support a TRANSLATE function, you must walk each row and find any that contains a character that contains a non-alphanumeric value. That can be done many ways, but the following solution uses an ASCII-value evaluation: 1 select data 2 from ( 3 select v.data, iter.pos, 4 substring(v.data,iter.pos,1) c, 5 ascii(substring(v.data,iter.pos,1)) val 6 from v, 7 ( select id as pos from t100 ) iter 8 where iter.pos <= len(v.data) 9 ) x 10 group by data 11 having min(val) between 48 and 122 ### Discussion The key to these solutions is being able to reference multiple characters concurrently. By using the function TRANSLATE you can easily manipulate all numbers or all characters without having to "iterate" and inspect each character one by one. #### DB2, Oracle, and PostgreSQL Only 9 of the 14 rows from view V are alphanumeric. To find the rows that are alphanumeric only, simply use the function TRANSLATE. In this example, TRANSLATE converts characters 0–9 and a–z to "a". Once the conversion is done, the converted row is then compared with a string of all "a" with the same length (as the row). If the length is the same, then you know all the characters are alphanumeric and nothing else. By using the TRANSLATE function (using the Oracle syntax): where translate(lower(data), '0123456789abcdefghijklmnopqrstuvwxyz', rpad('a',36,'a')) you convert all numbers and letters into a distinct character (I chose "a"). Once the data is converted, all strings that are indeed alphanumeric can be identified as a string comprising only a single character (in this case, "a"). This can be seen by running TRANSLATE by itself: **select data, translate(lower(data),** **'0123456789abcdefghijklmnopqrstuvwxyz',** **rpad('a',36,'a'))** **from V** DATA TRANSLATE(LOWER(DATA) -------------------- --------------------- CLARK aaaaa ... SMITH, $800.00 aaaaa, $aaa.aa ... ALLEN30 aaaaaaa ... The alphanumeric values are converted, but the string lengths have not been modified. Because the lengths are the same, the rows to keep are the ones for which the call to TRANSLATE returns all a's. You keep those rows, rejecting the others, by comparing each original string's length with the length of its corresponding string of a's: **select data, translate(lower(data),** **'0123456789abcdefghijklmnopqrstuvwxyz',** **rpad('a',36,'a')) translated,** **rpad('a',length(data),'a') fixed** **from V** DATA TRANSLATED FIXED -------------------- -------------------- ---------------- CLARK aaaaa aaaaa ... SMITH, $800.00 aaaaa, $aaa.aa aaaaaaaaaaaaaa ... ALLEN30 aaaaaaa aaaaaaa ... The last step is to keep only the strings where TRANSLATED equals FIXED. #### MySQL The expression in the WHERE clause: where data regexp '[^0-9a-zA-Z]' = 0 causes rows that have only numbers or characters to be returned. The value ranges in the brackets, "0-9a-zA-Z", represent all possible numbers and letters. The character "^" is for negation, so the expression can be stated as "not numbers or letters." A return value of 1 is true and 0 is false, so the whole expression can be stated as "return rows where anything other than numbers and letters is false." #### SQL Server The first step is to walk each row returned by view V. Each character in the value returned for DATA will itself be returned as a row. The values returned by C represent each individual character for the values returned by DATA: +-----------------+------+------+------+ | data | pos | c | val | +-----------------+------+------+------+ | ADAMS, $1100.00 | 1 | A | 65 | | ADAMS, $1100.00 | 2 | D | 68 | | ADAMS, $1100.00 | 3 | A | 65 | | ADAMS, $1100.00 | 4 | M | 77 | | ADAMS, $1100.00 | 5 | S | 83 | | ADAMS, $1100.00 | 6 | , | 44 | | ADAMS, $1100.00 | 7 | | 32 | | ADAMS, $1100.00 | 8 | $ | 36 | | ADAMS, $1100.00 | 9 | 1 | 49 | | ADAMS, $1100.00 | 10 | 1 | 49 | | ADAMS, $1100.00 | 11 | 0 | 48 | | ADAMS, $1100.00 | 12 | 0 | 48 | | ADAMS, $1100.00 | 13 | . | 46 | | ADAMS, $1100.00 | 14 | 0 | 48 | | ADAMS, $1100.00 | 15 | 0 | 48 | Inline view Z not only returns each character in the column DATA row by row, it also provides the ASCII value for each character. For this particular implementation of SQL Server, the range 48–122 represents alphanumeric characters. With that knowledge, you can group each row in DATA and filter out any such that the minimum ASCII value is not in the 48–122 range. ## 6.7. Extracting Initials from a Name ### Problem You want convert a full name into initials. Consider the following name: Stewie Griffin You would like to return: S.G. ### Solution It's important to keep in mind that SQL does not provide the flexibility of languages such as C or Python; therefore, creating a generic solution to deal with any name format is not something particularly easy to do in SQL. The solutions presented here expect the names to be either first and last name, or first, middle name/middle initial, and last name. #### DB2 Use the built-in functions REPLACE, TRANSLATE, and REPEAT to extract the initials: 1 select replace( 2 replace( 3 translate(replace('Stewie Griffin', '.', ''), 4 repeat('#',26), 5 'abcdefghijklmnopqrstuvwxyz'), 6 '#','' ), ' ','.' ) 7 ||'.' 8 from t1 #### MySQL Use the built-in functions CONCAT, CONCAT_WS, SUBSTRING, and SUBSTRING_ INDEX to extract the initials: 1 select case 2 when cnt = 2 then 3 trim(trailing '.' from 4 concat_ws('.', 5 substr(substring_index(name,' ',1),1,1), 6 substr(name, 7 length(substring_index(name,' ',1))+2,1), 8 substr(substring_index(name,' ',-1),1,1), 9 '.')) 10 else 11 trim(trailing '.' from 12 concat_ws('.', 13 substr(substring_index(name,' ',1),1,1), 14 substr(substring_index(name,' ',-1),1,1) 15 )) 16 end as initials 17 from ( 18 select name,length(name)-length(replace(name,' ','')) as cnt 19 from ( 20 select replace('Stewie Griffin','.','') as name from t1 21 )y 22 )x #### Oracle and PostgreSQL Use the built-in functions REPLACE, TRANSLATE, and RPAD to extract the initials: 1 select replace( 2 replace( 3 translate(replace('Stewie Griffin', '.', ''), 4 'abcdefghijklmnopqrstuvwxyz', 5 rpad('#',26,'#') ), '#','' ),' ','.' ) ||'.' 6 from t1 #### SQL Server As of the time of this writing, neither TRANSLATE nor CONCAT_WS is supported in SQL Server. ### Discussion By isolating the capital letters you can extract the initials from a name. The following sections describe each vendor-specific solution in detail. #### DB2 The REPLACE function will remove any periods in the name (to handle middle initials), and the TRANSLATE function will convert all non-uppercase letters to #. **select translate(replace('Stewie Griffin', '.', ''),** **repeat('#',26),** **'abcdefghijklmnopqrstuvwxyz')** **from t1** TRANSLATE('STE -------------- S##### G###### At this point, the initials are the characters that are not #. The function REPLACE is then used to remove all the # characters: **select replace(** **translate(replace('Stewie Griffin', '.', ''),** **repeat('#',26),** **'abcdefghijklmnopqrstuvwxyz'),'#','')** **from t1** REP --- S G The next step is to replace the white space with a period by using REPLACE again: **select replace(** **replace(** **translate(replace('Stewie Griffin', '.', ''),** **repeat('#',26),** **'abcdefghijklmnopqrstuvwxyz'),'#',''),' ','.') || '.'** **from t1** REPLA ----- S.G The final step is to append a decimal to the end of the initials. #### Oracle and PostgreSQL The REPLACE function will remove any periods in the name (to handle middle initials), and the TRANSLATE function will convert all non-uppercase letters to '#'. **select translate(replace('Stewie Griffin','.',''),** **'abcdefghijklmnopqrstuvwxyz',** **rpad('#',26,'#'))** **from t1** TRANSLATE('STE -------------- S##### G###### At this point, the initials are the characters that are not "#". The function REPLACE is then used to remove all the # characters: **select replace(** **translate(replace('Stewie Griffin','.',''),** **'abcdefghijklmnopqrstuvwxyz',** **rpad('#',26,'#')),'#','')** **from t1** REP --- S G The next step is to replace the white space with a period by using REPLACE again: **select replace(** **replace(** **translate(replace('Stewie Griffin','.',''),** **'abcdefghijklmnopqrstuvwxyz',** **rpad('#',26,'#') ),'#',''),' ','.') || '.'** **from t1** REPLA ----- S.G The final step is to append a decimal to the end of the initials. #### MySQL The inline view Y is used to remove any period from the name. The inline view X finds the number of white spaces in the name so the SUBSTR function can be called the correct number of times to extract the initials. The three calls to SUBSTRING_ INDEX parse the string into individual names based on the location of the white space. Because there is only a first and last name, the code in the ELSE portion of the case statement is executed: **select substr(substring_index(name, ' ',1),1,1) as a,** **substr(substring_index(name,' ',-1),1,1) as b** **from (select 'Stewie Griffin' as name from t1) x** A B - - S G If the name in question has a middle name or initial, the initial would be returned by executing substr(name,length(substring_index(name, ' ',1))+2,1) which finds the end of the first name then moves two spaces to the beginning of the middle name or initial; that is, the start position for SUBSTR. Because only onecharacter is kept, the middle name or initial is successfully returned. The initials are then passed to CONCAT_WS, which separates the initials by a period: **select concat_ws('.',** **substr(substring_index(name, ' ',1),1,1),** **substr(substring_index(name,' ',-1),1,1),** **'.' ) a** **from (select 'Stewie Griffin' as name from t1) x** A ----- S.G.. The last step is to trim the extraneous period from the initials. ## 6.8. Ordering by Parts of a String ### Problem You want to order your result set based on a substring. Consider the following records: ENAME ---------- SMITH ALLEN WARD JONES MARTIN BLAKE CLARK SCOTT KING TURNER ADAMS JAMES FORD MILLER You want the records to be ordered based on the _last_ two characters of each name: ENAME --------- ALLEN TURNER MILLER JONES JAMES MARTIN BLAKE ADAMS KING WARD FORD CLARK SMITH SCOTT ### Solution The key to this solution is to find and use your DBMS's built-in function to extract the substring on which you wish to sort. This is typically done with the SUBSTR function. #### DB2, Oracle, MySQL, and PostgreSQL Use a combination of the built-in functions LENGTH and SUBSTR to order by a specific part of a string: 1 select ename 2 from emp 3 order by substr(ename,length(ename)-1,) #### SQL Server Use functions SUBSTRING and LEN to order by a specific part of a string: 1 select ename 2 from emp 3 order by substring(ename,len(ename)-1,2) ### Discussion By using a SUBSTR expression in your ORDER BY clause, you can pick any part of a string to use in ordering a result set. You're not limited to SUBSTR either. You can order rows by the result of almost any expression. ## 6.9. Ordering by a Number in a String ### Problem You want order your result set based on a number within a string. Consider the following view: create view V as select e.ename ||' '|| cast(e.empno as char(4))||' '|| d.dname as data from emp e, dept d where e.deptno=d.deptno This view returns the following data: DATA ---------------------------- CLARK 7782 ACCOUNTING KING 7839 ACCOUNTING MILLER 7934 ACCOUNTING SMITH 7369 RESEARCH JONES 7566 RESEARCH SCOTT 7788 RESEARCH ADAMS 7876 RESEARCH FORD 7902 RESEARCH ALLEN 7499 SALES WARD 7521 SALES MARTIN 7654 SALES BLAKE 7698 SALES TURNER 7844 SALES JAMES 7900 SALES You want to order the results based on the employee number, which falls between the employee name and respective department: DATA --------------------------- SMITH 7369 RESEARCH ALLEN 7499 SALES WARD 7521 SALES JONES 7566 RESEARCH MARTIN 7654 SALES BLAKE 7698 SALES CLARK 7782 ACCOUNTING SCOTT 7788 RESEARCH KING 7839 ACCOUNTING TURNER 7844 SALES ADAMS 7876 RESEARCH JAMES 7900 SALES FORD 7902 RESEARCH MILLER 7934 ACCOUNTING ### Solution Each solution uses functions and syntax specific to its DBMS, but the method (making use of the built-in functions REPLACE and TRANSLATE) is the same for each. The idea is to use REPLACE and TRANSLATE to remove non-digits from the strings, leaving only the numeric values upon which to sort. #### DB2 Use the built-in functions REPLACE and TRANSLATE to order by numeric characters in a string: 1 select data 2 from V 3 order by 4 cast( 5 replace( 6 translate(data,repeat('#',length(data)), 7 replace( 8 translate(data,'##########','0123456789'), 9 '#','')),'#','') as integer) #### Oracle Use the built-in functions REPLACE and TRANSLATE to order by numeric characters in a string: 1 select data 2 from V 3 order by 4 to_number( 5 replace( 6 translate(data, 7 replace( 8 translate(data,'0123456789','##########'), 9 '#'),rpad('#',20,'#')),'#')) #### PostgreSQL Use the built-in functions REPLACE and TRANSLATE to order by numeric characters in a string: 1 select data 2 from V 3 order by 4 cast( 5 replace( 6 translate(data, 7 replace( 8 translate(data,'0123456789','##########'), 9 '#',''),rpad('#',20,'#')),'#','') as integer) #### MySQL and SQL Server As of the time of this writing, neither vendor supplies the TRANSLATE function. ### Discussion The purpose of view V is only to supply rows on which to demonstrate this recipe's solution. The view simply concatenates several columns from the EMP table. The solution shows how to take such concatenated text as input and sort it by the employee number embedded within. The ORDER BY clause in each solution may look a bit intimidating but performs quite well and is pretty straightforward once you examine it piece by piece. To order by the numbers in the string, it's easiest to remove any characters that are not numbers. Once the non-numeric characters are removed all that is left to do is cast the string of numerals into a number, then sort as you see fit. Before examining each function call it is important to understand the order in which each function is called. Starting with the innermost call, TRANSLATE (line 8 from each of the original solutions), you see that: 1. TRANSLATE (line 8) is called and the results are returned to 2. REPLACE (line 7) and those results are returned to 3. TRANSLATE (line 6) and those results are returned to 4. REPLACE (line 5) and those results are returned and finally 5. cast into a number The first step is to convert the numbers into characters that do not exist in the rest of the string. For this example, I chose "#" and used TRANSLATE to convert all non-numeric characters into occurrences of "#". For example, the following query shows the original data on the left and the results from the first translation: **select data,** **translate(data,'0123456789','##########') as tmp** **from V** DATA TMP ------------------------------ ----------------------- CLARK 7782 ACCOUNTING CLARK #### ACCOUNTING KING 7839 ACCOUNTING KING #### ACCOUNTING MILLER 7934 ACCOUNTING MILLER #### ACCOUNTING SMITH 7369 RESEARCH SMITH #### RESEARCH JONES 7566 RESEARCH JONES #### RESEARCH SCOTT 7788 RESEARCH SCOTT #### RESEARCH ADAMS 7876 RESEARCH ADAMS #### RESEARCH FORD 7902 RESEARCH FORD #### RESEARCH ALLEN 7499 SALES ALLEN #### SALES WARD 7521 SALES WARD #### SALES MARTIN 7654 SALES MARTIN #### SALES BLAKE 7698 SALES BLAKE #### SALES TURNER 7844 SALES TURNER #### SALES JAMES 7900 SALES JAMES #### SALES TRANSLATE finds the numerals in each string and converts each one to to the "#" character. The modified strings are then returned to REPLACE (line 11), which removes all occurrences of "#": **select data,** **replace(** **translate(data,'0123456789','##########'),'#') as tmp** **from V** DATA TMP ------------------------------ ------------------- CLARK 7782 ACCOUNTING CLARK ACCOUNTING KING 7839 ACCOUNTING KING ACCOUNTING MILLER 7934 ACCOUNTING MILLER ACCOUNTING SMITH 7369 RESEARCH SMITH RESEARCH JONES 7566 RESEARCH JONES RESEARCH SCOTT 7788 RESEARCH SCOTT RESEARCH ADAMS 7876 RESEARCH ADAMS RESEARCH FORD 7902 RESEARCH FORD RESEARCH ALLEN 7499 SALES ALLEN SALES WARD 7521 SALES WARD SALES MARTIN 7654 SALES MARTIN SALES BLAKE 7698 SALES BLAKE SALES TURNER 7844 SALES TURNER SALES JAMES 7900 SALES JAMES SALES The strings are then returned to TRANSLATE once again, but this time it's the second (outermost) TRANSLATE in the solution. TRANSLATE searches the original string for any characters that match the characters in TMP. If any are found, they too are converted to "#"s. This conversion allows all non-numeric characters to be treated as a single character (because they are all transformed to the same character): **select data, translate(data,** **replace(** **translate(data,'0123456789','##########'),** **'#'),** **rpad('#',length(data),'#')) as tmp** **from V** DATA TMP ------------------------------ --------------------------- CLARK 7782 ACCOUNTING ########7782########### KING 7839 ACCOUNTING ########7839########### MILLER 7934 ACCOUNTING ########7934########### SMITH 7369 RESEARCH ########7369######### JONES 7566 RESEARCH ########7566######### SCOTT 7788 RESEARCH ########7788######### ADAMS 7876 RESEARCH ########7876######### FORD 7902 RESEARCH ########7902######### ALLEN 7499 SALES ########7499###### WARD 7521 SALES ########7521###### MARTIN 7654 SALES ########7654###### BLAKE 7698 SALES ########7698###### TURNER 7844 SALES ########7844###### JAMES 7900 SALES ########7900###### The next step is to remove all "#" characters through a call to REPLACE (line 8), leaving you with only numbers: **select data, replace(** **translate(data,** **replace(** **translate(data,'0123456789','##########'),** **'#'),** **rpad('#',length(data),'#')),'#') as tmp** **from V** DATA TMP ------------------------------ ----------- CLARK 7782 ACCOUNTING 7782 KING 7839 ACCOUNTING 7839 MILLER 7934 ACCOUNTING 7934 SMITH 7369 RESEARCH 7369 JONES 7566 RESEARCH 7566 SCOTT 7788 RESEARCH 7788 ADAMS 7876 RESEARCH 7876 FORD 7902 RESEARCH 7902 ALLEN 7499 SALES 7499 WARD 7521 SALES 7521 MARTIN 7654 SALES 7654 BLAKE 7698 SALES 7698 TURNER 7844 SALES 7844 JAMES 7900 SALES 7900 Finally, cast TMP to a number (line 4) using the appropriate DBMS function (often CAST) to accomplish this: **select data, to_number(** **replace(** **translate(data,** **replace(** **translate(data,'0123456789','##########'),** **'#'),** **rpad('#',length(data),'#')),'#')) as tmp** **from V** DATA TMP ------------------------------ ---------- CLARK 7782 ACCOUNTING 7782 KING 7839 ACCOUNTING 7839 MILLER 7934 ACCOUNTING 7934 SMITH 7369 RESEARCH 7369 JONES 7566 RESEARCH 7566 SCOTT 7788 RESEARCH 7788 ADAMS 7876 RESEARCH 7876 FORD 7902 RESEARCH 7902 ALLEN 7499 SALES 7499 WARD 7521 SALES 7521 MARTIN 7654 SALES 7654 BLAKE 7698 SALES 7698 TURNER 7844 SALES 7844 JAMES 7900 SALES 7900 When developing queries like this, it's helpful to work with your expressions in the SELECT list. That way, you can easily view the intermediate results as you work toward a final solution. However, because the point of this recipe is to order the results, ultimately you should place all the function calls into the ORDER BY clause: **select data** **from V** **order by** **to_number(** **replace(** **translate( data,** **replace(** **translate( data,'0123456789','##########'),** **'#'),rpad('#',length(data),'#')),'#'))** DATA --------------------------- SMITH 7369 RESEARCH ALLEN 7499 SALES WARD 7521 SALES JONES 7566 RESEARCH MARTIN 7654 SALES BLAKE 7698 SALES CLARK 7782 ACCOUNTING SCOTT 7788 RESEARCH KING 7839 ACCOUNTING TURNER 7844 SALES ADAMS 7876 RESEARCH JAMES 7900 SALES FORD 7902 RESEARCH MILLER 7934 ACCOUNTING As a final note, the data in the view is comprised of three fields, only one being numeric. Keep in mind that if there had been multiple numeric fields, they would have all been concatenated into one number before the rows were sorted. ## 6.10. Creating a Delimited List from Table Rows ### Problem You want to return table rows as values in a delimited list, perhaps delimited by commas, rather than in vertical columns as they normally appear. You want to convert a result set from this: DEPTNO EMPS ------ ---------- 10 CLARK 10 KING 10 MILLER 20 SMITH 20 ADAMS 20 FORD 20 SCOTT 20 JONES 30 ALLEN 30 BLAKE 30 MARTIN 30 JAMES 30 TURNER 30 WARD to this: DEPTNO EMPS ------- ------------------------------------ 10 CLARK,KING,MILLER 20 SMITH,JONES,SCOTT,ADAMS,FORD 30 ALLEN,WARD,MARTIN,BLAKE,TURNER,JAMES ### Solution Each DBMS requires a different approach to this problem. The key is to take advantage of the built-in functions provided by your DBMS. Understanding what is available to you will allow you to exploit your DBMS's functionality and come up with creative solutions for a problem that is typically not solved in SQL. #### DB2 Use recursive WITH to build the delimited list: 1 with x (deptno, cnt, list, empno, len) 2 as ( 3 select deptno, count(*) over (partition by deptno), 4 cast(ename as varchar(100)), empno, 1 5 from emp 6 union all 7 select x.deptno, x.cnt, x.list ||','|| e.ename, e.empno, x.len+1 8 from emp e, x 9 where e.deptno = x.deptno 10 and e.empno > x. empno 11 ) 12 select deptno,list 13 from x 14 where len = cnt #### MySQL Use the built-in function GROUP_CONCAT to build the delimited list: 1 select deptno, 2 group_concat(ename order by empno separator, ',') as emps 3 from emp 4 group by deptno #### Oracle Use the built-in function SYS_CONNECT_BY_PATH to build the delimited list: 1 select deptno, 2 ltrim(sys_connect_by_path(ename,','),',') emps 3 from ( 4 select deptno, 5 ename, 6 row_number() over 7 (partition by deptno order by empno) rn, 8 count(*) over 9 (partition by deptno) cnt 10 from emp 11 ) 12 where level = cnt 13 start with rn = 1 14 connect by prior deptno = deptno and prior rn = rn-1 #### PostgreSQL PostgreSQL does not offer a standard built-in function for creating a delimited list, so it is necessary to know how many values will be in the list in advance. Once you know the size of the largest list, you can determine the number of values to append to create your list by using standard transposition and concatenation: 1 select deptno, 2 rtrim( 3 max(case when pos=1 then emps else '' end)|| 4 max(case when pos=2 then emps else '' end)|| 5 max(case when pos=3 then emps else '' end)|| 6 max(case when pos=4 then emps else '' end)|| 7 max(case when pos=5 then emps else '' end)|| 8 max(case when pos=6 then emps else '' end),',' 9 ) as emps 10 from ( 11 select a.deptno, 12 a.ename||',' as emps, 13 d.cnt, 14 (select count(*) from emp b 15 where a.deptno=b.deptno and b.empno <= a.empno) as pos 16 from emp a, 17 (select deptno, count(ename) as cnt 18 from emp 19 group by deptno) d 20 where d.deptno=a.deptno 21 ) x 22 group by deptno 23 order by 1 #### SQL Server Use recursive WITH to build the delimited list: 1 with x (deptno, cnt, list, empno, len) 2 as ( 3 select deptno, count(*) over (partition by deptno), 4 cast(ename as varchar(100)), 5 empno, 6 1 7 from emp 9 union all 9 select x.deptno, x.cnt, 10 cast(x.list + ',' + e.ename as varchar(100)), 11 e.empno, x.len+1 12 from emp e, x 13 where e.deptno = x.deptno 14 and e.empno > x. empno 15 ) 16 select deptno,list 17 from x 18 where len = cnt 19 order by 1 ### Discussion Being able to create delimited lists in SQL is useful because it is a common requirement. Yet each DBMS offers a unique method for building such a list in SQL. There's very little commonality between the vendor-specific solutions; the techniques vary from using recursion, to hierarchal functions, to classic transposition, to aggregation. #### DB2 and SQL Server The solution for these two databases differ slightly in syntax (the concatenation operators are "||" for DB2 and "+" for SQL Server), but the technique is the same. The first query in the WITH clause (upper portion of the UNION ALL) returns the following information about each employee: the department, the number of employees in that department, the name, the ID, and a constant 1 (which at this point doesn't do anything). Recursion takes place in the second query (lower half of the UNION ALL) to build the list. To understand how the list is built, examine the following excerpts from the solution: first, the third SELECT-list item from the second query in the union: x.list ||','|| e.ename and then the WHERE clause from that same query: where e.deptno = x.deptno and e.empno > x.empno The solution works by first ensuring the employees are in the same department. Then, for every employee returned by the upper portion of the UNION ALL, append the name of the employees who have a greater EMPNO. By doing this, you ensure that no employee will have his own name appended. The expression x.len+1 increments LEN (which starts at 1) every time an employee has been evaluated. When the incremented value equals the number of employees in the department: where len = cnt you know you have evaluated all the employees and have completed building the list. That is crucial to the query as it not only signals when the list is complete, but also stops the recursion from running longer than necessary. #### MySQL The function GROUP_CONCAT does all the work. It concatenates the values found in the column passed to it, in this case ENAME. It's an aggregate function, thus the need for GROUP BY in the query. #### Oracle The first step to understanding the Oracle query is to break it down. Running the inline view by itself (lines 4–10), you generate a result set that includes the following for each employee: her department, her name, a rank within her respective department that is derived by an ascending sort on EMPNO, and a count of all employees in her department. For example: **select deptno,** **ename,** **row_number() over** **(partition by deptno order by empno) rn,** **count(*) over (partition by deptno) cnt** **from emp** DEPTNO ENAME RN CNT ------ ---------- -- --- 10 CLARK 1 3 10 KING 2 3 10 MILLER 3 3 20 SMITH 1 5 20 JONES 2 5 20 SCOTT 3 5 20 ADAMS 4 5 20 FORD 5 5 30 ALLEN 1 6 30 WARD 2 6 30 MARTIN 3 6 30 BLAKE 4 6 30 TURNER 5 6 30 JAMES 6 6 The purpose of the rank (aliased RN in the query) is to allow you to walk the tree. Since the function ROW_NUMBER generates an enumeration starting from one with no duplicates or gaps, just subtract one (from the current value) to reference a prior (or parent) row. For example, the number prior to 3 is 3 minus 1, which equals 2. In this context, 2 is the parent of 3; you can observe this on line 12. Additionally, the lines start with rn = 1 connect by prior deptno = deptno identify the root for each DEPTNO as having RN equal to 1 and create a new list whenever a new department is encountered (whenever a new occurrence of 1 is found for RN). At this point, it's important to stop and look at the ORDER BY portion of the ROW_NUMBER function. Keep in mind the names are ranked by EMPNO and the list will be created in that order. The number of employees per department is calculated (aliased CNT) and is used to ensure that the query returns only the list that has all the employee names for a department. This is done because SYS_CONNECT_ BY_PATH builds the list iteratively, and you do not want to end up with partial lists. For hierarchical queries, the pseudocolumn LEVEL starts with 1 (for queries not using CONNECT BY, LEVEL is 0, unless you are on 10g and later when LEVEL is only available when using CONNECT BY) and increments by one after each employee in a department has been evaluated (for each level of depth in the hierarchy). Because of this, you know that once LEVEL reaches CNT, you have reached the last EMPNO and will have a complete list. ### Tip The SYS_CONNECT_BY_PATH function prefixes the list with your chosen delimiter (in this case, a comma). You may or may not want that behavior. In this recipe's solution, the call to the function LTRIM removes the leading comma from the list. #### PostgreSQL PostgreSQL's solution requires you to know in advance the maximum number of employees in any one department. Running the inline view by itself (lines 11–18) generates a result set that includes (for each employee) his department, his name with a comma appended, the number of employees in his department, and the number of employees who have an EMPNO that is less than his: deptno | emps | cnt | pos --------+----------+-----+----- 20 | SMITH, | 5 | 1 30 | ALLEN, | 6 | 1 30 | WARD, | 6 | 2 20 | JONES, | 5 | 2 30 | MARTIN, | 6 | 3 30 | BLAKE, | 6 | 4 10 | CLARK, | 3 | 1 20 | SCOTT, | 5 | 3 10 | KING, | 3 | 2 30 | TURNER, | 6 | 5 20 | ADAMS, | 5 | 4 30 | JAMES, | 6 | 6 20 | FORD, | 5 | 5 10 | MILLER, | 3 | 3 The scalar subquery, POS (lines 14-15), is used to rank each employee by EMPNO. For example, the line max(case when pos = 1 then ename else '' end)|| evaluates whether or not POS equals 1. The CASE expression returns the employee name when POS is 1, and otherwise returns NULL. You must query your table first to find the largest number of values that could be in any one list. Based on the EMP table, the largest number of employees in any one department is six, so the largest number of items in a list is six. The next step is to begin creating the list. Do this by performing some conditional logic (in the form of CASE expressions) on the rows returned from the inline view. You must write as many CASE expressions as there are possible values to be concatenated together. If POS equals one, the current name is added to the list. The second CASE expression evaluates whether or not POS equals two; if it does, then the second name is appended to the first. If there is no second name, then an additional comma is appended to the first name (this process is repeated for each distinct value of POS until the last one is reached). The use of the MAX function is necessary because you want to build only one list per department (you can also use MIN; it makes no difference in this case, since POS returns only one value for each case evaluation). Whenever an aggregate function is used, any items in the SELECT list not acted upon by the aggregate must be specified in the GROUP BY clause. This guarantees you will have only one row per item in the SELECT list not acted upon by the aggregate function. Notice that you also need the function RTRIM to remove trailing commas; the number of commas will always be equal to the maximum number of values that could potentially be in a list (in this case, six). ## 6.11. Converting Delimited Data into a Multi-Valued IN-List ### Problem You have delimited data that you want to pass to the IN-list iterator of a WHERE clause. Consider the following string: 7654,7698,7782,7788 You would like to use the string in a WHERE clause but the following SQL fails because EMPNO is a numeric column: select ename,sal,deptno from emp where empno in ( '7654,7698,7782,7788' ) This SQL fails because, while EMPNO is a numeric column, the IN list is composed of a single string value. You want that string to be treated as a comma-delimited list of numeric values. ### Solution On the surface it may seem that SQL should do the work of treating a delimited string as a list of delimited values for you, but that is not the case. When a comma embedded within quotes is encountered, SQL can't possibly know that signals a multi-valued list. SQL must treat everything between the quotes as a single entity, as one string value. You must break the string up into individual EMPNOs. The key to this solution is to walk the string, but not into individual characters. You want to walk the string into valid EMPNO values. #### DB2 By walking the string passed to the IN-list, you can easily convert it to rows. The functions ROW_NUMBER, LOCATE, and SUBSTR are particularly useful here: 1 select empno,ename,sal,deptno 2 from emp 3 where empno in ( 4 select cast(substr(c,2,locate(',',c,2)-2) as integer) empno 5 from ( 6 select substr(csv.emps,cast(iter.pos as integer)) as c 7 from (select ','||'7654,7698,7782,7788'||',' emps 8 from t1) csv, 9 (select id as pos 10 from t100 ) iter 11 where iter.pos <= length(csv.emps) 12 ) x 13 where length(c) > 1 14 and substr(c,1,1) = ',' 15 ) #### MySQL By walking the string passed to the IN-list, you can easily convert it to rows: 1 select empno, ename, sal, deptno 2 from emp 3 where empno in 4 ( 5 select substring_index( 6 substring_index(list.vals,',',iter.pos),',',-1) empno 7 from (select id pos from t10) as iter, 8 (select '7654,7698,7782,7788' as vals 9 from t1) list 10 where iter.pos <= 11 (length(list.vals)-length(replace(list.vals,',','')))+1 12 ) #### Oracle By walking the string passed to the IN-list, you can easily convert it to rows. The functions ROWNUM, SUBSTR, and INSTR are particularly useful here: 1 select empno,ename,sal,deptno 2 from emp 3 where empno in ( 4 select to_number( 5 rtrim( 6 substr(emps, 7 instr(emps,',',1,iter.pos)+1, 8 instr(emps,',',1,iter.pos+1) 9 instr(emps,',',1,iter.pos)),',')) emps 10 from (select ','||'7654,7698,7782,7788'||',' emps from t1) csv, 11 (select rownum pos from emp) iter 12 where iter.pos <= ((length(csv.emps)- 13 length(replace(csv.emps,',')))/length(','))-1 14 ) #### Postgres By walking the string passed to the IN-list, you can easily convert it to rows. The function SPLIT_PART makes it easy to parse the string into individual numbers: 1 select ename,sal,deptno 2 from emp 3 where empno in ( 4 select cast(empno as integer) as empno 5 from ( 6 select split_part(list.vals,',',iter.pos) as empno 7 from (select id as pos from t10) iter, 8 (select ','||'7654,7698,7782,7788'||',' as vals 9 from t1) list 10 where iter.pos <= 11 length(list.vals)-length(replace(list.vals,',','')) 12 ) z 13 where length(empno) > 0 14 ) #### SQL Server By walking the string passed to the IN-list, you can easily convert it to rows. The functions ROW_NUMBER, CHARINDEX, and SUBSTRING are particularly useful here: 1 select empno,ename,sal,deptno 2 from emp 3 where empno in (select substring(c,2,charindex(',',c,2)-2) as empno 4 from ( 5 select substring(csv.emps,iter.pos,len(csv.emps)) as c 6 from (select ','+'7654,7698,7782,7788'+',' as emps 7 from t1) csv, 8 (select id as pos 9 from t100) iter 10 where iter.pos <= len(csv.emps) 11 ) x 12 where len(c) > 1 13 and substring(c,1,1) = ',' 14 ) ### Discussion The first and most important step in this solution is to walk the string. Once you've accomplished that, all that's left is to parse the string into individual, numeric values using your DBMS's provided functions. #### DB2 and SQL Server The inline view X (lines 6–11) walks the string. The idea in this solution is to "walk through" the string, so that each row has one less character than the one before it: ,7654,7698,7782,7788, 7654,7698,7782,7788, 654,7698,7782,7788, 54,7698,7782,7788, 4,7698,7782,7788, ,7698,7782,7788, 7698,7782,7788, 698,7782,7788, 98,7782,7788, 8,7782,7788, ,7782,7788, 7782,7788, 782,7788, 82,7788, 2,7788, ,7788, 7788, 788, 88, 8, , Notice that by enclosing the string in commas (the delimiter), there's no need to make special checks as to where the beginning or end of the string is. The next step is to keep only the values you want to use in the IN-list. The values to keep are the ones with leading commas, with the exception of the last row with its lone comma. Use SUBSTR or SUBSTRING to identify which rows have a leading comma, then keep all characters found before the next comma in that row. Once that's done, cast the string to a number so it can be properly evaluated against the numeric column EMPNO (lines 4–14): EMPNO ------ 7654 7698 7782 7788 The final step is to use the results in a subquery to return the desired rows. #### MySQL The inline view (lines 5–9) walks the string. The expression on line 10 determines how many values are in the string by finding the number of commas (the delimiter) and adding one. The function SUBSTRING_INDEX (line 6) returns all characters in the string before (to the left of ) the _n_ th occurrence of a comma (the delimiter): +---------------------+ | empno | +---------------------+ | 7654 | | 7654,7698 | | 7654,7698,7782 | | 7654,7698,7782,7788 | +---------------------+ Those rows are then passed to another call to SUBSTRING_INDEX (line 5); this time the _n_ th occurrence of the delimited is –1, which causes all values to the right of the _n_ th occurrence of the delimiter to be kept: +-------+ | empno | +-------+ | 7654 | | 7698 | | 7782 | | 7788 | +-------+ The final step is to plug the results into a subquery. #### Oracle The first step is to walk the string: **select emps,pos** **from (select ','||'7654,7698,7782,7788'||',' emps** **from t1) csv,** **(select rownum pos from emp) iter** **where iter.pos<=** **((length(csv.emps)-length(replace(csv.emps,',')))/length(','))-1** EMPS POS --------------------- ---------- ,7654,7698,7782,7788, 1 ,7654,7698,7782,7788, 2 ,7654,7698,7782,7788, 3 ,7654,7698,7782,7788, 4 The number of rows returned represents the number of values in your list. The values for POS are crucial to the query as they are needed to parse the string into individual values. The strings are parsed using SUBSTR and INSTR. POS is used to locate the _n_ th occurrence of the delimiter in each string. By enclosing the strings in commas, no special checks are necessary to determine the beginning or end of a string. The values passed to SUBSTR, INSTR (lines 7–9) locate the _n_ th and _n_ th+1 occurrence of the delimiter. By subtracting the value returned for the current comma (the location in the string where the current comma is) from the value returned bythe next comma (the location in the string where the next comma is) you can extract each value from the string: **select substr(emps,** **instr(emps,',',1,iter.pos)+1,** **instr(emps,',',1,iter.pos+1)** **instr(emps,',',1,iter.pos)) emps** **from (select ','||'7654,7698,7782,7788'||',' emps** **from t1) csv,** **(select rownum pos from emp) iter** **where iter.pos<=** **((length(csv.emps)-length(replace(csv.emps,',')))/length(','))-1** EMPS ----------- 7654, 7698, 7782, 7788, The final step is to remove the trailing comma from each value, cast it to a number, and plug it into a subquery. #### PostgreSQL The inline view Z (lines 6–9) walks the string. The number of rows returned is determined by how many values are in the string. To find the number of values in the string, subtract the size of the string without the delimiter from the size of the string with the delimiter (line 9). The function SPLIT_PART does the work of parsing the string. It looks for the value that comes before the _n_ th occurrence of the delimiter: **select list.vals,** **split_part(list.vals,',',iter.pos) as empno,** **iter.pos** **from (select id as pos from t10) iter,** **(select ','||'7654,7698,7782,7788'||',' as vals** **from t1) list** **where iter.pos<=** **length(list.vals)-length(replace(list.vals,',',''))** vals | empno | pos ----------------------+-------+----- ,7654,7698,7782,7788, | | 1 ,7654,7698,7782,7788, | 7654 | 2 ,7654,7698,7782,7788, | 7698 | 3 ,7654,7698,7782,7788, | 7782 | 4 ,7654,7698,7782,7788, | 7788 | 5 The final step is to cast the values (EMPNO) to a number and plug it into a subquery. ## 6.12. Alphabetizing a String ### Problem You want alphabetize the individual characters within strings in your tables. Consider the following result set: ENAME ---------- ADAMS ALLEN BLAKE CLARK FORD JAMES JONES KING MARTIN MILLER SCOTT SMITH TURNER WARD You would like the result to be: OLD_NAME NEW_NAME ---------- -------- ADAMS AADMS ALLEN AELLN BLAKE ABEKL CLARK ACKLR FORD DFOR JAMES AEJMS JONES EJNOS KING GIKN MARTIN AIMNRT MILLER EILLMR SCOTT COSTT SMITH HIMST TURNER ENRRTU WARD ADRW ### Solution This problem is a perfect example of why it is crucial to understand your DBMS and what functionality is available to you. In situations where your DBMS does not provide built-in functions to facilitate this solution, you need to come up with something creative. Compare the MySQL solution with the rest. #### DB2 To alphabetize rows of strings it is necessary to walk each string then order its characters: 1 select ename, 2 max(case when pos=1 then c else '' end)|| 3 max(case when pos=2 then c else '' end)|| 4 max(case when pos=3 then c else '' end)|| 5 max(case when pos=4 then c else '' end)|| 6 max(case when pos=5 then c else '' end)|| 7 max(case when pos=6 then c else '' end) 8 from ( 9 select e.ename, 10 cast(substr(e.ename,iter.pos,1) as varchar(100)) c, 11 cast(row_number()over(partition by e.ename 12 order by substr(e.ename,iter.pos,1)) 13 as integer) pos 14 from emp e, 15 (select cast(row_number()over() as integer) pos 16 from emp) iter 17 where iter.pos <= length(e.ename) 18 ) x 19 group by ename #### MySQL The key here is the GROUP_CONCAT function, which allows you to not only concatenate the characters that make up each name but also order them: 1 select ename, group_concat(c order by c separator '') 2 from ( 3 select ename, substr(a.ename,iter.pos,1) c 4 from emp a, 5 ( select id pos from t10 ) iter 6 where iter.pos <= length(a.ename) 7 ) x 8 group by ename #### Oracle The function SYS_CONNECT_BY_PATH allows you to iteratively build a list: 1 select old_name, new_name 2 from ( 3 select old_name, replace(sys_connect_by_path(c,' '),' ') new_name 4 from ( 5 select e.ename old_name, 6 row_number() over(partition by e.ename 7 order by substr(e.ename,iter.pos,1)) rn, 8 substr(e.ename,iter.pos,1) c 9 from emp e, 10 ( select rownum pos from emp ) iter 11 where iter.pos <= length(e.ename) 12 order by 1 13 ) x 14 start with rn = 1 15 connect by prior rn = rn-1 and prior old_name = old_name 16 ) 17 where length(old_name) = length(new_name) #### PostgreSQL PostgreSQL does not offer any built-in functions to easily sort characters in a string, so it is necessary not only to walk through each string but also to know in advance the largest length of any one name. View V is used in this solution for readability: create or replace view V as select x.* from ( select a.ename, substr(a.ename,iter.pos,1) as c from emp a, (select id as pos from t10) iter where iter.pos <= length(a.ename) order by 1,2 ) x The following select statement leverages the view: 1 select ename, 2 max(case when pos=1 then 3 case when cnt=1 then c 4 else rpad(c,cast(cnt as integer),c) 5 end 6 else '' 7 end)|| 8 max(case when pos=2 then 9 case when cnt=1 then c 10 else rpad(c,cast(cnt as integer),c) 11 end 12 else '' 13 end)|| 14 max(case when pos=3 then 15 case when cnt=1 then c 16 else rpad(c,cast(cnt as integer),c) 17 end 18 else '' 19 end)|| 20 max(case when pos=4 then 21 case when cnt=1 then c 22 else rpad(c,cast(cnt as integer),c) 23 end 24 else '' 25 end)|| 26 max(case when pos=5 then 27 case when cnt=1 then c 28 else rpad(c,cast(cnt as integer),c) 29 end 30 else '' 31 end)|| 32 max(case when pos=6 then 33 case when cnt=1 then c 34 else rpad(c,cast(cnt as integer),c) 35 end 36 else '' 37 end) 38 from ( 39 select a.ename, a.c, 40 (select count(*) 41 from v b 42 where a.ename=b.ename and a.c=b.c ) as cnt, 43 (select count(*)+1 44 from v b 45 where a.ename=b.ename and b.c<a.c) as pos 46 from v a 47 ) x 48 group by ename #### SQL Server To alphabetize rows of strings it is necessary to walk each string, and then order their characters: 1 select ename, 2 max(case when pos=1 then c else '' end)+ 3 max(case when pos=2 then c else '' end)+ 4 max(case when pos=3 then c else '' end)+ 5 max(case when pos=4 then c else '' end)+ 6 max(case when pos=5 then c else '' end)+ 7 max(case when pos=6 then c else '' end) 8 from ( 9 select e.ename, 10 substring(e.ename,iter.pos,1) as c, 11 row_number() over ( 12 partition by e.ename 13 order by substring(e.ename,iter.pos,1)) as pos 14 from emp e, 15 (select row_number()over(order by ename) as pos 16 from emp) iter 17 where iter.pos <= len(e.ename) 18 ) x 19 group by ename ### Discussion #### DB2 and SQL Server The inline view X returns each character in each name as a row. The function SUBSTR or SUBSTRING extracts each character from each name, and the function ROW_NUMBER ranks each character alphabetically: ENAME C POS ----- - --- ADAMS A 1 ADAMS A 2 ADAMS D 3 ADAMS M 4 ADAMS S 5 ... To return each letter of a string as a row, you must walk the string. This is accomplished with inline view ITER. Now that the letters in each name have been alphabetized, the last step is to put those letters back together, into a string, in the order they are ranked. Each letter's position is evaluated by the CASE statements (lines 2–7). If a character is found at a particular position it is then concatenated to the result of the next evaluation (the following CASE statement). Because the aggregate function MAX is used as well, only one character per position POS is returned, so that only one row per name is returned. The CASE evaluation goes up to the number 6, which is the maximum number of characters in any name in table EMP. #### MySQL The inline view X (lines 3–6) returns each character in each name as a row. The function SUBSTR extracts each character from each name: ENAME C ----- - ADAMS A ADAMS A ADAMS D ADAMS M ADAMS S ... Inline view ITER is used to walk the string. From there, the rest of the work is done by the GROUP_CONCAT function. By specifying an order, the function not only concatenates each letter, it does so alphabetically. #### Oracle The real work is done by inline view X (lines 5–11), where the characters in each name are extracted and put into alphabetical order. This is accomplished by walking the string, then imposing order on those characters. The rest of the query merely glues the names back together. The tearing apart of names can be seen by executing only inline view X: OLD_NAME RN C ---------- --------- - ADAMS 1 A ADAMS 2 A ADAMS 3 D ADAMS 4 M ADAMS 5 S ... The next step is to take the alphabetized characters and rebuild each name. This is done with the function SYS_CONNECT_BY_PATH by appending each character to the ones before it: OLD_NAME NEW_NAME ---------- --------- ADAMS A ADAMS AA ADAMS AAD ADAMS AADM ADAMS AADMS ... The final step is to keep only the strings that have the same length as the names they were built from. #### PostgreSQL For readability, view V is used in this solution to walk the string. The function SUBSTR, in the view definition, extracts each character from each name so that the view returns: ENAME C ----- - ADAMS A ADAMS A ADAMS D ADAMS M ADAMS S ... The view also orders the results by ENAME and by each letter in each name. The inline view X (lines 15–18) returns the names and characters from view V, the number of times each character occurs in each name, and its position (alphabetically): ename | c | cnt | pos ------+---+-----+----- ADAMS | A | 2 | 1 ADAMS | A | 2 | 1 ADAMS | D | 1 | 3 ADAMS | M | 1 | 4 ADAMS | S | 1 | 5 The extra columns CNT and POS, returned by the inline view X, are crucial to the solution. POS is used to rank each character and CNT is used to determine the number of times the character exists in each name. The final step is to evaluate the position of each character and rebuild the name. You'll notice that each case statement is actually two case statements. This is to determine whether or not a character occursmore than once in a name; if it does, then rather than return that character, what is returned is that character appended to itself CNT times. The aggregate function, MAX, is used to ensure there is only one row per name. ## 6.13. Identifying Strings That Can Be Treated as Numbers ### Problem You have a column that is defined to hold character data. Unfortunately, the rows contain mixed numeric and character data. Consider view V: create view V as select replace(mixed,' ','') as mixed from ( select substr(ename,1,2)|| cast(deptno as char(4))|| substr(ename,3,2) as mixed from emp where deptno = 10 union all select cast(empno as char(4)) as mixed from emp where deptno = 20 union all select ename as mixed from emp where deptno = 30 ) x select * from v MIXED -------------- CL10AR KI10NG MI10LL 7369 7566 7788 7876 7902 ALLEN WARD MARTIN BLAKE TURNER JAMES You want to return rows that are numbers only, or that contain at least one number. If the numbers are mixed with character data, you want to remove the characters and return only the numbers. For the sample data above you want the following result set: MIXED -------- 10 10 10 7369 7566 7788 7876 7902 ### Solution The functions REPLACE and TRANSLATE are extremely useful for manipulating strings and individual characters. The key is to convert all numbers to a single character, which then makes it easy to isolate and identify any number by referring to a single character. #### DB2 Use functions TRANSLATE, REPLACE, and POSSTR to isolate the numeric characters in each row. The calls to CAST are necessary in view V; otherwise, the view will fail to be created due to type conversion errors. You'll need the function REPLACE to remove extraneous white space due to casting to the fixed length CHAR: 1 select mixed old, 2 cast( 3 case 4 when 5 replace( 6 translate(mixed,'9999999999','0123456789'),'9','') = '' 7 then 8 mixed 9 else replace( 10 translate(mixed, 11 repeat('#',length(mixed)), 12 replace( 13 translate(mixed,'9999999999','0123456789'),'9','')), 14 '#','') 15 end as integer ) mixed 16 from V 17 where posstr(translate(mixed,'9999999999','0123456789'),'9') > 0 #### MySQL The syntax for MySQL is slightly different and will define view V as: create view V as select concat( substr(ename,1,2), replace(cast(deptno as char(4)),' ',''), substr(ename,3,2) ) as mixed from emp where deptno = 10 union all select replace(cast(empno as char(4)), ' ', '') from emp where deptno = 20 union all select ename from emp where deptno = 30 Because MySQL does not support the TRANSLATE function, you must walk each row and evaluate it on a character-by-character basis. 1 select cast(group_concat(c order by pos separator '') as unsigned) 2 as MIXED1 3 from ( 4 select v.mixed, iter.pos, substr(v.mixed,iter.pos,1) as c 5 from V, 6 ( select id pos from t10 ) iter 7 where iter.pos <= length(v.mixed) 8 and ascii(substr(v.mixed,iter.pos,1)) between 48 and 57 9 ) y 10 group by mixed 11 order by 1 #### Oracle Use functions TRANSLATE, REPLACE, and INSTR to isolate the numeric characters in each row. The calls to CAST are not necessary in view V. Use the function REPLACE to remove extraneous white space due to casting to the fixed length CHAR. If you decide you would like to keep the explicit type conversion calls in the view definition, it is suggested you cast to VARCHAR2: 1 select to_number ( 2 case 3 when 4 replace(translate(mixed,'0123456789','9999999999'),'9') 5 is not null 6 then 7 replace( 8 translate(mixed, 9 replace( 10 translate(mixed,'0123456789','9999999999'),'9'), 11 rpad('#',length(mixed),'#')),'#') 12 else 13 mixed 14 end 15 ) mixed 16 from V 17 where instr(translate(mixed,'0123456789','9999999999'),'9') > 0 #### PostgreSQL Use functions TRANSLATE, REPLACE, and STRPOS to isolate the numeric characters in each row. The calls to CAST are not necessary in view V. Use the function REPLACE ito remove extraneous white space due to casting to the fixed length CHAR. If you decide you would like to keep the explicit type conversion calls in the view definition, it is suggested you cast to VARCHAR: 1 select cast( 2 case 3 when 4 replace(translate(mixed,'0123456789','9999999999'),'9','') 5 is not null 6 then 7 replace( 8 translate(mixed, 9 replace( 10 translate(mixed,'0123456789','9999999999'),'9',''), 11 rpad('#',length(mixed),'#')),'#','') 12 else 13 mixed 14 end as integer ) as mixed 15 from V 16 where strpos(translate(mixed,'0123456789','9999999999'),'9') > 0 #### SQL Server The built-in function ISNUMERIC along with a wildcard search allows you to easily identify strings that contains numbers, but getting numeric characters out of a string is not particularly efficient because the TRANSLATE function is not supported. ### Discussion The TRANSLATE function is very useful here as it allows you to easily isolate and identify numbers and characters. The trick is to convert all numbers to a single character; this way, rather than searching for different numbers you only search for one character. #### DB2, Oracle, and PostgreSQL The syntax differs slightly among these DBMSs, but the technique is the same. I'll use the solution for PostgreSQL for the discussion. The real work is done by functions TRANSLATE and REPLACE. To get the final result set requires several function calls, each listed below in one query: **select mixed as orig,** **translate(mixed,'0123456789','9999999999') as mixed1,** **replace(translate(mixed,'0123456789','9999999999'),'9','') as mixed2,** **translate(mixed,** **replace(** **translate(mixed,'0123456789','9999999999'),'9',''),** **rpad('#',length(mixed),'#')) as mixed3,** **replace(** **translate(mixed,** **replace(** **translate(mixed,'0123456789','9999999999'),'9',''),** **rpad('#',length(mixed),'#')),'#','') as mixed4** **from V** **where strpos(translate(mixed,'0123456789','9999999999'),'9')> 0** ORIG | MIXED1 | MIXED2 | MIXED3 | MIXED4 | MIXED5 --------+--------+--------+--------+--------+-------- CL10AR | CL99AR | CLAR | ##10## | 10 | 10 KI10NG | KI99NG | KING | ##10## | 10 | 10 MI10LL | MI99LL | MILL | ##10## | 10 | 10 7369 | 9999 | | 7369 | 7369 | 7369 7566 | 9999 | | 7566 | 7566 | 7566 7788 | 9999 | | 7788 | 7788 | 7788 7876 | 9999 | | 7876 | 7876 | 7876 7902 | 9999 | | 7902 | 7902 | 7902 First, notice that any rows without at least one number are removed. How this is accomplished will become clear as you examine each of the columns in the above result set. The rows that are kept are the values in the ORIG column and are the rows that will eventually make up the result set. The first step to extracting the numbers is to use the function TRANSLATE to convert any number to a 9 (you can use any digit; 9 is arbitrary), this is represented by the values in MIXED1. Now that all numbers are 9's, they can be treating as a single unit. The next step is to remove all of the numbers by using the function REPLACE. Because all digits are now 9, REPLACE simply looks for any 9's and removes them. This is represented by the values in MIXED2. The next step, MIXED3, uses values that are returned by MIXED2. These values are then compared to the values in ORIG. If any characters from MIXED2 are found in ORIG, they are converted to the # character by TRANSLATE. The result set from MIXED3 shows that the letters, not the numbers, have now been singled out and converted to a single character. Now that all non-numeric characters are represented by #'s, they can be treated as a single unit. The next step, MIXED4, uses REPLACE to find and remove any # characters in each row; what's left are numbers only. The final step is to cast the numeric characters as numbers. Now that you've gone through the steps, you can see how the WHERE clause works. The results from MIXED1 are passed to STRPOS, and if a 9 is found (the position in the string where the first 9 is located) the result must be greater than 0. For rows that return a value greater than zero, it means there's at least one number in that row and it should be kept. #### MySQL The first step is to walk each string and evaluate each character and determine whether or not it's a number: **select v.mixed, iter.pos, substr(v.mixed,iter.pos,1) as c** **from V,** **( select id pos from t10 ) iter** **where iter.pos<= length(v.mixed) ** **order by 1,2** +--------+------+------+ | mixed | pos | c | +--------+------+------+ | 7369 | 1 | 7 | | 7369 | 2 | 3 | | 7369 | 3 | 6 | | 7369 | 4 | 9 | ... | ALLEN | 1 | A | | ALLEN | 2 | L | | ALLEN | 3 | L | | ALLEN | 4 | E | | ALLEN | 5 | N | ... | CL10AR | 1 | C | | CL10AR | 2 | L | | CL10AR | 3 | 1 | | CL10AR | 4 | 0 | | CL10AR | 5 | A | | CL10AR | 6 | R | +--------+------+------+ Now that each character in each string can be evaluated individually, the next step is to keep only the rows that have a number in the C column: **select v.mixed, iter.pos, substr(v.mixed,iter.pos,1) as c** **from V,** **( select id pos from t10 ) iter** **where iter.pos<= length(v.mixed)** **and ascii(substr(v.mixed,iter.pos,1)) between 48 and 57** **order by 1,2** +--------+------+------+ | mixed | pos | c | +--------+------+------+ | 7369 | 1 | 7 | | 7369 | 2 | 3 | | 7369 | 3 | 6 | | 7369 | 4 | 9 | ... | CL10AR | 3 | 1 | | CL10AR | 4 | 0 | ... +--------+------+------+ At this point, all the rows in column C are numbers. The next step is to use GROUP_CONCAT to concatenate the numbers to form their respective whole number in MIXED. The final result is then cast as a number: **select cast(group_concat(c order by pos separator '') as unsigned)** **as MIXED1** **from (** **select v.mixed, iter.pos, substr(v.mixed,iter.pos,1) as c** **from V,** **( select id pos from t10 ) iter** **where iter.pos<= length(v.mixed) ** **and ascii(substr(x.mixed,iter.pos,1)) between 48 and 57** **) y** **group by mixed** **order by 1** +--------+ | MIXED1 | +--------+ | 10 | | 10 | | 10 | | 7369 | | 7566 | | 7788 | | 7876 | | 7902 | +--------+ As a final note, keep in mind that any digits in each string will be concatenated to form one numeric value. For example, an input value of, say, '99Gennick87' will result in the value 9987 being returned. This is something to keep in mind, particularly when working with serialized data. ## 6.14. Extracting the _n_ th Delimited Substring ### Problem You want to extract a specified, delimited substring from a string. Consider the following view V, which generates source data for this problem: create view V as select 'mo,larry,curly' as name from t1 union all select 'tina,gina,jaunita,regina,leena' as name from t1 Output from the view is as follows: **select * from v** NAME ------------------- mo,larry,curly tina,gina,jaunita,regina,leena You would like to extract the second name in each row, so the final result set would be: SUB ----- larry gina ### Solution The key to solving this problem is to return each name as an individual row while preserving the order in which the name exists in the list. Exactly how you do these things depends on which DBMS you are using. #### DB2 After walking the NAMEs returned by view V, use the function ROW_NUMBER to keep only the second name from each string: 1 select substr(c,2,locate(',',c,2)-2) 2 from ( 3 select pos, name, substr(name, pos) c, 4 row_number() over( partition by name 5 order by length(substr(name,pos)) desc) rn 6 from ( 7 select ',' ||csv.name|| ',' as name, 8 cast(iter.pos as integer) as pos 9 from V csv, 10 (select row_number() over() pos from t100 ) iter 11 where iter.pos <= length(csv.name)+2 12 ) x 13 where length(substr(name,pos)) > 1 14 and substr(substr(name,pos),1,1) = ',' 15 ) y 16 where rn = 2 #### MySQL After walking the NAMEs returned by view V, use the position of the commas to return only the second name in each string: 1 select name 2 from ( 3 select iter.pos, 4 substring_index( 5 substring_index(src.name,',',iter.pos),',',-1) name 6 from V src, 7 (select id pos from t10) iter, 8 where iter.pos <= 9 length(src.name)-length(replace(src.name,',','')) 10 ) x 11 where pos = 2 #### Oracle After walking the NAMEs returned by view V, retrieve the second name in each list by using SUBSTR and INSTR: 1 select sub 2 from ( 3 select iter.pos, 4 src.name, 5 substr( src.name, 6 instr( src.name,',',1,iter.pos )+1, 7 instr( src.name,',',1,iter.pos+1 ) - 8 instr( src.name,',',1,iter.pos )-1) sub 9 from (select ','||name||',' as name from V) src, 10 (select rownum pos from emp) iter 11 where iter.pos < length(src.name)-length(replace(src.name,',')) 12 ) 13 where pos = 2 #### PostgreSQL Use the function SPLIT_PART to help return each individual name as a row: 1 select name 2 from ( 3 select iter.pos, split_part(src.name,',',iter.pos) as name 4 from (select id as pos from t10) iter, 5 (select cast(name as text) as name from v) src 7 where iter.pos <= 8 length(src.name)-length(replace(src.name,',',''))+1 9 ) x 10 where pos = 2 #### SQL Server After walking the NAMEs returned by view V, use the function ROW_NUMBER to keep only the second name from each string: 1 select substring(c,2,charindex(',',c,2)-2) 2 from ( 3 select pos, name, substring(name, pos, len(name)) as c, 4 row_number() over( 5 partition by name 6 order by len(substring(name,pos,len(name))) desc) rn 7 from ( 8 select ',' + csv.name + ',' as name, 9 iter.pos 10 from V csv, 11 (select id as pos from t100 ) iter 12 where iter.pos <= len(csv.name)+2 13 ) x 14 where len(substring(name,pos,len(name))) > 1 15 and substring(substring(name,pos,len(name)),1,1) = ',' 16 ) y 17 where rn = 2 ### Discussion #### DB2 and SQL Server The syntax is slightly different between these two DBMSs, but the technique is the same. I will use the solution for DB2 for the discussion. The strings are walked and the results are represented by inline view X: **select ','||csv.name|| ',' as name,** **iter.pos** **from v csv,** **(select row_number() over() pos from t100 ) iter** **where iter.pos<= length(csv.name)+2** EMPS POS ------------------------------- ---- ,tina,gina,jaunita,regina,leena, 1 ,tina,gina,jaunita,regina,leena, 2 ,tina,gina,jaunita,regina,leena, 3 ... The next step is to then step through each character in each string: **select pos, name, substr(name, pos) c,** **row_number() over(partition by name** **order by length(substr(name, pos)) desc) rn** **from (** **select ','||csv.name||',' as name,** **cast(iter.pos as integer) as pos** **from v csv,** **(select row_number() over() pos from t100 ) iter** **where iter.pos<= length(csv.name)+2** **) x** **where length(substr(name,pos))> 1** POS EMPS C RN --- --------------- ---------------- -- 1 ,mo,larry,curly, ,mo,larry,curly, 1 2 ,mo,larry,curly, mo,larry,curly, 2 3 ,mo,larry,curly, o,larry,curly, 3 4 ,mo,larry,curly, ,larry,curly, 4 ... Now that different portions of the string are available to you, simply identify which rows to keep. The rows you are interested in are the ones that begin with a comma; the rest can be discarded: **select pos, name, substr(name,pos) c,** **row_number() over(partition by name** **order by length(substr(name, pos)) desc) rn** **from (** **select ','||csv.name||',' as name,** **cast(iter.pos as integer) as pos** **from v csv,** **(select row_number() over() pos from t100 ) iter** **where iter.pos<= length(csv.name)+2** **) x** **where length(substr(name,pos))> 1 ** **and substr(substr(name,pos),1,1) = ','** POS EMPS C RN --- -------------- ---------------- -- 1 ,mo,larry,curly, ,mo,larry,curly, 1 4 ,mo,larry,curly, ,larry,curly, 2 10 ,mo,larry,curly, ,curly, 3 1 ,tina,gina,jaunita,regina,leena, ,tina,gina,jaunita,regina,leena, 1 6 ,tina,gina,jaunita,regina,leena, ,gina,jaunita,regina,leena, 2 11 ,tina,gina,jaunita,regina,leena, ,jaunita,regina,leena, 3 19 ,tina,gina,jaunita,regina,leena, ,regina,leena, 4 26 ,tina,gina,jaunita,regina,leena, ,leena, 5 This is an important step as it sets up how you will get the _n_ th substring. Notice that many rows have been eliminated from this query because of the following condition in the WHERE clause: substr(substr(name,pos),1,1) = ',' You'll notice that `,larry,curly`, was ranked 4, but now is ranked 2. Remember, the WHERE clause is evaluated before the SELECT, so the rows with leading commas are kept, _then_ ROW_NUMBER performs its ranking. At this point it's easy to see that, to get the _n_ th substring you want rows where RN equals _n_. The last step is to keep only the rows you are interested in (in this case where RN equals 2) and use SUBSTR to extract the name from that row. The name to keep is the first name in the row: `larry` from `,larry,curly`, and `gina` from `,gina,jaunita,regina,leena`,. #### MySQL The inline view X walks each string. You can determine how many values are in each string by counting the delimiters in the string: **select iter.pos, src.name** **from (select id pos from t10) iter,** **V src** **where iter.pos<=** **length(src.name)-length(replace(src.name,',',''))** +------+--------------------------------+ | pos | name | +------+--------------------------------+ | 1 | mo,larry,curly | | 2 | mo,larry,curly | | 1 | tina,gina,jaunita,regina,leena | | 2 | tina,gina,jaunita,regina,leena | | 3 | tina,gina,jaunita,regina,leena | | 4 | tina,gina,jaunita,regina,leena | +------+--------------------------------+ In this case, there is one fewer row than values in each string because that's all that is needed. The function SUBSTRING_INDEX takes care of parsing the needed values: **select iter.pos,src.name name1,** **substring_index(src.name,',',iter.pos) name2,** **substring_index(** **substring_index(src.name,',',iter.pos),',',-1) name3** **from (select id pos from t10) iter,** **V src** **where iter.pos<=** **length(src.name)-length(replace(src.name,',',''))** +------+--------------------------------+--------------------------+---------+ | pos | name1 | name2 | name3 | +------+--------------------------------+--------------------------+---------+ | 1 | mo,larry,curly | mo | mo | | 2 | mo,larry,curly | mo,larry | larry | | 1 | tina,gina,jaunita,regina,leena | tina | tina | | 2 | tina,gina,jaunita,regina,leena | tina,gina | gina | | 3 | tina,gina,jaunita,regina,leena | tina,gina,jaunita | jaunita | | 4 | tina,gina,jaunita,regina,leena | tina,gina,jaunita,regina | regina | +------+--------------------------------+--------------------------+---------+ I've shown three name fields, so you can see how the nested SUBSTRING_INDEX calls work. The inner call returns all characters to the left of the _n_ th occurrence of a comma. The outer call returns everything to the right of the first comma it finds (starting from the end of the string). The final step is to keep the value for NAME3 where POS equals _n_ , in this case 2. #### Oracle The inline view walks each string. The number of times each string is returned is determined by how many values are in each string. The solution finds the number of values in each string by counting the number of delimiters in it. Because each string is enclosed in commas, the number of values in a string is the number of commas minus one. The strings are then UNIONed and joined to a table with a cardinality that is at least the number of values in the largest string. The functions SUBSTR and INSTR use the value of POS to parse each string: **select iter.pos, src.name,** **substr( src.name,** **instr( src.name,',',1,iter.pos )+1,** **instr( src.name,',',1,iter.pos+1 )** **instr( src.name,',',1,iter.pos )-1) sub** **from (select ','||name||',' as name from v) src,** **(select rownum pos from emp) iter** **where iter.pos< length(src.name)-length(replace(src.name,','))** POS NAME SUB --- --------------------------------- ------------- 1 ,mo,larry,curly, mo 1 , tina,gina,jaunita,regina,leena, tina 2 ,mo,larry,curly, larry 2 , tina,gina,jaunita,regina,leena, gina 3 ,mo,larry,curly, curly 3 , tina,gina,jaunita,regina,leena, jaunita 4 , tina,gina,jaunita,regina,leena, regina 5 , tina,gina,jaunita,regina,leena, leena The first call to INSTR within SUBSTR determines the start position of the substring to extract. The next call to INSTR within SUBSTR finds the position of the _n_ th comma (same as the start position) as well the position of the _n_ th + 1 comma. Subtracting the two values returns the length of the substring to extract. Because every value is parsed into its own row, simply specify WHERE POS = _n_ to keep the _n_ th substring (in this case, where POS = 2, so, the second substring in the list). #### PostgreSQL The inline view X walks each string. The number of rows returned is determined by how many values are in each string. To find the number of values in each string, find the number of delimiters in each string and add one. The function SPLIT_PART uses the values in POS to find the _n_ th occurrence of the delimiter and parse the string into values: **select iter.pos, src.name as name1,** **split_part(src.name,',',iter.pos) as name2** **from (select id as pos from t10) iter,** **(select cast(name as text) as name from v) src** **where iter.pos<=** **length(src.name)-length(replace(src.name,',',''))+1** pos | name1 | name2 -----+--------------------------------+--------- 1 | mo,larry,curly | mo 2 | mo,larry,curly | larry 3 | mo,larry,curly | curly 1 | tina,gina,jaunita,regina,leena | tina 2 | tina,gina,jaunita,regina,leena | gina 3 | tina,gina,jaunita,regina,leena | jaunita 4 | tina,gina,jaunita,regina,leena | regina 5 | tina,gina,jaunita,regina,leena | leena I've shown NAME twice so you can see how SPLIT_PART parses each string using POS. Once each string is parsed, the final step is the keep the rows where POS equals the _n_ th substring you are interested in, in this case, 2. ## 6.15. Parsing an IP Address ### Problem You want to parse an IP address's fields into columns. Consider the following IP address: 111.22.3.4 You would like the result of your query to be: A B C D ----- ----- ----- --- 111 22 3 4 ### Solution The solution depends on the built-in functions provided by your DBMS. Regardless of your DBMS, being able to locate periods and the numbers immediately surrounding them are the keys to the solution. #### DB2 Use the recursive WITH clause to simulate an iteration through the IP address while using SUBSTR to easily parse it. A leading period is added to the IP address so that every set of numbers has a period in front of it and can be treated the same way. 1 with x (pos,ip) as ( 2 values (1,'.92.111.0.222') 3 union all 4 select pos+1,ip from x where pos+1 <= 20 5 ) 6 select max(case when rn=1 then e end) a, 7 max(case when rn=2 then e end) b, 8 max(case when rn=3 then e end) c, 9 max(case when rn=4 then e end) d 10 from ( 11 select pos,c,d, 12 case when posstr(d,'.') > 0 then substr(d,1,posstr(d,'.')-1) 13 else d 14 end as e, 15 row_number() over( order by pos desc) rn 16 from ( 17 select pos, ip,right(ip,pos) as c, substr(right(ip,pos),2) as d 18 from x 19 where pos <= length(ip) 20 and substr(right(ip,pos),1,1) = '.' 21 ) x 22 ) y #### MySQL The function SUBSTR_INDEX makes parsing an IP address an easy operation: 1 select substring_index(substring_index(y.ip,'.',1),'.',-1) a, 2 substring_index(substring_index(y.ip,'.',2),'.',-1) b, 3 substring_index(substring_index(y.ip,'.',3),'.',-1) c, 4 substring_index(substring_index(y.ip,'.',4),'.',-1) d 5 from (select '92.111.0.2' as ip from t1) y #### Oracle Use the built-in function SUBSTR and INSTR to parse and navigate through the IP address: 1 select ip, 2 substr(ip, 1, instr(ip,'.')-1 ) a, 3 substr(ip, instr(ip,'.')+1, 4 instr(ip,'.',1,2)-instr(ip,'.')-1 ) b, 5 substr(ip, instr(ip,'.',1,2)+1, 6 instr(ip,'.',1,3)-instr(ip,'.',1,2)-1 ) c, 7 substr(ip, instr(ip,'.',1,3)+1 ) d 8 from (select '92.111.0.2' as ip from t1) #### PostgreSQL Use the built-in function SPLIT_PART to parse an IP address: 1 select split_part(y.ip,'.',1) as a, 2 split_part(y.ip,'.',2) as b, 3 split_part(y.ip,'.',3) as c, 4 split_part(y.ip,'.',4) as d 5 from (select cast('92.111.0.2' as text) as ip from t1) as y #### SQL Server Use the recursive WITH clause to simulate an iteration through the IP address while using SUBSTR to easily parse it. A leading period is added to the IP address so that every set of numbers has a period in front of it and can be treated the same way: 1 with x (pos,ip) as ( 2 select 1 as pos,'.92.111.0.222' as ip from t1 3 union all 4 select pos+1,ip from x where pos+1 <= 20 5 ) 6 select max(case when rn=1 then e end) a, 7 max(case when rn=2 then e end) b, 8 max(case when rn=3 then e end) c, 9 max(case when rn=4 then e end) d 10 from ( 11 select pos,c,d, 12 case when charindex('.',d) > 0 13 then substring(d,1,charindex('.',d)-1) 14 else d 15 end as e, 16 row_number() over(order by pos desc) rn 17 from ( 18 select pos, ip,right(ip,pos) as c, 19 substring(right(ip,pos),2,len(ip)) as d 20 from x 21 where pos <= len(ip) 22 and substring(right(ip,pos),1,1) = '.' 23 ) x 24 ) y ### Discussion By using the built-in functions for your database, you can easily walk through parts of a string. The key is being able to locate each of the periods in the address. Then you can parse the numbers between each. ## Chapter 7. Working with Numbers This chapter focuses on common operations involving numbers, including numeric computations. While SQL is not typically considered the first choice for complex computations, it is very efficient for day-to-day numeric chores. ### Tip Some recipes in this chapter make use of aggregate functions and the GROUP BY clause. If you are not familiar with grouping, please read at least the first major section, called "Grouping," in Appendix A. ## 7.1. Computing an Average ### Problem You want to compute the average value in a column, either for all rows in a table or for some subset of rows. For example, you might want to find the average salary for all employees as well as the average salary for each department. ### Solution When computing the average of all employee salaries, simply apply the AVG function to the column containing those salaries. By excluding a WHERE clause, the average is computed against all non-NULL values: **1 select avg(sal) as avg_sal** **2 from emp** AVG_SAL ---------- 2073.21429 To compute the average salary for each department, use the GROUP BY clause to create a group corresponding to each department: **1 select deptno, avg(sal) as avg_sal** **2 from emp** **3 group by deptno** DEPTNO AVG_SAL ---------- ---------- 10 2916.66667 20 2175 30 1566.66667 ### Discussion When finding an average where the whole table is the group or window, simply apply the AVG function to the column you are interested in without using the GROUP BY clause. It is important to realize that the function AVG ignores NULLs. The effect of NULL values being ignored can be seen here: create table t2(sal integer) insert into t2 values (10) insert into t2 values (20) insert into t2 values (null) **select avg(sal) select distinct 30/2** **from t2 from t2** AVG(SAL) 30/2 ---------- ---------- 15 15 **select avg(coalesce(sal,0)) select distinct 30/3** **from t2 from t2** AVG(COALESCE(SAL,0)) 30/3 -------------------- ---------- 10 10 The COALESCE function will return the first non-NULL value found in the list of values that you pass. When NULL SAL values are converted to zero, the average changes. When invoking aggregate functions, always give thought to how you want NULLs handled. The second part of the solution uses GROUP BY (line 3) to divide employee records into groups based on department affiliation. GROUP BY automatically causes aggregate functions such as AVG to execute and return a result for each group. In this example, AVG would execute once for each department-based group of employee records. It is not necessary, by the way, to include GROUP BY columns in your select list. For example: **select avg(sal)** **from emp** **group by deptno** AVG(SAL) ---------- 2916.66667 2175 1566.66667 You are still grouping by DEPTNO even though it is not in the SELECT clause. Including the column you are grouping by in the SELECT clause often improves readability, but is not mandatory. It is mandatory, however, to avoid placing columns in your SELECT list that are not also in your GROUP BY clause. ### See Also Appendix A for a refresher on GROUP BY functionality. ## 7.2. Finding the Min/Max Value in a Column ### Problem You want to find the highest and lowest values in a given column. For example, you want to find the highest and lowest salaries for all employees, as well as the highest and lowest salaries for each department. ### Solution When searching for the lowest and highest salaries for all employees, simply use the functions MIN and MAX, respectively: **1 select min(sal) as min_sal, max(sal) as max_sal** **2 from emp** MIN_SAL MAX_SAL ---------- ---------- 800 5000 When searching for the lowest and highest salaries for each department, use the functions MIN and MAX with the GROUP BY clause: **1 select deptno, min(sal) as min_sal, max(sal) as max_sal** **2 from emp** **3 group by deptno** DEPTNO MIN_SAL MAX_SAL ---------- ---------- ---------- 10 1300 5000 20 800 3000 30 950 2850 ### Discussion When searching for the highest or lowest values, and in cases where the whole table is the group or window, simply apply the MIN or MAX function to the column you are interested in without using the GROUP BY clause. Remember that the MIN and MAX functions ignore NULLs, and that you can have NULL groups as well as NULL values for columns in a group. The following are examples that ultimately lead to a query using GROUP BY that returns NULL values for two groups (DEPTNO 10 and 20): **select deptno, comm** **from emp** **where deptno in (10,30)** **order by 1** DEPTNO COMM ---------- ---------- 10 10 10 30 300 30 500 30 30 0 30 1300 30 **select min(comm), max(comm)** **from emp** MIN(COMM) MAX(COMM) ---------- ---------- 0 1300 **select deptno, min(comm), max(comm)** **from emp** **group by deptno** DEPTNO MIN(COMM) MAX(COMM) ---------- ---------- ---------- 10 20 30 0 1300 Remember, as Appendix A points out, even if nothing other than aggregate functions are listed in the SELECT clause, you can still group by other columns in the table; for example: select min(comm), max(comm) from emp group by deptno MIN(COMM) MAX(COMM) ---------- ---------- 0 1300 Here you are still grouping by DEPTNO even though it is not in the SELECT clause. Including the column you are grouping by in the SELECT clause often improves readability, but is not mandatory. It is mandatory, however, that any column in the SELECT list of a GROUP BY query also be listed in the GROUP BY clause. ### See Also Appendix A for a refresher on GROUP BY functionality. ## 7.3. Summing the Values in a Column ### Problem You want to compute the sum of all values, such as all employee salaries, in a column. ### Solution When computing a sum where the whole table is the group or window, simply apply the SUM function to the columns you are interested in without using the GROUP BY clause: **1 select sum(sal)** **2 from emp** SUM(SAL) ---------- 29025 When creating multiple groups or windows of data, use the SUM function with the GROUP BY clause. The following example sums employee salaries by department: **1 select deptno, sum(sal) as total_for_dept** **2 from emp** **3 group by deptno** DEPTNO TOTAL_FOR_DEPT ---------- -------------- 10 8750 20 10875 30 9400 ### Discussion When searching for the sum of all salaries for each department, you are creating groups or "windows" of data. Each employee's salary is added together to produce a total for his respective department. This is an example of aggregation in SQL because detailed information, such as each individual employee's salary, is not the focus; the focus is the end result for each department. It is important to note that the SUM function will ignore NULLs, but you can have NULL groups, which can be seen here. DEPTNO 10 does not have any employees who earn a commission, thus grouping by DEPTNO 10 while attempting to SUM the values in COMM will result in a group with a NULL value returned by SUM: **select deptno, comm** **from emp** **where deptno in (10,30)** **order by 1** DEPTNO COMM ---------- ---------- 10 10 10 30 300 30 500 30 30 0 30 1300 30 **select sum(comm)** **from emp** **SUM(COMM)** **----------** **2100** **select deptno, sum(comm)** **from emp** **where deptno in (10,30)** **group by deptno** DEPTNO SUM(COMM) ---------- ---------- 10 30 2100 ### See Also Appendix A for a refresher on GROUP BY functionality. ## 7.4. Counting Rows in a Table ### Problem You want to count the number of rows in a table, or you wish to count the number of values in a column. For example, you want to find the total number of employees as well as the number of employees in each department. ### Solution When counting rows where the whole table is the group or window, simply use the COUNT function along with the "*" character: **1 select count(*)** **2 from emp** COUNT(*) ---------- 14 When creating multiple groups, or windows of data, use the COUNT function with the GROUP BY clause: **1 select deptno, count(*)** **2 from emp** **3 group by deptno** DEPTNO COUNT(*) ---------- ---------- 10 3 20 5 30 6 ### Discussion When counting the number of employees for each department, you are creating groups or "windows" of data. Each employee found increments the count by one to produce a total for her respective department. This is an example of aggregation in SQL because detailed information, such as each individual employee's salary or job, is not the focus; the focus is the end result for each department. It is important to note that the COUNT function will ignore NULLs when passed a column name as an argument, but will include NULLs when passed the "*" character or any constant; consider: **select deptno, comm** **from emp** DEPTNO COMM ---------- ---------- 20 30 300 30 500 20 30 1300 30 10 20 10 30 0 20 30 20 10 **select count(*), count(deptno), count(comm), count('hello')** **from emp** COUNT(*) COUNT(DEPTNO) COUNT(COMM) COUNT('HELLO') ---------- ------------- ----------- -------------- 14 14 4 14 **select deptno, count(*), count(comm), count('hello')** **from emp** **group by deptno** DEPTNO COUNT(*) COUNT(COMM) COUNT('HELLO') ---------- ---------- ----------- -------------- 10 3 0 3 20 5 0 5 30 6 4 6 If all rows are null for the column passed to COUNT or if the table is empty, COUNT will return zero. It should also be noted that, even if nothing other than aggregate functions are specified in the SELECT clause, you can still group by other columns in the table; for example: **select count(*)** **from emp** **group by deptno** COUNT(*) ---------- 3 5 6 Notice that you are still grouping by DEPTNO even though it is not in the SELECT clause. Including the column you are grouping by in the SELECT clause often improves readability, but is not mandatory. If you do include it (in the SELECT list), it is mandatory that is it listed in the GROUP BY clause. ### See Also Appendix A for a refresher on GROUP BY functionality. ## 7.5. Counting Values in a Column ### Problem You wish to count the number of non-NULL values in a column. For example, you'd like to find out how many employees are on commission. ### Solution Count the number of non-NULL values in the EMP table's COMM column: **select count(comm)** **from emp** COUNT(COMM) ----------- 4 ### Discussion When you "count star," as in COUNT(*), what you are really counting is rows (regardless of actual value, which is why rows containing NULL and non-NULL values are counted). But when you COUNT a column, you are counting the number of non-NULL values in that column. The previous recipe's discussion touches on this distinction. In this solution, COUNT(COMM) returns the number of non-NULL values in the COMM column. Since only commissioned employees have commissions, the result of COUNT(COMM) is the number of such employees. ## 7.6. Generating a Running Total ### Problem You want to calculate a running total of values in a column. ### Solution As an example, the following solutions show how to compute a running total of salaries for all employees. For readability, results are ordered by SAL whenever possible so that you can easily eyeball the progression of the running total. #### DB2 and Oracle Use the windowing version of the function SUM to compute a running total: **1 select ename, sal,** **2 sum(sal) over (order by sal,empno) as running_total** **3 from emp** **4 order by 2** ENAME SAL RUNNING_TOTAL ---------- ---------- ------------- SMITH 800 800 JAMES 950 1750 ADAMS 1100 2850 WARD 1250 4100 MARTIN 1250 5350 MILLER 1300 6650 TURNER 1500 8150 ALLEN 1600 9750 CLARK 2450 12200 BLAKE 2850 15050 JONES 2975 18025 SCOTT 3000 21025 FORD 3000 24025 KING 5000 29025 #### MySQL, PostgreSQL, and SQL Server Use a scalar subquery to compute a running total (without the use of a window function such as SUM OVER, you cannot easily order the result set by SAL as in the DB2 and Oracle solution). Ultimately, the running total is correct (the final value is the same as the above recipe), but the intermediate values differ due to the lack of ordering: **1 select e.ename, e.sal,** **2 (select sum(d.sal) from emp d** **3 where d.empno<= e.empno) as running_total** **4 from emp e** **5 order by 3** ENAME SAL RUNNING_TOTAL ---------- ---------- ------------- SMITH 800 800 ALLEN 1600 2400 WARD 1250 3650 JONES 2975 6625 MARTIN 1250 7875 BLAKE 2850 10725 CLARK 2450 13175 SCOTT 3000 16175 KING 5000 21175 TURNER 1500 22675 ADAMS 1100 23775 JAMES 950 24725 FORD 3000 27725 MILLER 1300 29025 ### Discussion Generating a running total is one of the tasks made simple by the new ANSI windowing functions. For DBMSs that do not yet support these windowing functions, a scalar subquery (joining on a field with unique values) is required. #### DB2 and Oracle The windowing function SUM OVER makes generating a running total a simple task. The ORDER BY clause in the solution includes not only the SAL column, but also the EMPNO column (which is the primary key) to avoid duplicate values in the running total. The column RUNNING_TOTAL2 in the following example illustrates the problem that you might otherwise have with duplicates: **select empno, sal,** **sum(sal)over(order by sal,empno) as** **running_total1,** **sum(sal)over(order by sal) as running_total2** **from emp** **order by 2** ENAME SAL RUNNING_TOTAL1 RUNNING_TOTAL2 ---------- ---------- -------------- -------------- SMITH 800 800 800 JAMES 950 1750 1750 ADAMS 1100 2850 2850 WARD 1250 4100 5350 MARTIN 1250 5350 5350 MILLER 1300 6650 6650 TURNER 1500 8150 8150 ALLEN 1600 9750 9750 CLARK 2450 12200 12200 BLAKE 2850 15050 15050 JONES 2975 18025 18025 SCOTT 3000 21025 24025 FORD 3000 24025 24025 KING 5000 29025 29025 The values in RUNNING_TOTAL2 for WARD, MARTIN, SCOTT, and FORD are incorrect. Their salaries occur more than once, and those duplicates are summed together and added to the running total. This is why EMPNO (which is unique) is needed to produce the (correct) results that you see in RUNNING_TOTAL1. Consider this: for ADAMS you see 2850 for RUNNING_TOTAL1 and RUNNING_TOTAL2. Add WARD's salary of 1250 to 2850 and you get 4100, yet RUNNING_TOTAL2 returns 5350. Why? Since WARD and MARTIN have the same SAL, their two 1250 salaries are added together to yield 2500, which is then added to 2850 to arrive at 5350 for both WARD and MARTIN. By specifying a combination of columns to order by that cannot result in duplicate values (e.g., any combination of SAL and EMPNO is unique), you ensure the correct progression of the running total. #### MySQL, PostgreSQL, and SQL Server Until windowing functions are fully supported for these DBMSs, you can use a scalar subquery to compute a running total. You must join on a column with unique values; otherwise the running total will have incorrect values in the event that duplicate salaries exist. The key to this recipe's solution is the join on D.EMPNO to E. EMPNO, which returns (sums) every D.SAL where D.EMPNO is less than or equal E.EMPNO. This can be understood easily by rewriting the scalar subquery as a join for a handful of the employees: **select e.ename as ename1, e.empno as empno1, e.sal as sal1,** **d.ename as ename2, d.empno as empno2, d.sal as sal2** **from emp e, emp d** **where d.empno<= e.empno** **and e.empno = 7566** ENAME EMPNO1 SAL1 ENAME EMPNO2 SAL2 ---------- ---------- ---------- ---------- ---------- ---------- JONES 7566 2975 SMITH 7369 800 JONES 7566 2975 ALLEN 7499 1600 JONES 7566 2975 WARD 7521 1250 JONES 7566 2975 JONES 7566 2975 Every value in EMPNO2 is compared against every value in EMPNO1. For every row where the value in EMPNO2 is less than or equal to the value in EMPNO1, the value in SAL2 is included in the sum. In this snippet, the EMPNO values for employees Smith, Allen, Ward, and Jones are compared against the EMPNO of Jones. Since all four employees' EMPNOs meet the condition of being less than or equal to Jones' EMPNO, those salaries are summed. Any employee whose EMPNO is greater than Jones' is not included in the SUM (in this snippet). The way the full query works is by summing all the salaries where the corresponding EMPNO is less than or equal to 7934 (Miller's EMPNO), which is the highest in the table. ## 7.7. Generating a Running Product ### Problem You want to compute a running product on a numeric column. The operation is similar to "Calculating a Running Total," but using multiplication instead of addition. ### Solution By way of example, the solutions all compute running products of employee salaries. While a running product of salaries may not be all that useful, the technique can easily be applied to other, more useful domains. #### DB2 and Oracle Use the windowing function SUM OVER and take advantage of the fact that you can simulate multiplication by adding logarithms: **1 select empno,ename,sal,** **2 exp(sum(ln(sal))over(order by sal,empno)) as running_prod** **3 from emp** **4 where deptno = 10** EMPNO ENAME SAL RUNNING_PROD ----- ---------- ---- -------------------- 7934 MILLER 1300 1300 7782 CLARK 2450 3185000 7839 KING 5000 15925000000 It is not valid in SQL to compute logarithms of values less than or equal to zero. If you have such values in your tables you need to avoid passing those invalid values to SQL's LN function. Precautions against invalid values and NULLs are not provided in this solution for the sake of readability, but you should consider whether to place such precautions in production code that you write. If you absolutely must work with negative and zero values, then this solution may not work for you. An alternative, Oracle-only solution is to use the MODEL clause that became available in Oracle Database 10 _g_. In the following example, each SAL is returned as a negative number to show that negative values will not cause a problem for the running product: **1 select empno, ename, sal, tmp as running_prod** **2 from (** **3 select empno,ename,-sal as sal** **4 from emp** **5 where deptno=10** **6 )** **7 model** **8 dimension by(row_number()over(order by sal desc) rn )** **9 measures(sal, 0 tmp, empno, ename)** **10 rules (** **11 tmp[any] = case when sal[cv()-1] is null then sal[cv()]** **12 else tmp[cv()-1]*sal[cv()]** **13 end** **14 )** EMPNO ENAME SAL RUNNING_PROD ----- ---------- ---- -------------------- 7934 MILLER -1300 -1300 7782 CLARK -2450 3185000 7839 KING -5000 -15925000000 #### MySQL, PostgreSQL, and SQL Server You still use the approach of summing logarithms, but these platforms do not support windowing functions, so use a scalar subquery instead: **1 select e.empno,e.ename,e.sal,** **2 (select exp(sum(ln(d.sal)))** **3 from emp d** **4 where d.empno<= e.empno** **5 and e.deptno=d.deptno) as running_prod** **6 from emp e** **7 where e.deptno=10** EMPNO ENAME SAL RUNNING_PROD ----- ---------- ---- -------------------- 7782 CLARK 2450 2450 7839 KING 5000 12250000 7934 MILLER 1300 15925000000 SQL Server users use LOG instead of LN. ### Discussion Except for the MODEL clause solution, which is only usable with Oracle Database 10 _g_ or later, all the solutions take advantage of the fact that you can multiply two numbers by: 1. Computing their respective natural logarithms 2. Summing those logarithms 3. Raising the result to the power of the mathematical constant _e_ (using the EXP function) The one caveat when using this approach is that it doesn't work for summing zero or negative values, because any value less than or equal to zero is out of range for an SQL logarithm. #### DB2 and Oracle For an explanation of how the window function SUM OVER works, see the previous recipe "Generating a Running Total." In Oracle Database 10 _g_ and later, you can generate running products via the MODEL clause. Using the MODEL clause along with the window function ROW_NUMBER allows you to easily access prior rows. Each item in the MEASURES list can be accessed like an array. The arrays can then be searched by using the items in the DIMENSIONS list (which are the values returned by ROW_NUMBER, alias RN): **select empno, ename, sal, tmp as running_prod,rn** **from (** **select empno,ename,-sal as sal** **from emp** **where deptno=10** **)** **model** **dimension by(row_number()over(order by sal desc) rn )** **measures(sal, 0 tmp, empno, ename)** **rules ()** EMPNO ENAME SAL RUNNING_PROD RN ----- ---------- ---------- ------------ ---------- 7934 MILLER -1300 0 1 7782 CLARK -2450 0 2 7839 KING -5000 0 3 Observe that SAL[1] has a value of–1300. Because the numbers are increasing by one with no gaps, you can reference prior rows by subtracting one. The RULES clause: rules ( tmp[any] = case when sal[cv()-1] is null then sal[cv()] else tmp[cv()-1]*sal[cv()] end ) uses the built-in operator, ANY, to work through each row without hard-coding. ANY in this case will be the values 1, 2, and 3. TMP[ _n_ ] is initialized to zero. A value is assigned to TMP[ _n_ ] by evaluating the current value (the function CV returns the current value) of the corresponding SAL row. TMP[1] is initially zero and SAL[1] is–1300. There is no value for SAL[0] so TMP[1] is set to SAL[1]. After TMP[1] is set, the next row is TMP[2]. First SAL[1] is evaluated (SAL[CV()–1] is SAL[1] because the current value of ANY is now 2). SAL[1] is not null, it is–1300, so TMP[2] is set to the product of TMP[1] and SAL[2]. This is continued for all the rows. #### MySQL, PostgreSQL, and SQL Server See "Generating a Running Total" earlier in this chapter for an explanation of the subquery approach used for the MySQL, PostgreSQL, and SQL Server solutions. Be aware that the output of the subquery-based solution is slightly different from that of the Oracle and DB2 solutions due to the EMPNO comparison (the running product is computed in a different order). Like a running total, the summation is driven by the predicate of the scalar subquery; the ordering of rows is by EMPNO for this solution whereas the Oracle/DB2 solution order is by SAL. ## 7.8. Calculating a Running Difference ### Problem You want to compute a running difference on values in a numeric column. For example, you want to compute a running difference on the salaries in DEPTNO 10. You would like to return the following result set: ENAME SAL RUNNING_DIFF ---------- ---------- ------------ MILLER 1300 1300 CLARK 2450 -1150 KING 5000 -6150 ### Solution #### DB2 and Oracle Use the window function SUM OVER to create a running difference: 1 select ename,sal, 2 sum(case when rn = 1 then sal else -sal end) 3 over(order by sal,empno) as running_diff 4 from ( 5 select empno,ename,sal, 6 row_number()over(order by sal,empno) as rn 7 from emp 8 where deptno = 10 9 ) x #### MySQL, PostgreSQL, and SQL Server Use a scalar subquery to compute a running difference: 1 select a.empno, a.ename, a.sal, 2 (select case when a.empno = min(b.empno) then sum(b.sal) 3 else sum(-b.sal) 4 end 5 from emp b 6 where b.empno <= a.empno 7 and b.deptno = a.deptno ) as rnk 8 from emp a 9 where a.deptno = 10 ### Discussion The solutions are identical to those of "Generating a Running Total." The only difference is that all values for SAL are returned as negative values with the exception of the first (you want the starting point to be the first SAL in DEPTNO 10). ## 7.9. Calculating a Mode ### Problem You want to find the mode (for those of you who don't recall, the _mode_ in mathematics is the element that appears most frequently for a given set of data) of the values in a column. For example, you wish to find mode of the salaries in DEPTNO 20. Based on the following salaries: **select sal** **from emp** **where deptno = 20** **order by sal** SAL ---------- 800 1100 2975 3000 3000 the mode is 3000. ### Solution #### DB2 and SQL Server Use the window function DENSE_RANK to rank the counts of the salaries to facilitate extracting the mode: 1 select sal 2 from ( 3 select sal, 4 dense_rank()over( order by cnt desc) as rnk 5 from ( 6 select sal, count(*) as cnt 8 from emp 9 where deptno = 20 10 group by sal 11 ) x 12 ) y 13 where rnk = 1 #### Oracle Users on Oracle8 _i_ Database can use the solution provided for DB2. If you are on Oracle9 _i_ Database and later, you can use the KEEP extension to the aggregate function MAX to find the mode SAL. One important note is that if there are ties, i.e., multiple rows that are the mode, the solution using KEEP will only keep one, and that is the one with the highest salary. If you want to see all modes (if more than one exists), you must modify this solution or simply use the DB2 solution presented above. In this case, since 3000 is the mode SAL in DEPTNO 20 and is also the highest SAL, this solution is sufficient: 1 select max(sal) 2 keep(dense_rank first order by cnt desc) sal 3 from ( 4 select sal, count(*) cnt 5 from emp 6 where deptno=20 7 group by sal 8 ) #### MySQL and PostgreSQL Use a subquery to find the mode: 1 select sal 2 from emp 3 where deptno = 20 4 group by sal 5 having count(*) >= all ( select count(*) 6 from emp 7 where deptno = 20 8 group by sal ) ### Discussion #### DB2 and SQL Server The inline view X returns each SAL and the number of times it occurs. Inline view Y uses the window function DENSE_RANK (which allows for ties) to sort the results. The results are ranked based on the number of times each SAL occurs as is seen below: 1 select sal, 2 dense_rank()over(order by cnt desc) as rnk 3 from ( 4 select sal,count(*) as cnt 5 from emp 6 where deptno = 20 7 group by sal 8 ) x SAL RNK ----- ---------- 3000 1 800 2 1100 2 2975 2 The outermost portion of query simply keeps the row(s) where RNK is 1. #### Oracle The inline view returns each SAL and the number of times it occurs and is shown below: **select sal, count(*) cnt** **from emp** **where deptno=20** **group by sal** SAL CNT ----- ---------- 800 1 1100 1 2975 1 3000 2 The next step is to use the KEEP extension of the aggregate function MAX to find the mode. If you analyze the KEEP clause shown below you will notice three subclauses, DENSE_RANK, FIRST, and ORDER BY CNT DESC: keep(dense_rank first order by cnt desc) What this does is extremely convenient for finding the mode. The KEEP clause determines which SAL will be returned by MAX by looking at the value of CNT returned by the inline view. Working from right to left, the values for CNT are ordered in descending order, then the first is kept of all the values for CNT returned in DENSE_RANK order. Looking at the result set from the inline view, you can see that 3000 has the highest CNT of 2. The MAX(SAL) returned is the greatest SAL that has the greatest CNT, in this case 3000. ### See Also Chapter 11, the section on "Finding Knight Values," for a deeper discussion of Oracle's KEEP extension of aggregate functions. #### MySQL and PostgreSQL The subquery returns the number of times each SAL occurs. The outer query returns any SAL that has a number of occurrences greater than or equal to all of the counts returned by the subquery (or to put it another way, the outer query returns the most common salaries in DEPTNO 20). ## 7.10. Calculating a Median ### Problem You want to calculate the median (for those of who do not recall, the _median_ is the value of the middle member of a set of ordered elements) value for a column of numeric values. For example, you want to find the median of the salaries in DEPTNO 20. Based on the following salaries: **select sal** **from emp** **where deptno = 20** **order by sal** SAL ---------- 800 1100 2975 3000 3000 the median is 2975. ### Solution Other than the Oracle solution (which uses supplied functions to compute a median), all of the solutions are based on the method described by Rozenshtein, Abramovich, and Birger in _Optimizing Transact-SQL: Advanced Programming Techniques_ (SQL Forum Press, 1997). The introduction of window functions allows for a more efficient solution compared to the traditional self join. #### DB2 Use the window functions COUNT(*) OVER and ROW_NUMBER to find the median: 1 select avg(sal) 2 from ( 3 select sal, 4 count(*) over() total, 5 cast(count(*) over() as decimal)/2 mid, 6 ceil(cast(count(*) over() as decimal)/2) next, 7 row_number() over ( order by sal) rn 8 from emp 9 where deptno = 20 10 ) x 11 where ( mod(total,2) = 0 12 and rn in ( mid, mid+1 ) 13 ) 14 or ( mod(total,2) = 1 15 and rn = next 16 ) #### MySQL and PostgreSQL Use a self join to find the median: 1 select avg(sal) 2 from ( 3 select e.sal 4 from emp e, emp d 5 where e.deptno = d.deptno 6 and e.deptno = 20 7 group by e.sal 8 having sum(case when e.sal = d.sal then 1 else 0 end) 9 >= abs(sum(sign(e.sal - d.sal))) 10 ) #### Oracle Use the functions MEDIAN (Oracle Database 10 _g_ ) or PERCENTILE_CONT (Oracle9 _i_ Database): 1 select median(sal) 2 from emp 3 where deptno=20 1 select percentile_cont(0.5) 2 within group(order by sal) 3 from emp 4 where deptno=20 Use the DB2 solution for Oracle8 _i_ Database. For versions prior to Oracle8 _i_ Database you can use the PostgreSQL/MySQL solution. #### SQL Server Use the window functions COUNT(*) OVER and ROW_NUMBER to find the median: 1 select avg(sal) 2 from ( 3 select sal, 4 count(*)over() total, 5 cast(count(*)over() as decimal)/2 mid, 6 ceiling(cast(count(*)over() as decimal)/2) next, 7row_number()over( order by sal) rn 8 from emp 9 where deptno = 20 10 ) x 11 where ( total%2 = 0 12 and rn in ( mid, mid+1 ) 13 ) 14 or ( total%2 = 1 15 and rn = next 16 ) ### Discussion #### DB2 and SQL Server The only difference between the DB2 and SQL Server solutions is a small point of syntax: SQL Server uses "%" for modulo and DB2 uses the function MOD; otherwise they are the same. Inline view X returns three different counts, TOTAL, MID, and NEXT, along with RN, generated by ROW_NUMBER. These additional columns help determine how to find the median. Examine the result set for inline view X to see what these columns represent: **select sal,** **count(*)over() total,** **cast(count(*)over() as decimal)/2 mid,** **ceil(cast(count(*)over() as decimal)/2) next,** **row_number()over(order by sal) rn** **from emp** **where deptno = 20** SAL TOTAL MID NEXT RN ---- ----- ---- ---- ---- 800 5 2.5 3 1 1100 5 2.5 3 2 2975 5 2.5 3 3 3000 5 2.5 3 4 3000 5 2.5 3 5 To find the median, the values for SAL must be ordered from lowest to highest. Since DEPTNO 20 has an odd number of employees, the median is simply the SAL that is located in the position where RN equals NEXT (the position that represents the smallest whole number larger than the total number of employees divided by two). The first part of the WHERE clause (lines 11–13) is not satisfied if there are an odd number of rows returned by the result set. If you know that the result set will always be odd, you can simplify to: select avg(sal) from ( select sal, count(*)over() total, ceil(cast(count(*)over() as decimal)/2) next, row_number()over(order by sal) rn from emp where deptno = 20 ) x where rn = next Unfortunately, if you have an even number of rows in the result set, the simplified solution will not work. The original solution handles even-numbered rows by using the values in the column MID. Consider what the results from inline view X would look like for DEPTNO 30, which has six employees: **select sal,** **count(*)over() total,** **cast(count(*)over() as decimal)/2 mid,** **ceil(cast(count(*)over() as decimal)/2) next,** **row_number()over(order by sal) rn** **from emp** **where deptno = 30** SAL TOTAL MID NEXT RN ---- ----- ---- ---- ---- 950 6 3 3 1 1250 6 3 3 2 1250 6 3 3 3 1500 6 3 3 4 1600 6 3 3 5 2850 6 3 3 6 Since there are an even number of rows returned, the median is computed by taking the average of two rows; the row where RN equals MID and the row where RN equals MID + 1. #### MySQL and PostgreSQL The median is computed by first self joining table EMP, which returns a Cartesian product for all the salaries (but the GROUP BY on E.SAL will prevent duplicates from being returned). The HAVING clause uses the function SUM to count the number of times E.SAL equals D.SAL; if this count is greater than or equal to the number of times E.SAL is greater than D.SAL then that row is the median. You can observe this by moving the SUM into the SELECT list: **select e.sal,** **sum(case when e.sal=d.sal** **then 1 else 0 end) as cnt1,** **abs(sum(sign(e.sal - d.sal))) as cnt2** **from emp e, emp d** **where e.deptno = d.deptno** **and e.deptno = 20** **group by e.sal** SAL CNT1 CNT2 ---- ---- ---- 800 1 4 1100 1 2 2975 1 0 3000 4 6 #### Oracle If you are on Oracle Database 10 _g_ or Oracle9 _i_ Database, you can leave the work of computing a median to functions supplied by Oracle. If you are running Oracle8 _i_ Database, you can use the DB2 solution. Otherwise you must use the PostgreSQL solution. While the MEDIAN function obviously computes a median, it may not be at all obvious that PERCENTILE_CONT does so as well. The argument passed to PERCENTILE_CONT, 0.5, is a percentile value. The clause, WITHIN GROUP (ORDER BY SAL), determines which sorted rows PERCENTILE_CONT will search (remember, a median is the middle value from a set of ordered values). The value returned is the value from the sorted rows that falls into the given percentile (in this case, 0.5, which is the middle because the boundary values are 0 and 1). ## 7.11. Determining the Percentage of a Total ### Problem You want to determine the percentage that values in a specific column represent against a total. For example, you want to determine what percentage of all salaries are the salaries in DEPTNO 10 (the percentage that DEPTNO 10 salaries contribute to the total). ### Solution In general, computing a percentage against a total in SQL is no different than doing so on paper; simply divide, then multiply. In this example you want to find the percentage of total salaries in table EMP that come from DEPTNO 10. To do that, simply find the salaries for DEPTNO 10, and then divide by the total salary for the table. As the last step, multiply by 100 to return a value that represents a percent. #### MySQL and PostgreSQL Divide the sum of the salaries in DEPTNO 10 by the sum of all salaries: 1 select (sum( 2 case when deptno = 10 then sal end)/sum(sal) 3 )*100 as pct 4 from emp #### DB2, Oracle, and SQL Server Use an inline view with the window function SUM OVER to find the sum of all salaries along with the sum of all salaries in DEPTNO 10. Then do the division and multiplication in the outer query: 1 select distinct (d10/total)*100 as pct 2 from ( 3 select deptno, 4 sum(sal)over() total, 5 sum(sal)over(partition by deptno) d10 6 from emp 7 ) x 8 where deptno=10 ### Discussion #### MySQL and PostgreSQL The CASE statement conveniently returns only the salaries from DEPTNO 10. They are then summed and divided by the sum of all the salaries. Because NULLs are ignored by aggregates, an ELSE clause is not needed in the CASE statement. To see exactly which values are divided, execute the query without the division: **select sum(case when deptno = 10 then sal end) as d10,** **sum(sal)** **from emp** D10 SUM(SAL) ---- --------- 8750 29025 Depending on how you define SAL, you may need to include explicit casts when performing division. For example, on DB2, SQL Server, and PostgreSQL, if SAL is stored as an integer, you can cast to decimal to get the correct answer, as seen below: select (cast( sum(case when deptno = 10 then sal end) as decimal)/sum(sal) )*100 as pct from emp #### DB2, Oracle, and SQL Server As an alternative to the traditional solution, this solution uses window functions to compute a percentage relative to the total. For DB2 and SQL Server, if you've stored SAL as an integer, you'll need to cast before dividing: select distinct cast(d10 as decimal)/total*100 as pct from ( select deptno, sum(sal)over() total, sum(sal)over(partition by deptno) d10 from emp ) x where deptno=10 It is important to keep in mind that window functions are applied after the WHERE clause is evaluated. Thus, the filter on DEPTNO cannot be performed in inline view X. Consider the results of inline view X without and with the filter on DEPTNO. First without: **select deptno,** **sum(sal)over() total,** **sum(sal)over(partition by deptno) d10** **from emp** DEPTNO TOTAL D10 ------- --------- --------- 10 29025 8750 10 29025 8750 10 29025 8750 20 29025 10875 20 29025 10875 20 29025 10875 20 29025 10875 20 29025 10875 30 29025 9400 30 29025 9400 30 29025 9400 30 29025 9400 30 29025 9400 30 29025 9400 and now with: **select deptno,** **sum(sal)over() total,** **sum(sal)over(partition by deptno) d10** **from emp** **where deptno=10** DEPTNO TOTAL D10 ------ --------- --------- 10 8750 8750 10 8750 8750 10 8750 8750 Because window functions are applied after the WHERE clause, the value for TOTAL represents the sum of all salaries in DEPTNO 10 only. But to solve the problem you want the TOTAL to represent the sum of all salaries, period. That's why the filter on DEPTNO must happen outside of inline view X. ## 7.12. Aggregating Nullable Columns ### Problem You want to perform an aggregation on a column, but the column is nullable. You want the accuracy of your aggregation to be preserved, but are concerned because aggregate functions ignore NULLs. For example, you want to determine the average commission for employees in DEPTNO 30, but there are some employees who do not earn a commission (COMM is NULL for those employees). Because NULLs are ignored by aggregates, the accuracy of the output is compromised. You would like to somehow include NULL values in your aggregation. ### Solution Use the COALESCE function to convert NULLs to 0, so they will be included in the aggregation: 1 select avg(coalesce(comm,0)) as avg_comm 2 from emp 3 where deptno=30 ### Discussion When working with aggregate functions, keep in mind that NULLs are ignored. Consider the output of the solution without using the COALESCE function: **select avg(comm)** **from emp** **where deptno=30** AVG(COMM) --------- 550 This query shows an average commission of 550 for DEPTNO 30, but a quick examination of those rows: **select ename, comm** **from emp** **where deptno=30** **order by comm desc** ENAME COMM ---------- --------- BLAKE JAMES MARTIN 1400 WARD 500 ALLEN 300 TURNER 0 shows that only four of the six employees can earn a commission. The sum of all commissions in DEPTNO 30 is 2200, and the average should be 2200/6, not 2200/4. By excluding the COALESCE function, you answer the question, "What is the average commission of employees in DEPTNO 30 _who can earn a commission_?" rather than "What is the average commission of all employees in DEPTNO 30?" When working with aggregates, remember to treat NULLs accordingly. ## 7.13. Computing Averages Without High and Low Values ### Problem You want to compute an average, but you wish to exclude the highest and lowest values in order to (hopefully) reduce the effect of skew. For example, you want to compute the average salary of all employees excluding the highest and lowest salaries. ### Solution #### MySQL and PostgreSQL Use subqueries to exclude high and low values: 1 select avg(sal) 2 from emp 3 where sal not in ( 4 (select min(sal) from emp), 5 (select max(sal) from emp) 6 ) #### DB2, Oracle, and SQL Server Use an inline view with the windowing functions MAX OVER and MIN OVER to generate a result set from which you can easily eliminate the high and low values: 1 select avg(sal) 2 from ( 3 select sal, min(sal)over() min_sal, max(sal)over() max_sal 4 from emp 5 ) x 6 where sal not in (min_sal,max_sal) ### Discussion #### MySQL and PostgreSQL The subqueries return the highest and lowest salaries in the table. By using NOT IN against the values returned, you exclude the highest and lowest salaries from the average. Keep in mind that if there are duplicates (if multiple employees have the highest or lowest salaries), they will all be excluded from the average. If your goal is to exclude only a single instance of the high and low values, simply subtract them from the SUM and then divide: select (sum(sal)-min(sal)-max(sal))/(count(*)-2) from emp #### DB2, Oracle, and SQL Server Inline view X returns each salary along with the highest and lowest salary: **select sal, min(sal)over() min_sal, max(sal)over() max_sal** **from emp** SAL MIN_SAL MAX_SAL --------- --------- --------- 800 800 5000 1600 800 5000 1250 800 5000 2975 800 5000 1250 800 5000 2850 800 5000 2450 800 5000 3000 800 5000 5000 800 5000 1500 800 5000 1100 800 5000 950 800 5000 3000 800 5000 1300 800 5000 You can access the high and low salary at every row, so finding which salaries are highest and/or lowest is trivial. The outer query filters the rows returned from inline view X such that any salary that matches either MIN_SAL or MAX_SAL is excluded from the average. ## 7.14. Converting Alphanumeric Strings into Numbers ### Problem You have alphanumeric data and would like to return numbers only. You want to return the number 123321 from the string "paul123f321". ### Solution #### DB2 Use the functions TRANSLATE and REPLACE to extract numeric characters from an alphanumeric string: 1 select cast( 2 replace( 3 translate( 'paul123f321', 4 repeat('#',26), 5 'abcdefghijklmnopqrstuvwxyz'),'#','') 6 as integer ) as num 7 from t1 #### Oracle and PostgreSQL Use the functions TRANSLATE and REPLACE to extract numeric characters from an alphanumeric string: 1 select cast( 2 replace( 3 translate( 'paul123f321', 4 'abcdefghijklmnopqrstuvwxyz', 5 rpad('#',26,'#')),'#','') 6 as integer ) as num 7 from t1 #### MySQL and SQL Server As of the time of this writing, neither vendor supports the TRANSLATE function, thus a solution will not be provided. ### Discussion The only difference between the two solutions is syntax; DB2 uses the function REPEAT rather than RPAD and the parameter list for TRANSLATE is in a different order. The following explanation uses the Oracle/PostgreSQL solution but is relevant to DB2 as well. If you run query inside out (starting with TRANSLATE only), you'll see this is very simple. First, TRANSLATE converts any non-numeric character to an instance of "#": **select translate( 'paul123f321',** **'abcdefghijklmnopqrstuvwxyz',** **rpad('#',26,'#')) as num** **from t1** NUM ----------- ####123#321 Since all non-numeric characters are now represented by "#", simply use REPLACE to remove them, then cast the result to a number. This particular example is extremely simple because the data is alphanumeric. If additional characters can be stored, rather than fishing for those characters, it is easier to approach this problem differently: rather than finding non-numeric characters and then removing them, find all numeric characters and remove anything that is not amongst them. The following example will help clarify this technique: **select replace(** **translate('paul123f321',** **replace(translate( 'paul123f321',** **'0123456789',** **rpad('#',10,'#')),'#',''),** **rpad('#',length('paul123f321'),'#')),'#','') as num** **from t1** NUM ----------- 123321 This solution looks a bit more convoluted than the original but is not so bad once you break it down. Observe the innermost call to TRANSLATE: **select translate( 'paul123f321',** **'0123456789',** **rpad('#',10,'#'))** **from t1** TRANSLATE(' ----------- paul###f### So, the initial approach is different; rather than replacing each non-numeric character with an instance of "#", you replace each numeric character with an instance of "#". The next step removes all instances of "#", thus leaving only non-numeric characters: **select replace(translate( 'paul123f321',** **'0123456789',** **rpad('#',10,'#')),'#','')** **from t1** REPLA ----- paulf The next step is to call TRANSLATE again, this time to replace each of the non-numeric characters (from the query above) with an instance of "#" in the original string: **select translate('paul123f321',** **replace(translate( 'paul123f321',** **'0123456789',** **rpad('#',10,'#')),'#',''),** **rpad('#',length('paul123f321'),'#'))** **from t1** TRANSLATE(' ----------- ####123#321 At this point, stop and examine the outermost call to TRANSLATE. The second parameter to RPAD (or the second parameter to REPEAT for DB2) is the length of the original string. This is convenient to use since no character can occur enough times to be greater than the string it is part of. Now that all non-numeric characters are replaced by instances of "#", the last step is to use REPLACE to remove all instances of "#". Now you are left with a number. ## 7.15. Changing Values in a Running Total ### Problem You want to modify the values in a running total depending on the values in another column. Consider a scenario where you want to display the transaction history of a credit card account along with the current balance after each transaction. The following view, V, will be used in this example: **create view V (id,amt,trx)** **as** **select 1, 100, 'PR' from t1 union all** **select 2, 100, 'PR' from t1 union all** **select 3, 50, 'PY' from t1 union all** **select 4, 100, 'PR' from t1 union all** **select 5, 200, 'PY' from t1 union all** **select 6, 50, 'PY' from t1** **select * from V** ID AMT TR -- ---------- -- 1 100 PR 2 100 PR 3 50 PY 4 100 PR 5 200 PY 6 50 PY The ID column uniquely identifies each transaction. The AMT column represents the amount of money involved in each transaction (either a purchase or a payment). The TRX column defines the type of transaction; a payment is "PY" and a purchase is "PR." If the value for TRX is PY, you want the current value for AMT subtracted from the running total; if the value for TRX is PR, you want the current value for AMT added to the running total. Ultimately you want to return the following result set: TRX_TYPE AMT BALANCE -------- ---------- ---------- PURCHASE 100 100 PURCHASE 100 200 PAYMENT 50 150 PURCHASE 100 250 PAYMENT 200 50 PAYMENT 50 0 ### Solution #### DB2 and Oracle Use the window function SUM OVER to create the running total along with a CASE expression to determine the type of transaction: 1 select case when trx = 'PY' 2 then 'PAYMENT' 3 else 'PURCHASE' 4 end trx_type, 5 amt, 6 sum( 7 case when trx = 'PY' 8 then -amt else amt 9 end 10 ) over (order by id,amt) as balance 11 from V #### MySQL, PostgreSQL, and SQL Server Use a scalar subquery to create the running total along with a CASE expression to determine the type of transaction: 1 select case when v1.trx = 'PY' 2 then 'PAYMENT' 3 else 'PURCHASE' 4 end as trx_type, 5 v1.amt, 6 (select sum( 7 case when v2.trx = 'PY' 8 then -v2.amt else v2.amt 9 end 10 ) 11 from V v2 12 where v2.id <= v1.id) as balance 13 from V v1 ### Discussion The CASE expression determines whether the current AMT is added or deducted from the running total. If the transaction is a payment, the AMT is changed to a negative value, thus reducing the amount of the running total. The result of the CASE expression is seen below: **select case when trx = 'PY'** **then 'PAYMENT'** **else 'PURCHASE'** **end trx_type,** **case when trx = 'PY'** **then -amt else amt** **end as amt** **from V** TRX_TYPE AMT -------- --------- PURCHASE 100 PURCHASE 100 PAYMENT -50 PURCHASE 100 PAYMENT -200 PAYMENT -50 After evaluating the transaction type, the values for AMT are then added to or subtracted from the running total. For an explanation on how the window function, SUM OVER, or the scalar subquery creates the running total see recipe "Calculating a Running Total." ## Chapter 8. Date Arithmetic This chapter introduces techniques for performing simple date arithmetic. Recipes cover common tasks like adding days to dates, finding the number of business days between dates, and finding the difference between dates in days. Being able to successfully manipulate dates with your RDBMS's built-in functions can greatly improve your productivity. For all the recipes in this chapter, I try to take advantage of each RDBMS's built-in functions. In addition, I have chosen to use one date format for all the recipes, "DD-MON-YYYY". I chose to do this because I believe it will benefit those of you who work with one RDBMS and want to learn others. Seeing one standard format will help you focus on the different techniques and functions provided by each RDBMS without having to worry about default date formats. ### Tip This chapter focuses on basic date arithmetic. You'll find more advanced date recipes in the following chapter. The recipes presented in this chapter use simple date data types. If you are using more complex date data types you will need to adjust the solutions accordingly. ## 8.1. Adding and Subtracting Days, Months, and Years ### Problem You need to add or subtract some number of days, months, or years from a date. For example, using the HIREDATE for employee CLARK you want to return six different dates: five days before and after CLARK was hired, five months before and after CLARK was hired, and, finally, five years before and after CLARK was hired. CLARK was hired on "09-JUN-1981", so you want to return the following result set: HD_MINUS_5D HD_PLUS_5D HD_MINUS_5M HD_PLUS_5M HD_MINUS_5Y HD_PLUS_5Y ----------- ----------- ----------- ----------- ----------- ----------- 04-JUN-1981 14-JUN-1981 09-JAN-1981 09-NOV-1981 09-JUN-1976 09-JUN-1986 12-NOV-1981 22-NOV-1981 17-JUN-1981 17-APR-1982 17-NOV-1976 17-NOV-1986 18-JAN-1982 28-JAN-1982 23-AUG-1981 23-JUN-1982 23-JAN-1977 23-JAN-1987 ### Solution #### DB2 Standard addition and subtraction is allowed on date values, but any value that you add to or subtract from a date must be followed by the unit of time it represents: 1 select hiredate -5 day as hd_minus_5D, 2 hiredate +5 day as hd_plus_5D, 3 hiredate -5 month as hd_minus_5M, 4 hiredate +5 month as hd_plus_5M, 5 hiredate -5 year as hd_minus_5Y, 6 hiredate +5 year as hd_plus_5Y 7 from emp 8 where deptno = 10 #### Oracle Use standard addition and subtraction for days, and use the ADD_MONTHS function to add and subtract months and years: 1 select hiredate-5 as hd_minus_5D, 2 hiredate+5 as hd_plus_5D, 3 add_months(hiredate,-5) as hd_minus_5M, 4 add_months(hiredate,5) as hd_plus_5M, 5 add_months(hiredate,-5*12) as hd_minus_5Y, 6 add_months(hiredate,5*12) as hd_plus_5Y 7 from emp 8 where deptno = 10 #### PostgreSQL Use standard addition and subtraction with the INTERVAL keyword specifying the unit of time to add or subtract. Single quotes are required when specifying an INTERVAL value: 1 select hiredate - interval '5 day' as hd_minus_5D, 2 hiredate + interval '5 day' as hd_plus_5D, 3 hiredate - interval '5 month' as hd_minus_5M, 4 hiredate + interval '5 month' as hd_plus_5M, 5 hiredate - interval '5 year' as hd_minus_5Y, 6 hiredate + interval '5 year' as hd_plus_5Y 7 from emp 8 where deptno=10 #### MySQL Use standard addition and subtraction with the INTERVAL keyword specifying the unit of time to add or subtract. Unlike the PostgreSQL solution, you do not place single quotes around the INTERVAL value: 1 select hiredate - interval 5 day as hd_minus_5D, 2 hiredate + interval 5 day as hd_plus_5D, 3 hiredate - interval 5 month as hd_minus_5M, 4 hiredate + interval 5 month as hd_plus_5M, 5 hiredate - interval 5 year as hd_minus_5Y, 6 hiredate + interval 5 year as hd_plus_5Y 7 from emp 8 where deptno=10 Alternatively, you can use the DATE_ADD function, which is shown below: 1 select date_add(hiredate,interval -5 day) as hd_minus_5D, 2 date_add(hiredate,interval 5 day) as hd_plus_5D, 3 date_add(hiredate,interval -5 month) as hd_minus_5M, 4 date_add(hiredate,interval 5 month) as hd_plus_5M, 5 date_add(hiredate,interval -5 year) as hd_minus_5Y, 6 date_add(hiredate,interval 5 year) as hd_plus_5DY 7 from emp 8 where deptno=10 #### SQL Server Use the DATEADD function to add or subtract different units of time to/from a date: 1 select dateadd(day,-5,hiredate) as hd_minus_5D, 2 dateadd(day,5,hiredate) as hd_plus_5D, 3 dateadd(month,-5,hiredate) as hd_minus_5M, 4 dateadd(month,5,hiredate) as hd_plus_5M, 5 dateadd(year,-5,hiredate) as hd_minus_5Y, 6 dateadd(year,5,hiredate) as hd_plus_5Y 7 from emp 8 where deptno = 10 ### Discussion The Oracle solution takes advantage of the fact that integer values represent days when performing date arithmetic. However, that's true only of arithmetic with DATE types. Oracle9 _i_ Database introduced TIMESTAMP types. For those, you should use the INTERVAL solution shown for PostgreSQL. Beware too, of passing TIMESTAMPs to old-style date functions such as ADD_MONTHS. By doing so, you can lose any fractional seconds that such TIMESTAMP values may contain. The INTERVAL keyword and the string literals that go with it represent ISO-standard SQL syntax. The standard requires that interval values be enclosed within single quotes. PostgreSQL (and Oracle9 _i_ Database and later) complies with the standard. MySQL deviates somewhat by omitting support for the quotes. ## 8.2. Determining the Number of Days Between Two Dates ### Problem You want to find the difference between two dates and represent the result in days. For example, you want to find the difference in days between the HIREDATEs of employee ALLEN and employee WARD. ### Solution #### DB2 Use two inline views to find the HIREDATEs for WARD and ALLEN. Then subtract one HIREDATE from the other using the DAYS function: 1 select days(ward_hd) - days(allen_hd) 2 from ( 3 select hiredate as ward_hd 4 from emp 5 where ename = 'WARD' 6 ) x, 7 ( 8 select hiredate as allen_hd 9 from emp 10 where ename = 'ALLEN' 11 ) y #### Oracle and PostgreSQL Use two inline views to find the HIREDATEs for WARD and ALLEN, and then subtract one date from the other: 1 select ward_hd - allen_hd 2 from ( 3 select hiredate as ward_hd 4 from emp 5 where ename = 'WARD' 6 ) x, 7 ( 8 select hiredate as allen_hd 9 from emp 10 where ename = 'ALLEN' 11 ) y #### MySQL and SQL Server Use the function DATEDIFF to find the number of days between two dates. MySQL's version of DATEDIFF requires only two parameters (the two dates you want to find the difference in days between), and the smaller of the two dates should be passed first to avoid negative values (opposite in SQL Server). SQL Server's version of the function allows you to specify what you want the return value to represent (in this example you want to return the difference in days). The solution following uses the SQL Server version: 1 select datediff(day,allen_hd,ward_hd) 2 from ( 3 select hiredate as ward_hd 4 from emp 5 where ename = 'WARD' 6 ) x, 7 ( 8 select hiredate as allen_hd 9 from emp 10 where ename = 'ALLEN' 11 ) y MySQL users can simply remove the first argument of the function and flip-flop the order in which ALLEN_HD and WARD_HD is passed. ### Discussion For all solutions, inline views X and Y return the HIREDATEs for employees WARD and ALLEN respectively. For example: **select ward_hd, allen_hd** **from (** **select hiredate as ward_hd** **from emp** **where ename = 'WARD'** **) y,** **(** **select hiredate as allen_hd** **from emp** **where ename = 'ALLEN'** **) x** WARD_HD ALLEN_HD ----------- ---------- 22-FEB-1981 20-FEB-1981 You'll notice a Cartesian product is created, because there is no join specified between X and Y. In this case, the lack of a join is harmless as the cardinalities for X and Y are both 1, thus the result set will ultimately have one row (obviously, because 1x1=1). To get the difference in days, simply subtract one of the two values returned from the other using methods appropriate for your database. ## 8.3. Determining the Number of Business Days Between Two Dates ### Problem Given two dates, you want to find how many "working" days are between them, including the two dates themselves. For example, if January 10th is a Tuesday and January 11th is a Monday, then the number of working days between these two dates is two, as both days are typical work days. For this recipe, "business days" is defined as any day that is not Saturday or Sunday. ### Solution The solution examples find the number of business days between the HIREDATEs of BLAKE and JONES. To determine the number of business days between two dates, you can use a pivot table to return a row for each day between the two dates (including the start and end dates). Having done that, finding the number of business days is simply counting the dates returned that are not Saturday or Sunday. ### Tip If you want to exclude holidays as well, you can create a HOLIDAYS table. Then include a simple NOT IN predicate to exclude days listed in HOLIDAYS from the solution. #### DB2 Use the pivot table T500 to generate the required number of rows (representing days) between the two dates. Then count each day that is not a weekend. Use the DAYNAME function to return the weekday name of each date. For example: 1 select sum(case when dayname(jones_hd+t500.id day -1 day) 2 in ( 'Saturday','Sunday' ) 3 then 0 else 1 4 end) as days 5 from ( 6 select max(case when ename = 'BLAKE' 7 then hiredate 8 end) as blake_hd, 9 max(case when ename = 'JONES' 10 then hiredate 11 end) as jones_hd 12 from emp 13 where ename in ( 'BLAKE','JONES' ) 14 ) x, 15 t500 16 where t500.id <= blake_hd-jones_hd+1 #### MySQL Use the pivot table T500 to generate the required number of rows (days) between the two dates. Then count each day that is not a weekend. Use the DATE_ADD function to add days to each date. Use the DATE_FORMAT function to obtain the weekday name of each date: 1 select sum(case when date_format( 2 date_add(jones_hd, 3 interval t500.id-1 DAY),'%a') 4 in ( 'Sat','Sun' ) 5 then 0 else 1 6 end) as days 7 from ( 8 select max(case when ename = 'BLAKE' 9 then hiredate 10 end) as blake_hd, 11 max(case when ename = 'JONES' 12 then hiredate 13 end) as jones_hd 14 from emp 15 where ename in ( 'BLAKE','JONES' ) 16 ) x, 17 t500 18 where t500.id <= datediff(blake_hd,jones_hd)+1 #### Oracle Use the pivot table T500 to generate the required number of rows (days) between the two dates, and then count each day that is not a weekend. Use the TO_CHAR function to obtain the weekday name of each date: 1 select sum(case when to_char(jones_hd+t500.id-1,'DY') 2 in ( 'SAT','SUN' ) 3 then 0 else 1 4 end) as days 5 from ( 6 select max(case when ename = 'BLAKE' 7 then hiredate 8 end) as blake_hd, 9 max(case when ename = 'JONES' 10 then hiredate 11 end) as jones_hd 12 from emp 13 where ename in ( 'BLAKE','JONES' ) 14 ) x, 15 t500 16 where t500.id <= blake_hd-jones_hd+1 #### PostgreSQL Use the pivot table T500 to generate the required number of rows (days) between the two dates. Then count each day that is not a weekend. Use the TO_CHAR function to obtain the weekday name of each date: 1 select sum(case when trim(to_char(jones_hd+t500.id-1,'DAY')) 2 in ( 'SATURDAY','SUNDAY' ) 3 then 0 else 1 4 end) as days 5 from ( 6 select max(case when ename = 'BLAKE' 7 then hiredate 8 end) as blake_hd, 9 max(case when ename = 'JONES' 10 then hiredate 11 end) as jones_hd 12 from emp 13 where ename in ( 'BLAKE','JONES' ) 14 ) x, 15 t500 16 where t500.id <= blake_hd-jones_hd+1 #### SQL Server Use the pivot table T500 to generate the required number of rows (days) between the two dates, and then count each day that is not a weekend. Use the DATENAME function to obtain the weekday name of each date: 1 select sum(case when datename(dw,jones_hd+t500.id-1) 2 in ( 'SATURDAY','SUNDAY' ) 3 then 0 else 1 4 end) as days 5 from ( 6 selectmax(case when ename = 'BLAKE' 7 then hiredate 8 end) as blake_hd, 9 max(case when ename = 'JONES' 10 then hiredate 11 end) as jones_hd 12 from emp 13 where ename in ( 'BLAKE','JONES' ) 14 ) x, 15 t500 16 where t500.id <= datediff(day,jones_hd-blake_hd)+1 ### Discussion While each RDBMS requires the use of different built-in functions to determine the name of a day, the overall solution approach is the same for each. The solution can be broken into two steps: 1. Return the days between the start date and end date (inclusive). 2. Count how many days (i.e., rows) there are, excluding weekends. Inline view X performs step 1. If you examine inline view X, you'll notice the use of the aggregate function MAX, which the recipe uses to remove NULLs. If the use of MAX is unclear, the following output might help you understand. The output shows the results from inline view X without MAX: **select case when ename = 'BLAKE'** **then hiredate** **end as blake_hd,** **case when ename = 'JONES'** **then hiredate** **end as jones_hd** **from emp** **where ename in ( 'BLAKE','JONES' )** BLAKE_HD JONES_HD ----------- ----------- 02-APR-1981 01-MAY-1981 Without MAX, two rows are returned. By using MAX you return only one row instead of two, and the NULLs are eliminated: **select max(case when ename = 'BLAKE'** **then hiredate** **end) as blake_hd,** **max(case when ename = 'JONES'** **then hiredate** **end) as jones_hd** **from emp** **where ename in ( 'BLAKE','JONES' )** BLAKE_HD JONES_HD ----------- ----------- 01-MAY-1981 02-APR-1981 The number of days (inclusive) between the two dates here is 30. Now that the two dates are in one row, the next step is to generate one row for each of those 30 days. To return the 30 days (rows), use table T500. Since each value for ID in table T500 is simply 1 greater than the one before it, add each row returned by T500 to the earlier of the two dates (JONES_HD) to generate consecutive days starting from JONES_HD up to and including BLAKE_HD. The result of this addition is shown below (using Oracle syntax): **select x.*, t500.*, jones_hd+t500.id-1** **from (** **select max(case when ename = 'BLAKE'** **then hiredate** **end) as blake_hd,** **max(case when ename = 'JONES'** **then hiredate** **end) as jones_hd** **from emp** **where ename in ( 'BLAKE','JONES' )** **) x,** **t500** **where t500.id<= blake_hd-jones_hd+1** BLAKE_HD JONES_HD ID JONES_HD+T5 ----------- ----------- ---------- ----------- 01-MAY-1981 02-APR-1981 1 02-APR-1981 01-MAY-1981 02-APR-1981 2 03-APR-1981 01-MAY-1981 02-APR-1981 3 04-APR-1981 01-MAY-1981 02-APR-1981 4 05-APR-1981 01-MAY-1981 02-APR-1981 5 06-APR-1981 01-MAY-1981 02-APR-1981 6 07-APR-1981 01-MAY-1981 02-APR-1981 7 08-APR-1981 01-MAY-1981 02-APR-1981 8 09-APR-1981 01-MAY-1981 02-APR-1981 9 10-APR-1981 01-MAY-1981 02-APR-1981 10 11-APR-1981 01-MAY-1981 02-APR-1981 11 12-APR-1981 01-MAY-1981 02-APR-1981 12 13-APR-1981 01-MAY-1981 02-APR-1981 13 14-APR-1981 01-MAY-1981 02-APR-1981 14 15-APR-1981 01-MAY-1981 02-APR-1981 15 16-APR-1981 01-MAY-1981 02-APR-1981 16 17-APR-1981 01-MAY-1981 02-APR-1981 17 18-APR-1981 01-MAY-1981 02-APR-1981 18 19-APR-1981 01-MAY-1981 02-APR-1981 19 20-APR-1981 01-MAY-1981 02-APR-1981 20 21-APR-1981 01-MAY-1981 02-APR-1981 21 22-APR-1981 01-MAY-1981 02-APR-1981 22 23-APR-1981 01-MAY-1981 02-APR-1981 23 24-APR-1981 01-MAY-1981 02-APR-1981 24 25-APR-1981 01-MAY-1981 02-APR-1981 25 26-APR-1981 01-MAY-1981 02-APR-1981 26 27-APR-1981 01-MAY-1981 02-APR-1981 27 28-APR-1981 01-MAY-1981 02-APR-1981 28 29-APR-1981 01-MAY-1981 02-APR-1981 29 30-APR-1981 01-MAY-1981 02-APR-1981 30 01-MAY-1981 If you examine the WHERE clause, you'll notice that you add 1 to the difference between BLAKE_HD and JONES_HD to generate the required 30 rows (otherwise, you would get 29 rows). You'll also notice that you subtract 1 from T500.ID in the SELECT list of the outer query, since the values for ID start at 1 and adding 1 to JONES_HD would cause JONES_HD to be excluded from the final count. Once you generate the number of rows required for the result set, use a CASE expression to "flag" whether or not each of the days returned are weekdays or weekends (return a 1 for a weekday and a 0 for a weekend). The final step is to use the aggregate function SUM to tally up the number of 1s to get the final answer. ## 8.4. Determining the Number of Months or Years Between Two Dates ### Problem You want to find the difference between two dates in terms of either months or years. For example, you want to find the number of months between the first and last employees hired, and you also wish to express that value as some number of years. ### Solution Since there are always 12 months in a year, you can find the number of months between two dates, and then divide by 12 to get the number of years. After getting comfortable with the solution, you'll want to round the results up or down depending on what you want for the year. For example, the first HIREDATE in table EMP is "17-DEC-1980" and the last is "12-JAN-1983". If you do the math on the years (1983 minus 1980) you get three years, yet the difference in months is approximately 25 (a little over two years). You should tweak the solution as you see fit. The solutions below will return 25 months and ~2 years. #### DB2 and MySQL Use the functions YEAR and MONTH to return the four-digit year and the two-digit month for the dates supplied: 1 select mnth, mnth/12 2 from ( 3 select (year(max_hd) - year(min_hd))*12 + 4 (month(max_hd) - month(min_hd)) as mnth 5 from ( 6 select min(hiredate) as min_hd, max(hiredate) as max_hd 7 from emp 8 ) x 9 ) y #### Oracle Use the function MONTHS_BETWEEN to find the difference between two dates in months (to get years, simply divide by 12): 1 select months_between(max_hd,min_hd), 2 months_between(max_hd,min_hd)/12 3 from ( 4 select min(hiredate) min_hd, max(hiredate) max_hd 5 from emp 6 ) x #### PostgreSQL Use the function EXTRACT to return the four-digit year and two-digit month for the dates supplied: 1 select mnth, mnth/12 2 from ( 3 select ( extract(year from max_hd) 4 extract(year from min_hd) ) * 12 5 + 6 ( extract(month from max_hd) 7 extract(month from min_hd) ) as mnth 8 from ( 9 select min(hiredate) as min_hd, max(hiredate) as max_hd 10 from emp 11 ) x 12 ) y #### SQL Server Use the function DATEDIFF to find the difference between two dates in months (to get years, simply divide by 12): 1 select datediff(month,min_hd,max_hd), 2 datediff(month,min_hd,max_hd)/12 3 from ( 4 select min(hiredate) min_hd, max(hiredate) max_hd 5 from emp 6 ) x ### Discussion #### DB2, MySQL, and PostgreSQL Once you extract the year and month for MIN_HD and MAX_HD in the PostgreSQL solution, the method for finding the months and years between MIN_HD and MAX_HD is the same for all three RDBMs. This discussion will cover all three solutions. Inline view X returns the earliest and latest HIREDATEs in table EMP and can be seen below: **select min(hiredate) as min_hd,** **max(hiredate) as max_hd** **from emp** MIN_HD MAX_HD ----------- ----------- 17-DEC-1980 12-JAN-1983 To find the months between MAX_HD and MIN_HD, multiply the difference in years between MIN_HD and MAX_HD by 12, then add the difference in months between MAX_HD and MIN_HD. If you are having trouble seeing how this works, return the date component for each date. The numeric values for the years and months are show below: **select year(max_hd) as max_yr, year(min_hd) as min_yr,** **month(max_hd) as max_mon, month(min_hd) as min_mon** **from (** **select min(hiredate) as min_hd, max(hiredate) as max_hd** **from emp** **) x** MAX_YR MIN_YR MAX_MON MIN_MON ------ ---------- ---------- ---------- 1983 1980 1 12 Looking at the results above, finding the months between MAX_HD and MIN_HD is simply (1983–1980)*12 + (1–12). To find the number of years between MIN_HD and MAX_HD, divide the number of months by 12. Again, depending on the results you are looking for you will want to round the values. #### Oracle and SQL Server Inline view X returns the earliest and latest HIREDATEs in table EMP and can be seen below: **select min(hiredate) as min_hd, max(hiredate) as max_hd** **from emp** MIN_HD MAX_HD ----------- ----------- 17-DEC-1980 12-JAN-1983 The functions supplied by Oracle and SQL Server (MONTHS_BETWEEN and DATEDIFF, respectively) will return the number of months between two given dates. To find the year, divide the number of months by 12. ## 8.5. Determining the Number of Seconds, Minutes, or Hours Between Two Dates ### Problem You want to return the difference in seconds between two dates. For example, you want to return the difference between the HIREDATEs of ALLEN and WARD in seconds, minutes, and hours. ### Solution If you can find the number of days between two dates, you can find seconds, minutes, and hours as they are the units of time that make up a day. #### DB2 Use the function DAYS to find the difference between ALLEN_HD and WARD_HD in days. Then multiply to find each unit of time: 1 select dy*24 hr, dy*24*60 min, dy*24*60*60 sec 2 from ( 3 select ( days(max(case when ename = 'WARD' 4 then hiredate 5 end)) - 6 days(max(case when ename = 'ALLEN' 7 then hiredate 8 end)) 9 ) as dy 10 from emp 11 ) x #### MySQL and SQL Server Use the DATEDIFF function to return the number of days between ALLEN_HD and WARD_HD. Then multiply to find each unit of time: 1 select datediff(day,allen_hd,ward_hd)*24 hr, 2 datediff(day,allen_hd,ward_hd)*24*60 min, 3 datediff(day,allen_hd,ward_hd)*24*60*60 sec 4 from ( 5 select max(case when ename = 'WARD' 6 then hiredate 7 end) as ward_hd, 8 max(case when ename = 'ALLEN' 9 then hiredate 10 end) as allen_hd 11 from emp 12 ) x #### Oracle and PostgreSQL Use subtraction to return the number of days between ALLEN_HD and WARD_ HD. Then multiply to find each unit of time: 1 select dy*24 as hr, dy*24*60 as min, dy*24*60*60 as sec 2 from ( 3 select (max(case when ename = 'WARD' 4 then hiredate 5 end) - 6 max(case when ename = 'ALLEN' 7 then hiredate 8 end)) as dy 9 from emp 10 ) x ### Discussion Inline view X for all solutions returns the HIREDATEs for WARD and ALLEN, as can be seen below: **select max(case when ename = 'WARD'** **then hiredate** **end) as ward_hd,** **max(case when ename = 'ALLEN'** **then hiredate** **end) as allen_hd** **from emp** WARD_HD ALLEN_HD ----------- ----------- 22-FEB-1981 20-FEB-1981 Multiply the number of days between WARD_HD and ALLEN_HD by 24 (hours in a day), 1440 (minutes in a day), and 86400 (seconds in a day). ## 8.6. Counting the Occurrences of Weekdays in a Year ### Problem You want to count the number of times each weekday occurs in one year. ### Solution To find the number of occurrences of each weekday in a year, you must: 1. Generate all possible dates in the year. 2. Format the dates such that they resolve to the name of their respective weekdays. 3. Count the occurrence of each weekday name. #### DB2 Use recursive WITH to avoid the need to SELECT against a table with at least 366 rows. Use the function DAYNAME to obtain the weekday name for each date, and then count the occurrence of each: 1 with x (start_date,end_date) 2 as ( 3 select start_date, 4 start_date + 1 year end_date 5 from ( 6 select (current_date 7 dayofyear(current_date) day) 8 +1 day as start_date 9 from t1 10 ) tmp 11 union all 12 select start_date + 1 day, end_date 13 from x 14 where start_date + 1 day < end_date 15 ) 16 select dayname(start_date),count(*) 17 from x 18 group by dayname(start_date) #### MySQL Select against table T500 to generate enough rows to return every day in the year. Use the DATE_FORMAT function to obtain the weekday name of each date, and then count the occurrence of each name: 1 select date_format( 2 date_add( 3 cast( 4 concat(year(current_date),'-01-01') 5 as date), 6 interval t500.id-1 day), 7 '%W') day, 8 count(*) 9 from t500 10 where t500.id <= datediff( 11 cast( 12 concat(year(current_date)+1,'-01-01') 13 as date), 14 cast( 15 concat(year(current_date),'-01-01') 16 as date)) 17 group by date_format( 18 date_add( 19 cast( 20 concat(year(current_date),'-01-01') 21 as date), 22 interval t500.id-1 day), 23 '%W') #### Oracle If you are on Oracle9 _i_ Database or later, you can use the recursive CONNECT BY to return each day in a year. If you are on Oracle8 _i_ Database or earlier, select against table T500 to generate enough rows to return every day in a year. In either case, use the TO_CHAR function to obtain the weekday name of each date, and then count the occurrence of each name. First, the CONNECT BY solution: 1 with x as ( 2 select level lvl 3 from dual 4 connect by level <= ( 5 add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y') 6 ) 7 ) 8 select to_char(trunc(sysdate,'y')+lvl-1,'DAY'), count(*) 9 from x 10 group by to_char(trunc(sysdate,'y')+lvl-1,'DAY') and next, the solution for older releases of Oracle: 1 select to_char(trunc(sysdate,'y')+rownum-1,'DAY'), 2 count(*) 3 from t500 4 where rownum <= (add_months(trunc(sysdate,'y'),12) 5 - trunc(sysdate,'y')) 6 group by to_char(trunc(sysdate,'y')+rownum-1,'DAY') #### PostgreSQL Use the built-in function GENERATE_SERIES to generate one rows for every day in the year. Then use the TO_CHAR function to obtain the weekday name of each date. Finally, count the occurrence of each weekday name. For example: 1 select to_char( 2 cast( 3 date_trunc('year',current_date) 4 as date) + gs.id-1,'DAY'), 5 count(*) 6 from generate_series(1,366) gs(id) 7 where gs.id <= (cast 8 ( date_trunc('year',current_date) + 9 interval '12 month' as date) - 10 cast(date_trunc('year',current_date) 11 as date)) 12 group by to_char( 13 cast( 14 date_trunc('year',current_date) 15 as date) + gs.id-1,'DAY') #### SQL Server Use the recursive WITH to avoid the need to SELECT against a table with at least 366 rows. If you are on a version of SQL Server that does not support the WITH clause, see the alternative Oracle solution as a guideline for using a pivot table. Use the DATENAME function to obtain the weekday name of each date, and then count the occurrence of each name. For example: 1 with x (start_date,end_date) 2 as ( 3 select start_date, 4 dateadd(year,1,start_date) end_date 5 from ( 6 select cast( 7 cast(year(getdate()) as varchar) + '-01-01' 8 as datetime) start_date 9 from t1 10 ) tmp 11 union all 12 select dateadd(day,1,start_date), end_date 13 from x 14 where dateadd(day,1,start_date) < end_date 15 ) 16 select datename(dw,start_date),count(*) 17 from x 18 group by datename(dw,start_date) 19 OPTION (MAXRECURSION 366) ### Discussion #### DB2 Inline view TMP, in the recursive WITH view X, returns the first day of the current year and is shown below: **select (current_date** **dayofyear(current_date) day)** **+1 day as start_date** **from t1** START_DATE ------------- 01-JAN-2005 The next step is to add one year to START_DATE, so that you have the beginning and end dates. You need to know both because you want to generate every day in a year. START_DATE and END_DATE are shown below: **select start_date,** **start_date + 1 year end_date** **from (** **select (current_date** **dayofyear(current_date) day)** **+1 day as start_date** **from t1** ******) tmp** START_DATE END_DATE ----------- ------------ 01-JAN-2005 01-JAN-2006 The next step is to recursively increment START_DATE by one day, stopping before it equals END_DATE. A portion of the rows returned by the recursive view X is shown below: **with x (start_date,end_date)** **as (** **select start_date,** **start_date + 1 year end_date** **from (** **select (current_date -** **dayofyear(current_date) day)** **+1 day as start_date** **from t1** **) tmp** **union all** **select start_date + 1 day, end_date** **from x** **where start_date + 1 day< end_date** **)** **select * from x** START_DATE END_DATE ----------- ----------- 01-JAN-2005 01-JAN-2006 02-JAN-2005 01-JAN-2006 03-JAN-2005 01-JAN-2006 ... 29-JAN-2005 01-JAN-2006 30-JAN-2005 01-JAN-2006 31-JAN-2005 01-JAN-2006 ... 01-DEC-2005 01-JAN-2006 02-DEC-2005 01-JAN-2006 03-DEC-2005 01-JAN-2006 ... 29-DEC-2005 01-JAN-2006 30-DEC-2005 01-JAN-2006 31-DEC-2005 01-JAN-2006 The final step is to use the function DAYNAME on the rows returned by the recursive view X, and count how many times each weekday occurs. The final result is shown below: **with x (start_date,end_date)** **as (** **select start_date,** **start_date + 1 year end_date** **from (** **select (** ******current_date -** **dayofyear(current_date) day)** **+1 day as start_date** **from t1** **) tmp** **union all** **select start_date + 1 day, end_date** **from x** **where start_date + 1 day< end_date** **)** **select dayname(start_date),count(*)** **from x** **group by dayname(start_date)** START_DATE COUNT(*) ---------- ---------- FRIDAY 52 MONDAY 52 SATURDAY 53 SUNDAY 52 THURSDAY 52 TUESDAY 52 WEDNESDAY 52 #### MySQL This solution selects against table T500 to generate one row for every day in the year. The command on line 4 returns the first day of the current year. It does this by returning the year of the date returned by the function CURRENT_DATE, and then appending a month and day (following MySQL's default date format). The result is shown below: **select concat(year(current_date),'-01-01')** **from t1** START_DATE ----------- 01-JAN-2005 Now that you have the first day in the current year, use the DATEADD function to add each value from T500.IDto generate each day in the year. Use the function DATE_FORMAT to return the weekday for each date. To generate the required number of rows from table T500, find the difference in days between the first day of the current year and the first day of the next year, and return that many rows (will be either 365 or 366). A portion of the results is shown below: **select date_format(** **date_add(** **cast(** **concat(year(current_date),'-01-01')** **as date),** ******interval t500.id-1 day),** **'%W') day** **from t500** **where t500.id<= datediff(** **cast(** **concat(year(current_date)+1,'-01-01')** **as date),** **cast(** **concat(year(current_date),'-01-01')** **as date))** DAY ----------- 01-JAN-2005 02-JAN-2005 03-JAN-2005 ... 29-JAN-2005 30-JAN-2005 31-JAN-2005 ... 01-DEC-2005 02-DEC-2005 03-DEC-2005 ... 29-DEC-2005 30-DEC-2005 31-DEC-2005 Now that you can return every day in the current year, count the occurrences of each weekday returned by the function DAYNAME. The final results are shown below: **select date_format(** **date_add(** **cast(** **concat(year(current_date),'-01-01')** **as date),** **interval t500.id-1 day),** **'%W') day,** **count(*)** **from t500** **where t500.id<= datediff(** **cast(** **concat(year(current_date)+1,'-01-01')** **as date),** **cast(** **concat(year(current_date),'-01-01')** **as date))** **group by date_format(** **date_add(** **cast(** **concat(year(current_date),'-01-01')** **as date),** ******interval t500.id-1 day),** **'%W')** DAY COUNT(*) --------- ---------- FRIDAY 52 MONDAY 52 SATURDAY 53 SUNDAY 52 THURSDAY 52 TUESDAY 52 WEDNESDAY 52 #### Oracle The solutions provided either select against table T500 (a pivot table), or use the recursive CONNECT BY and WITH, to generate a row for every day in the current year. The call to the function TRUNC truncates the current date to the first day of the current year. If you are using the CONNECT BY/WITH solution, you can use the pseudo-column LEVEL to generate sequential numbers beginning at 1. To generate the required number of rows needed for this solution, filter ROWNUM or LEVEL on the difference in days between the first day of the current year and the first day of the next year (will be 365 or 366 days). The next step is to increment each day by adding ROWNUM or LEVEL to the first day of the current year. Partial results are shown below: **/* Oracle 9i and later */** **with x as (** **select level lvl** **from dual** **connect by level<= (** **add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y')** **)** **)** **select trunc(sysdate,'y')+lvl-1** **from x** If you are using the pivot-table solution, you can use any table or view with at least 366 rows in it. And since Oracle has ROWNUM, there's no need for a table with incrementing values starting from 1. Consider the following example, which uses pivot table T500 to return every day in the current year: **/* Oracle 8i and earlier */** **select trunc(sysdate,'y')+rownum-1 start_date** **from t500** **where rownum<= (add_months(trunc(sysdate,'y'),12)** **- trunc(sysdate,'y'))** START_DATE ----------- 01-JAN-2005 02-JAN-2005 03-JAN-2005 ... 29-JAN-2005 30-JAN-2005 31-JAN-2005 ... 01-DEC-2005 02-DEC-2005 03-DEC-2005 ... 29-DEC-2005 30-DEC-2005 31-DEC-2005 Regardless of which approach you take, you eventually must use the function TO_ CHAR to return the weekday name for each date, and then count the occurrence of each name. The final results are shown below: **/* Oracle 9i and later */** **with x as (** **select level lvl** **from dual** **connect by level<= (** **add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y')** **)** **)** **select to_char(trunc(sysdate,'y')+lvl-1,'DAY'), count(*)** **from x** **group by to_char(trunc(sysdate,'y')+lvl-1,'DAY')** **/* Oracle 8i and earlier */** **select to_char(trunc(sysdate,'y')+rownum-1,'DAY') start_date,** **count(*)** **from t500** **where rownum<= (add_months(trunc(sysdate,'y'),12)** **- trunc(sysdate,'y'))** **group by to_char(trunc(sysdate,'y')+rownum-1,'DAY')** START_DATE COUNT(*) ---------- ---------- FRIDAY 52 MONDAY 52 SATURDAY 53 SUNDAY 52 THURSDAY 52 TUESDAY 52 WEDNESDAY 52 #### PostgreSQL The first step is to use the DATE_TRUNC function to return the year of the current date (shown below, selecting against T1 so only one row is returned): **select cast(** **date_trunc('year',current_date)** **as date) as start_date** **from t1** START_DATE ---------- 01-JAN-2005 The next step is to select against a row source (any table expression, really) with at least 366 rows. The solution uses the function GENERATE_SERIES as the row source. You can, of course, use table T500 instead. Then add one day to the first day of the current year until you return every day in the year (shown below): **select cast( date_trunc('year',current_date)** **as date) + gs.id-1 as start_date** **from generate_series (1,366) gs(id)** **where gs.id<= (cast** **( date_trunc('year',current_date) +** **interval '12 month' as date) -** **cast(date_trunc('year',current_date)** **as date))** START_DATE ----------- 01-JAN-2005 02-JAN-2005 03-JAN-2005 ... 29-JAN-2005 30-JAN-2005 31-JAN-2005 ... 01-DEC-2005 02-DEC-2005 03-DEC-2005 ... 29-DEC-2005 30-DEC-2005 31-DEC-2005 The final step is to use the function TO_CHAR to return the weekday name for each date, and then count the occurrence of each name. The final results are shown below: **select to_char(** **cast(** **date_trunc('year',current_date)** **as date) + gs.id-1,'DAY') as start_dates,** **count(*)** **from generate_series(1,366) gs(id)** **where gs.id<= (cast** **( date_trunc('year',current_date) +** ******interval '12 month' as date) -** **cast(date_trunc('year',current_date)** **as date))** **group by to_char(** **cast(** **date_trunc('year',current_date)** **as date) + gs.id-1,'DAY')** START_DATE COUNT(*) ---------- ---------- FRIDAY 52 MONDAY 52 SATURDAY 53 SUNDAY 52 THURSDAY 52 TUESDAY 52 WEDNESDAY 52 #### SQL Server Inline view TMP, in the recursive WITH view X, returns the first day of the current year and is shown below: **select cast(** **cast(year(getdate()) as varchar) + '-01-01'** **as datetime) start_date** **from t1** START_DATE ----------- 01-JAN-2005 Once you return the first day of the current year, add one year to START_DATE so that you have the beginning and end dates. You need to know both because you want to generate every day in a year. START_DATE and END_DATE are shown below: **select start_date,** **dateadd(year,1,start_date) end_date** **from (** **select cast(** **cast(year(getdate()) as varchar) + '-01-01'** **as datetime) start_date** **from t1** **) tmp** START_DATE END_DATE ----------- ----------- 01-JAN-2005 01-JAN-2006 Next, recursively increment START_DATE by one day and stop before it equals END_DATE. A portion of the rows returned by the recursive view X is shown below: **with x (start_date,end_date)** **as (** **select start_date,** **dateadd(year,1,start_date) end_date** **from (** **select cast(** **cast(year(getdate()) as varchar) + '-01-01'** **as datetime) start_date** **from t1** **) tmp** **union all** **select dateadd(day,1,start_date), end_date** **from x** **where dateadd(day,1,start_date)< end_date** **)** **select * from x** **OPTION (MAXRECURSION 366)** START_DATE END_DATE ----------- ----------- 01-JAN-2005 01-JAN-2006 02-JAN-2005 01-JAN-2006 03-JAN-2005 01-JAN-2006 ... 29-JAN-2005 01-JAN-2006 30-JAN-2005 01-JAN-2006 31-JAN-2005 01-JAN-2006 ... 01-DEC-2005 01-JAN-2006 02-DEC-2005 01-JAN-2006 03-DEC-2005 01-JAN-2006 ... 29-DEC-2005 01-JAN-2006 30-DEC-2005 01-JAN-2006 31-DEC-2005 01-JAN-2006 The final step is to use the function DATENAME on the rows returned by the recursive view X and count how many times each weekday occurs. The final result is shown below: **with x(start_date,end_date)** **as (** **select start_date,** **dateadd(year,1,start_date) end_date** **from (** **select cast(** **cast(year(getdate()) as varchar) + '-01-01'** **as datetime) start_date** **from t1** **) tmp** **union all** **select dateadd(day,1,start_date), end_date** **from x** **where dateadd(day,1,start_date)< end_date** **)** **select datename(dw,start_date), count(*)** **from x** **group by datename(dw,start_date)** **OPTION (MAXRECURSION 366)** **** START_DATE COUNT(*) --------- ---------- FRIDAY 52 MONDAY 52 SATURDAY 53 SUNDAY 52 THURSDAY 52 TUESDAY 52 WEDNESDAY 52 ## 8.7. Determining the Date Difference Between the Current Record and the Next Record ### Problem You want to determine the difference in days between two dates (specifically dates stored in two different rows). For example, for every employee in DEPTNO 10, you want to determine the number of days between the day they were hired and the day the next employee (can be in another department) was hired. ### Solution The trick to this problem's solution is to find the earliest HIREDATE after the current employee was hired. After that, simply use the technique from "Determining the Number of Days between Two Dates" to find the difference in days. #### DB2 Use a scalar subquery to find the next HIREDATE relative to the current HIREDATE. Then use the DAYS function to find the difference in days: 1 select x.*, 2 days(x.next_hd) - days(x.hiredate) diff 3 from ( 4 select e.deptno, e.ename, e.hiredate, 5 (select min(d.hiredate) from emp d 6 where d.hiredate > e.hiredate) next_hd 7 from emp e 8 where e.deptno = 10 9 ) x #### MySQL and SQL Server Use a scalar subquery to find the next HIREDATE relative to the current HIREDATE. Then use the DATEDIFF function to find the difference in days. The SQL Server version of DATEDIFF is used below: 1 select x.*, 2 datediff(day,x.hiredate,x.next_hd) diff 3 from ( 4 select e.deptno, e.ename, e.hiredate, 5 (select min(d.hiredate) from emp d 6 where d.hiredate > e.hiredate) next_hd 7 from emp e 8 where e.deptno = 10 9 ) x MySQL users can exclude the first argument ("day") and switch the order of the two remaining arguments: 2 datediff(x.next_hd, x.hiredate) diff #### Oracle If you're on Oracle8 _i_ Database or later, use the window function LEAD OVER to access the next HIREDATE relative to the current row, thus facilitating subtraction: 1 select ename, hiredate, next_hd, 2 next_hd - hiredate diff 3 from ( 4 select deptno, ename, hiredate, 5 lead(hiredate)over(order by hiredate) next_hd 6 from emp 7 ) 8 where deptno=10 If you are on Oracle8 Database or earlier, you can use the PostgreSQL solution as an alternative. #### PostgreSQL Use a scalar subquery to find the next HIREDATE relative to the current HIREDATE. Then use simple subtraction to find the difference in days: 1 select x.*, 2 x.next_hd - x.hiredate as diff 3 from ( 4 select e.deptno, e.ename, e.hiredate, 5 (select min(d.hiredate) from emp d 6 where d.hiredate > e.hiredate) as next_hd 7 from emp e 8 where e.deptno = 10 9 ) x ### Discussion #### DB2, MySQL, PostgreSQL, and SQL Server Despite the differences in syntax, the approach is the same for all these solutions: use a scalar subquery to find the next HIREDATE relative to the current HIREDATE, and then find the difference in days between the two using the technique described in "Determining the Number of Days Between Two Dates," found earlier in this chapter. #### Oracle The window function LEAD OVER is extremely useful here as it allows you to access "future" rows ("future" determined by the ORDER BY clause, relative to the current row). The ability to access rows around your current row without additional joins provides for more readable and efficient code. When working with window functions, keep in mind that they are evaluated after the WHERE clause, hence the need for an inline view in the solution. If you were to move the filter on DEPTNO into the inline view, the results would change (only the HIREDATEs from DEPTNO 10 would be considered). One important note to mention about Oracle's LEAD and LAG functions is their behavior in the presence of duplicates. In the preface I mention that these recipes are not coded "defensively" because there are too many conditions that one can't possibly foresee that can break code. Or, even if one can foresee every problem, sometimes the resulting SQL becomes unreadable. So in most cases, the goal of a solution is to introduce a technique: one that you can use in your production system, but that must be tested and many times tweaked to work for your particular data. In this case, though, there is a situation that I will discuss simply because the workaround may not be all that obvious, particularly for those coming from non-Oracle systems. In this example there are no duplicate HIREDATEs in table EMP, but it is certainly possible (and probably likely) that there are duplicate date values in your tables. Consider the employees in DEPTNO 10 and their HIREDATEs: **select ename, hiredate** **from emp** **where deptno=10** **order by 2** ENAME HIREDATE ------ ----------- CLARK 09-JUN-1981 KING 17-NOV-1981 MILLER 23-JAN-1982 For the sake of this example, let's insert four duplicates such that there are five employees (including KING) hired on November 17: **insert into emp (empno,ename,deptno,hiredate)** **values (1,'ant',10,to_date('17-NOV-1981'))** **insert into emp (empno,ename,deptno,hiredate)** **values (2,'joe',10,to_date('17-NOV-1981'))** **insert into emp (empno,ename,deptno,hiredate)** **values (3,'jim',10,to_date('17-NOV-1981'))** **insert into emp (empno,ename,deptno,hiredate)** **values (4,'choi',10,to_date('17-NOV-1981'))** **select ename, hiredate** **from emp** **where deptno=10** **order by 2** ENAME HIREDATE ------ ----------- CLARK 09-JUN-1981 ant 17-NOV-1981 joe 17-NOV-1981 KING 17-NOV-1981 jim 17-NOV-1981 choi 17-NOV-1981 MILLER 23-JAN-1982 Now there are multiple employees in DEPTNO 10 hired on the same day. If you try to use the proposed solution (moving the filter into the inline view so you only are concerned with employees in DEPTNO 10 and their HIREDATEs) on this result set you get the following output: **select ename, hiredate, next_hd,** **next_hd - hiredate diff** **from (** **select deptno, ename, hiredate,** **lead(hiredate)over(order by hiredate) next_hd** **from emp** **where deptno=10** **)** ENAME HIREDATE NEXT_HD DIFF ------ ----------- ----------- ---------- CLARK 09-JUN-1981 17-NOV-1981 161 ant 17-NOV-1981 17-NOV-1981 0 joe 17-NOV-1981 17-NOV-1981 0 KING 17-NOV-1981 17-NOV-1981 0 jim 17-NOV-1981 17-NOV-1981 0 choi 17-NOV-1981 23-JAN-1982 67 MILLER 23-JAN-1982 (null) (null) Looking at the values of DIFF for four of the five employees hired on the same day, you can see that the value is zero. This is not correct. All employees hired on the same day should have their dates evaluated against the HIREDATE of the next date on which an employee was hired, i.e., all employees hired on November 17 should be evaluated against MILLER's HIREDATE. The problem here is that the LEAD function orders the rows by HIREDATE but does not skip duplicates. So, for example, when employee ANT's HIREDATE is evaluated against employee JOE's HIREDATE, the difference is zero, hence a DIFF value of zero for ANT. Fortunately, Oracle has provided an easy workaround for situations like this one. When invoking the LEAD function, you can pass an argument to LEAD to specify exactly where the future row is (i.e., is it the next row, 10 rows later, etc.). So, looking at employee ANT, instead of looking ahead one row you need to look ahead five rows (you want to jump over all the other duplicates), because that's where MILLER is. If you look at employee JOE, he is four rows from MILLER, JIM is three rows from MILLER, KING is two rows from MILLER and, pretty boy CHOI is one row from MILLER. To get the correct answer, simply pass the distance from each employee to MILLER as an argument to LEAD. The solution is shown below: **select ename, hiredate, next_hd,** **next_hd - hiredate diff** **from (** **select deptno, ename, hiredate,** **lead(hiredate,cnt-rn+1)over(order by hiredate) next_hd** **from (** **select deptno,ename,hiredate,** **count(*)over(partition by hiredate) cnt,** **row_number()over(partition by hiredate order by empno) rn** **from emp** **where deptno=10** ) ) ENAME HIREDATE NEXT_HD DIFF ------ ----------- ----------- ---------- CLARK 09-JUN-1981 17-NOV-1981 161 ant 17-NOV-1981 23-JAN-1982 67 joe 17-NOV-1981 23-JAN-1982 67 jim 17-NOV-1981 23-JAN-1982 67 choi 17-NOV-1981 23-JAN-1982 67 KING 17-NOV-1981 23-JAN-1982 67 MILLER 23-JAN-1982 (null) (null) Now the results are correct. All the employees hired on the same day have their HIREDATEs evaluated against the next HIREDATE, not a HIREDATE that matches their own. If the workaround isn't immediately obvious, simply break down the query. Start with the inline view: **select deptno,ename,hiredate,** **count(*)over(partition by hiredate) cnt,** **row_number()over(partition by hiredate order by empno) rn** **from emp** **where deptno=10** DEPTNO ENAME HIREDATE CNT RN ------ ------ ----------- ---------- ---------- 10 CLARK 09-JUN-1981 1 1 10 ant 17-NOV-1981 5 1 10 joe 17-NOV-1981 5 2 10 jim 17-NOV-1981 5 3 10 choi 17-NOV-1981 5 4 10 KING 17-NOV-1981 5 5 10 MILLER 23-JAN-1982 1 1 The window function COUNT OVER counts the number of times each HIREDATE occurs and returns this value to each row. For the duplicate HIREDATEs, a value of 5 is returned for each row with that HIREDATE. The window function ROW_ NUMBER OVER ranks each employee by EMPNO. The ranking is partitioned by HIREDATE, so unless there are duplicate HIREDATEs each employee will have a rank of 1. At this point, all the duplicates have been counted and ranked and the ranking can serve as the distance to the next HIREDATE (MILLER's HIREDATE). You can see this by subtracting RN from CNT and adding 1 for each row when calling LEAD: **select deptno, ename, hiredate,** **cnt-rn+1 distance_to_miller,** **lead(hiredate,cnt-rn+1)over(order by hiredate) next_hd** **from (** **select deptno,ename,hiredate,** **count(*)over(partition by hiredate) cnt,** **row_number()over(partition by hiredate order by empno) rn** **from emp** **where deptno=10** **)** DEPTNO ENAME HIREDATE DISTANCE_TO_MILLER NEXT_HD ------ ------ ----------- ------------------ ----------- 10 CLARK 09-JUN-1981 1 17-NOV-1981 10 ant 17-NOV-1981 5 23-JAN-1982 10 joe 17-NOV-1981 4 23-JAN-1982 10 jim 17-NOV-1981 3 23-JAN-1982 10 choi 17-NOV-1981 2 23-JAN-1982 10 KING 17-NOV-1981 1 23-JAN-1982 10 MILLER 23-JAN-1982 1 (null) As you can see, by passing the appropriate distance to jump ahead to, the LEAD function performs the subtraction on the correct dates. ## Chapter 9. Date Manipulation This chapter introduces recipes for searching and modifying dates. Queries involving dates are very common. Thus, you need to know how to think when working with dates, and you need to have a good understanding of the functions that your RDBMS platform provides for manipulating them. The recipes in this chapter form an important foundation for future work as you move on to more complex queries involving not only dates, but times too. Before getting into the recipes, I want to reinforce the concept (that I mentioned in the Preface) of using these solutions as guidelines to solving your specific problems. Try to think "big picture." For example, if a recipe solves a problem for the current month, keep in mind that you may be able to use the recipe for any month (with minor modifications), not just the month used in the recipe. Again, I want you to use these recipes as guidelines, not as the absolute final option. There's no possible way a book can contain an answer for all your problems, but if you understand what is presented here, modifying these solutions to fit your needs is trivial. I also urge you to consider alternative versions of the solutions I've provided. For instance, if I solve a problem using one particular function provided by your RDBMS, it is worth the time and effort to find out if there is an alternative—maybe one that is more or less efficient than what is presented here. Knowing what options you have will make you a better SQL programmer. ### Tip The recipes presented in this chapter use simple date data types. If you are using more complex date data types you will need to adjust the solutions accordingly. ## 9.1. Determining if a Year Is a Leap Year ### Problem You want to determine whether or not the current year is a leap year. ### Solution If you've worked on SQL for some time, there's no doubt that you've come across several techniques for solving this problem. Just about all the solutions I've encountered work well, but the one presented in this recipe is probably the simplest. This solution simply checks the last day of February; if it is the 29th then the current year is a leap year. #### DB2 Use the recursive WITH clause to return each day in February. Use the aggregate function MAX to determine the last day in February. 1 with x (dy,mth) 2 as ( 3 select dy, month(dy) 4 from ( 5 select (current_date - 6 dayofyear(current_date) days +1 days) 7 +1 months as dy 8 from t1 9 ) tmp1 10 union all 11 select dy+1 days, mth 12 from x 13 where month(dy+1 day) = mth 14 ) 15 select max(day(dy)) 16 from x #### Oracle Use the function LAST_DAY to find the last day in February: 1 select to_char( 2 last_day(add_months(trunc(sysdate,'y'),1)), 3 'DD') 4 from t1 #### PostgreSQL Use the function GENERATE_SERIES to return each day in February, then use the aggregate function MAX to find the last day in February: 1 select max(to_char(tmp2.dy+x.id,'DD')) as dy 2 from ( 3 select dy, to_char(dy,'MM') as mth 4 from ( 5 select cast(cast( 6 date_trunc('year',current_date) as date) 7 + interval '1 month' as date) as dy 8 from t1 9 ) tmp1 10 ) tmp2, generate_series (0,29) x(id) 11 where to_char(tmp2.dy+x.id,'MM') = tmp2.mth #### MySQL Use the function LAST_DAY to find the last day in February: 1 select day( 2 last_day( 3 date_add( 4 date_add( 5 date_add(current_date, 6 interval -dayofyear(current_date) day), 7 interval 1 day), 8 interval 1 month))) dy 9 from t1 #### SQL Server Use the recursive WITH clause to return each day in February. Use the aggregate function MAX to determine the last day in February: 1 with x (dy,mth) 2 as ( 3 select dy, month(dy) 4 from ( 5 select dateadd(mm,1,(getdate()-datepart(dy,getdate()))+1) dy 6 from t1 7 ) tmp1 8 union all 9 select dateadd(dd,1,dy), mth 10 from x 11 where month(dateadd(dd,1,dy)) = mth 12 ) 13 select max(day(dy)) 14 from x ### Discussion #### DB2 The inline view TMP1 in the recursive view X returns the first day in February by: 1. Starting with the current date 2. Using DAYOFYEAR to determine the number of days into the current year that the current date represents 3. Subtracting that number of days from the current date to get December 31 of the prior year, and then adding one to get to January 1 of the current year 4. Adding one month to get to February 1 The result of all this math is shown below: **select (current_date** ******dayofyear(current_date) days +1 days) +1 months as dy** **from t1** DY ----------- 01-FEB-2005 The next step is to return the month of the date returned by inline view TMP1 by using the MONTH function: **select dy, month(dy) as mth** **from (** **select (current_date** **dayofyear(current_date) days +1 days) +1 months as dy** **from t1** **) tmp1** DY MTH ----------- --- 01-FEB-2005 2 The results presented thus far provide the start point for the recursive operation that generates each day in February. To return each day in February, repeatedly add one day to DY until you are no longer in the month of February. A portion of the results of the WITH operation is shown below: **with x (dy,mth)** **as (** **select dy, month(dy)** **from (** **select (current_date -** **dayofyear(current_date) days +1 days) +1 months as dy** **from t1** **) tmp1** **union all** **select dy+1 days, mth** **from x** **where month(dy+1 day) = mth** **)** **select dy,mth** **from x** DY MTH ----------- --- 01-FEB-2005 2 ... 10-FEB-2005 2 ... 28-FEB-2005 2 The final step is to use the MAX function on the DY column to return the last day in February; if it is the 29th, you are in a leap year. #### Oracle The first step is to find the beginning of the year using the TRUNC function: **select trunc(sysdate,'y')** **from t1** DY ----------- 01-JAN-2005 Because the first day of the year is January 1st, the next step is to add one month to get to February 1st: **select add_months(trunc(sysdate,'y'),1) dy** **from t1** DY ----------- 01-FEB-2005 The next step is to use the LAST_DAY function to find the last day in February: **select last_day(add_months(trunc(sysdate,'y'),1)) dy** **from t1** DY ----------- 28-FEB-2005 The final step (which is optional) is to use TO_CHAR to return either 28 or 29. #### PostgreSQL The first step is to examine the results returned by inline view TMP1. Use the DATE_TRUNC function to find the beginning of the current year and cast that result as a DATE: **select cast(date_trunc('year',current_date) as date) as dy** **from t1** DY ----------- 01-JAN-2005 The next step is to add one month to the first day of the current year to get the first day in February, casting the result as a date: **select cast(cast(** **date_trunc('year',current_date) as date)** **+ interval '1 month' as date) as dy** **from t1** DY ----------- 01-FEB-2005 Next, return DY from inline view TMP1 along with the numeric month of DY. Return the numeric month by using the TO_CHAR function: **select dy, to_char(dy,'MM') as mth** **from (** **select cast(cast(** **date_trunc('** **year',current_date) as date)** **+ interval '1 month' as date) as dy** **from t1** **) tmp1** DY MTH ----------- --- 01-FEB-2005 2 The results shown thus far comprise the result set of inline view TMP2. Your next step is to use the extremely useful function GENERATE_SERIES to return 29 rows (values 1 through 29). Every row returned by GENERATE_SERIES (aliased X) is added to DY from inline view TMP2. Partial results are shown below: **select tmp2.dy+x.id as dy, tmp2.mth** **from (** **select dy, to_char(dy,'MM') as mth** **from (** **select cast(cast(** **date_trunc('year',current_date) as date)** **+ interval '1 month' as date) as dy** **from t1** **) tmp1** **) tmp2, generate_series (0,29) x(id)** **where to_char(tmp2.dy+x.id,'MM') = tmp2.mth** DY MTH ----------- --- 01-FEB-2005 02 ... 10-FEB-2005 02 ... 28-FEB-2005 02 The final step is to use the MAX function to return the last day in February. The function TO_CHAR is applied to that value and will return either 28 or 29. #### MySQL The first step is to find the first day of the current year by subtracting from the current date the number of days it is into the year, and then adding one day. Do all of this with the DATE_ADD function: **select date_add(** **date_add(current_date,** **interval** **-dayofyear(current_date) day),** **interval 1 day) dy** **from t1** DY ----------- 01-JAN-2005 Then add one month again using the DATE_ADD function: **select date_add(** **date_add(** **date_add(current_date,** **interval -dayofyear(current_date) day),** **interval 1 day),** **interval 1 month) dy** **from t1** DY ----------- 01-FEB-2005 Now that you've made it to February, use the LAST_DAY function to find the last day of the month: **select last_day(** **date_add(** **date_add(** **date_add(current_date,** **interval -dayofyear(current_date) day),** **interval 1 day),** **interval 1 month)) dy** **from t1** DY ----------- 28-FEB-2005 The final step (which is optional) is to use the DAY function to return either a 28 or 29. #### SQL Server This solution uses the recursive WITH clause to generate each day in February. The first step is to find the first day of February. To do this, find the first day of the current year by subtracting from the current date the number of days it is into the year, and then adding one day. Once you have the first day of the current year, use the DATEADD function to add one month to advance to the first day of February: **select dateadd(mm,1,(getdate()-datepart(dy,getdate()))+1) dy** **from t1** DY ----------- 01-FEB-2005 Next, return the first day of February along with the numeric month for February: **select dy, month(dy) mth** **from (** **select dateadd(mm,1,(getdate()-datepart(dy,getdate()))+1) dy** **from t1** **) tmp1** DY MTH ----------- --- 01-FEB-2005 2 Then use the recursive capabilities of the WITH clause to repeatedly add one day to DY from inline view TMP1 until you are no longer in February (partial results shown below): **with x (dy,mth)** **as (** **select dy, month(dy)** **from (** **select dateadd(mm,1,(getdate()-datepart(dy,getdate()))+1) dy** **from t1** **) tmp1** **union all** **select dateadd(dd,1,dy), mth** **from x** **where month(dateadd(dd,1,dy)) = mth** **)** **select dy,mth from x** DY MTH ----------- --- 01-FEB-2005 02 ... 10-FEB-2005 02 ... 28-FEB-2005 02 Now that you can return each day in February, the final step is to use the MAX function to see if the last day is the 28th or 29th. As an optional last step, you can use the DAY function to return a 28 or 29, rather than a date. ## 9.2. Determining the Number of Days in a Year ### Problem You want to count the number of days in the current year. ### Solution The number of days in the current year is the difference between the first day of the next year and the first day of the current year (in days). For each solution the steps are: 1. Find the first day of the current year. 2. Add one year to that date (to get the first day of the next year). 3. Subtract the current year from the result of Step 2. The solutions differ only in the built-in functions that you use to perform these steps. #### DB2 Use the function DAYOFYEAR to help find the first day of the current year, and use DAYS to find the number of days in the current year: 1 select days((curr_year + 1 year)) - days(curr_year) 2 from ( 3 select (current_date - 4 dayofyear(current_date) day + 5 1 day) curr_year 6 from t1 7 ) x #### Oracle Use the function TRUNC to find the beginning of the current year, and use ADD_ MONTHS to then find the beginning of next year: 1 selectadd_months(trunc(sysdate,'y'),12) - trunc(sysdate,'y') 2 from dual #### PostgreSQL Use the function DATE_TRUNC to find the beginning of the current year. Then use interval arithmetic to determine the beginning of next year: 1 select cast((curr_year + interval '1 year') as date) - curr_year 2 from ( 3 select cast(date_trunc('year',current_date) as date) as curr_year 4 from t1 5 ) x #### MySQL Use ADDDATE to help find the beginning of the current year. Use DATEDIFF and interval arithmetic to determine the number of days in the year: 1 select datediff((curr_year + interval 1 year),curr_year) 2 from ( 3 select adddate(current_date,-dayofyear(current_date)+1) curr_year 4 from t1 5 ) x #### SQL Server Use the function DATEADD to find the first day of the current year. Use DATEDIFF to return the number of days in the current year: 1 select datediff(d,curr_year,dateadd(yy,1,curr_year)) 2 from ( 3 select dateadd(d,-datepart(dy,getdate())+1,getdate()) curr_year 4 from t1 5 ) x ### Discussion #### DB2 The first step is to find the first day of the current year. Use DAYOFYEAR to determine how many days you are into the current year. Subtract that value from the current date to get the last day of last year, and then add 1: **select (current_date** **dayofyear(current_date) day +** **1 day) curr_year** **from t1** CURR_YEAR ----------- 01-JAN-2005 Now that you have the first day of the current year, just add one year to it; this gives you the first day of next year. Then subtract the beginning of the current year from the beginning of next year. #### Oracle The first step is to find the first day of the current year, which you can easily do by invoking the built-in TRUNC function and passing 'Y' as the second argument (thereby truncating the date to the beginning of the year): **select select trunc(sysdate,'y') curr_year** **from dual** CURR_YEAR ----------- 01-JAN-2005 Then add one year to arrive at the first day of the next year. Finally, subtract the two dates to find the number of days in the current year. #### PostgreSQL Begin by finding the first day of the current year. To do that, invoke the DATE_ TRUNC function as follows: **select cast(date_trunc('** **year',current_date) as date) as curr_year** **from t1** CURR_YEAR ----------- 01-JAN-2005 You can then easily add a year to compute the first day of next year. Then all you need to do is to subtract the two dates. Be sure to subtract the earlier date from the later date. The result will be the number of days in the current year. #### MySQL Your first step is to find the first day of the current year. Use DAYOFYEAR to find how many days you are into the current year. Subtract that value from the current date, and add 1: **select adddate(current_date,-dayofyear(current_date)+1) curr_year** **from t1** CURR_YEAR ----------- 01-JAN-2005 Now that you have the first day of the current year, your next step is to add one year to it to get the first day of next year. Then subtract the beginning of the current year from the beginning of the next year. The result is the number of days in the current year. #### SQL Server Your first step is to find the first day of the current year. Use DATEADD and DATEPART to subtract from the current date the number of days into the year the current date is, and add 1: **select dateadd(d,-datepart(dy,getdate())+1,getdate()) curr_year** **from t1** CURR_YEAR ----------- 01-JAN-2005 Now that you have the first day of the current year, your next step is to add one year to it get the first day of the next year. Then subtract the beginning of the current year from the beginning of the next year. The result is the number of days in the current year. ## 9.3. Extracting Units of Time from a Date ### Problem You want to break the current date down into six parts: day, month, year, second, minute, and hour. You want the results to be returned as numbers. ### Solution My use of the current date is arbitrary. Feel free to use this recipe with other dates. In Chapter 1, I mention the importance of learning and taking advantage of the built-in functions provided by your RDBMS; this is especially true when it comes to working with dates. There are different ways of extracting units of time from a date than those presented in this recipe, and it would benefit you to experiment with different techniques and functions. #### DB2 DB2 implements a set of built-in functions that make it easy for you to extract portions of a date. The function names HOUR, MINUTE, SECOND, DAY, MONTH, and YEAR conveniently correspond to the units of time you can return: if you want the day use DAY, hour use HOUR, etc. For example: **1 select hour( current_timestamp ) hr,** **2 minute( current_timestamp ) min,** **3 second( current_timestamp ) sec,** **4 day( current_timestamp ) dy,** **5 month( current_timestamp ) mth,** **6 year( current_timestamp ) yr** **7 from t1** HR MIN SEC DY MTH YR ---- ----- ----- ----- ----- ----- 20 28 36 15 6 2005 #### Oracle Use functions TO_CHAR and TO_NUMBER to return specific units of time from a date: **1 select to_number(to_char(sysdate,'hh24')) hour,** **2 to_number(to_char(sysdate,'mi')) min,** **3 to_number(to_char(sysdate,'ss')) sec,** **4 to_number(to_char(sysdate,'dd')) day,** **5 to_number(to_char(sysdate,'mm')) mth,** **6 to_number(to_char(sysdate,'yyyy')) year** **7 from dual** HOUR MIN SEC DAY MTH YEAR ---- ----- ----- ----- ----- ----- 20 28 36 15 6 2005 #### PostgreSQL Use functions TO_CHAR and TO_NUMBER to return specific units of time from a date: **1 select to_number(to_char(current_timestamp,'hh24'),'99') as hr,** **2 to_number(to_char(current_timestamp,'mi'),'99') as min,** **3 to_number(to_char(current_timestamp,'ss'),'99') as sec,** **4 to_number(to_char(current_timestamp,'dd'),'99') as day,** **5 to_number(to_char(current_timestamp,'mm'),'99') as mth,** **6 to_number(to_char(current_timestamp,'yyyy'),'9999') as yr** **7 from t1** HR MIN SEC DAY MTH YR ---- ----- ----- ----- ----- ----- 20 28 36 15 6 2005 #### MySQL Use the DATE_FORMAT function to return specific units of time from a date: **1 select date_format(current_timestamp,'%k') hr,** **2 date_format(current_timestamp,'%i') min,** **3 date_format(current_timestamp,'%s') sec,** **4 date_format(current_timestamp,'%d') dy,** **5 date_format(current_timestamp,'%m') mon,** **6 date_format(current_timestamp,'%Y') yr** **7 from t1** HR MIN SEC DAY MTH YR ---- ----- ----- ----- ----- ----- 20 28 36 15 6 2005 #### SQL Server Use the function DATEPART to return specific units of time from a date: **1 select datepart( hour, getdate()) hr,** **2 datepart( minute,getdate()) min,** **3 datepart( second,getdate()) sec,** **4 datepart( day, getdate()) dy,** **5 datepart( month, getdate()) mon,** **6 datepart( year, getdate()) yr** **7 from t1** HR MIN SEC DAY MTH YR ---- ----- ----- ----- ----- ----- 20 28 36 15 6 2005 ### Discussion There's nothing fancy in these solutions; just take advantage of what you're already paying for. Take the time to learn the date functions available to you. This recipe only scratches the surface of the functions presented in each solution. You'll find that each of the functions takes many more arguments and can return more information than what this recipe provides you. ## 9.4. Determining the First and Last Day of a Month ### Problem You want to determine the first and last days for the current month. ### Solution The solutions presented here are for finding first and last days for the current month. Using the current month is arbitrary. With a bit of adjustment, you can make the solutions work for any month. #### DB2 Use the DAY function to return the number of days into the current month the current date represents. Subtract this value from the current date, and then add 1 to get the first of the month. To get the last day of the month, add one month to the current date, then subtract from it the value returned by the DAY function as applied to the current date: 1 select (date(current_date) - day(date(current_date)) day + 1 day) firstday, 2 (date(current_date)+1 month - day(date(current_date)+1 month) day) lastday 3 from t1 #### Oracle Use the function TRUNC to find the first of the month, and the function LAST_DAY to find the last day of the month: 1 select trunc(sysdate,'mm') firstday, 2 last_day(sysdate) lastday 3 from dual ### Tip Using TRUNC as decribed here will result in the loss of any time-of-day component, whereas LAST_DAY will preserve the time of day. #### PostgreSQL Use the DATE_TRUNC function to truncate the current date to the first of the current month. Once you have the first day of the month, add one month and subtract one day to find the end of the current month: 1 select firstday, 2 cast(firstday + interval '1 month' 3 - interval '1 day' as date) as lastday 4 from ( 5 select cast(date_trunc('month',current_date) as date) as firstday 6 from t1 7 ) x #### MySQL Use the DATE_ADD and DAY functions to find the number of days into the month the current date is. Then subtract that value from the current date and add 1 to find the first of the month. To find the last day of the current month, use the LAST_DAY function: 1 select date_add(current_date, 2 interval -day(current_date)+1 day) firstday, 3 last_day(current_date) lastday 4 from t1 #### SQL Server Use the DATEADD and DAY functions to find the number of days into the month represented by the current date. Then subtract that value from the current date and add 1 to find the first of the month. To get the last day of the month, add one month to the current date, and then subtract from that result the value returned by the DAY function applied to the current date, again using the functions DAY and DATEADD: 1 select dateadd(day,-day(getdate())+1,getdate()) firstday, 2 dateadd(day, 3 -day(dateadd(month,1,getdate())), 4 dateadd(month,1,getdate())) lastday 5 from t1 ### Discussion #### DB2 To find the first day of the month simply find the numeric value of the current day of the month then subtract this from the current date. For example, if the date is March 14th, the numeric day value is 14. Subtracting 14 days from March 14th gives you the last day of the month in February. From there, simply add one day to get to the first of the current month. The technique to get the last day of the month is similar to that of the first; subtract the numeric day of the month from the current date to get the last day of the prior month. Since we want the last day of the current month (not the last day of the prior month), we need to add one month to the current date. #### Oracle To find the first day of the current month, use the TRUNC function with "mm" as the second argument to "truncate" the current date down to the first of the month. To find the last day of the current month, simply use the LAST_DAY function. #### PostgreSQL To find the first day of the current month, use the DATE_TRUNC function with "month" as the second argument to "truncate" the current date down to the first of the month. To find the last day of the current month, add one month to the first day of the month, and then subtract one day. #### MySQL To find the first day of the month, use the DAY function. The DAY function conveniently returns the day of the month for the date passed. If you subtract the value returned by DAY(CURRENT_DATE) from the current date, you get the last day of the prior month; add one day to get the first day of the current month. To find the last day of the current month, simply use the LAST_DAY function. #### SQL Server To find the first day of the month, use the DAY function. The DAY function conveniently returns the day of the month for the date passed. If you subtract the value returned by DAY(GETDATE()) from the current date, you get the last day of the prior month; add one day to get the first day of the current month. To find the last day of the current month, use the DATEADD function. Add one month to the current date, then subtract from it the value returned by DAY(GETDATE()) to get the last day of the current month. Add one month to the current date, then subtract from it the value returned by DAY(DATEADD(MONTH,1,GETDATE())) to get the last day of the current month. ## 9.5. Determining All Dates for a Particular Weekday Throughout a Year ### Problem You want to find all the dates in a year that correspond to a given day of the week. For example, you may wish to generate a list of Fridays for the current year. ### Solution Regardless of vendor, the key to the solution is to return each day for the current year and keep only those dates corresponding to the day of the week that you care about. The solution examples retain all the Fridays. #### DB2 Use the recursive WITH clause to return each day in the current year. Then use the function DAYNAME to keep only Fridays: 1 with x (dy,yr) 2 as ( 3 select dy, year(dy) yr 4 from ( 5 select (current_date - 6 dayofyear(current_date) days +1 days) as dy 7 from t1 8 ) tmp1 9 union all 10 select dy+1 days, yr 11 from x 12 where year(dy +1 day) = yr 13 ) 14 select dy 15 from x 16 where dayname(dy) = 'Friday' #### Oracle Use the recursive CONNECT BY clause to return each day in the current year. Then use the function TO_CHAR to keep only Fridays: 1 with x 2 as ( 3 select trunc(sysdate,'y')+level-1 dy 4 from t1 5 connect by level <= 6 add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y') 7 ) 8 select * 9 from x 10 where to_char( dy, 'dy') = 'fri' #### PostgreSQL Use the function GENERATE_SERIES to return each day in the current year. Then use the function TO_CHAR to keep only Fridays: 1 select cast(date_trunc('year',current_date) as date) 2 + x.id as dy 3 from generate_series ( 4 0, 5 ( select cast( 6 cast( 7 date_trunc('year',current_date) as date) 8 + interval '1 years' as date) 9 - cast( 10 date_trunc('year',current_date) as date) )-1 11 ) x(id) 12 where to_char( 13 cast( 14 date_trunc('year',current_date) 15 as date)+x.id,'dy') = 'fri' #### MySQL Use the pivot table T500 to return each day in the current year. Then use the function DAYNAME to keep only Fridays: 1 select dy 2 from ( 3 select adddate(x.dy,interval t500.id-1 day) dy 4 from ( 5 select dy, year(dy) yr 6 from ( 7 select adddate( 8 adddate(current_date, 9 interval -dayofyear(current_date) day), 10 interval 1 day ) dy 11 from t1 12 ) tmp1 13 ) x, 14 t500 15 where year(adddate(x.dy,interval t500.id-1 day)) = x.yr 16 ) tmp2 17 where dayname(dy) = 'Friday' #### SQL Server Use the recursive WITH clause to return each day in the current year. Then use the function DAYNAME to keep only Fridays: 1 with x (dy,yr) 2 as ( 3 select dy, year(dy) yr 4 from ( 5 select getdate()-datepart(dy,getdate())+1 dy 6 from t1 7 ) tmp1 8 union all 9 select dateadd(dd,1,dy), yr 10 from x 11 where year(dateadd(dd,1,dy)) = yr 12 ) 13 select x.dy 14 from x 15 where datename(dw,x.dy) = 'Friday' 16 option (maxrecursion 400) ### Discussion #### DB2 To find all the Fridays in the current year, you must be able to return every day in the current year. The first step is to find the first day of the year by using the DAYOFYEAR function. Subtract the value returned by DAYOFYEAR(CURRENT_DATE) from the current date to get December 31 of the prior year, and then add 1 to get the first day of the current year: **select (current_date** **dayofyear(current_date) days +1 days) as dy** **from t1** DY ----------- 01-JAN-2005 Now that you have the first day of the year, use the WITH clause to repeatedly add one day to the first day of the year until you are no longer in the current year. The result set will be every day in the current year (a portion of the rows returned by the recursive view X is shown below): **with x (dy,yr)** **as (** **select dy, year(dy) yr** **from (** **select (current_date** **dayofyear(current_date) days +1 days) as dy** **from t1** **) tmp1** **union all** **select dy+1 days, yr** **from x** **where year(dy +1 day) = yr** **)** **select dy** **from x** DY ----------- 01-JAN-2005 ... 15-FEB-2005 ... 22-NOV-2005 ... 31-DEC-2005 The final step is to use the DAYNAME function to keep only rows that are Fridays. #### Oracle To find all the Fridays in the current year, you must be able to return every day in the current year. Begin by using the TRUNC function to find the first day of the year: **select trunc(sysdate,'y') dy** **from t1** DY ----------- 01-JAN-2005 Next, use the CONNECT BY clause to return every day in the current year (to understand how to use CONNECT BY to generate rows, see "Generating Consecutive Time and Numeric Values" in Chapter 13). ### Tip As an aside, this recipe uses the WITH clause, but you can also use an inline view. At the time of this writing, Oracle's WITH clause is not meant for recursive operations (unlike the case with DB2 and SQL Server); recursive operations are done using CONNECT BY. A portion of the result set returned by view X is shown below: **with x** **as (** **select trunc(sysdate,'y')+level-1 dy** **from t1** **connect by level<=** **add_months(trunc(sysdate,'y'),12)-trunc(sysdate,'y')** **)** **select *** **from x** DY ----------- 01-JAN-2005 ... 15-FEB-2005 ... 22-NOV-2005 ... 31-DEC-2005 The final step is to use the TO_CHAR function to keep only Fridays. #### PostgreSQL To find all the Fridays in the current year, you must be able to return a row for every day in the current year. To do that, use the GENERATE_SERIES function. The start and end values to be returned by GENERATE_SERIES are 0 and the number of days in the current year minus 1. The first parameter passed to GENERATE_SERIES is 0, while the second is a query that determines the number of days in the current year (because you are adding to the first day of the current year, you actually want to add 1 less than the number of days in the current year, so as to not spill over into the next year). The result returned by the second parameter of the GENERATE_SERIES function is shown below: **select cast(** **cast(** **date_trunc('year',current_date) as date)** **+ interval '1 years' as date)** **-cast(** **date_trunc('year',current_date) as date)-1 as cnt** **from t1** CNT --- 364 Keeping in mind the result set above, the call to GENERATE_SERIES in the FROM clause will look like this: GENERATE_SERIES ( 0, 364 ). If you are in a leap year, such as 2004, the second parameter would be 365. The next step after generating a list of dates in the year is to add the values returned by GENERATE_SERIES to the first day of the current year. A portion of the results is shown below: **select cast(date_trunc('year',current_date) as date)** **+ x.id as dy** **from generate_series (** **0,** **( select cast(** **cast(** **date_trunc('year',current_date) as date)** **+ interval '1 years' as date)** **-cast(** **date_trunc('year',current_date) as date) )-1** **) x(id)** DY ----------- 01-JAN-2005 ... 15-FEB-2005 ... 22-NOV-2005 ... 31-DEC-2005 The final step is to use the TO_CHAR function to keep only the Fridays. #### MySQL To find all the Fridays in the current year, you must be able to return every day in the current year. The first step is to find the first day of the year by using the DAYOF-YEAR function. Subtract the value returned by DAYOFYEAR(CURRENT_DATE) from the current date, and then add 1 to get the first day of the current year: **select adddate(** **adddate(current_date,** **interval -dayofyear(current_date) day),** **interval 1 day ) dy** **from t1** DY ----------- 01-JAN-2005 Then use table T500 to generate enough rows to return each day in the current year. You can do this by adding each value of T500.ID to the first day of the year until you break out of the current year. Partial results of this operation are shown below: **select adddate(x.dy,interval t500.id-1 day) dy** **from (** **select dy, year(dy) yr** **from (** **select adddate(** **adddate(current_date,** **interval -dayofyear(current_date) day),** **interval 1 day ) dy** **from t1** **) tmp1** **) x,** **t500** **where year(adddate(x.dy,interval t500.id-1 day)) = x.yr** DY ----------- 01-JAN-2005 ... 15-FEB-2005 ... 22-NOV-2005 ... 31-DEC-2005 The final step is to use the DAYNAME function to keep only Fridays. #### SQL Server To find all the Fridays in the current year, you must be able to return every day in the current year. The first step is to find the first day of the year by using the DATEPART function. Subtract the value returned by DATEPART(DY,GETDATE()) from the current date, and then add 1 to get the first day of the current year: **select getdate()-datepart(dy,getdate())+1 dy** **from t1** DY ----------- 01-JAN-2005 Now that you have the first day of the year, use the WITH clause and the DATEADD function to repeatedly add one day to the first day of the year until you are no longer in the current year. The result set will be every day in the current year (a portion of the rows returned by the recursive view X is shown below): **with x (dy,yr)** **as (** **select dy, year(dy) yr** **from (** **select getdate()-datepart(dy,getdate())+1 dy** **from t1** **) tmp1** **union all** **select dateadd(dd,1,dy), yr** **from x** **where year(dateadd(dd,1,dy)) = yr** **)** **select x.dy** **from x** **option (maxrecursion 400)** DY ----------- 01-JAN-2005 ... 15-FEB-2005 ... 22-NOV-2005 ... 31-DEC-2005 Finally, use the DATENAME function to keep only rows that are Fridays. For this solution to work, you must set MAXRECURSION to at least 366 (the filter on the year portion of the current year, in recursive view X, guarantees you will never generate more than 366 rows). ## 9.6. Determining the Date of the First and Last Occurrence of a Specific Weekday in a Month ### Problem You want to find, for example, the first and last Mondays of the current month. ### Solution The choice to use Monday and the current month is arbitrary; you can use the solutions presented in this recipe for any weekday and any month. Because each weekday is seven days apart from itself, once you have the first instance of a weekday, you can add 7 days to get the second and 14 days to get the third. Likewise, if you have the last instance of a weekday in a month, you can subtract 7 days to get the third and subtract 14 days to get the second. #### DB2 Use the recursive WITH clause to generate each day in the current month and use a CASE expression to flag all Mondays. The first and last Mondays will be the earliest and latest of the flagged dates: 1 with x (dy,mth,is_monday) 2 as ( 3 select dy,month(dy), 4 case when dayname(dy)='Monday' 5 then 1 else 0 6 end 7 from ( 8 select (current_date-day(current_date) day +1 day) dy 9 from t1 10 ) tmp1 11 union all 12 select (dy +1 day), mth, 13 case when dayname(dy +1 day)='Monday' 14 then 1 else 0 15 end 16 from x 17 where month(dy +1 day) = mth 18 ) 19 select min(dy) first_monday, max(dy) last_monday 20 from x 21 where is_monday = 1 #### Oracle Use the functions NEXT_DAY and LAST_DAY, together with a bit of clever date arithmetic, to find the first and last Mondays of the current month: select next_day(trunc(sysdate,'mm')-1,'MONDAY') first_monday, next_day(last_day(trunc(sysdate,'mm'))-7,'MONDAY') last_monday from dual #### PostgreSQL Use the function DATE_TRUNC to find the first day of the month. Once you have the first day of the month, you can use simple arithmetic involving the numeric values of weekdays (Sun–Sat is 1–7) to find the first and last Mondays of the current month: 1 select first_monday, 2 case to_char(first_monday+28,'mm') 3 when mth then first_monday+28 4 else first_monday+21 5 end as last_monday 6 from ( 7 select case sign(cast(to_char(dy,'d') as integer)-2) 8 when 0 9 then dy 10 when -1 11 then dy+abs(cast(to_char(dy,'d') as integer)-2) 12 when 1 13 then (7-(cast(to_char(dy,'d') as integer)-2))+dy 14 end as first_monday, 15 mth 16 from ( 17 select cast(date_trunc('month',current_date) as date) as dy, 18 to_char(current_date,'mm') as mth 19 from t1 20 ) x 21 ) y #### MySQL Use the ADDDATE function to find the first day of the month. Once you have the first day of the month, you can use simple arithmetic on the numeric values of weekdays (Sun–Sat is 1–7) to find the first and last Mondays of the current month: 1 select first_monday, 2 case month(adddate(first_monday,28)) 3 when mth then adddate(first_monday,28) 4 else adddate(first_monday,21) 5 end last_monday 6 from ( 7 select case sign(dayofweek(dy)-2) 8 when 0 then dy 9 when -1 then adddate(dy,abs(dayofweek(dy)-2)) 10 when 1 then adddate(dy,(7-(dayofweek(dy)-2))) 11 end first_monday, 12 mth 13 from ( 14 select adddate(adddate(current_date,-day(current_date)),1) dy, 15 month(current_date) mth 16 from t1 17 ) x 18 ) y #### SQL Server Use the recursive WITH clause to generate each day in the current month, and then use a CASE expression to flag all Mondays. The first and last Mondays will be the earliest and latest of the flagged dates: 1 with x (dy,mth,is_monday) 2 as ( 3 select dy,mth, 4 case when datepart(dw,dy) = 2 5 then 1 else 0 6 end 7 from ( 8 select dateadd(day,1,dateadd(day,-day(getdate()),getdate())) dy, 9 month(getdate()) mth 10 from t1 11 ) tmp1 12 union all 13 select dateadd(day,1,dy), 14 mth, 15 case when datepart(dw,dateadd(day,1,dy)) = 2 16 then 1 else 0 17 end 18 from x 19 where month(dateadd(day,1,dy)) = mth 20 ) 21 select min(dy) first_monday, 22 max(dy) last_monday 23 from x 24 where is_monday = 1 ### Discussion #### DB2 and SQL Server DB2 and SQL Server use different functions to solve this problem, but the technique is exactly the same. If you eyeball both solutions you'll see the only difference between the two is the way dates are added. This discussion will cover both solutions, using the DB2 solution's code to show the results of intermediate steps. ### Tip If you do not have access to the recursive WITH clause in the version of SQL Server or DB2 that you are running, you can use the PostgreSQL technique instead. The first step in finding the first and last Mondays of the current month is to return the first day of the month. Inline view TMP1 in recursive view X finds the first day of the current month by first finding the current date, specifically, the day of the month for the current date. The day of the month for the current date represents how many days into the month you are (e.g., April 10th is the 10th day of the April). If you subtract this day of the month value from the current date, you end up at the last day of the previous month (e.g., subtracting 10 from April 10th puts you at the last day of March). After this subtraction, simply add one day to arrive at the first day of the current month: **select (current_date-day(current_date) day +1 day) dy** **from t1** DY ----------- 01-JUN-2005 Next, find the month for the current date using the MONTH function and a simple CASE expression to determine whether or not the first day of the month is a Monday: **select dy, month(dy) mth,** **case when dayname(dy)='Monday'** **then 1 else 0** **end is_monday** **from (** **select (current_date-day(current_date) day +1 day) dy** **from t1** **) tmp1** DY MTH IS_MONDAY ----------- --- ---------- 01-JUN-2005 6 0 Then use the recursive capabilities of the WITH clause to repeatedly add one day to the first day of the month until you're no longer in the current month. Along the way, you will use a CASE expression to determine which days in the month are Mondays (Mondays will be flagged with "1"). A portion of the output from recursive view X is shown below: **with x (dy,mth,is_monday)** **as (** **select dy,month(dy) mth,** **case when dayname(dy)='Monday'** **then 1 else 0** **end is_monday** **from (** **select (current_date-day(current_date) day +1 day) dy** **from t1** **) tmp1** **union all** **select (dy +1 day), mth,** **case when dayname(dy +1 day)='Monday'** **then 1 else 0** **end** **from x** **where month(dy +1 day) = mth** **)** **select *** **from x** DY MTH IS_MONDAY ----------- --- ---------- 01-JUN-2005 6 0 02-JUN-2005 6 0 03-JUN-2005 6 0 04-JUN-2005 6 0 05-JUN-2005 6 0 06-JUN-2005 6 1 07-JUN-2005 6 0 08-JUN-2005 6 0 ... Only Mondays will have a value of 1 for IS_MONDAY, so the final step is to use the aggregate functions MIN and MAX on rows where IS_MONDAY is 1 to find the first and last Mondays of the month. #### Oracle The function NEXT_DAY makes this problem easy to solve. To find the first Monday of the current month, first return the last day of the prior month via some date arithmetic involving the TRUNC function: **select trunc(sysdate,'mm')-1 dy** **from dual** DY ----------- 31-MAY-2005 Then use the NEXT_DAY function to find the first Monday that comes after the last day of the previous month (i.e., the first Monday of the current month): **select next_day(trunc(sysdate,'mm')-1,'MONDAY') first_monday** **from dual** FIRST_MONDAY ------------ 06-JUN-2005 To find the last Monday of the current month, start by returning the first day of the current month by using the TRUNC function: **select trunc(sysdate,'mm') dy** **from dual** DY ----------- 01-JUN-2005 The next step is to find the last week (the last seven days) of the month. Use the LAST_DAY function to find the last day of the month, and then subtract seven days: **select last_day(trunc(sysdate,'mm'))-7 dy** **from dual** DY ----------- 23-JUN-2005 If it isn't immediately obvious, you go back seven days from the last day of the month to ensure that you will have at least one of any weekday left in the month. The last step is to use the function NEXT_DAY to find the next (and last) Monday of the month: **select next_day(last_day(trunc(sysdate,'mm'))-7,'MONDAY') last_monday** **from dual** LAST_MONDAY ----------- 27-JUN-2005 #### PostgreSQL and MySQL PostgreSQL and MySQL also share the same solution approach. The difference is in the functions that you invoke. Despite their lengths, the respective queries are extremely simple; little overhead is involved in finding the first and last Mondays of the current month. The first step is to find the first day of the current month. The next step is to find the first Monday of the month. Since there is no function to find the next date for a given weekday, you need to use a little arithmetic. The CASE expression beginning on line 7 (of either solution) evaluates the difference between the numeric value for the weekday of the first day of the month and the numeric value corresponding to Monday. Given that the function TO_CHAR (PostgresSQL), when called with the 'D' or 'd' format, and the function DAYOFWEEK (MySQL) will return a numeric value from 1 to 7 representing days Sunday to Saturday; Monday is always represented by 2. The first test evaluated by CASE is the SIGN of the numeric value of the first day of the month (whatever it may be) minus the numeric value of Monday (2). If the result is 0, then the first day of the month falls on a Monday and that is the first Monday of the month. If the result is–1, then the first day of the month falls on a Sunday and to find the first Monday of the month simply add the difference in days between 2 and 1 (numeric values of Monday and Sunday, respectively) to the first day of the month. ### Tip If you are having trouble understanding how this works, forget the weekday names and just do the math. For example, say you happen to be starting on a Tuesday and you are looking for the next Friday. When using TO_CHAR with the 'd' format, or DAYOFWEEK, Friday is 6 and Tuesday is 3. To get to 6 from 3, simply take the difference (6–3 = 3) and add it to the smaller value ((6–3) + 3 = 6). So, regardless of the actual dates, if the numeric value of the day you are starting from is less than the numeric value of the day you are searching for, adding the difference between the two dates to the date you are starting from will get you to the date you are searching for. If the result from SIGN is 1, then the first day of the month falls between Tuesday and Saturday (inclusive). When the first day of the month has a numeric value greater than 2 (Monday), subtract from 7 the difference between the numeric value of the first day of the month and the numeric value of Monday (2), and then add that value to the first day of the month. You will have arrived at the day of the week that you are after, in this case Monday. ### Tip Again, if you are having trouble understanding how this works, forget the weekday names and just do the math. For example, suppose you want to find the next Tuesday and you are starting from Friday. Tuesday (3) is less than Friday (6). To get to 3 from 6 subtract the difference between the two values from 7 (7–( |3–6| ) = 4) and add the result (4) to the start day Friday. (The vertical bars in |3-6| generate the absolute value of that difference.) Here, you're not adding 4 to 6 (which will give you 10), you are adding four days to Friday, which will give you the next Tuesday. The idea behind the CASE expression is to create a sort of a "next day" function for PostgreSQL and MySQL. If you do not start with the first day of the month, the value for DY will be the value returned by CURRENT_DATE and the result of the CASE expression will return the date of the next Monday starting from the current date (unless CURRENT_DATE is a Monday, then that date will be returned). Now that you have the first Monday of the month, add either 21 or 28 days to find the last Monday of the month. The CASE expression in lines 2–5 determines whether to add 21 or 28 days by checking to see whether 28 days takes you into the next month. The CASE expression does this through the following process: 1. It adds 28 to the value of FIRST_MONDAY. 2. Using either TO_CHAR (PostgreSQL) or MONTH, the CASE expression extracts the name of the current month from result of FIRST_MONDAY + 28. 3. The result from Step 2 is compared to the value MTH from the inline view. The value MTH is the name of the current month as derived from CURRENT_ DATE. If the two month values match, then the month is large enough for you to need to add 28 days, and the CASE expression returns FIRST_MONDAY + 28. If the two month values do not match, then you do not have room to add 28 days, and the CASE expression returns FIRST_MONDAY + 21 days instead. It is convenient that our months are such that 28 and 21 are the only two possible values you need worry about adding. ### Tip You can extend the solution by adding 7 and 14 days to find the second and third Mondays of the month, respectively. ## 9.7. Creating a Calendar ### Problem You want to create a calendar for the current month. The calendar should be formatted like a calendar you might have on your desk seven columns across, (usually) five rows down. ### Solution Each solution will look a bit different, but they all solve the problem the same way: return each day for the current month, and then pivot on the day of the week for each week in the month to create a calendar. There are different formats available for calendars. For example, the Unix _cal_ command formats the days from Sunday to Saturday. The examples in this recipe are based on ISO weeks, so the Monday through Friday format is the most convenient to generate. Once you become comfortable with the solutions, you'll see that reformatting however you like is simply a matter of modifying the values assigned by the ISO week before pivoting. ### Tip As you begin to use different types of formatting with SQL to create readable output, you will notice your queries becoming longer. Don't let those long queries intimidate you; the queries presented for this recipe are extremely simple once broken down and run piece by piece. #### DB2 Use the recursive WITH clause to return every day in the current month. Then pivot on the day of the week using CASE and MAX: 1 with x(dy,dm,mth,dw,wk) 2 as ( 3 select (current_date -day(current_date) day +1 day) dy, 4 day((current_date -day(current_date) day +1 day)) dm, 5 month(current_date) mth, 6 dayofweek(current_date -day(current_date) day +1 day) dw, 7 week_iso(current_date -day(current_date) day +1 day) wk 8 from t1 9 union all 10 select dy+1 day, day(dy+1 day), mth, 11 dayofweek(dy+1 day), week_iso(dy+1 day) 12 from x 13 where month(dy+1 day) = mth 14 ) 15 select max(case dw when 2 then dm end) as Mo, 16 max(case dw when 3 then dm end) as Tu, 17 max(case dw when 4 then dm end) as We, 18 max(case dw when 5 then dm end) as Th, 19 max(case dw when 6 then dm end) as Fr, 20 max(case dw when 7 then dm end) as Sa, 21 max(case dw when 1 then dm end) as Su 22 from x 23 group by wk 24 order by wk #### Oracle Use the recursive CONNECT BY clause to return each day in the current month. Then pivot on the day of the week using CASE and MAX: 1 with x 2 as ( 3 select * 4 from ( 5 select to_char(trunc(sysdate,'mm')+level-1,'iw') wk, 6 to_char(trunc(sysdate,'mm')+level-1,'dd') dm, 7 to_number(to_char(trunc(sysdate,'mm')+level-1,'d')) dw, 8 to_char(trunc(sysdate,'mm')+level-1,'mm') curr_mth, 9 to_char(sysdate,'mm') mth 10 from dual 11 connect by level <= 31 12 ) 13 where curr_mth = mth 14 ) 15 select max(case dw when 2 then dm end) Mo, 16 max(case dw when 3 then dm end) Tu, 17 max(case dw when 4 then dm end) We, 18 max(case dw when 5 then dm end) Th, 19 max(case dw when 6 then dm end) Fr, 20 max(case dw when 7 then dm end) Sa, 21 max(case dw when 1 then dm end) Su 22 from x 23 group by wk 24 order by wk #### PostgreSQL Use the function GENERATE_SERIES to return every day in the current month. Then pivot on the day of the week using MAX and CASE: 1 select max(case dw when 2 then dm end) as Mo, 2 max(case dw when 3 then dm end) as Tu, 3 max(case dw when 4 then dm end) as We, 4 max(case dw when 5 then dm end) as Th, 5 max(case dw when 6 then dm end) as Fr, 6 max(case dw when 7 then dm end) as Sa, 7 max(case dw when 1 then dm end) as Su 8 from ( 9 select * 10 from ( 11 select cast(date_trunc('month',current_date) as date)+x.id, 12 to_char( 13 cast( 14 date_trunc('month',current_date) 15 as date)+x.id,'iw') as wk, 16 to_char( 17 cast( 18 date_trunc('month',current_date) 19 as date)+x.id,'dd') as dm, 20 cast( 21 to_char( 22 cast( 23 date_trunc('month',current_date) 24 as date)+x.id,'d') as integer) as dw, 25 to_char( 26 cast( 27 date_trunc('month',current_date) 28 as date)+x.id,'mm') as curr_mth, 29 to_char(current_date,'mm') as mth 30 from generate_series (0,31) x(id) 31 ) x 32 where mth = curr_mth 33 ) y 34 group by wk 35 order by wk #### Mysol Use table T500 to return each day in the current month. Then pivot on the day of the week using MAX and CASE: 1 select max(case dw when 2 then dm end) as Mo, 2 max(case dw when 3 then dm end) as Tu, 3 max(case dw when 4 then dm end) as We, 4 max(case dw when 5 then dm end) as Th, 5 max(case dw when 6 then dm end) as Fr, 6 max(case dw when 7 then dm end) as Sa, 7 max(case dw when 1 then dm end) as Su 8 from ( 9 select date_format(dy,'%u') wk, 10 date_format(dy,'%d') dm, 11 date_format(dy,'%w')+1 dw 12 from ( 13 select adddate(x.dy,t500.id-1) dy, 14 x.mth 15 from ( 16 select adddate(current_date,-dayofmonth(current_date)+1) dy, 17 date_format( 18 adddate(current_date, 19 -dayofmonth(current_date)+1), 20 '%m') mth 21 from t1 22 ) x, 23 t500 24 where t500.id <= 31 25 and date_format(adddate(x.dy,t500.id-1),'%m') = x.mth 26 ) y 27 ) z 28 group by wk 29 order by wk #### SQL Server Use the recursive WITH clause to return every day in the current month. Then pivot on the day of the week using CASE and MAX: 1 with x(dy,dm,mth,dw,wk) 2 as ( 3 select dy, 4 day(dy) dm, 5 datepart(m,dy) mth, 6 datepart(dw,dy) dw, 7 case when datepart(dw,dy) = 1 8 then datepart(ww,dy)-1 9 else datepart(ww,dy) 10 end wk 11 from ( 12 select dateadd(day,-day(getdate())+1,getdate()) dy 13 from t1 14 ) x 15 union all 16 select dateadd(d,1,dy), day(dateadd(d,1,dy)), mth, 17 datepart(dw,dateadd(d,1,dy)), 18 case when datepart(dw,dateadd(d,1,dy)) = 1 19 then datepart(wk,dateadd(d,1,dy))-1 20 else datepart(wk,dateadd(d,1,dy)) 21 end 22 from x 23 where datepart(m,dateadd(d,1,dy)) = mth 24 ) 25 select max(case dw when 2 then dm end) as Mo, 26 max(case dw when 3 then dm end) as Tu, 27 max(case dw when 4 then dm end) as We, 28 max(case dw when 5 then dm end) as Th, 29 max(case dw when 6 then dm end) as Fr, 30 max(case dw when 7 then dm end) as Sa, 31 max(case dw when 1 then dm end) as Su 32 from x 33 group by wk 34 order by wk ### Discussion #### DB2 The first step is to return each day in the month for which you want to create a calendar. Do that using the recursive WITH clause (if you don't have WITH available, you can use a pivot table, such as T500, as in the MySQL solution). Along with each day of the month (alias DM) you will need to return different parts of each date: the day of the week (alias DW), the current month you are working with (alias MTH), and the ISO week for each day of the month (alias WK). The results of the recursive view X prior to recursion taking place (the upper portion of the UNION ALL) are shown below: **select (current_date -day(current_date) day +1 day) dy,** **day((current_date -day(current_date) day +1 day)) dm,** **month(current_date) mth,** **dayofweek(current_date -day(current_date) day +1 day) dw,** **week_iso(current_date -day(current_date) day +1 day) wk** **from t1** DY DM MTH DW WK ----------- -- --- ---------- -- 01-JUN-2005 01 06 4 22 The next step is to repeatedly increase the value for DM (move through the days of the month) until you are no longer in the current month. As you move through each day in the month, you will also return the day of the week that each day is, and which ISO week the current day of the month falls into. Partial results are shown below: **with x(dy,dm,mth,dw,wk)** **as (** **select (current_date -day(current_date) day +1 day) dy,** **day((current_date -day(current_date) day +1 day)) dm,** **month(current_date) mth,** **dayofweek(current_date -day(current_date) day +1 day) dw,** **week_iso(current_date -day(current_date) day +1 day) wk** **from t1** **union all** **select dy+1 day, day(dy+1 day), mth,** **dayofweek(dy+1 day), week_iso(dy+1 day)** **from x** **where month(dy+1 day) = mth** **)** **select *** **from x** DY DM MTH DW WK ----------- -- --- ---------- -- 01-JUN-2005 01 06 4 22 02-JUN-2005 02 06 5 22 ... 21-JUN-2005 21 06 3 25 22-JUN-2005 22 06 4 25 ... 30-JUN-2005 30 06 5 26 What you are returning at this point are: each day for the current month, the two-digit numeric day of the month, the two-digit numeric month, the one-digit day of the week (1–7 for Sun–Sat), and the two-digit ISO week each day falls into. With all this information available, you can use a CASE expression to determine which day of the week each value of DM (each day of the month) falls into. A portion of the results is shown below: **with x(dy,dm,mth,dw,wk)** **as (** **select (current_date -day(current_date) day +1 day) dy,** **day((current_date -day(current_date) day +1 day)) dm,** **month(current_date) mth,** **dayofweek(current_date -day(current_date) day +1 day) dw,** **week_iso(current_date -day(current_date) day +1 day) wk** **from t1** **union all** **select dy+1 day, day(dy+1 day), mth,** **dayofweek(dy+1 day), week_iso(dy+1 day)** **from x** **where month(dy+1 day) = mth** **)** **select wk,** **case dw when 2 then dm end as Mo,** **case dw when 3 then dm end as Tu,** **case dw when 4 then dm end as We,** **case dw when 5 then dm end as Th,** **case dw when 6 then dm end as Fr,** **case dw when 7 then dm end as Sa,** **case dw when 1 then dm end as Su** **from x** WK MO TU WE TH FR SA SU -- -- -- -- -- -- -- -- 22 01 22 02 22 03 22 04 22 05 23 06 23 07 23 08 23 09 23 10 23 11 23 12 As you can see from the partial output, every day in each week is returned as a row. What you want to do now is to group the days by week, and then collapse all the days for each week into a single row. Use the aggregate function MAX, and group by WK (the ISO week) to return all the days for a week as one row. To properly format the calendar and ensure that the days are in the right order, order the results by WK. The final output is shown below: **with x(dy,dm,mth,dw,wk)** **as (** **select (current_date -day(current_date) day +1 day) dy,** **day((current_date -day(current_date) day +1 day)) dm,** **month(current_date) mth,** **dayofweek(current_date -day(current_date) day +1 day) dw,** **week_iso(current_date -day(current_date) day +1 day) wk** **from t1** **union all** **select dy+1 day, day(dy+1 day), mth,** **dayofweek(dy+1 day), week_iso(dy+1 day)** **from x** **where month(dy+1 day) = mth** **)** **select max(case dw when 2 then dm end) as Mo,** **max(case dw when 3 then dm end) as Tu,** **max(case dw when 4 then dm end) as We,** **max(case dw when 5 then dm end) as Th,** **max(case dw when 6 then dm end) as Fr,** **max(case dw when 7 then dm end) as Sa,** **max(case dw when 1 then dm end) as Su** **from x** **group by wk** **order by wk** MO TU WE TH FR SA SU -- -- -- -- -- -- -- 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #### Oracle Begin by using the recursive CONNECT BY clause to generate a row for each day in the month for which you wish to generate a calendar. If you aren't running at least Oracle9 _i_ Database, you can't use CONNECT BY this way. Instead, you can use a pivot table, such as T500 in the MySQL solution. Along with each day of the month, you will need to return different bits of information for each day: the day of the month (alias DM), the day of the week (alias DW), the current month you are working with (alias MTH), and the ISO week for each day of the month (alias WK). The results of the WITH view X for the first day of the current month are shown below: **select trunc(sysdate,'mm') dy,** **to_char(trunc(sysdate,'mm'),'dd') dm,** **to_char(sysdate,'mm') mth,** **to_number(to_char(trunc(sysdate,'mm'),'d')) dw,** **to_char(trunc(sysdate,'mm'),'iw') wk** **from dual** DY DM MT DW WK ----------- -- -- ---------- -- 01-JUN-2005 01 06 4 22 The next step is to repeatedly increase the value for DM (move through the days of the month) until you are no longer in the current month. As you move through each day in the month, you will also return the day of the week for each day and the ISO week into which the current day falls. Partial results are shown below (the full date for each day is added below for readability): **with x** **as (** **select *** **from (** **select trunc(sysdate,'mm')+level-1 dy,** **to_char(trunc(sysdate,'mm')+level-1,'iw') wk,** **to_char(trunc(sysdate,'mm')+level-1,'dd') dm,** **to_number(to_char(trunc(sysdate,'mm')+level-1,'d')) dw,** **to_char(trunc(sysdate,'mm')+level-1,'mm') curr_mth,** **to_char(sysdate,'mm') mth** **from dual** **connect by level<= 31** **)** **where curr_mth = mth** **)** **select *** **from x** DY WK DM DW CU MT ----------- -- -- ---------- -- -- 01-JUN-2005 22 01 4 06 06 02-JUN-2005 22 02 5 06 06 ... 21-JUN-2005 25 21 3 06 06 22-JUN-2005 25 22 4 06 06 ... 30-JUN-2005 26 30 5 06 06 What you are returning at this point is one row for each day of the current month. In that row you have: the two-digit numeric day of the month, the two-digit numeric month, the one-digit day of the week (1–7 for Sun–Sat), and the two-digit ISO week number. With all this information available, you can use a CASE expression to determine which day of the week each value of DM (each day of the month) falls into. A portion of the results is shown below: **with x** **as (** **select *** **from (** **select trunc(sysdate,'mm')+level-1 dy,** **to_char(trunc(sysdate,'mm')+level-1,'iw') wk,** **to_char(trunc(sysdate,'mm')+level-1,'dd') dm,** **to_number(to_char(trunc(sysdate,'mm')+level-1,'d')) dw,** **to_char(trunc(sysdate,'mm')+level-1,'mm') curr_mth,** **to_char(sysdate,'mm') mth** **from dual** **connect by level<= 31** **)** **where curr_mth = mth** **)** **select wk,** **case dw when 2 then dm end as Mo,** **case dw when 3 then dm end as Tu,** **case dw when 4 then dm end as We,** **case dw when 5 then dm end as Th,** **case dw when 6 then dm end as Fr,** **case dw when 7 then dm end as Sa,** **case dw when 1 then dm end as Su** **from x** WK MO TU WE TH FR SA SU -- -- -- -- -- -- -- -- 22 01 22 02 22 03 22 04 22 05 23 06 23 07 23 08 23 09 23 10 23 11 23 12 As you can see from the partial output, every day in each week is returned as a row, but the day number is in one of seven columns corresponding to the day of the week. Your task now is to consolidate the days into one row for each week. Use the aggregate function MAX and group by WK (the ISO week) to return all the days for a week as one row. To ensure the days are in the right order, order the results by WK. The final output is shown below: **with x** **as (** **select *** **from (** **select to_char(trunc(sysdate,'mm')+level-1,'iw') wk,** **to_char(trunc(sysdate,'mm')+level-1,'dd') dm,** **to_number(to_char(trunc(sysdate,'mm')+level-1,'d')) dw,** **to_char(trunc(sysdate,'mm')+level-1,'mm') curr_mth,** **to_char(sysdate,'mm') mth** **from dual** **connect by level<= 31** **)** **where curr_mth = mth** **)** **select max(case dw when 2 then dm end) Mo,** **max(case dw when 3 then dm end) Tu,** **max(case dw when 4 then dm end) We,** **max(case dw when 5 then dm end) Th,** **max(case dw when 6 then dm end) Fr,** **max(case dw when 7 then dm end) Sa,** **max(case dw when 1 then dm end) Su** **from x** **group by wk** **order by wk** MO TU WE TH FR SA SU -- -- -- -- -- -- -- 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #### PostgreSQL Use the GENERATE_SERIES function to return one row for each day in the month. If your version of PostgreSQL doesn't support GENERATE_SERIES, then query a pivot table as shown in the MySQL solution. For each day of the month, return the following information: the day of the month (alias DM), the day of the week (alias DW), the current month you are working with (alias MTH), and the ISO week for each day of the month (alias WK). The formatting and explicit casting makes this solution tough on the eyes, but it's really quite simple. Partial results from inline view X are shown below: **select cast(date_trunc('month',current_date) as date)+x.id as dy,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'iw') as wk,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'dd') as dm,** **cast(** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'d') as integer) as dw,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'mm') as curr_mth,** **to_char(current_date,'mm') as mth** **from generate_series (0,31) x(id)** DY WK DM DW CU MT ----------- -- -- ---------- -- -- 01-JUN-2005 22 01 4 06 06 02-JUN-2005 22 02 5 06 06 ... 21-JUN-2005 25 21 3 06 06 22-JUN-2005 25 22 4 06 06 ... 30-JUN-2005 26 30 5 06 06 Notice that as you move through each day in the month, you will also return the day of the week and the ISO week number. To ensure you return days only for the month you are interested in, return only rows where CURR_MTH = MTH (the month each day belongs to should be the month the current date belongs to). What you are returning at this point is, for each day for the current month: the two-digit numeric day of the month, the two-digit numeric month, the one-digit day of the week (1–7 for Sun – Sat), and the two-digit ISO week. Your next step is to use a CASE expression to determine which day of the week each value of DM (each day of the month) falls into. A portion of the results is shown below: **select case dw when 2 then dm end as Mo,** **case dw when 3 then dm end as Tu,** **case dw when 4 then dm end as We,** **case dw when 5 then dm end as Th,** **case dw when 6 then dm end as Fr,** **case dw when 7 then dm end as Sa,** **case dw when 1 then dm end as Su** **from (** **select *** **from (** **select cast(date_trunc('month',current_date) as date)+x.id,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'iw') as wk,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'dd') as dm,** **cast(** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'d') as integer) as dw,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'mm') as curr_mth,** **to_char(current_date,'mm') as mth** **from generate_series (0,31) x(id)** **) x** **where mth = curr_mth** **) y** WK MO TU WE TH FR SA SU -- -- -- -- -- -- -- -- 22 01 22 02 22 03 22 04 22 05 23 06 23 07 23 08 23 09 23 10 23 11 23 12 As you can see from the partial output, every day in each week is returned as a row, and each day number falls into the column corresponding to its day of the week. Your job now is to collapse the days into one row for each week. To that end, use the aggregate function MAX and group the rows by WK (the ISO week). The result will be all the days for each week returned as one row as you would see on a calendar. To ensure the days are in the right order, order the results by WK. The final output is shown below: **select max(case dw when 2 then dm end) as Mo,** **max(case dw when 3 then dm end) as Tu,** **max(case dw when 4 then dm end) as We,** **max(case dw when 5 then dm end) as Th,** **max(case dw when 6 then dm end) as Fr,** **max(case dw when 7 then dm end) as Sa,** **max(case dw when 1 then dm end) as Su** **from (** **select *** **from (** **select cast(date_trunc('month',current_date) as date)+x.id,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'iw') as wk,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'dd') as dm,** **cast(** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'d') as integer) as dw,** **to_char(** **cast(** **date_trunc('month',current_date)** **as date)+x.id,'mm') as curr_mth,** **to_char(current_date,'mm') as mth** **from generate_series (0,31) x(id)** **) x** **where mth = curr_mth** **) y** **group by wk** **order by wk** MO TU WE TH FR SA SU -- -- -- -- -- -- -- 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #### MySQL The first step is to return a row for each day in the month for which you want to create a calendar. To that end, query against table T500. By adding each value returned by T500 to the first day of the month, you can return each day in the month. For each date, you will need to return the following bits of information: the day of the month (alias DM), the day of the week (alias DW), the current month you are working with (alias MTH), and the ISO week for each day of the month (alias WK). Inline view X returns the first day of the current month along with the two-digit numeric value for the current month. Results are shown below: **select adddate(current_date,-dayofmonth(current_date)+1) dy,** **date_format(** **adddate(current_date,** **-dayofmonth(current_date)+1),** **'%m') mth** **from t1** DY MT ----------- -- 01-JUN-2005 06 The next step is to move through the month, starting from the first day and returning each day in the month. Notice that as you move through each day in the month, you will also return the corresponding day of the week and ISO week number. To ensure you return days only for the month you are interested in, return only rows where the month of the day returned is equal to the current month (the month each day belongs to should be the month the current date belongs to). A portion of the rows from inline view Y is shown below: **select date_format(dy,'%u') wk,** **date_format(dy,'%d') dm,** **date_format(dy,'%w')+1 dw** **from (** **select adddate(x.dy,t500.id-1) dy,** **x.mth** **from (** **select adddate(current_date,-dayofmonth(current_date)+1) dy,** **date_format(** **adddate(current_date,** **-dayofmonth(current_date)+1),** **'%m') mth** **from t1** **) x,** **t500** **where t500.id<= 31** **and date_format(adddate(x.dy,t500.id-1),'%m') = x.mth** **) y** WK DM DW -- -- ---------- 22 01 4 22 02 5 ... 25 21 3 25 22 4 ... 26 30 5 For each day for the current month you now have: the two-digit numeric day of the month (DM), the one-digit day of the week (DW), and the two-digit ISO week number (WK). Using this information, you can write a CASE expression to determine which day of the week each value of DM (each day of the month) falls into. A portion of the results is shown below: **select case dw when 2 then dm end as Mo,** **case dw when 3 then dm end as Tu,** **case dw when 4 then dm end as We,** **case dw when 5 then dm end as Th,** **case dw when 6 then dm end as Fr,** **case dw when 7 then dm end as Sa,** **case dw when 1 then dm end as Su** **from (** **select date_format(dy,'%u') wk,** **date_format(dy,'%d') dm,** **date_format(dy,'%w')+1 dw** **from (** **select adddate(x.dy,t500.id-1) dy,** **x.mth** **from (** **select adddate(current_date,-dayofmonth(current_date)+1) dy,** **date_format(** **adddate(current_date,** **-dayofmonth(current_date)+1),** **'%m') mth** **from t1** **) x,** **t500** **where t500.id<= 31** **and date_format(adddate(x.dy,t500.id-1),'%m') = x.mth** **) y** **) z** WK MO TU WE TH FR SA SU -- -- -- -- -- -- -- -- 22 01 22 02 22 03 22 04 22 05 23 06 23 07 23 08 23 09 23 10 23 11 23 12 As you can see from the partial output, every day in each week is returned as a row. Within each row, the day number falls into the column corresponding to the appropriate weekday. Now you need to consolidate the days into one row for each week. To do that, use the aggregate function MAX, and group the rows by WK (the ISO week). To ensure the days are in the right order, order the results by WK. The final output is shown below: **select max(case dw when 2 then dm end) as Mo,** **max(case dw when 3 then dm end) as Tu,** **max(case dw when 4 then dm end) as We,** **max(case dw when 5 then dm end) as Th,** **max(case dw when 6 then dm end) as Fr,** **max(case dw when 7 then dm end) as Sa,** **max(case dw when 1 then dm end) as Su** **from (** **select date_format(dy,'%u') wk,** **date_format(dy,'%d') dm,** **date_format(dy,'%w')+1 dw** **from (** **select adddate(x.dy,t500.id-1) dy,** **x.mth** **from (** **select adddate(current_date,-dayofmonth(current_date)+1) dy,** **date_format(** **adddate(current_date,** **-dayofmonth(current_date)+1),** **'%m') mth** **from t1** **) x,** **t500** **where t500.id<= 31** **and date_format(adddate(x.dy,t500.id-1),'%m') = x.mth** **) y** **) z** **group by wk** **order by wk** MO TU WE TH FR SA SU -- -- -- -- -- -- -- 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 #### SQL Server Begin by returning one row for each day of the month. You can do that using the recursive WITH clause. Or, if your version of SQL Server doesn't support recursive WITH, you can use a pivot table in the same manner as the MySQL solution. For each row that you return, you will need the following items: the day of the month (alias DM), the day of the week (alias DW), the current month you are working with (alias MTH), and the ISO week for each day of the month (alias WK). The results of the recursive view X prior to recursion taking place (the upper portion of the UNION ALL) are shown below: **select dy,** **day(dy) dm,** **datepart(m,dy) mth,** **datepart(dw,dy) dw,** **case when datepart(dw,dy) = 1** **then datepart(ww,dy)-1** **else datepart(ww,dy)** **end wk** **from (** **select dateadd(day,-day(getdate())+1,getdate()) dy** **from t1** **) x** DY DM MTH DW WK ----------- -- --- ---------- -- 01-JUN-2005 1 6 4 23 Your next step is to repeatedly increase the value for DM (move through the days of the month) until you are no longer in the current month. As you move through each day in the month, you will also return the day of the week and the ISO week number. Partial results are shown below: **with x(dy,dm,mth,dw,wk)** **as (** **select dy,** **day(dy) dm,** **datepart(m,dy) mth,** **datepart(dw,dy) dw,** **case when datepart(dw,dy) = 1** **then datepart(ww,dy)-1** **else datepart(ww,dy)** **end wk** **from (** **select dateadd(day,-day(getdate())+1,getdate()) dy** **from t1** **) x** **union all** **select dateadd(d,1,dy), day(dateadd(d,1,dy)), mth,** **datepart(dw,dateadd(d,1,dy)),** **case when datepart(dw,dateadd(d,1,dy)) = 1** **then datepart(wk,dateadd(d,1,dy))-1** **else datepart(wk,dateadd(d,1,dy))** **end** **from x** **where datepart(m,dateadd(d,1,dy)) = mth** **)** **select *** **from x** DY DM MTH DW WK ----------- -- --- ---------- -- 01-JUN-2005 01 06 4 23 02-JUN-2005 02 06 5 23 ... 21-JUN-2005 21 06 3 26 22-JUN-2005 22 06 4 26 ... 30-JUN-2005 30 06 5 27 You now have, for each day in the current month: the two-digit numeric day of the month, the two-digit numeric month, the one-digit day of the week (1–7 for Sun– Sat), and the two-digit ISO week number. Now, use a CASE expression to determine which day of the week each value of DM (each day of the month) falls into. A portion of the results is shown below: **with x(dy,dm,mth,dw,wk)** **as (** **select dy,** **day(dy) dm,** **datepart(m,dy) mth,** **datepart(dw,dy) dw,** **case when datepart(dw,dy) = 1** **then datepart(ww,dy)-1** **else datepart(ww,dy)** **end wk** **from (** **select dateadd(day,-day(getdate())+1,getdate()) dy** **from t1** **) x** **union all** **select dateadd(d,1,dy), day(dateadd(d,1,dy)), mth,** **datepart(dw,dateadd(d,1,dy)),** **case when datepart(dw,dateadd(d,1,dy)) = 1** **then datepart(wk,dateadd(d,1,dy))-1** **else datepart(wk,dateadd(d,1,dy))** **end** **from x** **where datepart(m,dateadd(d,1,dy)) = mth** **)** **select case dw when 2 then dm end as Mo,** **case dw when 3 then dm end as Tu,** **case dw when 4 then dm end as We,** **case dw when 5 then dm end as Th,** **case dw when 6 then dm end as Fr,** **case dw when 7 then dm end as Sa,** **case dw when 1 then dm end as Su** **from x** WK MO TU WE TH FR SA SU -- -- -- -- -- -- -- -- 22 01 22 02 22 03 22 04 22 05 23 06 23 07 23 08 23 09 23 10 23 11 23 12 Every day in each week is returned as a separate row. In each row, the column containing the day number corresponds to the day of the week. You now need to consolidate the days for each week into one row. Do that by grouping the rows by WK (the ISO week) and applying the MAX function to the different columns. The results will be in calendar format as shown below: **with x(dy,dm,mth,dw,wk)** **as (** **select dy,** **day(dy) dm,** **datepart(m,dy) mth,** **datepart(dw,dy) dw,** **case when datepart(dw,dy) = 1** **then datepart(ww,dy)-1** **else datepart(ww,dy)** **end wk** **from (** **select dateadd(day,-day(getdate())+1,getdate()) dy** **from t1** **) x** **union all** **select dateadd(d,1,dy), day(dateadd(d,1,dy)), mth,** **datepart(dw,dateadd(d,1,dy)),** **case when datepart(dw,dateadd(d,1,dy)) = 1** **then datepart(wk,dateadd(d,1,dy))-1** **else datepart(wk,dateadd(d,1,dy))** **end** **from x** **where datepart(m,dateadd(d,1,dy)) = mth** **)** **select max(case dw when 2 then dm end) as Mo,** **max(case dw when 3 then dm end) as Tu,** **max(case dw when 4 then dm end) as We,** **max(case dw when 5 then dm end) as Th,** **max(case dw when 6 then dm end) as Fr,** **max(case dw when 7 then dm end) as Sa,** **max(case dw when 1 then dm end) as Su** **from x** **group by wk** **order by wk** MO TU WE TH FR SA SU -- -- -- -- -- -- -- 01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 ## 9.8. Listing Quarter Start and End Dates for the Year ### Problem You want to return the start and end dates for each of the four quarters of a given year. ### Solution There are four quarters to a year, so you know you will need to generate four rows. After generating the desired number of rows, simply use the date functions supplied by your RDBMS to return the quarter the start and end dates fall into. Your goal is to produce the following result set (one again, the choice to use the current year is arbitrary): QTR Q_START Q_END --- ----------- ----------- 1 01-JAN-2005 31-MAR-2005 2 01-APR-2005 30-JUN-2005 3 01-JUL-2005 30-SEP-2005 4 01-OCT-2005 31-DEC-2005 #### DB2 Use table EMP and the window function ROW_NUMBER OVER to generate four rows. Alternatively, you can use the WITH clause to generate rows (as many of the recipes do), or you can query against any table with at least four rows. The following solution uses the ROW_NUMBER OVER approach: 1 select quarter(dy-1 day) QTR, 2 dy-3 month Q_start, 3 dy-1 day Q_end 4 from ( 5 select (current_date - 6 (dayofyear(current_date)-1) day 7 + (rn*3) month) dy 8 from ( 9 select row_number()over() rn 10 from emp 11 fetch first 4 rows only 12 ) x 13 ) y #### Oracle Use the function ADD_MONTHS to find the start and end dates for each quarter. Use ROWNUM to represent the quarter the start and end dates belong to. The following solution uses table EMP to generate four rows. 1 select rownum qtr, 2 add_months(trunc(sysdate,'y'),(rownum-1)*3) q_start, 3 add_months(trunc(sysdate,'y'),rownum*3)-1 q_end 4 from emp 5 where rownum <= 4 #### PostgreSQL Use the function GENERATE_SERIES to generate the required four quarters. Use the DATE_TRUNC function to truncate the dates generated for each quarter down to year and month. Use the TO_CHAR function to determine which quarter the start and end dates belong to: 1 select to_char(dy,'Q') as QTR, 2 date( 3 date_trunc('month',dy)-(2*interval '1 month') 4 ) as Q_start, 5 dy as Q_end 6 from ( 7 select date(dy+((rn*3) * interval '1 month'))-1 as dy 8 from ( 9 select rn, date(date_trunc('year',current_date)) as dy 10 from generate_series(1,4) gs(rn) 11 ) x 12 ) y #### MySQL Use table T500 to generate four rows (one for each quarter). Use functions DATE_ ADD and ADDDATE to create the start and end dates for each quarter. Use the QUARTER function to determine which quarter the start and end dates belong to: 1 select quarter(adddate(dy,-1)) QTR, 2date_add(dy,interval -3 month) Q_start, 3 adddate(dy,-1) Q_end 4 from ( 5 select date_add(dy,interval (3*id) month) dy 6 from ( 7 select id, 8 adddate(current_date,-dayofyear(current_date)+1) dy 9 from t500 10 where id <= 4 11 ) x 12 ) y #### SQL Server Use the recursive WITH clause to generate four rows. Use the function DATEADD to find the start and end dates. Use the function DATEPART to determine which quarter the start and end dates belong to: 1 with x (dy,cnt) 2 as ( 3 select dateadd(d,-(datepart(dy,getdate())-1),getdate()), 4 1 5 from t1 6 union all 7 select dateadd(m,3,dy), cnt+1 8 from x 9 where cnt+1 <= 4 10 ) 11 select datepart(q,dateadd(d,-1,dy)) QTR, 1 dateadd(m,-3,dy) Q_start, 13 dateadd(d,-1,dy) Q_end 14 from x 15 order by 1 ### Discussion #### DB2 The first step is to generate four rows (with values 1 through 4) for each quarter in the year. Inline view X uses the window function ROW_NUMBER OVER and the FETCH FIRST clause to return only four rows from EMP. The results are shown below: **select row_number()over() rn** **from emp** **fetch first 4 rows only** RN -- 1 2 3 4 The next step is to find the first day of the year, then add _n_ months to it, where _n_ is three times RN (you are adding 3, 6, 9, and 12 months to the first day of the year). The results are shown below: **select (current_date** **(dayofyear(current_date)-1) day** **+ (rn*3) month) dy** **from (** **select row_number()over() rn** **from emp** **fetch first 4 rows only** **) x** DY ----------- 01-APR-2005 01-JUL-2005 01-OCT-2005 01-JAN-2005 At this point, the values for DY are one day after the end date for each quarter. The next step is to get the start and end dates for each quarter. Subtract one day from DY to get the end of each quarter, and subtract three months from DY to get the start of each quarter. Use the QUARTER function on DY-1 (the end date for each quarter) to determine which quarter the start and end dates belong to. #### Oracle The combination of ROWNUM, TRUNC, and ADD_MONTHS makes this solution very easy. To find the start of each quarter simply add _n_ months to the first day of the year, where _n_ is (ROWNUM-1)*3 (giving you 0,3,6,9). To find the end of each quarter add _n_ months to the first day of the year, where _n_ is ROWNUM*3, and subtract one day. As an aside, when working with quarters, you may also find it useful to use TO_CHAR and/or TRUNC with the 'q' formatting option. #### PostgreSQL The first step is to truncate the current date to the first day of the year using the DATE_TRUNC function. Next, add _n_ months, where _n_ is RN (the values returned by GENERATE_SERIES) times three, and subtract one day. The results are shown below: **select date(dy+((rn*3) * interval '1 month'))-1 as dy** **from (** **select rn, date(date_trunc('year',current_date)) as dy** **from generate_series(1,4) gs(rn)** **) x** DY ----------- 31-MAR-2005 30-JUN-2005 30-SEP-2005 31-DEC-2005 Now that you have the end dates for each quarter, the final step is to find the start date by subtracting two months from DY then truncating to the first day of the month by using the DATE_TRUNC function. Use the TO_CHAR function on the end date for each quarter (DY) to determine which quarter the start and end dates belong to. #### MySQL The first step is to find the first day of the year by using functions ADDDATE and DAYOFYEAR, then adding _n_ months to the first day of the year, where _n_ is T500.ID times three, by using the DATE_ADD function. The results are shown below: **select date_add(dy,interval (3*id) month) dy** **from (** **select id,** **adddate(current_date,-dayofyear(current_date)+1) dy** **from t500** **where id<= 4** **) x** DY ----------- 01-APR-2005 01-JUL-2005 01-OCT-2005 01-JAN-2005 At this point the dates are one day after the end of each quarter; to find the end of each quarter, simply subtract one day from DY. The next step is to find the start of each quarter by subtracting three months from DY. Use the QUARTER function on the end date of each quarter to determine which quarter the start and end dates belong to. #### SQL Server The first step is to find the first day of the year, then recursively add _n_ months, where _n_ is three times the current iteration (there are four iterations, therefore, you are adding 3*1 months, 3*2 months, etc.), using the DATEADD function. The results are shown below: **with x (dy,cnt)** **as (** **select dateadd(d,-(datepart(dy,getdate())-1),getdate()),** **1** **from t1** **union all** **select dateadd(m,3,dy), cnt+1** **from x** **where cnt+1<= 4** **)** **select dy** **from x** DY ----------- 01-APR-2005 01-JUL-2005 01-OCT-2005 01-JAN-2005 The values for DY are one day after the end of each quarter. To get the end of each quarter, simply subtract one day from DY by using the DATEADD function. To find the start of each quarter, use the DATEADD function to subtract three months from DY. Use the DATEPART function on the end date for each quarter to determine which quarter the start and end dates belong to. ## 9.9. Determining Quarter Start and End Dates for a Given Quarter ### Problem When given a year and quarter in the format of YYYYQ (four-digit year, one-digit quarter), you want to return the quarter's start and end dates. ### Solution The key to this solution is to find the quarter by using the modulus function on the YYYYQ value. (As an alternative to modulo, since the year format is four digits, you can simply substring out the last digit to get the quarter.) Once you have the quarter, simply multiply by 3 to get the ending month for the quarter. In the solutions that follow, inline view X will return all four year and quarter combinations. The result set for inline view X is as follows: **select 20051 as yrq from t1 union all** **select 20052 as yrq from t1 union all** **select 20053 as yrq from t1 union all** **select 20054 as yrq from t1** YRQ ------- 20051 20052 20053 20054 #### DB2 Use the function SUBSTR to return the year from inline view X. Use the MOD function to determine which quarter you are looking for: 1 select (q_end-2 month) q_start, 2 (q_end+1 month)-1 day q_end 3 from ( 4 select date(substr(cast(yrq as char(4)),1,4) ||'-'|| 5 rtrim(cast(mod(yrq,10)*3 as char(2))) ||'-1') q_end 6 from ( 7 select 20051 yrq from t1 union all 8 select 20052 yrq from t1 union all 9 select 20053 yrq from t1 union all 10 select 20054 yrq from t1 11 ) x 12 ) y #### Oracle Use the function SUBSTR to return the year from inline view X. Use the MOD function to determine which quarter you are looking for: 1 select add_months(q_end,-2) q_start, 2 last_day(q_end) q_end 3 from ( 4 select to_date(substr(yrq,1,4)||mod(yrq,10)*3,'yyyymm') q_end 5 from ( 6 select 20051 yrq from dual union all 7 select 20052 yrq from dual union all 8 select 20053 yrq from dual union all 9 select 20054 yrq from dual 10 ) x 11 ) y #### PostgreSQL Use the function SUBSTR to return the year from the inline view X. Use the MOD function to determine which quarter you are looking for: 1 select date(q_end-(2*interval '1 month')) as q_start, 2 date(q_end+interval '1 month'-interval '1 day') as q_end 3 from ( 4 select to_date(substr(yrq,1,4)||mod(yrq,10)*3,'yyyymm') as q_end 5 from ( 6 select 20051 as yrq from t1 union all 7 select 20052 as yrq from t1 union all 8 select 20053 as yrq from t1 union all 9 select 20054 as yrq from t1 10 ) x 11 ) y #### MySQL Use the function SUBSTR to return the year from the inline view X. Use the MOD function to determine which quarter you are looking for: 1 select date_add( 2 adddate(q_end,-day(q_end)+1), 3 interval -2 month) q_start, 4 q_end 5 from ( 6 select last_day( 7 str_to_date( 8 concat( 9 substr(yrq,1,4),mod(yrq,10)*3),'%Y%m')) q_end 10 from ( 11 select 20051 as yrq from t1 union all 12 select 20052 as yrq from t1 union all 13 select 20053 as yrq from t1 union all 14 select 20054 as yrq from t1 15 ) x 16 ) y #### SQL Server Use the function SUBSTRING to return the year from the inline view X. Use the modulus function (%) to determine which quarter you are looking for: 1 select dateadd(m,-2,q_end) q_start, 2 dateadd(d,-1,dateadd(m,1,q_end)) q_end 3 from ( 4 select cast(substring(cast(yrq as varchar),1,4)+'-'+ 5 cast(yrq%10*3 as varchar)+'-1' as datetime) q_end 6 from ( 7 select 20051 as yrq from t1 union all 8 select 20052 as yrq from t1 union all 9 select 20052 as yrq from t1 union all 10 select 20054 as yrq from t1 11 ) x 12 ) y ### Discussion #### DB2 The first step is to find the year and quarter you are working with. Substring out the year from inline view X (X.YRQ) using the SUBSTR function. To get the quarter, use modulus 10 on YRQ. Once you have the quarter, multiply by 3 to get the end month for the quarter. The results are shown below: **select substr(cast(yrq as char(4)),1,4) yr,** **mod(yrq,10)*3 mth** **from (** **select 20051 yrq from t1 union all** **select 20052 yrq from t1 union all** **select 20053 yrq from t1 union all** **select 20054 yrq from t1** **) x** YR MTH ---- ------ 2005 3 2005 6 2005 9 2005 12 At this point you have the year and end month for each quarter. Use those values to construct a date, specifically, the first day of the last month for each quarter. Use the concatenation operator "||" to glue together the year and month, then use the DATE function to convert to a date: **select date(substr(cast(yrq as char(4)),1,4) ||'-'||** **rtrim(cast(mod(yrq,10)*3 as char(2))) ||'-1') q_end** **from (** **select 20051 yrq from t1 union all** **select 20052 yrq from t1 union all** **select 20053 yrq from t1 union all** **select 20054 yrq from t1** **) x** Q_END ----------- 01-MAR-2005 01-JUN-2005 01-SEP-2005 01-DEC-2005 The values for Q_END are the first day of the last month of each quarter. To get to the last day of the month add one month to Q_END, then subtract one day. To find the start date for each quarter subtract two months from Q_END. #### Oracle The first step is to find the year and quarter you are working with. Substring out the year from inline view X (X.YRQ) using the SUBSTR function. To get the quarter, use modulus 10 on YRQ. Once you have the quarter, multiply by 3 to get the end month for the quarter. The results are shown below: **select substr(yrq,1,4) yr, mod(yrq,10)*3 mth** **from (** **select 20051 yrq from dual union all** **select 20052 yrq from dual union all** **select 20053 yrq from dual union all** **select 20054 yrq from dual** **) x** YR MTH ---- ------ 2005 3 2005 6 2005 9 2005 12 At this point you have the year and end month for each quarter. Use those values to construct a date, specifically, the first day of the last month for each quarter. Use the concatenation operator "||" to glue together the year and month, then use the TO_DATE function to convert to a date: **select to_date(substr(yrq,1,4)||mod(yrq,10)*3,'yyyymm') q_end** **from (** **select 20051 yrq from dual union all** **select 20052 yrq from dual union all** **select 20053 yrq from dual union all** **select 20054 yrq from dual** **) x** Q_END ----------- 01-MAR-2005 01-JUN-2005 01-SEP-2005 01-DEC-2005 The values for Q_END are the first day of the last month of each quarter. To get to the last day of the month use the LAST_DAY function on Q_END. To find the start date for each quarter subtract two months from Q_END using the ADD_MONTHS function. #### PostgreSQL The first step is to find the year and quarter you are working with. Substring out the year from inline view X (X.YRQ) using the SUBSTR function. To get the quarter, use modulus 10 on YRQ. Once you have the quarter, multiply by 3 to get the end month for the quarter. The results are shown below: **select substr(yrq,1,4) yr, mod(yrq,10)*3 mth** **from (** **select 20051 yrq from dual union all** **select 20052 yrq from dual union all** **select 20053 yrq from dual union all** **select 20054 yrq from dual** **) x** YR MTH ---- ------- 2005 3 2005 6 2005 9 2005 12 At this point you have the year and end month for each quarter. Use those values to construct a date, specifically, the first day of the last month for each quarter. Use the concatenation operator "||" to glue together the year and month, then use the TO_ DATE function to convert to a date: **select** **to_date(substr(yrq,1,4)||mod(yrq,10)*3,'yyyymm') q_end** **from (** **select 20051 yrq from dual union all** **select 20052 yrq from dual union all** **select 20053 yrq from dual union all** **select 20054 yrq from dual** **) x** Q_END ----------- 01-MAR-2005 01-JUN-2005 01-SEP-2005 01-DEC-2005 The values for Q_END are the first day of the last month of each quarter. To get to the last day of the month add one month to Q_END and subtract one day. To find the start date for each quarter subtract two months from Q_END. Cast the final result as dates. #### MySQL The first step is to find the year and quarter you are working with. Substring out the year from inline view X (X.YRQ) using the SUBSTR function. To get the quarter, use modulus 10 on YRQ. Once you have the quarter, multiply by 3 to get the end month for the quarter. The results are shown below: **select substr(yrq,1,4) yr, mod(yrq,10)*3 mth** **from (** **select 20051 yrq from dual union all** **select 20052 yrq from dual union all** **select 20053 yrq from dual union all** **select 20054 yrq from dual** **) x** YR MTH ---- ------ 2005 3 2005 6 2005 9 2005 12 At this point you have the year and end month for each quarter. Use those values to construct a date, specifically, the last day of each quarter. Use the CONCAT function to glue together the year and month, then use the STR_TO_DATE function to convert to a date. Use the LAST_DAY function to find the last day for each quarter: **select last_day(** **str_to_date(** **concat(** **substr(yrq,1,4),mod(yrq,10)*3),'** **%Y%m')) q_end** **from (** **select 20051 as yrq from t1 union all** **select 20052 as yrq from t1 union all** **select 20053 as yrq from t1 union all** **select 20054 as yrq from t1** **) x** Q_END ----------- 31-MAR-2005 30-JUN-2005 30-SEP-2005 31-DEC-2005 Because you already have the end of each quarter, all that's left is to find the start date for each quarter. Use the DAY function to return the day of the month the end of each quarter falls on, and subtract that from Q_END using the ADDDATE function to give you the end of the prior month; add one day to bring you to the first day of the last month of each quarter. The last step is to use the DATE_ADD function to subtract two months from the first day of the last month of each quarter to get you to the start date for each quarter. #### SQL Server The first step is to find the year and quarter you are working with. Substring out the year from inline view X (X.YRQ) using the SUBSTRING function. To get the quarter, use modulus 10 on YRQ. Once you have the quarter, multiply by 3 to get the end month for the quarter. The results are shown below: **select substring(yrq,1,4) yr, yrq%10*3 mth** **from (** **select 20051 yrq from dual union all** **select 20052 yrq from dual union all** **select 20053 yrq from dual union all** **select 20054 yrq from dual** **) x** YR MTH ---- ------ 2005 3 2005 6 2005 9 2005 12 At this point, you have the year and end month for each quarter. Use those values to construct a date, specifically, the first day of the last month for each quarter. Use the concatenation operator "+" to glue together the year and month, then use the CAST function to convert to a date: **select cast(substring(cast(yrq as varchar),1,4)+'-'+** **cast(yrq%10*3 as varchar)+'-1' as datetime) q_end** **from (** **select 20051 yrq from t1 union all** **select 20052 yrq from t1 union all** **select 20053 yrq from t1 union all** **select 20054 yrq from t1** **) x** Q_END ----------- 01-MAR-2005 01-JUN-2005 01-SEP-2005 01-DEC-2005 The values for Q_END are the first day of the last month of each quarter. To get to the last day of the month add one month to Q_END and subtract one day using the DATEADD function. To find the start date for each quarter subtract two months from Q_END using the DATEADD function. ## 9.10. Filling in Missing Dates ### Problem You need to generate a row for every date (or every month, week, or year) within a given range. Such rowsets are often used to generate summary reports. For example, you want to count the number of employees hired every month of every year in which any employee has been hired. Examining the dates of all the employees hired, there have been hirings from 1980 to 1983: **select distinct** **extract(year from hiredate) as year** **from emp** YEAR ----- 1980 1981 1982 1983 You want to determine the number of employees hired each month from 1980 to 1983. A portion of the desired result set is shown below: MTH NUM_HIRED ----------- ---------- 01-JAN-1981 0 01-FEB-1981 2 01-MAR-1981 0 01-APR-1981 1 01-MAY-1981 1 01-JUN-1981 1 01-JUL-1981 0 01-AUG-1981 0 01-SEP-1981 2 01-OCT-1981 0 01-NOV-1981 1 01-DEC-1981 2 ### Solution The trick here is that you want to return a row for each month even if no employee was hired (i.e., the count would be zero). Because there isn't an employee hired every month between 1980 and 1983, you must generate those months yourself, and then outer join to table EMP on HIREDATE (truncating the actual HIREDATE to its month, so it can match the generated months when possible). #### DB2 Use the recursive WITH clause to generate every month (the first day of each month from January 1, 1980, to December 1, 1983). Once you have all the months for the required range of dates, outer join to table EMP and use the aggregate function COUNT to count the number of hires for each month: 1 with x (start_date,end_date) 2 as ( 3 select (min(hiredate) 4 dayofyear(min(hiredate)) day +1 day) start_date, 5 (max(hiredate) 6 dayofyear(max(hiredate)) day +1 day) +1 year end_date 7 from emp 8 union all 9 select start_date +1 month, end_date 10 from x 11 where (start_date +1 month) < end_date 12 ) 13 select x.start_date mth, count(e.hiredate) num_hired 14 from x left join emp e 15 on (x.start_date = (e.hiredate-(day(hiredate)-1) day)) 16 group by x.start_date 17 order by 1 #### Oracle Use the CONNECT BY clause to generate each month between 1980 and 1983. Then outer join to table EMP and use the aggregate function COUNT to count the number of employees hired in each month. If you are on Oracle8 _i_ Database and earlier, the ANSI outer join is not available to you, nor is the ability to use CONNECT BY as a row generator; a simple workaround is to use a traditional pivot table (like the one used in the MySQL solution). Following as an Oracle solution using Oracle's outer-join syntax: 1 with x 2 as ( 3 select add_months(start_date,level-1) start_date 4 from ( 5 select min(trunc(hiredate,'y')) start_date, 6 add_months(max(trunc(hiredate,'y')),12) end_date 7 from emp 8 ) 9 connect by level <= months_between(end_date,start_date) 10 ) 11 select x.start_date MTH, count(e.hiredate) num_hired 12 from x, emp e 13 where x.start_date = trunc(e.hiredate(+),'mm') 14 group by x.start_date 15 order by 1 and here is a second Oracle solution, this time using the ANSI syntax: 1 with x 2 as ( 3 select add_months(start_date,level-1) start_date 4 from ( 5 select min(trunc(hiredate,'y')) start_date, 6 add_months(max(trunc(hiredate,'y')),12) end_date 7 from emp 8 ) 9 connect by level <= months_between(end_date,start_date) 10 ) 11 select x.start_date MTH, count(e.hiredate) num_hired 12 from x left join emp e 13 on (x.start_date = trunc(e.hiredate,'mm')) 14 group by x.start_date 15 order by 1 #### PostgreSQL To improve readability, this solution uses a view, named V, to return the number of months between the first day of the first month of the year the first employee was hired and the first day of the last month of the year the most recent employee was hired. Use the value returned by view V as the second value passed to the function GENERATE_SERIES, so that the correct number of months (rows) are generated. Once you have all the months for the required range of dates, outer join to table EMP and use the aggregate function COUNT to count the number of hires for each month: create view v as select cast( extract(year from age(last_month,first_month))*12-1 as integer) as mths from ( select cast(date_trunc('year',min(hiredate)) as date) as first_month, cast(cast(date_trunc('year',max(hiredate)) as date) + interval '1 year' as date) as last_month from emp ) x 1 select y.mth, count(e.hiredate) as num_hired 2 from ( 3 select cast(e.start_date + (x.id * interval '1 month') 4 as date) as mth 5 from generate_series (0,(select mths from v)) x(id), 6 ( select cast( 7 date_trunc('year',min(hiredate)) 8 as date) as start_date 9 from emp ) e 10 ) y left join emp e 11 on (y.mth = date_trunc('month',e.hiredate)) 12 group by y.mth 13 order by 1 #### MySQL Use the pivot table T500 to generate each month between 1980 and 1983. Then outer join to table EMP and use the aggregate function COUNT to count the number of employees hired for each month: 1 select z.mth, count(e.hiredate) num_hired 2 from ( 3 select date_add(min_hd,interval t500.id-1 month) mth 4 from ( 5 select min_hd, date_add(max_hd,interval 11 month) max_hd 6 from ( 7 select adddate(min(hiredate),-dayofyear(min(hiredate))+1) min_hd, 8 adddate(max(hiredate),-dayofyear(max(hiredate))+1) max_hd 9 from emp 10 ) x 11 ) y, 12 t500 13 where date_add(min_hd,interval t500.id-1 month) <= max_hd 14 ) z left join emp e 15 on (z.mth = adddate( 16 date_add( 17 last_day(e.hiredate),interval -1 month),1)) 18 group by z.mth 19 order by 1 #### SQL Server Use the recursive WITH clause to generate every month (the first day of each month from January 1, 1980, to December 1, 1983). Once you have all the months for the required range of dates, outer join to table EMP and use the aggregate function COUNT to count the number of hires for each month: 1 with x (start_date,end_date) 2 as ( 3 select (min(hiredate) 4 datepart(dy,min(hiredate))+1) start_date, 5 dateadd(yy,1, 6 (max(hiredate) 7 datepart(dy,max(hiredate))+1)) end_date 8 from emp 9 union all 10 select dateadd(mm,1,start_date), end_date 11 from x 12 where dateadd(mm,1,start_date) < end_date 13 ) 14 select x.start_date mth, count(e.hiredate) num_hired 15 from x left join emp e 16 on (x.start_date = 17 dateadd(dd,-day(e.hiredate)+1,e.hiredate)) 18 group by x.start_date 19 order by 1 ### Discussion #### DB2 The first step is to generate every month (actually the first day of each month) from 1980 to 1983. Start using the DAYOFYEAR function on the MIN and MAX HIREDATEs to find the boundary months: **select (min(hiredate)** **dayofyear(min(hiredate)) day +1 day) start_date,** **(max(hiredate)** **dayofyear(max(hiredate)) day +1 day) +1 year end_date** **from emp** START_DATE END_DATE ----------- ----------- 01-JAN-1980 01-JAN-1984 Your next step is to repeatedly add months to START_DATE to return all the months necessary for the final result set. The value for END_DATE is one day more than it should be. This is OK. As you recursively add months to START_DATE, you can stop before you hit END_DATE. A portion of the months created is shown below: **with x (start_date,end_date)** **as (** **select (min(hiredate)** **dayofyear(min(hiredate)) day +1 day) start_date,** **(max(hiredate)** **dayofyear(max(hiredate)) day +1 day) +1 year end_date** **from emp** **union all** **select start_date +1 month, end_date** **from x** **where (start_date +1 month)< end_date** **)** **select *** **from x** START_DATE END_DATE ----------- ----------- 01-JAN-1980 01-JAN-1984 01-FEB-1980 01-JAN-1984 01-MAR-1980 01-JAN-1984 ... 01-OCT-1983 01-JAN-1984 01-NOV-1983 01-JAN-1984 01-DEC-1983 01-JAN-1984 At this point, you have all the months you need, and you can simply outer join to EMP.HIREDATE. Because the day for each START_DATE is the first of the month, truncate EMP.HIREDATE to the first day of its month. Finally, use the aggregate function COUNT on EMP.HIREDATE. #### Oracle The first step is to generate the first day of every for every month from 1980 to 1983. Start by using TRUNC and ADD_MONTHS together with the MIN and MAX HIREDATE values to find the boundary months: **select min(trunc(hiredate,'y')) start_date,** **add_months(max(trunc(hiredate,'y')),12) end_date** **from emp** START_DATE END_DATE ----------- ----------- 01-JAN-1980 01-JAN-1984 Then repeatedly add months to START_DATE to return all the months necessary for the final result set. The value for END_DATE is one day more than it should be, which is OK. As you recursively add months to START_DATE, you can stop before you hit END_DATE. A portion of the months created is shown below: **with x as (** **select add_months(start_date,level-1) start_date** **from (** **select min(trunc(hiredate,'y')) start_date,** **add_months(max(trunc(hiredate,'y')),12) end_date** **from emp** **)** **connect by level<= months_between(end_date,start_date)** **)** **select *** **from x** START_DATE ----------- 01-JAN-1980 01-FEB-1980 01-MAR-1980 ... 01-OCT-1983 01-NOV-1983 01-DEC-1983 At this point, you have all the months you need; simply outer join to EMP.HIREDATE. Because the day for each START_DATE is the first of the month, truncate EMP.HIREDATE to the first day of the month it is in. The final step is to use the aggregate function COUNT on EMP.HIREDATE. #### PostgreSQL This solution uses the function GENERATE_SERIES to return the months you need. If you do not have the GENERATE_SERIES function available, you can use a pivot table as in the MySQL solution. The first step is to understand view V. View V simply finds the number of months you'll need to generate by finding the boundary dates for the range. Inline view X in view V uses the MIN and MAX HIREDATEs to find the start and end boundary dates and is shown below: **select cast(date_trunc('year',min(hiredate)) as date) as first_month,** **cast(cast(date_trunc('year',max(hiredate))** **as date) + interval '1 year'** **as date) as last_month** **from emp** FIRST_MONTH LAST_MONTH ----------- ----------- 01-JAN-1980 01-JAN-1984 The value for LAST_MONTH is actually one day more than it should be. This is fine, as you can just subtract 1 when you calculate the months between these two dates. The next step is to use the AGE function to find the difference between the two dates in years, then multiply by 12 (and remember, subtract by 1!): **select cast(** **extract(year from age(last_month,first_month))*12-1** **as integer) as mths** **from (** **select cast(date_trunc('year',min(hiredate)) as date) as first_month,** **cast(cast(date_trunc('year',max(hiredate))** **as date) + interval '1 year'** **as date) as last_month** **from emp** **) x** MTHS ---- 47 Use the value returned by view V as the second parameter of GENERATE_SERIES to return the number of months you need. Your next step is then to find your start date. You'll repeatedly add months to your start date to create your range of months. Inline view Y uses the DATE_TRUNC function on the MIN(HIREDATE) to find the start date, and uses the values returned by GENERATE_SERIES to add months. Partial results are shown below: **select cast(e.start_date + (x.id * interval '1 month')** **as date) as mth** **from generate_series (0,(select mths from v)) x(id),** **( select cast(** **date_trunc('year',min(hiredate))** **as date) as start_date** **from emp** **) e** MTH ----------- 01-JAN-1980 01-FEB-1980 01-MAR-1980 ... 01-OCT-1983 01-NOV-1983 01-DEC-1983 Now that you have each month you need for the final result set, outer join to EMP. HIREDATE and use the aggregate function COUNT to count the number of hires for each month. #### MySQL First, find the boundary dates by using the aggregate functions MIN and MAX along with the DAYOFYEAR and ADDDATE functions. The result set shown below is from inline view X: **select adddate(min(hiredate),-dayofyear(min(hiredate))+1) min_hd,** **adddate(max(hiredate),-dayofyear(max(hiredate))+1) max_hd** **from emp** MIN_HD MAX_HD ----------- ----------- 01-JAN-1980 01-JAN-1983 Next, increment MAX_HD to the last month of the year: **select min_hd, date_add(max_hd,interval 11 month) max_hd** **from (** **select adddate(min(hiredate),-dayofyear(min(hiredate))+1) min_hd,** **adddate(max(hiredate),-dayofyear(max(hiredate))+1) max_hd** **from emp** **) x** MIN_HD MAX_HD ----------- ----------- 01-JAN-1980 01-DEC-1983 Now that you have the boundary dates, add months to MIN_HD up to and including MAX_HD by using pivot table T500 to generate the rows you need. A portion of the results is shown below: **select date_add(min_hd,interval t500.id-1 month) mth** **from (** **select min_hd, date_add(max_hd,interval 11 month) max_hd** **from (** **select adddate(min(hiredate),-dayofyear(min(hiredate))+1) min_hd,** **adddate(max(hiredate),-dayofyear(max(hiredate))+1) max_hd** **from emp** **) x** **) y,** **t500** **where date_add(min_hd,interval t500.id-1 month)<= max_hd** MTH ----------- 01-JAN-1980 01-FEB-1980 01-MAR-1980 ... 01-OCT-1983 01-NOV-1983 01-DEC-1983 Now that you have all the months you need for the final result set, outer join to EMP.HIREDATE (be sure to truncate EMP.HIREDATE to the first day of the month) and use the aggregate function COUNT on EMP.HIREDATE to count the number of hires in each month. #### SQL Server Begin by generating every month (actually, the first day of each month) from 1980 to 1983. Then find the boundary months by applying the DAYOFYEAR function to the MIN and MAX HIREDATEs: **select (min(hiredate) -** **datepart(dy,min(hiredate))+1) start_date,** **dateadd(yy,1,** **(max(hiredate) -** **datepart(dy,max(hiredate))+1)) end_date** **from emp** START_DATE END_DATE ----------- ----------- 01-JAN-1980 01-JAN-1984 Your next step is to repeatedly add months to START_DATE to return all the months necessary for the final result set. The value for END_DATE is one day more than it should be, which is OK, as you can stop recursively adding months to START_DATE before you hit END_DATE. A portion of the months created is shown below: **with x (start_date,end_date)** **as (** **select (min(hiredate) -** **datepart(dy,min(hiredate))+1) start_date,** **dateadd(yy,1,** **(max(hiredate) -** **datepart(dy,max(hiredate))+1)) end_date** **from emp** **union all** **select dateadd(mm,1,start_date), end_date** **from x** **where dateadd(mm,1,start_date)< end_date** **)** **select *** **from x** START_DATE END_DATE ----------- ----------- 01-JAN-1980 01-JAN-1984 01-FEB-1980 01-JAN-1984 01-MAR-1980 01-JAN-1984 ... 01-OCT-1983 01-JAN-1984 01-NOV-1983 01-JAN-1984 01-DEC-1983 01-JAN-1984 At this point, you have all the months you need. Simply outer join to EMP.HIREDATE. Because the day for each START_DATE is the first of the month, truncate EMP.HIREDATE to the first day of the month. The final step is to use the aggregate function COUNT on EMP.HIREDATE. ## 9.11. Searching on Specific Units of Time ### Problem You want to search for dates that match a given month, or day of the week, or some other unit of time. For example, you want to find all employees hired in February or December, as well as employees hired on a Tuesday. ### Solution Use the functions supplied by your RDBMS to find month and weekday names for dates. This particular recipe can be useful in various places. Consider, if you wanted to search HIREDATEs but wanted to ignore the year by extracting the month (or any other part of the HIREDATE you are interested in), you can do so. The example solutions to this problem search by month and weekday name. By studying the date formatting functions provided by your RDBMS, you can easily modify these solutions to search by year, quarter, combination of year and quarter, month and year combination, etc. #### DB2 and MySQL Use the functions MONTHNAME and DAYNAME to find the name of the month and weekday an employee was hired, respectively: 1 select ename 2 from emp 3 where monthname(hiredate) in ('February','December') 4 or dayname(hiredate) = 'Tuesday' #### Oracle and PostgreSQL Use the function TO_CHAR to find the names of the month and weekday an employee was hired. Use the function RTRIM to remove trailing whitespaces: 1 select ename 2 from emp 3 where rtrim(to_char(hiredate,'month')) in ('february','december') 4 or rtrim(to_char(hiredate,'day')) = 'tuesday' #### SQL Server Use the function DATENAME to find the names of the month and weekday an employee was hired: 1 select ename 2 from emp 3 where datename(m,hiredate) in ('February','December') 4 or datename(dw,hiredate) = 'Tuesday' ### Discussion The key to each solution is simply knowing which functions to use and how to use them. To verify what the return values are, put the functions in the SELECT clause and examine the output. Listed below is the result set for employees in DEPTNO 10 (using SQL Server syntax): **select ename,datename(m,hiredate) mth,datename(dw,hiredate) dw** **from emp** **where deptno = 10** ENAME MTH DW ------ --------- ----------- CLARK June Tuesday KING November Tuesday MILLER January Saturday Once you know what the function(s) return, finding rows using the functions shown in each of the solutions is easy. ## 9.12. Comparing Records Using Specific Parts of a Date ### Problem You want to find which employees have been hired on the same month and weekday. For example, if an employee was hired on Monday, March 10, 1988, and another employee was hired on Monday, March 2, 2001, you want those two to come up as a match since the day of week and month match. In table EMP, only three employees meet this requirement. You want to return the following result set: MSG ------------------------------------------------------ JAMES was hired on the same month and weekday as FORD SCOTT was hired on the same month and weekday as JAMES SCOTT was hired on the same month and weekday as FORD ### Solution Because you want to compare one employee's HIREDATE with the HIREDATE of the other employees, you will need to self join table EMP. That makes each possible combination of HIREDATEs available for you to compare. Then, simply extract the weekday and month from each HIREDATE and compare. #### DB2 After self joining table EMP, use the function DAYOFWEEK to return the numeric day of the week. Use the function MONTHNAME to return the name of the month: 1 select a.ename || 2 ' was hired on the same month and weekday as '|| 3 b.ename msg 4 from emp a, emp b 5 where (dayofweek(a.hiredate),monthname(a.hiredate)) = 6 (dayofweek(b.hiredate),monthname(b.hiredate)) 7 and a.empno < b.empno 8 order by a.ename #### Oracle and PostgreSQL After self joining table EMP, use the TO_CHAR function to format the HIREDATE into weekday and month for comparison: 1 select a.ename || 2 ' was hired on the same month and weekday as '|| 3 b.ename as msg 4 from emp a, emp b 5 where to_char(a.hiredate,'DMON') = 6 to_char(b.hiredate,'DMON') 7 and a.empno < b.empno 8 order by a.ename #### MySQL After self joining table EMP, use the DATE_FORMAT function to format the HIREDATE into weekday and month for comparison: 1 select concat(a.ename, 2 ' was hired on the same month and weekday as ', 3 b.ename) msg 4 from emp a, emp b 5 where date_format(a.hiredate,'%w%M') = 6 date_format(b.hiredate,'%w%M') 7 and a.empno < b.empno 8 order by a.ename #### SQL Server After self joining table EMP, use the DATENAME function to format the HIREDATE into weekday and month for comparison: 1 select a.ename + 2 ' was hired on the same month and weekday as '+ 3 b.ename msg 4 from emp a, emp b 5 where datename(dw,a.hiredate) = datename(dw,b.hiredate) 6 and datename(m,a.hiredate) = datename(m,b.hiredate) 7 and a.empno < b.empno 8 order by a.ename ### Discussion The only difference between the solutions is the date function used to format the HIREDATE. I'm going to use the Oracle/PostgreSQL solution in this discussion (because it's the shortest to type out), but the explanation holds true for the other solutions as well. The first step is to self join EMP so that each employee has access to the other employees' HIREDATEs. Consider the results of the query below (filtered for SCOTT): **select a.ename as scott, a.hiredate as scott_hd,** **b.ename as other_emps, b.hiredate as other_hds** **from emp a, emp b** **where a.ename = 'SCOTT'** **and a.empno != b.empno** SCOTT SCOTT_HD OTHER_EMPS OTHER_HDS ---------- ----------- ---------- ----------- SCOTT 09-DEC-1982 SMITH 17-DEC-1980 SCOTT 09-DEC-1982 ALLEN 20-FEB-1981 SCOTT 09-DEC-1982 WARD 22-FEB-1981 SCOTT 09-DEC-1982 JONES 02-APR-1981 SCOTT 09-DEC-1982 MARTIN 28-SEP-1981 SCOTT 09-DEC-1982 BLAKE 01-MAY-1981 SCOTT 09-DEC-1982 CLARK 09-JUN-1981 SCOTT 09-DEC-1982 KING 17-NOV-1981 SCOTT 09-DEC-1982 TURNER 08-SEP-1981 SCOTT 09-DEC-1982 ADAMS 12-JAN-1983 SCOTT 09-DEC-1982 JAMES 03-DEC-1981 SCOTT 09-DEC-1982 FORD 03-DEC-1981 SCOTT 09-DEC-1982 MILLER 23-JAN-1982 By self-joining table EMP, you can compare SCOTT's HIREDATE to the HIREDATE of all the other employees. The filter on EMPNO is so that SCOTT's HIREDATE is not returned as one of the OTHER_HDS. The next step is to use your RDBMS's supplied date formatting function(s) to compare the weekday and month of the HIREDATEs and keep only those that match: **select a.ename as emp1, a.hiredate as emp1_hd,** **b.ename as emp2, b.hiredate as emp2_hd** **from emp a, emp b** **where to_char(a.hiredate,'DMON') =** **to_char(b.hiredate,'DMON')** **and a.empno != b.empno** **order by 1** EMP1 EMP1_HD EMP2 EMP2_HD ---------- ----------- ---------- ----------- FORD 03-DEC-1981 SCOTT 09-DEC-1982 FORD 03-DEC-1981 JAMES 03-DEC-1981 JAMES 03-DEC-1981 SCOTT 09-DEC-1982 JAMES 03-DEC-1981 FORD 03-DEC-1981 SCOTT 09-DEC-1982 JAMES 03-DEC-1981 SCOTT 09-DEC-1982 FORD 03-DEC-1981 At this point, the HIREDATEs are correctly matched, but there are six rows in the result set rather than the three in the "Problem" section of this recipe. The reason for the extra rows is the filter on EMPNO. By using "not equals" you do not filter out the reciprocals. For example, the first row matches FORD and SCOTT and the last row matches SCOTT and FORD. The six rows in the result set are technically accurate but redundant. To remove the redundancy use "less than" (the HIREDATEs are removed to bring the intermediate queries closer to the final result set): **select a.ename as emp1, b.ename as emp2** **from emp a, emp b** **where to_char(a.hiredate,'DMON') =** **to_char(b.hiredate,'DMON')** **and a.empno< b.empno** **order by 1** EMP1 EMP2 ---------- ---------- JAMES FORD SCOTT JAMES SCOTT FORD The final step is to simply concatenate the result set to form the message. ## 9.13. Identifying Overlapping Date Ranges ### Problem You want to find all instances of an employee starting a new project before ending an existing project. Consider table EMP_PROJECT: **select *** **from emp_project** EMPNO ENAME PROJ_ID PROJ_START PROJ_END ----- ---------- ------- ----------- ----------- 7782 CLARK 1 16-JUN-2005 18-JUN-2005 7782 CLARK 4 19-JUN-2005 24-JUN-2005 7782 CLARK 7 22-JUN-2005 25-JUN-2005 7782 CLARK 10 25-JUN-2005 28-JUN-2005 7782 CLARK 13 28-JUN-2005 02-JUL-2005 7839 KING 2 17-JUN-2005 21-JUN-2005 7839 KING 8 23-JUN-2005 25-JUN-2005 7839 KING 14 29-JUN-2005 30-JUN-2005 7839 KING 11 26-JUN-2005 27-JUN-2005 7839 KING 5 20-JUN-2005 24-JUN-2005 7934 MILLER 3 18-JUN-2005 22-JUN-2005 7934 MILLER 12 27-JUN-2005 28-JUN-2005 7934 MILLER 15 30-JUN-2005 03-JUL-2005 7934 MILLER 9 24-JUN-2005 27-JUN-2005 7934 MILLER 6 21-JUN-2005 23-JUN-2005 Looking at the results for employee KING, you see that KING began PROJ_ID 8 before finishing PROJ_ID 5 and began PROJ_ID 5 before finishing PROJ_ID 2. You want to return the following result set: EMPNO ENAME MSG ----- ---------- -------------------------------- 7782 CLARK project 7 overlaps project 4 7782 CLARK project 10 overlaps project 7 7782 CLARK project 13 overlaps project 10 7839 KING project 8 overlaps project 5 7839 KING project 5 overlaps project 2 7934 MILLER project 12 overlaps project 9 7934 MILLER project 6 overlaps project 3 ### Solution The key here is to find rows where PROJ_START (the date the new project starts) occurs on or after another project's PROJ_START date and on or before that other project's PROJ_END date. To begin, you need to be able to compare each project with each other project (for the same employee). By self joining EMP_PROJECT on employee, you generate every possible combination of two projects for each employee. To find the overlaps, simply find the rows where PROJ_START for any PROJ_ID falls between PROJ_START and PROJ_END for another PROJ_ID by the same employee. #### DB2, PostgreSQL, and Oracle Self join EMP_PROJECT. Then use the concatenation operator "||" to construct the message that explains which projects overlap: 1 select a.empno,a.ename, 2 'project '||b.proj_id|| 3 ' overlaps project '||a.proj_id as msg 4 from emp_project a, 5 emp_project b 6 where a.empno = b.empno 7 and b.proj_start >= a.proj_start 8 and b.proj_start <= a.proj_end 9 and a.proj_id != b.proj_id #### MySQL Self join EMP_PROJECT. Then use the CONCAT function to construct the message that explains which projects overlap: 1 select a.empno,a.ename, 2 concat('project ',b.proj_id, 3 ' overlaps project ',a.proj_id) as msg 4 from emp_project a, 5 emp_project b 6 where a.empno = b.empno 7 and b.proj_start >= a.proj_start 8 and b.proj_start <= a.proj_end 9 and a.proj_id != b.proj_id #### SQL Server Self join EMP_PROJECT. Then use the concatenation operator "+" to construct the message that explains which projects overlap: 1 select a.empno,a.ename, 2 'project '+b.proj_id+ 3 ' overlaps project '+a.proj_id as msg 4 from emp_project a, 5 emp_project b 6 where a.empno = b.empno 7 and b.proj_start >= a.proj_start 8 and b.proj_start <= a.proj_end 9 and a.proj_id != b.proj_id ### Discussion The only difference between the solutions lies in the string concatenation, so one discussion using the DB2 syntax will cover all three solutions. The first step is a self join of EMP_PROJECT so that the PROJ_START dates can be compared amongst the different projects. The output of the self join for employee KING is shown below. You can observe how each project can "see" the other projects: **select a.ename,** **a.proj_id as a_id,** **a.proj_start as a_start,** **a.proj_end as a_end,** **b.proj_id as b_id,** **b.proj_start as b_start** **from emp_project a,** **emp_project b** **where a.ename = 'KING'** **and a.empno = b.empno** **and a.proj_id != b.proj_id** **order by 2** ENAME A_ID A_START A_END B_ID B_START ------ ----- ----------- ----------- ----- ----------- KING 2 17-JUN-2005 21-JUN-2005 8 23-JUN-2005 KING 2 17-JUN-2005 21-JUN-2005 14 29-JUN-2005 KING 2 17-JUN-2005 21-JUN-2005 11 26-JUN-2005 KING 2 17-JUN-2005 21-JUN-2005 5 20-JUN-2005 KING 5 20-JUN-2005 24-JUN-2005 2 17-JUN-2005 KING 5 20-JUN-2005 24-JUN-2005 8 23-JUN-2005 KING 5 20-JUN-2005 24-JUN-2005 11 26-JUN-2005 KING 5 20-JUN-2005 24-JUN-2005 14 29-JUN-2005 KING 8 23-JUN-2005 25-JUN-2005 2 17-JUN-2005 KING 8 23-JUN-2005 25-JUN-2005 14 29-JUN-2005 KING 8 23-JUN-2005 25-JUN-2005 5 20-JUN-2005 KING 8 23-JUN-2005 25-JUN-2005 11 26-JUN-2005 KING 11 26-JUN-2005 27-JUN-2005 2 17-JUN-2005 KING 11 26-JUN-2005 27-JUN-2005 8 23-JUN-2005 KING 11 26-JUN-2005 27-JUN-2005 14 29-JUN-2005 KING 11 26-JUN-2005 27-JUN-2005 5 20-JUN-2005 KING 14 29-JUN-2005 30-JUN-2005 2 17-JUN-2005 KING 14 29-JUN-2005 30-JUN-2005 8 23-JUN-2005 KING 14 29-JUN-2005 30-JUN-2005 5 20-JUN-2005 KING 14 29-JUN-2005 30-JUN-2005 11 26-JUN-2005 As you can see from the result set above, the self join makes finding overlapping dates easy; simply return each row where B_START occurs between A_START and A_END. If you look at the WHERE clause on lines 7 and 8 of the solution: and b.proj_start >= a.proj_start and b.proj_start <= a.proj_end it is doing just that. Once you have the required rows, constructing the messages is just a matter of concatenating the return values. Oracle users can use the window function LEAD OVER to avoid the self join, if the maximum number of projects per employee is fixed. This can come in handy if the self join is expensive for your particular results (if the self join requires more resources than the sorts needed for LEAD OVER). For example, consider the alternative for employee KING using LEAD OVER: **select empno,** **ename,** **proj_id,** **proj_start,** **proj_end,** **case** **when lead(proj_start,1)over(order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(order by proj_start)** **when lead(proj_start,2)over(order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(order by proj_start)** **when lead(proj_start,3)over(order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(order by proj_start)** **when lead(proj_start,4)over(order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(order by proj_start)** **end is_overlap** **from emp_project** **where ename = 'KING'** EMPNO ENAME PROJ_ID PROJ_START PROJ_END IS_OVERLAP ----- ------ ------- ----------- ----------- ---------- 7839 KING 2 17-JUN-2005 21-JUN-2005 5 7839 KING 5 20-JUN-2005 24-JUN-2005 8 7839 KING 8 23-JUN-2005 25-JUN-2005 7839 KING 11 26-JUN-2005 27-JUN-2005 7839 KING 14 29-JUN-2005 30-JUN-2005 Because the number of projects is fixed at five for employee KING, you can use LEAD OVER to move examine the dates of all the projects without a self join. From here, producing the final result set is easy. Simply keep the rows where IS_OVERLAP is not NULL: **select empno,ename,** **'project '||is_overlap||** **' overlaps project '||proj_id msg** **from (** **select empno,** **ename,** **proj_id,** **proj_start,** **proj_end,** **case** **when lead(proj_start,1)over(order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(order by proj_start)** **when lead(proj_start,2)over(order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(order by proj_start)** **when lead(proj_start,3)over(order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(order by proj_start)** **when lead(proj_start,4)over(order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(order by proj_start)** **end is_overlap** **from emp_project** **where ename = 'KING'** **)** **where is_overlap is not null** EMPNO ENAME MSG ----- ------ -------------------------------- 7839 KING project 5 overlaps project 2 7839 KING project 8 overlaps project 5 To allow the solution to work for all employees (not just KING), partition by ENAME in the LEAD OVER function: **select empno,ename,** **'project '||is_overlap||** **' overlaps project '||proj_id msg** **from (** **select empno,** **ename,** **proj_id,** **proj_start,** **proj_end,** **case** **when lead(proj_start,1)over(partition by ename** **order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(partition by ename** **order by proj_start)** **when lead(proj_start,2)over(partition by ename** **order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(partition by ename** **order by proj_start)** **when lead(proj_start,3)over(partition by ename** **order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(partition by ename** **order by proj_start)** **when lead(proj_start,4)over(partition by ename** **order by proj_start)** **between proj_start and proj_end** **then lead(proj_id)over(partition by ename** **order by proj_start)** **end is_overlap** **from emp_project** **)** **where is_overlap is not null** EMPNO ENAME MSG ----- ------ ------------------------------- 7782 CLARK project 7 overlaps project 4 7782 CLARK project 10 overlaps project 7 7782 CLARK project 13 overlaps project 10 7839 KING project 5 overlaps project 2 7839 KING project 8 overlaps project 5 7934 MILLER project 6 overlaps project 3 7934 MILLER project 12 overlaps project 9 ## Chapter 10. Working with Ranges This chapter is about "everyday" queries that involve ranges. Ranges are common in everyday life. For example, projects that we work on range over consecutive periods of time. In SQL, it's often necessary to search for ranges, or to generate ranges, or to otherwise manipulate range-based data. The queries you'll read about here are slightly more involved than the queries found in the preceding chapters, but they are just as common, and they'll begin to give you a sense of what SQL can really do for you when you learn to take full advantage of it. ## 10.1. Locating a Range of Consecutive Values ### Problem You want to determine which rows represent a range of consecutive projects. Consider the following result set from view V, which contains data about a project and its start and end dates: select * from V PROJ_ID PROJ_START PROJ_END ------- ----------- ----------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 3 03-JAN-2005 04-JAN-2005 4 04-JAN-2005 05-JAN-2005 5 06-JAN-2005 07-JAN-2005 6 16-JAN-2005 17-JAN-2005 7 17-JAN-2005 18-JAN-2005 8 18-JAN-2005 19-JAN-2005 9 19-JAN-2005 20-JAN-2005 10 21-JAN-2005 22-JAN-2005 11 26-JAN-2005 27-JAN-2005 12 27-JAN-2005 28-JAN-2005 13 28-JAN-2005 29-JAN-2005 14 29-JAN-2005 30-JAN-2005 Excluding the first row, each row's PROJ_START should equal the PROJ_END of the row before it ("before" is defined as PROJ_ID–1 for the current row). Examining the first five rows from view V, PROJ_IDs 1 through 3 are part of the same "group" as each PROJ_END equals the PROJ_START of the row after it. Because you want to find the range of dates for consecutive projects, you would like to return all rows where the current PROJ_END equals the next row's PROJ_START. If the first five rows comprised the entire result set, you would like to return only the first three rows. The final result set (using all 14 rows from view V) should be: PROJ_ID PROJ_START PROJ_END ------- ----------- ----------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 3 03-JAN-2005 04-JAN-2005 6 16-JAN-2005 17-JAN-2005 7 17-JAN-2005 18-JAN-2005 8 18-JAN-2005 19-JAN-2005 11 26-JAN-2005 27-JAN-2005 12 27-JAN-2005 28-JAN-2005 13 28-JAN-2005 29-JAN-2005 The rows with PROJ_IDs 4,5,9,10, and 14 are excluded from this result set because the PROJ_END of each of these rows does not match the PROJ_START of the row following it. ### Solution #### DB2, MySQL, PostgreSQL, and SQL Server Use a self join to find the rows with consecutive values: 1 select v1.proj_id, 2 v1.proj_start, 3 v1.proj_end 4 from V v1, V v2 5 where v1.proj_end = v2.proj_start #### Oracle The preceding solution will also work for Oracle. Alternatively, here is another solution that takes advantage of the window function LEAD OVER to look at the "next" row's BEGIN_DATE, thus avoiding the need to self join: 1 select proj_id, proj_start, proj_end 2 from ( 3 select proj_id, proj_start, proj_end, 4 lead(proj_start)over(order by proj_id) next_proj_start 5 from V 6 ) 7 where next_proj_start = proj_end ### Discussion #### DB2, MySQL, PostgreSQL, and SQL Server By self joining the view to itself, each row can be compared to every other row returned. Consider a partial result set for IDs 1 and 4: **select v1.proj_id as v1_id,** **v1.proj_end as v1_end,** **v2.proj_start as v2_begin,** **v2.proj_id as v2_id** **from v v1, v v2** **where v1.proj_id in ( 1, 4 )** V1_ID V1_END V2_BEGIN V2_ID ----- ----------- ----------- ---------- 1 02-JAN-2005 01-JAN-2005 1 1 02-JAN-2005 02-JAN-2005 2 1 02-JAN-2005 03-JAN-2005 3 1 02-JAN-2005 04-JAN-2005 4 1 02-JAN-2005 06-JAN-2005 5 1 02-JAN-2005 16-JAN-2005 6 1 02-JAN-2005 17-JAN-2005 7 1 02-JAN-2005 18-JAN-2005 8 1 02-JAN-2005 19-JAN-2005 9 1 02-JAN-2005 21-JAN-2005 10 1 02-JAN-2005 26-JAN-2005 11 1 02-JAN-2005 27-JAN-2005 12 1 02-JAN-2005 28-JAN-2005 13 1 02-JAN-2005 29-JAN-2005 14 4 05-JAN-2005 01-JAN-2005 1 4 05-JAN-2005 02-JAN-2005 2 4 05-JAN-2005 03-JAN-2005 3 4 05-JAN-2005 04-JAN-2005 4 4 05-JAN-2005 06-JAN-2005 5 4 05-JAN-2005 16-JAN-2005 6 4 05-JAN-2005 17-JAN-2005 7 4 05-JAN-2005 18-JAN-2005 8 4 05-JAN-2005 19-JAN-2005 9 4 05-JAN-2005 21-JAN-2005 10 4 05-JAN-2005 26-JAN-2005 11 4 05-JAN-2005 27-JAN-2005 12 4 05-JAN-2005 28-JAN-2005 13 4 05-JAN-2005 29-JAN-2005 14 Examining this result set, you can see why PROJ_ID 1 is included in the final result set and PROJ_ID 4 is not: there is no corresponding V2_BEGIN value for the V1_ END value returned for V1_ID 4. Depending on how you view the data, PROJ_ID 4 can just as easily be considered contiguous. Consider the following result set: **select *** **from V** **where proj_id<= 5** PROJ_ID PROJ_START PROJ_END ------- ---------- ----------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 3 03-JAN-2005 04-JAN-2005 4 04-JAN-2005 05-JAN-2005 5 06-JAN-2005 07-JAN-2005 If "contiguous" is defined as a project that starts the same day another project ends, then PROJ_ID 4 should be included in the result set. PROJ_ID 4 was originally eliminated because of the forward comparison (comparing its PROJ_END with the next PROJ_START), but if you do a backwards comparison (PROJ_START with the prior PROJ_END), then PROJ_ID 4 will be included in the result set. Modifying the solution to include PROJ_ID 4 is trivial: simply add an additional predicate to ensure that both PROJ_START and PROJ_END are checked for being contiguous, not just PROJ_END. The modification shown in the following query produces a result set that includes PROJ_ID 4 (DISTINCT is necessary because some rows satisfy both predicate conditions): **select distinct** **v1.proj_id,** **v1.proj_start,** **v1.proj_end** **from V v1, V v2** **where v1.proj_end = v2.proj_start** **or v1.proj_start = v2.proj_end** PROJ_ID PROJ_START PROJ_END ------- ----------- ----------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 3 03-JAN-2005 04-JAN-2005 4 04-JAN-2005 05-JAN-2005 #### Oracle While the self-join solution certainly works, the window function LEAD OVER is perfect for this type of problem. The function LEAD OVER allows you to examine other rows without performing a self join (though the function must impose order on the result set to do so). Consider the results of the inline view (lines 3–5) for IDs 1 and 4: **select *** **from (** **select proj_id, proj_start, proj_end,** **lead(proj_start)over(order by proj_id) next_proj_start** **from v** **)** **where proj_id in ( 1, 4 )** PROJ_ID PROJ_START PROJ_END NEXT_PROJ_START ------- ----------- ----------- --------------- 1 01-JAN-2005 02-JAN-2005 02-JAN-2005 4 04-JAN-2005 05-JAN-2005 06-JAN-2005 Examining the above snippet of code and its result set, it is particularly easy to see why PROJ_ID 4 is excluded from the final result set of the complete solution. It's excluded because its PROJ_END date of 05-JAN-2005 does not match the "next" project's start date of 06-JAN-2005. The function LEAD OVER is extremely handy when it comes to problems such as this one, particularly when examining partial results. When working with window functions, keep in mind that they are evaluated after the FROM and WHERE clauses, so the LEAD OVER function in the preceding query must be embedded within an inline view. Otherwise the LEAD OVER function is applied to the result set after the WHERE clause has filtered out all rows except for PROJ_ID's 1 and 4. Now, depending on how you view the data, you may very well want to include PROJ_ID 4 in the final result set. Consider the first five rows from view V: **select *** **from V** **where proj_id<= 5** PROJ_ID PROJ_START PROJ_END ------- ----------- ----------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 3 03-JAN-2005 04-JAN-2005 4 04-JAN-2005 05-JAN-2005 5 06-JAN-2005 07-JAN-2005 If your requirement is such that PROJ_ID 4 is in fact contiguous (because PROJ_ START for PROJ_ID 4 matches PROJ_END for PROJ_ID 3), and that only PROJ_ ID 5 should be discarded, the proposed solution for this recipe is incorrect (!), or at the very least, incomplete: **select proj_id, proj_start, proj_end** **from (** **select proj_id, proj_start, proj_end,** **lead(proj_start)over(order by proj_id) next_start** **from V** **where proj_id<= 5** **)** **where proj_end = next_start** PROJ_ID PROJ_START PROJ_END ------- ----------- ----------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 3 03-JAN-2005 04-JAN-2005 If you believe PROJ_ID 4 should be included, simply add LAG OVER to the query and use an additional filter in the WHERE clause: **select proj_id, proj_start, proj_end** **from (** **select proj_id, proj_start, proj_end,** **lead(proj_start)over(order by proj_id) next_start,** **lag(proj_end)over(order by proj_id) last_end** **from V** **where proj_id<= 5** **)** **where proj_end = next_start** **or proj_start = last_end** PROJ_ID PROJ_START PROJ_END ------- ----------- ----------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 3 03-JAN-2005 04-JAN-2005 4 04-JAN-2005 05-JAN-2005 Now PROJ_ID 4 is included in the final result set, and only the evil PROJ_ID 5 is excluded. Please consider your exact requirements when applying these recipes to your code. ## 10.2. Finding Differences Between Rows in the Same Group or Partition ### Problem You want to return the DEPTNO, ENAME, and SAL of each employee along with the difference in SAL between employees in the same department (i.e., having the same value for DEPTNO). The difference should be between each current employee and the employee hired immediately afterwards (you want to see if there is a correlation between seniority and salary on a "per department" basis). For each employee hired last in his department, return "N/A" for the difference. The result set should look like this: DEPTNO ENAME SAL HIREDATE DIFF ------ ---------- ---------- ----------- ---------- 10 CLARK 2450 09-JUN-1981 -2550 10 KING 5000 17-NOV-1981 3700 10 MILLER 1300 23-JAN-1982 N/A 20 SMITH 800 17-DEC-1980 -2175 20 JONES 2975 02-APR-1981 -25 20 FORD 3000 03-DEC-1981 0 20 SCOTT 3000 09-DEC-1982 1900 20 ADAMS 1100 12-JAN-1983 N/A 30 ALLEN 1600 20-FEB-1981 350 30 WARD 1250 22-FEB-1981 -1600 30 BLAKE 2850 01-MAY-1981 1350 30 TURNER 1500 08-SEP-1981 250 30 MARTIN 1250 28-SEP-1981 300 30 JAMES 950 03-DEC-1981 N/A ### Solution The is another example of where the Oracle window functions LEAD OVER and LAG OVER come in handy. You can easily access next and prior rows without additional joins. For other RDBMSs, you can use scalar subqueries, though not as easily. This particular problem is not at all elegant when having to use scalar subqueries or self joins to solve it. #### DB2, MySQL, PostgreSQL, and SQL Server Use a scalar subquery to retrieve the HIREDATE of the employee hired immediately after each employee. Then use another scalar subquery to find the salary of said employee: 1 select deptno, ename, hiredate, sal, 2 coalesce(cast(sal-next_sal as char(10)), 'N/A') as diff 3 from ( 4 select e.deptno, 5 e.ename, 6 e.hiredate, 7 e.sal, 8 (select min(sal) from emp d 9 where d.deptno=e.deptno 10 and d.hiredate = 11 (select min(hiredate) from emp d 12 where e.deptno=d.deptno 13 and d.hiredate > e.hiredate)) as next_sal 14 from emp e 15 ) x #### Oracle Use the window function LEAD OVER to access the "next" employee's salary relative to the current row: 1 select deptno, ename, sal, hiredate, 2 lpad(nvl(to_char(sal-next_sal), 'N/A'), 10) diff 3 from ( 4 select deptno, ename, sal, hiredate, 5 lead(sal)over(partition by deptno 6 order by hiredate) next_sal 7 from emp 8 ) ### Discussion #### DB2, MySQL, PostgreSQL, and SQL Server The first step is to use a scalar subquery to find the HIREDATE of the employee hired immediately after each employee in the same department. The solution uses MIN(HIREDATE) in the scalar subquery to ensure that only one value is returned even in the event of multiple people being hired on the same date: **select e.deptno,** **e.ename,** **e.hiredate,** **e.sal,** **(select min(hiredate) from emp d** **where e.deptno=d.deptno** **and d.hiredate> e.hiredate) as next_hire** **from emp e** **order by 1** DEPTNO ENAME HIREDATE SAL NEXT_HIRE ------ ---------- ----------- ---------- ----------- 10 CLARK 09-JUN-1981 2450 17-NOV-1981 10 KING 17-NOV-1981 5000 23-JAN-1982 10 MILLER 23-JAN-1982 1300 20 SMITH 17-DEC-1980 800 02-APR-1981 20 ADAMS 12-JAN-1983 1100 20 FORD 03-DEC-1981 3000 09-DEC-1982 20 SCOTT 09-DEC-1982 3000 12-JAN-1983 20 JONES 02-APR-1981 2975 03-DEC-1981 30 ALLEN 20-FEB-1981 1600 22-FEB-1981 30 BLAKE 01-MAY-1981 2850 08-SEP-1981 30 MARTIN 28-SEP-1981 1250 03-DEC-1981 30 JAMES 03-DEC-1981 950 30 TURNER 08-SEP-1981 1500 28-SEP-1981 30 WARD 22-FEB-1981 1250 01-MAY-1981 The next step is to use another scalar subquery to find the salary of the employee who was hired on the NEXT_HIRE date. Again, the solution uses MIN to ensure that just one value is always returned: **select e.deptno,** **e.ename,** **e.hiredate,** **e.sal,** **(select min(sal) from emp d** **where d.deptno=e.deptno** **and d.hiredate =** **(select min(hiredate) from emp d** **where e.deptno=d.deptno** **and d.hiredate> e.hiredate)) as next_sal** **from emp e** **order by 1** DEPTNO ENAME HIREDATE SAL NEXT_SAL ------ ---------- ----------- ---------- ---------- 10 CLARK 09-JUN-1981 2450 5000 10 KING 17-NOV-1981 5000 1300 10 MILLER 23-JAN-1982 1300 20 SMITH 17-DEC-1980 800 2975 20 ADAMS 12-JAN-1983 1100 20 FORD 03-DEC-1981 3000 3000 20 SCOTT 09-DEC-1982 3000 1100 20 JONES 02-APR-1981 2975 3000 30 ALLEN 20-FEB-1981 1600 1250 30 BLAKE 01-MAY-1981 2850 1500 30 MARTIN 28-SEP-1981 1250 950 30 JAMES 03-DEC-1981 950 30 TURNER 08-SEP-1981 1500 1250 30 WARD 22-FEB-1981 1250 2850 The final step is to find the difference between SAL and NEXT_SAL, and to use the function COALESCE to return "N/A" when applicable. Since the result of the subtraction is a number and can potentially be NULL, you must cast to a string for COALESCE to work: **select deptno, ename, hiredate, sal,** **coalesce(cast(sal-next_sal as char(10)), 'N/A') as diff** **from (** **select e.deptno,** **e.ename,** **e.hiredate,** **e.sal,** **(select min(sal) from emp d** **where d.deptno=e.deptno** **and d.hiredate =** **(select min(hiredate) from emp d** **where e.deptno=d.deptno** **and d.hiredate> e.hiredate)) as next_sal** **from emp e** **) x** **order by 1** DEPTNO ENAME HIREDATE SAL DIFF ------ ---------- ----------- ---------- --------- 10 CLARK 09-JUN-1981 2450 -2550 10 KING 17-NOV-1981 5000 3700 10 MILLER 23-JAN-1982 1300 N/A 20 SMITH 17-DEC-1980 800 -2175 20 ADAMS 12-JAN-1983 1100 N/A 20 FORD 03-DEC-1981 3000 0 20 SCOTT 09-DEC-1982 3000 1900 20 JONES 02-APR-1981 2975 -25 30 ALLEN 20-FEB-1981 1600 350 30 BLAKE 01-MAY-1981 2850 1350 30 MARTIN 28-SEP-1981 1250 300 30 JAMES 03-DEC-1981 950 N/A 30 TURNER 08-SEP-1981 1500 250 30 WARD 22-FEB-1981 1250 -1600 ### Tip The use of MIN(SAL) in this solution is an example of how, in some ways, you can unintentionally inject business logic into a query while making what appears to be a solely technical decision. If multiple salaries are available for a given date, should you take the least? the highest? the average? In my example, I choose to take the least. In real life, I might well punt that decision back to the business client who requested the report to begin with. #### Oracle The first step is to use the LEAD OVER window function to find the "next" salary for each employee within her department. The employees hired last in each department will have a NULL value for NEXT_SAL: **select deptno,ename,sal,hiredate,** **lead(sal)over(partition by deptno order by hiredate) next_sal** **from emp** DEPTNO ENAME SAL HIREDATE NEXT_SAL ------ ---------- ---------- ----------- ---------- 10 CLARK 2450 09-JUN-1981 5000 10 KING 5000 17-NOV-1981 1300 10 MILLER 1300 23-JAN-1982 20 SMITH 800 17-DEC-1980 2975 20 JONES 2975 02-APR-1981 3000 20 FORD 3000 03-DEC-1981 3000 20 SCOTT 3000 09-DEC-1982 1100 20 ADAMS 1100 12-JAN-1983 30 ALLEN 1600 20-FEB-1981 1250 30 WARD 1250 22-FEB-1981 2850 30 BLAKE 2850 01-MAY-1981 1500 30 TURNER 1500 08-SEP-1981 1250 30 MARTIN 1250 28-SEP-1981 950 30 JAMES 950 03-DEC-1981 The next step is to take the difference between each employee's salary and the salary of the employee hired immediately after her in the same department: **select deptno,ename,sal,hiredate, sal-next_sal diff** **from (** **select deptno,ename,sal,hiredate,** **lead(sal)over(partition by deptno order by hiredate) next_sal** **from emp** **)** DEPTNO ENAME SAL HIREDATE DIFF ------ ---------- ---------- ----------- ---------- 10 CLARK 2450 09-JUN-1981 -2550 10 KING 5000 17-NOV-1981 3700 10 MILLER 1300 23-JAN-1982 20 SMITH 800 17-DEC-1980 -2175 20 JONES 2975 02-APR-1981 -25 20 FORD 3000 03-DEC-1981 0 20 SCOTT 3000 09-DEC-1982 1900 20 ADAMS 1100 12-JAN-1983 30 ALLEN 1600 20-FEB-1981 350 30 WARD 1250 22-FEB-1981 -1600 30 BLAKE 2850 01-MAY-1981 1350 30 TURNER 1500 08-SEP-1981 250 30 MARTIN 1250 28-SEP-1981 300 30 JAMES 950 03-DEC-1981 The next step is to use the function NVL to return "N/A" when DIFF is NULL. To be able to return "N/A" you must cast the value of DIFF to a string, otherwise NVL will fail: **select deptno,ename,sal,hiredate,** **nvl(to_char(sal-next_sal),'N/A') diff** **from (** **select deptno,ename,sal,hiredate,** **lead(sal)over(partition by deptno order by hiredate) next_sal** **from emp** **)** DEPTNO ENAME SAL HIREDATE DIFF ------ ---------- ---------- ----------- --------------- 10 CLARK 2450 09-JUN-1981 -2550 10 KING 5000 17-NOV-1981 3700 10 MILLER 1300 23-JAN-1982 N/A 20 SMITH 800 17-DEC-1980 -2175 20 JONES 2975 02-APR-1981 -25 20 FORD 3000 03-DEC-1981 0 20 SCOTT 3000 09-DEC-1982 1900 20 ADAMS 1100 12-JAN-1983 N/A 30 ALLEN 1600 20-FEB-1981 350 30 WARD 1250 22-FEB-1981 -1600 30 BLAKE 2850 01-MAY-1981 1350 30 TURNER 1500 08-SEP-1981 250 30 MARTIN 1250 28-SEP-1981 300 30 JAMES 950 03-DEC-1981 N/A The last step is to use the function LPAD to format the values for DIFF. This is because, by default, numbers are right justified while strings are left justified. Using LPAD, you can right justify all the results in the column: **select deptno,ename,sal,hiredate,** **lpad(nvl(to_char(sal-next_sal),'N/A'),10) diff** **from (** **select deptno,ename,sal,hiredate,** **lead(sal)over(partition by deptno order by hiredate) next_sal** **from emp** **)** DEPTNO ENAME SAL HIREDATE DIFF ------ ---------- ---------- ----------- ---------- 10 CLARK 2450 09-JUN-1981 -2550 10 KING 5000 17-NOV-1981 3700 10 MILLER 1300 23-JAN-1982 N/A 20 SMITH 800 17-DEC-1980 -2175 20 JONES 2975 02-APR-1981 -25 20 FORD 3000 03-DEC-1981 0 20 SCOTT 3000 09-DEC-1982 1900 20 ADAMS 1100 12-JAN-1983 N/A 30 ALLEN 1600 20-FEB-1981 350 30 WARD 1250 22-FEB-1981 -1600 30 BLAKE 2850 01-MAY-1981 1350 30 TURNER 1500 08-SEP-1981 250 30 MARTIN 1250 28-SEP-1981 300 30 JAMES 950 03-DEC-1981 N/A While the majority of the solutions provided in this book do not deal with "what if" scenarios (for the sake of readability and the author's sanity), the scenario involving duplicates when using Oracle's LEAD OVER function in this manner must be discussed. In the simple sample data in table EMP, no employees have duplicate HIREDATEs, yet this is a very likely situation. Normally, I would not discuss a "what if" situation such as duplicates (since there aren't any in table EMP), but the workaround involving LEAD (particularly to those of you with non-Oracle backgrounds) may not be immediately obvious. Consider the following query, which returns the difference in SAL between the employees in DEPTNO 10 (the difference is performed in the order in which they were hired): **select deptno,ename,sal,hiredate,** **lpad(nvl(to_char(sal-next_sal),'N/A'),10) diff** **from (** **select deptno,ename,sal,hiredate,** **lead(sal)over(partition by deptno** **order by hiredate) next_sal** **from emp** **where deptno=10 and empno> 10** **)** DEPTNO ENAME SAL HIREDATE DIFF ------ ------ ----- ----------- ---------- 10 CLARK 2450 09-JUN-1981 -2550 10 KING 5000 17-NOV-1981 3700 10 MILLER 1300 23-JAN-1982 N/A This solution is correct considering the data in table EMP but, if there were duplicate rows, the solution would fail. Consider the example below, showing four more employees hired on the same day as KING: **insert into emp (empno,ename,deptno,sal,hiredate)** **values (1,'ant',10,1000,to_date('17-NOV-1981'))** **insert into emp (empno,ename,deptno,sal,hiredate)** **values (2,'joe',10,1500,to_date('17-NOV-1981'))** **insert into emp (empno,ename,deptno,sal,hiredate)** **values (3,'jim',10,1600,to_date('17-NOV-1981'))** **insert into emp (empno,ename,deptno,sal,hiredate)** **values (4,'jon',10,1700,to_date('17-NOV-1981'))** **select deptno,ename,sal,hiredate,** **lpad(nvl(to_char(sal-next_sal),'N/A'),10) diff** **from (** **select deptno,ename,sal,hiredate,** **lead(sal)over(partition by deptno** **order by hiredate) next_sal** **from emp** **where deptno=10** **)** DEPTNO ENAME SAL HIREDATE DIFF ------ ------ ----- ----------- ---------- 10 CLARK 2450 09-JUN-1981 1450 10 ant 1000 17-NOV-1981 -500 10 joe 1500 17-NOV-1981 -3500 10 KING 5000 17-NOV-1981 3400 10 jim 1600 17-NOV-1981 -100 10 jon 1700 17-NOV-1981 400 10 MILLER 1300 23-JAN-1982 N/A You'll notice that with the exception of employee JON, all employees hired on the same date (November 17) evaluate their salary against another employee hired on the same date! This is incorrect. All employees hired on November 17 should have the difference of salary computed against MILLER's salary, not another employee hired on November 17. Take, for example, employee ANT. The value for DIFF for ANT is–500 because ANT's SAL is compared with JOE's SAL and is 500 less than JOE's SAL, hence the value of–500. The correct value for DIFF for employee ANT should be–300 because ANT makes 300 less than MILLER, who is the next employee hired by HIREDATE. The reason the solution seems to not work is due to the default behavior of Oracle's LEAD OVER function. By default, LEAD OVER only looks ahead one row. So, for employee ANT, the next SAL based on HIREDATE is JOE's SAL, because LEAD OVER simply looks one row ahead and doesn't skip duplicates. Fortunately, Oracle planned for such a situation and allows you to pass an additional parameter to LEAD OVER to determine how far ahead it should look. In the example above, the solution is simply a matter of counting: find the distance from each employee hired on November 17 to January 23 (MILLER's HIREDATE). The solution below shows how to accomplish this: **select deptno,ename,sal,hiredate,** **lpad(nvl(to_char(sal-next_sal),'N/A'),10) diff** **from (** **select deptno,ename,sal,hiredate,** **lead(sal,cnt-rn+1)over(partition by deptno** **order by hiredate) next_sal** **from (** **select deptno,ename,sal,hiredate,** **count(*)over(partition by deptno,hiredate) cnt,** **row_number()over(partition by deptno,hiredate order by sal) rn** **from emp** **where deptno=10** **)** **)** DEPTNO ENAME SAL HIREDATE DIFF ------ ------ ----- ----------- ---------- 10 CLARK 2450 09-JUN-1981 1450 10 ant 1000 17-NOV-1981 -300 10 joe 1500 17-NOV-1981 200 10 jim 1600 17-NOV-1981 300 10 jon 1700 17-NOV-1981 400 10 KING 5000 17-NOV-1981 3700 10 MILLER 1300 23-JAN-1982 N/A Now the solution is correct. As you can see, all the employees hired on November 17 now have their salaries compared with MILLER's salary. Inspecting the results, employee ANT now has a value of–300 for DIFF, which is what we were hoping for. If it isn't immediately obvious, the expression passed to LEAD OVER; CNT-RN+1 is simply the distance from each employee hired on November 17 to MILLER. Consider the inline view below, which shows the values for CNT and RN: **select deptno,ename,sal,hiredate,** **count(*)over(partition by deptno,hiredate) cnt,** **row_number()over(partition by deptno,hiredate order by sal) rn** **from emp** **where deptno=10** DEPTNO ENAME SAL HIREDATE CNT RN ------ ------ ----- ----------- ---------- ---------- 10 CLARK 2450 09-JUN-1981 1 1 10 ant 1000 17-NOV-1981 5 1 10 joe 1500 17-NOV-1981 5 2 10 jim 1600 17-NOV-1981 5 3 10 jon 1700 17-NOV-1981 5 4 10 KING 5000 17-NOV-1981 5 5 10 MILLER 1300 23-JAN-1982 1 1 The value for CNT represents, for each employee with a duplicate HIREDATE, how many duplicates there are in total for their HIREDATE. The value for RN represents a ranking for the employees in DEPTNO 10. The rank is partitioned by DEPTNO and HIREDATE so only employees with a HIREDATE that another employee has will have a value greater than one. The ranking is sorted by SAL (this is arbitrary; SAL is convenient, but we could have just as easily chosen EMPNO). Now that you know how many total duplicates there are and you have a ranking of each duplicate, the distance to MILLER is simply the total number of duplicates minus the current rank plus one (CNT-RN+1). The results of the distance calculation and its effect on LEAD OVER are shown below: **select deptno,ename,sal,hiredate,** **lead(sal)over(partition by deptno** **order by hiredate) incorrect,** **cnt-rn+1 distance,** **lead(sal,cnt-rn+1)over(partition by deptno** **order by hiredate) correct** **from (** **select deptno,ename,sal,hiredate,** **count(*)over(partition by deptno,hiredate) cnt,** **row_number()over(partition by deptno,hiredate** **order by sal) rn** **from emp** **where deptno=10** **)** DEPTNO ENAME SAL HIREDATE INCORRECT DISTANCE CORRECT ------ ------ ----- ----------- ---------- ---------- ---------- 10 CLARK 2450 09-JUN-1981 1000 1 1000 10 ant 1000 17-NOV-1981 1500 5 1300 10 joe 1500 17-NOV-1981 1600 4 1300 10 jim 1600 17-NOV-1981 1700 3 1300 10 jon 1700 17-NOV-1981 5000 2 1300 10 KING 5000 17-NOV-1981 1300 1 1300 10 MILLER 1300 23-JAN-1982 1 Now you can clearly see the effect that you have when you pass the correct distance to LEAD OVER. The rows for INCORRECT represent the values returned by LEAD OVER using a default distance of one. The rows for CORRECT represent the values returned by LEAD OVER using the proper distance for each employee with a duplicate HIREDATE to MILLER. At this point, all that is left is to find the difference between CORRECT and SAL for each row, which has already been shown. ## 10.3. Locating the Beginning and End of a Range of Consecutive Values ### Problem This recipe is an extension of the prior recipe , and it uses the same view V from the prior recipe. Now that you've located the ranges of consecutive values, you want to find just their start and end points. Unlike the prior recipe, if a row is not part of a set of consecutive values, you still want to return it. Why? Because such a row represents both the beginning and end of its range. Using the data from view V: **select *** **from V** PROJ_ID PROJ_START PROJ_END ------- ----------- ----------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 3 03-JAN-2005 04-JAN-2005 4 04-JAN-2005 05-JAN-2005 5 06-JAN-2005 07-JAN-2005 6 16-JAN-2005 17-JAN-2005 7 17-JAN-2005 18-JAN-2005 8 18-JAN-2005 19-JAN-2005 9 19-JAN-2005 20-JAN-2005 10 21-JAN-2005 22-JAN-2005 11 26-JAN-2005 27-JAN-2005 12 27-JAN-2005 28-JAN-2005 13 28-JAN-2005 29-JAN-2005 14 29-JAN-2005 30-JAN-2005 you want the final result set to be: PROJ_GRP PROJ_START PROJ_END -------- ----------- ----------- 1 01-JAN-2005 05-JAN-2005 2 06-JAN-2005 07-JAN-2005 3 16-JAN-2005 20-JAN-2005 4 21-JAN-2005 22-JAN-2005 5 26-JAN-2005 30-JAN-2005 ### Solution This problem is a bit more involved than its predecessor. First, you must identify what the ranges are. A range of rows is defined by the values for PROJ_START and PROJ_END. For a row to be considered "consecutive" or part of a group, its PROJ_ START value must equal the PROJ_END value of the row before it. In the case where a row's PROJ_START value does not equal the prior row's PROJ_END value and its PROJ_END value does not equal the next row's PROJ_START value, this is an instance of a single row group. Once you have identify the ranges, you need to be able to group the rows in these ranges together (into groups) and return only their start and end points. Examine the first row of the desired result set. The PROJ_START is the PROJ_ START for PROJ_ID 1 from view V and the PROJ_END is the PROJ_END for PROJ_ID 4 from view V. Despite the fact that PROJ_ID 4 does not have a consecutive value following it, it is the last of a range of consecutive values, and thus it is included in the first group. #### DB2, MySQL, PostgreSQL, and SQL Server The solution for these platforms will use use view V2 to help improve readability. View V2 is defined as follows: create view v2 as select a.*, case when ( select b.proj_id from V b where a.proj_start = b.proj_end ) is not null then 0 else 1 end as flag from V a The result set from view V2 is: **select *** **from V2** PROJ_ID PROJ_START PROJ_END FLAG ------- ----------- ----------- ---------- 1 01-JAN-2005 02-JAN-2005 1 2 02-JAN-2005 03-JAN-2005 0 3 03-JAN-2005 04-JAN-2005 0 4 04-JAN-2005 05-JAN-2005 0 5 06-JAN-2005 07-JAN-2005 1 6 16-JAN-2005 17-JAN-2005 1 7 17-JAN-2005 18-JAN-2005 0 8 18-JAN-2005 19-JAN-2005 0 9 19-JAN-2005 20-JAN-2005 0 10 21-JAN-2005 22-JAN-2005 1 11 26-JAN-2005 27-JAN-2005 1 12 27-JAN-2005 28-JAN-2005 0 13 28-JAN-2005 29-JAN-2005 0 14 29-JAN-2005 30-JAN-2005 0 Using V2, the solution is as follows. First, find the rows that are part of a set of consecutive values. Group those rows together. Then use the MIN and MAX functions to find their start and end points: 1 select proj_grp, 2 min(proj_start) as proj_start, 3 max(proj_end) as proj_end 4 from ( 5 select a.proj_id,a.proj_start,a.proj_end, 6 (select sum(b.flag) 7 from V2 b 8 where b.proj_id <= a.proj_id) as proj_grp 9 from V2 a 10 ) x 11 group by proj_grp #### Oracle While the solution for the other vendors will work for Oracle, there's no need to introduce additional views when you can take advantage of Oracle's LAG OVER window function. Use LAG OVER to determine whether or not each prior row's PROJ_END equals the current row's PROJ_START to help place the rows into groups. Once they are grouped, use the aggregate functions MIN and MAX to find their start and end points: 1 select proj_grp, min(proj_start), max(proj_end) 2 from ( 3 select proj_id,proj_start,proj_end, 4 sum(flag)over(order by proj_id) proj_grp 5 from ( 6 select proj_id,proj_start,proj_end, 7 case when 8 lag(proj_end)over(order by proj_id) = proj_start 9 then 0 else 1 10 end flag 11 from V 12 ) 13 ) 14 group by proj_grp ### Discussion #### DB2, MySQL, PostgreSQL, and SQL Server Using view V2 makes this problem relatively easy to solve. View V2 uses a scalar subquery in a CASE expression to determine whether or not a particular row is part of a set of consecutive values. The CASE expression, aliased FLAG, returns a 0 if the current row is part of a consecutive set or a 1 if it is not (membership in a consecutive set is determined by whether or not there is a record with a PROJ_END value that matches the current row's PROJ_START value). The next step is to examine inline view X (lines 5–9). Inline view X returns all rows from view V2 along with a running total on FLAG; this running total is what creates our groups and can be seen below: **select a.proj_id,a.proj_start,a.proj_end,** **(select sum(b.flag)** **from v2 b** **where b.proj_id<= a.proj_id) as proj_grp** **from v2 a** PROJ_ID PROJ_START PROJ_END PROJ_GRP ------- ----------- ----------- ---------- 1 01-JAN-2005 02-JAN-2005 1 2 02-JAN-2005 03-JAN-2005 1 3 03-JAN-2005 04-JAN-2005 1 4 04-JAN-2005 05-JAN-2005 1 5 06-JAN-2005 07-JAN-2005 2 6 16-JAN-2005 17-JAN-2005 3 7 17-JAN-2005 18-JAN-2005 3 8 18-JAN-2005 19-JAN-2005 3 9 19-JAN-2005 20-JAN-2005 3 10 21-JAN-2005 22-JAN-2005 4 11 26-JAN-2005 27-JAN-2005 5 12 27-JAN-2005 28-JAN-2005 5 13 28-JAN-2005 29-JAN-2005 5 14 29-JAN-2005 30-JAN-2005 5 Now that the ranges have been grouped, find the start and end point for each by simply using the aggregate functions MIN and MAX on PROJ_START and PROJ_END respectively, and group by the values created by the running total. #### Oracle The window function LAG OVER is extremely useful in this situation. You can examine each prior row's PROJ_END value without a self join, without a scalar sub-query, and without a view. The results of the LAG OVER function without the CASE expression are as follows: **select proj_id,proj_start,proj_end,** **lag(proj_end)over(order by proj_id) prior_proj_end** **from V** PROJ_ID PROJ_START PROJ_END PRIOR_PROJ_END ------- ----------- ----------- -------------- 1 01-JAN-2005 02-JAN-2005 2 02-JAN-2005 03-JAN-2005 02-JAN-2005 3 03-JAN-2005 04-JAN-2005 03-JAN-2005 4 04-JAN-2005 05-JAN-2005 04-JAN-2005 5 06-JAN-2005 07-JAN-2005 05-JAN-2005 6 16-JAN-2005 17-JAN-2005 07-JAN-2005 7 17-JAN-2005 18-JAN-2005 17-JAN-2005 8 18-JAN-2005 19-JAN-2005 18-JAN-2005 9 19-JAN-2005 20-JAN-2005 19-JAN-2005 10 21-JAN-2005 22-JAN-2005 20-JAN-2005 11 26-JAN-2005 27-JAN-2005 22-JAN-2005 12 27-JAN-2005 28-JAN-2005 27-JAN-2005 13 28-JAN-2005 29-JAN-2005 28-JAN-2005 14 29-JAN-2005 30-JAN-2005 29-JAN-2005 The CASE expression in the complete solution simply compares the value returned by LAG OVER to the current row's PROJ_START value; if they are the same, return 0, else return 1. The next step is to create a running total on the 0's and 1's returned by the CASE expression to put each row into a group. The results of the running total can be seen below: **select proj_id,proj_start,proj_end,** **sum(flag)over(order by proj_id) proj_grp** **from (** **select proj_id,proj_start,proj_end,** **case when** **lag(proj_end)over(order by proj_id) = proj_start** **then 0 else 1** **end flag** **from V** **)** PROJ_ID PROJ_START PROJ_END PROJ_GRP ------- ----------- ----------- ---------- 1 01-JAN-2005 02-JAN-2005 1 2 02-JAN-2005 03-JAN-2005 1 3 03-JAN-2005 04-JAN-2005 1 4 04-JAN-2005 05-JAN-2005 1 5 06-JAN-2005 07-JAN-2005 2 6 16-JAN-2005 17-JAN-2005 3 7 17-JAN-2005 18-JAN-2005 3 8 18-JAN-2005 19-JAN-2005 3 9 19-JAN-2005 20-JAN-2005 3 10 21-JAN-2005 22-JAN-2005 4 11 26-JAN-2005 27-JAN-2005 5 12 27-JAN-2005 28-JAN-2005 5 13 28-JAN-2005 29-JAN-2005 5 14 29-JAN-2005 30-JAN-2005 5 Now that each row has been placed into a group, simply use the aggregate functions MIN and MAX on PROJ_START and PROJ_END respectively, and group by the values created in the PROJ_GRP running total column. ## 10.4. Filling in Missing Values in a Range of Values ### Problem You want to return the number of employees hired each year for the entire decade of the 1980s, but there are some years in which no employees were hired. You would like to return the following result set: YR CNT ---- ---------- 1980 1 1981 10 1982 2 1983 1 1984 0 1985 0 1986 0 1987 0 1988 0 1989 0 ### Solution The trick to this solution is returning zeros for years that saw no employees hired. If no employee was hired in a given year, then no rows for that year will exist in table EMP. If the year does not exist in the table, how can you return a count, any count, even zero? The solution requires you to outer join. You must supply a result set that returns all the years you want to see, and then perform a count against table EMP to see if there were any employees hired in each of those years. #### DB2 Use table EMP as a pivot table (because it has 14 rows) and the built-in function YEAR to generate one row for each year in the decade of 1980. Outer join to table EMP and count how many employees were hired each year: 1 select x.yr, coalesce(y.cnt,0) cnt 2 from ( 3 select year(min(hiredate)over()) - 4 mod(year(min(hiredate)over()),10) + 5 row_number()over()-1 yr 6 from emp fetch first 10 rows only 7 ) x 8 left join 9 ( 10 select year(hiredate) yr1, count(*) cnt 11 from emp 12 group by year(hiredate) 13 ) y 14 on ( x.yr = y.yr1 ) #### Oracle Use table EMP as a pivot table (because it has 14 rows) and the built-in functions TO_NUMBER and TO_CHAR to generate one row for each year in the decade of 1980. Outer join to table EMP and count how many employees were hired each year: 1 select x.yr, coalesce(cnt,0) cnt 2 from ( 3 select extract(year from min(hiredate)over()) - 4 mod(extract(year from min(hiredate)over()),10) + 5 rownum-1 yr 6 from emp 7 where rownum <= 10 8 ) x, 9 ( 10 select to_number(to_char(hiredate,'YYYY')) yr, count(*) cnt 11 from emp 12 group by to_number(to_char(hiredate,'YYYY')) 13 ) y 14 where x.yr = y.yr(+) If you're using Oracle9 _i_ Database or later, you can implement the solution using the newly supported JOIN clause: 1 select x.yr, coalesce(cnt,0) cnt 2 from ( 3 select extract(year from min(hiredate)over()) - 4 mod(extract(year from min(hiredate)over()),10) + 5 rownum-1 yr 6 from emp 7 where rownum <= 10 8 ) x 9 left join 10 ( 11 select to_number(to_char(hiredate,'YYYY')) yr, count(*) cnt 12 from emp 13 group by to_number(to_char(hiredate,'YYYY')) 14 ) y 15 on ( x.yr = y.yr ) #### PostgreSQL and MySQL Use table T10 as a pivot table (because it has 10 rows) and the built-in function EXTRACT to generate one row for each year in the decade of 1980. Outer join to table EMP and count how many employees were hired each year: 1 select y.yr, coalesce(x.cnt,0) as cnt 2 from ( 3 selectmin_year-mod(cast(min_year as int),10)+rn as yr 4 from ( 5 select (select min(extract(year from hiredate)) 6 from emp) as min_year, 7 id-1 as rn 8 from t10 9 ) a 10 ) y 11 left join 12 ( 13 select extract(year from hiredate) as yr, count(*) as cnt 14 from emp 15 group by extract(year from hiredate) 16 ) x 17 on ( y.yr = x.yr ) #### SQL Server Use table EMP as a pivot table (because it has 14 rows) and the built-in function YEAR to generate one row for each year in the decade of 1980. Outer join to table EMP and count how many employees were hired each year: 1 select x.yr, coalesce(y.cnt,0) cnt 2 from ( 3 select top (10) 4 (year(min(hiredate)over()) - 5 year(min(hiredate)over())%10)+ 6 row_number()over(order by hiredate)-1 yr 7 from emp 8 ) x 9 left join 10 ( 11 select year(hiredate) yr, count(*) cnt 12 from emp 13 group by year(hiredate) 14 ) y 15 on ( x.yr = y.yr ) ### Discussion Despite the difference in syntax, the approach is the same for all solutions. Inline view X returns each year in the decade of the '80s by first finding the year of the earliest HIREDATE. The next step is to add RN–1 to the difference between the earliest year and the earliest year modulus ten. To see how this works, simply execute inline view X and return each of the values involved separately. Listed below is the result set for inline view X using the window function MIN OVER (DB2, Oracle, SQL Server) and a scalar subquery (MySQL, PostgreSQL): **select year(min(hiredate)over()) -** **mod(year(min(hiredate)over()),10) +** **row_number()over()-1 yr,** **year(min(hiredate)over()) min_year,** **mod(year(min(hiredate)over()),10) mod_yr,** **row_number()over()-1 rn** **from emp fetch first 10 rows only** YR MIN_YEAR MOD_YR RN ---- ---------- ---------- ---------- 1980 1980 0 0 1981 1980 0 1 1982 1980 0 2 1983 1980 0 3 1984 1980 0 4 1985 1980 0 5 1986 1980 0 6 1987 1980 0 7 1988 1980 0 8 1989 1980 0 9 **select min_year-mod(min_year,10)+rn as yr,** **min_year,** **mod(min_year,10) as mod_yr** **rn** **from (** **select (select min(extract(year from hiredate))** **from emp) as min_year,** **id-1 as rn** **from t10** **) x** YR MIN_YEAR MOD_YR RN ---- ---------- ---------- ---------- 1980 1980 0 0 1981 1980 0 1 1982 1980 0 2 1983 1980 0 3 1984 1980 0 4 1985 1980 0 5 1986 1980 0 6 1987 1980 0 7 1988 1980 0 8 1989 1980 0 9 Inline view Y returns the year for each HIREDATE and the number of employees hired during that year: **select year(hiredate) yr, count(*) cnt** **from emp** **group by year(hiredate)** YR CNT ----- ---------- 1980 1 1981 10 1982 2 1983 1 For the final solution, outer join inline view Y to inline view X so that every year is returned even if there are no employees hired. ## 10.5. Generating Consecutive Numeric Values ### Problem You would like to have a "row source generator" available to you in your queries. Row source generators are useful for queries that require pivoting. For example, you want to return a result set such as the following, up to any number of rows that you specify: ID --- 1 2 3 4 5 6 7 8 9 10 ... If your RDBMS provides built-in functions for returning rows dynamically, you do not need to create a pivot table in advance with a fixed number of rows. That's why a dynamic row generator can be so handy. Otherwise, you must use a traditional pivot table with a fixed number of rows (that may not always be enough) to generate rows when needed. ### Solution This solution shows how to return 10 rows of increasing numbers starting from 1. You can easily adapt the solution to return any number of rows. The ability to return increasing values from 1 opens the door to many other solutions. For example, you can generate numbers to add to dates in order to generate sequences of days. You can also use such numbers to parse through strings. #### DB2 and SQL Server Use the recursive WITH clause to generate a sequence of rows with incrementing values. Use a one-row table such as T1 to kick off the row generation; the WITH clause does the rest: 1 with x (id) 2 as ( 3 select 1 4 from t1 5 union all 6 select id+1 7 from x 8 where id+1 <= 10 9 ) 10 select * from x Following is a second, alternative solution for DB2 only. Its advantage is that it does not require table T1: 1 with x (id) 2 as ( 3 values (1) 4 union all 5 select id+1 6 from x 7 where id+1 <= 10 8 ) 9 select * from x #### Oracle Use the recursive CONNECT BY clause (Oracle9 _i_ Database or later). In Oracle 9 _i_ Database, you must either wrap the CONNECT BY solution in an inline view or place it in the WITH clause: 1 with x 2 as ( 3 select level id 4 from dual 5 connect by level <= 10 6 ) 7 select * from x In Oracle Database 10 _g_ or later, you can generate rows using the MODEL clause: 1 select array id 2 from dual 3 model 4 dimension by (0 idx) 5 measures(1 array) 6 rules iterate (10) ( 7 array[iteration_number] = iteration_number+1 8 ) #### PostgreSQL Use the very handy function GENERATE_SERIES, which is designed for the express purpose of generating rows: 1 select id 2 from generate_series (1, 10) x(id) ### Discussion #### DB2 and SQL Server The recursive WITH clause increments ID (which starts at 1) until the WHERE clause is satisfied. To kick things off you must generate one row having the value 1. You can do this by selecting 1 from a one-row table or, in the case of DB2, by using the VALUES clause to create a one-row result set. #### Oracle The solution places the CONNECT BY subquery into the WITH clause. Rows will continue to be returned unless short-circuited by the WHERE clause. Oracle will increment the pseudo-column LEVEL automatically, so there's no need for you to do so. In the MODEL clause solution, there is an explicit ITERATE command that allows you to generate multiple rows. Without the ITERATE clause, only one row will be returned, since DUAL has only one row. For example: **select array id** **from dual** **model** **dimension by (0 idx)** **measures(1 array)** **rules ()** ID -- 1 The MODEL clause not only allows you array access to rows, it allows you to easily "create" or return rows that are not in the table you are selecting against. In this solution, IDX is the array index (location of a specific value in the array) and ARRAY (aliased ID) is the "array" of rows. The first row defaults to 1 and can be referenced with ARRAY[0]. Oracle provides the function ITERATION_NUMBER so you can track the number of times you've iterated. The solution iterates 10 times, causing ITERATION_NUMBER to go from 0 to 9. Adding 1 to each of those values yields the results 1 through 10. It may be easier to visualize what's happening with the model clause if you execute the following query: **select 'array['||idx||'] = '||array as output** **from dual** **model** **dimension by (0 idx)** **measures(1 array)** **rules iterate (10) (** **array[iteration_number] = iteration_number+1** **)** OUTPUT ------------------ array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4 array[4] = 5 array[5] = 6 array[6] = 7 array[7] = 8 array[8] = 9 array[9] = 10 #### PostgreSQL All the work is done by the function GENERATE_SERIES. The function accepts three parameters, all numeric values. The first parameter is the start value, the second parameter is the ending value, and the third parameter is an optional "step" value (how much each value is incremented by). If you do not pass a third parameter, the increment defaults to 1. The GENERATE_SERIES function is flexible enough so that you do not have to hardcode parameters. For example, if you wanted to return five rows starting from value 10 and ending with value 30, incrementing by 5 such that the result set is the following: ID --- 10 15 20 25 30 you can be creative and do something like this: select id from generate_series( (select min(deptno) from emp), (select max(deptno) from emp), 5 ) x(id) Notice here that the actual values passed to GENERATE_SERIES are not known when the query is written. Instead, they are generated by subqueries when the main query executes. ## Chapter 11. Advanced Searching In a very real sense, this entire book so far has been about searching. You've seen all sorts of queries that use joins and WHERE clauses and grouping techniques to search out and return the results that you need. Some types of searching operations, though, stand apart from others in that they represent a different way of thinking about searching. Perhaps you're displaying a result set one page at a time. Half of that problem is to identify (search for) the entire set of records that you want to display. The other half of that problem is to repeatedly search for the next page to display as a user cycles through the records on a display. Your first thought may not be to think of pagination as a searching problem, but it _can_ be thought of that way, and it can be solved that way; that is the type of searching solution this chapter is all about. ## 11.1. Paginating Through a Result Set ### Problem You want to paginate or "scroll through" a result set. For example, you want to return the first five salaries from table EMP, then the next five, and so forth. Your goal is to allow a user to view five records at a time, scrolling forward with each click of a "Next" button. ### Solution Because there is no concept of first, last, or next in SQL, you must impose order on the rows you are working with. Only by imposing order can you accurately return ranges of records. #### DB2, Oracle, and SQL Server Use the window function ROW_NUMBER OVER to impose order, and specify the window of records that you want returned in your WHERE clause. For example, to return rows 1 through 5: **select sal** **from (** **select row_number() over (order by sal) as rn,** **sal** **from emp** **) x** **where rn between 1 and 5** SAL ---- 800 950 1100 1250 1250 Then to return rows 6 through 10: **select sal** **from (** **select row_number() over (order by sal) as rn,** **sal** **from emp** **) x** **where rn between 6 and 10** SAL ----- 1300 1500 1600 2450 2850 You can return any range of rows that you wish simply by changing the WHERE clause of your query. #### MySQL and PostgreSQL Scrolling through a result set is particularly easy due to the LIMIT and OFFSET clauses that these products support. Use LIMIT to specify the number of rows to return, and use OFFSET to specify the number of rows to skip. For example, to return the first five rows in order of salary: **select sal** **from emp** **order by sal limit 5 offset 0** SAL ----- 800 950 1100 1250 1250 To return the next group of five rows: **select sal** **from emp** **order by sal limit 5 offset 5** SAL ----- 1300 1500 1600 2450 2850 LIMIT and OFFSET not only make the MySQL and PostgreSQL solutions easy to write, but they are quite readable, too. ### Discussion #### DB2, Oracle, and SQL Server The window function ROW_NUMBER OVER in inline view X will assign a unique number to each salary (in increasing order starting from 1). Listed below is the result set for inline view X: **select row_number() over (order by sal) as rn,** **sal** **from emp** RN SAL -- ---------- 1 800 2 950 3 1100 4 1250 5 1250 6 1300 7 1500 8 1600 9 2450 10 2850 11 2975 12 3000 13 3000 14 5000 Once a number has been assigned to a salary, simply pick the range you want to return by specifying values for RN. For Oracle users, an alternative: you can use ROWNUM instead of ROW NUMBER OVER to generate sequence numbers for the rows: **select sal** **from (** **select sal, rownum rn** **from (** **select sal** **from emp** **order by sal** **)** **)** **where rn between 6 and 10** SAL ----- 1300 1500 1600 2450 2850 Using ROWNUM forces you into writing an extra level of subquery. The innermost subquery sorts rows by salary. The next outermost subquery applies row numbers to those rows, and, finally, the very outermost SELECT returns the data you are after. #### MySQL and PostgreSQL The OFFSET clause added to the SELECT clause makes scrolling through results intuitive and easy. Specifying OFFSET 0 will start you at the first row, OFFSET 5 at the sixth row, and OFFSET 10 at the eleventh row. The LIMIT clause restricts the number of rows returned. By combining the two clauses you can easily specify where in a result set to start returning rows and how many to return. ## 11.2. Skipping n Rows from a Table ### Problem You want a query to return every other employee in table EMP; you want the first employee, third employee, and so forth. For example, from the following result set: ENAME -------- ADAMS ALLEN BLAKE CLARK FORD JAMES JONES KING MARTIN MILLER SCOTT SMITH TURNER WARD you want to return: ENAME ---------- ADAMS BLAKE FORD JONES MARTIN SCOTT TURNER ### Solution To skip the second or fourth or _n_ th row from a result set, you must impose order on the result set, otherwise there is no concept of first or next, second, or fourth. #### DB2, Oracle, and SQL Server Use the window function ROW_NUMBER OVER to assign a number to each row, which you can then use in conjunction with the modulo function to skip unwanted rows. The modulo function is MOD for DB2 and Oracle. In SQL Server, use the percent (%) operator. The following example uses MOD to skip even-numbered rows: 1 select ename 2 from ( 3 select row_number() over (order by ename) rn, 4 ename 5 from emp 6 ) x 7 where mod(rn,2) = 1 #### MySQL and PostgreSQL Because there are no built-in functions for ranking or numbering rows, you need to use a scalar subquery to rank the rows (by name in this example). Then use modulus to skip rows: 1 select x.ename 2 from ( 3 select a.ename, 4 (select count(*) 5 from emp b 6 where b.ename <= a.ename) as rn 7 from emp a 8 ) x 9 where mod(x.rn,2) = 1 ### Discussion #### DB2, Oracle, and SQL Server The call to the window function ROW_NUMBER OVER in inline view X will assign a rank to each row (no ties, even with duplicate names). The results are shown below: **select row_number() over (order by ename) rn, ename** **from emp** RN ENAME -- -------- 1 ADAMS 2 ALLEN 3 BLAKE 4 CLARK 5 FORD 6 JAMES 7 JONES 8 KING 9 MARTIN 10 MILLER 11 SCOTT 12 SMITH 13 TURNER 14 WARD The last step is to simply use modulus to skip every other row. #### MySQL and PostgreSQL With a function to rank or number rows, you can use a scalar subquery to first rank the employee names. Inline view X ranks each name and is shown below: **select a.ename,** **(select count(*)** **from emp b** **where b.ename<= a.ename) as rn** **from emp a** ENAME RN ---------- ---------- ADAMS 1 ALLEN 2 BLAKE 3 CLARK 4 FORD 5 JAMES 6 JONES 7 KING 8 MARTIN 9 MILLER 10 SCOTT 11 SMITH 12 TURNER 13 WARD 14 The final step is to use the modulo function on the generated rank to skip rows. ## 11.3. Incorporating OR Logic when Using Outer Joins ### Problem You want to return the name and department information for all employees in departments 10 and 20 along with department information for departments 30 and 40 (but no employee information). Your first attempt looks like this: **select e.ename, d.deptno, d.dname, d.loc** **from dept d, emp e** **where d.deptno = e.deptno** **and (e.deptno = 10 or e.deptno = 20)** **order by 2** ENAME DEPTNO DNAME LOC ------- ---------- -------------- ----------- CLARK 10 ACCOUNTING NEW YORK KING 10 ACCOUNTING NEW YORK MILLER 10 ACCOUNTING NEW YORK SMITH 20 RESEARCH DALLAS ADAMS 20 RESEARCH DALLAS FORD 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS JONES 20 RESEARCH DALLAS Because the join in this query is an inner join, the result set does not include department information for DEPTNOs 30 and 40. You attempt to outer join EMP to DEPT with the following query, but you still do not get the correct results: **select e.ename, d.deptno, d.dname, d.loc** **from dept d left join emp e** **on (d.deptno = e.deptno)** **where e.deptno = 10** **or e.deptno = 20** **order by 2** ENAME DEPTNO DNAME LOC ------- ---------- ------------ ----------- CLARK 10 ACCOUNTING NEW YORK KING 10 ACCOUNTING NEW YORK MILLER 10 ACCOUNTING NEW YORK SMITH 20 RESEARCH DALLAS ADAMS 20 RESEARCH DALLAS FORD 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS JONES 20 RESEARCH DALLAS Ultimately, you would like the result set to be: ENAME DEPTNO DNAME LOC ------- ---------- ------------ --------- CLARK 10 ACCOUNTING NEW YORK KING 10 ACCOUNTING NEW YORK MILLER 10 ACCOUNTING NEW YORK SMITH 20 RESEARCH DALLAS JONES 20 RESEARCH DALLAS SCOTT 20 RESEARCH DALLAS ADAMS 20 RESEARCH DALLAS FORD 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON ### Solution #### DB2, MySQL, PostgreSQL, and SQL Server Move the OR condition into the JOIN clause: 1 select e.ename, d.deptno, d.dname, d.loc 2 from dept d left join emp e 3 on (d.deptno = e.deptno 4 and (e.deptno=10 or e.deptno=20)) 5 order by 2 Alternatively, you can filter on EMP.DEPTNO first in an inline view and then outer join: 1 select e.ename, d.deptno, d.dname, d.loc 2 from dept d 3 left join 4 (select ename, deptno 5 from emp 6 where deptno in ( 10, 20 ) 7 ) e on ( e.deptno = d.deptno ) 8 order by 2 #### Oracle If you are on Oracle9 _i_ Database or later, you can use either of the solutions for the other products. Otherwise, you need to use CASE or DECODE in a workaround. Following is a solution using CASE: select e.ename, d.deptno, d.dname, d.loc from dept d, emp e where d.deptno = e.deptno (+) and d.deptno = case when e.deptno(+) = 10 then e.deptno(+) when e.deptno(+) = 20 then e.deptno(+) end order by 2 And next is the same solution, but this time using DECODE: select e.ename, d.deptno, d.dname, d.loc from dept d, emp e where d.deptno = e.deptno (+) and d.deptno = decode(e.deptno(+),10,e.deptno(+), 20,e.deptno(+)) order by 2 When using the proprietary Oracle outer join syntax (+) along with an IN or OR predicate on an outer joined column, the query will return an error. The solution is to move the IN or OR predicate to an inline view: select e.ename, d.deptno, d.dname, d.loc from dept d, ( select ename, deptno from emp where deptno in ( 10, 20 ) ) e where d.deptno = e.deptno (+) order by 2 ### Discussion #### DB2, MySQL, PostgreSQL, and SQL Server Two solutions are given for these products. The first moves the OR condition into the JOIN clause, making it part of the join condition. By doing that, you can filter the rows returned from EMP without losing DEPTNOs 30 and 40 from DEPT. The second solution moves the filtering into an inline view. Inline view E filters on EMP.DEPTNO and returns EMP rows of interest. These are then outer joined to DEPT. Because DEPT is the anchor table in the outer join, all departments, including 30 and 40, are returned. #### Oracle Use the CASE and DECODE functions as a workaround for what seems to be a bug in the older outer-join syntax. The solution using inline view E works by first finding the rows of interest in table EMP, and then outer joining to DEPT. ## 11.4. Determining Which Rows Are Reciprocals ### Problem You have a table containing the results of two tests, and you want to determine which pair of scores are reciprocals. Consider the result set below from view V: select * from V TEST1 TEST2 ----- ---------- 20 20 50 25 20 20 60 30 70 90 80 130 90 70 100 50 110 55 120 60 130 80 140 70 Examining these results, you see that a test score for TEST1 of 70 and TEST2 of 90 is a reciprocal (there exists a score of 90 for TEST1 and a score of 70 for TEST2). Likewise, the scores of 80 for TEST1 and 130 for TEST2 are reciprocals of 130 for TEST1 and 80 for TEST2. Additionally, the scores of 20 for TEST1 and 20 for TEST2 are reciprocals of 20 for TEST2 and 20 for TEST1. You want to identify only one set of reciprocals. You want your result set to be this: TEST1 TEST2 ----- --------- 20 20 70 90 80 130 not this: TEST1 TEST2 ----- --------- 20 20 20 20 70 90 80 130 90 70 130 80 ### Solution Use a self join to identify rows where TEST1 equals TEST2 and vice versa: select distinct v1.* from V v1, V v2 where v1.test1 = v2.test2 and v1.test2 = v2.test1 and v1.test1 <= v1.test2 ### Discussion The self-join results in a Cartesian product in which every TEST1 score can be compared against every TEST2 score and vice versa. The query below will identify the reciprocals: select v1.* from V v1, V v2 where v1.test1 = v2.test2 and v1.test2 = v2.test1 TEST1 TEST2 ----- ---------- 20 20 20 20 20 20 20 20 90 70 130 80 70 90 80 130 The use of DISTINCT ensures that duplicate rows are removed from the final result set. The final filter in the WHERE clause (and V1.TEST1 <= V1.TEST2) will ensure that only one pair of reciprocals (where TEST1 is the smaller or equal value) is returned. ## 11.5. Selecting the Top n Records ### Problem You want to limit a result set to a specific number of records based on a ranking of some sort. For example, you want to return the names and salaries of the employees with the top five salaries. ### Solution The key to this solution is to make two passes: first rank the rows on whatever value you want to rank on; then limit the result set to the number of rows you are interested in. #### DB2, Oracle, and SQL Server The solution to this problem depends on the use of a window function. Which window function you will use depends on how you want to deal with ties. The following solution uses DENSE_RANK, so that each tie in salary will count as only one against the total: 1 select ename,sal 2 from ( 3 select ename, sal, 4 dense_rank() over (order by sal desc) dr 5 from emp 6 ) x 7 where dr <= 5 The total number of rows returned may exceed five, but there will be only five distinct salaries. Use ROW_NUMBER OVER if you wish to return five rows regardless of ties (as no ties are allowed with this function). #### MySQL and PostgreSQL Use a scalar subquery to create a rank for each salary. Then restrict the results of that subquery by rank: 1 select ename,sal 2 from ( 3 select (select count(distinct b.sal) 4 from emp b 5 where a.sal <= b.sal) as rnk, 6 a.sal, 7 a.ename 8 from emp a 9 ) 10 where rnk <= 5 ### Discussion #### DB2, Oracle, and SQL Server The window function DENSE_RANK OVER in inline view X does all the work. The following example shows the entire table after applying that function: **select ename, sal,** **dense_rank() over (order by sal desc) dr** **from emp** ENAME SAL DR ------- ------ ---------- KING 5000 1 SCOTT 3000 2 FORD 3000 2 JONES 2975 3 BLAKE 2850 4 CLARK 2450 5 ALLEN 1600 6 TURNER 1500 7 MILLER 1300 8 WARD 1250 9 MARTIN 1250 9 ADAMS 1100 10 JAMES 950 11 SMITH 800 12 Now it's just a matter of returning rows where DR is less than or equal to five. #### MySQL and PostgreSQL The scalar subquery in inline view X ranks the salaries as follows: **select (select count(distinct b.sal)** **from emp b** **where a.sal<= b.sal) as rnk,** **a.sal,** **a.ename** **from emp a** RNK SAL ENAME --- ------ ------- 1 5000 KING 2 3000 SCOTT 2 3000 FORD 3 2975 JONES 4 2850 BLAKE 5 2450 CLARK 6 1600 ALLEN 7 1500 TURNER 8 1300 MILLER 9 1250 WARD 9 1250 MARTIN 10 1100 ADAMS 11 950 JAMES 12 800 SMITH The final step is to return only rows where RNK is less than or equal to five. ## 11.6. Finding Records with the Highest and Lowest Values ### Problem You want to find "extreme" values in your table. For example, you want to find the employees with the highest and lowest salaries in table EMP. ### Solution #### DB2, Oracle, and SQL Server Use the window functions MIN OVER and MAX OVER to find the lowest and highest salaries, respectively: 1 select ename 2 from ( 3 select ename, sal, 4 min(sal)over() min_sal, 5 max(sal)over() max_sal 6 from emp 7 ) x 8 where sal in (min_sal,max_sal) #### MySQL and PostgreSQL Write two subqueries, one each to return the MIN and MAX values of SAL: 1 select ename 2 from emp 3 where sal in ( (select min(sal) from emp), 4 (select max(sal) from emp) ) ### Discussion #### DB2, Oracle, and SQL Server The window functions MIN OVER and MAX OVER allow each row to have access to the lowest and highest salaries. The result set from inline view X is as follows: **select ename, sal,** **min(sal)over() min_sal,** **max(sal)over() max_sal** **from emp** ENAME SAL MIN_SAL MAX_SAL ------- ------ ---------- ---------- SMITH 800 800 5000 ALLEN 1600 800 5000 WARD 1250 800 5000 JONES 2975 800 5000 MARTIN 1250 800 5000 BLAKE 2850 800 5000 CLARK 2450 800 5000 SCOTT 3000 800 5000 KING 5000 800 5000 TURNER 1500 800 5000 ADAMS 1100 800 5000 JAMES 950 800 5000 FORD 3000 800 5000 MILLER 1300 800 5000 Given this result set, all that's left is to return rows where SAL equals MIN_SAL or MAX_SAL. #### MySQL and PostgreSQL This solution uses two subqueries in one IN list to find the lowest and highest salaries from EMP. The rows returned by the outer query are the ones having salaries that match the values returned by either subquery. ## 11.7. Investigating Future Rows ### Problem You want to find any employees who earn less than the employee hired immediately after them. Based on the following result set: ENAME SAL HIREDATE ---------- ---------- --------- SMITH 800 17-DEC-80 ALLEN 1600 20-FEB-81 WARD 1250 22-FEB-81 JONES 2975 02-APR-81 BLAKE 2850 01-MAY-81 CLARK 2450 09-JUN-81 TURNER 1500 08-SEP-81 MARTIN 1250 28-SEP-81 KING 5000 17-NOV-81 JAMES 950 03-DEC-81 FORD 3000 03-DEC-81 MILLER 1300 23-JAN-82 SCOTT 3000 09-DEC-82 ADAMS 1100 12-JAN-83 SMITH, WARD, MARTIN, JAMES, and MILLER earn less than the person hired immediately after they were hired, so those are the employees you wish to find with a query. ### Solution The first step is to define what "future" means. You must impose order on your result set to be able to define a row as having a value that is "later" than another. #### DB2, MySQL, PostgreSQL, and SQL Server Use subqueries to determine the following for each employee: * The date of the first person subsequently hired with a greater salary * The date of the next person to be hired When the two dates match, you have what you are looking for: 1 select ename, sal, hiredate 2 from ( 3 select a.ename, a.sal, a.hiredate, 4 (select min(hiredate) from emp b 5 where b.hiredate > a.hiredate 6 and b.sal > a.sal ) as next_sal_grtr, 7 (select min(hiredate) from emp b 8 where b.hiredate > a.hiredate) as next_hire 9 from emp a 10 ) x 11 where next_sal_grtr = next_hire #### Oracle You can use the LEAD OVER window function to access the salary of the next employee that was hired. It's then a simple matter to check whether that salary is larger: 1 select ename, sal, hiredate 2 from ( 3 select ename, sal, hiredate, 4 lead(sal)over(order by hiredate) next_sal 5 from emp 6 ) 7 where sal < next_sal ### Discussion #### DB2, MySQL, PostgreSQL, and SQL Server The scalar subqueries return, for each employee, the HIREDATE of the very next employee hired and the HIREDATE of the first, subsequently hired employee who earns more than the current employee. Here's a look at the raw data: **select a.ename, a.sal, a.hiredate,** **(select min(hiredate) from emp b** **where b.hiredate> a.hiredate** **and b.sal> a.sal ) as next_sal_grtr,** **(select min(hiredate) from emp b** **where b.hiredate> a.hiredate) as next_hire** **from emp a** ENAME SAL HIREDATE NEXT_SAL_GRTR NEXT_HIRE ------- ------ --------- ------------- --------- SMITH 800 17-DEC-80 20-FEB-81 20-FEB-81 ALLEN 1600 20-FEB-81 02-APR-81 22-FEB-81 WARD 1250 22-FEB-81 02-APR-81 02-APR-81 JONES 2975 02-APR-81 17-NOV-81 01-MAY-81 MARTIN 1250 28-SEP-81 17-NOV-81 17-NOV-81 BLAKE 2850 01-MAY-81 17-NOV-81 09-JUN-81 CLARK 2450 09-JUN-81 17-NOV-81 08-SEP-81 SCOTT 3000 09-DEC-82 12-JAN-83 KING 5000 17-NOV-81 03-DEC-81 TURNER 1500 08-SEP-81 17-NOV-81 28-SEP-81 ADAMS 1100 12-JAN-83 JAMES 950 03-DEC-81 23-JAN-82 23-JAN-82 FORD 3000 03-DEC-81 23-JAN-82 MILLER 1300 23-JAN-82 09-DEC-82 09-DEC-82 Someone hired subsequently may or may not have been hired immediately after the current employee was hired. The next (and last) step then is to return only rows where NEXT_SAL_GRTR (the earliest HIREDATE of an employee who earns more than the current employee) equals NEXT_HIRE (the HIREDATE of the very next employee relative to the current employee's HIREDATE). #### Oracle The window function LEAD OVER is perfect for a problem such as this one. It not only makes for a more readable query than the solution for the other products, LEAD OVER also leads to a more flexible solution because an argument can be passed to it that will determine how many rows ahead it should look (by default 1). Being able to leap ahead more than one row is important in the case of duplicates in the column you are ordering by. The following example shows how easy it is to use LEAD OVER to look at the salary of the "next" employee hired: **select ename, sal, hiredate,** **lead(sal)over(order by hiredate) next_sal** **from emp** ENAME SAL HIREDATE NEXT_SAL ------- ------ --------- ---------- SMITH 800 17-DEC-80 1600 ALLEN 1600 20-FEB-81 1250 WARD 1250 22-FEB-81 2975 JONES 2975 02-APR-81 2850 BLAKE 2850 01-MAY-81 2450 CLARK 2450 09-JUN-81 1500 TURNER 1500 08-SEP-81 1250 MARTIN 1250 28-SEP-81 5000 KING 5000 17-NOV-81 950 JAMES 950 03-DEC-81 3000 FORD 3000 03-DEC-81 1300 MILLER 1300 23-JAN-82 3000 SCOTT 3000 09-DEC-82 1100 ADAMS 1100 12-JAN-83 The final step is to return only rows where SAL is less than NEXT_SAL. Because of LEAD OVER's default range of one row, if there had been duplicates in table EMP, in particular, multiple employees hired on the same date, their SAL would be compared. This may or may not have been what you intended. If your goal is to compare the SAL of each employee with SAL of the next employee hired, excluding other employees hired on the same day, you can use the following solution as an alternative: select ename, sal, hiredate from ( select ename, sal, hiredate, lead(sal,cnt-rn+1)over(order by hiredate) next_sal from ( select ename,sal,hiredate, count(*)over(partition by hiredate) cnt, row_number()over(partition by hiredate order by empno) rn from emp ) ) where sal < next_sal The idea behind this solution is to find the distance from the current row to the row it should be compared with. For example, if there are five duplicates, the first of the five needs to leap five rows to get to its correct LEAD OVER row. The value for CNT represents, for each employee with a duplicate HIREDATE, how many duplicates there are in total for their HIREDATE. The value for RN represents a ranking for the employees in DEPTNO 10. The rank is partitioned by HIREDATE so only employees with a HIREDATE that another employee has will have a value greater than one. The ranking is sorted by EMPNO (this is arbitrary). Now that you now how many total duplicates there are and you have a ranking of each duplicate, the distance to the next HIREDATE is simply the total number of duplicates minus the current rank plus one (CNT-RN+1). ### See Also For additional examples of using LEAD OVER in the presence of duplicates (and a more thorough discussion of the technique above): Chapter 8, the section on "Determining the Date Difference Between the Current Record and the Next Record" and Chapter 10, the section on "Finding Differences Between Rows in the Same Group or Partition." ## 11.8. Shifting Row Values ### Problem You want to return each employee's name and salary along with the next highest and lowest salaries. If there are no higher or lower salaries, you want the results to wrap (first SAL shows last SAL and vice versa). You want to return the following result set: ENAME SAL FORWARD REWIND ---------- ---------- ---------- ---------- SMITH 800 950 5000 JAMES 950 1100 800 ADAMS 1100 1250 950 WARD 1250 1250 1100 MARTIN 1250 1300 1250 MILLER 1300 1500 1250 TURNER 1500 1600 1300 ALLEN 1600 2450 1500 CLARK 2450 2850 1600 BLAKE 2850 2975 2450 JONES 2975 3000 2850 SCOTT 3000 3000 2975 FORD 3000 5000 3000 KING 5000 800 3000 ### Solution For Oracle users, the window functions LEAD OVER and LAG OVER make this problem easy to solve and the resulting queries very readable. With other RDBMSs you can use scalar subqueries, though ties will present a problem. Because of the problem with ties, the RDBMSs without support for window functions enable only an approximate solution to this problem. #### DB2, SQL Server, MySQL, and PostgreSQL Use a scalar subquery to find next and prior salaries relative to each salary: 1 select e.ename, e.sal, 2 coalesce( 3 (select min(sal) from emp d where d.sal > e.sal), 4 (select min(sal) from emp) 5 ) as forward, 6 coalesce( 7 (select max(sal) from emp d where d.sal < e.sal), 8 (select max(sal) from emp) 9 ) as rewind 10 from emp e 11 order by 2 #### Oracle Use the window functions LAG OVER and LEAD OVER to access prior and next rows relative to the current row: 1 select ename,sal, 2 nvl(lead(sal)over(order by sal),min(sal)over()) forward, 3 nvl(lag(sal)over(order by sal),max(sal)over()) rewind 4 from emp ### Discussion #### DB2, SQL Server, MySQL, and PostgreSQL The scalar subquery solution is not a true solution to the problem. It's an approximation that will fail in the event any two records contain the same value for SAL. It's the best you can do without having window functions available. #### Oracle The window functions LAG OVER and LEAD OVER will (by default and unless otherwise specified) return values from the row before and after the current row, respectively. You define what "before" or "after" means in the ORDER BY portion of the OVER clause. If you examine the solution, the first step is to return the next and prior rows relative to the current row, ordered by SAL: **select ename,sal,** **lead(sal)over(order by sal) forward,** **lag(sal)over(order by sal) rewind** **from emp** ENAME SAL FORWARD REWIND ---------- ---------- ---------- ---------- SMITH 800 950 JAMES 950 1100 800 ADAMS 1100 1250 950 WARD 1250 1250 1100 MARTIN 1250 1300 1250 MILLER 1300 1500 1250 TURNER 1500 1600 1300 ALLEN 1600 2450 1500 CLARK 2450 2850 1600 BLAKE 2850 2975 2450 JONES 2975 3000 2850 SCOTT 3000 3000 2975 FORD 3000 5000 3000 KING 5000 3000 Notice that REWIND is NULL for employee SMITH and FORWARD is NULL for employee KING; that is because those two employees have the lowest and highest salaries, respectively. The requirement in the problem section should NULL values exist in FORWARD or REWIND is to "wrap" the results meaning that, for the highest SAL, FORWARD should be the value of the lowest SAL in the table, and for the lowest SAL, REWIND should be the value of the highest SAL in the table. The window functions MIN OVER and MAX OVER with no partition or window specified (i.e., an empty parenthesis after the OVER clause) will return the lowest and highest salaries in the table, respectively. The results are shown below: **select ename,sal,** **nvl(lead(sal)over(order by sal),min(sal)over()) forward,** **nvl(lag(sal)over(order by sal),max(sal)over()) rewind** **from emp** ENAME SAL FORWARD REWIND ---------- ---------- ---------- ---------- SMITH 800 950 5000 JAMES 950 1100 800 ADAMS 1100 1250 950 WARD 1250 1250 1100 MARTIN 1250 1300 1250 MILLER 1300 1500 1250 TURNER 1500 1600 1300 ALLEN 1600 2450 1500 CLARK 2450 2850 1600 BLAKE 2850 2975 2450 JONES 2975 3000 2850 SCOTT 3000 3000 2975 FORD 3000 5000 3000 KING 5000 800 3000 Another useful feature of LAG OVER and LEAD OVER is the ability to define how far forward or back you would like to go. In the example for this recipe, you go only one row forward or back. If want to move three rows forward and five rows back, doing so is simple. Just specify the values 3 and 5 as shown below: **select ename,sal,** **lead(sal,3)over(order by sal) forward,** **lag(sal,5)over(order by sal) rewind** **from emp** ENAME SAL FORWARD REWIND ---------- ---------- ---------- ---------- SMITH 800 1250 JAMES 950 1250 ADAMS 1100 1300 WARD 1250 1500 MARTIN 1250 1600 MILLER 1300 2450 800 TURNER 1500 2850 950 ALLEN 1600 2975 1100 CLARK 2450 3000 1250 BLAKE 2850 3000 1250 JONES 2975 5000 1300 SCOTT 3000 1500 FORD 3000 1600 KING 5000 2450 ## 11.9. Ranking Results ### Problem You want to rank the salaries in table EMP while allowing for ties. You want to return the following result set: RNK SAL --- ------- 1 800 2 950 3 1100 4 1250 4 1250 5 1300 6 1500 7 1600 8 2450 9 2850 10 2975 11 3000 11 3000 12 5000 ### Solution Window functions make ranking queries extremely simple. Three window functions are particularly useful for ranking: DENSE_RANK OVER, ROW_NUMBER OVER, and RANK OVER. #### DB2, Oracle, and SQL Server Because you want to allow for ties, use the window function DENSE_RANK OVER: 1 select dense_rank() over(order by sal) rnk, sal 2 from emp #### MySQL and PostgreSQL Until window functions are introduced, use a scalar subquery to rank the salaries: 1 select (select count(distinct b.sal) 2 from emp b 3 where b.sal <= a.sal) as rnk, 4 a.sal 5 from emp a ### Discussion #### DB2, Oracle, and SQL Server The window function DENSE_RANK OVER does all the legwork here. In parentheses following the OVER keyword you place an ORDER BY clause to specify the order in which rows are ranked. The solution uses ORDER BY SAL, so rows from EMP are ranked in ascending order of salary. #### MySQL and PostgreSQL The output from the scalar subquery solution is similar to that of DENSE_RANK because the driving predicate in the scalar subquery is on SAL. ## 11.10. Suppressing Duplicates ### Problem You want to find the different job types in table EMP but do not want to see duplicates. The result set should be: JOB --------- ANALYST CLERK MANAGER PRESIDENT SALESMAN ### Solution All of the RDBMSs support the keyword DISTINCT, and it arguably is the easiest mechanism for suppressing duplicates from the result set. However, this recipe will also cover two additional methods for suppressing duplicates. #### DB2, Oracle, and SQL Server The traditional method of using DISTINCT and sometimes GROUP BY (as seen next in the MySQL/PostgreSQL solution) certainly works for these RDBMSs. The solution below is an alternative that makes use of the window function ROW_NUMBER OVER: 1 select job 2 from ( 3 select job, 4 row_number()over(partition by job order by job) rn 5 from emp 6 ) x 7 where rn = 1 #### MySQL and PostgreSQL Use the DISTINCT keyword to suppress duplicates from the result set: select distinct job from emp Additionally, it is also possible to use GROUP BY to suppress duplicates: select job from emp group by job ### Discussion #### DB2, Oracle, and SQL Server This solution depends on some outside-the-box thinking about partitioned window functions. By using PARTITION BY in the OVER clause of ROW_NUMBER, you can reset the value returned by ROW_NUMBER to 1 whenever a new job is encountered. The results below are from inline view X: **select job,** **row_number()over(partition by job order by job) rn** **from emp** JOB RN --------- ---------- ANALYST 1 ANALYST 2 CLERK 1 CLERK 2 CLERK 3 CLERK 4 MANAGER 1 MANAGER 2 MANAGER 3 PRESIDENT 1 SALESMAN 1 SALESMAN 2 SALESMAN 3 SALESMAN 4 Each row is given an increasing, sequential number, and that number is reset to 1 whenever the job changes. To filter out the duplicates, all you must do is keep the rows where RN is 1. An ORDER BY clause is mandatory when using ROW_NUMBER OVER (except in DB2) but doesn't affect the result. Which job is returned is irrelevant so long as you return one of each job. #### MySQL and PostgreSQL The first solution shows how to use the keyword DISTINCT to suppress duplicates from a result set. Keep in mind that DISTINCT is applied to the whole SELECT list; additional columns can and will change the result set. Consider the difference between the two queries below: select distinct job select distinct job, deptno from emp from emp JOB JOB DEPTNO --------- --------- ---------- ANALYST ANALYST 20 CLERK CLERK 10 MANAGER CLERK 20 PRESIDENT CLERK 30 SALESMAN MANAGER 10 MANAGER 20 MANAGER 30 PRESIDENT 10 SALESMAN 30 By adding DEPTNO to the SELECT list, what you return is each DISTINCT pair of JOB/DEPTNO values from table EMP. The second solution uses GROUP BY to suppress duplicates. While using GROUP BY this way is not uncommon, keep in mind that GROUP BY and DISTINCT are two very different clauses that are not interchangeable. I've included GROUP BY in this solution for completeness, as you will no doubt come across it at some point. ## 11.11. Finding Knight Values ### Problem You want return a result set that contains each employee's name, the department they work in, their salary, the date they were hired, and the salary of the last employee hired, in each department. You want to return the following result set: DEPTNO ENAME SAL HIREDATE LATEST_SAL ------ ---------- ---------- ----------- ---------- 10 MILLER 1300 23-JAN-1982 1300 10 KING 5000 17-NOV-1981 1300 10 CLARK 2450 09-JUN-1981 1300 20 ADAMS 1100 12-JAN-1983 1100 20 SCOTT 3000 09-DEC-1982 1100 20 FORD 3000 03-DEC-1981 1100 20 JONES 2975 02-APR-1981 1100 20 SMITH 800 17-DEC-1980 1100 30 JAMES 950 03-DEC-1981 950 30 MARTIN 1250 28-SEP-1981 950 30 TURNER 1500 08-SEP-1981 950 30 BLAKE 2850 01-MAY-1981 950 30 WARD 1250 22-FEB-1981 950 30 ALLEN 1600 20-FEB-1981 950 The values in LATEST_SAL are the "Knight values" because the path to find them is analogous to a knight's path in the game of chess. You determine the result the way a knight determines a new location: by jumping to a row then turning and jumping to a different column (see Figure 11-1). To find the correct values for LATEST_SAL, you must first locate (jump to) the row with the latest HIREDATE in each DEPTNO, and then you select (jump to) the SAL column of that row. Figure 11-1. A knight value comes from "up and over" ### Tip The term "Knight value" was coined by a very clever coworker of mine, Kay Young. After having him review the recipes for correctness I admitted to him that I was stumped and could not come up with a good title. Because you need to initially evaluate one row then "jump" and take a value from another, he came up with the term "Knight value." ### Solution #### DB2 and SQL Server Use a CASE expression in a subquery to return the SAL of the last employee hired in each DEPTNO; for all other salaries, return zero. Use the window function MAX OVER in the outer query to return the non-zero SAL for each employee's department: 1 select deptno, 2 ename, 3 sal, 4 hiredate, 5 max(latest_sal)over(partition by deptno) latest_sal 6 from ( 7 select deptno, 8 ename, 9 sal, 10 hiredate, 11 case 12 when hiredate = max(hiredate)over(partition by deptno) 13 then sal else 0 14 end latest_sal 15 from emp 16 ) x 17 order by 1, 4 desc #### MySQL and PostgreSQL Use a scalar subquery nested two levels deep. First, find the HIREDATE of the last employee in each DEPTO. Then use the aggregate function MAX (in case there are duplicates) to find the SAL of the last employee hired in each DEPTNO: 1 select e.deptno, 2 e.ename, 3 e.sal, 4 e.hiredate, 5 (select max(d.sal) 6 from emp d 7 where d.deptno = e.deptno 8 and d.hiredate = 9 (select max(f.hiredate) 10 from emp f 11 where f.deptno = e.deptno)) as latest_sal 12 from emp e 13 order by 1, 4 desc #### Oracle Use the window function MAX OVER to return the highest SAL for each DEPTNO. Use the functions DENSE_RANK and LAST, while ordering by HIREDATE, in the KEEP clause to return the highest SAL for the latest HIREDATE in a given DEPTNO: 1 select deptno, 2 ename, 3 sal, 4 hiredate, 5 max(sal) 6 keep(dense_rank last order by hiredate) 7 over(partition by deptno) latest_sal 8 from emp 9 order by 1, 4 desc ### Discussion #### DB2 and SQL Server The first step is to use the window function MAX OVER in a CASE expression to find the employee hired last, or most recently, in each DEPTNO. If an employee's HIREDATE matches the value returned by MAX OVER, then use a CASE expression to return that employee's SAL; otherwise return 0. The results of this are shown below: **select deptno,** **ename,** **sal,** **hiredate,** **case** **when hiredate = max(hiredate)over(partition by deptno)** **then sal else 0** **end latest_sal** **from emp** DEPTNO ENAME SAL HIREDATE LATEST_SAL ------ --------- ----------- ----------- ---------- 10 CLARK 2450 09-JUN-1981 0 10 KING 5000 17-NOV-1981 0 10 MILLER 1300 23-JAN-1982 1300 20 SMITH 800 17-DEC-1980 0 20 ADAMS 1100 12-JAN-1983 1100 20 FORD 3000 03-DEC-1981 0 20 SCOTT 3000 09-DEC-1982 0 20 JONES 2975 02-APR-1981 0 30 ALLEN 1600 20-FEB-1981 0 30 BLAKE 2850 01-MAY-1981 0 30 MARTIN 1250 28-SEP-1981 0 30 JAMES 950 03-DEC-1981 950 30 TURNER 1500 08-SEP-1981 0 30 WARD 1250 22-FEB-1981 0 Because the value for LATEST_SAL will be either 0 or the SAL of the employee(s) hired most recently, you can wrap the above query in an inline view and use MAX OVER again, but this time to return the greatest non-zero LATEST_SAL for each DEPTNO: **select deptno,** **ename,** **sal,** **hiredate,** **max(latest_sal)over(partition by deptno) latest_sal** **from (** **select deptno,** **ename,** **sal,** **hiredate,** **case** **when hiredate = max(hiredate)over(partition by deptno)** **then sal else 0** **end latest_sal** **from emp** **) x** **order by 1, 4 desc** DEPTNO ENAME SAL HIREDATE LATEST_SAL ------- --------- ---------- ----------- ---------- 10 MILLER 1300 23-JAN-1982 1300 10 KING 5000 17-NOV-1981 1300 10 CLARK 2450 09-JUN-1981 1300 20 ADAMS 1100 12-JAN-1983 1100 20 SCOTT 3000 09-DEC-1982 1100 20 FORD 3000 03-DEC-1981 1100 20 JONES 2975 02-APR-1981 1100 20 SMITH 800 17-DEC-1980 1100 30 JAMES 950 03-DEC-1981 950 30 MARTIN 1250 28-SEP-1981 950 30 TURNER 1500 08-SEP-1981 950 30 BLAKE 2850 01-MAY-1981 950 30 WARD 1250 22-FEB-1981 950 30 ALLEN 1600 20-FEB-1981 950 #### MySQL and PostgreSQL The first step is to use a scalar subquery to find the HIREDATE of the last employee hired in each DEPTNO: **select e.deptno,** **e.ename,** **e.sal,** **e.hiredate,** **(select max(f.hiredate)** **from emp f** **where f.deptno = e.deptno) as last_hire** **from emp e** **order by 1, 4 desc** DEPTNO ENAME SAL HIREDATE LAST_HIRE ------ ---------- ---------- ----------- ----------- 10 MILLER 1300 23-JAN-1982 23-JAN-1982 10 KING 5000 17-NOV-1981 23-JAN-1982 10 CLARK 2450 09-JUN-1981 23-JAN-1982 20 ADAMS 1100 12-JAN-1983 12-JAN-1983 20 SCOTT 3000 09-DEC-1982 12-JAN-1983 20 FORD 3000 03-DEC-1981 12-JAN-1983 20 JONES 2975 02-APR-1981 12-JAN-1983 20 SMITH 800 17-DEC-1980 12-JAN-1983 30 JAMES 950 03-DEC-1981 03-DEC-1981 30 MARTIN 1250 28-SEP-1981 03-DEC-1981 30 TURNER 1500 08-SEP-1981 03-DEC-1981 30 BLAKE 2850 01-MAY-1981 03-DEC-1981 30 WARD 1250 22-FEB-1981 03-DEC-1981 30 ALLEN 1600 20-FEB-1981 03-DEC-1981 The next step is to find the SAL for the employee(s) in each DEPTNO hired on LAST_HIRE. Use the aggregate function MAX to keep the highest (if there are multiple employees hired on the same day): **select e.deptno,** **e.ename,** **e.sal,** **e.hiredate,** **(select max(d.sal)** **from emp d** **where d.deptno = e.deptno** **and d.hiredate =** **(select max(f.hiredate)** **from emp f** **where f.deptno = e.deptno)) as latest_sal** **from emp e** **order by 1, 4 desc** DEPTNO ENAME SAL HIREDATE LATEST_SAL ------ ---------- ---------- ----------- ---------- 10 MILLER 1300 23-JAN-1982 1300 10 KING 5000 17-NOV-1981 1300 10 CLARK 2450 09-JUN-1981 1300 20 ADAMS 1100 12-JAN-1983 1100 20 SCOTT 3000 09-DEC-1982 1100 20 FORD 3000 03-DEC-1981 1100 20 JONES 2975 02-APR-1981 1100 20 SMITH 800 17-DEC-1980 1100 30 JAMES 950 03-DEC-1981 950 30 MARTIN 1250 28-SEP-1981 950 30 TURNER 1500 08-SEP-1981 950 30 BLAKE 2850 01-MAY-1981 950 30 WARD 1250 22-FEB-1981 950 30 ALLEN 1600 20-FEB-1981 950 #### Oracle Users on Oracle8 _i_ Database can use the DB2 solution. For users on Oracle9 _i_ Database and later, you can use the solution presented below. The key to the Oracle solution is to take advantage of the KEEP clause. The KEEP clause allows you to rank the rows returned by a group/partition and work with the first or last row in the group. Consider what the solution looks like without KEEP: **select deptno,** **ename,** **sal,** **hiredate,** **max(sal) over(partition by deptno) latest_sal** **from emp** **order by 1, 4 desc** DEPTNO ENAME SAL HIREDATE LATEST_SAL ------ ---------- ---------- ----------- ---------- 10 MILLER 1300 23-JAN-1982 5000 10 KING 5000 17-NOV-1981 5000 10 CLARK 2450 09-JUN-1981 5000 20 ADAMS 1100 12-JAN-1983 3000 20 SCOTT 3000 09-DEC-1982 3000 20 FORD 3000 03-DEC-1981 3000 20 JONES 2975 02-APR-1981 3000 20 SMITH 800 17-DEC-1980 3000 30 JAMES 950 03-DEC-1981 2850 30 MARTIN 1250 28-SEP-1981 2850 30 TURNER 1500 08-SEP-1981 2850 30 BLAKE 2850 01-MAY-1981 2850 30 WARD 1250 22-FEB-1981 2850 30 ALLEN 1600 20-FEB-1981 2850 Rather than returning the SAL of the latest employee hired, MAX OVER without KEEP simply returns the highest salary in each DEPTNO. KEEP, in this recipe, allows you to order the salaries by HIREDATE in each DEPTNO by specifying ORDER BY HIREDATE. Then, the function DENSE_RANK assigns a rank to each HIREDATE in ascending order. Finally, the function LAST determines which row to apply the aggregate function to: the "last" row based on the ranking of DENSE_ RANK. In this case, the aggregate function MAX is applied to the SAL column for the row with the "last" HIREDATE. In essence, keep the SAL of the HIREDATE ranked last in each DEPTNO. You are ranking the rows in each DEPTNO based on one column (HIREDATE), but then applying the aggregation (MAX) on another column (SAL). This ability to rank in one dimension and aggregate over another is convenient as it allows you to avoid extra joins and inline views as are used in the other solutions. Finally, by adding the OVER clause after the KEEP clause you can return the SAL "kept" by KEEP for each row in the partition. Alternatively, you can order by HIREDATE in descending order and "keep" the first SAL. Compare the two queries below, which return the same result set: **select deptno,** **ename,** **sal,** **hiredate,** **max(sal)** **keep(dense_rank last order by hiredate)** **over(partition by deptno) latest_sal** **from emp** **order by 1, 4 desc** DEPTNO ENAME SAL HIREDATE LATEST_SAL ------ ---------- ---------- ----------- ---------- 10 MILLER 1300 23-JAN-1982 1300 10 KING 5000 17-NOV-1981 1300 10 CLARK 2450 09-JUN-1981 1300 20 ADAMS 1100 12-JAN-1983 1100 20 SCOTT 3000 09-DEC-1982 1100 20 FORD 3000 03-DEC-1981 1100 20 JONES 2975 02-APR-1981 1100 20 SMITH 800 17-DEC-1980 1100 30 JAMES 950 03-DEC-1981 950 30 MARTIN 1250 28-SEP-1981 950 30 TURNER 1500 08-SEP-1981 950 30 BLAKE 2850 01-MAY-1981 950 30 WARD 1250 22-FEB-1981 950 30 ALLEN 1600 20-FEB-1981 950 **select deptno,** **ename,** **sal,** **hiredate,** **max(sal)** **keep(dense_rank first order by hiredate desc)** **over(partition by deptno) latest_sal** **from emp** **order by 1, 4 desc** DEPTNO ENAME SAL HIREDATE LATEST_SAL ------ ---------- ---------- ----------- ---------- 10 MILLER 1300 23-JAN-1982 1300 10 KING 5000 17-NOV-1981 1300 10 CLARK 2450 09-JUN-1981 1300 20 ADAMS 1100 12-JAN-1983 1100 20 SCOTT 3000 09-DEC-1982 1100 20 FORD 3000 03-DEC-1981 1100 20 JONES 2975 02-APR-1981 1100 20 SMITH 800 17-DEC-1980 1100 30 JAMES 950 03-DEC-1981 950 30 MARTIN 1250 28-SEP-1981 950 30 TURNER 1500 08-SEP-1981 950 30 BLAKE 2850 01-MAY-1981 950 30 WARD 1250 22-FEB-1981 950 30 ALLEN 1600 20-FEB-1981 950 ## 11.12. Generating Simple Forecasts ### Problem Based on current data, you want to return addition rows and columns representing future actions. For example, consider the following result set: ID ORDER_DATE PROCESS_DATE -- ----------- ------------ 1 25-SEP-2005 27-SEP-2005 2 26-SEP-2005 28-SEP-2005 3 27-SEP-2005 29-SEP-2005 You want to return three rows per row returned in your result set (each row plus two additional rows for each order). Along with the extra rows you would like to return two additional columns providing dates for expected order processing. From the result set above you can see that an order takes two days to process. For the purposes of this example, let's say the next step after processing is verification, and the last step is shipment. Verification occurs one day after processing and shipment occurs one day after verification. You want to return a result set expressing the whole procedure. Ultimately you want to transform the result set above to the following result set: ID ORDER_DATE PROCESS_DATE VERIFIED SHIPPED -- ----------- ------------ ----------- ----------- 1 25-SEP-2005 27-SEP-2005 1 25-SEP-2005 27-SEP-2005 28-SEP-2005 1 25-SEP-2005 27-SEP-2005 28-SEP-2005 29-SEP-2005 2 26-SEP-2005 28-SEP-2005 2 26-SEP-2005 28-SEP-2005 29-SEP-2005 2 26-SEP-2005 28-SEP-2005 29-SEP-2005 30-SEP-2005 3 27-SEP-2005 29-SEP-2005 3 27-SEP-2005 29-SEP-2005 30-SEP-2005 3 27-SEP-2005 29-SEP-2005 30-SEP-2005 01-OCT-2005 ### Solution The key is to use a Cartesian product to generate two additional rows for each order then simply use CASE expressions to create the required column values. #### DB2 and SQL Server Use the recursive WITH clause to generate rows needed for your Cartesian product. The DB2 and SQL Server solutions are identical except for the function used to retrieve the current date. DB2 uses CURRENT_DATE and SQL Server uses GET-DATE. The SQL Server solution is shown below: 1 withnrows(n) as ( 2 select 1 from t1 union all 3 select n+1 from nrows where n+1 <= 3 4 ) 5 select id, 6 order_date, 7 process_date, 8 case when nrows.n >= 2 9 then process_date+1 10 else null 11 end as verified, 12 case when nrows.n = 3 13 then process_date+2 14 else null 15 end as shipped 16 from ( 17 select nrows.n id, 18 getdate()+nrows.n as order_date, 19 getdate()+nrows.n+2 as process_date 20 from nrows 21 ) orders, nrows 22 order by 1 #### Oracle Use the hierarchical CONNECT BY clause to generate the three rows needed for the Cartesian product. Use the WITH clause to allow you to reuse the results returned by CONNECT BY without having to call it again: 1 with nrows as ( 2 select level n 3 from dual 4 connect by level <= 3 5 ) 6 select id, 7 order_date, 8 process_date, 9 case when nrows.n >= 2 10 then process_date+1 11 else null 12 end as verified, 13 case when nrows.n = 3 14 then process_date+2 15 else null 16 end as shipped 17 from ( 18 select nrows.n id, 19 sysdate+nrows.n as order_date, 20 sysdate+nrows.n+2 as process_date 21 from nrows 22 ) orders, nrows #### PostgreSQL You can create a Cartesian product many different ways; this solution uses the PostgreSQL function GENERATE_SERIES: 1 select id, 2 order_date, 3 process_date, 4 case when gs.n >= 2 5 then process_date+1 6 else null 7 end as verified, 8 case when gs.n = 3 9 then process_date+2 10 else null 11 end as shipped 12 from ( 13 select gs.id, 14 current_date+gs.id as order_date, 15 current_date+gs.id+2 as process_date 16 from generate_series(1,3) gs (id) 17 ) orders, 18 generate_series(1,3)gs(n) #### MySQL MySQL does not support a function for automatic row generation. ### Discussion #### DB2 and SQL Server The result set presented in the problem section is returned via inline view ORDERS and is shown below: with nrows(n) as ( select 1 from t1 union all select n+1 from nrows where n+1 <= 3 ) select nrows.n id,getdate()+nrows.n as order_date, getdate()+nrows.n+2 as process_date from nrows ID ORDER_DATE PROCESS_DATE -- ----------- ------------ 1 25-SEP-2005 27-SEP-2005 2 26-SEP-2005 28-SEP-2005 3 27-SEP-2005 29-SEP-2005 The query above simply uses the WITH clause to make up three rows representing the orders you must process. NROWS returns the values 1, 2, and 3, and those numbers are added to GETDATE (CURRENT_DATE for DB2) to represent the dates of the orders. Because the problem section states that processing time takes two days, the query above also adds two days to the ORDER_DATE (adds the value returned by NROWS to GETDATE, then adds two more days). Now that you have your base result set, the next step is to create a Cartesian product because the requirement is to return three rows for each order. Use NROWS to create a Cartesian product to return three rows for each order: with nrows(n) as ( select 1 from t1 union all select n+1 from nrows where n+1 <= 3 ) select nrows.n, orders.* from ( select nrows.n id, getdate()+nrows.n as order_date, getdate()+nrows.n+2 as process_date from nrows ) orders, nrows order by 2,1 N ID ORDER_DATE PROCESS_DATE --- --- ----------- ------------ 1 1 25-SEP-2005 27-SEP-2005 2 1 25-SEP-2005 27-SEP-2005 3 1 25-SEP-2005 27-SEP-2005 1 2 26-SEP-2005 28-SEP-2005 2 2 26-SEP-2005 28-SEP-2005 3 2 26-SEP-2005 28-SEP-2005 1 3 27-SEP-2005 29-SEP-2005 2 3 27-SEP-2005 29-SEP-2005 3 3 27-SEP-2005 29-SEP-2005 Now that you have three rows for each order, simply use a CASE expression to create the addition column values to represent the status of verification and shipment. The first row for each order should have a NULL value for VERIFIED and SHIPPED. The second row for each order should have a NULL value for SHIPPED. The third row for each order should have non-NULL values for each column. The final result set is shown below: with nrows(n) as ( select 1 from t1 union all select n+1 from nrows where n+1 <= 3 ) select id, order_date, process_date, case when nrows.n >= 2 then process_date+1 else null end as verified, case when nrows.n = 3 then process_date+2 else null end as shipped from ( select nrows.n id, getdate()+nrows.n as order_date, getdate()+nrows.n+2 as process_date from nrows ) orders, nrows order by 1 ID ORDER_DATE PROCESS_DATE VERIFIED SHIPPED -- ----------- ------------ ----------- ----------- 1 25-SEP-2005 27-SEP-2005 1 25-SEP-2005 27-SEP-2005 28-SEP-2005 1 25-SEP-2005 27-SEP-2005 28-SEP-2005 29-SEP-2005 2 26-SEP-2005 28-SEP-2005 2 26-SEP-2005 28-SEP-2005 29-SEP-2005 2 26-SEP-2005 28-SEP-2005 29-SEP-2005 30-SEP-2005 3 27-SEP-2005 29-SEP-2005 3 27-SEP-2005 29-SEP-2005 30-SEP-2005 3 27-SEP-2005 29-SEP-2005 30-SEP-2005 01-OCT-2005 The final result set expresses the complete order process from the day the order was received to the day it should be shipped. #### Oracle The result set presented in the problem section is returned via inline view ORDERS and is shown below: with nrows as ( select level n from dual connect by level <= 3 ) select nrows.n id, sysdate+nrows.n order_date, sysdate+nrows.n+2 process_date from nrows ID ORDER_DATE PROCESS_DATE -- ----------- ------------ 1 25-SEP-2005 27-SEP-2005 2 26-SEP-2005 28-SEP-2005 3 27-SEP-2005 29-SEP-2005 The query above simply uses CONNECT BY to make up three rows representing the orders you must process. Use the WITH clause to refer to the rows returned by CONNECT BY as NROWS.N. CONNECT BY returns the values 1, 2, and 3, and those numbers are added to SYSDATE to represent the dates of the orders. Since the problem section states that processing time takes two days, the query above also adds two days to the ORDER_DATE (adds the value returned by GENERATE_ SERIES to SYSDATE, then adds two more days). Now that you have your base result set, the next step is to create a Cartesian product because the requirement is to return three rows for each order. Use NROWS to create a Cartesian product to return three rows for each order: with nrows as ( select level n from dual connect by level <= 3 ) select nrows.n, orders.* from ( select nrows.n id, sysdate+nrows.n order_date, sysdate+nrows.n+2 process_date from nrows ) orders, nrows N ID ORDER_DATE PROCESS_DATE --- --- ----------- ------------ 1 1 25-SEP-2005 27-SEP-2005 2 1 25-SEP-2005 27-SEP-2005 3 1 25-SEP-2005 27-SEP-2005 1 2 26-SEP-2005 28-SEP-2005 2 2 26-SEP-2005 28-SEP-2005 3 2 26-SEP-2005 28-SEP-2005 1 3 27-SEP-2005 29-SEP-2005 2 3 27-SEP-2005 29-SEP-2005 3 3 27-SEP-2005 29-SEP-2005 Now that you have three rows for each order, simply use a CASE expression to create the addition column values to represent the status of verification and shipment. The first row for each order should have a NULL value for VERIFIED and SHIPPED. The second row for each order should have a NULL value for SHIPPED. The third row for each order should have non-NULL values for each column. The final result set is shown below: with nrows as ( select level n from dual connect by level <= 3 ) select id, order_date, process_date, case when nrows.n >= 2 then process_date+1 else null end as verified, case when nrows.n = 3 then process_date+2 else null end as shipped from ( select nrows.n id, sysdate+nrows.n order_date, sysdate+nrows.n+2 process_date from nrows ) orders, nrows ID ORDER_DATE PROCESS_DATE VERIFIED SHIPPED -- ----------- ------------ ----------- ----------- 1 25-SEP-2005 27-SEP-2005 1 25-SEP-2005 27-SEP-2005 28-SEP-2005 1 25-SEP-2005 27-SEP-2005 28-SEP-2005 29-SEP-2005 2 26-SEP-2005 28-SEP-2005 2 26-SEP-2005 28-SEP-2005 29-SEP-2005 2 26-SEP-2005 28-SEP-2005 29-SEP-2005 30-SEP-2005 3 27-SEP-2005 29-SEP-2005 3 27-SEP-2005 29-SEP-2005 30-SEP-2005 3 27-SEP-2005 29-SEP-2005 30-SEP-2005 01-OCT-2005 The final result set expresses the complete order process from the day the order was received to the day it should be shipped. #### PostgreSQL The result set presented in the problem section is returned via inline view ORDERS and is shown below: select gs.id, current_date+gs.id as order_date, current_date+gs.id+2 as process_date from generate_series(1,3) gs (id) ID ORDER_DATE PROCESS_DATE -- ----------- ------------ 1 25-SEP-2005 27-SEP-2005 2 26-SEP-2005 28-SEP-2005 3 27-SEP-2005 29-SEP-2005 The query above simply uses the GENERATE_SERIES function to make up three rows representing the orders you must process. GENERATE_SERIES returns the values 1, 2, and 3, and those numbers are added to CURRENT_DATE to represent the dates of the orders. Since the problem section states that processing time takes two days, the query above also adds two days to the ORDER_DATE (adds the value returned by GENERATE_SERIES to CURRENT_DATE, then adds two more days). Now that you have your base result set, the next step is to create a Cartesian product because the requirement is to return three rows for each order. Use the GENERATE_ SERIES function to create a Cartesian product to return three rows for each order: select gs.n, orders.* from ( select gs.id, current_date+gs.id as order_date, current_date+gs.id+2 as process_date from generate_series(1,3) gs (id) ) orders, generate_series(1,3)gs(n) N ID ORDER_DATE PROCESS_DATE --- --- ----------- ------------ 1 1 25-SEP-2005 27-SEP-2005 2 1 25-SEP-2005 27-SEP-2005 3 1 25-SEP-2005 27-SEP-2005 1 2 26-SEP-2005 28-SEP-2005 2 2 26-SEP-2005 28-SEP-2005 3 2 26-SEP-2005 28-SEP-2005 1 3 27-SEP-2005 29-SEP-2005 2 3 27-SEP-2005 29-SEP-2005 3 3 27-SEP-2005 29-SEP-2005 Now that you have three rows for each order, simply use a CASE expression to create the addition column values to represent the status of verification and shipment. The first row for each order should have a NULL value for VERIFIED and SHIPPED. The second row for each order should have a NULL value for SHIPPED. The third row for each order should have non-NULL values for each column. The final result set is shown below: select id, order_date, process_date, case when gs.n >= 2 then process_date+1 else null end as verified, case when gs.n = 3 then process_date+2 else null end as shipped from ( select gs.id, current_date+gs.id as order_date, current_date+gs.id+2 as process_date from generate_series(1,3) gs(id) ) orders, generate_series(1,3)gs(n) ID ORDER_DATE PROCESS_DATE VERIFIED SHIPPED -- ----------- ------------ ----------- ----------- 1 25-SEP-2005 27-SEP-2005 1 25-SEP-2005 27-SEP-2005 28-SEP-2005 1 25-SEP-2005 27-SEP-2005 28-SEP-2005 29-SEP-2005 2 26-SEP-2005 28-SEP-2005 2 26-SEP-2005 28-SEP-2005 29-SEP-2005 2 26-SEP-2005 28-SEP-2005 29-SEP-2005 30-SEP-2005 3 27-SEP-2005 29-SEP-2005 3 27-SEP-2005 29-SEP-2005 30-SEP-2005 3 27-SEP-2005 29-SEP-2005 30-SEP-2005 01-OCT-2005 The final result set expresses the complete order process from the day the order was received to the day it should be shipped. ## Chapter 12. Reporting and Warehousing This chapter introduces queries you may find helpful for creating reports. These typically involve reporting-specific formatting considerations along with different levels of aggregation. Another focus of this chapter is on transposing or pivoting result sets, converting rows into columns. Pivoting is an extremely useful technique for solving a variety of problems. As your comfort level increases with pivoting, you'll undoubtedly find uses for it outside of what are presented in this chapter. ## 12.1. Pivoting a Result Set into One Row ### Problem You wish to take values from groups of rows and turn those values into columns in a single row per group. For example, you have a result set displaying the number of employees in each department: DEPTNO CNT ------ ---------- 10 3 20 5 30 6 You would like to reformat the output such the result set looks as follows: DEPTNO_10 DEPTNO_20 DEPTNO_30 --------- ---------- ---------- 3 5 6 ### Solution Transpose the result set using a CASE expression and the aggregate function SUM: 1 select sum(case when deptno=10 then 1 else 0 end) as deptno_10, 2 sum(case when deptno=20 then 1 else 0 end) as deptno_20, 3 sum(case when deptno=30 then 1 else 0 end) as deptno_30 4 from emp ### Discussion This example is an excellent introduction to pivoting. The concept is simple: for each row returned by the unpivoted query, use a CASE expression to separate the rows into columns. Then, because this particular problem is to count the number of employees per department, use the aggregate function SUM to count the occurrence of each DEPTNO. If you're having trouble understanding how this works exactly, execute the query with the aggregate function SUM and include DEPTNO for readability: **select deptno,** **case when deptno=10 then 1 else 0 end as deptno_10,** **case when deptno=20 then 1 else 0 end as deptno_20,** **case when deptno=30 then 1 else 0 end as deptno_30** **from emp** **order by 1** DEPTNO DEPTNO_10 DEPTNO_20 DEPTNO_30 ------ ---------- ---------- ---------- 10 1 0 0 10 1 0 0 10 1 0 0 20 0 1 0 20 0 1 0 20 0 1 0 20 0 1 0 30 0 0 1 30 0 0 1 30 0 0 1 30 0 0 1 30 0 0 1 30 0 0 1 You can think of each CASE expression as a flag to determine which DEPTNO a row belongs to. At this point, the "rows to columns" transformation is already done; the next step is to simply sum the values returned by DEPTNO_10, DEPTNO_20, and DEPTNO_30, and then to group by DEPTNO. Following are the results: **select deptno,** **sum(case when deptno=10 then 1 else 0 end) as deptno_10,** **sum(case when deptno=20 then 1 else 0 end) as deptno_20,** **sum(case when deptno=30 then 1 else 0 end) as deptno_30** **from emp** **group by deptno** DEPTNO DEPTNO_10 DEPTNO_20 DEPTNO_30 ------ ---------- ---------- ---------- 10 3 0 0 20 0 5 0 30 0 0 6 If you eyeball this result set, you see that logically the output makes sense; for example, DEPTNO 10 has 3 employees in DEPTNO_10 and zero in the other departments. Since the goal is to return one row, the last step is to lose the DEPTNO and GROUP BY, and simply sum the CASE expressions: **select sum(case when deptno=10 then 1 else 0 end) as deptno_10,** **sum(case when deptno=20 then 1 else 0 end) as deptno_20,** **sum(case when deptno=30 then 1 else 0 end) as deptno_30** **from emp** DEPTNO_10 DEPTNO_20 DEPTNO_30 --------- ---------- ---------- 3 5 6 Following is another approach that you may sometimes see applied to this same sort of problem: select max(case when deptno=10 then empcount else null end) as deptno_10 max(case when deptno=20 then empcount else null end) as deptno_20, max(case when deptno=10 then empcount else null end) as deptno_30 from ( select deptno, count(*) as empcount from emp group by deptno ) x This approach uses an inline view to generate the employee counts per department. CASE expressions in the main query translate rows to columns, getting you to the following results: DEPTNO_10 DEPTNO_20 DEPTNO_30 --------- ---------- ---------- 3 NULL NULL NULL 5 NULL NULL NULL 6 Then the MAX functions collapses the columns into one row: DEPTNO_10 DEPTNO_20 DEPTNO_30 --------- ---------- ---------- 3 5 6 ## 12.2. Pivoting a Result Set into Multiple Rows ### Problem You want to turn rows into columns by creating a column corresponding to each of the values in a single given column. However, unlike in the previous recipe, you need multiple rows of output. For example, you want to return each employee and their position (JOB), and you currently use a query that returns the following result set: JOB ENAME --------- ---------- ANALYST SCOTT ANALYST FORD CLERK SMITH CLERK ADAMS CLERK MILLER CLERK JAMES MANAGER JONES MANAGER CLARK MANAGER BLAKE PRESIDENT KING SALESMAN ALLEN SALESMAN MARTIN SALESMAN TURNER SALESMAN WARD You would like to format the result set such that each job gets its own column: CLERKS ANALYSTS MGRS PREZ SALES ------ -------- ----- ---- ------ MILLER FORD CLARK KING TURNER JAMES SCOTT BLAKE MARTIN ADAMS JONES WARD SMITH ALLEN ### Solution Unlike the first recipe in this chapter, the result set for this recipe consists of more than one row. Using the previous recipe's technique will not work for this recipe, as the MAX(ENAME) for each JOB would be returned, which would result in one ENAME for each JOB (i.e., one row will be returned as in the first recipe). To solve this problem, you must make each JOB/ENAME combination unique. Then, when you apply an aggregate function to remove NULLs, you don't lose any ENAMEs. #### DB2, Oracle, and SQL Server Use the window function ROW_NUMBER OVER to make each JOB/ENAME combination unique. Pivot the result set using a CASE expression and the aggregate function MAX while grouping on the value returned by the window function: 1 select max(case when job='CLERK' 2 then ename else null end) as clerks, 3 max(case when job='ANALYST' 4 then ename else null end) as analysts, 5 max(case when job='MANAGER' 6 then ename else null end) as mgrs, 7 max(case when job='PRESIDENT' 8 then ename else null end) as prez, 9 max(case when job='SALESMAN' 10 then ename else null end) as sales 11 from ( 12 select job, 13 ename, 14 row_number()over(partition by job order by ename) rn 15 from emp 16 ) x 17 group by rn #### PostgreSQL and MySQL Use a scalar subquery to rank each employee by EMPNO. Pivot the result set using a CASE expression and the aggregate function MAX while grouping on the value returned by the scalar subquery: 1 select max(case when job='CLERK' 2 then ename else null end) as clerks, 3 max(case when job='ANALYST' 4 then ename else null end) as analysts, 5 max(case when job='MANAGER' 6 then ename else null end) as mgrs, 7 max(case when job='PRESIDENT' 8 then ename else null end) as prez, 9 max(case when job='SALESMAN' 10 then ename else null end) as sales 11 from ( 12 select e.job, 13 e.ename, 14 (select count(*) from emp d 15 where e.job=d.job and e.empno < d.empno) as rnk 16 from emp e 17 ) x 18 group by rnk ### Discussion #### DB2, Oracle, and SQL Server The first step is to use the window function ROW_NUMBER OVER to help make each JOB/ENAME combination unique: **select job,** **ename,** **row_number()over(partition by job order by ename) rn** **from emp** JOB ENAME RN --------- ---------- ---------- ANALYST FORD 1 ANALYST SCOTT 2 CLERK ADAMS 1 CLERK JAMES 2 CLERK MILLER 3 CLERK SMITH 4 MANAGER BLAKE 1 MANAGER CLARK 2 MANAGER JONES 3 PRESIDENT KING 1 SALESMAN ALLEN 1 SALESMAN MARTIN 2 SALESMAN TURNER 3 SALESMAN WARD 4 Giving each ENAME a unique "row number" within a given job prevents any problems that might otherwise result from two employees having the same name and job. The goal here is to be able to group on row number (on RN) without dropping any employees from the result set due to the use of MAX. This step is the most important step in solving the problem. Without this first step, the aggregation in the outer query will remove necessary rows. Consider what the result set would look like without using ROW_NUMBER OVER, using the same technique as seen in the first recipe: **select max(case when job='CLERK'** **then ename else null end) as clerks,** **max(case when job='ANALYST'** **then ename else null end) as analysts,** **max(case when job='MANAGER'** **then ename else null end) as mgrs,** **max(case when job='PRESIDENT'** **then ename else null end) as prez,** **max(case when job='SALESMAN'** **then ename else null end) as sales** **from emp** CLERKS ANALYSTS MGRS PREZ SALES ---------- ---------- ---------- ---------- ---------- SMITH SCOTT JONES KING WARD Unfortunately, only one row is returned for each JOB: the employee with the MAX ENAME. When it comes time to pivot the result set, using MIN or MAX should serve as a means to remove NULLs from the result set, not restrict the ENAMEs returned. How this works will be come clearer as you continue through the explanation. The next step uses a CASE expression to organize the ENAMEs into their proper column (JOB): **select rn,** **case when job='CLERK'** **then ename else null end as clerks,** **case when job='ANALYST'** **then ename else null end as analysts,** **case when job='MANAGER'** **then ename else null end as mgrs,** **case when job='PRESIDENT'** **then ename else null end as prez,** **case when job='SALESMAN'** **then ename else null end as sales** **from (** **Select job,** **ename,** **row_number()over(partition by job order by ename) rn** **from emp** **) x** RN CLERKS ANALYSTS MGRS PREZ SALES -- ---------- ---------- ---------- ---------- ---------- 1 FORD 2 SCOTT 1 ADAMS 2 JAMES 3 MILLER 4 SMITH 1 BLAKE 2 CLARK 3 JONES 1 KING 1 ALLEN 2 MARTIN 3 TURNER 4 WARD At this point, the rows are transposed into columns and the last step is to remove the NULLs to make the result set more readable. To remove the NULLs use the aggregate function MAX and group by RN. (You can use the function MIN as well. The choice to use MAX is arbitrary, as you will only ever be aggregating one value per group.) There is only one value for each RN/JOB/ENAME combination. Grouping by RN in conjunction with the CASE expressions embedded within the calls to MAX ensures that each call to MAX results in picking only one name from a group of otherwise NULL values: **select max(case when job='CLERK'** **then ename else null end) as clerks,** **max(case when job='ANALYST'** **then ename else null end) as analysts,** **max(case when job='MANAGER'** **then ename else null end) as mgrs,** **max(case when job='PRESIDENT'** **then ename else null end) as prez,** **max(case when job='SALESMAN'** **then ename else null end) as sales** **from (** **Select job,** **ename,** **row_number()over(partition by job order by ename) rn** **from emp** **) x** **group by rn** CLERKS ANALYSTS MGRS PREZ SALES ------ -------- ----- ---- ------ MILLER FORD CLARK KING TURNER JAMES SCOTT BLAKE MARTIN ADAMS JONES WARD SMITH ALLEN The technique of using ROW_NUMBER OVER to create unique combinations of rows is extremely useful for formatting query results. Consider the query below that creates a sparse report showing employees by DEPTNO and JOB: **select deptno dno, job,** **max(case when deptno=10** **then ename else null end) as d10,** **max(case when deptno=20** **then ename else null end) as d20,** **max(case when deptno=30** **then ename else null end) as d30,** **max(case when job='CLERK'** **then ename else null end) as clerks,** **max(case when job='ANALYST'** **then ename else null end) as anals,** **max(case when job='MANAGER'** **then ename else null end) as mgrs,** **max(case when job='PRESIDENT'** **then ename else null end) as prez,** **max(case when job='SALESMAN'** **then ename else null end) as sales** **from (** **Select deptno,** **job,** **ename,** **row_number()over(partition by job order by ename) rn_job,** **row_number()over(partition by job order by ename) rn_deptno** **from emp** **) x** **group by deptno, job, rn_deptno, rn_job** **order by 1** DNO JOB D10 D20 D30 CLERKS ANALS MGRS PREZ SALES --- --------- ------ ----- ------ ------ ----- ----- ---- ------ 10 CLERK MILLER MILLER 10 MANAGER CLARK CLARK 10 PRESIDENT KING KING 20 ANALYST FORD FORD 20 ANALYST SCOTT SCOTT 20 CLERK ADAMS ADAMS 20 CLERK SMITH SMITH 20 MANAGER JONES JONES 30 CLERK JAMES JAMES 30 MANAGER BLAKE BLAKE 30 SALESMAN ALLEN ALLEN 30 SALESMAN MARTIN MARTIN 30 SALESMAN TURNER TURNER 30 SALESMAN WARD WARD By simply modifying what you group by (hence the nonaggregate items in the SELECT list above), you can produce reports with different formats. It is worth the time of changing things around to understand how these formats change based on what you include in your GROUP BY clause. #### PostgreSQL and MySQL The technique for these RDBMSs is the same as for the others once a method of creating unique JOB/ENAME combinations is established. The first step is to use a scalar subquery to provide a "row number" or "rank" for each JOB/ENAME combination: **select e.job,** **e.ename,** **(select count(*) from emp d** **where e.job=d.job and e.empno< d.empno) as rnk** **from emp e** JOB ENAME RNK --------- ---------- ---------- CLERK SMITH 3 SALESMAN ALLEN 3 SALESMAN WARD 2 MANAGER JONES 2 SALESMAN MARTIN 1 MANAGER BLAKE 1 MANAGER CLARK 0 ANALYST SCOTT 1 PRESIDENT KING 0 SALESMAN TURNER 0 CLERK ADAMS 2 CLERK JAMES 1 ANALYST FORD 0 CLERK MILLER 0 Giving each JOB/ENAME combination a unique "rank" makes each row unique. Even if there are employees with the same name working the same job, no two employees will share the same rank within a job. This step is the most important step in solving the problem. Without this first step, the aggregation in the outer query will remove necessary rows. Consider what the result set would look like without applying a rank to each JOB/ENAME combination, using the same technique as seen in the first recipe: **select max(case when job='CLERK'** **then ename else null end) as clerks,** **max(case when job='ANALYST'** **then ename else null end) as analysts,** **max(case when job='MANAGER'** **then ename else null end) as mgrs,** **max(case when job='PRESIDENT'** **then ename else null end) as prez,** **max(case when job='SALESMAN'** **then ename else null end) as sales** **from emp** CLERKS ANALYSTS MGRS PREZ SALES ---------- ---------- ---------- ---------- ---------- SMITH SCOTT JONES KING WARD Unfortunately, only one row is returned for each JOB: the employee with the MAX ENAME. When it comes time to pivot the result set, using MIN or MAX should serve as a means to remove NULLs from the result set, not to restrict the ENAMEs returned. Now, that you see the purpose of applying a rank, you can move on to the next step. The next step uses a CASE expression to organize the ENAMEs into their proper column (JOB): **select rnk,** **case when job='CLERK'** **then ename else null end as clerks,** **case when job='ANALYST'** **then ename else null end as analysts,** **case when job='MANAGER'** **then ename else null end as mgrs,** **case when job='PRESIDENT'** **then ename else null end as prez,** **case when job='SALESMAN'** **then ename else null end as sales** **from (** **Select e.job,** **e.ename,** **(select count(*) from emp d** **where e.job=d.job and e.empno< d.empno) as rnk** **from emp e** **) x** RNK CLERKS ANALYSTS MGRS PREZ SALES --- ------ -------- ----- ---- ---------- 3 SMITH 3 ALLEN 2 WARD 2 JONES 1 MARTIN 1 BLAKE 0 CLARK 1 SCOTT 0 KING 0 TURNER 2 ADAMS 1 JAMES 0 FORD 0 MILLER At this point, the rows are transposed into columns and the last step is to remove the NULLs to make the result set more readable. To remove the NULLs use the aggregate function MAX and group by RNK. (MAX is an arbitrary choice. You can use the function MIN as well.) There is only one value for each RN/JOB/ENAME combination, so the application of the aggregate function is simply to remove NULLs: **select max(case when job='CLERK'** **then ename else null end) as clerks,** **max(case when job='ANALYST'** **then ename else null end) as analysts,** **max(case when job='MANAGER'** **then ename else null end) as mgrs,** **max(case when job='PRESIDENT'** **then ename else null end) as prez,** **max(case when job='SALESMAN'** **then ename else null end) as sales** **from (** **Select e.job,** **e.ename,** **(select count(*) from emp d** **where e.job=d.job and e.empno< d.empno) as rnk** **from emp e** **) x** **group by rnk** CLERKS ANALYSTS MGRS PREZ SALES ------ -------- ----- ---- ------ MILLER FORD CLARK KING TURNER JAMES SCOTT BLAKE MARTIN ADAMS JONES WARD SMITH ALLEN ## 12.3. Reverse Pivoting a Result Set ### Problem You want to transform columns to rows. Consider the following result set: DEPTNO_10 DEPTNO_20 DEPTNO_30 ---------- ---------- ---------- 3 5 6 You would like to convert that to: DEPTNO COUNTS_BY_DEPT ------ -------------- 10 3 20 5 30 6 ### Solution Examining the desired result set, it's easy to see that you can execute a simple COUNT and GROUP BY on table EMP to produce the desired result. The object here, though, is to imagine that the data is not stored as rows; perhaps the data is denormalized and aggregated values are stored as multiple columns. To convert columns to rows, use a Cartesian product. You'll need to know in advance how many columns you want to convert to rows because the table expression you use to create the Cartesian product must have a cardinality of at least the number of columns you want to transpose. Rather than create a denormalized table of data, the solution for this recipe will use the solution from the first recipe of this chapter to create a "wide" result set. The full solution is as follows: 1 select dept.deptno, 2 case dept.deptno 3 when 10 then emp_cnts.deptno_10 4 when 20 then emp_cnts.deptno_20 5 when 30 then emp_cnts.deptno_30 6 end as counts_by_dept 7 from ( 8 select sum(case when deptno=10 then 1 else 0 end) as deptno_10, 9 sum(case when deptno=20 then 1 else 0 end) as deptno_20, 10 sum(case when deptno=30 then 1 else 0 end) as deptno_30 11 from emp 12 ) emp_cnts, 13 (select deptno from dept where deptno <= 30) dept ### Discussion The inline view EMP_CNTS represents the denormalized view, or "wide" result set that you want to convert to rows, and is shown below: **select sum(case when deptno=10 then 1 else 0 end) as deptno_10,** **sum(case when deptno=20 then 1 else 0 end) as deptno_20,** **sum(case when deptno=30 then 1 else 0 end) as deptno_30** **from emp** DEPTNO_10 DEPTNO_20 DEPTNO_30 --------- ---------- ---------- 3 5 6 Because there are three columns, you will create three rows. Begin by creating a Cartesian product between inline view EMP_CNTS and some table expression that has at least three rows. The following code uses table DEPT to create the Cartesian product; DEPT has four rows: **select dept.deptno,** **emp_cnts.deptno_10,** **emp_cnts.deptno_20,** **emp_cnts.deptno_30** **from (** **Select sum(case when deptno=10 then 1 else 0 end) as deptno_10,** **sum(case when deptno=20 then 1 else 0 end) as deptno_20,** **sum(case when deptno=30 then 1 else 0 end) as deptno_30** **from emp** **) emp_cnts,** **(select deptno from dept where deptno<= 30) dept** DEPTNO DEPTNO_10 DEPTNO_20 DEPTNO_30 ------ ---------- ---------- --------- 10 3 5 6 20 3 5 6 30 3 5 6 The Cartesian product enables you to return a row for each column in inline view EMP_CNTS. Since the final result set should have only the DEPTNO and the number of employees in said DEPTNO, use a CASE expression to transform the three columns into one: **select dept.deptno,** **case dept.deptno** **when 10 then emp_cnts.deptno_10** **when 20 then emp_cnts.deptno_20** **when 30 then emp_cnts.deptno_30** **end as counts_by_dept** **from (** **Select sum(case when deptno=10 then 1 else 0 end) as deptno_10,** **sum(case when deptno=20 then 1 else 0 end) as deptno_20,** **sum(case when deptno=30 then 1 else 0 end) as deptno_30** **from emp** **) emp_cnts,** **(select deptno from dept where deptno<= 30) dept** DEPTNO COUNTS_BY_DEPT ------ -------------- 10 3 20 5 30 6 ## 12.4. Reverse Pivoting a Result Set into One Column ### Problem You want to return all columns from a query as just one column. For example, you want to return the ENAME, JOB, and SAL of all employees in DEPTNO 10, and you want to return all three values in one column. You want to return three rows for each employee and one row of white space between employees. You want to return the following result set: EMPS ---------- CLARK MANAGER 2450 KING PRESIDENT 5000 MILLER CLERK 1300 ### Solution The key is to use a Cartesian product to return four rows for each employee. This lets you return one column value per row and have an extra row for spacing between employees. #### DB2, Oracle, and SQL Server Use the window function ROW_NUMBER OVER to rank each row based on EMPNO (1–4). Then use a CASE expression to transform three columns into one: 1 select case rn 2 when 1 then ename 3 when 2 then job 4 when 3 then cast(sal as char(4)) 5 end emps 6 from ( 7 select e.ename,e.job,e.sal, 8 row_number()over(partition by e.empno 9 order by e.empno) rn 10 from emp e, 11 (select * 12 from emp where job='CLERK') four_rows 13 where e.deptno=10 14 ) x #### PostgreSQL and MySQL This recipe is meant to highlight the use of window functions to provide a ranking for your rows, which then comes into play later when pivoting. At the time of this writing, neither PostgreSQL nor MySQL support window functions. ### Discussion #### DB2, Oracle, and SQL Server The first step is to use the window function ROW_NUMBER OVER to create a ranking for each employee in DEPTNO 10: **select e.ename,e.job,e.sal,** **row_number()over(partition by e.empno** **order by e.empno) rn** **from emp e** **where e.deptno=10** ENAME JOB SAL RN ---------- --------- ---------- ---------- CLARK MANAGER 2450 1 KING PRESIDENT 5000 1 MILLER CLERK 1300 1 At this point the ranking doesn't mean much. You are partitioning by EMPNO, so the rank is 1 for all three rows in DEPTNO 10. Once you add the Cartesian product, the rank will begin to take shape, as can be seen in the following results: **select e.ename,e.job,e.sal,** **row_number()over(partition by e.empno** **order by e.empno) rn** **from emp e,** **(select *** **from emp where job='CLERK') four_rows** **where e.deptno=10** ENAME JOB SAL RN ---------- --------- ---------- ---------- CLARK MANAGER 2450 1 CLARK MANAGER 2450 2 CLARK MANAGER 2450 3 CLARK MANAGER 2450 4 KING PRESIDENT 5000 1 KING PRESIDENT 5000 2 KING PRESIDENT 5000 3 KING PRESIDENT 5000 4 MILLER CLERK 1300 1 MILLER CLERK 1300 2 MILLER CLERK 1300 3 MILLER CLERK 1300 4 You should stop at this point and understand two key points: * RN is no longer 1 for each employee; it is now a repeating sequence of values from 1 to 4, the reason being, window functions are applied after the FROM and WHERE clauses are evaluated. So, partitioning by EMPNO causes the RN to reset to 1 when a new employee is encountered. * The inline view FOUR_ROWS is simply that a SQL statement exists simply to return four rows. That is all it does. You want to return a row for every column (ENAME, JOB, SAL) plus an additional row for whitespace. At this point, the hard work is done and all that is left is to use a CASE expression to put ENAME, JOB, and SAL into one column for each employee (you need to cast SAL to a string to make CASE happy): **select case rn** **when 1 then ename** **when 2 then joB** **when 3 then cast(sal as char(4))** **end emps** **from (** **Select e.ename,e.job,e.sal,** **row_number()over(partition by e.empno** **order by e.empno) rn** **from emp e,** **(select *** **from emp where job='CLERK') four_rows** **where e.deptno=10** **) x** EMPS ---------- CLARK MANAGER 2450 KING PRESIDENT 5000 MILLER CLERK 1300 ## 12.5. Suppressing Repeating Values from a Result Set ### Problem You are generating a report, and, when two rows have the same value in a column, you wish to display that value only once. For example, you want to return DEPTNO and ENAME from table EMP, you wish to group all rows for each DEPTNO, and you wish to display each DEPTNO only one time. You want to return the following result set: DEPTNO ENAME ------ --------- 10 CLARK KING MILLER 20 SMITH ADAMS FORD SCOTT JONES 30 ALLEN BLAKE MARTIN JAMES TURNER WARD ### Solution This is a simple formatting problem that is easily solved by the window function LAG OVER provided by Oracle. There are other methods such as scalar subqueries and other window functions that you can use (and that you'll have to use for non-Oracle platforms), but LAG OVER is most convenient and appropriate here. #### DB2 and SQL Server You can use the window function MIN OVER to find the smallest EMPNO for each DEPTNO. Then use a CASE expression to "white out" the rows that do not have this EMPNO: 1 select case when empno=min_empno 2 then deptno else null 3 end deptno, 4 ename 5 from ( 6 select deptno, 7 min(empno)over(partition by deptno) min_empno, 8 empno, 9 ename 10 from emp 11 ) x #### Oracle Use the window function LAG OVER to access prior rows relative to the current row, to find the first DEPTNO for each partition: 1 select to_number( 2 decode(lag(deptno)over(order by deptno), 3 deptno,null,deptno) 4 ) deptno, ename 5 from emp #### PostgreSQL and MySQL This recipe highlights the use of window functions for easily accessing rows around your current row. At the time of this writing, these vendors do not support window functions. ### Discussion #### DB2 and SQL Server The first step is to use the window function MIN OVER to find the lowest EMPNO in each DEPTNO: **select deptno,** **min(empno)over(partition by deptno) min_empno,** **empno,** **ename** **from emp** DEPTNO MIN_EMPNO EMPNO ENAME ------ ---------- ---------- ---------- 10 7782 7782 CLARK 10 7782 7839 KING 10 7782 7934 MILLER 20 7369 7369 SMITH 20 7369 7876 ADAMS 20 7369 7902 FORD 20 7369 7788 SCOTT 20 7369 7566 JONES 30 7499 7499 ALLEN 30 7499 7698 BLAKE 30 7499 7654 MARTIN 30 7499 7900 JAMES 30 7499 7844 TURNER 30 7499 7521 WARD The next and last step is to use a CASE expression to suppress the repeated display of DEPTNO. If an employee's EMPNO matches MIN_EMPNO, return DEPTNO, otherwise return NULL: **select case when empno=min_empno** **then deptno else null** **end deptno,** **ename** **from (** **Select deptno,** **min(empno)over(partition by deptno) min_empno,** **empno,** **ename** **from emp** **) x** DEPTNO ENAME ------ ---------- 10 CLARK KING MILLER 20 SMITH ADAMS FORD SCOTT JONES 30 ALLEN BLAKE MARTIN JAMES TURNER WARD #### Oracle The first step is to use the window function LAG OVER to return the prior DEPTNO for each row: Select lag(deptno)over(order by deptno) lag_deptno, deptno, ename from emp LAG_DEPTNO DEPTNO ENAME ---------- ---------- ---------- 10 CLARK 10 10 KING 10 10 MILLER 10 20 SMITH 20 20 ADAMS 20 20 FORD 20 20 SCOTT 20 20 JONES 20 30 ALLEN 30 30 BLAKE 30 30 MARTIN 30 30 JAMES 30 30 TURNER 30 30 WARD If you eyeball the result set above, you can easily see where DEPTNO matches LAG_ DEPTNO. For those rows, you want to set DEPTNO to NULL. Do that by using DECODE (TO_NUMBER is included to cast DEPTNO as a number): **select to_number(** **decode(lag(deptno)over(order by deptno),** **deptno,null,deptno)** **) deptno, ename** **from emp** DEPTNO ENAME ------ ---------- 10 CLARK KING MILLER 20 SMITH ADAMS FORD SCOTT JONES 30 ALLEN BLAKE MARTIN JAMES TURNER WARD ## 12.6. Pivoting a Result Set to Facilitate Inter-Row Calculations ### Problem You wish to make calculations involving data from multiple rows. To make your job easier, you wish to pivot those rows into columns such that all values you need are then in a single row. In this book's example data, DEPTNO 20 is the department with the highest combined salary, which you can confirm by executing the following query: **select deptno, sum(sal) as sal** **from emp** **group by deptno** DEPTNO SAL ------ ---------- 10 8750 20 10875 30 9400 You want to calculate the difference between the salaries of DEPTNO 20 and DEPTNO 10 and between DEPTNO 20 and DEPTNO 30. ### Solution Transpose the totals using the aggregate function SUM and a CASE expression. Then code your expressions in the select list: 1 select d20_sal - d10_sal as d20_10_diff, 2 d20_sal - d30_sal as d20_30_diff 3 from ( 4 select sum(case when deptno=10 then sal end) as d10_sal, 5 sum(case when deptno=20 then sal end) as d20_sal, 6 sum(case when deptno=30 then sal end) as d30_sal 7 from emp 8 ) totals_by_dept ### Discussion The first step is to pivot the salaries for each DEPTNO from rows to columns by using a CASE expression: **select case when deptno=10 then sal end as d10_sal,** **case when deptno=20 then sal end as d20_sal,** **case when deptno=30 then sal end as d30_sal** **from emp** D10_SAL D20_SAL D30_SAL ------- ---------- ---------- 800 1600 1250 2975 1250 2850 2450 3000 5000 1500 1100 950 3000 1300 The next step is to sum all the salaries for each DEPTNO by applying the aggregate function SUM to each CASE expression: **select sum(case when deptno=10 then sal end) as d10_sal,** **sum(case when deptno=20 then sal end) as d20_sal,** **sum(case when deptno=30 then sal end) as d30_sal** **from emp** D10_SAL D20_SAL D30_SAL ------- ---------- ---------- 8750 10875 9400 The final step is to simply wrap the above SQL in an inline view and perform the subtractions. ## 12.7. Creating Buckets of Data, of a Fixed Size ### Problem You wish to organized data into evenly sized buckets, with a predetermined number of elements in each bucket. The total number of buckets may be unknown, but you want to ensure that each bucket has five elements. For example, you want to organize the employees in table EMP into groups of five based on the value of EMPNO, as shown in the following results: GRP EMPNO ENAME --- ---------- ------- 1 7369 SMITH 1 7499 ALLEN 1 7521 WARD 1 7566 JONES 1 7654 MARTIN 2 7698 BLAKE 2 7782 CLARK 2 7788 SCOTT 2 7839 KING 2 7844 TURNER 3 7876 ADAMS 3 7900 JAMES 3 7902 FORD 3 7934 MILLER ### Solution The solution to this problem is greatly simplified if your RDBMS provides functions for ranking rows. Once rows are ranked, creating buckets of five is simply a matter of dividing and then taking the mathematical ceiling of the quotient. #### DB2, Oracle, and SQL Server Use the window function ROW_NUMBER OVER to rank each employee by EMPNO. Then divide by 5 to create the groups (SQL Server users will use CEILING, not CEIL): 1 select ceil(row_number()over(order by empno)/5.0) grp, 2 empno, 3 ename 4 from emp #### PostgreSQL and MySQL Use a scalar subquery to rank each EMPNO. Then divide by 5 to create the groups: 1 select ceil(rnk/5.0) as grp, 2 empno, ename 3 from ( 4 select e.empno, e.ename, 5 (select count(*) from emp d 6 where e.empno > d.empno)+1 as rnk 7 from emp e 8 ) x 9 order by grp ### Discussion #### DB2, Oracle, and SQL Server The window function ROW_NUMBER OVER assigns a rank or "row number" to each row sorted by EMPNO: **select row_number()over(order by empno) rn,** **empno,** **ename** **from emp** RN EMPNO ENAME -- ---------- ---------- 1 7369 SMITH 2 7499 ALLEN 3 7521 WARD 4 7566 JONES 5 7654 MARTIN 6 7698 BLAKE 7 7782 CLARK 8 7788 SCOTT 9 7839 KING 10 7844 TURNER 11 7876 ADAMS 12 7900 JAMES 13 7902 FORD 14 7934 MILLER The next step is to apply the function CEIL (or CEILING) after dividing ROW_ NUMBER OVER by five. Dividing by five logically organizes the rows into groups of five, i.e., five values less than or equal to 1, five values greater than 1 but less than or equal to 2, the remaining group (composed of the last four rows since 14, the number of rows in table EMP, is not a multiple of 5) has a value greater than 2 but less than or equal to 3. The CEIL function will return the smallest whole number greater than the value passed to it; this will create whole number groups. The results of the division and application of the CEIL are shown below. You can follow the order of operation from left to right, from RN to DIVISION to GRP: **select row_number()over(order by empno) rn,** **row_number()over(order by empno)/5.0 division,** **ceil(row_number()over(order by empno)/5.0) grp,** **empno,** **ename** **from emp** RN DIVISION GRP EMPNO ENAME -- ---------- --- ----- ---------- 1 .2 1 7369 SMITH 2 .4 1 7499 ALLEN 3 .6 1 7521 WARD 4 .8 1 7566 JONES 5 1 1 7654 MARTIN 6 1.2 2 7698 BLAKE 7 1.4 2 7782 CLARK 8 1.6 2 7788 SCOTT 9 1.8 2 7839 KING 10 2 2 7844 TURNER 11 2.2 3 7876 ADAMS 12 2.4 3 7900 JAMES 13 2.6 3 7902 FORD 14 2.8 3 7934 MILLER #### PostgreSQL and MySQL The first step is to use a scalar subquery to rank each row by EMPNO: **select (select count(*) from emp d** **where e.empno< d.empno)+1 as rnk,** **e.empno, e.ename** **from emp e** **order by 1** RNK EMPNO ENAME --- ---------- ---------- 1 7934 MILLER 2 7902 FORD 3 7900 JAMES 4 7876 ADAMS 5 7844 TURNER 6 7839 KING 7 7788 SCOTT 8 7782 CLARK 9 7698 BLAKE 10 7654 MARTIN 11 7566 JONES 12 7521 WARD 13 7499 ALLEN 14 7369 SMITH The next step is to apply the function CEIL after dividing RNK by 5. Dividing by 5 logically organizes the rows into groups of five, i.e., five values less than or equal to 1, five values greater than one but less than or equal to 2, the remaining group (composed of the last four rows since 14, the number of rows in table EMP, is not a multiple of 5) has a value greater than 2 but less than or equal to 3. The results of the division and application of the CEIL are shown below. You can follow the order of operation from left to right as you work your way from RNK over to GRP: **select rnk,** **rnk/5.0 as division,** **ceil(rnk/5.0) as grp,** **empno, ename** **from (** **Select e.empno, e.ename,** **(select count(*) from emp d** **where e.empno< d.empno)+1 as rnk** **from emp e** **) x** **order by 1** RNK DIVISION GRP EMPNO ENAME --- ---------- --- ----- ------- 1 .2 1 7934 MILLER 2 .4 1 7902 FORD 3 .6 1 7900 JAMES 4 .8 1 7876 ADAMS 5 1 1 7844 TURNER 6 1.2 2 7839 KING 7 1.4 2 7788 SCOTT 8 1.6 2 7782 CLARK 9 1.8 2 7698 BLAKE 10 2 2 7654 MARTIN 11 2.2 3 7566 JONES 12 2.4 3 7521 WARD 13 2.6 3 7499 ALLEN 14 2.8 3 7369 SMITH ## 12.8. Creating a Predefined Number of Buckets ### Problem You want to organize your data into a fixed number of buckets. For example, you want to organize the employees in table EMP into four buckets. The result set should look similar to the following: GRP EMPNO ENAME --- ----- --------- 1 7369 SMITH 1 7499 ALLEN 1 7521 WARD 1 7566 JONES 2 7654 MARTIN 2 7698 BLAKE 2 7782 CLARK 2 7788 SCOTT 3 7839 KING 3 7844 TURNER 3 7876 ADAMS 4 7900 JAMES 4 7902 FORD 4 7934 MILLER This problem is the opposite of the previous recipe, where you had an unknown number of buckets but a predetermined number of elements in each bucket. In this recipe, the goal is such that you may not necessarily know how many elements are in each bucket, but you are defining a fixed (known) number of buckets to be created. ### Solution The solution to this problem is trivial if your RDBMS provides functions for creating "buckets" of rows. If your RDBMS provides no such functions, you can simply rank each row, and then use the modulus of said rank and _n_ , where _n_ is the number of buckets you wish to create, in an expression to determine into which bucket the row falls. Where available, this solution will make use of the NTILE window function for creating a fixed number of buckets. NTILE organizes an ordered set into the number of buckets you specify, with any stragglers distributed into the available buckets starting from the first bucket. The desired result set for this recipe reflects this: buckets 1 and 2 have four rows while buckets 3 and 4 have three rows. If your RDBMS does not support NTILE, don't worry about which rows are in which buckets; the main goal of this recipe is to create the fixed number of buckets you are requesting. #### DB2 Use the window function ROW_NUMBER OVER window function to rank the rows by EMPNO, then use the modulus of the rank and 4 to create four buckets: 1 select mod(row_number()over(order by empno),4)+1 grp, 2 empno, 3 ename 4 from emp 5 order by 1 #### Oracle and SQL Server The DB2 solution will work for these vendors but alternatively (conveniently) you may use the NTILE window function to create four buckets: 1 select ntile(4)over(order by empno) grp, 2 empno, 3 ename 4 from emp #### MySQL, and PostgreSQL Use a self join to rank the rows by EMPNO, then use the modulus of the rank and 4 to create your buckets: 1 select mod(count(*),4)+1 as grp, 2 e.empno, 3 e.ename 4 from emp e, emp d 5 where e.empno >= d.empno 6 group by e.empno,e.ename 7 order by 1 ### Discussion #### DB2 The first step is to use the window function ROW_NUMBER OVER to rank each row by EMPNO: **select row_number()over(order by empno) grp,** **empno,** **ename** **from emp** GRP EMPNO ENAME --- ----- ------ 1 7369 SMITH 2 7499 ALLEN 3 7521 WARD 4 7566 JONES 5 7654 MARTIN 6 7698 BLAKE 7 7782 CLARK 8 7788 SCOTT 9 7839 KING 10 7844 TURNER 11 7876 ADAMS 12 7900 JAMES 13 7902 FORD 14 7934 MILLER Now that the rows are ranked, use the modulo function, MOD, to create four buckets: **select mod(row_number()over(order by empno),4) grp,** **empno,** **ename** **from emp** GRP EMPNO ENAME --- ----- ------ 1 7369 SMITH 2 7499 ALLEN 3 7521 WARD 0 7566 JONES 1 7654 MARTIN 2 7698 BLAKE 3 7782 CLARK 0 7788 SCOTT 1 7839 KING 2 7844 TURNER 3 7876 ADAMS 0 7900 JAMES 1 7902 FORD 2 7934 MILLER The last step is to add one GRP so the buckets start at 1, not 0, and use ORDER BY on GRP to order the rows by bucket. #### Oracle and SQL Server All the work is done by the NTILE function. Simply pass it a number representing the number of buckets you want, and watch the magic unfold right in front of your eyes. #### MySQL and PostgreSQL The fist step is to generate a Cartesian product with table EMP so that each EMPNO can be compared with every other EMPNO [only a snippet of the Cartesian is shown below because there would be 196 rows returned (14x14)]: **select e.empno,** **e.ename,** **d.empno,** **d.ename** **from emp e, emp d** EMPNO ENAME EMPNO ENAME ----- ---------- ---------- --------- 7369 SMITH 7369 SMITH 7369 SMITH 7499 ALLEN 7369 SMITH 7521 WARD 7369 SMITH 7566 JONES 7369 SMITH 7654 MARTIN 7369 SMITH 7698 BLAKE 7369 SMITH 7782 CLARK 7369 SMITH 7788 SCOTT 7369 SMITH 7839 KING 7369 SMITH 7844 TURNER 7369 SMITH 7876 ADAMS 7369 SMITH 7900 JAMES 7369 SMITH 7902 FORD 7369 SMITH 7934 MILLER ... As you can see from this result set, you can compare SMITH's EMPNO to the EMPNO of all the other employees in EMP (you can compare each employee's EMPNO with all the other employees' EMPNOs). The next step is to restrict the Cartesian product to only those EMPNOs that are greater than or equal to another EMPNO. A portion of the result set (as there are 105 rows) is shown below: **select e.empno,** **e.ename,** **d.empno,** **d.ename** **from emp e, emp d** **where e.empno>= d.empno** EMPNO ENAME EMPNO ENAME ----- ---------- ---------- ---------- 7934 MILLER 7934 MILLER 7934 MILLER 7902 FORD 7934 MILLER 7900 JAMES 7934 MILLER 7876 ADAMS 7934 MILLER 7844 TURNER 7934 MILLER 7839 KING 7934 MILLER 7788 SCOTT 7934 MILLER 7782 CLARK 7934 MILLER 7698 BLAKE 7934 MILLER 7654 MARTIN 7934 MILLER 7566 JONES 7934 MILLER 7521 WARD 7934 MILLER 7499 ALLEN 7934 MILLER 7369 SMITH ... 7499 ALLEN 7499 ALLEN 7499 ALLEN 7369 SMITH 7369 SMITH 7369 SMITH Of the entire result set, I've included only rows (from EMP E) for MILLER, ALLEN, and SMITH in this output. The reason is to show you how the Cartesian product has been restricted by the WHERE clause. Because the filter on EMPNO in the WHERE clause uses "greater than or equal to," you know you will get at least one row for each employee because each EMPNO is equal to itself. But why is there only one row for SMITH (on the left-hand side of the result set) when there are two rows for ALLEN and 14 rows for MILLER? The reason is the compound evaluation on EMPNO in the WHERE clause: "greater than or equal to". In SMITH's case, there is no EMPNO that 7369 is greater than, so only one row is returned for SMITH. In ALLEN's case, ALLEN's EMPNO is obviously equal to itself (so that row is returned), but 7499 is also greater than 7369 (SMITH's EMPNO) so two rows are returned for ALLEN. In the case of MILLER's EMPNO 7934, it is greater than all the other EMPNOs in table EMP (and obviously equal to itself ) so there are 14 MILLER rows returned. Now you can compare each EMPNO and determine which ones are greater than others. Use the aggregate function COUNT to return the self join as a more expressive result set: **select count(*) as grp,** **e.empno,** **e.ename** **from emp e, emp d** **where e.empno>= d.empno** **group by e.empno,e.ename** **order by 1** GRP EMPNO ENAME --- ---------- ---------- 1 7369 SMITH 2 7499 ALLEN 3 7521 WARD 4 7566 JONES 5 7654 MARTIN 6 7698 BLAKE 7 7782 CLARK 8 7788 SCOTT 9 7839 KING 10 7844 TURNER 11 7876 ADAMS 12 7900 JAMES 13 7902 FORD 14 7934 MILLER Now that the rows are ranked, simply add 1 to the modulus of GRP and 4 to create four buckets (adding 1 so the buckets start at 1, not 0). Use the ORDER BY clause on GRP to order the buckets appropriately: **select mod(count(*),4)+1 as grp,** **e.empno,** **e.ename** **from emp e, emp d** **where e.empno>= d.empno** **group by e.empno,e.ename** **order by 1** GRP EMPNO ENAME --- ---------- --------- 1 7900 JAMES 1 7566 JONES 1 7788 SCOTT 2 7369 SMITH 2 7902 FORD 2 7654 MARTIN 2 7839 KING 3 7499 ALLEN 3 7698 BLAKE 3 7934 MILLER 3 7844 TURNER 4 7521 WARD 4 7782 CLARK 4 7876 ADAMS ## 12.9. Creating Horizontal Histograms ### Problem You want to use SQL to generate histograms that extend horizontally. For example, you want to display the number of employees in each department as a horizontal histogram with each employee represented by an instance of "*". You want to return the following result set: DEPTNO CNT ------ ---------- 10 *** 20 ***** 30 ****** ### Solution The key to this solution is to use the aggregate function COUNT, and use GROUP BY DEPTNO to determine the number of employees in each DEPTNO. The value returned by COUNT is then passed to a string function that generates a series of "*" characters. #### DB2 Use the REPEAT function to generate the histogram: 1 select deptno, 2 repeat('*',count(*)) cnt 3 from emp 4 group by deptno #### Oracle, PostgreSQL, and MySQL Use the LPAD function to generate the needed strings of "*" characters: 1 select deptno, 2 lpad('*',count(*),'*') as cnt 3 from emp 4 group by deptno #### SQL Server Generate the histogram using the REPLICATE function: 1 select deptno, 2 replicate('*',count(*)) cnt 3 from emp 4 group by deptno ### Discussion The technique is the same for all vendors. The only difference lies in the string function used to return a "*" for each employee. The Oracle solution will be used for this discussion, but the explanation is relevant for all the solutions. The first step is to count the number of employees in each department: **select deptno,** **count(*)** **from emp** **group by deptno** DEPTNO COUNT(*) ------ ---------- 10 3 20 5 30 6 The next step is to use the value returned by COUNT(*) to control the number of "*"characters to return for each department. Simply pass COUNT(*) as an argument to the string function LPAD to return the desired number of "*"s: **select deptno,** **lpad('*',count(*),'*') as cnt** **from emp** **group by deptno** DEPTNO CNT ------ ---------- 10 *** 20 ***** 30 ****** For PostgreSQL users, you may need to explicitly cast the value returned by COUNT(*) to an integer as can be seen below: **select deptno,** **lpad('*',count(*)::integer,'*') as cnt** **from emp** **group by deptno** DEPTNO CNT ------ ---------- 10 *** 20 ***** 30 ****** This CAST is necessary because PostgreSQL requires the numeric argument to LPAD to be an integer. ## 12.10. Creating Vertical Histograms ### Problem You want to generate a histogram that grows from the bottom up. For example, you want to display the number of employees in each department as a vertical histogram with each employee represented by an instance of "*". You want to return the following result set: D10 D20 D30 --- --- --- * * * * * * * * * * * * * * ### Solution The technique used to solve this problem is built upon that used as the second recipe in this chapter: . #### DB2, Oracle, and SQL Server Use the ROW_NUMBER OVER function to uniquely identify each instance of "*" for each DEPTNO. Use the aggregate function MAX to pivot the result set and group by the values returned by ROW_NUMBER OVER (SQL Server users should not use DESC in the ORDER BY clause): 1 select max(deptno_10) d10, 2 max(deptno_20) d20, 3 max(deptno_30) d30 4 from ( 5 select row_number()over(partition by deptno order by empno) rn, 6 case when deptno=10 then '*' else null end deptno_10, 7 case when deptno=20 then '*' else null end deptno_20, 8 case when deptno=30 then '*' else null end deptno_30 9 from emp 10 ) x 11 group by rn 12 order by 1 desc, 2 desc, 3 desc #### PostgreSQL and MySQL Use a scalar subquery to uniquely identify each instance of "*" for each DEPTNO. Use the aggregate function MAX on the values returned by inline view X, while also grouping by RNK to pivot the result set. MySQL users should not use DESC in the ORDER BY clause: 1 select max(deptno_10) as d10, 2 max(deptno_20) as d20, 3 max(deptno_30) as d30 4 from ( 5 select case when e.deptno=10 then '*' else null end deptno_10, 6 case when e.deptno=20 then '*' else null end deptno_20, 7 case when e.deptno=30 then '*' else null end deptno_30, 8 (select count(*) from emp d 9 where e.deptno=d.deptno and e.empno < d.empno ) as rnk 10 from emp e 11 ) x 12 group by rnk 13 order by 1 desc, 2 desc, 3 desc ### Discussion #### DB2, Oracle, and SQL Server The first step is to use the window function ROW_NUMBER to uniquely identify each instance of "*" in each department. Use a CASE expression to return a "*" for each employee in each department: **select row_number()over(partition by deptno order by empno) rn,** **case when deptno=10 then '*' else null end deptno_10,** **case when deptno=20 then '*' else null end deptno_20,** **case when deptno=30 then '*' else null end deptno_30** **from emp** RN DEPTNO_10 DEPTNO_20 DEPTNO_30 -- ---------- ---------- --------- 1 * 2 * 3 * 1 * 2 * 3 * 4 * 5 * 1 * 2 * 3 * 4 * 5 * 6 * The next and last step is to use the aggregate function MAX on each CASE expression, grouping by RN to remove the NULLs from the result set. Order the results ASC or DESC depending on how your RDBMS sorts NULLs: **select max(deptno_10) d10,** **max(deptno_20) d20,** **max(deptno_30) d30** **from (** **Select row_number()over(partition by deptno order by empno) rn,** **case when deptno=10 then '*' else null end deptno_10,** **case when deptno=20 then '*' else null end deptno_20,** **case when deptno=30 then '*' else null end deptno_30** **from emp** **) x** **group by rn** **order by 1 desc, 2 desc, 3 desc** D10 D20 D30 --- --- --- * * * * * * * * * * * * * * #### PostgreSQL and MySQL The first step is to use a scalar subquery to uniquely identify each instance of "*" in each department. The scalar subquery ranks the employees by EMPNO in each DEPTNO, so there can be no duplicates. Use a CASE expression to generate a "*" for each employee in each department: **select case when e.deptno=10 then '*' else null end deptno_10,** **case when e.deptno=20 then '*' else null end deptno_20,** **case when e.deptno=30 then '*' else null end deptno_30,** **(select count(*) from emp d** **where e.deptno=d.deptno and e.empno< d.empno ) as rnk** **from emp e** DEPTNO_10 DEPTNO_20 DEPTNO_30 RNK ---------- ---------- ---------- ---------- * 4 * 5 * 4 * 3 * 3 * 2 * 2 * 2 * 1 * 1 * 1 * 0 * 0 * 0 Then use the aggregate function MAX on each CASE expression, being sure to group by RNK to remove the NULLs from the result set. Order the results ASC or DESC depending on how your RDBMS sorts NULLs: **select max(deptno_10) as d10,** **max(deptno_20) as d20,** **max(deptno_30) as d30** **from (** **Select case when e.deptno=10 then '*' else null end deptno_10,** **case when e.deptno=20 then '*' else null end deptno_20,** **case when e.deptno=30 then '*' else null end deptno_30,** **(select count(*) from emp d** **where e.deptno=d.deptno and e.empno< d.empno ) as rnk** **from emp e** **) x** **group by rnk** **order by 1 desc, 2 desc, 3 desc** D10 D20 D30 --- --- --- * * * * * * * * * * * * * * ## 12.11. Returning Non-GROUP BY Columns ### Problem You are executing a GROUP BY query, and you wish to return columns in your select list that are not also listed in your GROUP BY clause. This is not normally possible, as such ungrouped columns would not represent a single value per row. Say that you want to find the employees who earn the highest and lowest salaries in each department, as well as the employees who earn the highest and lowest salaries in each job. You want to see each employee's name, the department he works in, his job title, and his salary. You want to return the following result set: DEPTNO ENAME JOB SAL DEPT_STATUS JOB_STATUS ------ ------ --------- ----- --------------- -------------- 10 MILLER CLERK 1300 LOW SAL IN DEPT TOP SAL IN JOB 10 CLARK MANAGER 2450 LOW SAL IN JOB 10 KING PRESIDENT 5000 TOP SAL IN DEPT TOP SAL IN JOB 20 SCOTT ANALYST 3000 TOP SAL IN DEPT TOP SAL IN JOB 20 FORD ANALYST 3000 TOP SAL IN DEPT TOP SAL IN JOB 20 SMITH CLERK 800 LOW SAL IN DEPT LOW SAL IN JOB 20 JONES MANAGER 2975 TOP SAL IN JOB 30 JAMES CLERK 950 LOW SAL IN DEPT 30 MARTIN SALESMAN 1250 LOW SAL IN JOB 30 WARD SALESMAN 1250 LOW SAL IN JOB 30 ALLEN SALESMAN 1600 TOP SAL IN JOB 30 BLAKE MANAGER 2850 TOP SAL IN DEPT Unfortunately, including all these columns in the SELECT clause will ruin the grouping. Consider the following example. Employee "KING" earns the highest salary. You want to verify this with the following query: Select ename,max(sal) from empgroup by ename Instead of seeing "KING" and KING's salary, the above query will return all 14 rows from table EMP. The reason is because of the grouping: the MAX(SAL) is applied to each ENAME. So, it would seem the above query can be stated as "find the employee with the highest salary" but in fact what it is doing is "find the highest salary for each ENAME in table EMP." This recipe explains a technique for including ENAME without the need to GROUP BY that column. ### Solution Use an inline view to find the high and low salaries by DEPTNO and JOB. Then keep only the employees who make those salaries. #### DB2, Oracle, and SQL Server Use the window functions MAX OVER and MIN OVER to find the highest and lowest salaries by DEPTNO and JOB. Then keep the rows where the salaries are those that are highest or lowest by DEPTNO or JOB: 1 select deptno,ename,job,sal, 2 case when sal = max_by_dept 3 then 'TOP SAL IN DEPT' 4 when sal = min_by_dept 5 then 'LOW SAL IN DEPT' 6 end dept_status, 7 case when sal = max_by_job 8 then 'TOP SAL IN JOB' 9 when sal = min_by_job 10 then 'LOW SAL IN JOB' 11 end job_status 12 from ( 13 select deptno,ename,job,sal, 14 max(sal)over(partition by deptno) max_by_dept, 15 max(sal)over(partition by job) max_by_job, 16 min(sal)over(partition by deptno) min_by_dept, 17 min(sal)over(partition by job) min_by_job 18 from emp 19 ) emp_sals 20 where sal in (max_by_dept,max_by_job, 21 min_by_dept,min_by_job) #### PostgreSQL and MySQL Use scalar subqueries to find the highest and lowest salaries by DEPTNO and JOB. Then keep only those employees who match those salaries: 1 select deptno,ename,job,sal, 2 case when sal = max_by_dept 3 then 'TOP SAL IN DEPT' 4 when sal = min_by_dept 5 then 'LOW SAL IN DEPT' 6 end as dept_status, 7 case when sal = max_by_job 8 then 'TOP SAL IN JOB' 9 when sal = min_by_job 10 then 'LOW SAL IN JOB' 11 end as job_status 12 from ( 13 select e.deptno,e.ename,e.job,e.sal, 14 (select max(sal) from emp d 15 where d.deptno = e.deptno) as max_by_dept, 16 (select max(sal) from emp d 17 where d.job = e.job) as max_by_job, 18 (select min(sal) from emp d 19 where d.deptno = e.deptno) as min_by_dept, 20 (select min(sal) from emp d 21 where d.job = e.job) as min_by_job 22 from emp e 23 ) x 24 where sal in (max_by_dept,max_by_job, 25 min_by_dept,min_by_job) ### Discussion #### DB2, Oracle, and SQL Server The first step is to use the window functions MAX OVER and MIN OVER to find the highest and lowest salaries by DEPTNO and JOB: **select deptno,ename,job,sal,** **max(sal)over(partition by deptno) maxDEPT,** **max(sal)over(partition by job) maxJOB,** **min(sal)over(partition by deptno) minDEPT,** **min(sal)over(partition by job) minJOB** **from emp** DEPTNO ENAME JOB SAL MAXDEPT MAXJOB MINDEPT MINJOB ------ ------ --------- ----- ------- ------ ------- ------ 10 MILLER CLERK 1300 5000 1300 1300 800 10 CLARK MANAGER 2450 5000 2975 1300 2450 10 KING PRESIDENT 5000 5000 5000 1300 5000 20 SCOTT ANALYST 3000 3000 3000 800 3000 20 FORD ANALYST 3000 3000 3000 800 3000 20 SMITH CLERK 800 3000 1300 800 800 20 JONES MANAGER 2975 3000 2975 800 2450 20 ADAMS CLERK 1100 3000 1300 800 800 30 JAMES CLERK 950 2850 1300 950 800 30 MARTIN SALESMAN 1250 2850 1600 950 1250 30 TURNER SALESMAN 1500 2850 1600 950 1250 30 WARD SALESMAN 1250 2850 1600 950 1250 30 ALLEN SALESMAN 1600 2850 1600 950 1250 30 BLAKE MANAGER 2850 2850 2975 950 2450 At this point, every salary can be compared with the highest and lowest salaries by DEPTNO and JOB. Notice that the grouping (the inclusion of multiple columns in the SELECT clause) does not affect the values returned by MIN OVER and MAX OVER. This is the beauty of window functions: the aggregate is computed over a defined "group" or partition and returns multiple rows for each group. The last step is to simply wrap the window functions in an inline view and keep only those rows that match the values returned by the window functions. Use a simple CASE expression to display the "status" of each employee in the final result set: **select deptno,ename,job,sal,** **case when sal = max_by_dept** **then 'TOP SAL IN DEPT'** **when sal = min_by_dept** **then 'LOW SAL IN DEPT'** **end dept_status,** **case when sal = max_by_job** **then 'TOP SAL IN JOB'** **when sal = min_by_job** **then 'LOW SAL IN JOB'** **end job_status** **from (** **select deptno,ename,job,sal,** **max(sal)over(partition by deptno) max_by_dept,** **max(sal)over(partition by job) max_by_job,** **min(sal)over(partition by deptno) min_by_dept,** **min(sal)over(partition by job) min_by_job** **from emp** **) x** **where sal in (max_by_dept,max_by_job,** **min_by_dept,min_by_job)** DEPTNO ENAME JOB SAL DEPT_STATUS JOB_STATUS ------ ------ --------- ----- --------------- -------------- 10 MILLER CLERK 1300 LOW SAL IN DEPT TOP SAL IN JOB 10 CLARK MANAGER 2450 LOW SAL IN JOB 10 KING PRESIDENT 5000 TOP SAL IN DEPT TOP SAL IN JOB 20 SCOTT ANALYST 3000 TOP SAL IN DEPT TOP SAL IN JOB 20 FORD ANALYST 3000 TOP SAL IN DEPT TOP SAL IN JOB 20 SMITH CLERK 800 LOW SAL IN DEPT LOW SAL IN JOB 20 JONES MANAGER 2975 TOP SAL IN JOB 30 JAMES CLERK 950 LOW SAL IN DEPT 30 MARTIN SALESMAN 1250 LOW SAL IN JOB 30 WARD SALESMAN 1250 LOW SAL IN JOB 30 ALLEN SALESMAN 1600 TOP SAL IN JOB 30 BLAKE MANAGER 2850 TOP SAL IN DEPT #### PostgreSQL and MySQL The first step is to use scalar subqueries to find the highest and lowest salaries by DEPTNO and JOB: **select e.deptno,e.ename,e.job,e.sal,** **(select max(sal) from emp d** **where d.deptno = e.deptno) as maxDEPT,** **(select max(sal) from emp d** **where d.job = e.job) as maxJOB,** **(select min(sal) from emp d** **where d.deptno = e.deptno) as minDEPT,** **(select min(sal) from emp d** **where d.job = e.job) as minJOB** **from emp e** DEPTNO ENAME JOB SAL MAXDEPT MAXJOB MINDEPT MINJOB ------ ------ --------- ----- ------- ------ ------- ------ 20 SMITH CLERK 800 3000 1300 800 800 30 ALLEN SALESMAN 1600 2850 1600 950 1250 30 WARD SALESMAN 1250 2850 1600 950 1250 20 JONES MANAGER 2975 3000 2975 800 2450 30 MARTIN SALESMAN 1250 2850 1600 950 1250 30 BLAKE MANAGER 2850 2850 2975 950 2450 10 CLARK MANAGER 2450 5000 2975 1300 2450 20 SCOTT ANALYST 3000 3000 3000 800 3000 10 KING PRESIDENT 5000 5000 5000 1300 5000 30 TURNER SALESMAN 1500 2850 1600 950 1250 20 ADAMS CLERK 1100 3000 1300 800 800 30 JAMES CLERK 950 2850 1300 950 800 20 FORD ANALYST 3000 3000 3000 800 3000 10 MILLER CLERK 1300 5000 1300 1300 800 The highest and lowest salaries by DEPTNO and JOB can now be compared with all other salaries in table EMP. The final step is to wrap the scalar subqueries in an inline view and simply keep the employees whose salaries match one of the scalar subqueries. Use a CASE expression to display each employee's status in the final result set: **select deptno,ename,job,sal,** **case when sal = max_by_dept** **then 'TOP SAL IN DEPT'** **when sal = min_by_dept** **then 'LOW SAL IN DEPT'** **end as dept_status,** **case when sal = max_by_job** **then 'TOP SAL IN JOB'** **when sal = min_by_job** **then 'LOW SAL IN JOB'** **end as job_status** **from (** **select e.deptno,e.ename,e.job,e.sal,** **(select max(sal) from emp d** **where d.deptno = e.deptno) as max_** **by_dept,** **(select max(sal) from emp d** **where d.job = e.job) as max_** **by_job,** **(select min(sal) from emp d** **where d.deptno = e.deptno) as min_by_dept,** **(select min(sal) from emp d** **where d.job = e.job) as min_by_job** **from emp e** **) x** **where sal in (max_by_dept,max_by_job,** **min_by_dept,min_by_job)** DEPTNO ENAME JOB SAL DEPT_STATUS JOB_STATUS ------ ------ --------- ----- --------------- -------------- 10 CLARK MANAGER 2450 LOW SAL IN JOB 10 KING PRESIDENT 5000 TOP SAL IN DEPT TOP SAL IN JOB 10 MILLER CLERK 1300 LOW SAL IN DEPT TOP SAL IN JOB 20 SMITH CLERK 800 LOW SAL IN DEPT LOW SAL IN JOB 20 FORD ANALYST 3000 TOP SAL IN DEPT TOP SAL IN JOB 20 SCOTT ANALYST 3000 TOP SAL IN DEPT TOP SAL IN JOB 20 JONES MANAGER 2975 TOP SAL IN JOB 30 ALLEN SALESMAN 1600 TOP SAL IN JOB 30 BLAKE MANAGER 2850 TOP SAL IN DEPT 30 MARTIN SALESMAN 1250 LOW SAL IN JOB 30 JAMES CLERK 950 LOW SAL IN DEPT 30 WARD SALESMAN 1250 LOW SAL IN JOB ## 12.12. Calculating Simple Subtotals ### Problem For the purposes of this recipe, a "simple subtotal" is defined as a result set that contains values from the aggregation of one column along with a grand total value for the table. An example would be a result set that sums the salaries in table EMP by JOB, and that also includes the sum of all salaries in table EMP. The summed salaries by JOB are the subtotals, and the sum of all salaries in table EMP is the grand total. Such a result set should look as follows: JOB SAL --------- ---------- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 TOTAL 29025 ### Solution The ROLLUP extension to the GROUP BY clause solves this problem perfectly. If ROLLUP is not available for your RDBMS, you can solve the problem, albeit with more difficulty, using a scalar subquery or a UNION query. #### DB2 and Oracle Use the aggregate function SUM to sum the salaries, and use the ROLLUP extension of GROUP BY to organize the results into subtotals (by JOB) and a grand total (for the whole table): 1 select case grouping(job) 2 when 0 then job 3 else 'TOTAL' 4 end job, 5 sum(sal) sal 6 from emp 7 group by rollup(job) #### SQL Server and MySQL Use the aggregate function SUM to sum the salaries, and use WITH ROLLUP to organize the results into subtotals (by JOB) and a grand total (for the whole table). Then use COALESCE to supply the label 'TOTAL' for the grand total row (which will otherwise have a NULL in the job column): 1 select coalesce(job,'TOTAL') job, 2 sum(sal) sal 3 from emp 4 group by job with rollup With SQL Server, you also have the option to use the GROUPING function shown in the Oracle/DB2 recipe rather than COALESCE to determine the level of aggregation. #### PostgreSQL Use the aggregate function SUM to sum the salaries by DEPTNO. Then UNION ALL with a query generating the sum of all the salaries in the table: 1 select job, sum(sal) as sal 2 from emp 3 group by job 4 union all 5 select 'TOTAL', sum(sal) 6 from emp ### Discussion #### DB2 and Oracle The first step is to use the aggregate function SUM, grouping by JOB in order to sum the salaries by JOB: **select job, sum(sal) sal** **from emp** **group by job** JOB SAL --------- ----- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 The next step is to use the ROLLUP extension to GROUP BY to produce a grand total for all salaries along with the subtotals for each JOB: **select job, sum(sal) sal** **from emp** **group by rollup(job)** JOB SAL --------- ------- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 29025 The last step is to use the GROUPING function in the JOB column to display a label for the grand total. If the value of JOB is NULL, the GROUPING function will return 1, which signifies that the value for SAL is the grand total created by ROLLUP. If the value of JOB is not NULL, the GROUPING function will return 0, which signifies the value for SAL is the result of the GROUP BY, not the ROLLUP. Wrap the call to GROUPING(JOB) in a CASE expression that returns either the job name or the label 'TOTAL', as appropriate: **select case grouping(job)** **when 0 then job** **else 'TOTAL'** **end job,** **sum(sal) sal** **from emp** **group by rollup(job)** JOB SAL --------- ---------- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 TOTAL 29025 #### SQL Server and MySQL The first step is to use the aggregate function SUM, grouping the results by JOB to generate salary sums by JOB: **select job, sum(sal) sal** **from emp** **group by job** JOB SAL --------- ----- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 The next step is to use GROUP BY's ROLLUP extension to produce a grand total for all salaries along with the subtotals for each JOB: **select job, sum(sal) sal** **from emp** **group by job with rollup** JOB SAL --------- ------- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 29025 The last step is to use the COEALESCE function against the JOB column. If the value of JOB is NULL, the value for SAL is the grand total created by ROLLUP. If the value of JOB is not NULL, the value for SAL is the result of the "regular" GROUP BY, not the ROLLUP: **select coalesce(job,'TOTAL') job,** **sum(sal) sal** **from emp** **group by job with rollup** JOB SAL --------- ---------- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 TOTAL 29025 #### PostgreSQL The first step is to group the results by job, using the aggregate function SUM to return salary totals by JOB: **select job, sum(sal) sal** **from emp** **group by job** JOB SAL --------- ----- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 The last step is to use a UNION ALL to supply the grand total to the above query: **select job, sum(sal) as sal** **from emp** **group by job** **union all** **select 'TOTAL', sum(sal)** **from emp** JOB SAL --------- ------- ANALYST 6000 CLERK 4150 MANAGER 8275 PRESIDENT 5000 SALESMAN 5600 TOTAL 29025 ## 12.13. Calculating Subtotals for All Possible Expression Combinations ### Problem You want to find the sum of all salaries by DEPTNO, and by JOB, for every JOB/ DEPTNO combination. You also want a grand total for all salaries in table EMP. You want to return the following result set: DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ------- 10 CLERK TOTAL BY DEPT AND JOB 1300 10 MANAGER TOTAL BY DEPT AND JOB 2450 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 20 CLERK TOTAL BY DEPT AND JOB 1900 30 CLERK TOTAL BY DEPT AND JOB 950 30 SALESMAN TOTAL BY DEPT AND JOB 5600 30 MANAGER TOTAL BY DEPT AND JOB 2850 20 MANAGER TOTAL BY DEPT AND JOB 2975 20 ANALYST TOTAL BY DEPT AND JOB 6000 CLERK TOTAL BY JOB 4150 ANALYST TOTAL BY JOB 6000 MANAGER TOTAL BY JOB 8275 PRESIDENT TOTAL BY JOB 5000 SALESMAN TOTAL BY JOB 5600 10 TOTAL BY DEPT 8750 30 TOTAL BY DEPT 9400 20 TOTAL BY DEPT 10875 GRAND TOTAL FOR TABLE 29025 ### Solution Extensions added to GROUP BY in recent years make this a fairly easy problem to solve. If your platform does not supply such extensions for computing various levels of subtotals, then you must compute them manually (via self joins or scalar subqueries). #### DB2 For DB2, you will need to CAST the results from GROUPING to the CHAR(1) data type: 1 select deptno, 2 job, 3 case cast(grouping(deptno) as char(1))|| 4 cast(grouping(job) as char(1)) 5 when '00' then 'TOTAL BY DEPT AND JOB' 6 when '10' then 'TOTAL BY JOB' 7 when '01' then 'TOTAL BY DEPT' 8 when '11' then 'TOTAL FOR TABLE' 9 end category, 10 sum(sal) 11 from emp 12 group by cube(deptno,job) 13 order by grouping(job),grouping(deptno) #### Oracle Use the CUBE extension to the GROUP BY clause with the concatenation operator ||: 1 select deptno, 2 job, 3 case grouping(deptno)||grouping(job) 4 when '00' then 'TOTAL BY DEPT AND JOB' 5 when '10' then 'TOTAL BY JOB' 6 when '01' then 'TOTAL BY DEPT' 7 when '11' then 'GRAND TOTALFOR TABLE' 8 end category, 9 sum(sal) sal 10 from emp 11 group by cube(deptno,job) 12 order by grouping(job),grouping(deptno) #### SQL Server Use the CUBE extension to the GROUP BY clause. For SQL Server, you will need to CAST the results from GROUPING to CHAR(1), and you will need to use the + operator for concatenation (as opposed to Oracle's || operator): 1 select deptno, 2 job, 3 case cast(grouping(deptno)as char(1))+ 4 cast(grouping(job)as char(1)) 5 when '00' then 'TOTAL BY DEPT AND JOB' 6 when '10' then 'TOTAL BY JOB' 7 when '01' then 'TOTAL BY DEPT' 8 when '11' then 'GRAND TOTAL FOR TABLE' 9 end category, 10 sum(sal) sal 11 from emp 12 group by deptno,job with cube 13 order by grouping(job),grouping(deptno) #### PostgreSQL and MySQL Use multiple UNION ALLs, creating different sums for each: 1 select deptno, job, 2 'TOTAL BY DEPT AND JOB' as category, 3 sum(sal) as sal 4 from emp 5 group by deptno, job 6 union all 7 select null, job, 'TOTAL BY JOB', sum(sal) 8 from emp 9 group by job 10 union all 11 select deptno, null, 'TOTAL BY DEPT', sum(sal) 12 from emp 13 group by deptno 14 union all 15 select null,null,'GRAND TOTAL FOR TABLE', sum(sal) 16 from emp ### Discussion #### Oracle, DB2, and SQL Server The solutions for all three are essentially the same. The first step is to use the aggregate function SUM and group by both DEPTNO and JOB to find the total salaries for each JOB and DEPTNO combination: **select deptno, job, sum(sal) sal** **from emp** **group by deptno, job** DEPTNO JOB SAL ------ --------- ------- 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 The next step is to create subtotals by JOB and DEPTNO along with the grand total for the whole table. Use the CUBE extension to the GROUP BY clause to perform aggregations on SAL by DEPTNO, JOB, and for the whole table: **select deptno,** **job,** **sum(sal) sal** **from emp** **group by cube(deptno,job)** DEPTNO JOB SAL ------ --------- ------- 29025 CLERK 4150 ANALYST 6000 MANAGER 8275 SALESMAN 5600 PRESIDENT 5000 10 8750 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 10875 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 9400 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 Next, use the GROUPING function in conjunction with CASE to format the results into more meaningful output. The value from GROUPING(JOB) will be 1 or 0 depending on whether or not the values for SAL are due to the GROUP BY or the CUBE. If the results are due to the CUBE, the value will be 1, otherwise it will be 0. The same goes for GROUPING(DEPTNO). Looking at the first step of the solution, you should see that grouping is done by DEPTNO and JOB. Thus, the expected values from the calls to GROUPING when a row represents a combination of both DEPTNO and JOB is 0. The query below confirms this: **select deptno,** **job,** **grouping(deptno) is_deptno_subtotal,** **grouping(job) is_job_subtotal,** **sum(sal) sal** **from emp** **group by cube(deptno,job)** **order by 3,4** DEPTNO JOB IS_DEPTNO_SUBTOTAL IS_JOB_SUBTOTAL SAL ------ --------- ------------------ --------------- ------- 10 CLERK 0 0 1300 10 MANAGER 0 0 2450 10 PRESIDENT 0 0 5000 20 CLERK 0 0 1900 30 CLERK 0 0 950 30 SALESMAN 0 0 5600 30 MANAGER 0 0 2850 20 MANAGER 0 0 2975 20 ANALYST 0 0 6000 10 0 1 8750 20 0 1 10875 30 0 1 9400 CLERK 1 0 4150 ANALYST 1 0 6000 MANAGER 1 0 8275 PRESIDENT 1 0 5000 SALESMAN 1 0 5600 1 1 29025 The final step is to use a CASE expression to determine which category each row belongs to based on the values returned by GROUPING(JOB) and GROUPING(DEPTNO) concatenated: **select deptno,** **job,** **case grouping(deptno)||grouping(job)** **when '00' then 'TOTAL BY DEPT AND JOB'** **when '10' then 'TOTAL BY JOB'** **when '01' then 'TOTAL BY DEPT'** **when '11' then 'GRAND TOTAL FOR TABLE'** **end category,** **sum(sal) sal** **from emp** **group by cube(deptno,job)** **order by grouping(job),grouping(deptno)** DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ------- 10 CLERK TOTAL BY DEPT AND JOB 1300 10 MANAGER TOTAL BY DEPT AND JOB 2450 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 20 CLERK TOTAL BY DEPT AND JOB 1900 30 CLERK TOTAL BY DEPT AND JOB 950 30 SALESMAN TOTAL BY DEPT AND JOB 5600 30 MANAGER TOTAL BY DEPT AND JOB 2850 20 MANAGER TOTAL BY DEPT AND JOB 2975 20 ANALYST TOTAL BY DEPT AND JOB 6000 CLERK TOTAL BY JOB 4150 ANALYST TOTAL BY JOB 6000 MANAGER TOTAL BY JOB 8275 PRESIDENT TOTAL BY JOB 5000 SALESMAN TOTAL BY JOB 5600 10 TOTAL BY DEPT 8750 30 TOTAL BY DEPT 9400 20 TOTAL BY DEPT 10875 GRAND TOTAL FOR TABLE 29025 This Oracle solution implicitly converts the results from the GROUPING functions to a character type in preparation for concatenating the two values. DB2 and SQL Server users will need to explicitly CAST the results of the GROUPING functions to CHAR(1) as shown in the solution. In addition, SQL Server users must use the + operator, and not the || operator, to concatenate the results from the two GROUPING calls into one string. For Oracle and DB2 users, there is an additional extension to GROUP BY called GROUPING SETS; this extension is extremely useful. For example, you can use GROUPING SETS to mimic the output created by CUBE as is done below (DB2 and SQL Server users will need to add explicit CASTS to the values returned by the GROUPING function just as in the CUBE solution): **select deptno,** **job,** **case grouping(deptno)||grouping(job)** **when '00' then 'TOTAL BY DEPT AND JOB'** **when '10' then 'TOTAL BY JOB'** **when '01' then 'TOTAL BY DEPT'** **when '11' then 'GRAND TOTAL FOR TABLE'** **end category,** **sum(sal) sal** **from emp** **group by grouping sets ((deptno),(job),(deptno,job),())** DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ------- 10 CLERK TOTAL BY DEPT AND JOB 1300 20 CLERK TOTAL BY DEPT AND JOB 1900 30 CLERK TOTAL BY DEPT AND JOB 950 20 ANALYST TOTAL BY DEPT AND JOB 6000 10 MANAGER TOTAL BY DEPT AND JOB 2450 20 MANAGER TOTAL BY DEPT AND JOB 2975 30 MANAGER TOTAL BY DEPT AND JOB 2850 30 SALESMAN TOTAL BY DEPT AND JOB 5600 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 CLERK TOTAL BY JOB 4150 ANALYST TOTAL BY JOB 6000 MANAGER TOTAL BY JOB 8275 SALESMAN TOTAL BY JOB 5600 PRESIDENT TOTAL BY JOB 5000 10 TOTAL BY DEPT 8750 20 TOTAL BY DEPT 10875 30 TOTAL BY DEPT 9400 GRAND TOTAL FOR TABLE 29025 What's great about GROUPING SETS is that it allows you to define the groups. The GROUPING SETS clause in the preceding query causes groups to be created by DEPTNO, by JOB, by the combination of DEPTNO and JOB, and finally the empty parenthesis requests a grand total. GROUPING SETS gives you enormous flexibility for creating reports with different levels of aggregation; for example, if you wanted to modify the preceding example to exclude the GRAND TOTAL, simply modify the GROUPING SETS clause by excluding the empty parentheses: /* no grand total */ **select deptno,** **job,** **case grouping(deptno)||grouping(job)** **when '00' then 'TOTAL BY DEPT AND JOB'** **when '10' then 'TOTAL BY JOB'** **when '01' then 'TOTAL BY DEPT'** **when '11' then 'GRAND TOTAL FOR TABLE'** **end category,** **sum(sal) sal** **from emp** **group by grouping sets ((deptno),(job),(deptno,job))** DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ---------- 10 CLERK TOTAL BY DEPT AND JOB 1300 20 CLERK TOTAL BY DEPT AND JOB 1900 30 CLERK TOTAL BY DEPT AND JOB 950 20 ANALYST TOTAL BY DEPT AND JOB 6000 10 MANAGER TOTAL BY DEPT AND JOB 2450 20 MANAGER TOTAL BY DEPT AND JOB 2975 30 MANAGER TOTAL BY DEPT AND JOB 2850 30 SALESMAN TOTAL BY DEPT AND JOB 5600 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 CLERK TOTAL BY JOB 4150 ANALYST TOTAL BY JOB 6000 ANAGER TOTAL BY JOB 8275 SALESMAN TOTAL BY JOB 5600 PRESIDENT TOTAL BY JOB 5000 10 TOTAL BY DEPT 8750 20 TOTAL BY DEPT 10875 30 TOTAL BY DEPT 9400 You can also eliminate a subtotal, such as the one on DEPTNO, simply by omitting (DEPTNO) from the GROUPING SETS clause: /* nosubtotals by DEPTNO */ **select deptno,** **job,** **case grouping(deptno)||grouping(job)** **when '00' then 'TOTAL BY DEPT AND JOB'** **when '10' then 'TOTAL BY JOB'** **when '01' then 'TOTAL BY DEPT'** **when '11' then 'GRAND TOTAL FOR TABLE'** **end category,** **sum(sal) sal** **from emp** **group by grouping sets ((job),(deptno,job),())** **order by 3** DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ---------- GRAND TOTAL FOR TABLE 29025 10 CLERK TOTAL BY DEPT AND JOB 1300 20 CLERK TOTAL BY DEPT AND JOB 1900 30 CLERK TOTAL BY DEPT AND JOB 950 20 ANALYST TOTAL BY DEPT AND JOB 6000 20 MANAGER TOTAL BY DEPT AND JOB 2975 30 MANAGER TOTAL BY DEPT AND JOB 2850 30 SALESMAN TOTAL BY DEPT AND JOB 5600 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 10 MANAGER TOTAL BY DEPT AND JOB 2450 CLERK TOTAL BY JOB 4150 SALESMAN TOTAL BY JOB 5600 PRESIDENT TOTAL BY JOB 5000 MANAGER TOTAL BY JOB 8275 ANALYST TOTAL BY JOB 6000 As you can see, GROUPING SETS makes it very easy indeed to play around with totals and subtotals in order to look at your data from different angles. #### PostgreSQL and MySQL The first step is to use the aggregate function SUM and group by both DEPTNO and JOB: **select deptno, job,** **'TOTAL BY DEPT AND JOB' as category,** **sum(sal) as sal** **from emp** **group by deptno, job** DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ------- 10 CLERK TOTAL BY DEPT AND JOB 1300 10 MANAGER TOTAL BY DEPT AND JOB 2450 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 20 CLERK TOTAL BY DEPT AND JOB 1900 20 ANALYST TOTAL BY DEPT AND JOB 6000 20 MANAGER TOTAL BY DEPT AND JOB 2975 30 CLERK TOTAL BY DEPT AND JOB 950 30 MANAGER TOTAL BY DEPT AND JOB 2850 30 SALESMAN TOTAL BY DEPT AND JOB 5600 The next step is to UNION ALL the sum of all the salaries by JOB: **select deptno, job,** **'TOTAL BY DEPT AND JOB' as category,** **sum(sal) as sal** **from emp** **group by deptno, job** **union all** **select null, job, 'TOTAL BY JOB', sum(sal)** **from emp** **group by job** DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ------- 10 CLERK TOTAL BY DEPT AND JOB 1300 10 MANAGER TOTAL BY DEPT AND JOB 2450 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 20 CLERK TOTAL BY DEPT AND JOB 1900 20 ANALYST TOTAL BY DEPT AND JOB 6000 20 MANAGER TOTAL BY DEPT AND JOB 2975 30 CLERK TOTAL BY DEPT AND JOB 950 30 MANAGER TOTAL BY DEPT AND JOB 2850 30 SALESMAN TOTAL BY DEPT AND JOB 5600 ANALYST TOTAL BY JOB 6000 CLERK TOTAL BY JOB 4150 MANAGER TOTAL BY JOB 8275 PRESIDENT TOTAL BY JOB 5000 SALESMAN TOTAL BY JOB 5600 The next step is to UNION ALL the sum of all the salaries by DEPTNO: **select deptno, job,** **'TOTAL BY DEPT AND JOB' as category,** **sum(sal) as sal** **from emp** **group by deptno, job** **union all** **select null, job, 'TOTAL BY JOB', sum(sal)** **from emp** **group by job** **union all** **select deptno, null, 'TOTAL BY DEPT', sum(sal)** **from emp** **group by deptno** DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ------- 10 CLERK TOTAL BY DEPT AND JOB 1300 10 MANAGER TOTAL BY DEPT AND JOB 2450 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 20 CLERK TOTAL BY DEPT AND JOB 1900 20 ANALYST TOTAL BY DEPT AND JOB 6000 20 MANAGER TOTAL BY DEPT AND JOB 2975 30 CLERK TOTAL BY DEPT AND JOB 950 30 MANAGER TOTAL BY DEPT AND JOB 2850 30 SALESMAN TOTAL BY DEPT AND JOB 5600 ANALYST TOTAL BY JOB 6000 CLERK TOTAL BY JOB 4150 MANAGER TOTAL BY JOB 8275 PRESIDENT TOTAL BY JOB 5000 SALESMAN TOTAL BY JOB 5600 10 TOTAL BY DEPT 8750 20 TOTAL BY DEPT 10875 30 TOTAL BY DEPT 9400 The final step is to UNION ALL the sum of all salaries in table EMP: **select deptno, job,** **'TOTAL BY DEPT AND JOB' as category,** **sum(sal) as sal** **from emp** **group by deptno, job** **union all** **select null, job, 'TOTAL BY JOB', sum(sal)** **from emp** **group by job** **union all** **select deptno, null, 'TOTAL BY DEPT', sum(sal)** **from emp** **group by deptno** **union all** **select null,null, 'GRAND TOTAL** **FOR TABLE', sum(sal)** **from emp** DEPTNO JOB CATEGORY SAL ------ --------- --------------------- ------- 10 CLERK TOTAL BY DEPT AND JOB 1300 10 MANAGER TOTAL BY DEPT AND JOB 2450 10 PRESIDENT TOTAL BY DEPT AND JOB 5000 20 CLERK TOTAL BY DEPT AND JOB 1900 20 ANALYST TOTAL BY DEPT AND JOB 6000 20 MANAGER TOTAL BY DEPT AND JOB 2975 30 CLERK TOTAL BY DEPT AND JOB 950 30 MANAGER TOTAL BY DEPT AND JOB 2850 30 SALESMAN TOTAL BY DEPT AND JOB 5600 ANALYST TOTAL BY JOB 6000 CLERK TOTAL BY JOB 4150 MANAGER TOTAL BY JOB 8275 PRESIDENT TOTAL BY JOB 5000 SALESMAN TOTAL BY JOB 5600 10 TOTAL BY DEPT 8750 20 TOTAL BY DEPT 10875 30 TOTAL BY DEPT 9400 GRAND TOTAL FOR TABLE 29025 ## 12.14. Identifying Rows That Are Not Subtotals ### Problem You've used the CUBE extension of the GROUP BY clause to create a report, and you need a way to differentiate between rows that would be generated by a normal GROUP BY clause and those rows that have been generated as a result of using CUBE or ROLLUP. Following is the result set from a query using the CUBE extension to GROUP BY to create a breakdown of the salaries in table EMP: DEPTNO JOB SAL ------ --------- ------- 29025 CLERK 4150 ANALYST 6000 MANAGER 8275 SALESMAN 5600 PRESIDENT 5000 10 8750 10 CLERK 1300 10 MANAGER 2450 10 PRESIDENT 5000 20 10875 20 CLERK 1900 20 ANALYST 6000 20 MANAGER 2975 30 9400 30 CLERK 950 30 MANAGER 2850 30 SALESMAN 5600 This report includes the sum of all salaries by DEPTNO and JOB (for each JOB per DEPTNO), the sum of all salaries by DEPTNO, the sum of all salaries by JOB, and finally a grand total (the sum of all salaries in table EMP). You want to clearly identify the different levels of aggregation. You want to be able to identify which category an aggregated value belongs to (i.e., does a given value in the SAL column represent a total by DEPTNO? By JOB? The grand total?). You would like to return the following result set: DEPTNO JOB SAL DEPTNO_SUBTOTALS JOB_SUBTOTALS ------ --------- ------- ---------------- ------------- 29025 1 1 CLERK 4150 1 0 ANALYST 6000 1 0 MANAGER 8275 1 0 SALESMAN 5600 1 0 PRESIDENT 5000 1 0 10 8750 0 1 10 CLERK 1300 0 0 10 MANAGER 2450 0 0 10 PRESIDENT 5000 0 0 20 10875 0 1 20 CLERK 1900 0 0 20 ANALYST 6000 0 0 20 MANAGER 2975 0 0 30 9400 0 1 30 CLERK 950 0 0 30 MANAGER 2850 0 0 30 SALESMAN 5600 0 0 ### Solution Use the GROUPING function to identify which values exist due to CUBE's or ROLLUP's creation of subtotals, or _superaggregate_ values. The following is an example for DB2 and Oracle: 1 select deptno, job, sum(sal) sal, 2 grouping(deptno) deptno_subtotals, 3 grouping(job) job_subtotals 4 from emp 5 group by cube(deptno,job) The only difference between the SQL Server solution and that for DB2 and Oracle lies in how the CUBE/ROLLUP clauses are written: 1 select deptno, job, sum(sal) sal, 2 grouping(deptno) deptno_subtotals, 3 grouping(job) job_subtotals 4 from emp 5 group by deptno,job with cube This recipe is meant to highlight the use of CUBE and GROUPING when working with subtotals. As of the time of this writing, PostgreSQL and MySQL support neither CUBE nor GROUPING. ### Discussion If DEPTNO_SUBTOTALS is 0 and JOB_SUBTOTALS is 1 (in which case JOB is NULL), the value of SAL represents a subtotal of salaries by DEPTNO created by CUBE. If JOB_SUBTOTALS is 0 and DEPTNO_SUBTOTALS is 1 (in which case DEPTNO is NULL) the value of SAL represents a subtotal of salaries by JOB created by CUBE. Rows with 0 for both DEPTNO_SUBTOTALS and JOB_SUBTOTALS represent rows created by regular aggregation (the sum of SAL for each DEPTNO/JOB combination). ## 12.15. Using Case Expressions to Flag Rows ### Problem You want to map the values in a column, say, the EMP table's JOB column, into a series of "Boolean" flags. For example, you wish to return the following result set: ENAME IS_CLERK IS_SALES IS_MGR IS_ANALYST IS_PREZ ------ -------- -------- ------ ---------- ------- KING 0 0 0 0 1 SCOTT 0 0 0 1 0 FORD 0 0 0 1 0 JONES 0 0 1 0 0 BLAKE 0 0 1 0 0 CLARK 0 0 1 0 0 ALLEN 0 1 0 0 0 WARD 0 1 0 0 0 MARTIN 0 1 0 0 0 TURNER 0 1 0 0 0 SMITH 1 0 0 0 0 MILLER 1 0 0 0 0 ADAMS 1 0 0 0 0 JAMES 1 0 0 0 0 Such a result set can be useful for debugging and to provide yourself a view of the data different from what you'd see in a more typical result set. ### Solution Use a CASE expression to evaluate each employee's JOB, and return a 1 or 0 to signify her JOB. You'll need to write one CASE expression, and thus create one column for each possible job: 1 select ename, 2 case when job = 'CLERK' 3 then 1 else 0 4 end as is_clerk, 5 case when job = 'SALESMAN' 6 then 1 else 0 7 end as is_sales, 8 case when job = 'MANAGER' 9 then 1 else 0 10 end as is_mgr, 11 case when job = 'ANALYST' 12 then 1 else 0 13 end as is_analyst, 14 case when job = 'PRESIDENT' 15 then 1 else 0 16 end as is_prez 17 from emp 18 order by 2,3,4,5,6 ### Discussion The solution code is pretty much self-explanatory. If you are having trouble understanding it, simply add JOB to the SELECT clause: **select ename,** **job,** **case when job = 'CLERK'** **then 1 else 0** **end as is_clerk,** **case when job = 'SALESMAN'** **then 1 else 0** **end as is_sales,** **case when job = 'MANAGER'** **then 1 else 0** **end as is_mgr,** **case when job = 'ANALYST'** **then 1 else 0** **end as is_analyst,** **case when job = 'PRESIDENT'** **then 1 else 0** **end as is_prez** **from emp** **order by 2** ENAME JOB IS_CLERK IS_SALES IS_MGR IS_ANALYST IS_PREZ ------ --------- -------- -------- ------ ---------- ------- SCOTT ANALYST 0 0 0 1 0 FORD ANALYST 0 0 0 1 0 SMITH CLERK 1 0 0 0 0 ADAMS CLERK 1 0 0 0 0 MILLER CLERK 1 0 0 0 0 JAMES CLERK 1 0 0 0 0 JONES MANAGER 0 0 1 0 0 CLARK MANAGER 0 0 1 0 0 BLAKE MANAGER 0 0 1 0 0 KING PRESIDENT 0 0 0 0 1 ALLEN SALESMAN 0 1 0 0 0 MARTIN SALESMAN 0 1 0 0 0 TURNER SALESMAN 0 1 0 0 0 WARD SALESMAN 0 1 0 0 0 ## 12.16. Creating a Sparse Matrix ### Problem You want to create a sparse matrix, such as the following one transposing the DEPTNO and JOB columns of table EMP: D10 D20 D30 CLERKS MGRS PREZ ANALS SALES ---------- ---------- ---------- ------ ----- ---- ----- ------ SMITH SMITH ALLEN ALLEN WARD WARD JONES JONES MARTIN MARTIN BLAKE BLAKE CLARK CLARK SCOTT SCOTT KING KING TURNER TURNER ADAMS ADAMS JAMES JAMES FORD FORD MILLER MILLER ### Solution Use CASE expressions to create a sparse row-to-column transformation: 1 select case deptno when 10 then ename end as d10, 2 case deptno when 20 then ename end as d20, 3 case deptno when 30 then ename end as d30, 4 case job when 'CLERK' then ename end as clerks, 5 case job when 'MANAGER' then ename end as mgrs, 6 case job when 'PRESIDENT' then ename end as prez, 7 case job when 'ANALYST' then ename end as anals, 8 case job when 'SALESMAN' then ename end as sales 9 from emp ### Discussion To transform the DEPTNO and JOB rows to columns, simply use a CASE expression to evaluate the possible values returned by those rows. That's all there is to it. As an aside, if you want to "densify" the report and get rid of some of those NULL rows, you would need to find something to group by. For example, use the window function ROW_NUMBER OVER to assign a ranking for each employee per DEPTNO, and then use the aggregate function MAX to rub out some of the NULLs: **select max(case deptno when 10 then ename end) d10,** **max(case deptno when 20 then ename end) d20,** **max(case deptno when 30 then ename end) d30,** **max(case job when 'CLERK' then ename end) clerks,** **max(case job when 'MANAGER' then ename end) mgrs,** **max(case job when 'PRESIDENT' then ename end) prez,** **max(case job when 'ANALYST' then ename end) anals,** **max(case job when 'SALESMAN' then ename end) sales** **from (** **select deptno, job, ename,** **row_number()over(partition** **by deptno order by empno) rn** **from emp** **) x** **group by rn** D10 D20 D30 CLERKS MGRS PREZ ANALS SALES ---------- ---------- ---------- ------ ----- ---- ----- ------ CLARK SMITH ALLEN SMITH CLARK ALLEN KING JONES WARD JONES KING WARD MILLER SCOTT MARTIN MILLER SCOTT MARTIN ADAMS BLAKE ADAMS BLAKE FORD TURNER FORD TURNER JAMES JAMES ## 12.17. Grouping Rows by Units of Time ### Problem You want to summarize data by some interval of time. For example, you have a transaction log and want to summarize transactions by 5-second intervals. The rows in table TRX_LOG are shown below: **select trx_id,** **trx_date,** **trx_cnt** **from trx_log** TRX_ID TRX_DATE TRX_CNT ------ -------------------- ---------- 1 28-JUL-2005 19:03:07 44 2 28-JUL-2005 19:03:08 18 3 28-JUL-2005 19:03:09 23 4 28-JUL-2005 19:03:10 29 5 28-JUL-2005 19:03:11 27 6 28-JUL-2005 19:03:12 45 7 28-JUL-2005 19:03:13 45 8 28-JUL-2005 19:03:14 32 9 28-JUL-2005 19:03:15 41 10 28-JUL-2005 19:03:16 15 11 28-JUL-2005 19:03:17 24 12 28-JUL-2005 19:03:18 47 13 28-JUL-2005 19:03:19 37 14 28-JUL-2005 19:03:20 48 15 28-JUL-2005 19:03:21 46 16 28-JUL-2005 19:03:22 44 17 28-JUL-2005 19:03:23 36 18 28-JUL-2005 19:03:24 41 19 28-JUL-2005 19:03:25 33 20 28-JUL-2005 19:03:26 19 You want to return the following result set: GRP TRX_START TRX_END TOTAL --- -------------------- -------------------- ---------- 1 28-JUL-2005 19:03:07 28-JUL-2005 19:03:11 141 2 28-JUL-2005 19:03:12 28-JUL-2005 19:03:16 178 3 28-JUL-2005 19:03:17 28-JUL-2005 19:03:21 202 4 28-JUL-2005 19:03:22 28-JUL-2005 19:03:26 173 ### Solution Group the entries into five row buckets. There are several ways to accomplish that logical grouping; this recipe does so by dividing the TRX_ID values by 5, using a technique shown earlier in "Creating Buckets of Data, of a Fixed Size." Once you've created the "groups," use the aggregate functions MIN, MAX, and SUM to find the start time, end time, and total number of transactions for each "group" (SQL Server users should use CEILING instead of CEIL): 1 select ceil(trx_id/5.0) as grp, 2 min(trx_date) as trx_start, 3 max(trx_date) as trx_end, 4 sum(trx_cnt) as total 5 from trx_log 6 group by ceil(trx_id/5.0) ### Discussion The first step, and the key to the whole solution, is to logically group the rows together. By dividing by 5 and taking the smallest whole number greater than the quotient, you can create logical groups. For example: **select trx_id,** **trx_date,** **trx_cnt,** **trx_id/5.0 as val,** **ceil(trx_id/5.0) as grp** **from trx_log** TRX_ID TRX_DATE TRX_CNT VAL GRP ------ -------------------- ------- ------ --- 1 28-JUL-2005 19:03:07 44 .20 1 2 28-JUL-2005 19:03:08 18 .40 1 3 28-JUL-2005 19:03:09 23 .60 1 4 28-JUL-2005 19:03:10 29 .80 1 5 28-JUL-2005 19:03:11 27 1.00 1 6 28-JUL-2005 19:03:12 45 1.20 2 7 28-JUL-2005 19:03:13 45 1.40 2 8 28-JUL-2005 19:03:14 32 1.60 2 9 28-JUL-2005 19:03:15 41 1.80 2 10 28-JUL-2005 19:03:16 15 2.00 2 11 28-JUL-2005 19:03:17 24 2.20 3 12 28-JUL-2005 19:03:18 47 2.40 3 13 28-JUL-2005 19:03:19 37 2.60 3 14 28-JUL-2005 19:03:20 48 2.80 3 15 28-JUL-2005 19:03:21 46 3.00 3 16 28-JUL-2005 19:03:22 44 3.20 4 17 28-JUL-2005 19:03:23 36 3.40 4 18 28-JUL-2005 19:03:24 41 3.60 4 19 28-JUL-2005 19:03:25 33 3.80 4 20 28-JUL-2005 19:03:26 19 4.00 4 The last step is to apply the appropriate aggregate functions to find the total number of transactions per 5 seconds along with the start and end times for each transaction: **select ceil(trx_id/5.0) as grp,** **min(trx_date) as trx_start,** **max(trx_date) as trx_end,** **sum(trx_cnt) as total** **from trx_log** **group** **by ceil(trx_id/5.0)** GRP TRX_START TRX_END TOTAL --- -------------------- -------------------- ---------- 1 28-JUL-2005 19:03:07 28-JUL-2005 19:03:11 141 2 28-JUL-2005 19:03:12 28-JUL-2005 19:03:16 178 3 28-JUL-2005 19:03:17 28-JUL-2005 19:03:21 202 4 28-JUL-2005 19:03:22 28-JUL-2005 19:03:26 173 If your data is slightly different (perhaps you don't have an ID for each row), you can always "group" by dividing the seconds of each TRX_DATE row by 5 to create a similar grouping. Then you can include the hour for each TRX_DATE and group by the actual hour and logical "grouping," GRP. Following is an example of this technique (using Oracle's TO_CHAR and TO_NUMBER functions, you would use the appropriate date and character formatting functions for your platform): **select trx_date,trx_cnt,** **to_number(to_char(trx_date,'hh24')) hr,** **ceil(to_number(to_char(trx_date-1/24/60/60,'miss'))/5.0) grp** **from trx_log** TRX_DATE TRX_CNT HR GRP -------------------- ---------- ---------- ---------- 28-JUL-2005 19:03:07 44 19 62 28-JUL-2005 19:03:08 18 19 62 28-JUL-2005 19:03:09 23 19 62 28-JUL-2005 19:03:10 29 19 62 28-JUL-2005 19:03:11 27 19 62 28-JUL-2005 19:03:12 45 19 63 28-JUL-2005 19:03:13 45 19 63 28-JUL-2005 19:03:14 32 19 63 28-JUL-2005 19:03:15 41 19 63 28-JUL-2005 19:03:16 15 19 63 28-JUL-2005 19:03:17 24 19 64 28-JUL-2005 19:03:18 47 19 64 28-JUL-2005 19:03:19 37 19 64 28-JUL-2005 19:03:20 48 19 64 28-JUL-2005 19:03:21 46 19 64 28-JUL-2005 19:03:22 44 19 65 28-JUL-2005 19:03:23 36 19 65 28-JUL-2005 19:03:24 41 19 65 28-JUL-2005 19:03:25 33 19 65 28-JUL-2005 19:03:26 19 19 65 Regardless of the actual values for GRP, the key here is that you are grouping for every 5 seconds. From there you can apply the aggregate functions in the same way as in the original solution: **select hr,grp,sum(trx_cnt) total** **from (** **select trx_date,trx_cnt,** **to_number(to_char(trx_date,'hh24')) hr,** **ceil(to_number(to_char(trx_date-1/24/60/60,'miss'))/5.0) grp** **from trx_log** **) x** **group** **by hr,grp** HR GRP TOTAL -- ---------- ---------- 19 62 141 19 63 178 19 64 202 19 65 173 Including the hour in the grouping is useful if your transaction log spans hours. In DB2 and Oracle, you can also use the window function SUM OVER to produce the same result. The following query returns all rows from TRX_LOG along with a running total for TRX_CNT by logical "group," and the TOTAL for TRX_CNT for each row in the "group": **select trx_id, trx_date, trx_cnt,** **sum(trx_cnt)over(partition by ceil(trx_id/5.0)** **order by trx_date** **range between unbounded preceding** **and current row) runing_total,** **sum(trx_cnt)over(partition by ceil(trx_id/5.0)) total,** **case when mod(trx_id,5.0) = 0 then 'X' end grp_end** **from trx_log** TRX_ID TRX_DATE TRX_CNT RUNING_TOTAL TOTAL GRP_END ------ -------------------- ---------- ------------ ---------- ------- 1 28-JUL-2005 19:03:07 44 44 141 2 28-JUL-2005 19:03:08 18 62 141 3 28-JUL-2005 19:03:09 23 85 141 4 28-JUL-2005 19:03:10 29 114 141 5 28-JUL-2005 19:03:11 27 141 141 X 6 28-JUL-2005 19:03:12 45 45 178 7 28-JUL-2005 19:03:13 45 90 178 8 28-JUL-2005 19:03:14 32 122 178 9 28-JUL-2005 19:03:15 41 163 178 10 28-JUL-2005 19:03:16 15 178 178 X 11 28-JUL-2005 19:03:17 24 24 202 12 28-JUL-2005 19:03:18 47 71 202 13 28-JUL-2005 19:03:19 37 108 202 14 28-JUL-2005 19:03:20 48 156 202 15 28-JUL-2005 19:03:21 46 202 202 X 16 28-JUL-2005 19:03:22 44 44 173 17 28-JUL-2005 19:03:23 36 80 173 18 28-JUL-2005 19:03:24 41 121 173 19 28-JUL-2005 19:03:25 33 154 173 20 28-JUL-2005 19:03:26 19 173 173 X ## 12.18. Performing Aggregations over Different Groups/Partitions Simultaneously ### Problem You want to aggregate over different dimensions at the same time. For example, you want to return a result set that lists each employee's name, his department, the number of employees in his department (himself included), the number of employees that have the same job as he does (himself included in this count as well), and the total number of employees in the EMP table. The result set should look like the following: ENAME DEPTNO DEPTNO_CNT JOB JOB_CNT TOTAL ------ ------ ---------- --------- -------- ------ MILLER 10 3 CLERK 4 14 CLARK 10 3 MANAGER 3 14 KING 10 3 PRESIDENT 1 14 SCOTT 20 5 ANALYST 2 14 FORD 20 5 ANALYST 2 14 SMITH 20 5 CLERK 4 14 JONES 20 5 MANAGER 3 14 ADAMS 20 5 CLERK 4 14 JAMES 30 6 CLERK 4 14 MARTIN 30 6 SALESMAN 4 14 TURNER 30 6 SALESMAN 4 14 WARD 30 6 SALESMAN 4 14 ALLEN 30 6 SALESMAN 4 14 BLAKE 30 6 MANAGER 3 14 ### Solution Window functions make this problem quite easy to solve. If you do not have window functions available to you, you can use scalar subqueries. #### DB2, Oracle, and SQL Server Use the COUNT OVER window function while specifying different partitions, or groups of data on which to perform aggregation: select ename, deptno, count(*)over(partition by deptno) deptno_cnt, job, count(*)over(partition by job) job_cnt, count(*)over() total from emp #### PostgreSQL and MySQL Use scalar subqueries in your SELECT list to perform the aggregate count operations on different groups of rows: 1 select e.ename, 2 e.deptno, 3 (select count(*) from emp d 4 where d.deptno = e.deptno) as deptno_cnt, 5 job, 6 (select count(*) from emp d 7 where d.job = e.job) as job_cnt, 8 (select count(*) from emp) as total 9 from emp e ### Discussion #### DB2, Oracle, and SQL Server This example really shows off the power and convenience of window functions. By simply specifying different partitions or groups of data to aggregate, you can create immensely detailed reports without having to self join over and over, and without having to write cumbersome and perhaps poorly performing subqueries in your SELECT list. All the work is done by the window function COUNT OVER. To understand the output, focus on the OVER clause for a moment for each COUNT operation: count(*)over(partition by deptno) count(*)over(partition by job) count(*)over() Remember the main parts of the OVER clause: the partition, specified by PARTITION BY: and the frame or window, specified by ORDER BY. Look at the first COUNT, which partitions by DEPTNO. The rows in table EMP will be grouped by DEPTNO and the COUNT operation will be performed on all the rows in each group. Since there is no frame or window clause specified (no ORDER BY), all the rows in the group are counted. The PARTITION BY clause finds all the unique DEPTNO values, and then the COUNT function counts the number of rows having each value. In the specific example of COUNT(*)OVER(PARTITION BY DEPTNO), The PARTITION BY clause identifies the partitions or groups to be values 10, 20, and 30. The same processing is applied to the second COUNT, which partitions by JOB. The last count does not partition by anything, and simply has an empty parenthesis. An empty parenthesis implies "the whole table." So, whereas the two prior COUNTs aggregate values based on the defined groups or partitions, the final COUNT counts all rows in table EMP. ### Warning Keep in mind that window functions are applied after the WHERE clause. If you were to filter the result set in some way, for example, excluding all employees in DEPTNO 10, the value for TOTAL would not be 14, it would be 11. To filter results after window functions have been evaluated, you must make your windowing query into an inline view and then filter on the results from that view. #### PostgreSQL and MySQL For every row returned by the main query (rows from EMP E), use multiple scalar subqueries in the SELECT list to perform different counts for each DEPTNO and JOB. To get the TOTAL, simply use another scalar subquery to get the count of all employees in table EMP. ## 12.19. Performing Aggregations over a Moving Range of Values ### Problem You want to compute a moving aggregation, such as a moving sum on the salaries in table EMP. You want to compute a sum for every 90 days, starting with the HIREDATE of the first employee. You want to see how spending has fluctuated for every 90-day period between the first and last employee hired. You want to return the following result set: HIREDATE SAL SPENDING_PATTERN ----------- ------- ---------------- 17-DEC-1980 800 800 20-FEB-1981 1600 2400 22-FEB-1981 1250 3650 02-APR-1981 2975 5825 01-MAY-1981 2850 8675 09-JUN-1981 2450 8275 08-SEP-1981 1500 1500 28-SEP-1981 1250 2750 17-NOV-1981 5000 7750 03-DEC-1981 950 11700 03-DEC-1981 3000 11700 23-JAN-1982 1300 10250 09-DEC-1982 3000 3000 12-JAN-1983 1100 4100 ### Solution Being able to specify a moving window in the framing or windowing clause of window functions makes this problem very easy to solve, if your RDBMS supports such functions. The key is to order by HIREDATE in your window function and then specify a window of 90 days starting from the earliest employee hired. The sum will be computed using the salaries of employees hired up to 90 days prior to the current employee's HIREDATE (the current employee is included in the sum). If you do not have window functions available, you can use scalar subqueries, but the solution will be more complex. #### DB2 and Oracle For DB2 and Oracle, use the window function SUM OVER and order by HIREDATE. Specify a range of 90 days in the window or "framing" clause to allow the sum to be computed for each employee's salary and to include the salaries of all employees hired up to 90 days earlier. Because DB2 does not allow you to specify HIREDATE in the ORDER BY clause of a window function (line 3 below), you can order by DAYS(HIREDATE) instead: 1 select hiredate, 2 sal, 3 sum(sal)over(order by days(hiredate) 4 range between 90 preceding 5 and current row) spending_pattern 6 from emp e The Oracle solution is more straightforward than DB2's, because Oracle allows window functions to order by datetime types: 1 select hiredate, 2 sal, 3 sum(sal)over(order by hiredate 4 range between 90 preceding 5 and current row) spending_pattern 6 from emp e #### MySQL, PostgreSQL, and SQL Server Use a scalar subquery to sum the salaries of all employees hired up to 90 days prior to the day each employee was hired: 1 select e.hiredate, 2 e.sal, 3 (select sum(sal) from emp d 4 whered.hiredate between e.hiredate-90 5 and e.hiredate) as spending_pattern 6 from emp e 7 order by 1 ### Discussion #### DB2 and Oracle DB2 and Oracle share the same solution. The only difference, and it's minor between the two solutions, lies in how you specify HIREDATE in the ORDER BY clause of the window function. At the time of this book's writing, DB2 doesn't allow a DATE value in such an ORDER BY clause if you are using a numeric value to set the window's range. (For example, RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW allows you to order by a date, but RANGE BETWEEN 90 PRECEDING AND CURRENT ROW does not.) To understand what the solution query is doing, you simply need to understand what the window clause is doing. The window you are defining orders the salaries for all employees by HIREDATE. Then the function computes a sum. The sum is not computed for all salaries. Instead, the processing is as follows: 1. The salary of the first employee hired is evaluated. Since no employees were hired before the first employee, the sum at this point is simply the first employee's salary. 2. The salary of the next employee (by HIREDATE) is evaluated. This employee's salary is included in the moving sum along with any other employees who were hired up to 90 days prior. The HIREDATE of the first employee is December 17, 1980, and the HIREDATE of the next hired employee is February 20, 1981. The second employee was hired less than 90 days after the first employee, and thus the moving sum for the second employee is 2400 (1600 + 800). If you are having trouble understanding where the values in SPENDING_PATTERN come from, examine the following query and result set: **select distinct** **dense_rank()** **over(order by e.hiredate) window,** **e.hiredate current_hiredate,** **d.hiredate hiredate_within_90_days,** **d.sal sals_used_for_sum** **from emp e,** **emp d** **where d.hiredate between e.hiredate-90 and e.hiredate** WINDOW CURRENT_HIREDATE HIREDATE_WITHIN_90_DAYS SALS_USED_FOR_SUM ------ ---------------- ----------------------- ----------------- 1 17-DEC-1980 17-DEC-1980 800 2 20-FEB-1981 17-DEC-1980 800 2 20-FEB-1981 20-FEB-1981 1600 3 22-FEB-1981 17-DEC-1980 800 3 22-FEB-1981 20-FEB-1981 1600 3 22-FEB-1981 22-FEB-1981 1250 4 02-APR-1981 20-FEB-1981 1600 4 02-APR-1981 22-FEB-1981 1250 4 02-APR-1981 02-APR-1981 2975 5 01-MAY-1981 20-FEB-1981 1600 5 01-MAY-1981 22-FEB-1981 1250 5 01-MAY-1981 02-APR-1981 2975 5 01-MAY-1981 01-MAY-1981 2850 6 09-JUN-1981 02-APR-1981 2975 6 09-JUN-1981 01-MAY-1981 2850 6 09-JUN-1981 09-JUN-1981 2450 7 08-SEP-1981 08-SEP-1981 1500 8 28-SEP-1981 08-SEP-1981 1500 8 28-SEP-1981 28-SEP-1981 1250 9 17-NOV-1981 08-SEP-1981 1500 9 17-NOV-1981 28-SEP-1981 1250 9 17-NOV-1981 17-NOV-1981 5000 10 03-DEC-1981 08-SEP-1981 1500 10 03-DEC-1981 28-SEP-1981 1250 10 03-DEC-1981 17-NOV-1981 5000 10 03-DEC-1981 03-DEC-1981 950 10 03-DEC-1981 03-DEC-1981 3000 11 23-JAN-1982 17-NOV-1981 5000 11 23-JAN-1982 03-DEC-1981 950 11 23-JAN-1982 03-DEC-1981 3000 11 23-JAN-1982 23-JAN-1982 1300 12 09-DEC-1982 09-DEC-1982 3000 13 12-JAN-1983 09-DEC-1982 3000 13 12-JAN-1983 12-JAN-1983 1100 If you look at the WINDOW column, only those rows with the same WINDOW value will be considered for each sum. Take for example, WINDOW 3. The salaries used for the sum for that window are 800, 1600, and 1250, which total 3650. If you look at the final result set in the "Problem" section, you'll see the SPENDING_PATTERN for February 22, 1981 (WINDOW 3) is 3650. As proof, to verify that the above self join includes the correct salaries for the windows defined, simply sum the values in SALS_USED_FOR_SUM and group by CURRENT_DATE. The result should be the same as the result set shown in the "Problem" section (with the duplicate row for December 3, 1981, filtered out): **select current_hiredate,** **sum(sals_used_for_sum) spending_pattern** **from (** **select distinct** **dense_rank()** **over(order by e.hiredate) window,** **e.hiredate current_hiredate,** **d.hiredate hiredate_within_90_days,** **d.sal sals_used_for_sum** **from emp e,** **emp d** **where d.hiredate between e.hiredate-90 and e.hiredate** **) x** **group by current_hiredate** CURRENT_HIREDATE SPENDING_PATTERN ---------------- ---------------- 17-DEC-1980 800 20-FEB-1981 2400 22-FEB-1981 3650 02-APR-1981 5825 01-MAY-1981 8675 09-JUN-1981 8275 08-SEP-1981 1500 28-SEP-1981 2750 17-NOV-1981 7750 03-DEC-1981 11700 23-JAN-1982 10250 09-DEC-1982 3000 12-JAN-1983 4100 #### MySQL, PostgreSQL, and SQL Server The key to this solution is to use a scalar subquery (a self join will work as well) while using the aggregate function SUM to compute a sum for every 90 days based on HIREDATE. If you are having trouble seeing how this works, simply convert the solution to a self join and examine which rows are included in the computations. Consider the result set below, which returns the same result set as that in the solution: **select e.hiredate,** **e.sal,** **sum(d.sal) as spending_pattern** **from emp e, emp d** **where d.hiredate** **between e.hiredate-90 and e.hiredate** **group by e.hiredate,e.sal** **order by 1** \ HIREDATE SAL SPENDING_PATTERN ----------- ----- ---------------- 17-DEC-1980 800 800 20-FEB-1981 1600 2400 22-FEB-1981 1250 3650 02-APR-1981 2975 5825 01-MAY-1981 2850 8675 09-JUN-1981 2450 8275 08-SEP-1981 1500 1500 28-SEP-1981 1250 2750 17-NOV-1981 5000 7750 03-DEC-1981 950 11700 03-DEC-1981 3000 11700 23-JAN-1982 1300 10250 09-DEC-1982 3000 3000 12-JAN-1983 1100 4100 If it is still unclear, simply remove the aggregation and start with the Cartesian product. The first step is to generate a Cartesian product using table EMP so that each HIREDATE can be compared with all the other HIREDATEs. [Only a snippet of the result set is shown below because there are 196 rows (14x14) returned by a Cartesian of EMP.] **select e.hiredate,** **e.sal,** **d.sal,** **d.hiredate** **from emp e, emp d** HIREDATE SAL SAL HIREDATE ----------- ----- ----- ----------- 17-DEC-1980 800 800 17-DEC-1980 17-DEC-1980 800 1600 20-FEB-1981 17-DEC-1980 800 1250 22-FEB-1981 17-DEC-1980 800 2975 02-APR-1981 17-DEC-1980 800 1250 28-SEP-1981 17-DEC-1980 800 2850 01-MAY-1981 17-DEC-1980 800 2450 09-JUN-1981 17-DEC-1980 800 3000 09-DEC-1982 17-DEC-1980 800 5000 17-NOV-1981 17-DEC-1980 800 1500 08-SEP-1981 17-DEC-1980 800 1100 12-JAN-1983 17-DEC-1980 800 950 03-DEC-1981 17-DEC-1980 800 3000 03-DEC-1981 17-DEC-1980 800 1300 23-JAN-1982 20-FEB-1981 1600 800 17-DEC-1980 20-FEB-1981 1600 1600 20-FEB-1981 20-FEB-1981 1600 1250 22-FEB-1981 20-FEB-1981 1600 2975 02-APR-1981 20-FEB-1981 1600 1250 28-SEP-1981 20-FEB-1981 1600 2850 01-MAY-1981 20-FEB-1981 1600 2450 09-JUN-1981 20-FEB-1981 1600 3000 09-DEC-1982 20-FEB-1981 1600 5000 17-NOV-1981 20-FEB-1981 1600 1500 08-SEP-1981 20-FEB-1981 1600 1100 12-JAN-1983 20-FEB-1981 1600 950 03-DEC-1981 20-FEB-1981 1600 3000 03-DEC-1981 20-FEB-1981 1600 1300 23-JAN-1982 If you examine the result set above, you'll notice that there is no HIREDATE 90 days earlier or equal to December 17, except for December 17. So, the sum for that row should be only 800. If you examine the next HIREDATE, February 20, you'll notice that there is one HIREDATE that falls within the 90-day window (within 90 days prior), and that is December 17. If you sum the SAL from December 17 with the SAL from February 20 (because we are looking for HIREDATEs equal to each HIREDATE or within 90 days earlier) you get 2400, which happens to be the final result for that HIREDATE. Now that you know how it works, use a filter in the WHERE clause to return for each HIREDATE and HIREDATE that is equal to it or is no more than 90 days earlier: **select e.hiredate,** **e.sal,** **d.sal sal_to_sum,** **d.hiredate within_90_days** **from emp e, emp d** **where d.hiredate** **between e.hiredate-90 and e.hiredate** **order by 1** HIREDATE SAL SAL_TO_SUM WITHIN_90_DAYS ----------- ----- ---------- -------------- 17-DEC-1980 800 800 17-DEC-1980 20-FEB-1981 1600 800 17-DEC-1980 20-FEB-1981 1600 1600 20-FEB-1981 22-FEB-1981 1250 800 17-DEC-1980 22-FEB-1981 1250 1600 20-FEB-1981 22-FEB-1981 1250 1250 22-FEB-1981 02-APR-1981 2975 1600 20-FEB-1981 02-APR-1981 2975 1250 22-FEB-1981 02-APR-1981 2975 2975 02-APR-1981 01-MAY-1981 2850 1600 20-FEB-1981 01-MAY-1981 2850 1250 22-FEB-1981 01-MAY-1981 2850 2975 02-APR-1981 01-MAY-1981 2850 2850 01-MAY-1981 09-JUN-1981 2450 2975 02-APR-1981 09-JUN-1981 2450 2850 01-MAY-1981 09-JUN-1981 2450 2450 09-JUN-1981 08-SEP-1981 1500 1500 08-SEP-1981 28-SEP-1981 1250 1500 08-SEP-1981 28-SEP-1981 1250 1250 28-SEP-1981 17-NOV-1981 5000 1500 08-SEP-1981 17-NOV-1981 5000 1250 28-SEP-1981 17-NOV-1981 5000 5000 17-NOV-1981 03-DEC-1981 950 1500 08-SEP-1981 03-DEC-1981 950 1250 28-SEP-1981 03-DEC-1981 950 5000 17-NOV-1981 03-DEC-1981 950 950 03-DEC-1981 03-DEC-1981 950 3000 03-DEC-1981 03-DEC-1981 3000 1500 08-SEP-1981 03-DEC-1981 3000 1250 28-SEP-1981 03-DEC-1981 3000 5000 17-NOV-1981 03-DEC-1981 3000 950 03-DEC-1981 03-DEC-1981 3000 3000 03-DEC-1981 23-JAN-1982 1300 5000 17-NOV-1981 23-JAN-1982 1300 950 03-DEC-1981 23-JAN-1982 1300 3000 03-DEC-1981 23-JAN-1982 1300 1300 23-JAN-1982 09-DEC-1982 3000 3000 09-DEC-1982 12-JAN-1983 1100 3000 09-DEC-1982 12-JAN-1983 1100 1100 12-JAN-1983 Now that you know which SALs are to be included in the moving window of summation, simply use the aggregate function SUM to produce a more expressive result set: select e.hiredate, e.sal, sum(d.sal) as spending_pattern from emp e, emp d where d.hiredate between e.hiredate-90 and e.hiredate group by e.hiredate,e.sal order by 1 If you compare the result set for the query above and the result set for the query below (which is the original solution presented), you will see they are the same: select e.hiredate, e.sal, (select sum(sal) from emp d where d.hiredate between e.hiredate-90 and e.hiredate) as spending_pattern from emp e order by 1 HIREDATE SAL SPENDING_PATTERN ----------- ----- ---------------- 17-DEC-1980 800 800 20-FEB-1981 1600 2400 22-FEB-1981 1250 3650 02-APR-1981 2975 5825 01-MAY-1981 2850 8675 09-JUN-1981 2450 8275 08-SEP-1981 1500 1500 28-SEP-1981 1250 2750 17-NOV-1981 5000 7750 03-DEC-1981 950 11700 03-DEC-1981 3000 11700 23-JAN-1982 1300 10250 09-DEC-1982 3000 3000 12-JAN-1983 1100 4100 ## 12.20. Pivoting a Result Set with Subtotals ### Problem You want to create a report containing subtotals, then transpose the results to provide a more readable report. For example, you've been asked to create a report that displays for each department, the managers in the department along with a sum of the salaries of the employees who work for those managers. Additionally, you want to return two subtotals: the sum of all salaries in each department for those employees who have managers, and a sum of all salaries in the result set (the sum of the department subtotals). You currently have the following report: DEPTNO MGR SAL ------ ---------- ---------- 10 7782 1300 10 7839 2450 10 3750 20 7566 6000 20 7788 1100 20 7839 2975 20 7902 800 20 10875 30 7698 6550 30 7839 2850 30 9400 24025 You want to provide a more readable report and wish to transform the above result set to the following, which makes the meaning of the report much more clear: MGR DEPT10 DEPT20 DEPT30 TOTAL ---- ---------- ---------- ---------- ---------- 7566 0 6000 0 7698 0 0 6550 7782 1300 0 0 7788 0 1100 0 7839 2450 2975 2850 7902 0 800 0 3750 10875 9400 24025 ### Solution The first step is to generate subtotals using the ROLLUP extension to GROUP BY. The next step is to perform a classic pivot (aggregate and CASE expression) to create the desired columns for your report. The GROUPING function allows you to easily determine which values are subtotals (that is, exist because of ROLLUP and otherwise would not normally be there). Depending on how your RDBMS sorts NULL values, you may need to add an ORDER BY to the solution to allow it to look like the target result set above. #### DB2 and Oracle Use the ROLLUP extension to GROUP BY then use a CASE expression to format the data into a more readable report: 1 select mgr, 2 sum(case deptno when 10 then sal else 0 end) dept10, 3 sum(case deptno when 20 then sal else 0 end) dept20, 4 sum(case deptno when 30 then sal else 0 end) dept30, 5 sum(case flag when '11' then sal else null end) total 6 from ( 7 select deptno,mgr,sum(sal) sal, 8 cast(grouping(deptno) as char(1))|| 9 cast(grouping(mgr) as char(1)) flag 10 from emp 11 where mgr is not null 12 group by rollup(deptno,mgr) 13 ) x 14 group by mgr #### SQL Server Use the ROLLUP extension to GROUP BY then use a CASE expression to format the data into a more readable report: 1 select mgr, 2 sum(case deptno when 10 then sal else 0 end) dept10, 3 sum(case deptno when 20 then sal else 0 end) dept20, 4 sum(case deptno when 30 then sal else 0 end) dept30, 5 sum(case flag when '11' then sal else null end) total 6 from ( 7 select deptno,mgr,sum(sal) sal, 8 cast(grouping(deptno) as char(1))+ 9 cast(grouping(mgr) as char(1)) flag 10 from emp 11 where mgr is not null 12 group by deptno,mgr with rollup 13 ) x 14 group by mgr #### MySQL and PostgreSQL The GROUPING function is not supported by either RDBMS. ### Discussion The solutions provided above are identical except for the string concatenation and how GROUPING is specified. Because the solutions are so similar, the discussion below will refer to the SQL Server solution to highlight the intermediate result sets (the discussion is relevant to DB2 and Oracle as well). The first step is to generate a result set that sums the SAL for the employees in each DEPTNO per MGR. The idea is to show how much the employees make under a particular manager in a particular department. For example, this query below will allow you to compare the salaries of employees who work for KING in DEPTNO 10 compared with those who work for KING in DEPTNO 30: select deptno,mgr,sum(sal) sal from emp where mgr is not null group by mgr,deptno order by 1,2 DEPTNO MGR SAL ------ ---------- ---------- 10 7782 1300 10 7839 2450 20 7566 6000 20 7788 1100 20 7839 2975 20 7902 800 30 7698 6550 30 7839 2850 The next step is to use the ROLLUP extension to GROUP BY to create subtotals for each DEPTNO and across all employees (who have a manager): select deptno,mgr,sum(sal) sal from emp where mgr is not null group by deptno,mgr with rollup DEPTNO MGR SAL ------ ---------- ---------- 10 7782 1300 10 7839 2450 10 3750 20 7566 6000 20 7788 1100 20 7839 2975 20 7902 800 20 10875 30 7698 6550 30 7839 2850 30 9400 24025 With the subtotals created, you need a way to determine which values are in fact subtotals (created by ROLLUP) and which are results of the regular GROUP BY. Use the GROUPING function to create bitmaps to help identify the subtotal values from the regular aggregate values: select deptno,mgr,sum(sal) sal, cast(grouping(deptno) as char(1))+ cast(grouping(mgr) as char(1)) flag from emp where mgr is not null group by deptno,mgr with rollup DEPTNO MGR SAL FLAG ------ ---------- ---------- ---- 10 7782 1300 00 10 7839 2450 00 10 3750 01 20 7566 6000 00 20 7788 1100 00 20 7839 2975 00 20 7902 800 00 20 10875 01 30 7698 6550 00 30 7839 2850 00 30 9400 01 24025 11 If it isn't immediately obvious, the rows with a value of 00 for FLAG are the results of regular aggregation. The rows with a value of 01 for FLAG are the results of ROLLUP aggregating SAL by DEPTNO (since DEPTNO is listed first in the ROLLUP; if you switch the order, for example, "GROUP BY MGR, DEPTNO WITH ROLLUP", you'd see quite different results). The row with a value of 11 for FLAG is the result of ROLLUP aggregating SAL over all rows. At this point you have everything you need to create a beautified report by simply using CASE expressions. The goal is to provide a report that shows employee salaries for each manager across departments. If a manager does not have any subordinates in a particular department, a zero should be returned; otherwise, you want to return the sum of all salaries for that manager's subordinates in that department. Additionally, you want to add a final column, TOTAL, representing a sum of all the salaries in the report. The solution satisfying all these requirements is shown below: select mgr, sum(case deptno when 10 then sal else 0 end) dept10, sum(case deptno when 20 then sal else 0 end) dept20, sum(case deptno when 30 then sal else 0 end) dept30, sum(case flag when '11' then sal else null end) total from ( select deptno,mgr,sum(sal) sal, cast(grouping(deptno) as char(1))+ cast(grouping(mgr) as char(1)) flag from emp where mgr is not null group by deptno,mgr with rollup ) x group by mgr order by coalesce(mgr,9999) MGR DEPT10 DEPT20 DEPT30 TOTAL ---- ---------- ---------- ---------- ---------- 7566 0 6000 0 7698 0 0 6550 7782 1300 0 0 7788 0 1100 0 7839 2450 2975 2850 7902 0 800 0 3750 10875 9400 24025 ## Chapter 13. Hierarchical Queries This chapter introduces recipes for expressing hierarchical relationships that you may have in your data. It is typical when working with hierarchical data to have more difficulty retrieving and displaying the data (as a hierarchy) than storing it. This is particularly true because of the inflexibility of SQL (SQL's nonrecursive nature). When working with hierarchical queries, it is absolutely crucial that you take advantage of what your RDBMS supplies you to facilitate these operations; otherwise you will end up writing potentially less efficient queries and constructing convoluted data models to deal with the hierarchical data. For PostgreSQL users, the recursive WITH clause will most likely be added to later versions PostgreSQL, so it would behoove you to pay attention to the DB2 solutions to these queries. This chapter will provide recipes to help you unravel the hierarchical structure of your data by taking advantage of the functions supplied by each of the RDBMSs. Before starting, examine table EMP and the hierarchical relationship between EMPNO and MGR: **select empno,mgr** **from emp** **order by 2** EMPNO MGR ---------- ---------- 7788 7566 7902 7566 7499 7698 7521 7698 7900 7698 7844 7698 7654 7698 7934 7782 7876 7788 7566 7839 7782 7839 7698 7839 7369 7902 7839 If you look carefully, you will see that each value for MGR is also an EMPNO, meaning the manager of each employee in table EMP is also an employee in table EMP and not stored somewhere else. The relationship between MGR and EMPNO is a parent–child relationship in that the value for MGR is the most immediate parent for a given EMPNO (it is also possible that the manager for a specific employee can have a manager herself, and those managers can in turn have managers, and so on, creating an _n_ -tier hierarchy). If an employee has no manager, then MGR is NULL. ## 13.1. Expressing a Parent-Child Relationship ### Problem You want to include parent information along with data from child records. For example, you want to display each employee's name along with the name of his manager. You want to return the following result set: EMPS_AND_MGRS ------------------------------ FORD works for JONES SCOTT works for JONES JAMES works for BLAKE TURNER works for BLAKE MARTIN works for BLAKE WARD works for BLAKE ALLEN works for BLAKE MILLER works for CLARK ADAMS works for SCOTT CLARK works for KING BLAKE works for KING JONES works for KING SMITH works for FORD ### Solution Self join EMP on MGR and EMPNO to find the name of each employee's manager. Then use your RDBMS's supplied function(s) for string concatenation to generate the strings in the desired result set. #### DB2, Oracle, and PostgreSQL Self join on EMP. Then use the double vertical-bar (||) concatenation operator: 1 select a.ename || ' works for ' || b.ename as emps_and_mgrs 2 from emp a, emp b 3 where a.mgr = b.empno #### MySQL Self join on EMP. Then use the concatenation function CONCAT: 1 select concat(a.ename, ' works for ',b.ename) as emps_and_mgrs 2 from emp a, emp b 3 where a.mgr = b.empno #### SQL Server Self join on EMP. Then use the plus sign (+) as the concatenation operator: 1 select a.ename + ' works for ' + b.ename as emps_and_mgrs 2 from emp a, emp b 3 where a.mgr = b.empno ### Discussion The implementation is essentially the same for all the solutions. The difference lies only in the method of string concatenation, and thus one discussion will cover all of the solutions. The key is the join between MGR and EMPNO. The fist step is to build a Cartesian product by joining EMP to itself (only a portion of the rows returned by the Cartesian product is shown below): **select a.empno, b.empno** **from emp a, emp b** EMPNO MGR ----- ---------- 7369 7369 7369 7499 7369 7521 7369 7566 7369 7654 7369 7698 7369 7782 7369 7788 7369 7839 7369 7844 7369 7876 7369 7900 7369 7902 7369 7934 7499 7369 7499 7499 7499 7521 7499 7566 7499 7654 7499 7698 7499 7782 7499 7788 7499 7839 7499 7844 7499 7876 7499 7900 7499 7902 7499 7934 As you can see, by using a Cartesian product you are returning every possible EMPNO/EMPNO combination (such that it looks like the manager for EMPNO 7369 is all the other employees in the table, including EMPNO 7369). The next step is to filter the results such that you return only each employee and his manager's EMPNO. Accomplish this by joining on MGR and EMPNO: **1 select a.empno, b.empno mgr** **2 from emp a, emp b** **3 where a.mgr = b.empno** EMPNO MGR ---------- ---------- 7902 7566 7788 7566 7900 7698 7844 7698 7654 7698 7521 7698 7499 7698 7934 7782 7876 7788 7782 7839 7698 7839 7566 7839 7369 7902 Now that you have each employee and the EMPNO of his manager, you can return the name of each manager by simply selecting B.ENAME rather than B.EMPNO. If after some practice you have difficulty grasping how this works, you can use a scalar subquery rather than a self join to get the answer: **select a.ename,** **(select b.ename** **from emp b** **where b.empno = a.mgr) as mgr** **from emp a** ENAME MGR ---------- ---------- SMITH FORD ALLEN BLAKE WARD BLAKE JONES KING MARTIN BLAKE BLAKE KING CLARK KING SCOTT JONES KING TURNER BLAKE ADAMS SCOTT JAMES BLAKE FORD JONES MILLER CLARK The scalar subquery version is equivalent to the self join, except for one row: employee KING is in the result set, but that is not the case with the self join. "Why not?" you might ask. Remember, NULL is never equal to anything, not even itself. In the self-join solution, you use an equi-join between EMPNO and MGR, thus filtering out any employees who have NULL for MGR. To see employee KING when using the self-join method, you must outer join as shown in the following two queries. The first solution uses the ANSI outer join while the second uses the Oracle outer-join syntax. The output is the same for both and is shown following the second query: **/* ANSI */** **select a.ename, b.ename mgr** **from emp a left join emp b** **on (a.mgr = b.empno)** **/* Oracle */** **select a.ename, b.ename mgr** **from emp a, emp b** **where a.mgr = b.empno (+)** ENAME MGR ---------- ---------- FORD JONES SCOTT JONES JAMES BLAKE TURNER BLAKE MARTIN BLAKE WARD BLAKE ALLEN BLAKE MILLER CLARK ADAMS SCOTT CLARK KING BLAKE KING JONES KING SMITH FORD KING ## 13.2. Expressing a Child-Parent-Grandparent Relationship ### Problem Employee CLARK works for KING and to express that relationship you can use the first recipe in this chapter. What if employee CLARK was in turn a manager for another employee? Consider the following query: **select ename,empno,mgr** **from emp** **where ename in ('KING','CLARK','MILLER')** ENAME EMPNO MGR --------- -------- ------- CLARK 7782 7839 KING 7839 MILLER 7934 7782 As you can see, employee MILLER works for CLARK who in turn works for KING. You want to express the full hierarchy from MILLER to KING. You want to return the following result set: LEAF___BRANCH___ROOT --------------------- MILLER-->CLARK-->KING However, the single self-join approach from the previous recipe will not suffice to show the entire relationship from top to bottom. You could write a query that does two self joins, but what you really need is a general approach for traversing such hierarchies. ### Solution This recipe differs from the first recipe because there is now a three-tier relationship, as the title suggests. If your RDBMS does not supply functionality for traversing tree-structured data, then you can solve this problem using the techniques described for PostgreSQL and MySQL, but you must add an additional self join. DB2, SQL Server, and Oracle offer functions for expressing hierarchies. Thus self joins on those RDBMSs aren't necessary, though they certainly work. #### DB2 and SQL Server Use the recursive WITH clause to find MILLER's manager, CLARK, then CLARK's manager, KING. The SQL Server string concatenation operator + is used in this solution: 1 with x (tree,mgr,depth) 2 as ( 3 select cast(ename as varchar(100)), 4 mgr, 0 5 from emp 6 where ename = 'MILLER' 7 union all 8 select cast(x.tree+'-->'+e.ename as varchar(100)), 9 e.mgr, x.depth+1 10 from emp e, x 11 where x.mgr = e.empno 12 ) 13 select tree leaf___branch___root 14 from x 15 where depth = 2 The only modification necessary for this solution to work on DB2 is to use DB2's concatenation operator, ||. Otherwise, the solution will work as is, on DB2 as well as SQL Server. #### Oracle Use the function SYS_CONNECT_BY_PATH to return MILLER, MILLER's manager, CLARK, then CLARK's manager, KING. Use the CONNECT BY clause to walk the tree: 1 select ltrim( 2 sys_connect_by_path(ename,'-->'), 3 '-->') leaf___branch___root 4 from emp 5 where level = 3 6 start with ename = 'MILLER' 7 connect by prior mgr = empno #### PostgreSQL and MySQL Self join on table EMP twice to return MILLER, MILLER's manager, CLARK, then CLARK's manager, KING. The following solution uses PostgreSQL's concatenation operator, the double vertical-bar (||): 1 select a.ename||'-->'||b.ename 2 ||'-->'||c.ename as leaf___branch___root 3 from emp a, emp b, emp c 4 where a.ename = 'MILLER' 5 and a.mgr = b.empno 6 and b.mgr = c.empno For MySQL users, simply use the CONCAT function; this solution will work for PostgreSQL as well. ### Discussion #### DB2 and SQL Server The approach here is to start at the leaf node and walk your way up to the root (as useful practice, try walking in the other direction). The upper part of the UNION ALL simply finds the row for employee MILLER (the leaf node). The lower part of the UNION ALL finds the employee who is MILLER's manager, then finds that person's manager, and this process of finding the "manager's manager" repeats until processing stops at the highest-level manager (the root node). The value for DEPTH starts at 0 and increments automatically by 1 each time a manager is found. DEPTH is a value that DB2 maintains for you when you execute a recursive query. ### Tip For an interesting and in-depth introduction to the WITH clause with focus on its use recursively, see Jonathan Gennick's article "Understanding the WITH Clause" at <http://gennick.com/with.htm>. Next, the second query of the UNION ALL joins the recursive view X to table EMP, to define the parent–child relationship. The query at this point, using SQL Server's concatenation operator, is as follows: **with x (tree,mgr,depth)** **as (** **select cast(ename as varchar(100)),** **mgr, 0** **from emp** **where ename = 'MILLER'** **union all** **select cast(x.tree+'-->'+e.ename as varchar(100)),** **e.mgr, x.depth+1** **from emp e, x** **where x.mgr = e.empno** **)** **select tree leaf___branch___root** **from x** TREE DEPTH ---------- ---------- MILLER 0 CLARK 1 KING 2 At this point, the heart of the problem has been solved; starting from MILLER, return the full hierarchical relationship from bottom to top. What's left then is merely formatting. Since the tree traversal is recursive, simply concatenate the current ENAME from EMP to the one before it, which gives you the following result set: **with x (tree,mgr,depth)** **as (** **select cast(ename as varchar(100)),** **mgr, 0** **from emp** **where ename = 'MILLER'** **union all** **select cast(x.tree+'-->'+e.ename as varchar(100)),** **e.mgr, x.depth+1** **from emp e, x** **where x.mgr = e.empno** **)** **select depth, tree** **from x** DEPTH TREE ----- --------------------------- 0 MILLER 1 MILLER-->CLARK 2 MILLER-->CLARK-->KING The final step is to keep only the last row in the hierarchy. There are several ways to do this, but the solution uses DEPTH to determine when the root is reached (obviously, if CLARK has a manager other than KING, the filter on DEPTH would have to change; for a more generic solution that requires no such filter, see the next recipe). #### Oracle The CONNECT BY clause does all the work in the Oracle solution. Starting with MILLER, you walk all the way to KING without the need for any joins. The expression in the CONNECT BY clause defines the relationship of the data and how the tree will be walked: **select ename** **from emp** **start with ename = 'MILLER'** **connect by** **prior mgr = empno** ENAME -------- MILLER CLARK KING The keyword PRIOR lets you access values from the previous record in the hierarchy. Thus, for any given EMPNO you can use PRIOR MGR to access that employee's manager number. When you see a clause such as CONNECT BY PRIOR MGR = EMPNO, think of that clause as expressing a join between, in this case, parent and child. ### Tip For more on CONNECT BY and related features, see the following Oracle Technology Network articles: "Querying Hierarchies: Top-of-the-Line Support" at <http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/gennick_connectby.html>, and "New CONNECT BY Features in Oracle Database 10g"at <http://www.oracle.com/technology/oramag/webcolumns/2003/techarticles/gennick_connectby_10g.html>. At this point you have successfully displayed the full hierarchy starting from MILLER and ending at KING. The problem is for the most part solved. All that remains is the formatting. Use the function SYS_CONNECT_BY_PATH to append each ENAME to the one before it: **select sys_connect_by_path(ename,'-->') tree** **from emp** **start with ename = 'MILLER'** **connect by prior mgr = empno** TREE --------------------------- -->MILLER -->MILLER-->CLARK -->MILLER-->CLARK-->KING Because you are interested in only the complete hierarchy, you can filter on the pseudo-column LEVEL (a more generic approach is shown in the next recipe): **select sys_connect_by_path(ename,'-->') tree** **from emp** **where level = 3** **start with ename = 'MILLER'** **connect by prior mgr = empno** TREE --------------------------- -->MILLER-->CLARK-->KING The final step is to use the LTRIM function to remove the leading "-->" from the result set. #### PostgreSQL and MySQL Without built-in support for hierarchical queries, you must self join _n_ times to return the whole tree (where _n_ is the number of nodes between the leaf and the root, including the root itself; in this example, relative to MILLER, CLARK is a branch node and KING is the root node, so the distance is two nodes, and _n_ = 2). This solution simply uses the technique from the previous recipe and adds one more self join: **select a.ename as leaf,** **b.ename as branch,** **c.ename as root** **from emp a, emp b, emp c** **where a.ename = 'MILLER'** **and a.mgr = b.empno** **and b.mgr = c.empno** LEAF BRANCH ROOT --------- ---------- ----- MILLER CLARK KING The next and last step is to format the output using the || concatenation operator for PostgreSQL or the CONCAT function for MySQL. The drawback to this kind of query is that if the hierarchy changes—for example, if there is another node between CLARK and KING—the query would need to have yet another join to return the whole tree. This is why it is such an advantage to have and use built-in functions for hierarchies. ## 13.3. Creating a Hierarchical View of a Table ### Problem You want to return a result set that describes the hierarchy of an entire table. In the case of the EMP table, employee KING has no manager, so KING is the root node. You want to display, starting from KING, all employees under KING and all employees (if any) under KING's subordinates. Ultimately, you want to return the following result set: EMP_TREE ------------------------------ KING KING - BLAKE KING - BLAKE - ALLEN KING - BLAKE - JAMES KING - BLAKE - MARTIN KING - BLAKE - TURNER KING - BLAKE - WARD KING - CLARK KING - CLARK - MILLER KING - JONES KING - JONES - FORD KING - JONES - FORD - SMITH KING - JONES - SCOTT KING - JONES - SCOTT - ADAMS ### Solution #### DB2 and SQL Server Use the recursive WITH clause to start building the hierarchy at KING and then ultimately display all the employees. The solution following uses the DB2 concatenation operator "||". SQL Server users use the concatenation operator +. Other than the concatenation operators, the solution will work as-is on both RDBMSs: 1 with x (ename,empno) 2 as ( 3 select cast(ename as varchar(100)),empno 4 from emp 5 where mgr is null 6 union all 7 select cast(x.ename||' - '||e.ename as varchar(100)), 8 e.empno 9 from emp e, x 10 where e.mgr = x.empno 11 ) 12 select ename as emp_tree 13 from x 14 order by 1 #### Oracle Use the CONNECT BY function to define the hierarchy. Use SYS_CONNECT_BY_PATH function to format the output accordingly: 1 select ltrim( 2 sys_connect_by_path(ename,' - '), 3 ' - ') emp_tree 4 from emp 5 start with mgr is null 6 connect by prior empno=mgr 7 order by 1 This solution differs from that in the previous recipe in that it includes no filter on the LEVEL pseudo-column. Without the filter, all possible trees (where PRIOR EMPNO=MGR) are displayed. #### PostgreSQL Use three UNIONs and multiple self joins: 1 select emp_tree 2 from ( 3 select ename as emp_tree 4 from emp 5 where mgr is null 6 union 7 select a.ename||' - '||b.ename 8 from emp a 9 join 10 emp b on (a.empno=b.mgr) 11 where a.mgr is null 12 union 13 select rtrim(a.ename||' - '||b.ename 14 ||' - '||c.ename,' - ') 15 from emp a 16 join 17 emp b on (a.empno=b.mgr) 18 left join 19 emp c on (b.empno=c.mgr) 20 where a.ename = 'KING' 21 union 22 select rtrim(a.ename||' - '||b.ename||' - '|| 23 c.ename||' - '||d.ename,' - ') 24 from emp a 25 join 26 emp b on (a.empno=b.mgr) 27 join 28 emp c on (b.empno=c.mgr) 29 left join 30 emp d on (c.empno=d.mgr) 31 where a.ename = 'KING' 32 ) x 33 where tree is not null 34 order by 1 #### MySQL Use three UNIONs and multiple self joins: 1 select emp_tree 2 from ( 3 select ename as emp_tree 4 from emp 5 where mgr is null 6 union 7 select concat(a.ename,' - ',b.ename) 8 from emp a 9 join 10 emp b on (a.empno=b.mgr) 11 where a.mgr is null 12 union 13 select concat(a.ename,' - ', 14 b.ename,' - ',c.ename) 15 from emp a 16 join 17 emp b on (a.empno=b.mgr) 18 left join 19 emp c on (b.empno=c.mgr) 20 where a.ename = 'KING' 21 union 22 select concat(a.ename,' - ',b.ename,' - ', 23 c.ename,' - ',d.ename) 24 from emp a 25 join 26 emp b on (a.empno=b.mgr) 27 join 28 emp c on (b.empno=c.mgr) 29 left join 30 emp d on (c.empno=d.mgr) 31 where a.ename = 'KING' 32 ) x 33 where tree is not null 34 order by 1 ### Discussion #### DB2 and SQL Server The first step is to identify the root row (employee KING) in the upper part of the UNION ALL in the recursive view X. The next step is to find KING's subordinates, and their subordinates if there are any, by joining recursive view X to table EMP. Recursion will continue until you've returned all employees. Without the formatting you see in the final result set, the result set returned by the recursive view X is shown below: **with x (ename,empno)** **as (** **select cast(ename as varchar(100)),empno** **from emp** **where mgr is null** **union all** **select cast(e.ename as varchar(100)),e.empno** **from emp e, x** **where e.mgr = x.empno** **)** **select ename emp_tree** **from x** EMP_TREE ---------------- KING JONES SCOTT ADAMS FORD SMITH BLAKE ALLEN WARD MARTIN TURNER JAMES CLARK MILLER All the rows in the hierarchy are returned (which can be useful), but without the formatting you cannot tell who the managers are. By concatenating each employee to her manager, you return more meaningful output. Produce the desired output simply by using cast(x.ename+','+e.ename as varchar(100)) in the SELECT clause of the lower portion of the UNION ALL in recursive view X. The WITH clause is extremely useful in solving this type of problem, because the hierarchy can change (for example, leaf nodes become branch nodes) without any need to modify the query. #### Oracle The CONNECT BY clause returns the rows in the hierarchy. The START WITH clause defines the root row. If you run the solution without SYS_CONNECT_BY_PATH, you can see that the correct rows are returned (which can be useful), but not formatted to express the relationship of the rows: **select ename emp_tree** **from emp** **start with mgr is null** **connect by prior empno = mgr** EMP_TREE ----------------- KING JONES SCOTT ADAMS FORD SMITH BLAKE ALLEN WARD MARTIN TURNER JAMES CLARK MILLER By using the pseudo-column LEVEL and the function LPAD, you can see the hierarchy more clearly, and you can ultimately see why SYS_CONNECT_BY_PATH returns the results that you see in the desired output shown earlier: select lpad('.',2*level,'.')||ename emp_tree from emp start with mgr is null connect by prior empno = mgr EMP_TREE ----------------- ..KING ....JONES ......SCOTT ........ADAMS ......FORD ........SMITH ....BLAKE ......ALLEN ......WARD ......MARTIN ......TURNER ......JAMES ....CLARK ......MILLER The indentation in this output indicates who the managers are by nesting subordinates under their superiors. For example, KING works for no one. JONES works for KING. SCOTT works for JONES. ADAMS works for SCOTT. If you look at the corresponding rows from the solution when using SYS_CONNECT_BY_PATH, you will see that SYS_CONNECT_BY_PATH rolls up the hierarchy for you. When you get to a new node, you see all the prior nodes as well: KING KING - JONES KING - JONES - SCOTT KING - JONES - SCOTT - ADAMS ### Tip If you are on Oracle8 _i_ Database or earlier, you can use the PostgreSQL solution to this problem. Alternatively, because CONNECT BY is available on older versions of Oracle, you can simply use LEVEL and RPAD/ LPAD for formatting (although to reproduce the output created by SYS_CONNECT_BY_PATH would require a bit more work). #### PostgreSQL and MySQL With the exception of string concatenation in the SELECT clauses, the solutions are the same for both PostgreSQL and MySQL. The first step is to determine the maximum number of nodes for any one branch. You have to do this manually, before you write the query. If you examine the data in the EMP table, you will see that employees ADAM and SMITH are the leaf nodes at the greatest depth (you may wish to look at the Oracle discussion where you'll find a nicely formatted tree of the EMP hierarchy). If you look at employee ADAMS, you see that ADAMS works for SCOTT who in turn works for JONES who in turn works for KING, so the depth is 4. To be able to express a hierarchy with a depth of four, you must self join four instances of table EMP, and you must write a four-part UNION query. The results of the four-way self join (which is the lower part of the last UNION, from top to bottom) is shown below (using PostgreSQL syntax; MySQL users, simply substitute "||" for the CONCAT function call): **select rtrim(a.ename||' - '||b.ename||' - '||** **c.ename||' - '||d.ename,' - ') as max_depth_4** **from emp a** **join** **emp b on (a.empno=b.mgr)** **join** **emp c on (b.empno=c.mgr)** **left join** **emp d on (c.empno=d.mgr)** **where a.ename = 'KING'** MAX_DEPTH_4 ----------------------------- KING - JONES - FORD - SMITH KING - JONES - SCOTT - ADAMS KING - BLAKE - TURNER KING - BLAKE - ALLEN KING - BLAKE - WARD KING - CLARK - MILLER KING - BLAKE - MARTIN KING - BLAKE - JAMES The filter on A.ENAME is necessary to ensure that the root row is KING and no other employee. If you look at the result set above and compare it with the final result set, you'll see that there are some three-deep hierarchies not returned: KING - JONES - FORD and KING - JONES - SCOTT. To include those rows in the final result set, you need to write another query similar to the one above, but with one less join (self joining only three instances of table EMP rather than four). The result set of this query is shown below: **select rtrim(a.ename||' - '||b.ename** **||' - '||c.ename,' - ') as max_depth_3** **from emp a** **join** **emp b on (a.empno=b.mgr)** **left join** **emp c on (b.empno=c.mgr)** **where a.ename = 'KING'** MAX_DEPTH_3 --------------------------- KING - BLAKE - ALLEN KING - BLAKE - WARD KING - BLAKE - MARTIN KING - JONES - SCOTT KING - BLAKE - TURNER KING - BLAKE - JAMES KING - JONES - FORD KING - CLARK - MILLER Like the query before it, the filter on A.ENAME is necessary to ensure the root row node is KING. You'll notice some overlapping rows between the query above and the four-way EMP join. To get rid of the redundant rows, simply UNION the two queries: **select rtrim(a.ename||' - '||b.ename** **||' - '||c.ename,' - ') as partial_tree** **from emp a** **join** **emp b on (a.empno=b.mgr)** **left join** **emp c on (b.empno=c.mgr)** **where a.ename = 'KING'** **union** **select rtrim(a.ename||' - '||b.ename||' - '||** **c.ename||' - '||d.ename,' - ')** **from emp a** **join** **emp b on (a.empno=b.mgr)** **join** **emp c on (b.empno=c.mgr)** **left join** **emp d on (c.empno=d.mgr)** **where a.ename = 'KING'** PARTIAL_TREE ------------------------------- KING - BLAKE - ALLEN KING - BLAKE - JAMES KING - BLAKE - MARTIN KING - BLAKE - TURNER KING - BLAKE - WARD KING - CLARK - MILLER KING - JONES - FORD KING - JONES - FORD - SMITH KING - JONES - SCOTT KING - JONES - SCOTT - ADAMS At this point the tree is almost complete. The next step is to return rows that represent a two-deep hierarchy with KING as the root node (i.e., employees who work directly for KING). The query to return those rows is shown below: **select a.ename||' - '||b.ename as max_depth_2** **from emp a** **join** **emp b on (a.empno=b.mgr)** **where a.mgr is null** MAX_DEPTH_2 --------------- KING - JONES KING - BLAKE KING - CLARK The next step is to UNION the above query, to the PARTIAL_TREE union: **select a.ename||' - '||b.ename as partial_tree** **from emp a** **join** **emp b on (a.empno=b.mgr)** **where a.mgr is null** **union** **select rtrim(a.ename||' - '||b.ename** **||' - '||c.ename,' - ')** **from emp a** **join** **emp b on (a.empno=b.mgr)** **left join** **emp c on (b.empno=c.mgr)** **where a.ename = 'KING'** **union** **select rtrim(a.ename||' - '||b.ename||' - '||** **c.ename||' - '||d.ename,' - ')** **from emp a** **join** **emp b on (a.empno=b.mgr)** **join** **emp c on (b.empno=c.mgr)** **left join** **emp d on (c.empno=d.mgr)** **where a.ename = 'KING'** PARTIAL_TREE ---------------------------------- KING - BLAKE KING - BLAKE - ALLEN KING - BLAKE - JAMES KING - BLAKE - MARTIN KING - BLAKE - TURNER KING - BLAKE - WARD KING - CLARK KING - CLARK - MILLER KING - JONES KING - JONES - FORD KING - JONES - FORD - SMITH KING - JONES - SCOTT KING - JONES - SCOTT - ADAMS The final step is to UNION KING to the top of PARTIAL_TREE to return the desired result set. ## 13.4. Finding All Child Rows for a Given Parent Row ### Problem You want to find all the employees who work for JONES, either directly or indirectly (i.e., they work for someone who works for JONES). The list of employees under JONES is shown below (JONES is included in the result set): ENAME ---------- JONES SCOTT ADAMS FORD SMITH ### Solution Being able to move to the absolute top or bottom of a tree is extremely useful. For this solution there is no special formatting necessary. The goal is to simply return all employees who work under employee JONES, including JONES himself. This type of query really shows the usefulness of recursive SQL extensions like Oracle's CONNECT BY and SQL Server's/DB2's WITH clause. #### DB2 and SQL Server Use the recursive WITH clause to find all employees under JONES. Begin with JONES by specifying WHERE ENAME = 'JONES' in the first of the two union queries: 1 with x (ename,empno) 2 as ( 3 select ename,empno 4 from emp 5 where ename = 'JONES' 6 union all 7 select e.ename, e.empno 8 from emp e, x 9 where x.empno = e.mgr 10 ) 11 select ename 12 from x #### Oracle Use the CONNECT BY clause and specify START WITH ENAME = 'JONES' to find all the employees under JONES: 1 select ename 2 from emp 3 start with ename = 'JONES' 4 connect by prior empno = mgr #### PostgreSQL and MySQL You must know in advance how many nodes there are in the tree. The following queries show how to determine the depth of the hierarchy: **/* find JONES' EMPNO */** **select ename,empno,mgr** **from emp** **where ename = 'JONES'** ENAME EMPNO MGR ---------- ----------- --------- JONES 7566 7839 **/* are there any employees who work directly under JONES? */** **select count(*)** **from emp** **where mgr = 7566** COUNT(*) --------- 2 **/* there are two employees under JONES, find their EMPNOs */** **select ename,empno,mgr** **from emp** **where mgr = 7566** ENAME EMPNO MGR ---------- ----------- ----------- SCOTT 7788 7566 FORD 7902 7566 **/* are there any employees under SCOTT or FORD? */** **select count(*)** **from emp** **where mgr in (7788,7902)** COUNT(*) --------- 2 **/* there are two employees under SCOTT or FORD, find their EMPNOs */** **select ename,empno,mgr** **from emp** **where mgr in (7788,7902)** ENAME EMPNO MGR --------- ----------- -------- SMITH 7369 7902 ADAMS 7876 7788 **/* are there any employees under SMITH or ADAMS? */** **select count(*)** **from emp** **where mgr in (7369,7876)** COUNT(*) ---------- 0 The hierarchy starting from JONES ends with employees SMITH and ADAMS. That makes the hierarchy three levels deep. Now that you know the depth, you can begin to traverse the hierarchy from top to bottom. First, self join table EMP twice. Then unpivot inline view X to transform three columns with two rows into one column with six rows (in PostgreSQL, you can use GENERATE_SERIES(1,6) as an alternative to querying the T100 pivot table): 1 select distinct 2 case t100.id 3 when 1 then root 4 when 2 then branch 5 else leaf 6 end as JONES_SUBORDINATES 7 from ( 8 select a.ename as root, 9 b.ename as branch, 10 c.ename as leaf 11 from emp a, emp b, emp c 12 where a.ename = 'JONES' 13 and a.empno = b.mgr 14 and b.empno = c.mgr 15 ) x, 16 t100 17 where t100.id <= 6 As an alternative, you can use views and UNION the results. If you create the following views: create view v1 as select ename,mgr,empno from emp where ename = 'JONES' create view v2 as select ename,mgr,empno from emp where mgr = (select empno from v1) create view v3 as select ename,mgr,empno from emp where mgrin (select empno from v2) the solution then becomes: select ename from v1 union select ename from v2 union select ename from v3 ### Discussion #### DB2 and SQL Server The recursive WITH clause makes this a relatively easy problem to solve. The first part of the WITH clause, the upper part of the UNION ALL, returns the row for employee JONES. You need to return ENAME to see the name and EMPNO so you can use it to join on. The lower part of the UNION ALL recursively joins EMP.MGR to X.EMPNO. The join condition will be applied until the result set is exhausted. #### Oracle The START WTH clause tells the query to make JONES the root node. The condition in the CONNECT BY clause drives the tree walk and will run until the condition is no longer true. #### PostgreSQL and MySQL The technique used here is the same as that of the second recipe in this chapter, "Expressing a Child-Parent-Grandparent Relationship." A major drawback is that you must know in advance the depth of the hierarchy. ## 13.5. Determining Which Rows Are Leaf, Branch, or Root Nodes ### Problem You want to determine what type of node a given row is: a leaf, branch, or root. For this example, a leaf node is an employee who is not a manager. A branch node is an employee who is both a manager and also has a manager. A root node is an employee without a manager. You want to return 1 (TRUE) or 0 (FALSE) to reflect the status of each row in the hierarchy. You want to return the following result set: ENAME IS_LEAF IS_BRANCH IS_ROOT ---------- ---------- ---------- ---------- KING 0 0 1 JONES 0 1 0 SCOTT 0 1 0 FORD 0 1 0 CLARK 0 1 0 BLAKE 0 1 0 ADAMS 1 0 0 MILLER 1 0 0 JAMES 1 0 0 TURNER 1 0 0 ALLEN 1 0 0 WARD 1 0 0 MARTIN 1 0 0 SMITH 1 0 0 ### Solution It is important to realize that the EMP table is modeled in a tree hierarchy, not a recursive hierarchy, the value for MGR for root nodes is NULL. If EMP was modeled to use a recursive hierarchy, root nodes would be self-referencing (i.e., the value for MGR for employee KING would be KING's EMPNO). I find self-referencing to be counterintuitive and thus am using NULL values for root nodes' MGR. For Oracle users using CONNECT BY and DB2/SQL Server users using WITH, you'll find tree hierarchies easier to work with and potentially more efficient than recursive hierarchies. If you are in a situation where you have a recursive hierarchy and are using CONNECT BY or WITH, watch out: you can end up with a loop in your SQL. You need to code around such loops if you are stuck with recursive hierarchies. #### DB2, PostgreSQL, MySQL, and SQL Server Use three scalar subqueries to determine the correct "Boolean" value (either a 1 or a 0) to return for each node type: 1 select e.ename, 2 (select sign(count(*)) from emp d 3 where 0 = 4 (select count(*) from emp f 5 where f.mgr = e.empno)) as is_leaf, 6 (select sign(count(*)) from emp d 7 where d.mgr = e.empno 8 and e.mgr is not null) as is_branch, 9 (select sign(count(*)) from emp d 10 where d.empno = e.empno 11 and d.mgr is null) as is_root 12 from emp e 13 order by 4 desc,3 desc #### Oracle The scalar subquery solution will work for Oracle as well, and should be used if you are on a version of Oracle prior to Oracle Database 10 _g_. The following solution highlights built-in functions provided by Oracle (that were introduced in Oracle Database 10 _g_ ) to identify root and leaf rows. The functions are CONNECT_BY_ROOT and CONNECT_BY_ISLEAF, respectively: 1 select ename, 2 connect_by_isleaf is_leaf, 3 (select count(*) from emp e 4 where e.mgr = emp.empno 5 and emp.mgr is not null 6 and rownum = 1) is_branch, 7 decode(ename,connect_by_root(ename),1,0) is_root 8 from emp 9 start with mgr is null 10 connect by prior empno = mgr 11 order by 4 desc, 3 desc ### Discussion #### DB2, PostgreSQL, MySQL, and SQL Server This solution simply applies the rules defined in the "Problem" section to determine leaves, branches, and roots. The first step is to find determine whether an employee is a leaf node. If the employee is not a manager (no one works under her), then she is a leaf node. The first scalar subquery, IS_LEAF, is shown below: **select e.ename,** **(select sign(count(*)) from emp d** **where 0 =** **(select count(*) from emp f** **where f.mgr = e.empno)) as is_leaf** **from emp e** **order by 2 desc** ENAME IS_LEAF ----------- -------- SMITH 1 ALLEN 1 WARD 1 ADAMS 1 TURNER 1 MARTIN 1 JAMES 1 MILLER 1 JONES 0 BLAKE 0 CLARK 0 FORD 0 SCOTT 0 KING 0 Because the output for IS_LEAF should be a 0 or 1, it is necessary to take the SIGN of the COUNT(*) operation. Otherwise you would get 14 instead of 1 for leaf rows. As an alternative, you can use a table with only one row to count against, because you only want to return 0 or 1. For example: **select e.ename,** **(select count(*) from t1 d** **where not exists** **(select null from emp f** **where f.mgr = e.empno)) as is_leaf** **from emp e** **order by 2 desc** ENAME IS_LEAF ---------- ---------- SMITH 1 ALLEN 1 WARD 1 ADAMS 1 TURNER 1 MARTIN 1 JAMES 1 MILLER 1 JONES 0 BLAKE 0 CLARK 0 FORD 0 SCOTT 0 KING 0 The next step is to find branch nodes. If an employee is a manager (someone works for them), and they also happen to work for someone else, then the employee is a branch node. The results of the scalar subquery IS_BRANCH are shown below: **select e.ename,** **(select sign(count(*)) from emp d** **where d.mgr = e.empno** **and e.mgr is not null) as is_branch** **from emp e** **order by 2 desc** ENAME IS_BRANCH ----------- --------- JONES 1 BLAKE 1 SCOTT 1 CLARK 1 FORD 1 SMITH 0 TURNER 0 MILLER 0 JAMES 0 ADAMS 0 KING 0 ALLEN 0 MARTIN 0 WARD 0 Again, it is necessary to take the SIGN of the COUNT(*) operation. Otherwise you will get (potentially) values greater than 1 when a node is a branch. Like scalar subquery IS_LEAF, you can use a table with one row to avoid using SIGN. The following solution uses a one-row table named dual: **select e.ename,** **(select count(*) from t1 t** **where exists (** **select null from emp f** **where f.mgr = e.empno** **and e.mgr is not null)) as is_branch** **from emp e** **order by 2 desc** ENAME IS_BRANCH --------------- ---------- JONES 1 BLAKE 1 SCOTT 1 CLARK 1 FORD 1 SMITH 0 TURNER 0 MILLER 0 JAMES 0 ADAMS 0 KING 0 ALLEN 0 MARTIN 0 WARD 0 The last step is to find the root nodes. A root node is defined as an employee who is a manager but who does not work for anyone else. In table EMP, only KING is a root node. Scalar subquery IS_ROOT is shown below: **select e.ename,** **(select sign(count(*)) from emp d** **where d.empno = e.empno** **and d.mgr is null) as is_root** **from emp e** **order by 2 desc** ENAME IS_ROOT ---------- --------- KING 1 SMITH 0 ALLEN 0 WARD 0 JONES 0 TURNER 0 JAMES 0 MILLER 0 FORD 0 ADAMS 0 MARTIN 0 BLAKE 0 CLARK 0 SCOTT 0 Because EMP is a small 14-row table, it is easy to see that employee KING is the only root node, so in this case taking the SIGN of the COUNT(*) operation is not strictly necessary. If there can be multiple root nodes, then you can use SIGN, or you can use a one-row table in the scalar subquery as is shown earlier for IS_BRANCH and IS_LEAF. #### Oracle For those of you on versions of Oracle prior to Oracle Database 10 _g_ , you can follow the discussion for the other RDBMSs, as that solution will work (without modifications) in Oracle. If you are on Oracle Database 10 _g_ or later, you may want to take advantage of two functions to make identifying root and leaf nodes a simple task: they are CONNECT_BY_ROOT and CONNECT_BY_ISLEAF, respectively. As of the time of this writing, it is necessary to use CONNECT BY in your SQL statement in order for you to be able to use CONNECT_BY_ROOT and CONNECT_BY_ISLEAF. The first step is to find the leaf nodes by using CONNECT_BY_ISLEAF as follows: **select ename,** **connect_by_isleaf is_leaf** **from emp** **start with mgr is null** **connect by prior empno = mgr** **order by 2 desc** ENAME IS_LEAF ---------- ---------- ADAMS 1 SMITH 1 ALLEN 1 TURNER 1 MARTIN 1 WARD 1 JAMES 1 MILLER 1 KING 0 JONES 0 BLAKE 0 CLARK 0 FORD 0 SCOTT 0 The next step is to use a scalar subquery to find the branch nodes. Branch nodes are employees who are managers but who also work for someone else: **select ename,** **(select count(*) from emp e** **where e.mgr = emp.empno** **and emp.mgr is not null** **and rownum = 1) is_branch** **from emp** **start with mgr is null** **connect by prior empno = mgr** **order by 2 desc** ENAME IS_BRANCH ---------- ---------- JONES 1 SCOTT 1 BLAKE 1 FORD 1 CLARK 1 KING 0 MARTIN 0 MILLER 0 JAMES 0 TURNER 0 WARD 0 ADAMS 0 ALLEN 0 SMITH 0 The filter on ROWNUM is necessary to ensure that you return a count of 1 or 0, and nothing else. The last step is to identify the root nodes by using the function CONNECT_BY_ROOT. The solution finds the ENAME for the root node and compares it with all the rows returned by the query. If there is a match, that row is the root node: **select ename,** **decode(ename,connect_by_root(ename),1,0) is_root** **from emp** **start with mgr is null** **connect by prior empno = mgr** **order by 2 desc** ENAME IS_ROOT ---------- ---------- KING 1 JONES 0 SCOTT 0 ADAMS 0 FORD 0 SMITH 0 BLAKE 0 ALLEN 0 WARD 0 MARTIN 0 TURNER 0 JAMES 0 CLARK 0 MILLER 0 If using Oracle9 _i_ Database or later, you can use the SYS_CONNECT_BY_PATH function as an alternative to CONNECT_BY_ROOT. The Oracle9 _i_ Database version of the preceding would be: **select ename,** **decode(substr(root,1,instr(root,',')-1),NULL,1,0) root** **from (** **select ename,** **ltrim(sys_connect_by_path(ename,','),',') root** **from emp** **start with mgr is null** **connect by prior empno=mgr** **)** ENAME ROOT ---------- ---- KING 1 JONES 0 SCOTT 0 ADAMS 0 FORD 0 SMITH 0 BLAKE 0 ALLEN 0 WARD 0 MARTIN 0 TURNER 0 JAMES 0 CLARK 0 MILLER 0 The SYS_CONNECT_BY_PATH function rolls up a hierarchy starting from the root value as is shown below: **select ename,** **ltrim(sys_connect_by_path(ename,','),',') path** **from emp** **start with mgr is null** **connect by prior empno=mgr** ENAME PATH ---------- ---------------------------- KING KING JONES KING,JONES SCOTT KING,JONES,SCOTT ADAMS KING,JONES,SCOTT,ADAMS FORD KING,JONES,FORD SMITH KING,JONES,FORD,SMITH BLAKE KING,BLAKE ALLEN KING,BLAKE,ALLEN WARD KING,BLAKE,WARD MARTIN KING,BLAKE,MARTIN TURNER KING,BLAKE,TURNER JAMES KING,BLAKE,JAMES CLARK KING,CLARK MILLER KING,CLARK,MILLER To get the root row, simply substring out the first ENAME in PATH: **select ename,** **substr(root,1,instr(root,',')-1) root** **from (** **select ename,** **ltrim(sys_connect_by_path(ename,','),',') root** **from emp** **start with mgr is null** **connect by prior empno=mgr** **)** ENAME ROOT ---------- ---------- KING JONES KING SCOTT KING ADAMS KING FORD KING SMITH KING BLAKE KING ALLEN KING WARD KING MARTIN KING TURNER KING JAMES KING CLARK KING MILLER KING The last step is to flag the result from the ROOT column if it is NULL; that is your root row. ## Chapter 14. Odds 'n' Ends This chapter contains queries that didn't fit in any other chapter either because the chapter they would belong to is already long enough, or because the problems they solve are more fun than realistic. This chapter is meant to be a "fun" chapter, in that the recipes here may or may not be recipes that you would actually use; nevertheless, I consider the queries interesting and wanted to include them somewhere in this book. ## 14.1. Creating Cross-Tab Reports Using SQL Server's PIVOT Operator ### Problem You want to create a cross-tab report, to transform your result set's rows into columns. You are aware of traditional methods of pivoting but would like to try something different. In particular, you want to return the following result set without using CASE expressions or joins: DEPT_10 DEPT_20 DEPT_30 DEPT_40 ------- ----------- ----------- ---------- 3 5 6 0 ### Solution Use the PIVOT operator to create the required result set without CASE expressions or additional joins: 1 select [10] as dept_10, 2 [20] as dept_20, 3 [30] as dept_30, 4 [40] as dept_40 5 from (select deptno, empno from emp) driver 6 pivot ( 7 count(driver.empno) 8 for driver.deptno in ( [10],[20],[30],[40] ) 9 ) as empPivot ### Discussion The PIVOT operator may seem strange at first, but the operation it performs in the solution is technically the same as the more familiar transposition query shown below: **select sum(case deptno when 10 then 1 else 0 end) as dept_10,** **sum(case deptno when 20 then 1 else 0 end) as dept_20,** **sum(case deptno when 30 then 1 else 0 end) as dept_30,** **sum(case deptno when 40 then 1 else 0 end) as dept_40** **from emp** DEPT_10 DEPT_20 DEPT_30 DEPT_40 ------- ---------- ---------- ---------- 3 5 6 0 Now that you know what is essentially happening, let's break down what the PIVOT operator is doing. Line 5 of the solution shows an inline view named DRIVER: from (select deptno, empno from emp) driver I've chosen the alias "driver" because the rows from this inline view (or table expression) feed directly into the PIVOT operation. The PIVOT operator rotates the rows to columns by evaluating the items listed on line 8 in the FOR list (shown below): for driver.deptno in ( [10],[20],[30],[40] ) The evaluation goes something like this: 1. If there are any DEPTNOs with a value of 10, perform the aggregate operation defined ( COUNT(DRIVER.EMPNO) ) for those rows. 2. Repeat for DEPTNOs 20, 30, and 40. The items listed in the brackets on line 8 serve not only to define values for which aggregation is performed; the items also become the column names in the result set (without the square brackets). In the SELECT clause of the solution, the items in the FOR list are referenced and aliased. If you do not alias the items in the FOR list, the column names become the items in the FOR list sans brackets. Interestingly enough, since inline view DRIVER is just that, an inline view, you may put more complex SQL in there. For example, consider the situation where you want to modify the result set such that the actual department name is the name of the column. Listed below are the rows in table DEPT: **select * from dept** DEPTNO DNAME LOC ------ -------------- ------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON You would like to use PIVOT to return the following result set: ACCOUNTING RESEARCH SALES OPERATIONS ---------- ---------- ---------- ---------- 3 5 6 0 Because inline view DRIVER can be practically any valid table expression, you can perform the join from table EMP to table DEPT, and then have PIVOT evaluate those rows. The following query will return the desired result set: select [ACCOUNTING] as ACCOUNTING, [SALES] as SALES, [RESEARCH] as RESEARCH, [OPERATIONS] as OPERATIONS from ( select d.dname, e.empno from emp e,dept d where e.deptno=d.deptno ) driver pivot ( count(driver.empno) for driver.dname in ([ACCOUNTING],[SALES],[RESEARCH],[OPERATIONS]) ) as empPivot As you can see, PIVOT provides an interesting spin on pivoting result sets. Regardless of whether or not you prefer using it to the traditional methods of pivoting, it's nice to have another tool in your toolbox. ## 14.2. Unpivoting a Cross-Tab Report Using SQL Server's UNPIVOT Operator ### Problem You have a pivoted result set (or simply a fat table) and you wish to unpivot the result set. For example, instead of having a result set with one row and four columns you want to return a result set with two columns and four rows. Using the result set from the previous recipe, you want to convert it from this: ACCOUNTING RESEARCH SALES OPERATIONS ---------- ---------- ---------- ---------- 3 5 6 0 to this: DNAME CNT -------------- ---------- ACCOUNTING 3 RESEARCH 5 SALES 6 OPERATIONS 0 ### Solution You didn't think SQL Server would give you the ability to PIVOT without being able to UNPIVOT, did you? To unpivot the result set just use it as the driver and let the UNPIVOT operator do all the work. All you need to do is specify the column names: 1 select DNAME, CNT 2 from ( 3 select [ACCOUNTING] as ACCOUNTING, 4 [SALES] as SALES, 5 [RESEARCH] as RESEARCH, 6 [OPERATIONS] as OPERATIONS 7 from ( 8 select d.dname, e.empno 9 from emp e,dept d 10 where e.deptno=d.deptno 11 12 ) driver 13 pivot ( 14 count(driver.empno) 15 for driver.dname in ([ACCOUNTING],[SALES],[RESEARCH],[OPERATIONS]) 16 ) as empPivot 17 ) new_driver 18 unpivot (cnt for dname in (ACCOUNTING,SALES,RESEARCH,OPERATIONS) 19 ) as un_pivot Hopefully, before reading this recipe you've read the one prior to it, because the inline view NEW_DRIVER is simply the code from the previous recipe (if you don't understand it, please refer to the previous recipe before looking at this one). Since lines 3–16 consist of code you've already seen, the only new syntax is on line 18, where you use UNPIVOT. The UNPIVOT command simply looks at the result set from NEW_DRIVER and evaluates each column and row. For example, the UNPIVOT operator evaluates the column names from NEW_DRIVER. When it encounters ACCOUNTING, it transforms the column name ACCOUNTING into a row value (under the column DNAME). It also takes the value for ACCOUNTING from NEW_DRIVER (which is 3) and returns that as part of the ACCOUNTING row as well (under the column CNT). UNPIVOT does this for each of the items specified in the FOR list and simply returns each one as a row. The new result set is now skinny and has two columns, DNAME and CNT, with four rows: **select DNAME, CNT** **from (** **select [ACCOUNTING] as ACCOUNTING,** **[SALES] as SALES,** **[RESEARCH] as RESEARCH,** **[OPERATIONS] as OPERATIONS** **from (** **select d.dname, e.empno** **from emp e,dept d** **where e.deptno=d.deptno** **) driver** **pivot (** **count(driver.empno)** **for driver.dname in ( [ACCOUNTING],[SALES],[RESEARCH],[OPERATIONS] )** **) as empPivot** **) new_driver** ******unpivot (cnt for dname in (ACCOUNTING,SALES,RESEARCH,OPERATIONS)** **) as un_pivot** DNAME CNT -------------- ---------- ACCOUNTING 3 RESEARCH 5 SALES 6 OPERATIONS 0 ## 14.3. Transposing a Result Set Using Oracle's MODEL Clause ### Problem Like the fist recipe in this chapter, you wish to find an alternative to the traditional pivoting techniques you've seen already. You want to try your hand at Oracle's MODEL clause. Unlike SQL Server's PIVOT operator, Oracle's MODEL clause does not exist to transpose result sets; as a matter of fact, it would be quite accurate to say the application of the MODEL clause for pivoting would be a misuse and clearly not what the MODEL clause was intended for. Nevertheless, the MODEL clause provides for an interesting approach to a common problem. For this particular problem, you want to transform the following result set from this: **select deptno, count(*) cnt** **from emp** **group by deptno** DEPTNO CNT ------ ---------- 10 3 20 5 30 6 to this: D10 D20 D30 ---------- ---------- ---------- 3 5 6 ### Solution Use aggregation and CASE expressions in the MODEL clause just as you would use them if pivoting with traditional techniques. The main difference in this case is that you use arrays to store the values of the aggregation and return the arrays in the result set: select max(d10) d10, max(d20) d20, max(d30) d30 from ( select d10,d20,d30 from ( select deptno, count(*) cnt from emp group by deptno ) model dimension by(deptno d) measures(deptno, cnt d10, cnt d20, cnt d30) rules( d10[any] = case when deptno[cv()]=10 then d10[cv()] else 0 end, d20[any] = case when deptno[cv()]=20 then d20[cv()] else 0 end, d30[any] = case when deptno[cv()]=30 then d30[cv()] else 0 end ) ) ### Discussion The MODEL clause is an extremely useful and powerful addition to the Oracle SQL toolbox. Once you begin working with MODEL you'll notice helpful features such as iteration, array access to row values, the ability to "upsert" rows into a result set, and the ability to build reference models. You'll quickly see that this recipe doesn't take advantage of any of the cool features the MODEL clause offers, but it's nice to be able to look at a problem from multiple angles and use different features in unexpected ways (if for no other reason than to learn where certain features are more useful than others). The first step to understanding the solution is to examine the inline view in the FROM clause. The inline view simply counts the number of employees in each DEPTNO in table EMP. The results are shown below: **select deptno, count(*) cnt** **from emp** **group by deptno** DEPTNO CNT ------ ---------- 10 3 20 5 30 6 This result set is what is given to MODEL to work with. Examining the MODEL clause, you see three subclauses that stand out: DIMENSION BY, MEASURES, and RULES. Let's start with MEASURES. The items in the MEASURES list are simply the arrays you are declaring for this query. The query uses four arrays: DEPTNO, D10, D20, and D30. Like columns in a SELECT list, arrays in the MEASURES list can have aliases. As you can see, three of the four arrays are actually CNT from the inline view. If the MEASURES list contains our arrays, then the items in the DIMENSION BY subclause are the array indices. Consider this: array D10 is simply an alias for CNT. If you look at the result set for the inline view above, you'll see that CNT has three values: 3, 5, and 6. When you create an array of CNT, you are creating an array with three elements, namely, the three integers 3, 5, and 6. Now, how do you access these values from the array individually? You use the array index. The index, defined in the DIMENSION BY subclause, has the values of 10, 20, and 30 (from the result set above). So, for example, the following expression: d10[10] would evaluate to 3, as you are accessing the value for CNT in array D10 for DEPTNO 10 (which is 3). Because each of the three arrays (D10, D20, D30) contain the values from CNT, all three of them have the same results. How then do we get the proper count into the correct array? Enter the RULES subclause. If you look at the result set for the inline view shown earlier, you'll see that the values for DEPTNO are 10, 20, and 30. The expressions involving CASE in the RULES clause simply evaluate each value in the DEPTNO array: * If the value is 10, store the CNT for DEPTNO 10 in D10[10] else store 0. * If the value is 20, store the CNT for DEPTNO 20 in D20[20] else store 0. * If the value is 30, store the CNT for DEPTNO 30 in D30[30] else store 0. If you find yourself feeling a bit like Alice tumbling down the rabbit hole, don't worry; just stop and execute what's been discussed thus far. The following result set represents what has been discussed. Sometimes it's easier to read a bit, look at the code that actually performs what you just read, then go back and read it again. The following is quite simple once you see it in action: **select deptno, d10,d20,d30** **from ( select deptno, count(*) cnt from emp group by deptno )** **model** **dimension by(deptno d)** **measures(deptno, cnt d10, cnt d20, cnt d30)** **rules(** **d10[any] = case when deptno[cv()]=10 then d10[cv()] else 0 end,** **d20[any] = case when deptno[cv()]=20 then d20[cv()] else 0 end,** **d30[any] = case when deptno[cv()]=30 then d30[cv()] else 0 end** **)** DEPTNO D10 D20 D30 ------ ---------- ---------- ---------- 10 3 0 0 20 0 5 0 30 0 0 6 As you can see, the RULES subclause is what changed the values in each array. If you are still not catching on, simply execute the same query but comment out the expressions in the RULES subclase: **select deptno, d10,d20,d30** **from ( select deptno, count(*) cnt from emp group by deptno )** **model** **dimension by(deptno d)** **measures(deptno, cnt d10, cnt d20, cnt d30)** **rules(** **/*** **d10[any] = case when deptno[cv()]=10 then d10[cv()] else 0 end,** **d20[any] = case when deptno[cv()]=20 then d20[cv()] else 0 end,** **d30[any] = case when deptno[cv()]=30 then d30[cv()] else 0 end** ***/** **)** DEPTNO D10 D20 D30 ------ ---------- ---------- ---------- 10 3 3 3 20 5 5 5 30 6 6 6 It should be clear now that the result set from the MODEL clause is the same as the inline view, except that the COUNT operation is aliased D10, D20, and D30. The query below proves this: **select deptno, count(*) d10, count(*) d20, count(*) d30** **from emp** **group by deptno** DEPTNO D10 D20 D30 ------ ---------- ---------- ---------- 10 3 3 3 20 5 5 5 30 6 6 6 So, all the MODEL clause did was to take the values for DEPTNO and CNT, put them into arrays, and then make sure that each array represents a single DEPTNO. At this point, arrays D10, D20, and D30 each have a single non-zero value representing the CNT for a given DEPTNO. The result set is already transposed, and all that is left is to use the aggregate function MAX (you could have used MIN or SUM; it would make no difference in this case) to return only one row: **select max(d10) d10,** **max(d20) d20,** **max(d30) d30** **from (** **select d10,d20,d30** **from ( select deptno, count(*) cnt from emp group by deptno )** **model** **dimension by(deptno d)** **measures(deptno, cnt d10, cnt d20, cnt d30)** **rules(** **d10[any] = case when deptno[cv()]=10 then d10[cv()] else 0 end,** **d20[any] = case when deptno[cv()]=20 then d20[cv()] else 0 end,** **d30[any] = case when deptno[cv()]=30 then d30[cv()] else 0 end** **)** **)** D10 D20 D30 ---------- ---------- ---------- 3 5 6 ## 14.4. Extracting Elements of a String from Unfixed Locations ### Problem You have a string field that contains serialized log data. You want to parse through the string and extract the relevant information. Unfortunately, the relevant information is not at fixed points in the string. Instead, you must use the fact that certain characters exist around the information you need, to extract said information. For example, consider the following strings: xxxxxabc[867]xxx[-]xxxx[5309]xxxxx xxxxxtime:[11271978]favnum:[4]id:[Joe]xxxxx call:[F_GET_ROWS()]b1:[ROSEWOOD...SIR]b2:[44400002]77.90xxxxx film:[non_marked]qq:[unit]tailpipe:[withabanana?]80sxxxxx You want to extract the values between the square brackets, returning the following result set: FIRST_VAL SECOND_VAL LAST_VAL --------------- ------------------- --------------- 867 - 5309 11271978 4 Joe F_GET_ROWS() ROSEWOOD...SIR 44400002 non_marked unit withabanana? ### Solution Despite not knowing the exact locations within the string of the interesting values, you do know that they are located between square brackets [], and you know there are three of them. Use Oracle's built-in function INSTR to find the locations to of the brackets. Use the built-in function SUBSTR to extract the values from the string. View V will contain the strings to parse and is defined as follows (its use is strictly for readability): create view V as select 'xxxxxabc[867]xxx[-]xxxx[5309]xxxxx' msg from dual union all select 'xxxxxtime:[11271978]favnum:[4]id:[Joe]xxxxx' msg from dual union all select 'call:[F_GET_ROWS()]b1:[ROSEWOOD...SIR]b2:[44400002]77.90xxxxx' msg from dual union all select 'film:[non_marked]qq:[unit]tailpipe:[withabanana?]80sxxxxx' msg from dual 1 select substr(msg, 2instr(msg,'[',1,1)+1, 3 instr(msg,']',1,1)-instr(msg,'[',1,1)-1) first_val, 4 substr(msg, 5 instr(msg,'[',1,2)+1, 6 instr(msg,']',1,2)-instr(msg,'[',1,2)-1) second_val, 7 substr(msg, 8 instr(msg,'[',-1,1)+1, 9 instr(msg,']',-1,1)-instr(msg,'[',-1,1)-1) last_val 10 from V ### Discussion Using Oracle's built-in function INSTR makes this problem fairly simple to solve. Since you know the values you are after are enclosed in [], and that there are three sets of [], the first step to this solution is to simply use INSTR to find the numeric positions of [] in each string. The following example returns the numeric position of the opening and closing brackets in each row: **select instr(msg,'[',1,1) "1st_[",** **instr(msg,']',1,1) "]_1st",** **instr(msg,'[',1,2) "2nd_[",** **instr(msg,']',1,2) "]_2nd",** **instr(msg,'[',-1,1) "3rd_[",** **instr(msg,']',-1,1) "]_3rd"** **from V** 1st_[ ]_1st 2nd_[ ]_2nd 3rd_[ ]_3rd ------ ----- ---------- ----- ---------- ----- 9 13 17 19 24 29 11 20 28 30 34 38 6 19 23 38 42 51 6 17 21 26 36 49 At this point, the hard work is done. All that is left is to plug the numeric positions into SUBSTR to parse MSG at those locations. You'll notice that in the complete solution there's some simple arithmetic on the values returned by INSTR, particularly, +1 and–1; this is necessary to ensure the opening square bracket, [, is not returned in the final result set. Listed below is the solution less addition and subtraction of 1 on the return values from INSTR; notice how each value has a leading square bracket: **select substr(msg,** **instr(msg,'[',1,1),** **instr(msg,']',1,1)-instr(msg,'[',1,1)) first_val,** **substr(msg,** **instr(msg,'[',1,2),** **instr(msg,']',1,2)-instr(msg,'[',1,2)) second_val,** **substr(msg,** **instr(msg,'[',-1,1),** **instr(msg,']',-1,1)-instr(msg,'[',-1,1)) last_val** **from V** FIRST_VAL SECOND_VAL LAST_VAL --------------- -------------------- ------- [867 [- [5309 [11271978 [4 [Joe [F_GET_ROWS() [ROSEWOOD...SIR [44400002 [non_marked [unit [withabanana? From the result set above, you can see that the open bracket is there. You may be thinking: "OK, put the addition of 1 to INSTR back and the leading square bracket goes away. Why do we need to subtract 1?" The reason is this: if you put the addition back but leave out the subtraction, you end up including the closing square bracket, as can be seen below: **select substr(msg,** **instr(msg,'[',1,1)+1,** **instr(msg,']',1,1)-instr(msg,'[',1,1)) first_val,** **substr(msg,** **instr(msg,'[',1,2)+1,** **instr(msg,']',1,2)-instr(msg,'[',1,2)) second_val,** **substr(msg,** **instr(msg,'[',-1,1)+1,** **instr(msg,']',-1,1)-instr(msg,'[',-1,1)) last_val** **from V** FIRST_VAL SECOND_VAL LAST_VAL --------------- --------------- ------------- 867] -] 5309] 11271978] 4] Joe] F_GET_ROWS()] ROSEWOOD...SIR] 44400002] non_marked] unit] withabanana?] At this point it should be clear: to ensure you include neither of the square brackets, you must add 1 to the beginning index and subtract one from the ending index. ## 14.5. Finding the Number of Days in a Year (an Alternate Solution for Oracle) ### Problem You want to find the number of days in a year. ### Tip This recipe presents an alternative solution to "Determining the Number of Days in a Year" from Chapter 9. This solution is specific to Oracle. ### Solution Use the TO_CHAR function to format the last date of the year into a three-digit day-of-the-year number: **1 select 'Days in 2005: '||** **2 to_char(add_months(trunc(sysdate,'y'),12)-1,'DDD')** **3 as report** **4 from dual** **5 union all** **6 select 'Days in 2004: '||** **7 to_char(add_months(trunc(** **8 to_date('01-SEP-2004'),'y'),12)-1,'DDD')** **9 from dual** REPORT ----------------- Days in 2005: 365 Days in 2004: 366 ### Discussion Begin by using the TRUNC function to return the first day of the year for the given date, as follows: **select trunc(to_date('01-SEP-2004'),'y')** **from dual** TRUNC(TO_DA ----------- 01-JAN-2004 Next, use ADD_MONTHS to add one year (12 months) to the truncated date. Then subtract one day, bringing you to the end of the year in which your original date falls: **select add_months(** **trunc(to_date('01-SEP-2004'),'y'),** **12) before_subtraction,** **add_months(** **trunc(to_date('01-SEP-2004'),'y'),** **12)-1 after_subtraction** **from dual** BEFORE_SUBT AFTER_SUBTR ----------- ----------- 01-JAN-2005 31-DEC-2004 Now that you have found the last day in the year you are working with, simply use TO_CHAR to return a three-digit number representing on which day (1st, 50th, etc.) of the year the last day is: **select to_char(** **add_months(** **trunc(to_date('01-SEP-2004'),'y'),** **12)-1,'DDD') num_days_in_2004** **from dual** NUM --- 366 ## 14.6. Searching for Mixed Alphanumeric Strings ### Problem You have a column with mixed alphanumeric data. You want to return those rows that have both alphabetical and numeric characters; in other words, if a string has only number or only letters, do not return it. The return values should have a mix of both letters and numbers. Consider the following data: STRINGS ------------ 1010 switch 333 3453430278 ClassSummary findRow 55 threes The final result set should contain only those rows that have both letters and numbers: STRINGS ------------ 1010 switch findRow 55 ### Solution Use the built-in function TRANSLATE to convert each occurrence of a letter or digit into a specific character. Then keep only those strings that have at least one occurrence of both. The solution uses Oracle syntax, but both DB2 and PostgreSQL support TRANSLATE, so modifying the solution to work on those platforms should be trivial: with v as ( select 'ClassSummary' strings from dual union select '3453430278' from dual union select 'findRow 55' from dual union select '1010 switch' from dual union select '333' from dual union select 'threes' from dual ) select strings from ( select strings, translate( strings, 'abcdefghijklmnopqrstuvwxyz0123456789', rpad('#',26,'#')||rpad('*',10,'*')) translated from v ) x whereinstr(translated,'#') > 0 and instr(translated,'*') > 0 ### Tip As an alternative to the WITH clause, you may use an inline view or simply create a view. ### Discussion The TRANSLATE function makes this problem extremely easy to solve. The first step is to use TRANSLATE to identify all letters and all digits by pound (#) and asterisk (*) characters, respectively. The intermediate results (from inline view X) are as follows: **with v as (** **select 'ClassSummary' strings from dual union** **select '3453430278' from dual union** **select 'findRow 55' from dual union** **select '1010 switch' from dual union** **select '333' from dual union** **select 'threes' from dual** **)** **select strings,** **translate(** **strings,** **'abcdefghijklmnopqrstuvwxyz0123456789',** **rpad('#',26,'#')||rpad('*',10,'*')) translated** **from v** STRINGS TRANSLATED ------------- ------------ 1010 switch **** ###### 333 *** 3453430278 ********** ClassSummary C####S###### findRow 55 ####R## ** threes ###### At this point, it is only a matter of keeping those rows that have at least one instance each of "#" and "*". Use the function INSTR to determine whether "#" and "*" are in a string. If those two characters are, in fact, present, then the value returned will be greater than zero. The final strings to return, along with their translated values, are shown next for clarity: **with v as (** **select 'ClassSummary' strings from dual union** **select '3453430278' from dual union** **select 'findRow 55' from dual union** **select '1010 switch' from dual union** **select '333' from dual union** **select 'threes' from dual** **)** **select strings, translated** **from (** **select strings,** **translate(** **strings,** **'abcdefghijklmnopqrstuvwxyz0123456789',** **rpad('#',26,'#')||rpad('*',10,'*')) translated** **from v** **)** **where instr(translated,'#')> 0** **and instr(translated,'*')> 0** STRINGS TRANSLATED ------------ ------------ 1010 switch **** ###### findRow 55 ####R## ** ## 14.7. Converting Whole Numbers to Binary Using Oracle ### Problem You want to convert a whole number to its binary representation on an Oracle system. For example, you would like to return all the salaries in table EMP in binary as part of the following result set: ENAME SAL SAL_BINARY ---------- ----- -------------------- SMITH 800 1100100000 ALLEN 1600 11001000000 WARD 1250 10011100010 JONES 2975 101110011111 MARTIN 1250 10011100010 BLAKE 2850 101100100010 CLARK 2450 100110010010 SCOTT 3000 101110111000 KING 5000 1001110001000 TURNER 1500 10111011100 ADAMS 1100 10001001100 JAMES 950 1110110110 FORD 3000 101110111000 MILLER 1300 10100010100 ### Solution This solution makes use of the MODEL clause, so you'll need to be running Oracle Database 10 _g_ or later for it to work. Because of MODEL's ability to iterate and provide array access to row values, it is a natural choice for this operation (assuming you are forced to solve the problem in SQL, as a stored function is more appropriate here). Like the rest of the solutions in this book, even if you don't find a practical application for this code, focus on the technique. It is useful to know that the MODEL clause can perform procedural tasks while still keeping SQL's set-based nature and power. So, even if you find yourself saying: "I'd never do this in SQL," that's fine. I'm in no way suggesting you should or shouldn't. I only remind you to focus on the technique, so you can apply it to whatever you consider a more "practical" application. The following solution returns all ENAME and SAL from table EMP, while calling the MODEL clause in a scalar subquery (this way it serves as sort of a standalone function from table EMP that simply receives an input, processes it, and returns a value, much like a function would): 1 select ename, 2 sal, 3 ( 4 select bin 5 from dual 6 model 7 dimension by ( 0 attr ) 8 measures ( sal num, 9 cast(null as varchar2(30)) bin, 10 '0123456789ABCDEF' hex 11 ) 12 rules iterate (10000) until (num[0] <= 0) ( 13 bin[0] = substr(hex[cv()],mod(num[cv()],2)+1,1)||bin[cv()], 14 num[0] = trunc(num[cv()]/2) 15 ) 16 ) sal_binary 17 from emp ### Discussion I mentioned in the "Solution" section that this problem is most likely better solved via a stored function. Indeed, the idea for this recipe came from a function. As a matter of fact, this recipe is an adaptation of a function called TO_BASE, written by Tom Kyte of Oracle Corporation. Like other recipes in this book that you may decide not to use, even if you do not use this recipe it does a nice job of showing of some of the features of the MODEL clause such as iteration and array access of rows. To make the explanation easier, I am going to focus on a slight variation of the subquery containing the MODEL clause. The code that follows is essentially the subquery from the solution, except that it's been hard-wired to return the value 2 in binary: **select bin** **from dual** **model** **dimension by ( 0 attr )** **measures ( 2 num,** **cast(null as varchar2(30)) bin,** **'0123456789ABCDEF' hex** **)** **rules iterate (10000) until (num[0]<= 0) (** **bin[0] = substr (hex[cv()],mod(num[cv()],2)+1,1)||bin[cv()],** **num[0] = trunc(num[cv()]/2)** **)** BIN ---------- 10 The following query outputs the values returned from one iteration of the RULES defined in the query above: **select 2 start_val,** **'0123456789ABCDEF' hex,** **substr('0123456789ABCDEF',mod(2,2)+1,1) ||** **cast(null as varchar2(30)) bin,** **trunc(2/2) num** **from dual** START_VAL HEX BIN NUM --------- ---------------- ---------- --- 2 0123456789ABCDEF 0 1 START_VAL represents the number you want to convert to binary, which in this case is 2. The value for BIN is the result of a substring operation on '0123456789ABCDEF' (HEX, in the original solution). The value for NUM is the test that will determine when you exit the loop. As you can see from the preceding result set, the first time through the loop BIN is 0 and NUM is 1. Because NUM is not less than or equal to 0, another loop iteration occurs. The following SQL statement shows the results of the next iteration: **select num start_val,** **substr('0123456789ABCDEF',mod(1,2)+1,1) || bin bin,** **trunc(1/2) num** **from (** **select 2 start_val,** **'0123456789ABCDEF' hex,** **substr('0123456789ABCDEF',mod(2,2)+1,1) ||** **cast(null as varchar2(30)) bin,** **trunc(2/2) num** **from dual** **)** START_VAL BIN NUM --------- ---------- --- 1 10 0 The next time through the loop, the result of the substring operation on HEX returns 1 and the prior value of BIN, 0, is appended to it. The test, NUM, is now 0, thus this is the last iteration and the return value "10" is the binary representation of the number 2. Once you're comfortable with what's going on, you can remove the iteration from the MODEL clause and step through it row by row to follow how the rules are applied to come to the final result set, as is shown below: **select 2 orig_val, num, bin** **from dual** **model** **dimension by ( 0 attr )** **measures ( 2 num,** **cast(null as varchar2(30)) bin,** **'0123456789ABCDEF' hex** **)** **rules (** **bin[0] = substr (hex[cv()],mod(num[cv()],2)+1,1)||bin[cv()],** **num[0] = trunc(num[cv()]/2),** **bin[1] = substr (hex[0],mod(num[0],2)+1,1)||bin[0],** **num[1] = trunc(num[0]/2)** **)** ORIG_VAL NUM BIN -------- --- --------- 2 1 0 2 0 10 ## 14.8. Pivoting a Ranked Result Set ### Problem You want to rank the values in a table, then pivot the result set into three columns. The idea is to show the top three, the next three, then all the rest. For example, you want to rank the employees in table EMP by SAL, and then pivot the results into three columns. The desired result set is as follows: TOP_3 NEXT_3 REST --------------- --------------- -------------- KING (5000) BLAKE (2850) TURNER (1500) FORD (3000) CLARK (2450) MILLER (1300) SCOTT (3000) ALLEN (1600) MARTIN (1250) JONES (2975) WARD (1250) ADAMS (1100) JAMES (950) SMITH (800) ### Solution The key to this solution is to first use the window function DENSE_RANK OVER to rank the employees by SAL while allowing for ties. By using DENSE_RANK OVER, you can easily see the top three salaries, the next three salaries, and then all the rest. Next, use the window function ROW_NUMBER OVER to rank each employee within his group (the top three, next three, or last group). From there, simply perform a classic transpose, while using the built-in string functions available on your platform to beautify the results. The following solution uses Oracle syntax. Since both DB2 and SQL Server 2005 support window functions, converting the solution to work for those platforms is trivial: 1 select max(case grp when 1 then rpad(ename,6) || 2 ' ('|| sal ||')' end) top_3, 3 max(case grp when 2 then rpad(ename,6) || 4 ' ('|| sal ||')' end) next_3, 5 max(case grp when 3 then rpad(ename,6) || 6 ' ('|| sal ||')' end) rest 7 from ( 8 select ename, 9 sal, 10 rnk, 11 case when rnk <= 3 then 1 12 when rnk <= 6 then 2 13 else 3 14 end grp, 15 row_number()over ( 16 partition by case when rnk <= 3 then 1 17 when rnk <= 6 then 2 18 else 3 19 end 20 order by sal desc, ename 21 ) grp_rnk 22 from ( 23 select ename, 24 sal, 25 dense_rank()over(order by sal desc) rnk 26 from emp 27 ) x 28 ) y 29 group by grp_rnk ### Discussion This recipe is a perfect example of how much you can accomplish with so little, with the help of window functions. The solution may look involved, but as you break it down from inside out you will be surprised how simple it is. Let's begin by executing inline view X first: **select ename,** **sal,** **dense_rank()over(order by sal desc) rnk** **from emp** ENAME SAL RNK ---------- ----- ---------- KING 5000 1 SCOTT 3000 2 FORD 3000 2 JONES 2975 3 BLAKE 2850 4 CLARK 2450 5 ALLEN 1600 6 TURNER 1500 7 MILLER 1300 8 WARD 1250 9 MARTIN 1250 9 ADAMS 1100 10 JAMES 950 11 SMITH 800 12 As you can see from the result set above, inline view X simply ranks the employees by SAL, while allowing for ties (because the solution uses DENSE_RANK instead of RANK, there are ties without gaps). The next step is to take the rows from inline view X and create groups by using a CASE expression to evaluate the ranking from DENSE_RANK. Additionally, use the window function ROW_NUMBER OVER to rank the employees by SAL within their group (within the group you are creating with the CASE expression). All of this happens in inline view Y and is shown below: **select ename,** **sal,** **rnk,** **case when rnk<= 3 then 1** **when rnk<= 6 then 2** **else 3** **end grp,** **row_number()over (** **partition by case when rnk<= 3 then 1** **when rnk<= 6 then 2** **else 3** **end** **order by sal desc, ename** **) grp_rnk** **from (** **select ename,** **sal,** **dense_rank()over(order by sal desc) rnk** **from emp** **) x** ENAME SAL RNK GRP GRP_RNK ---------- ----- ---- ---- ------- KING 5000 1 1 1 FORD 3000 2 1 2 SCOTT 3000 2 1 3 JONES 2975 3 1 4 BLAKE 2850 4 2 1 CLARK 2450 5 2 2 ALLEN 1600 6 2 3 TURNER 1500 7 3 1 MILLER 1300 8 3 2 MARTIN 1250 9 3 3 WARD 1250 9 3 4 ADAMS 1100 10 3 5 JAMES 950 11 3 6 SMITH 800 12 3 7 Now the query is starting to take shape and, if you followed it from the beginning (from inline view X), you can see that it's not that complicated. The query so far returns each employee, her SAL, her RNK, which represents where her SAL ranks amongst all employees, her GRP, which indicates the group each employee is in (based on SAL), and finally GRP_RANK, which is a ranking (based on SAL) within her GRP. At this point, perform a traditional pivot on ENAME while using the Oracle concatenation operator || to append the SAL. The function RPAD ensures that the numeric values in parentheses line up nicely. Finally, use GROUP BY on GRP_RNK to ensure you show each employee in the result set. The final result set is shown below: **select max(case grp when 1 then rpad(ename,6) ||** **' ('|| sal ||')' end) top_3,** **max(case grp when 2 then rpad(ename,6) ||** **' ('|| sal ||')' end) next_3,** **max(case grp when 3 then rpad(ename,6) ||** **' ('|| sal ||')' end) rest** **from (** **select ename,** **sal,** **rnk,** **case when rnk<= 3 then 1** **when rnk<= 6 then 2** **else 3** **end grp,** **row_number()over (** **partition by case when rnk<= 3 then 1** **when rnk<= 6 then 2** **else 3** **end** **Order by sal desc, ename** **) grp_rnk** **from (** **select ename,** **sal,** **dense_rank()over(order by sal desc) rnk** **from emp** **) x** **) y** **group by grp_rnk** TOP_3 NEXT_3 REST --------------- --------------- ------------- KING (5000) BLAKE (2850) TURNER (1500) FORD (3000) CLARK (2450) MILLER (1300) SCOTT (3000) ALLEN (1600) MARTIN (1250) JONES (2975) WARD (1250) ADAMS (1100) JAMES (950) SMITH (800) If you examine the queries in all of the steps you'll notice that table EMP is accessed exactly once. One of the remarkable things about window functions is how much work you can do in just one pass through your data. No need for self joins or temp tables; just get the rows you need, then let the window functions do the rest. Only in inline view X do you need to access EMP. From there, it's simply a matter of massaging the result set to look the way you want. Consider what all this means for performance if you can create this type of report with a single table access. Pretty cool. ## 14.9. Adding a Column Header into a Double Pivoted Result Set ### Problem You want to stack two result sets, and then pivot them into two columns. Additionally, you want to add a "header" for each group of rows in each column. For example, you have two tables containing information about employees working in different areas of development in your company (say, in research and applications): **select * from it_research** DEPTNO ENAME ------ -------------------- 100 HOPKINS 100 JONES 100 TONEY 200 MORALES 200 P.WHITAKER 200 MARCIANO 200 ROBINSON 300 LACY 300 WRIGHT 300 J.TAYLOR **select * from it_apps** DEPTNO ENAME ------ ----------------- 400 CORRALES 400 MAYWEATHER 400 CASTILLO 400 MARQUEZ 400 MOSLEY 500 GATTI 500 CALZAGHE 600 LAMOTTA 600 HAGLER 600 HEARNS 600 FRAZIER 700 GUINN 700 JUDAH 700 MARGARITO You would like to create a report listing the employees from each table in two columns. You want to return the DEPTNO followed by ENAME for each. Ultimately you want to return the following result set: RESEARCH APPS -------------------- --------------- 100 400 JONES MAYWEATHER TONEY CASTILLO HOPKINS MARQUEZ 200 MOSLEY P.WHITAKER CORRALES MARCIANO 500 ROBINSON CALZAGHE MORALES GATTI 300 600 WRIGHT HAGLER J.TAYLOR HEARNS LACY FRAZIER LAMOTTA 700 JUDAH MARGARITO GUINN ### Solution For the most part, this solution requires nothing more than a simple stack-n-pivot (union then pivot) with an added twist: the DEPTNO must precede the ENAME for each employee returned. The technique here uses a Cartesian product to generate an extra row for each DEPTNO, so you have the required rows necessary to show all employees, plus room for the DEPTNO. The solution uses Oracle syntax, but since DB2 supports window functions that can compute moving windows (the framing clause), converting this solution to work for DB2 is trivial. Because the IT_ RESEARCH and IT_APPS tables exist only for this recipe, their table creation statements are shown along with this solution: create table IT_research (deptno number, ename varchar2(20)) insert into IT_research values (100,'HOPKINS') insert into IT_research values (100,'JONES') insert into IT_research values (100,'TONEY') insert into IT_research values (200,'MORALES') insert into IT_research values (200,'P.WHITAKER') insert into IT_research values (200,'MARCIANO') insert into IT_research values (200,'ROBINSON') insert into IT_research values (300,'LACY') insert into IT_research values (300,'WRIGHT') insert into IT_research values (300,'J.TAYLOR') create table IT_apps (deptno number, ename varchar2(20)) insert into IT_apps values (400,'CORRALES') insert into IT_apps values (400,'MAYWEATHER') insert into IT_apps values (400,'CASTILLO') insert into IT_apps values (400,'MARQUEZ') insert into IT_apps values (400,'MOSLEY') insert into IT_apps values (500,'GATTI') insert into IT_apps values (500,'CALZAGHE') insert into IT_apps values (600,'LAMOTTA') insert into IT_apps values (600,'HAGLER') insert into IT_apps values (600,'HEARNS') insert into IT_apps values (600,'FRAZIER') insert into IT_apps values (700,'GUINN') insert into IT_apps values (700,'JUDAH') insert into IT_apps values (700,'MARGARITO') 1 select max(decode(flag2,0,it_dept)) research, 2 max(decode(flag2,1,it_dept)) apps 3 from ( 4 select sum(flag1)over(partition by flag2 5 order by flag1,rownum) flag, 6 it_dept, flag2 7 from ( 8 select 1 flag1, 0 flag2, 9 decode(rn,1,to_char(deptno),' '||ename) it_dept 10 from ( 11 select x.*, y.id, 12 row_number()over(partition by x.deptno order by y.id) rn 13 from ( 14 select deptno, 15 ename, 16 count(*)over(partition by deptno) cnt 17 from it_research 18 ) x, 19 (select level id from dual connect by level <= 2) y 20 ) 21 where rn <= cnt+1 22 union all 23 select 1 flag1, 1 flag2, 24 decode(rn,1,to_char(deptno),' '||ename) it_dept 25 from ( 26 select x.*, y.id, 27 row_number()over(partition by x.deptno order by y.id) rn 28 from ( 29 select deptno, 30 ename, 31 count(*)over(partition by deptno) cnt 32 from it_apps 33 ) x, 34 (select level id from dual connect by level <= 2) y 35 ) 36 where rn <= cnt+1 37 ) tmp1 38 ) tmp2 39 group by flag ### Discussion Like many of the other warehousing/report type queries, the solution presented looks quite convoluted but once broken down you'll seen it's nothing more than a stack-n-pivot with a Cartesian twist (on the rocks, with a little umbrella). The way to break this query down is to work on each part of the UNION ALL first, then bring it together for the pivot. Let's start with the lower portion of the UNION ALL: **select 1 flag1, 1 flag2,** **decode(rn,1,to_char(deptno),' '||ename) it_dept** **from (** **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_apps** **) x,** **(select level id from dual connect by level<= 2) y** **) z** **where rn<= cnt+1** FLAG1 FLAG2 IT_DEPT ----- ---------- -------------------------- 1 1 400 1 1 MAYWEATHER 1 1 CASTILLO 1 1 MARQUEZ 1 1 MOSLEY 1 1 CORRALES 1 1 500 1 1 CALZAGHE 1 1 GATTI 1 1 600 1 1 HAGLER 1 1 HEARNS 1 1 FRAZIER 1 1 LAMOTTA 1 1 700 1 1 JUDAH 1 1 MARGARITO 1 1 GUINN Let's examine exactly how that result set is put together. Breaking down the above query to its simplest components, you have inline view X, which simply returns each ENAME and DEPTNO and the number of employees in each DEPTNO from table IT_APPS. The results are as follows: **select deptno deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_apps** DEPTNO ENAME CNT ------ -------------------- ---------- 400 CORRALES 5 400 MAYWEATHER 5 400 CASTILLO 5 400 MARQUEZ 5 400 MOSLEY 5 500 GATTI 2 500 CALZAGHE 2 600 LAMOTTA 4 600 HAGLER 4 600 HEARNS 4 600 FRAZIER 4 700 GUINN 3 700 JUDAH 3 700 MARGARITO 3 The next step is to create a Cartesian product between the rows returned from inline view X and two rows generated from DUAL using CONNECT BY. The results of this operation are as follows: **select *** **from (** **select deptno deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_apps** **) x,** **(select level id from dual connect by level<= 2) y** **order by 2** DEPTNO ENAME CNT ID ------ ---------- --- --- 500 CALZAGHE 2 1 500 CALZAGHE 2 2 400 CASTILLO 5 1 400 CASTILLO 5 2 400 CORRALES 5 1 400 CORRALES 5 2 600 FRAZIER 4 1 600 FRAZIER 4 2 500 GATTI 2 1 500 GATTI 2 2 700 GUINN 3 1 700 GUINN 3 2 600 HAGLER 4 1 600 HAGLER 4 2 600 HEARNS 4 1 600 HEARNS 4 2 700 JUDAH 3 1 700 JUDAH 3 2 600 LAMOTTA 4 1 600 LAMOTTA 4 2 700 MARGARITO 3 1 700 MARGARITO 3 2 400 MARQUEZ 5 1 400 MARQUEZ 5 2 400 MAYWEATHER 5 1 400 MAYWEATHER 5 2 400 MOSLEY 5 1 400 MOSLEY 5 2 As you can see from these results, each row from inline view X is now returned twice due to the Cartesian product with inline view Y. The reason a Cartesian is needed will become clear shortly. The next step is to take the current result set and rank each employee within his DEPTNO by ID (ID has a value of 1 or 2 as was returned by the Cartesian product). The result of this ranking is shown in the output from the following query: **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_apps** **) x,** **(select level id from dual connect by level<= 2) y** DEPTNO ENAME CNT ID RN ------ ---------- --- --- ---------- 400 CORRALES 5 1 1 400 MAYWEATHER 5 1 2 400 CASTILLO 5 1 3 400 MARQUEZ 5 1 4 400 MOSLEY 5 1 5 400 CORRALES 5 2 6 400 MOSLEY 5 2 7 400 MAYWEATHER 5 2 8 400 CASTILLO 5 2 9 400 MARQUEZ 5 2 10 500 GATTI 2 1 1 500 CALZAGHE 2 1 2 500 GATTI 2 2 3 500 CALZAGHE 2 2 4 600 LAMOTTA 4 1 1 600 HAGLER 4 1 2 600 HEARNS 4 1 3 600 FRAZIER 4 1 4 600 LAMOTTA 4 2 5 600 HAGLER 4 2 6 600 FRAZIER 4 2 7 600 HEARNS 4 2 8 700 GUINN 3 1 1 700 JUDAH 3 1 2 700 MARGARITO 3 1 3 700 GUINN 3 2 4 700 JUDAH 3 2 5 700 MARGARITO 3 2 6 Each employee is ranked; then his duplicate is ranked. The result set contains duplicates for all employees in table IT_APP, along with their ranking within their DEPTNO. The reason you need to generate these extra rows is because you need a slot in the result set to slip in the DEPTNO in the ENAME column. If you Cartesian-join IT_APPS with a one-row table, you get no extra rows (because cardinality of any table x1 = cardinality of that table). The next step is to take the results returned thus far and pivot the result set such that all the ENAMES are returned in one column but are preceded by the DEPTNO they are in. The following query shows how this happens: **select 1 flag1, 1 flag2,** **decode(rn,1,to_char(deptno),' '||ename) it_dept** **from (** **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_apps** **) x,** **(select level id from dual connect by level<= 2) y** **) z** **where rn<= cnt+1** FLAG1 FLAG2 IT_DEPT ----- ---------- ------------------------- 1 1 400 1 1 MAYWEATHER 1 1 CASTILLO 1 1 MARQUEZ 1 1 MOSLEY 1 1 CORRALES 1 1 500 1 1 CALZAGHE 1 1 GATTI 1 1 600 1 1 HAGLER 1 1 HEARNS 1 1 FRAZIER 1 1 LAMOTTA 1 1 700 1 1 JUDAH 1 1 MARGARITO 1 1 GUINN FLAG1 and FLAG2 come into play later and can be ignored for the moment. Focus your attention on the rows in IT_DEPT. The number of rows returned for each DEPTNO is CNT*2, but all that is needed is CNT+1, which is the filter in the WHERE clause. RN is the ranking for each employee. The rows kept are all those ranked less than or equal to CNT+1; i.e., all employees in each DEPTNO plus one more (this extra employee is the employee who is ranked first in their DEPTNO). This extra row is where the DEPTNO will slide in. By using DECODE (an older Oracle function that gives more or less the equivalent of a CASE expression) to evaluate the value of RN, you can slide the value of DEPTNO into the result set. The employee who was at position 1 (based on the value of RN) is still shown in the result set, but is now last in each DEPTNO (because the order is irrelevant, this is not a problem). That pretty much covers the lower part of the UNION ALL. The upper part of the UNION ALL is processed in the same way as the lower part so there's no need to explain how that works. Instead, let's examine the result set returned when stacking the queries: **select 1 flag1, 0 flag2,** **decode(rn,1,to_char(deptno),' '||ename) it_dept** **from (** **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_research** **) x,** **(select level id from dual connect by level<= 2) y** **)** **where rn<= cnt+1** **union all** **select 1 flag1, 1 flag2,** **decode(rn,1,to_char(deptno),' '||ename) it_dept** **from (** **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_apps** **) x,** **(select level id from dual connect by level<= 2) y** **)** **where rn<= cnt+1** FLAG1 FLAG2 IT_DEPT ----- ---------- ----------------------- 1 0 100 1 0 JONES 1 0 TONEY 1 0 HOPKINS 1 0 200 1 0 P.WHITAKER 1 0 MARCIANO 1 0 ROBINSON 1 0 MORALES 1 0 300 1 0 WRIGHT 1 0 J.TAYLOR 1 0 LACY 1 1 400 1 1 MAYWEATHER 1 1 CASTILLO 1 1 MARQUEZ 1 1 MOSLEY 1 1 CORRALES 1 1 500 1 1 CALZAGHE 1 1 GATTI 1 1 600 1 1 HAGLER 1 1 HEARNS 1 1 FRAZIER 1 1 LAMOTTA 1 1 700 1 1 JUDAH 1 1 MARGARITO 1 1 GUINN At this point, it isn't clear what FLAG1's purpose is, but you can see that FLAG2 identifies which rows come from which part of the UNION ALL (0 for the upper part, 1 for the lower part). The next step is to wrap the stacked result set in an inline view and create a running total on FLAG1 (finally, its purpose is revealed!), which will act as a ranking for each row in each stack. The results of the ranking (running total) are shown below: **select sum(flag1)over(partition by flag2** **order by flag1,rownum) flag,** **it_dept, flag2** **from (** **select 1 flag1, 0 flag2,** **decode(rn,1,to_char(deptno),' '||ename) it_dept** **from (** **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_research** **) x,** **(select level id from dual connect by level<= 2) y** **)** **where rn<= cnt+1** **union all** **select 1 flag1, 1 flag2,** **decode(rn,1,to_char(deptno),' '||ename) it_dept** **from (** **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_apps** **) x,** **(select level id from dual connect by level<= 2) y** **)** **where rn<= cnt+1** **) tmp1** FLAG IT_DEPT FLAG2 ---- --------------- ---------- 1 100 0 2 JONES 0 3 TONEY 0 4 HOPKINS 0 5 200 0 6 P.WHITAKER 0 7 MARCIANO 0 8 ROBINSON 0 9 MORALES 0 10 300 0 11 WRIGHT 0 12 J.TAYLOR 0 13 LACY 0 1 400 1 2 MAYWEATHER 1 3 CASTILLO 1 4 MARQUEZ 1 5 MOSLEY 1 6 CORRALES 1 7 500 1 8 CALZAGHEe 1 9 GATTI 1 10 600 1 11 HAGLER 1 12 HEARNS 1 13 FRAZIER 1 14 LAMOTTA 1 15 700 1 16 JUDAH 1 17 MARGARITO 1 18 GUINN 1 The last remaining step (finally!) is to pivot the value returned by TMP1 on FLAG2 while grouping by FLAG (the running total generated in TMP1). The results from TMP1 are wrapped in an inline view and pivoted (wrapped in a final inline view called TMP2). The final solution and result set is shown below: **select max(decode(flag2,0,it_dept)) research,** **max(decode(flag2,1,it_dept)) apps** **from (** **select sum(flag1)over(partition by flag2** **order by flag1,rownum) flag,** **it_dept, flag2** **from (** **select 1 flag1, 0 flag2,** **decode(rn,1,to_char(deptno),' '||ename) it_dept** **from (** **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_research** **) x,** **(select level id from dual connect by level<= 2) y** **)** **where rn<= cnt+1** **union all** **select 1 flag1, 1 flag2,** **decode(rn,1,to_char(deptno),' '||ename) it_dept** **from (** **select x.*, y.id,** **row_number()over(partition by x.deptno order by y.id) rn** **from (** **select deptno deptno,** **ename,** **count(*)over(partition by deptno) cnt** **from it_apps** **) x,** **(select level id from dual connect by level<= 2) y** **)** **where rn<= cnt+1** **) tmp1** **) tmp2** **group by flag** RESEARCH APPS -------------------- --------------- 100 400 JONES MAYWEATHER TONEY CASTILLO HOPKINS MARQUEZ 200 MOSLEY P.WHITAKER CORRALES MARCIANO 500 ROBINSON CALZAGHE MORALES GATTI 300 600 WRIGHT HAGLER J.TAYLOR HEARNS LACY FRAZIER LAMOTTA 700 JUDAH MARGARITO GUINN ## 14.10. Converting a Scalar Subquery to a Composite Subquery in Oracle ### Problem You would like to bypass the restriction of returning exactly one value from a scalar subquery. For example, you attempt to execute the following query: select e.deptno, e.ename, e.sal, (select d.dname,d.loc,sysdate today from dept d where e.deptno=d.deptno) from emp e but receive an error because subqueries in the SELECT list are allowed to return only a single value. ### Solution Admittedly, this problem is quite unrealistic, because a simple join between tables EMP and DEPT would allow you to return as many values you want from DEPT. Nevertheless, the key is to focus on the technique and understand how to apply it to a scenario that you find useful. The key to bypassing the requirement to return a single value when placing a SELECT within SELECT (scalar subquery) is to take advantage of Oracle's object types. You can define an object to have several attributes, and then you can work with it as a single entity or reference each element individually. In effect, you don't really bypass the rule at all. You simply return one value, an object, that in turn contains many attributes. This solution makes use of the following object type: create type generic_obj as object ( val1 varchar2(10), val2 varchar2(10), val3 date ); With this type in place, you can execute the following query: **1 select x.deptno,** **2 x.ename,** **3 x.multival.val1 dname,** **4 x.multival.val2 loc,** **5 x.multival.val3** **today** **6 from (** **7select e.deptno,** **8 e.ename,** **9 e.sal,** **10 (select generic_obj(d.dname,d.loc,sysdate+1)** **11 from dept d** **12 where e.deptno=d.deptno) multival** **13 from emp e** **14 ) x** DEPTNO ENAME DNAME LOC TODAY ------ ---------- ---------- ---------- ----------- 20 SMITH RESEARCH DALLAS 12-SEP-2005 30 ALLEN SALES CHICAGO 12-SEP-2005 30 WARD SALES CHICAGO 12-SEP-2005 20 JONES RESEARCH DALLAS 12-SEP-2005 30 MARTIN SALES CHICAGO 12-SEP-2005 30 BLAKE SALES CHICAGO 12-SEP-2005 10 CLARK ACCOUNTING NEW YORK 12-SEP-2005 20 SCOTT RESEARCH DALLAS 12-SEP-2005 10 KING ACCOUNTING NEW YORK 12-SEP-2005 30 TURNER SALES CHICAGO 12-SEP-2005 20 ADAMS RESEARCH DALLAS 12-SEP-2005 30 JAMES SALES CHICAGO 12-SEP-2005 20 FORD RESEARCH DALLAS 12-SEP-2005 10 MILLER ACCOUNTING NEW YORK 12-SEP-2005 ### Discussion The key to the solution is to use the object's constructor function (by default the constructor function has the same name as the object). Because the object itself is a single scalar value, it does not violate the scalar subquery rule, as you can see from the following: **select e.deptno,** **e.ename,** **e.sal,** **(select generic_obj(d.dname,d.loc,sysdate-1)** **from dept d** **where e.deptno=d.deptno) multival** **from emp e** DEPTNO ENAME SAL MULTIVAL(VAL1, VAL2, VAL3) ------ ------ ----- ------------------------------------------------------- 20 SMITH 800 GENERIC_OBJ('RESEARCH', 'DALLAS', '12-SEP-2005') 30 ALLEN 1600 GENERIC_OBJ('SALES', 'CHICAGO', '12-SEP-2005') 30 WARD 1250 GENERIC_OBJ('SALES', 'CHICAGO', '12-SEP-2005') 20 JONES 2975 GENERIC_OBJ('RESEARCH', 'DALLAS', '12-SEP-2005') 30 MARTIN 1250 GENERIC_OBJ('SALES', 'CHICAGO', '12-SEP-2005') 30 BLAKE 2850 GENERIC_OBJ('SALES', 'CHICAGO', '12-SEP-2005') 10 CLARK 2450 GENERIC_OBJ('ACCOUNTING', 'NEW YORK', '12-SEP-2005') 20 SCOTT 3000 GENERIC_OBJ('RESEARCH', 'DALLAS', '12-SEP-2005') 10 KING 5000 GENERIC_OBJ('ACCOUNTING', 'NEW YORK', '12-SEP-2005') 30 TURNER 1500 GENERIC_OBJ('SALES', 'CHICAGO', '12-SEP-2005') 20 ADAMS 1100 GENERIC_OBJ('RESEARCH', 'DALLAS', '12-SEP-2005') 30 JAMES 950 GENERIC_OBJ('SALES', 'CHICAGO', '12-SEP-2005') 20 FORD 3000 GENERIC_OBJ('RESEARCH', 'DALLAS', '12-SEP-2005') 10 MILLER 1300 GENERIC_OBJ('ACCOUNTING', 'NEW YORK', '12-SEP-2005') The next step is to simply wrap the query in an inline view and extract the attributes. ### Warning One important note: In Oracle, unlike the case with other vendors, you do not generally need to name your inline views. In this particular case, however, you do need to name your inline view. Otherwise you will not be able to reference the object's attributes. ## 14.11. Parsing Serialized Data into Rows ### Problem You have serialized data (stored in strings) that you want to parse and return as rows. For example, you store the following data: STRINGS ----------------------------------- entry:stewiegriffin:lois:brian: entry:moe::sizlack: entry:petergriffin:meg:chris: entry:willie: entry:quagmire:mayorwest:cleveland: entry:::flanders: entry:robo:tchi:ken: You want to convert these serialized strings into the following result set: VAL1 VAL2 VAL3 --------------- --------------- --------------- moe sizlack petergriffin meg chris quagmire mayorwest cleveland robo tchi ken stewiegriffin lois brian willie flanders ### Solution Each serialized string in this example can store up to three values. The values are delimited by colons, and a string may or may not have all three entries. If a string does not have all three entries, you must be careful to place the entries that are available into the correct column in the result set. For example, consider the following row: entry:::flanders: This row represents an entry with the first two values missing and only the third value available. Hence, if you examine the target result set in the "Problem" section, you will notice that for the row "flanders" is in, both VAL1 and VAL2 are NULL. The key to this solution is nothing more than a string walk with some string parsing, following by a simple pivot. This solution uses rows from view V, which is defined as follows. The example uses Oracle syntax, but since nothing more than string parsing functions are needed for this recipe, converting to other platforms is trivial: create view V as select 'entry:stewiegriffin:lois:brian:' strings from dual union all select 'entry:moe::sizlack:' from dual union all select 'entry:petergriffin:meg:chris:' from dual union all select 'entry:willie:' from dual union all select 'entry:quagmire:mayorwest:cleveland:' from dual union all select 'entry:::flanders:' from dual union all select 'entry:robo:tchi:ken:' from dual Using view V to supply the example data to parse, the solution is as follows: 1 with cartesian as ( 2 select level id 3 from dual 4 connect by level <= 100 5 ) 6 select max(decode(id,1,substr(strings,p1+1,p2-1))) val1, 7 max(decode(id,2,substr(strings,p1+1,p2-1))) val2, 8 max(decode(id,3,substr(strings,p1+1,p2-1))) val3 9 from ( 10 select v.strings, 11 c.id, 12 instr(v.strings,':',1,c.id) p1, 13 instr(v.strings,':',1,c.id+1)-instr(v.strings,':',1,c.id) p2 14 from v, cartesian c 15 where c.id <= (length(v.strings)-length(replace(v.strings,':')))-1 16 ) 17 group by strings 18 order by 1 ### Discussion The first step is to walk the serialized strings: **with cartesian as (** **select level id** **from dual** **connect by level<= 100** **)** **select v.strings,** **c.id** **from v,cartesian c** **where c.id<= (length(v.strings)-length(replace(v.strings,':')))-1** STRINGS ID ----------------------------------- --- entry:::flanders: 1 entry:::flanders: 2 entry:::flanders: 3 entry:moe::sizlack: 1 entry:moe::sizlack: 2 entry:moe::sizlack: 3 entry:petergriffin:meg:chris: 1 entry:petergriffin:meg:chris: 3 entry:petergriffin:meg:chris: 2 entry:quagmire:mayorwest:cleveland: 1 entry:quagmire:mayorwest:cleveland: 3 entry:quagmire:mayorwest:cleveland: 2 entry:robo:tchi:ken: 1 entry:robo:tchi:ken: 2 entry:robo:tchi:ken: 3 entry:stewiegriffin:lois:brian: 1 entry:stewiegriffin:lois:brian: 3 entry:stewiegriffin:lois:brian: 2 entry:willie: 1 The next step is to use the function INSTR to find the numeric position of each colon in each string. Since each value you need to extract is enclosed by two colons, the numeric values are aliased P1 and P2, for "position 1" and "position 2": **with cartesian as (** **select level id** **from dual** **connect by level<= 100** **)** **select v.strings,** **c.id,** **instr(v.strings,':',1,c.id) p1,** **instr(v.strings,':',1,c.id+1)-instr(v.strings,':',1,c.id) p2** **from v,cartesian c** **where c.id<= (length(v.strings)-length(replace(v.strings,':')))-1** **order by 1** STRINGS ID P1 P2 ----------------------------------- --- ---------- ---------- entry:::flanders: 1 6 1 entry:::flanders: 2 7 1 entry:::flanders: 3 8 9 entry:moe::sizlack: 1 6 4 entry:moe::sizlack: 2 10 1 entry:moe::sizlack: 3 11 8 entry:petergriffin:meg:chris: 1 6 13 entry:petergriffin:meg:chris: 3 23 6 entry:petergriffin:meg:chris: 2 19 4 entry:quagmire:mayorwest:cleveland: 1 6 9 entry:quagmire:mayorwest:cleveland: 3 25 10 entry:quagmire:mayorwest:cleveland: 2 15 10 entry:robo:tchi:ken: 1 6 5 entry:robo:tchi:ken: 2 11 5 entry:robo:tchi:ken: 3 16 4 entry:stewiegriffin:lois:brian: 1 6 14 entry:stewiegriffin:lois:brian: 3 25 6 entry:stewiegriffin:lois:brian: 2 20 5 entry:willie: 1 6 7 Now that you know the numeric positions for each pair of colons in each string, simply pass the information to the function SUBSTR to extract values. Since you want to create a result set with three columns, use DECODE to evaluate the ID from the Cartesian product: **with cartesian as (** **select level id** **from dual** **connect by level<= 100** **)** **select decode(id,1,substr(strings,p1+1,p2-1)) val1,** **decode(id,2,substr(strings,p1+1,p2-1)) val2,** **decode(id,3,substr(strings,p1+1,p2-1)) val3** **from (** **select v.strings,** **c.id,** **instr(v.strings,':',1,c.id) p1,** **instr(v.strings,':',1,c.id+1)-instr(v.strings,':',1,c.id) p2** **from v,cartesian c** **where c.id<= (length(v.strings)-length(replace(v.strings,':')))-1** **)** **order by 1** VAL1 VAL2 VAL3 --------------- --------------- -------------- moe petergriffin quagmire robo stewiegriffin willie lois meg mayorwest tchi brian sizlack chris cleveland flanders ken The last step is to apply an aggregate function to the values returned by SUBSTR while grouping by ID, to make a human-readable result set: **with cartesian as (** **select level id** **from dual** **connect by level<= 100** **)** **select max(decode(id,1,substr(strings,p1+1,p2-1))) val1,** **max(decode(id,2,substr(strings,p1+1,p2-1))) val2,** **max(decode(id,3,substr(strings,p1+1,p2-1))) val3** **from (** **select v.strings,** **c.id,** **instr(v.strings,':',1,c.id) p1,** **instr(v.strings,':',1,c.id+1)-instr(v.strings,':',1,c.id) p2** **from v,cartesian c** **where c.id<= (length(v.strings)-length(replace(v.strings,':')))-1** **)** **group by strings** **order by 1** VAL1 VAL2 VAL3 --------------- --------------- ----------- moe sizlack petergriffin meg chris quagmire mayorwest cleveland robo tchi ken stewiegriffin lois brian willie flanders ## 14.12. Calculating Percent Relative to Total ### Problem You want to report a set of numeric values, and you want to show each value as a percentage of the whole. For example, you are on an Oracle system and you want to return a result set that shows the breakdown of salaries by JOB so that you can determine which JOB position costs the company the most money. You also want to include the number of employees per JOB to prevent the results from being misleading. You want to produce the following report: JOB NUM_EMPS PCT_OF_ALL_SALARIES --------- ---------- ------------------- CLERK 4 14 ANALYST 2 20 MANAGER 3 28 SALESMAN 4 19 PRESIDENT 1 17 As you can see, if the number of employees is not included in the report, it would look as if the president position takes very little of the overall salary. Seeing that there is only one president helps put into perspective what that 17% means. ### Solution Only Oracle enables a decent solution to this problem, which involves using the built-in function RATIO_TO_REPORT. To calculate percentages of the whole for other databases, you can use division as shown in "Determining the Percentage of a Total" in Chapter 7. 1 select job,num_emps,sum(round(pct)) pct_of_all_salaries 2 from ( 3 select job, 4 count(*)over(partition by job) num_emps, 5 ratio_to_report(sal)over()*100 pct 6 from emp 7 ) 8 group by job,num_emps ### Discussion The first step is to use the window function COUNT OVER to return the number of employees per JOB. Then use RATIO_TO_REPORT to return the percentage each salary counts against the total (the value is returned in decimal): **select job,** **count(*)over(partition by job) num_emps,** **ratio_to_report(sal)over()*100 pct** **from emp** JOB NUM_EMPS PCT --------- ---------- ---------- ANALYST 2 10.3359173 ANALYST 2 10.3359173 CLERK 4 2.75624462 CLERK 4 3.78983635 CLERK 4 4.4788975 CLERK 4 3.27304048 MANAGER 3 10.2497847 MANAGER 3 8.44099914 MANAGER 3 9.81912145 PRESIDENT 1 17.2265289 SALESMAN 4 5.51248923 SALESMAN 4 4.30663221 SALESMAN 4 5.16795866 SALESMAN 4 4.30663221 The last step is to use the aggregate function SUM to sum the values returned by RATIO_TO_REPORT. Be sure to group by JOB and NUM_EMPS. Multiply by 100 to return a whole number that represents a percentage (e.g., to return 25 rather than 0.25 for 25%): **select job,num_emps,sum(round(pct)) pct_of_all_salaries** **from (** **select job,** **count(*)over(partition by job) num_emps,** **ratio_to_report(sal)over()*100 pct** **from emp** **)** **group by job,num_emps** JOB NUM_EMPS PCT_OF_ALL_SALARIES --------- ---------- ------------------- CLERK 4 14 ANALYST 2 20 MANAGER 3 28 SALESMAN 4 19 PRESIDENT 1 17 ## 14.13. Creating CSV Output from Oracle ### Problem You want to create a delimited list (perhaps comma delimited) from rows in a table. For example, using table EMP, you want to return the following result set: DEPTNO LIST ------ -------------------------------------- 10 MILLER,KING,CLARK 20 FORD,ADAMS,SCOTT,JONES,SMITH 30 JAMES,TURNER,BLAKE,MARTIN,WARD,ALLEN You are on an Oracle system (Oracle Database 10 _g_ or later) and want to use the MODEL clause. ### Solution This solution takes advantage of the iteration capabilities of Oracle's MODEL clause. The technique is to use the window function ROW_NUMBER OVER to rank each employee (by EMPNO, which is arbitrary) in each DEPTNO. Because MODEL provides array access, you can access prior array elements by subtracting from the rank. So, for each row, create a list that includes each employee's name, plus the name of the employee ranked before the current employee: 1 select deptno, 2 list 3 from ( 4 select * 5 from ( 6 select deptno,empno,ename, 7 lag(deptno)over(partition by deptno 8 order by empno) prior_deptno 9 from emp 10 ) 11 model 12 dimension by 13 ( 14 deptno, 15 row_number()over(partition by deptno order by empno) rn 16 ) 17 measures 18 ( 19 ename, 20 prior_deptno,cast(null as varchar2(60)) list, 21 count(*)over(partition by deptno) cnt, 22 row_number()over(partition by deptno order by empno) rnk 23 ) 24 rules 25 ( 26 list[any,any] 27 order by deptno,rn = case when prior_deptno[cv(),cv()] is null 28 then ename[cv(),cv()] 29 else ename[cv(),cv()]||','|| 30 list[cv(),rnk[cv(),cv()]-1] 31 end 32 ) 33 ) 34 where cnt = rn ### Discussion The first step is to use the window function LAG OVER to return the DEPTNO of the previous employee (sorted by EMPNO). The results are partitioned by DEPTNO, so the return value will be NULL for the first employee (by EMPNO) in the department and DEPTNO for the rest. The results are as follows: **select deptno,empno,ename,** **lag(deptno)over(partition by deptno** **order by empno) prior_deptno** **from emp** DEPTNO EMPNO ENAME PRIOR_DEPTNO ------ ---------- ------ ------------ 10 7782 CLARK 10 7839 KING 10 10 7934 MILLER 10 20 7369 SMITH 20 7566 JONES 20 20 7788 SCOTT 20 20 7876 ADAMS 20 20 7902 FORD 20 30 7499 ALLEN 30 7521 WARD 30 30 7654 MARTIN 30 30 7698 BLAKE 30 30 7844 TURNER 30 30 7900 JAMES 30 The next step is to examine the MEASURES subclause of the MODEL clause. The items in the MEASURES list are the arrays: ENAME An array of all the ENAMEs in EMP PRIOR_DEPTNO An array of the values returned by the LAG OVER window function CNT An array of the number of employees in each DEPTNO RNK An array of rankings (by EMPNO) for each employee in each DEPTNO The array indices are DEPTNO and RN (the value returned by the ROW_NUMBER OVER window function in the DIMENSION BY subclause). To see what all these arrays contain, simply comment out the code listed in the RULES subclause of the MODEL clause and execute the query, as follows: **select *** **from (** **select deptno,empno,ename,** **lag(deptno)over(partition by deptno** **order by empno) prior_deptno** **from emp** **)** **model** **dimension by** **(** **deptno,** **row_number()over(partition by deptno order by empno) rn** **)** **measures** **(** **ename,** **prior_deptno,cast(null as varchar2(60)) list,** **count(*)over(partition by deptno) cnt,** **row_number()over(partition by deptno order by empno) rnk** **)** **rules** **(** **/*** **list[any,any]** **order by deptno,rn = case when prior_deptno[cv(),cv()] is null** **then ename[cv(),cv()]** **else ename[cv(),cv()]||','||** **list[cv(),rnk[cv(),cv()]-1]** **end** ***/** **)** **order by 1** DEPTNO RN ENAME PRIOR_DEPTNO LIST CNT RNK ------ --- ------ ------------ ---------- --- ---- 10 1 CLARK 3 1 10 2 KING 10 3 2 10 3 MILLER 10 3 3 20 1 SMITH 5 1 20 2 JONES 20 5 2 20 4 ADAMS 20 5 4 20 5 FORD 20 5 5 20 3 SCOTT 20 5 3 30 1 ALLEN 6 1 30 6 JAMES 30 6 6 30 4 BLAKE 30 6 4 30 3 MARTIN 30 6 3 30 5 TURNER 30 6 5 30 2 WARD 30 6 2 Now that you know exactly what each item declared in the MODEL clause does, continue on to the RULES subclause. If you look at the CASE expression, you'll see that the current value for PRIOR_DEPTNO is being evaluated. If that value is NULL, it signifies that the first employee in each DEPTNO and ENAME should be returned to that employee's LIST array. If the value for PRIOR_DEPTNO is not NULL, then append the value of the prior employee's LIST to the current employee's name (ENAME array), and then return that result as the current employee's LIST. This CASE expression operation, when performed for each row in DEPTNO, results in an iteratively built comma-separated values (CSV) list. You can see the intermediate results in the following example: **select deptno,** **list** **from (** **select *** **from (** **select deptno,empno,ename,** **lag(deptno)over(partition by deptno** **order by empno) prior_deptno** **from emp** **)** **model** **dimension by** **(** **deptno,** **row_number()over(partition by deptno order by empno) rn** **)** **measures** **(** **ename,** **prior_deptno,cast(null as varchar2(60)) list,** **count(*)over(partition by deptno) cnt,** **row_number()over(partition by deptno order by empno) rnk** **)** **rules** **(** **list[any,any]** **order by deptno,rn = case when prior_deptno[cv(),cv()] is null** **then ename[cv(),cv()]** **else ename[cv(),cv()]||','||** **list[cv(),rnk[cv(),cv()]-1]** **end** **)** **)** DEPTNO LIST ------ --------------------------------------- 10 CLARK 10 KING,CLARK 10 MILLER,KING,CLARK 20 SMITH 20 JONES,SMITH 20 SCOTT,JONES,SMITH 20 ADAMS,SCOTT,JONES,SMITH 20 FORD,ADAMS,SCOTT,JONES,SMITH 30 ALLEN 30 WARD,ALLEN 30 MARTIN,WARD,ALLEN 30 BLAKE,MARTIN,WARD,ALLEN 30 TURNER,BLAKE,MARTIN,WARD,ALLEN 30 JAMES,TURNER,BLAKE,MARTIN,WARD,ALLEN The last step is to keep only the last employee in each DEPTNO to ensure that you have a complete CSV list for each DEPTNO. Use the values stored in the CNT array and the values stored in the RN array to keep only the completed CSV for each DEPTNO. Because RN represents a ranking of employees in each DEPTNO by EMPNO, the last employee in each DEPTNO will be the one where CNT = RN, as the following example shows: **select deptno,** **list** **from (** **select *** **from (** **select deptno,empno,ename,** **lag(deptno)over(partition by deptno** **order by empno) prior_deptno** **from emp** **)** **model** **dimension by** **(** **deptno,** **row_number()over(partition by deptno order by empno) rn** **)** **measures** **(** **ename,** **prior_deptno,cast(null as varchar2(60)) list,** **count(*)over(partition by deptno) cnt,** **row_number()over(partition by deptno order by empno) rnk** **)** **rules** **(** **list[any,any]** **order by deptno,rn = case when prior_deptno[cv(),cv()] is null** **then ename[cv(),cv()]** **else ename[cv(),cv()]||','||** **list[cv(),rnk[cv(),cv()]-1]** **end** **)** **)** **where cnt = rn** DEPTNO LIST ------ ---------------------------------------- 10 MILLER,KING,CLARK 20 FORD,ADAMS,SCOTT,JONES,SMITH 30 JAMES,TURNER,BLAKE,MARTIN,WARD,ALLEN ## 14.14. Finding Text Not Matching a Pattern (Oracle) ### Problem You have a text field that contains some structured text values (e.g., phone numbers), and you wish to find occurrences where those values are structured incorrectly. For example, you have data like the following: **select emp_id, text** **from employee_comment** EMP_ID TEXT ---------- ------------------------------------------------------------ 7369 126 Varnum, Edmore MI 48829, 989 313-5351 7499 1105 McConnell Court Cedar Lake MI 48812 Home: 989-387-4321 Cell: (237) 438-3333 and you wish to list rows having invalidly formatted phone numbers. For example, you wish to list the following row because its phone number uses two different separator characters: 7369 126 Varnum, Edmore MI 48829, 989 313-5351 You wish to consider valid only those phone numbers that use the same character for both delimiters. ### Solution This problem has a multi-part solution: 1. Find a way to describe the universe of apparent phone numbers that you wish to consider. 2. Remove any validly formatted phone numbers from consideration. 3. See whether you still have any apparent phone numbers left. If you do, you know those are invalidly formatted. The following solution makes good use of the regular expression functionality introduced in Oracle Database 10 _g_ **select emp_id, text** **from employee_comment** **where regexp_like(text, '[0-9]{3}[-. ][0-9]{3}[-. ][0-9]{4}')** **and regexp_like(** **regexp_replace(text,** **'[0-9]{3}([-. ])[0-9]{3}\1[0-9]{4}','***'),** **'[0-9]{3}[-. ][0-9]{3}[-. ][0-9]{4}')** EMP_ID TEXT ---------- ------------------------------------------------------------ 7369 126 Varnum, Edmore MI 48829, 989 313-5351 7844 989-387.5359 9999 906-387-1698, 313-535.8886 Each of these rows contains at least one apparent phone number that is not correctly formatted. ### Discussion The key to this solution lies in the detection of an "apparent phone number." Given that the phone numbers are stored in a comment field, any text at all in the field could be construed to be an invalid phone number. You need a way to narrow the field to a more reasonable set of values to consider. You don't, for example, want to see the following row in your output: EMP_ID TEXT ---------- ---------------------------------------------------------- 7900 Cares for 100-year-old aunt during the day. Schedule only for evening and night shifts. Clearly there's no phone number at all in this row, much less one that is invalid. You and I can see that. The question is, how do you get the RDBMS to "see" it. I think you'll enjoy the answer. Please read on. ### Tip This recipe comes (with permission) from an article by Jonathan Gennick called "Regular Expression Anti-Patterns," which you can read at: <http://gennick.com/antiregex.htm>. The solution uses Pattern A to define the set of "apparent" phone numbers to consider: Pattern A: [0-9]{3}[-. ][0-9]{3}[-. ][0-9]{4} Pattern A checks for two groups of three digits followed by one group of four digits. Any one of a dash (-), a period (.), or a space are accepted as delimiters between groups. You could come up with a more complex pattern. For example, you could decide that you also wish to consider seven-digit phone numbers. But don't get side-tracked. The point now is that somehow you do need to define the universe of possible phone number strings to consider, and for this problem that universe is defined by Pattern A. You can define a different Pattern A, and the general solution still applies. The solution uses Pattern A in the WHERE clause to ensure that only rows having potential phone numbers (as defined by the pattern!) are considered: select emp_id, text from employee_comment where regexp_like(text, '[0-9]{3}[-. ][0-9]{3}[-. ][0-9]{4}') Next, you need to define what a "good" phone number looks like. The solution does this using Pattern B: Pattern B: [0-9]{3}([-. ])[0-9]{3}\1[0-9]{4} This time, the pattern uses \1 to reference the first subexpression. Whichever character is matched by ([-. ]) must also be matched by \1. Pattern B describes good phone numbers, which must be eliminated from consideration (as they are not bad). The solution eliminates the well-formatted phone numbers through a call to REGEXP_ REPLACE: regexp_replace(text, '[0-9]{3}([-. ])[0-9]{3}\1[0-9]{4}','***'), This call to REGEXP_REPLACE occurs in the WHERE clause. Any well-formatted phone numbers are replaced by a string of three asterisks. Again, Pattern B can be any pattern that you desire. The point is that Pattern B describes the acceptable pattern that you are after. Having replaced well-formatted phone numbers with strings of three asterisks (***), any "apparent" phone numbers that remain must, by definition, be poorly formatted. The solution applies REGEXP_LIKE to the output from REGEXP_LIKE to see whether any poorly formatted phone numbers remain: and regexp_like( regexp_replace(text, '[0-9]{3}([-. ])[0-9]{3}\1[0-9]{4}','***'), '[0-9]{3}[-. ][0-9]{3}[-. ][0-9]{4}') This recipe would be difficult to implement without the pattern matching capabilities inherent in Oracle's relatively new regular expression features. In particular, this recipe depends on REGEXP_REPLACE. Other databases (notably PostgreSQL) implement support for regular expressions. But to my knowledge, only Oracle supports the regular expression search and replace functionality on which this recipe depends. ## 14.15. Transforming Data with an Inline View ### Problem You have a table in a column that sometimes contains numeric data and sometimes character data. Another column in the same table indicates which is the case. You wish to use a subquery to isolate only the numeric data: select * from ( select flag, to_number(num) num from subtest where flag in ('A', 'C') ) where num > 0 Unfortunately, this query against an inline view often (but perhaps not always!) results in the following error message; ERROR: ORA-01722: invalid number ### Solution One solution is to force the inline view to completely execute prior to the outer SELECT statement. You can do that, in Oracle at least, by including the row number pseudo-column in your inner SELECT list: select * from ( select rownum, flag, to_number(num) num from subtest where flag in ('A', 'C') ) where num > 0 See "Discussion" for an explanation of why this solution works. ### Discussion The reason for the invalid number error in the problem query is that some optimizers will merge the inner and outer queries. While it looks like you are executing an inner query first to remove all non-numeric NUM values, you might really be executing: select flag, to_number(num) num from subtest where to_number(num) > 0 and flag in ('A', 'C'); And now you can probably clearly see the reason for the error: rows with non-numeric NUM values are _not_ filtered out before the TO_NUMBER function is applied. ### Tip _Should_ a database merge sub and main queries? The answer depends on whether you are thinking in terms of relational theory, in terms of the SQL standard, or in terms of how your particular database vendor chooses to implement his brand of SQL. You can learn more by visiting <http://gennick.com/madness.html>. The solution solves the problem, in Oracle at least, because it adds ROWNUM to the inner query's SELECT list. ROWNUM is a function that returns a sequentially increasing number for each row _returned by a query_. Those last words are important. The sequentially increasing number, termed a _row number_ , cannot be computed outside the context of returning a row from a query. Thus, Oracle is forced to materialize the result of the subquery, which means that Oracle is forced to execute the subquery first in order to return rows from that subquery in order to properly assign row numbers. Thus, querying for ROWNUM is one mechanism that you can use to force Oracle to fully execute a subquery prior to the main query (i.e., no merging of queries allowed). If you are not using Oracle, and you need to force the order of execution of a subquery, check to see whether your database supports something analogous to Oracle's ROWNUM function. ## 14.16. Testing for Existence of a Value Within a Group ### Problem You want to create a Boolean flag for a row depending on whether or not any row in its group contains a specific value. Consider an example of a student who has taken a certain number of exams during a period of time. A student will take three exams over three months. If a student passes one of these exams, the requirement is satisfied and a flag should be returned to express that fact. If a student did not pass any of the three tests in the three month period, then an additional flag should be returned to express that fact as well. Consider the following example (using Oracle syntax to make up rows for this example; minor modifications are necessary for DB2 and SQL Server, because both support window functions): create view V as select 1 student_id, 1 test_id, 2 grade_id, 1 period_id, to_date('02/01/2005','MM/DD/YYYY') test_date, 0 pass_fail from dual union all select 1, 2, 2, 1, to_date('03/01/2005','MM/DD/YYYY'), 1 from dual union all select 1, 3, 2, 1, to_date('04/01/2005','MM/DD/YYYY'), 0 from dual union all select 1, 4, 2, 2, to_date('05/01/2005','MM/DD/YYYY'), 0 from dual union all select 1, 5, 2, 2, to_date('06/01/2005','MM/DD/YYYY'), 0 from dual union all select 1, 6, 2, 2, to_date('07/01/2005','MM/DD/YYYY'), 0 from dual select * from V STUDENT_ID TEST_ID GRADE_ID PERIOD_ID TEST_DATE PASS_FAIL ---------- ------- -------- --------- ----------- --------- 1 1 2 1 01-FEB-2005 0 1 2 2 1 01-MAR-2005 1 1 3 2 1 01-APR-2005 0 1 4 2 2 01-MAY-2005 0 1 5 2 2 01-JUN-2005 0 1 6 2 2 01-JUL-2005 0 Examining the result set above, you see that the student has taken six tests over two, three-month periods. The student has passed one test (1 means "pass"; 0 means "fail"), thus the requirement is satisfied for the entire first period. Because the student did not pass any exams during the second period (the next three months), PASS_FAIL is 0 for all three exams. You want to return a result set that highlights whether or not a student has passed a test for a given period. Ultimately you want to return the following result set: STUDENT_ID TEST_ID GRADE_ID PERIOD_ID TEST_DATE METREQ IN_PROGRESS ---------- ------- -------- --------- ----------- ------ ----------- 1 1 2 1 01-FEB-2005 + 0 1 2 2 1 01-MAR-2005 + 0 1 3 2 1 01-APR-2005 + 0 1 4 2 2 01-MAY-2005 - 0 1 5 2 2 01-JUN-2005 - 0 1 6 2 2 01-JUL-2005 - 1 The values for METREQ ("met requirement") are + and -, signifying the student either has or has not satisfied the requirement of passing at least one test in a period (three-month span), respectively. The value for IN_PROGRESS should be 0 if a student has already passed a test in a given period. If a student has not passed a test for a given period, then the row that has the latest exam date for that student will have a value of 1 for IN_PROGRESS. ### Solution What makes this problem a bit tricky is the fact that you have to treat rows in a group as a group and not as individuals. Consider the values for PASS_FAIL in the problem section. If you evaluate row by row, it would seem that the value for METREQ for each row except TEST_ID 2 should be "-", when in fact that is not the case. You must ensure you evaluate the rows as a group. By using the window function MAX OVER you can easily determine whether or not a student passed at least one test during a particular period. Once you have that information, the "Boolean" values are a simple matter of using CASE expressions: 1 select student_id, 2 test_id, 3 grade_id, 4 period_id, 5 test_date, 6 decode( grp_p_f,1,lpad('+',6),lpad('-',6) ) metreq, 7 decode( grp_p_f,1,0, 8 decode( test_date,last_test,1,0 ) ) in_progress 9 from ( 10 select V.*, 11 max(pass_fail)over(partition by 12 student_id,grade_id,period_id) grp_p_f, 13 max(test_date)over(partition by 14 student_id,grade_id,period_id) last_test 15 from V 16 ) x ### Discussion The key to the solution is using the window function MAX OVER to return the greatest value of PASS_FAIL for each group. Because the values for PASS_FAIL are only 1 or 0, if a student passed at least one exam, then MAX OVER would return 1 for the entire group. How this works is shown below: select V.*, max(pass_fail)over(partition by student_id,grade_id,period_id) grp_pass_fail from V STUDENT_ID TEST_ID GRADE_ID PERIOD_ID TEST_DATE PASS_FAIL GRP_PASS_FAIL ---------- ------- -------- --------- ----------- --------- ------------- 1 1 2 1 01-FEB-2005 0 1 1 2 2 1 01-MAR-2005 1 1 1 3 2 1 01-APR-2005 0 1 1 4 2 2 01-MAY-2005 0 0 1 5 2 2 01-JUN-2005 0 0 1 6 2 2 01-JUL-2005 0 0 The result set above shows that the student passed at least one test during the first period, thus the entire group has a value of 1 or "pass." The next requirement is that if the student has not passed any tests in a period, return a value of 1 for he IN_ PROGRESS flag for the latest test date in that group. You can use the window function MAX OVER to do this as well: select V.*, max(pass_fail)over(partition by student_id,grade_id,period_id) grp_p_f, max(test_date)over(partition by student_id,grade_id,period_id) last_test from V STUDENT_ID TEST_ID GRADE_ID PERIOD_ID TEST_DATE PASS_FAIL GRP_P_F LAST_TEST ---------- ------- -------- --------- ----------- --------- ------- ----------- 1 1 2 1 01-FEB-2005 0 1 01-APR-2005 1 2 2 1 01-MAR-2005 1 1 01-APR-2005 1 3 2 1 01-APR-2005 0 1 01-APR-2005 1 4 2 2 01-MAY-2005 0 0 01-JUL-2005 1 5 2 2 01-JUN-2005 0 0 01-JUL-2005 1 6 2 2 01-JUL-2005 0 0 01-JUL-2005 Now that you have determined for which period the student has passed a test and what the latest test date for each period is, the last step is simply a matter of applying some formatting magic to make the result set look nice. The final solution uses Oracle's DECODE function (CASE supporters eat your hearts out) to create the METREQ and IN_PROGRESS columns. Use the LPAD function to right justify the values for METREQ: select student_id, test_id, grade_id, period_id, test_date, decode( grp_p_f,1,lpad('+',6),lpad('-',6) ) metreq, decode( grp_p_f,1,0, decode( test_date,last_test,1,0 ) ) in_progress from ( select V.*, max(pass_fail)over(partition by student_id,grade_id,period_id) grp_p_f, max(test_date)over(partition by student_id,grade_id,period_id) last_test from V ) x STUDENT_ID TEST_ID GRADE_ID PERIOD_ID TEST_DATE METREQ IN_PROGRESS ---------- ------- -------- --------- ----------- ------ ----------- 1 1 2 1 01-FEB-2005 + 0 1 2 2 1 01-MAR-2005 + 0 1 3 2 1 01-APR-2005 + 0 1 4 2 2 01-MAY-2005 - 0 1 5 2 2 01-JUN-2005 - 0 1 6 2 2 01-JUL-2005 - 1 ## Appendix A. Window Function Refresher The recipes in this book take full advantage of the window functions added to the ISO SQL standard in 2003, as well as vendor-specific window functions. This appendix is meant to serve as a brief overview of how window functions work. Window functions make many typically difficult tasks (difficult to solve using standard SQL, that is) quite easy. For a complete list of window functions available, full syntax, and in-depth coverage of how they work, please consult your vendor's documentation. ## A.1. Grouping Before moving on to window functions, it is crucial that you understand how grouping works in SQL. In my experience, the concept of grouping results in SQL has been a stumbling block for many. The problems stem from not fully understanding how the GROUP BY clause works and why certain queries return certain results when using GROUP BY. Simply stated, grouping is a way to organize like rows together. When you use GROUP BY in a query, each row in the result set is a group and represents one or more rows with the same values in one or more columns that you specify. That's the gist of it. If a group is simply a unique instance of a row that represents one or more rows with the same value for a particular column (or columns), then practical examples of groups from table EMP include _all employees in department 10_ (the common value for these employees that enable them to be in the same group is DEPTNO=10) or _all clerks_ (the common value for these employees that enable them to be in the same group is JOB='CLERK'). Consider the following queries. The first shows all employees in department 10; the second query groups the employees in department 10 and returns the following information about the group: the number of rows (members) in the group, the highest salary, and the lowest salary: **select deptno,ename** **from emp** **where deptno=10** DEPTNO ENAME ------ ---------- 10 CLARK 10 KING 10 MILLER **select deptno,** **count(*) as cnt,** **max(sal) as hi_sal,** **min(sal) as lo_sal** **from emp** **where deptno=10** **group by deptno** DEPTNO CNT HI_SAL LO_SAL ------ ---------- ---------- ---------- 10 3 5000 1300 If you were not able to group the employees in department 10 together, to get the information in the second query above you would have to manually inspect the rows for that department (trivial if there are only three rows, but what if there were three million rows?). So, why would anyone want to group? Reasons for doing so vary; perhaps you want to see how many different groups exist or how many members (rows) are in each group. As you can see from the simple example above, grouping allows you to get information about many rows in a table without having to inspect them one by one. ### Definition of an SQL Group In mathematics, a group is defined, for the most part, as ( _G_ , •, _e_ ), where _G_ is a set, • is a binary operation in _G_ , and _e_ is a member of _G_. We will use this definition as the foundation for what a SQL group is. A SQL group will be defined as ( _G_ , _e_ ), where _G_ is a result set of a single or self-contained query that uses GROUP BY, _e_ is a member of _G_ , and the following axioms are satisfied: * For each _e_ in _G_ , _e_ is distinct and represents one or more instances of _e_. * For each _e_ in G, the aggregate function COUNT returns a value > 0. ### Tip The result set is included in the definition of a SQL group to reinforce the fact that we are defining what groups are when working with queries only. Thus, it would be accurate to replace "e" in each axiom with the word "row" because the rows in the result set are technically the groups. Because these properties are fundamental to what we consider a group, it is important that we prove they are true (and we will proceed to do so through the use of some example SQL queries). #### Groups are non-empty By its very definition, a group must have at least one member (or row). If we accept this as a truth, then it can be said that a group cannot be created from an empty table. To prove that proposition true, simply try to prove it is false. The following example creates an empty table, and then attempts to create groups via three different queries against that empty table: **create table fruits (name varchar(10))** **select name** **from fruits** **group by name** (no rows selected) **select count(*) as cnt** **from fruits** **group by name** (no rows selected) **select name, count(*) as cnt** **from fruits** **group by name** (no rows selected) As you can see from these queries, it is impossible to create what SQL considers a group from an empty table. #### Groups are distinct Now let's prove that the groups created via queries with a GROUP BY clause are distinct. The following example inserts five rows into table FRUITS, and then creates groups from those rows: **insert into fruits values ('Oranges')** **insert into fruits values ('Oranges')** **insert into fruits values ('Oranges')** **insert into fruits values ('Apple')** **insert into fruits values ('Peach')** **select *** **from fruits** NAME -------- Oranges Oranges Oranges Apple Peach **select name** **from fruits** **group by name** NAME ------- Apple Oranges Peach **select name, count(*) as cnt** **from fruits** **group by name** NAME CNT ------- -------- Apple 1 Oranges 3 Peach 1 The first query shows that "Oranges" occurs three times in table FRUITS. However, the second and third queries (using GROUP BY) return only one instance of "Oranges." Taken together, these queries prove that the rows in the result set (e in G, from our definition) are distinct, and each value of NAME represents one or more instances of itself in table FRUITS. Knowing that groups are distinct is important because it means, typically, you would not use the DISTINCT keyword in your SELECT list when using a GROUP BY in your queries. ### Tip I am in no way suggesting GROUP BY and DISTINCT are the same. They represent two completely different concepts. I am merely stating that the items listed in the GROUP BY clause will be distinct in the result set and that using DISTINCT as well as GROUP BY is redundant. Frege's Axiom and Russell's Paradox For those of you who are interested, Frege's _axiom of abstraction_, based on Cantor's solution for defining set membership for infinite or uncountable sets, states that, given a specific identifying property, there exists a set whose members are only those items having that property. The source of trouble, as put by Robert Stoll, "is the unrestrictd use of the principal of abstraction." Bertrand Russell asked Gottlob Frege to consider a set whose members are sets and have the defining property of not being members of themselves. As Russell pointed out, the axiom of abstraction gives too much freedom because you are simply specifiying a condition or property to define set membership, thus a contradiction can be found. To better explain how a contradiction can be found, he devised the "Barber Puzzle." The Barber Puzzle states: > In a certain town there is a male barber who shaves all those men, and only those men, who do not shave themselves. If this is true, who, then, shaves the barber? For a more concrete example, consider the set that can be described as: > _For all members x in y that satisfy a specific condition (P)_ The mathematical notation for this description is: {x e y | P(x)} Because the above set considers _only those x in y that satisfy a condition (P)_ you may find it more intuitive to describe the set as _x is a member of y if and only if x satisfies a condition (P)_. At this point let us define this condition _P(x)_ as _x is not a member of x_ : ( x e x ) The set is now defined as _x is a member of y if and only if x is not a member of x_ : {x e y | ( x e x )} Russell's paradox may not be clear to you yet, but ask yourself this: can the set above be a member of itself? Let's assume that _x_ = _y_ and look at the above set again. The following set can be defined as _y is a member of y if and only if y is not a member of y_ : {y e y | ( y e y )} Simply put, Russell's paradox leaves us in a position to have a set that is concurrently a member of itself and not a member of itself, which is a contradiction. Intuitive thinking would lead one to believe this isn't a problem at all; indeed, how can a set be a member of itself? The set of all books, after all, is not a book. So why does this paradox exist and how can it be an issue? It becomes an issue when you consider more abstract applications of set theory. For example, a "practical" application of Russell's paradox can be demonstrated by considering the set of all sets. If we allow such a concept to exist, then by its very definition, it must be a member of itself (it is, after all, the set of all sets). What then happens when you apply _P(x)_ above to the set of all sets? Simply stated, Russell's paradox would state that the set of all sets is a member of itself if and only if it is not a member of itself—clearly a contradiction. For those of you who are interested, Ernst Zermelo developed the axiom schema of separation (also referred to as the axiom schema of subsets or the axiom of specification) to elegantly sidestep Russell's paradox in axiomatic set theory. #### COUNT is never zero The queries and results in the preceding section also prove the final axiom that the aggregate function COUNT will never return zero when used in a query with GROUP BY on a nonempty table. It should not be surprising that you cannot return a count of zero for a group. We have already proved that a group cannot be created from an empty table, thus a group must have at least one row. If at least one row exists, then the count will always be at least 1. ### Tip Remember, we are talking about using COUNT with GROUP BY, not COUNT by itself. A query using COUNT without a GROUP BY on an empty table will of course return zero. ### Paradoxes > "Hardly anything more unfortunate can befall a scientific writer than to have one of the foundations of his edifice shaken after the work is finished.... This was the position I was placed in by a letter of Mr. Bertrand Russell, just when the printing of this volume was nearing its completion." The preceding quote is from Gottlob Frege in response to Bertrand Russell's discovery of a contradiction to Frege's axiom of abstraction in set theory. Paradoxes many times provide scenarios that would seem to contradict established theories or ideas. In many cases these contradictions are localized and can be "worked around," or they are applicable to such small test cases that they can be safely ignored. You may have guessed by now that the point to all this discussion of paradoxes is that there exists a paradox concerning our definition of an SQL group, and that paradox must be addressed. Although our focus right now is on groups, ultimately we are discussing SQL queries. In its GROUP BY clause, a query may have a wide range of values such as constants, expressions, or, most commonly, columns from a table. We pay a price for this flexibility, because NULL is a valid "value" in SQL. NULLs present problems because they are effectively ignored by aggregate functions. With that said, if a table consists of a single row and its value is NULL, what would the aggregate function COUNT return when used in a GROUP BY query? By our very definition, when using GROUP BY and the aggregate function COUNT, a value >= 1 must be returned. What happens, then, in the case of values ignored by functions such as COUNT, and what does this mean to our definition of a GROUP? Consider the following example, which reveals the NULL group paradox (using the function COALESCE when necessary for readability): **select *** **from fruits** NAME ------- Oranges Oranges Oranges Apple Peach **insert into fruits values (null)** **insert into fruits values (null)** **insert into fruits values (null)** **insert into fruits values (null)** **insert into fruits values (null)** **select coalesce(name,'NULL') as name** **from fruits** NAME -------- Oranges Oranges Oranges Apple Peach NULL NULL NULL NULL NULL **select coalesce(name,'NULL') as name,** **count(name) as cnt** **from fruits** **group by name** NAME CNT -------- ---------- Apple 1 NULL 0 Oranges 3 Peach 1 It would seem that the presence of NULL values in our table introduces a contradiction, or paradox, to our definition of a SQL group. Fortunately, this contradiction is not a real cause for concern, because the paradox has more to do with the implementation of aggregate functions than our definition. Consider the final query in the preceding set; a general problem statement for that query would be: > _Count the number of times each name occurs in table FRUITS or count the number of members in each group_. Examining the INSERT statements above, it's clear that there are five rows with NULL values, which means there exists a NULL group with five members. ### Tip While NULL certainly has properties that differentiate it from other values, it is nevertheless a value, and can in fact be a group. How, then, can we write the query to return a count of 5 instead of 0, thus returning the information we are looking for while conforming to our definition of a group? The example below shows a workaround to deal with the NULL group paradox: **select coalesce(name,'NULL') as name,** **count(*) as cnt** **from fruits** **group by name** NAME CNT --------- -------- Apple 1 Oranges 3 Peach 1 NULL 5 The workaround is to use COUNT(*) rather than COUNT(NAME) to avoid the NULL group paradox. Aggregate functions will ignore NULL values if any exist in the column passed to them. Thus, to avoid a zero when using COUNT do not pass the column name; instead, pass in an asterisk (*). The * causes the COUNT function to count rows rather than the actual column values, so whether or not the actual values are NULL or not NULL is irrelevant. One more paradox has to do with the axiom that each group in a result set (for each _e_ in _G_ ) is distinct. Because of the nature of SQL result sets and tables, which are more accurately defined as multisets or "bags," not sets (because duplicate rows are allowed), it is possible to return a result set with duplicate groups. Consider the following queries: **select coalesce(name,'** **NULL') as name,** **count(*) as cnt** **from fruits** **group by name** ******union all** **select coalesce(name,'NULL') as name,** **count(*) as cnt** **from fruits** **group by name** NAME CNT ---------- --------- Apple 1 Oranges 3 Peach 1 NULL 5 Apple 1 Oranges 3 Peach 1 NULL 5 **select x.*** **from (** **select coalesce(name,'NULL') as name,** **count(*) as cnt** **from fruits** **group by name** **) x,** **(select deptno from dept) y** NAME CNT ---------- ---------- Apple 1 Apple 1 Apple 1 Apple 1 Oranges 3 Oranges 3 Oranges 3 Oranges 3 Peach 1 Peach 1 Peach 1 Peach 1 NULL 5 NULL 5 NULL 5 NULL 5 As you can see in these queries, the groups are in fact repeated in the final results. Fortunately, this is not much to worry about because it represents only a partial paradox. The first property of a group states that for ( _G_ , _e_ ), _G_ is a result set from a single or self-contained query that uses GROUP BY. Simply put, the result set from any GROUP BY query itself conforms to our definition of a group. It is only when you combine the result sets from two GROUP BY queries to create a multiset that groups may repeat. The first query in the preceding example uses UNION ALL, which is not a set operation but a multiset operation, and invokes GROUP BY twice, effectively executing two queries. ### Tip If you use UNION, which is a set operation, you will not see repeating groups. The second query in the preceding set uses a Cartesian product, which only works if you materialize the group first and then perform the Cartesian. Thus the GROUP BY query when self-contained conforms to our definition. Neither of the two examples takes anything away from the definition of a SQL group. They are shown for completeness, and so that you can be aware that almost anything is possible in SQL. ### Relationship Between SELECT and GROUP BY With the concept of a group defined and proved, it is now time to move on to more practical matters concerning queries using GROUP BY. It is important to understand the relationship between the SELECT clause and the GROUP BY clause when grouping in SQL. It is important to keep in mind when using aggregate functions such as COUNT that any item in your SELECT list that is not used as an argument to an aggregate function must be part of your group. For example, if you write a SELECT clause such as: select deptno, count(*) as cnt from emp then you must list DEPTNO in your GROUP BY clause: **select deptno, count(*) as cnt** **from emp** **group by deptno** DEPTNO CNT ------- ---- 10 3 20 5 30 6 Constants, scalar values returned by user-defined functions, window functions, and non-correlated scalar subqueries are exceptions to this rule. Since the SELECT clause is evaluated after the GROUP BY clause, these constructs are allowed in the SELECT list and do not have to (and in some cases cannot) be specified in the GROUP BY clause. For example: **select 'hello' as msg,** **1 as num,** **deptno,** **(** **select count(*) from emp) as total,** **count(*) as cnt** **from emp** **group by deptno** MSG NUM DEPTNO TOTAL CNT ----- --- ------ ----- --- hello 1 10 14 3 hello 1 20 14 5 hello 1 30 14 6 Don't let this query confuse you. The items in the SELECT list not listed in the GROUP BY clause do not change the value of CNT for each DEPTNO, nor do the values for DEPTNO change. Based on the results of the preceding query, we can define the rule about matching items in the SELECT list and the GROUP BY clause when using aggregates a bit more precisely: > Items in a SELECT list that can potentially change the group or change the value returned by an aggregate function must be included in the GROUP BY clause. The additional items in the preceding SELECT list did not change the value of CNT for any group (each DEPTNO), nor did they change the groups themselves. Now it's fair to ask: exactly what items in a SELECT list can change a grouping or the value returned by an aggregate function? The answer is simple: other columns from the table(s) you are selecting from. Consider the prospect of adding the JOB column to the query we've been looking at: **select deptno, job, count(*) as cnt** **from emp** **group by deptno, job** DEPTNO JOB CNT ------ ---------- ---- 10 CLERK 1 10 MANAGER 1 10 PRESIDENT 1 20 CLERK 2 20 ANALYST 2 20 MANAGER 1 30 CLERK 1 30 MANAGER 1 30 SALESMAN 4 By listing another column, JOB, from table EMP, we are changing the group and changing the result set; thus we must now include JOB in the GROUP BY clause along with DEPTNO, otherwise the query will fail. The inclusion of JOB in the SELECT/GROUP BY clauses changes the query from "How many employees are in each department?" to "How many different types of employees are in each department?" Notice again that the groups are distinct; the values for DEPTNO and JOB _individually_ are not distinct, but the combination of the two (which is what is in the GROUP BY and SELECT list, and thus is the group) are distinct (e.g., 10 and CLERK appear only once). If you choose not to put items other than aggregate functions in the SELECT list, then you may list any valid column you wish, in the GROUP BY clause. Consider the following two queries, which highlight this fact: **select count(*)** **from emp** **group by deptno** COUNT(*) --------- 3 5 6 **select count(*)** **from emp** **group by deptno,job** COUNT(*) ---------- 1 1 1 2 2 1 1 1 4 Including items other than aggregate functions in the SELECT list is not mandatory, but often improves readability and usability of the results. ### Tip As a rule, when using GROUP BY and aggregate functions, any items in the SELECT list [from the table(s) in the FROM clause] not used as an argument to an aggregate function must be included in the GROUP BY clause. However, MySQL has a "feature" that allows you to deviate from this rule, allowing you to place items in your SELECT list [that are columns in the table(s) you are selecting from] that are not used as arguments to an aggregate function and that are not present in your GROUP BY clause. I use the term "feature" very loosely here as its use is a bug waiting to happen and I urge you to avoid it. As a matter of fact, if you use MySQL and care at all about the accuracy of your queries I suggest you urge them to remove this, ahem, "feature." ## A.2. Windowing Once you understand the concept of grouping and using aggregates in SQL, understanding _window functions_ is easy. Window functions, like aggregate functions, perform an aggregation on a defined set (a group) of rows, but rather than returning one value per group, window functions can return multiple values for each group. The group of rows to perform the aggregation on is the _window_ (hence the name "window functions"). DB2 actually calls such functions _online analytic processing (OLAP) functions_ , and Oracle calls them _analytic functions_ , but the ISO SQL standard calls them window functions, so that's the term I use in this book. ### A Simple Example Let's say that you wish to count the total number of employees across all departments. The traditional method for doing that is to issue a COUNT(*) query against the entire EMP table: **select count(*) as cnt** **from emp** CNT ----- 14 This is easy enough, but often you will find yourself wanting to access such aggregate data from rows that do not represent an aggregation, or that represent a different aggregation. Window functions make light work of such problems. For example, the following query shows how you can use a window function to access aggregate data (the total count of employees) from detail rows (one per employee): **select ename,** **deptno,** **count(*) over() as cnt** **from emp** **order by 2** ENAME DEPTNO CNT ---------- ------ ------ CLARK 10 14 KING 10 14 MILLER 10 14 SMITH 20 14 ADAMS 20 14 FORD 20 14 SCOTT 20 14 JONES 20 14 ALLEN 30 14 BLAKE 30 14 MARTIN 30 14 JAMES 30 14 TURNER 30 14 WARD 30 14 The window function invocation in this example is COUNT(*) OVER(). The presence of the OVER keyword indicates that the invocation of COUNT will be treated as a window function, not as an aggregate function. In general, the SQL standard allows for all aggregate functions to also be window functions, and the keyword OVER is how the language distinguishes between the two uses. So, what did the window function COUNT(*) OVER () do exactly? For every row being returned in the query, it returned the count of _all the rows_ in the table. As the empty parentheses suggest, the OVER keyword accepts additional clauses to affect the range of rows that a given window function considers. Absent any such clauses, the window function looks at all rows in the result set, which is why you see the value 14 repeated in each row of output. Hopefully you begin to see the great utility of window functions, which is that they allow you to work with multiple levels of aggregation in one row. As you continue through this appendix, you'll begin to see even more just how incredibly useful that ability can be. ### Order of Evaluation Before digging deeper into the OVER clause, it is important to note that window functions are performed as the last step in SQL processing prior to the ORDER BY clause. As an example of how window functions are processed last, let's take the query from the preceding section and use a WHERE clause to filter out employees from DEPTNO 20 and 30: **select ename,** **deptno,** **count(*) over() as cnt** **from emp** **where deptno = 10** **order by 2** ENAME DEPTNO CNT ---------- ------ ------ CLARK 10 3 KING 10 3 MILLER 10 3 The value for CNT for each row is no longer 14, it is now 3. In this example, it is the WHERE clause that restricts the result set to three rows, hence the window function will count only three rows (there are only three rows available to the window function by the time processing reaches the SELECT portion of the query). From this example you can see that window functions perform their computations after clauses such as WHERE and GROUP BY are evaluated. ### Partitions Use the PARTITION BY clause to define a _partition_ or group of rows to perform an aggregation over. As we've seen already, if you use empty parentheses then the entire result set is the partition that a window function aggregation will be computed over. You can think of the PARTITION BY clause as a "moving GROUP BY" because unlike a traditional GROUP BY, a group created by PARTITION BY is not distinct in a result set. You can use PARTITION BY to compute an aggregation over a defined group of rows (resetting when a new group is encountered) and rather than having one group represent all instances of that value in the table, each value (each member in each group) is returned. Consider the following query: **select ename,** **deptno,** **count(*) over(** **partition by deptno) as cnt** **from emp** **order by 2** ENAME DEPTNO CNT ---------- ------ ------ CLARK 10 3 KING 10 3 MILLER 10 3 SMITH 20 5 ADAMS 20 5 FORD 20 5 SCOTT 20 5 JONES 20 5 ALLEN 30 6 BLAKE 30 6 MARTIN 30 6 JAMES 30 6 TURNER 30 6 WARD 30 6 This query still returns 14 rows, but now the COUNT is performed for each department as a result of the PARTITION BY DEPTNO clause. Each employee in the same department (in the same partition) will have the same value for CNT, because the aggregation will not reset (recompute) until a new department is encountered. Also note that you are returning information about each group, along with the members of each group. You can think of the preceding query as a more efficient version of the following: **select e.ename,** **e.deptno,** **(select count(*) from emp d** **where e.deptno=d.deptno) as cnt** **from emp e** **order by 2** ENAME DEPTNO CNT ---------- ------ ------ CLARK 10 3 KING 10 3 MILLER 10 3 SMITH 20 5 ADAMS 20 5 FORD 20 5 SCOTT 20 5 JONES 20 5 ALLEN 30 6 BLAKE 30 6 MARTIN 30 6 JAMES 30 6 TURNER 30 6 WARD 30 6 Additionally, what's nice about the PARTITION BY clause is that it performs its computations independently of other window functions, partitioning by different columns in the same SELECT statement. Consider the following query, which returns each employee, her department, the number of employees in her respective department, her job, and the number of employees with the same job: **select ename,** **deptno,** **count(*) over(partition by deptno) as dept_cnt,** **job,** **count(*) over(partition by job) as job_cnt** **from emp** **order by 2** ENAME DEPTNO DEPT_CNT JOB JOB_CNT ---------- ------ -------- --------- ------- MILLER 10 3 CLERK 4 CLARK 10 3 MANAGER 3 KING 10 3 PRESIDENT 1 SCOTT 20 5 ANALYST 2 FORD 20 5 ANALYST 2 SMITH 20 5 CLERK 4 JONES 20 5 MANAGER 3 ADAMS 20 5 CLERK 4 JAMES 30 6 CLERK 4 MARTIN 30 6 SALESMAN 4 TURNER 30 6 SALESMAN 4 WARD 30 6 SALESMAN 4 ALLEN 30 6 SALESMAN 4 BLAKE 30 6 MANAGER 3 In this result set, you can see that employees in the same department have the same value for DEPT_CNT, and that employees who have the same job position have the same value for JOB_CNT. By now it should be clear that the PARTITION BY clause works like a GROUP BY clause, but it does so without being affected by the other items in the SELECT clause and without requiring you to write a GROUP BY clause. ### Effect of NULLs Like the GROUP BY clause, the PARTITION BY clause lumps all the NULLs into one group or partition. Thus, the effect from NULLs when using PARTITION BY is similar to that from using GROUP BY. The following query uses a window function to count the number of employees with each distinct commission (returning–1 in place of NULL for readability): **select coalesce(comm,-1) as comm,** ******count(*)over(** **partition by comm) as cnt** **from emp** COMM CNT ------ ---------- 0 1 300 1 500 1 1400 1 -1 10 -1 10 -1 10 -1 10 -1 10 -1 10 -1 10 -1 10 -1 10 -1 10 Because COUNT(*) is used, the function counts rows. You can see that there are 10 employees having NULL commissions. Use COMM instead of *, however, and you get quite different results: **select coalesce(comm,-1) as comm,** **count(comm)over(partition by comm) as cnt** **from emp** COMM CNT ---- ---------- 0 1 300 1 500 1 1400 1 -1 0 -1 0 -1 0 -1 0 -1 0 -1 0 -1 0 -1 0 -1 0 -1 0 This query uses COUNT(COMM), which means that only the non-NULL values in the COMM column are counted. There is one employee with a commission of 0, one employee with a commission of 300, and so forth. But notice the counts for those with NULL commissions! Those counts are 0. Why? Because aggregate functions ignore NULL values, or more accurately, aggregate functions count only non-NULL values. ### Tip When using COUNT, consider whether you wish to include NULLs. Use COUNT(column) to avoid counting NULLs. Use COUNT(*) if you do wish to include NULLs (since you are no longer counting actual column values, you are counting rows). ### When Order Matters Sometimes the order in which rows are treated by a window function is material to the results that you wish to obtain from a query. For this reason, window function syntax includes an ORDER BY subclause that you can place within an OVER clause. Use the ORDER BY clause to specify how the rows are ordered with a partition (remember, "partition" in the absence of a PARTITION BY clause means the entire result set). ### Warning Some window functions _require_ you to impose order on the partitions of rows being affected. Thus, for some window functions an ORDER BY clause is mandatory. At the time of this writing, SQL Server does not allow ORDER BY in the OVER clause when used with aggregate window functions. SQL Server does permit ORDER BY in the OVER clause when used with window ranking functions. When you use an ORDER BY clause in the OVER clause of a window function you are specifying two things: 1. How the rows in the partition are ordered 2. What rows are included in the computation Consider the following query, which sums and computes a running total of salaries for employees in DEPTNO 10: **select deptno,** **ename,** **hiredate,** **sal,** **sum(sal)over(partition by deptno) as total1,** **sum(sal)over() as total2,** **sum(sal)over(order by hiredate) as running_total** **from emp** **where deptno=10** DEPTNO ENAME HIREDATE SAL TOTAL1 TOTAL2 RUNNING_TOTAL ------ ------ ----------- ----- ------ ------ ------------- 10 CLARK 09-JUN-1981 2450 8750 8750 2450 10 KING 17-NOV-1981 5000 8750 8750 7450 10 MILLER 23-JAN-1982 1300 8750 8750 8750 ### Warning Just to keep you on your toes, I've included a sum with empty parentheses. Notice how TOTAL1 and TOTAL2 have the same values. Why? Once again, the order in which window functions are evaluated answers the question. The WHERE clause filters the result set such that only salaries from DEPTNO 10 are considered for summation. In this case there is only one partition—the entire result set, which consists of only salaries from DEPTNO 10. Thus TOTAL1 and TOTAL2 are the same. Looking at the values returned by column SAL, you can easily see where the values for RUNNING_TOTAL come from. You can eyeball the values and add them yourself to compute the running total. But more importantly, why did including an ORDER BY in the OVER clause create a running total in the first place? The reason is, when you use ORDER BY in the OVER clause you are specify a default "moving" or "sliding" window within the partition even though you don't see it. The ORDER BY HIREDATE clause terminates summation at the HIREDATE in the current row. The following query is the same as the previous one, but uses the RANGE BETWEEN clause (which you'll learn more about later) to explicitly specify the default behavior that results from ORDER BY HIREDATE: **select deptno,** **ename,** **hiredate,** **sal,** **sum(sal)over(partition by deptno) as total1,** **sum(sal)over() as total2,** **sum(sal)over(order by hiredate** **range between unbounded preceding** **and current row) as running_total** **from emp** **where deptno=10** DEPTNO ENAME HIREDATE SAL TOTAL1 TOTAL2 RUNNING_TOTAL ------ ------ ----------- ----- ------ ------ ------------- 10 CLARK 09-JUN-1981 2450 8750 8750 2450 10 KING 17-NOV-1981 5000 8750 8750 7450 10 MILLER 23-JAN-1982 1300 8750 8750 8750 The RANGE BETWEEN clause that you see in this query is termed the _framing clause_ by ANSI and I'll use that term here. Now, it should be easy to see why specifying an ORDER BY in the OVER clause created a running total; we've (by default) told the query to sum all rows starting from the current row and include all prior rows ("prior" as defined in the ORDER BY, in this case ordering the rows by HIREDATE). ### The Framing Clause Let's apply the framing clause from the preceding query to the result set, starting with the first employee hired, who is named CLARK. 1. Starting with CLARK's salary, 2450, and including all employees hired before CLARK, compute a sum. Since CLARK was the first employee hired in DEPTNO 10, the sum is simply CLARK's salary, 2450, which is the first value returned by RUNNING_TOTAL. 2. Let's move to the next employee based on HIREDATE, named KING, and apply the framing clause once again. Compute a sum on SAL starting with the current row, 5000 (KING's salary), and include all prior rows (all employees hired before KING). CLARK is the only one hired before KING so the sum is 5000 + 2450, which is 7450, the second value returned by RUNNING_TOTAL. 3. Moving on to MILLER, the last employee in the partition based on HIREDATE, let's one more time apply the framing clause. Compute a sum on SAL starting with the current row, 1300 (MILLER's salary), and include all prior rows (all employees hired before MILLER). CLARK and KING were both hired before MILLER, and thus their salaries are included in MILLER's RUNNING_TOTAL: 2450 + 5000 \+ 1300 is 8750, which is the value for RUNNING_TOTAL for MILLER. As you can see, it is really the framing clause that produces the running total. The ORDER BY defines the order of evaluation and happens to also imply a default framing. In general, the framing clause allows you to define different "sub-windows" of data to include in your computations. There are many ways to specify such sub-windows. Consider the following query: **select deptno,** **ename,** **sal,** **sum(sal)over(order by hiredate** ******range between unbounded preceding** **and current row) as run_total1,** **sum(sal)over(order by hiredate** **rows between 1 preceding** **and current row) as run_total2,** **sum(sal)over(order by hiredate** **range between current row** **and unbounded following) as run_total3,** **sum(sal)over(order by hiredate** **rows between current row** **and 1 following) as run_total4** **from emp** **where deptno=10** DEPTNO ENAME SAL RUN_TOTAL1 RUN_TOTAL2 RUN_TOTAL3 RUN_TOTAL4 ------ ------ ----- ---------- ---------- ---------- ---------- 10 CLARK 2450 2450 2450 8750 7450 10 KING 5000 7450 7450 6300 6300 10 MILLER 1300 8750 6300 1300 1300 Don't be intimidated here; this query is not as bad as it looks. You've already seen RUN_TOTAL1 and the effects of the framing clause "UNBOUNDED PRECEDING AND CURRENT ROW". Here's a quick description of what's happening in the other examples: RUN_TOTAL2 Rather than the keyword RANGE, this framing clause specifies ROWS, which means the _frame_ , or window, is going to be constructed by counting some number of rows. The 1 PRECEDING means that the frame will begin with the row immediately preceding the current row. The range continues through the CUR-RENT ROW. So what you get in RUN_TOTAL2 is the sum of the current employee's salary and that of the preceding employee, based on HIREDATE. ### Tip It so happens that RUN_TOTAL1 and RUN_TOTAL2 are the same for both CLARK and KING. Why? Think about which values are being summed for each of those employees, for each of the two window functions. Think carefully, and you'll get the answer. RUN_TOTAL3 The window function for RUN_TOTAL3 works just the opposite of that for RUN_TOTAL1; rather than starting with the current row and including all prior rows in the summation, summation begins with the current row and includes all subsequent rows in the summation. RUN_TOTAL4 Is inverse of RUN_TOTAL2; rather than starting from the current row and including one prior row in the summation, start with the current row and include one subsequent row in the summation. ### Tip If you can understand what's been explained thus far, you will have no problem with any of the recipes in this book. If you're not catching on, though, try practicing with your own examples and your own data. I personally find learning easier by actually coding new features rather than just reading about them. ### A Framing Finale As a final example of the effect of the framing clause on query output, consider the following query: **select ename,** **sal,** **min(sal)over(order by sal) min1,** **max(sal)over(order by sal) max1,** **min(sal)over(order by sal** ******range between unbounded preceding** **and unbounded following) min2,** **max(sal)over(order by sal** **range between unbounded preceding** **and unbounded following) max2,** **min(sal)over(order by sal** **range between current row** **and current row) min3,** **max(sal)over(order by sal** **range between current row** **and current row) max3,** **max(sal)over(order by sal** **rows between 3 preceding** **and 3 following) max4** **from emp** ENAME SAL MIN1 MAX1 MIN2 MAX2 MIN3 MAX3 MAX4 ------ ----- ------ ------ ------ ------ ------ ------ ------ SMITH 800 800 800 800 5000 800 800 1250 JAMES 950 800 950 800 5000 950 950 1250 ADAMS 1100 800 1100 800 5000 1100 1100 1300 WARD 1250 800 1250 800 5000 1250 1250 1500 MARTIN 1250 800 1250 800 5000 1250 1250 1600 MILLER 1300 800 1300 800 5000 1300 1300 2450 TURNER 1500 800 1500 800 5000 1500 1500 2850 ALLEN 1600 800 1600 800 5000 1600 1600 2975 CLARK 2450 800 2450 800 5000 2450 2450 3000 BLAKE 2850 800 2850 800 5000 2850 2850 3000 JONES 2975 800 2975 800 5000 2975 2975 5000 SCOTT 3000 800 3000 800 5000 3000 3000 5000 FORD 3000 800 3000 800 5000 3000 3000 5000 KING 5000 800 5000 800 5000 5000 5000 5000 OK, let's break this query down: MIN1 The window function generating this column does not specify a framing clause, so the default framing clause of UNBOUNDED PRECEDING AND CURRENT ROW kicks in. Why is MIN1 800 for all rows? It's because the lowest salary comes first (ORDER BY SAL), and it remains the lowest, or minimum, salary forever after. MAX1 The values for MAX1 are much different from those for MIN1. Why? The answer (again) is the default framing clause UNBOUNDED PRECEDING AND CURRENT ROW. In conjunction with ORDER BY SAL, this framing clause ensures that the maximum salary will also correspond to that of the current row. Consider the first row, for SMITH. When evaluating SMITH's salary and all prior salaries, MAX1 for SMITH is SMITH's salary, because there are no prior salaries. Moving on to the next row, JAMES, when comparing JAMES' salary to all prior salaries, in this case comparing to the salary of SMITH, JAMES' salary is the higher of the two, and thus it is the maximum. If you apply this logic to all rows, you will see that the value of MAX1 for each row is the current employee's salary. MIN2 and MAX2 The framing clause given for these is UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING, which is the same as specifying empty parentheses. Thus, all rows in the result set are considered when computing MIN and MAX. As you might expect, the MIN and MAX values for the entire result set are constant, and thus the value of these columns is constant as well. MIN3 and MAX3 The framing clause for these is CURRENT ROW AND CURRENT ROW, which simply means use only the current employee's salary when looking for the MIN and MAX salary. Thus both MIN3 and MAX3 are the same as SAL for each row. That was easy, wasn't it? MAX4 The framing clause defined for MAX4 is 3 PRECEDING AND 3 FOLLOWING, which means, for every row, consider the three rows prior and the three rows after the current row, as well as the current row itself. This particular invocation of MAX(SAL) will return from those rows the highest salary value. If you look at the value of MAX4 for employee MARTIN you can see how the framing clause is applied. MARTIN's salary is 1250 and the three employee salaries prior to MARTIN's are WARD's (1250), ADAMS' (1100) and JAMES' (950). The three employee salaries after MARTIN's are MILLER's (1300), TURNER's (1500), and ALLEN's (1600). Out of all those salaries, including MARTIN's, the highest is ALLEN's, and thus the value of MAX4 for MARTIN is 1600. ### Readability + Performance = Power As you can see, window functions are extremely powerful as they allow you to write queries that contain both detailed and aggregate information. Using window functions allows you to write smaller, more efficient queries as compared to using multiple self join and/or scalar subqueries. Consider the following query, which easily answers all of the following questions: "What is the number of employees in each department? How many different types of employees are in each department (e.g., how many clerks are in department 10)? How many total employees are in table EMP?" **select deptno,** **job,** **count(*) over (partition by deptno) as emp_cnt,** **count(job) over (partition by deptno,job) as job_cnt,** **count(*) over () as total** **from emp** DEPTNO JOB EMP_CNT JOB_CNT TOTAL ------ --------- ---------- ---------- ---------- 10 CLERK 3 1 14 10 MANAGER 3 1 14 10 PRESIDENT 3 1 14 20 ANALYST 5 2 14 20 ANALYST 5 2 14 20 CLERK 5 2 14 20 CLERK 5 2 14 20 MANAGER 5 1 14 30 CLERK 6 1 14 30 MANAGER 6 1 14 30 SALESMAN 6 4 14 30 SALESMAN 6 4 14 30 SALESMAN 6 4 14 30 SALESMAN 6 4 14 To return the same result set without using window functions would require a bit more work: **select a.deptno, a.job,** **(select count(*) from emp b** **where b.deptno = a.deptno) as emp_cnt,** **(select count(*) from emp b** **where b.deptno = a.deptno and b.job = a.job) as job_cnt,** **(select count(*) from emp) as total** **from emp a** **order by 1,2** DEPTNO JOB EMP_CNT JOB_CNT TOTAL ------ --------- ---------- ---------- ---------- 10 CLERK 3 1 14 10 MANAGER 3 1 14 10 PRESIDENT 3 1 14 20 ANALYST 5 2 14 20 ANALYST 5 2 14 20 CLERK 5 2 14 20 CLERK 5 2 14 20 MANAGER 5 1 14 30 CLERK 6 1 14 30 MANAGER 6 1 14 30 SALESMAN 6 4 14 30 SALESMAN 6 4 14 30 SALESMAN 6 4 14 30 SALESMAN 6 4 14 The non-window solution is obviously not difficult to write, yet it certainly is not as clean or efficient (you won't see performance differences with a 14-row table, but try these queries with, say, a 1,000- or 10,000-row table and then you'll see the benefit of using window functions over multiple self joins and scalar subqueries). ### Providing a Base Besides readability and performance, window functions are useful for providing a "base" for more complex "report style" queries. For example, consider the following "report style" query that uses window functions in an inline view and then aggregates the results in an outer query. Using window functions allows you to return detailed as well as aggregate data, which is useful for reports. The query below uses window functions to find counts using different partitions. Because the aggregation is applied to multiple rows, the inline view returns all rows from EMP, which the outer CASE expressions can use to transpose and create a formatted report: **select deptno,** **emp_cnt as dept_total,** **total,** **max(case when job = 'CLERK'** **then job_cnt else 0 end) as clerks,** **max(case when job = 'MANAGER'** **then job_cnt else 0 end) as mgrs,** **max(case when job = 'PRESIDENT'** **then job_cnt else 0 end) as prez,** **max(case when job = 'ANALYST'** **then job_cnt else 0 end) as anals,** **max(case when job = 'SALESMAN'** **then job_cnt else 0 end) as smen** **from (** **select deptno,** **job,** **count(*) over (partition by deptno) as emp_cnt,** **count(job) over (partition by deptno,job) as job_cnt,** **count(*) over () as total** **from emp** **) x** **group by deptno, emp_cnt, total** DEPTNO DEPT_TOTAL TOTAL CLERKS MGRS PREZ ANALS SMEN ------ ---------- ----- ------ ---- ---- ----- ---- 10 3 14 1 1 1 0 0 20 5 14 2 1 0 2 0 30 6 14 1 1 0 0 4 The query above returns each department, the total number of employees in each department, the total number of employees in table EMP, and a breakdown of the number of different job types in each department. All this is done in one query, without additional joins or temp tables! As a final example of how easily multiple questions can be answered using window functions, consider the following query: **select ename as name,** **sal,** **max(sal)over(partition by deptno) as hiDpt,** **min(sal)over(partition by deptno) as loDpt,** **max(sal)over(partition by job) as hiJob,** **min(sal)over(partition by job) as loJob,** **max(sal)over() as hi,** **min(sal)over() as lo,** **sum(sal)over(partition by deptno** **order by sal,empno) as dptRT,** **sum(sal)over(partition by deptno) as dptSum,** **sum(sal)over() as ttl** **from emp** **order by deptno,dptRT** NAME SAL HIDPT LODPT HIJOB LOJOB HI LO DPTRT DPTSUM TTL ------ ----- ----- ----- ----- ----- ----- ---- ------ ------ ------ MILLER 1300 5000 1300 1300 800 5000 800 1300 8750 29025 CLARK 2450 5000 1300 2975 2450 5000 800 3750 8750 29025 KING 5000 5000 1300 5000 5000 5000 800 8750 8750 29025 SMITH 800 3000 800 1300 800 5000 800 800 10875 29025 ADAMS 1100 3000 800 1300 800 5000 800 1900 10875 29025 JONES 2975 3000 800 2975 2450 5000 800 4875 10875 29025 SCOTT 3000 3000 800 3000 3000 5000 800 7875 10875 29025 FORD 3000 3000 800 3000 3000 5000 800 10875 10875 29025 JAMES 950 2850 950 1300 800 5000 800 950 9400 29025 WARD 1250 2850 950 1600 1250 5000 800 2200 9400 29025 MARTIN 1250 2850 950 1600 1250 5000 800 3450 9400 29025 TURNER 1500 2850 950 1600 1250 5000 800 4950 9400 29025 ALLEN 1600 2850 950 1600 1250 5000 800 6550 9400 29025 BLAKE 2850 2850 950 2975 2450 5000 800 9400 9400 29025 This query answers the following questions easily, efficiently, and readably (and without additional joins to EMP!). Simply match the employee and her salary with the different rows in the result set to determine: 1. who makes the highest salary of all employees (HI) 2. who makes the lowest salary of all employees (LO) 3. who makes the highest salary in her department (HIDPT) 4. who makes the lowest salary in her department (LODPT) 5. who makes the highest salary in her job (HIJOB) 6. who makes the lowest salary in her job (LOJOB) 7. what is the sum of all salaries (TTL) 8. what is the sum of salaries per department (DPTSUM) 9. what is the running total of all salaries per department (DPTRT) ## Appendix B. Rozenshtein Revisited This appendix is a tribute to David Rozenshtein. As I mentioned in the introduction, I feel his book _The Essence of SQL_ is (even today) the best book ever written on SQL. Although only 119 pages long, the book covers what I consider to be crucial topics for any SQL programmer. In particular, David shows how to think through a problem and arrive at an answer. The solutions provided by Rozenshtein are very set oriented. Even if the size of your tables do not permit you to use his solutions in a practical environment, his approach is excellent as it forces you to stop searching for a procedural solution to a problem and start thinking in sets. _The Essence of SQL_ was published long before window functions and MODEL clauses. In this appendix I provide alternative solutions to some of the questions in Rozenshtein's book using some of the newer functions available in standard SQL. (Whether these new solutions are "better" than Rozenshtein's depends on the circumstances.) At the end of each discussion, I present a solution based on the original solution from Rozenshtein's book. For the examples in which I present a variation of a problem found in Rozenshtein's text, I will also present a variation of a solution (a solution that may not necessarily exist in Rozenshtein's book, but that uses a similar technique). ## B.1. Rozenshtein's Example Tables The following tables are based on Rozenshtein's book and will be used in this chapter: /* table of students */ create table student ( sno integer, sname varchar(10), age integer ) /* table of courses */ create table courses ( cno varchar(5), title varchar(10), credits integer ) /* table of professors */ create table professor ( lname varchar(10), dept varchar(10), salary integer, age integer ) /* table of students and the courses they take */ create table take ( sno integer, cno varchar(5) ) /* table of professors and the courses they teach */ create table teach ( lname varchar(10), cno varchar(5) ) insert into student values (1,'AARON',20) insert into student values (2,'CHUCK',21) insert into student values (3,'DOUG',20) insert into student values (4,'MAGGIE',19) insert into student values (5,'STEVE',22) insert into student values (6,'JING',18) insert into student values (7,'BRIAN',21) insert into student values (8,'KAY',20) insert into student values (9,'GILLIAN',20) insert into student values (10,'CHAD',21) insert into courses values ('CS112','PHYSICS',4) insert into courses values ('CS113','CALCULUS',4) insert into courses values ('CS114','HISTORY',4) insert into professor values ('CHOI','SCIENCE',400,45) insert into professor values ('GUNN','HISTORY',300,60) insert into professor values ('MAYER','MATH',400,55) insert into professor values ('POMEL','SCIENCE',500,65) insert into professor values ('FEUER','MATH',400,40) insert into take values (1,'CS112') insert into take values (1,'CS113') insert into take values (1,'CS114') insert into take values (2,'CS112') insert into take values (3,'CS112') insert into take values (3,'CS114') insert into take values (4,'CS112') insert into take values (4,'CS113') insert into take values (5,'CS113') insert into take values (6,'CS113') insert into take values (6,'CS114') insert into teach values ('CHOI','CS112') insert into teach values ('CHOI','CS113') insert into teach values ('CHOI','CS114') insert into teach values ('POMEL','CS113') insert into teach values ('MAYER','CS112') insert into teach values ('MAYER','CS114') ## B.2. Answering Questions Involving Negation In his book, Rozenshtein approached the teaching of SQL through an examination of the different types of fundamental problems that you are often called upon to solve, in one form or another. Negation is one such type. It is often necessary to find rows for which some condition is not true. Simple conditions are easy but, as the following questions show, some negation problems require a bit of creativity and thought to solve. ### Question 1 You want to find students who do not take CS112, but the following query is returning the wrong results: select * from student where sno in ( select sno from take where cno != 'CS112' ) Because a student may take several courses, this query can (and does) return students who take CS112. The query is incorrect because it does not answer the question: "Who does not take CS112?" Instead, it answers the question "Who takes a course that is not CS112?" The correct result set should include students who take no courses as well as students who take courses but none of them CS112. Ultimately, you should return the following result set: SNO SNAME AGE --------- ---------- ---------- 5 STEVE 22 6 JING 18 7 BRIAN 21 8 KAY 20 9 GILLIAN 20 10 CHAD 21 #### MySQL and PostgreSQL Use a CASE expression with the aggregate function MAX to flag CS112 if it exists for a particular student: 1 select s.sno,s.sname,s.age 2 from student s left join take t 3 on (s.sno = t.sno) 4 group by s.sno,s.sname,s.age 5 having max(case when t.cno = 'CS112' 6 then 1 else 0 end) = 0 #### DB2 and SQL Server Use a CASE expression with the window function MAX OVER to flag CS112 if it exists for a particular student: 1 select distinct sno,sname,age 2 from ( 3 select s.sno,s.sname,s.age, 4 max(case when t.cno = 'CS112' 5 then 1 else 0 end) 7 over(partition by s.sno,s.sname,s.age) as takes_CS112 9 from student s left join take t 10 on (s.sno = t.sno) 11 ) x 12 where takes_CS112 = 0 #### Oracle For users on Oracle9 _i_ Database and later, you can use the DB2 solution above. Alternatively, you can use the proprietary Oracle outer-join syntax, which is mandatory for users on Oracle8 _i_ Database and earlier: /* group by solution */ 1 select s.sno,s.sname,s.age 2 from student s, take t 3 where s.sno = t.sno (+) 4 group by s.sno,s.sname,s.age 5 having max(case when t.cno = 'CS112' 6 then 1 else 0 end) = 0 /* window solution */ 1 select distinct sno,sname,age 2 from ( 3 select s.sno,s.sname,s.age, 4 max(case when t.cno = 'CS112' 5 then 1 else 0 end) 7 over(partition by s.sno,s.sname,s.age) as takes_CS112 9 from student s, take t 10 where s.sno = t.sno (+) 11 ) x 12 where takes_CS112 = 0 #### Discussion Despite the different syntax for each solution, the technique is the same. The idea is to create a "Boolean" column in the result set to denote whether or not a student takes CS112. If a student takes CS112, then return 1 in that column; otherwise, return 0. The following query moves the CASE expression into the SELECT list and shows the intermediate results thus far: **select s.sno,s.sname,s.age,** **case when t.cno = 'CS112'** **then 1** **else 0** **end as takes_CS112** **from student s left join take t** **on (s.sno=t.sno)** SNO SNAME AGE TAKES_CS112 --- ---------- ---------- ----------- 1 AARON 20 1 1 AARON 20 0 1 AARON 20 0 2 CHUCK 21 1 3 DOUG 20 1 3 DOUG 20 0 4 MAGGIE 19 1 4 MAGGIE 19 0 5 STEVE 22 0 6 JING 18 0 6 JING 18 0 8 KAY 20 0 10 CHAD 21 0 7 BRIAN 21 0 9 GILLIAN 20 0 The outer join to table TAKE ensures that even students who take no courses are returned. The next step is to use MAX to take the greatest value returned by the CASE expression for each student. If a student takes CS112, the greatest value will be 1, because all other courses are 0. For the solution using GROUP BY, the final step is to use the HAVING clause to keep only students with 0 returned from the MAX/CASE expression. For the window solution, you need to wrap the query in an inline view and then reference TAKES_CS112, because window functions cannot be referenced directly in the WHERE clause. Because of how window functions work, it is also necessary to remove duplicates caused by multiple courses. #### Original solution The original solution to this problem is quite clever and is shown here: select * from student where snonot in (select sno from take where cno = 'CS112') This can be stated as: "Find the students in table TAKE who take CS112, and then return all students in table STUDENT who are not them." This technique follows the advice regarding negation found at the end of Rozenshtein's book: > Remember that real negation requires two passes: To find out "who does not," first find out "who does" and then get rid of them. ### Question 2 You want to find students who take CS112 or CS114 but not both. The following query looks promising as a solution but returns the wrong result set: select * from student where sno in ( select sno from take where cno != 'CS112' and cno != 'CS114' ) Of the students who take courses, only students DOUG and AARON take both CS112 and CS114. Those two should be excluded. Student STEVE takes CS113, but not CS112 or CS114, and should be excluded as well. Because a student can take multiple courses, the approach here is to return a single row for each student with information regarding whether the student takes CS112 or CS114, or both. This approach allows you to easily evaluate whether or not the student takes both courses without having to make multiple passes through the data. The final result set should be: SNO SNAME AGE --- ---------- ---------- 2 CHUCK 21 4 MAGGIE 19 6 JING 18 #### MySQL and PostgreSQL Use a CASE expression with the aggregate function SUM to find students who take either CS112 or CS114 but not both: 1 select s.sno,s.sname,s.age 2 from student s, take t 3 where s.sno = t.sno 4 group by s.sno,s.sname,s.age 5 having sum(case when t.cno in ('CS112','CS114') 6 then 1 else 0 end) = 1 #### DB2, Oracle, and SQL Server Use a CASE expression with the window function SUM OVER to find students who take either CS112 or CS114 but not both: 1 select distinct sno,sname,age 2 from ( 3 select s.sno,s.sname,s.age, 4 sum(case when t.cno in ('CS112','CS114') then 1 else 0 end) 5 over (partition by s.sno,s.sname,s.age) as takes_either_or 6 from student s, take t 7 where s.sno = t.sno 8 ) x 9 where takes_either_or = 1 #### Discussion The first step in solving the problem is to use an inner join from table STUDENT to table TAKE, thus eliminating any students who do not take any courses. The next step is to use a CASE expression to denote whether a student takes each respective course. In the following query, the CASE expressions are moved into the SELECT list and return the intermediate results thus far: **select s.sno,s.sname,s.age,** **case when t.cno in ('CS112','CS114')** **then 1 else 0 end as takes_either_or** **from student s, take t** **where s.sno = t.sno** SNO SNAME AGE TAKES_EITHER_OR --- ---------- --- --------------- 1 AARON 20 1 1 AARON 20 0 1 AARON 20 1 2 CHUCK 21 1 3 DOUG 20 1 3 DOUG 20 1 4 MAGGIE 19 1 4 MAGGIE 19 0 5 STEVE 22 0 6 JING 18 0 6 JING 18 1 A value of 1 for TAKES_EITHER_OR signifies the student takes CS112 or CS114. Because a student can take multiple courses, the next step is to return only one row per student by using a GROUP BY with the aggregate function SUM. The function SUM will sum all the 1's for each student: **select s.sno,s.sname,s.age,** **sum(case when t.cno in ('CS112','CS114')** **then 1 else 0 end) as takes_either_or** **from student s, take t** **where s.sno = t.sno** **group by s.sno,s.sname,s.age** SNO SNAME AGE TAKES_EITHER_OR --- ---------- --- --------------- 1 AARON 20 2 2 CHUCK 21 1 3 DOUG 20 2 4 MAGGIE 19 1 5 STEVE 22 0 6 JING 18 1 Students who do not take CS112 or CS114 will have 0 for TAKES_EITHER_OR. Students who take both CS112 and CS114 will have 2 for TAKES_EITHER_OR. Thus the only students you want to return are those with a value of 1 for TAKES_EITHER_OR. The final solution uses the HAVING clause to keep only those students where the SUM of TAKES_EITHER_OR is one. For the window solution, the same technique is used. You also need to wrap the query in an inline view, and then reference the column TAKES_EITHER_OR, because window functions cannot be referenced directly in the WHERE clause (they are evaluated last in SQL processing, prior only to the ORDER BY clause). Because of how window functions work, it is necessary to remove duplicates caused by multiple courses. #### Original solution The following query is the original solution (modified slightly). The query is quite clever and uses the same approach as the original solution in Question 1. The solution uses a self join to find students who take both CS112 and CS114, and then uses a subquery to filter them out of the set of students who take either CS112 or CS114: select * from student s, take t where s.sno = t.sno and t.cno in ( 'CS112', 'CS114' ) and s.sno not in ( select a.sno from take a, take b where a.sno = b.sno and a.cno = 'CS112' and b.cno = 'CS114' ) ### Question 3 You want to find students who take CS112 and no other courses, but the following query returns incorrect results: select s.* from student s, take t where s.sno = t.sno and t.cno = 'CS112' CHUCK is the only student who takes CS112 and no other courses, and is the only student that should be returned from the query. This question can be restated as "Find students who take only CS112." The query above finds students who take CS112, but also returns students who take other courses as well. The query should answer the question "Who takes only one course and that one course is CS112?" #### MySQL and PostgreSQL Use the aggregate function COUNT to ensure that students returned by the query take only one course: 1 select s.* 2 from student s, 3 take t1, 4 ( 5 select sno 6 from take 7 group by sno 8 having count(*) = 1 9 ) t2 10 where s.sno = t1.sno 11 and t1.sno = t2.sno 12 and t1.cno = 'CS112' #### DB2, Oracle, and SQL Server Use the window function COUNT OVER to ensure a student takes only one course: 1 select sno,sname,age 2 from ( 3 select s.sno,s.sname,s.age,t.cno, 4 count(t.cno) over ( 5 partition by s.sno,s.sname,s.age 6 ) as cnt 7 from student s, take t 8 where s.sno = t.sno 9 ) x 10 where cnt = 1 11 and cno = 'CS112' #### Discussion The key to the solutions is to write a query to answer both of the following questions: "Which student takes only one course?" and "Which student takes CS112?" The first approach uses inline view T2 to find students who take only one course. The next step is to join inline view T2 to table TAKE and keep only students who take CS112 (so what you are left with are students who take only one course and that one course is CS112). The query below shows the results thus far: **select t1.*** **from take t1,** **(** **select sno** **from** **take** **group by sno** **having count(*) = 1** **) t2** **where t1.sno = t2.sno** **and t1.cno = 'CS112'** SNO CNO --- ----- 2 CS112 The final step is to join to table STUDENT and find the students who match those returned by the join between inline view T2 and table TAKE. The window solution takes a similar approach but does so in a different (more efficient) way. Inline view X returns the students, the courses they take, and the number of courses they take (the inner join between table TAKE and table STUDENT guarantees that students who take no courses are excluded). The results are shown below: **select s.sno,s.sname,s.age,t.cno,** **count(t.cno) over (** **partition by s.sno,s.sname,s.age** **) as cnt** **from student s, take t** **where s.sno = t.sno** SNO SNAME AGE CNO CNT --- ---------- ---------- ----- ---------- 1 AARON 20 CS112 3 1 AARON 20 CS113 3 1 AARON 20 CS114 3 2 CHUCK 21 CS112 1 3 DOUG 20 CS112 2 3 DOUG 20 CS114 2 4 MAGGIE 19 CS112 2 4 MAGGIE 19 CS113 2 5 STEVE 22 CS113 1 6 JING 18 CS113 2 6 JING 18 CS114 2 With the course and count available, the last step is to simply keep only rows such that CNT is 1 and CNO is CS112. #### Original solution The original solution uses a subquery and double negation: select s.* from student s, take t where s.sno = t.sno and s.sno not in ( select sno from take where cno != 'CS112' ) This is an extremely clever solution, because nowhere in the query is the number of courses checked, nor is there a filter to ensure that students returned by the query actually take CS112! How does this work, then? The subquery returns all students who take a course other than CS112 and the results are shown below: **select sno** **from take** **where cno != 'CS112'** SNO ---- 1 1 3 4 5 6 6 The outer query returns all students who take a course (any course) and are not amongst the students returned by the subquery. Ignoring the NOT IN portion of the outer query for a moment, the results would be the following (showing all students who take a course): **select s.*** **from student s, take t** **where s.sno = t.sno** SNO SNAME AGE --- ---------- ---------- 1 AARON 20 1 AARON 20 1 AARON 20 2 CHUCK 21 3 DOUG 20 3 DOUG 20 4 MAGGIE 19 4 MAGGIE 19 5 STEVE 22 6 JING 18 6 JING 18 If you compare the two results sets, you see that the addition of NOT IN to the outer query effectively performs a set difference between SNO from the outer query and SNO from the subquery, returning only the student whose SNO is 2. In summary, the subquery finds all students who take a course that is not CS112. The outer query returns all students who are not amongst those that take a course other than CS112 (at this point the only available students are those who actually take CS112 or take nothing at all). The join between table STUDENT and table TAKE filters out the students who do not take any classes at all, leaving you only with the student who takes CS112 and only CS112. Set-based problem solving at its best! ## B.3. Answering Questions Involving "at Most" Questions involving "at most" represent another type of query problem that you'll encounter from time to time. It's easy enough to find rows for which a condition is true, but what if you want to place a limit on the number of such rows? That's what the next next two questions are all about. ### Question 4 You want to find the students who take at most two courses. Students who do not take any courses should be excluded. Of the students who take courses, only AARON takes more than two and should be excluded from the result set. Ultimately, you want to return the following result set: SNO SNAME AGE --- ---------- ---------- 2 CHUCK 21 3 DOUG 20 4 MAGGIE 19 5 STEVE 22 6 JING 18 #### MySQL and PostgreSQL Use the aggregate function COUNT to determine which students take no more than two courses: 1 select s.sno,s.sname,s.age 2 from student s, take t 3 where s.sno = t.sno 4 group by s.sno,s.sname,s.age 5 having count(*) <= 2 #### DB2, Oracle, and SQL Server Use the window function COUNT OVER, again to determine which students take no more than two courses: 1 select distinct sno,sname,age 2 from ( 3 select s.sno,s.sname,s.age, 4 count(*) over ( 5 partition by s.sno,s.sname,s.age 6 ) as cnt 7 from student s, take t 8 where s.sno = t.sno 9 ) x 10 where cnt <= 2 #### Discussion Both solutions work by simply counting the number of times a particular SNO occurs in table TAKE. The inner join to table TAKE ensures that students who take no courses are excluded from the final result set. #### Original solution Rozenshtein used the aggregate solution shown here for MySQL and PostgreSQL in his book along with an alternative solution using multiple self joins, shown here: select distinct s.* from student s, take t where s.sno = t.sno and s.sno not in ( select t1.sno from take t1, take t2, take t3 where t1.sno = t2.sno and t2.sno = t3.sno and t1.cno < t2.cno and t2.cno < t3.cno ) The multiple self-join solution is interesting because it solves the problem without using aggregation. To understand how the solution works, focus on the WHERE clause of the subquery. The inner joins on SNO ensure that you are dealing with the same student across all columns of each row that can potentially be returned by the subquery. The less-than comparisons are what determine whether or not a student is taking more than two courses. The WHERE clause in the subquery can be stated as: "For a particular student, return rows where the first CNO is less than the second CNO and the second CNO is less than the THIRD CNO." If a student has fewer than three courses, that expression can never evaluate to true as there is no third CNO. The job of the subquery is to find students who take three or more courses. The outer query then returns students who take at least one course and are not amongst those returned by the subquery. ### Question 5 You want to find students who are older than at most two other students. Another way to think about the problem is to find only the students who are older than zero, one, or two other students. The final result set should be: SNO SNAME AGE ---- ---------- --- 6 JING 18 4 MAGGIE 19 1 AARON 20 9 GILLIAN 20 8 KAY 20 3 DOUG 20 #### MySQL and PostgreSQL Use the aggregate function COUNT and a correlated subquery to find the students who are older than zero, one, or two other students: 1 select s1.* 2 from student s1 3 where 2 >= ( select count(*) 4 from student s2 5 where s2.age < s1.age ) #### DB2, Oracle, and SQL Server Use the window function DENSE_RANK to find the students who are older than zero, one, or two other students: 1 select sno,sname,age 2 from ( 3 select sno,sname,age, 4 dense_rank()over(order by age) as dr 5 from student 6 ) x 7 where dr <= 3 #### Discussion The aggregate solution uses a scalar subquery to find all students who are older than no more than two other students. To see how this works, rewrite the solution to use a scalar subquery. In the following example, the column CNT represents the number of students that are younger than the current student: **select s1.*,** **(select count(*) from student s2** **where s2.age< s1.age) as cnt** **from student s1** **order by 4** SNO SNAME AGE CNT --- ---------- ---------- ---------- 6 JING 18 0 4 MAGGIE 19 1 1 AARON 20 2 3 DOUG 20 2 8 KAY 20 2 9 GILLIAN 20 2 2 CHUCK 21 6 7 BRIAN 21 6 10 CHAD 21 6 5 STEVE 22 9 Rewriting the solution this way makes it easy to see that the students in the final result set are those for whom CNT is less than or equal to 2. The solution using the window function DENSE_RANK is similar to the scalar subquery example in that every row is ranked based on how many students are younger than the current student (ties are allowed and there are no gaps). The following query shows the output from the DENSE_RANK function: **select sno,sname,age,** **dense_rank()over(order by age) as dr** **from student** SNO SNAME AGE DR --- ---------- ---------- ---------- 6 JING 18 1 4 MAGGIE 19 2 1 AARON 20 3 3 DOUG 20 3 8 KAY 20 3 9 GILLIAN 20 3 2 CHUCK 21 4 7 BRIAN 21 4 10 CHAD 21 4 5 STEVE 22 5 The final step is to wrap the query in an inline view and keep only those rows where DR is less than or equal to 3. #### Original solution Rozenshtein takes an interesting approach to solving this problem by rephrasing it. Instead of "find the students who are older than at most two students," his approach is to "find the students who are not older than three or more (at least three) students." This approach is brilliant for those of you who want to learn how to problem solve in sets, because it forces you to find the solution in two passes: 1. Find the set of students who are older than three or more students. 2. Simply return all students who are not amongst the students returned by step 1. The solution is shown below: **select *** **from student** **where sno not in (** **select s1.sno** **from student s1,** **student s2,** **student s3,** **student s4** **where s1.age> s2.age** **and s2.age> s3.age** **and s3.age> s4.age** **)** SNO SNAME AGE --- ---------- --- 6 JING 18 4 MAGGIE 19 1 AARON 20 9 GILLIAN 20 8 KAY 20 3 DOUG 20 If you examine the solution from bottom up, you see that step 1, "find all students who are older than three or more students," is performed first and is shown below (using DISTINCT to reduce the result set size for readability): **select distinct s1.*** **from student s1,** **student s2,** **student s3,** **student s4** **where s1.age> s2.age** **and s2.age> s3.age** **and s3.age> s4.age** SNO SNAME AGE --- ---------- --- 2 CHUCK 21 5 STEVE 22 7 BRIAN 21 10 CHAD 21 If you are getting confused by all the self joins, simply focus on the WHERE clause. S1.AGE is greater than S2.AGE so you know at that point any student who is older than at least one other student is considered. Next, S2.AGE is greater than S3.AGE. At this point any student who is older than two other students is considered. If you are stumbling at this point, try to keep in mind that greater-than comparisons are transitive. If S1.AGE is greater than S2.AGE, and S2.AGE is greater than S3.AGE, then it is also true that S1AGE is greater than S3.AGE. You may find it helpful to strip down the query to one self join and build the query once you understand what is returned by each step. For example, find all students who are older than at least one other student (all students except the youngest, JING, should be returned): **select distinct s1.*** **from student s1,** **student s2** **where s1.age> s2.age** SNO SNAME AGE --- ---------- --- 5 STEVE 22 7 BRIAN 21 10 CHAD 21 2 CHUCK 21 1 AARON 20 3 DOUG 20 9 GILLIAN 20 8 KAY 20 4 MAGGIE 19 Next, find all students who are older than two or more students (now, both JING and MAGGIE should be excluded from the result set): **select distinct s1.*** **from student s1,** **student s2,** **student s3** **where s1.age> s2.age** **and s2.age> s3.age** SNO SNAME AGE --- ---------- --- 1 AARON 20 2 CHUCK 21 3 DOUG 20 5 STEVE 22 7 BRIAN 21 8 KAY 20 9 GILLIAN 20 10 CHAD 21 Finally, find all students who are older than three or more students (only CHUCK, STEVE, BRIAN, and CHAD are in this result set): **select distinct s1.*** **from student s1,** **student s2,** **student s3,** **student s4** **where s1.age> s2.age** **and s2.age> s3.age** **and s3.age> s4.age** SNO SNAME AGE --- ---------- --- 2 CHUCK 21 5 STEVE 22 7 BRIAN 21 10 CHAD 21 Now that you know which students are older than three or more other students, simply return only those students who are not amongst the four students above by using NOT IN with a subquery. ## B.4. Answering Questions Involving "at Least" The flip side of "at most" is "at least." You can often solve "at least" questions by applying variations of the techniques described for "at most" questions. When solving "at least" problems it is often helpful to rephrase them as "having no fewer than." In general, if you can identify a threshold in your requirement, you've already solved half the problem. Once you know the threshold, you can decide to solve the problem using one pass (aggregate or window functions typically using COUNT) or two passes (negation with subquery). ### Question 6 You want to find students who take at least two courses. You may find it helpful to restate the problem as "Find students who take two or more courses" or as "Find students who take no fewer than two courses." You can use the same technique used for Question 4: use the aggregate function COUNT or window function COUNT OVER. The final result set should be: SNO SNAME AGE --- ---------- ---------- 1 AARON 20 3 DOUG 20 4 MAGGIE 19 6 JING 18 #### MySQL and PostgreSQL Use the aggregate function COUNT to find students who take at least two courses: 1 select s.sno,s.sname,s.age 2 from student s, take t 3 where s.sno = t.sno 4 group by s.sno,s.sname,s.age 5 having count(*) >= 2 #### DB2, Oracle, and SQL Server Use the window function COUNT OVER to find students who take at least two courses: 1 select distinct sno,sname,age 2 from ( 3 select s.sno,s.sname,s.age, 4 count(*) over ( 5 partition by s.sno,s.sname,s.age 6 ) as cnt 7 from student s, take t 8 where s.sno = t.sno 9 ) x 10 where cnt >= 2 #### Discussion See Question 4 for a full discussion of the solutions presented in this section; the techniques are the same. For the aggregate solution, join table STUDENT to table TAKE and use COUNT in the HAVING clause to keep only those students with two or more courses. For the window solution, join table STUDENT to table TAKE and perform a count over the partition that is defined by specifying all the columns from table STUDENT. From there, simply keep only those rows where CNT is two or greater. #### Original solution The solution below uses a self join on table TAKE to find students who take two or more classes. The equi-join on SNO in the subquery ensures that each student is evaluated against his/her own courses only. The greater-than comparison on CNO can only be true if a student takes more than one course, otherwise CNO would equal CNO (as there is only one course to be compared with itself). The last step is to return all students who are amongst those returned by the subquery, and is shown below: **select *** **from student** **where sno in (** **select t1.sno** **from take t1,** **take t2** **where t1.sno = t2.sno** **and t1.cno> t2.cno** **)** SNO SNAME AGE --- ---------- ---------- 1 AARON 20 3 DOUG 20 4 MAGGIE 19 6 JING 18 ### Question 7 You want to find students who take both CS112 and CS114. The students may take other courses, but they must take CS112 and CS114 as well. This problem is similar to Question 2, except that in that case a student may take more than two courses whereas in this case they take _at least_ 2 courses (AARON and DOUG are the only students who take both CS112 and CS114). You can easily modify the solution from Question 2 to work here. The final result set should be: SNO SNAME AGE --- ---------- ---- 1 AARON 20 3 DOUG 20 #### MySQL and PostgreSQL Use the aggregate functions MIN and MAX to find students who take both CS112 and CS114: 1 select s.sno, s.sname, s.age 2 from student s, take t 3 where s.sno = t.sno 4 and t.cno in ('CS114','CS112') 5 group by s.sno, s.sname, s.age 6 having min(t.cno) != max(t.cno) #### DB2, Oracle, and SQL Server Use the window functions MIN OVER and MAX OVER to find students who take both CS112 and CS114: 1 select distinct sno, sname, age 2 from ( 3 select s.sno, s.sname, s.age, 4 min(cno) over (partition by s.sno) as min_cno, 5 max(cno) over (partition by s.sno) as max_cno 6 from student s, take t 7 where s.sno = t.sno 8 and t.cno in ('CS114','CS112') 9 ) x 10 where min_cno != max_cno #### Discussion Both solutions use the same technique to find the answer. The IN list ensures only students who take CS112 or CS114, or both, are returned. If a student does not take both courses, then MIN(CNO) will equal MAX(CNO) and that student is excluded. To help visualize how this works, the intermediate results of the window solution are shown below (T.CNO is added for clarity): **select s.sno, s.sname, s.age, t.cno,** **min(cno) over (partition by s.sno) as min_cno,** **max(cno) over (partition by s.sno) as max_cno** **from student s, take t** **where s.sno = t.sno** **and t.cno in ('CS114','CS112')** SNO SNAME AGE CNO MIN_C MAX_C --- ---------- ---- ----- ----- ----- 1 AARON 20 CS114 CS112 CS114 1 AARON 20 CS112 CS112 CS114 2 CHUCK 21 CS112 CS112 CS112 3 DOUG 20 CS114 CS112 CS114 3 DOUG 20 CS112 CS112 CS114 4 MAGGIE 19 CS112 CS112 CS112 6 JING 18 CS114 CS114 CS114 Examining the results, it's easy to see only AARON and DOUG have rows where MIN(CNO) != MAX(CNO). #### Original solution The original solution by Rozenshtein uses a self join on table TAKE. Following is the original solution, which performs extremely well with the proper indexes in place: **select s.*** **from student s,** **take t1,** **take t2** **where s.sno = t1.sno** **and t1.sno = t2.sno** **and t1.cno = 'CS112'** **and t2.cno = 'CS114'** SNO SNAME AGE --- ----- --- 1 AARON 20 3 DOUG 20 All the solutions work by ensuring that, regardless of the other courses a student may take, they must take both CS112 and CS114. If you are having trouble understanding the self join, you may find it easier to understand the following example: **select s.*** **from take t1, student s** **where s.sno = t1.sno** **and t1.cno = 'CS114'** **and 'CS112' = any (select t2.cno** **from take t2** **where t1.sno = t2.sno** **and t2.cno != 'CS114')** SNO SNAME AGE --- ----- --- 1 AARON 20 3 DOUG 20 ### Question 8 Find students who are older than at least two other students. You may find it helpful to restate the problem as "Find students who are older than two or more other students." You can use the same technique used in Question 5. The final result set is shown below (only JING and MAGGIE are not older than two or more students): SNO SNAME AGE --- ---------- ---------- 1 AARON 20 2 CHUCK 21 3 DOUG 20 5 STEVE 22 7 BRIAN 21 8 KAY 20 9 GILLIAN 20 10 CHAD 21 #### MySQL and PostgreSQL Use the aggregate function COUNT and a correlated subquery to find students older than at least two other students: 1 select s1.* 2 from student s1 3 where 2 <= ( select count(*) 4 from student s2 5 where s2.age < s1.age ) #### DB2, Oracle, and SQL Server Use the window function DENSE_RANK to find students older than at least two other students: 1 select sno,sname,age 2 from ( 3 select sno,sname,age, 4 dense_rank()over(order by age) as dr 5 from student 6 ) x 7 where dr >= 3 #### Discussion For a full discussion see Question 5. The technique is exactly the same for both solutions, with the only difference being the final evaluation on the count or rank. #### Original solution The problem is a variation of Question 6, the difference being you are now only dealing with the STUDENT table. This solution in Question 6 can be easily adapted to "find students older than at least two other students" and is shown below: **select distinct s1.*** **from student s1,** **student s2,** **student s3** **where s1.age> s2.age** **and s2.age> s3.age** SNO SNAME AGE --- ---------- ---------- 1 AARON 20 2 CHUCK 21 3 DOUG 20 5 STEVE 22 7 BRIAN 21 8 KAY 20 9 GILLIAN 20 10 CHAD 21 ## B.5. Answering Questions Involving "Exactly" You would think that answering the question of whether or not something is true would be easy. In many cases it is easy. But sometimes it can be tricky to answer questions of whether something is "exactly" true, especially when answering involves joining master/detail data. The problem stems from the exclusive nature of "exactly." It may be more helpful to think of it as "only." Consider the difference between people who wear shoes and those who wear only shoes. It is not enough to satisfy the condition; you must satisfy the condition while ensuring that no other conditions are satisfied. ### Question 9 Find professors who teach exactly one course. You can restate the problem as "Find professors who teach only one course." Which course they teach is unimportant; what matters is that only one course is taught. The final result set should be: LNAME DEPT SALARY AGE ---------- ---------- ---------- ---- POMEL SCIENCE 500 65 #### MySQL and PostgreSQL Use the aggregate function COUNT to find the professors who teach exactly one course: 1 select p.lname,p.dept,p.salary,p.age 2 from professor p, teach t 3 where p.lname = t.lname 4 group by p.lname,p.dept,p.salary,p.age 5 having count(*) = 1 #### DB2, Oracle, and SQL Server Use the window function COUNT OVER to find the professors who teach exactly one course: 1 select lname, dept, salary, age 2 from ( 3 select p.lname,p.dept,p.salary,p.age, 4 count(*) over (partition by p.lname) as cnt 5 from professor p, teach t 6 where p.lname = t.lname 7 ) x 8 where cnt = 1 #### Discussion By inner joining table PROFESSOR to table TEACH you ensure that all professors who teach no courses are excluded. The aggregate solution uses the COUNT function in the HAVING clause to return only professors who teach exactly one course. The window solution uses the COUNT OVER function, but notice that the columns from table PROFESSOR that are used in the PARTITION clause of the COUNT OVER function are different from the columns that are used in the GROUP BY of the aggregate solution. In this example it is safe for the GROUP BY and PARTITION BY clauses to be different, because the last names are unique in table TEACHER, i.e., excluding P.DEPT, P.SALARY, and .PAGE from the partition does not affect the COUNT operation. In solutions prior to this one, I purposely use the same columns in the PARTITION clause of a window function solution as I use in the GROUP BY clause of an aggregate solution to show that the PARTITION is a moving, more flexible kind of GROUP BY. #### Original solution This solution uses the same technique used in Question 3: perform two passes to find the answer. The first step is to find those professors who teach two or more classes. The second step is to find those professors who teach a course and are not amongst those returned by step 1. Please refer to Question 3 for a full discussion. The solution is shown below: **select p.*** **from professor p,** **teach t** **where p.lname = t.lname** **and p.lname not in (** **select t1.lname** **from teach t1,** **teach t2** **where t1.lname = t2.lname** **and t1.cno> t2.cno** **)** LNAME DEPT SALARY AGE ---------- ---------- ---------- ---------- POMEL SCIENCE 500 65 ### Question 10 You want to find students who take only CS112 and CS114 (exactly those two courses and no other courses), but the following query returns an empty result set: select s.* from student s, take t where s.sno = t.sno and t.cno = 'CS112' and t.cno = 'CS114' No row can have a column that is simultaneously two values (assuming simple scalar data types such as those used for table STUDENT), so the query will never work. Rozenshtein's book does a nice job of discussing how intuitive thinking when writing queries causes errors such as this one. DOUG is the only student who takes only CS112 and CS114 and should be the only student returned for this query. #### MySQL and PostgreSQL Use a CASE expression and the aggregate function COUNT to find students who take only CS112 and CS114: 1 select s.sno, s.sname, s.age 2 from student s, take t 3 where s.sno = t.sno 4 group by s.sno, s.sname, s.age 5 having count(*) = 2 6 and max(case when cno = 'CS112' then 1 else 0 end) + 7 max(case when cno = 'CS114' then 1 else 0 end) = 2 #### DB2, Oracle, and SQL Server Use the window function COUNT OVER with a CASE expression to find students who take only CS112 and CS114: 1 select sno,sname,age 2 from ( 3 select s.sno, 4 s.sname, 5 s.age, 6 count(*) over (partition by s.sno) as cnt, 7 sum(case when t.cno in ( 'CS112', 'CS114' ) 8 then 1 else 0 9 end) 10 over (partition by s.sno) as both, 11 row_number() 12 over (partition by s.sno order by s.sno) as rn 13 from student s, take t 14 where s.sno = t.sno 15 ) x 16 where cnt = 2 17 and both = 2 18 and rn = 1 #### Discussion The aggregate solution uses the same technique found in Question 1 and Question 2. The inner join from table STUDENT to table TAKE ensures that any students who take no courses are excluded. The COUNT expression in the HAVING clause keeps only students who take exactly two courses. The results of the CASE expressions counting the number of courses are summed. Only those students who take both CS112 and CS114 have a sum of 2. The window solution uses a technique similar to the window solutions found in Question 1 and Question 2. This version is slightly different as the value of the CASE expression is returned to the window function SUM OVER. Another variation in this solution is the use of the window function ROW_NUMBER to avoid using DISTINCT. The results of the window solution without the final filters are shown below: **select s.sno,** **s.sname,** **s.age,** **count(*) over (partition by s.sno) as cnt,** **sum(case when t.cno in ( 'CS112', 'CS114' )** **then 1 else 0** **end)** **over (partition by s.sno) as both,** **row_number()** **over (partition by s.sno order by s.sno) as rn** **from student s, take t** **where s.sno = t.sno** SNO SNAME AGE CNT BOTH RN --- ------ ---- ---- ---- ---- 1 AARON 20 3 2 1 1 AARON 20 3 2 2 1 AARON 20 3 2 3 2 CHUCK 21 1 1 1 3 DOUG 20 2 2 1 3 DOUG 20 2 2 2 4 MAGGIE 19 2 1 1 4 MAGGIE 19 2 1 2 5 STEVE 22 1 0 1 6 JING 18 2 1 1 6 JING 18 2 1 2 Examining these results, you can see that the final result set is the one where BOTH and CNT are 2. RN can be either 1 or 2, it doesn't matter; that column exists only to help filter out duplicates without using DISTINCT. #### Original solution This solution uses a subquery with multiple self joins to first find students who take at least three classes. The next step is to use a self join on table TAKE to find those students who take both CS112 and CS114. The final step is to keep only those students who take both CS112 and CS114 and do not take three or more classes. The solution is shown below: **select s1.*** **from student s1,** **take t1,** **take t2** **where s1.sno = t1.sno** **and s1.sno = t2.sno** **and t1.cno = 'CS112'** **and t2.cno = 'CS114'** **and s1.sno not in (** **select s2.sno** **from student s2,** **take t3,** **take t4,** **take t5** **where s2.sno = t3.sno** **and s2.sno = t4.sno** **and s2.sno = t5.sno** **and t3.cno> t4.cno** **and t4.cno> t5.cno** **)** SNO SNAME AGE --- ---------- --- 3 DOUG 20 ### Question 11 You want to find students who are older than exactly two other students. Another way of stating the problem is that you want to find the third youngest student(s). The final result set should be: SNO SNAME AGE --- ---------- ---------- 1 AARON 20 3 DOUG 20 8 KAY 20 9 GILLIAN 20 #### MySQL and PostgreSQL Use the aggregate function COUNT and a correlated subquery to find the third youngest student: 1 select s1.* 2 from student s1 3 where 2 = ( select count(*) 4 from student s2 5 where s2.age < s1.age ) #### DB2, Oracle, and SQL Server Use the window function DENSE_RANK to find the third youngest student: 1 select sno,sname,age 2 from ( 3 select sno,sname,age, 4 dense_rank()over(order by age) as dr 5 from student 6 ) x 7 where dr = 3 #### Discussion The aggregate solution uses a scalar subquery to find all students who are older than two (and only two) other students. To see how this works, rewrite the solution to use a scalar subquery. In the following example, the column CNT represents the number of students that are younger than the current student: **select s1.*,** **(select count(*) from student s2** **where s2.age< s1.age) as cnt** **from student s1** **order by 4** SNO SNAME AGE CNT --- ---------- ---------- ---------- 6 JING 18 0 4 MAGGIE 19 1 1 AARON 20 2 3 DOUG 20 2 8 KAY 20 2 9 GILLIAN 20 2 2 CHUCK 21 6 7 BRIAN 21 6 10 CHAD 21 6 5 STEVE 22 9 Rewriting the solution this way makes it easy to see who the third youngest students are (those whose CNT is 2). The solution using the window function DENSE_RANK is similar to the scalar subquery example in that every row is ranked based on how many students are younger than the current student (ties are allowed and there are no gaps). The following query shows the output from the DENSE_RANK function: **select sno,sname,age,** **dense_rank()over(order by age) as dr** **from student** SNO SNAME AGE DR --- ---------- ---------- ---------- 6 JING 18 1 4 MAGGIE 19 2 1 AARON 20 3 3 DOUG 20 3 8 KAY 20 3 9 GILLIAN 20 3 2 CHUCK 21 4 7 BRIAN 21 4 10 CHAD 21 4 5 STEVE 22 5 The final step is to wrap the query in an inline view and keep only those rows where DR is 3. #### Original solution The original solution uses a two-pass approach: step 1, find the students who are older than three or more students; step 2, find the students who are older than two students who are not amongst the students returned by step 1. Alternatively, Rozenshtein would rephrase this as, "Find students who are older than at least two students and are not older than at least three students." The solution is shown below: **select s5.*** **from student s5,** **student s6,** **student s7** **where s5.age> s6.age** **and s6.age> s7.age** **and s5.sno not in (** **select s1.sno** **from student s1,** **student s2,** **student s3,** **student s4** **where s1.age> s2.age** **and s2.age> s3.age** **and s3.age> s4.age** **)** SNO SNAME AGE --- ------ ---- 1 AARON 20 3 DOUG 20 9 GILLIAN 20 8 KAY 20 The solution above uses the technique shown in Question 5. Refer to Question 5 for a complete discussion of how extremes are found using self joins. ## B.6. Answering Questions Involving "Any" or "All" Queries involving "any" or "all" typically require you to find rows that satisfy one or more conditions completely. For example, if you are asked to find people who eat all vegetables, you are essentially looking for people for whom there is no vegetable that they do not eat. This type of problem statement is typically categorized as _relational division_. With questions regarding "any," it is crucial you pay close attention to how the question is phrased. Consider the difference between these two requirements: "a student who takes any class" and "a plane faster than any train." The former implies, "find a student who takes at least one class," while the latter implies "find a plane that is faster than all trains." ### Question 12 You want to find students who take all courses. The number of courses for a student in table TAKE must be equal to the total number of courses in table COURSES. There are three courses in table COURSES. Only AARON takes all three courses and should be the only student returned. The final result set should be: SNO SNAME AGE --- ------ --- 1 AARON 20 #### MySQL and PostgreSQL Use the aggregate function COUNT to find students who take every course: 1 select s.sno,s.sname,s.age 2 from student s, take t 3 where s.sno = t.sno 4 group by s.sno,s.sname,s.age 5 having count(t.cno) = (select count(*) from courses) #### DB2 and SQL Server Use the window function COUNT OVER and an outer join instead of a subquery: 1 select sno,sname,age 2 from ( 3 select s.sno,s.sname,s.age, 4 count(t.cno) 5 over (partition by s.sno) as cnt, 6 count(distinct c.title) over() as total, 7 row_number() over 8 (partition by s.sno order by c.cno) as rn 9 from courses c 10 left join take t on (c.cno = t.cno) 11 left join student s on (t.sno = s.sno) 12 ) x 13 where cnt = total 14 and rn = 1 #### Oracle Users on Oracle9 _i_ and later can use the DB2 solution. Alternatively, you can use the proprietary Oracle outer-join syntax, which is mandatory for users on 8 _i_ and earlier: 1 select sno,sname,age 2 from ( 3 select s.sno,s.sname,s.age, 4 count(t.cno) 5 over (partition by s.sno) as cnt, 6 count(distinct c.title) over() as total, 7 row_number() over 8 (partition by s.snoorder by c.cno) as rn 9 from courses c, take t, student s 10 where c.cno = t.cno (+) 11 and t.sno = s.sno (+) 12 ) 13 where cnt = total 14 and rn = 1 #### Discussion The aggregate solution uses a subquery to return the total number of courses available. The outer query keeps only students who take the same number of courses as the value returned by the subquery. The window solution takes a different approach: it uses an outer join to table COURSES instead of a subquery. The window solution also uses window functions to return the number of courses a student takes (aliased CNT) along with the total number of courses there are in table COURSES (aliased TOTAL). The query below shows the intermediate results from those window functions: **select s.sno,s.sname,s.age,** **count(distinct t.cno)** **over (partition by s.sno) as cnt,** **count(distinct c.title) over() as total,** **row_number()** **over(partition by s.sno order by c.cno) as rn** **from courses c** **left join take t on (c.cno = t.cno)** **left join student s on (t.sno = s.sno)** **order by 1** SNO SNAME AGE CNT TOTAL RN --- ------ ---- ---- ---------- ---- 1 AARON 20 3 3 1 1 AARON 20 3 3 2 1 AARON 20 3 3 3 2 CHUCK 21 1 3 1 3 DOUG 20 2 3 1 3 DOUG 20 2 3 2 4 MAGGIE 19 2 3 1 4 MAGGIE 19 2 3 2 5 STEVE 22 1 3 1 6 JING 18 2 3 1 6 JING 18 2 3 2 The student who takes all courses is the one where CNT equals TOTAL. ROW_NUMBER is used instead of DISTINCT to filter out the duplicates from the final result set. Strictly speaking, the outer joins to tables TAKE and STUDENT are not necessary, as there are no courses that aren't taken by at least one student. If there is a course that no students take, CNT would not equal TOTAL, and a row with NULL values for SNO, SNAME, and AGE would be returned. The example below creates a new course that no students take. The following query demonstrates what the intermediate result set would look like if there exists a course no students take (for clarity, C.TITLE is included below): **insert into courses values ('CS115','BIOLOGY',4)** **select s.sno,s.sname,s.age,c.title,** **count(distinct t.cno)** **over (partition by s.sno) as cnt,** **count(distinct c.title) over() as total,** **row_number()** **over(partition by s.sno order by c.cno) as rn** **from courses c** **left join take t on (c.cno = t.cno)** **left join student s on (t.sno = s.sno)** **order by 1** SNO SNAME AGE TITLE CNT TOTAL RN --- ------ --- ---------- --- ----- --- 1 AARON 20 PHYSICS 3 4 1 1 AARON 20 CALCULUS 3 4 2 1 AARON 20 HISTORY 3 4 3 2 CHUCK 21 PHYSICS 1 4 1 3 DOUG 20 PHYSICS 2 4 1 3 DOUG 20 HISTORY 2 4 2 4 MAGGIE 19 PHYSICS 2 4 1 4 MAGGIE 19 CALCULUS 2 4 2 5 STEVE 22 CALCULUS 1 4 1 6 JING 18 CALCULUS 2 4 1 6 JING 18 HISTORY 2 4 2 BIOLOGY 0 4 1 Examining these results, it's easy to see no rows will be returned when the final filters are applied. Additionally, keep in mind that window functions take effect after the WHERE clause is evaluated so it is necessary to use DISTINCT when counting the total courses available in table COURSES (otherwise you get the total from the result set, which would be the total number of courses taken by all students, i.e., select count(cno) from take). ### Tip The sample data used for this example does not have any duplicates in table TAKE, so the solution provided works fine. If there had been duplicates in TAKE, for example, a student that takes the same courses three times, the solution would fail. The workaround for dealing with duplicates in this solution is trivial; simply add DISTINCT when performing the count on T.CNO and the solution will work correctly. #### Original solution The original solution avoids aggregates by using a Cartesian product in a devilishly clever way. The query below is based on the original: select * from student where sno not in ( select s.sno from student s, courses c where (s.sno,c.cno) not in (select sno,cno from take) ) Rozenshtein restates the problem to be "Which students are not among those for whom there is a course that they do not take?" If you look at the problem that way, you are now working with negation. Recall how Rozenshtein suggests handling negation: > Remember that real negation requires two passes: To find out "who does not," first find out "who does" and then get rid of them. The innermost subquery returns all valid SNO/CNO combinations. The middle subquery, which uses a Cartesian product between tables STUDENT and COURSES, returns all students and all courses (i.e., every student taking every course) and filters out the valid SNO/CNO combinations (leaving only "made up" SNO/CNO combinations). The outermost query returns only the rows from table STUDENT where the SNO is not amongst those returned by the middle subquery. The following queries may make the solution a bit more clear. To keep it readable, I'll use only AARON and CHUCK (only AARON takes all courses): **select *** **from student** **where sno in ( 1,2 )** SNO SNAME AGE --- ---------- ---- 1 AARON 20 2 CHUCK 21 **select *** **from take** **where sno in ( 1,2 )** SNO CNO --- ----- 1 CS112 1 CS113 1 CS114 2 CS112 **select s.sno, c.cno** **from student s, courses c** **where s.sno in ( 1,2 )** **order by 1** SNO CNO --- ----- 1 CS112 1 CS113 1 CS114 2 CS112 2 CS113 2 CS114 These queries show the rows from table STUDENT for AARON and CHUCK, the courses that AARON and CHUCK take, and a Cartesian product that returns AARON and CHUCK taking all courses, respectively. The result set from the Cartesian product for AARON matches the result set returned for AARON from table TAKE, but CHUCK has two "made up" rows as a result of the Cartesian product that do not match his rows in table TAKE. The following query is the middle subquery and uses NOT IN to filter out the valid SNO/CNO combinations: **select s.sno, c.cno** **from student s, courses c** **where s.sno in ( 1,2 )** **and (s.sno,c.cno) not in (select sno,cno from take)** SNO CNO --- ---- 2 CS113 2 CS114 Notice that AARON is not returned by the middle subquery (because AARON takes all courses). The result set of the middle subquery contains rows that exist due to the Cartesian product, not because CHUCK actually takes those courses. The outermost query then returns rows from table STUDENT where the SNO is not amongst the SNO returned by the middle subquery: **select *** **from student** **where sno in ( 1,2 )** **and sno not in** **(select s.sno from student s, courses c** **where s.sno in ( 1,2 )** **and (s.sno,c.cno) not in (select sno,cno from take))** SNO SNAME AGE --- ---------- ----- 1 AARON 20 ### Question 13 Find students who are older than any other students. You can restate the problem as "Find the oldest students." The final result set should be: SNO SNAME AGE --- -------- ------ 5 STEVE 22 #### MySQL and PostgreSQL Use the aggregate function MAX in a subquery to find the oldest students: 1 select * 2 from student 3 where age = (select max(age) from student) #### DB2, Oracle, and SQL Server Use the window function MAX OVER in an inline view to find the oldest students: 1 select sno,sname,age 2 from ( 3 select s.*, 4 max(s.age)over() as oldest 5 from student s 6 ) x 7 where age = oldest #### Discussion Both solutions use the function MAX to find the oldest student. The subquery solution first finds the greatest age in table STUDENT and returns it to the outer query, which finds student of that age. The window version does the same as the subquery solution but returns the greatest age for each row. The intermediate results of the window query are as follows: **select s.*,** **max(s.age) over() as oldest** **from student s** SNO SNAME AGE OLDEST --- ---------- ---- ---------- 1 AARON 20 22 2 CHUCK 21 22 3 DOUG 20 22 4 MAGGIE 19 22 5 STEVE 22 22 6 JING 18 22 7 BRIAN 21 22 8 KAY 20 22 9 GILLIAN 20 22 10 CHAD 21 22 To find the oldest students, simply keep the rows where AGE = OLDEST. #### Original solution The original solution uses a self join on table STUDENT in a subquery to find all students who are younger than some other student. The outer query returns all students from table STUDENT who are not amongst those returned by the subquery. The operation can be rephrased as "find all students who are not amongst those students who are younger than at least one other student": select * from student where age not in (select a.age from student a, student b where a.age < b.age) The subquery returns use a Cartesian product to find all ages in A that are younger than all ages in B. The only age that would not be younger than any other age is the greatest age. The greatest age is not returned by the subquery. The outer query uses NOT IN to return all rows from table STUDENT where AGE is not amongst the AGE returned by the subquery (if A.AGE is returned, that means there is an AGE somewhere in table STUDENT that is greater than it). If you have trouble understanding how it works, examine the following query. Conceptually they both work in a similar way, but the following is probably more common: select * from student where age >= all (select age from student) ## Index ### A note on the digital index A link in an index entry is displayed as the section title in which that entry appears. Because some sections have multiple index markers, it is not unusual for an entry to have several links to the same section. Clicking on any link will take you directly to the place in the text in which the marker appears. ### Symbols % (modulus) function (SQL Server), SQL Server, MySQL, MySQL % (wildcard) operator, Solution * character in SELECT statements, Retrieving Records \+ (concatenation) operator (SQL Server), SQL Server, SQL Server ### A abstraction, Paradoxes ADDDATE function (MySQL), MySQL, MySQL, MySQL, MySQL ADD_MONTHS function (Oracle), Oracle, Discussion, Oracle, Oracle, Oracle aggregate functions defining rows to perform operation on, Partitions, Partitions grouping and, Relationship Between SELECT and GROUP BY, Windowing multiple tables and, Problem NULL values and, Problem, Paradoxes, Effect of NULLs WHERE clause, Discussion window functions versus, Windowing aliases for CASE expression, Problem inline views, Discussion timing of application, Discussion any or "all" queries, Oracle any or "all" queries, Answering Questions Involving "Any" or "All", Answering Questions Involving "Any" or "All", Discussion, Original solution, Question 13, DB2, Oracle, and SQL Server arithmetic dates difference between dates, Problem seconds/minutes/hours between dates, Oracle and SQL Server AS keyword, Solution at least queries, Answering Questions Involving "at Least", Question 6, Question 7, MySQL and PostgreSQL, Question 8, MySQL and PostgreSQL, Answering Questions Involving "Exactly" at most queries, Answering Questions Involving "at Most", Question 5, MySQL and PostgreSQL, Original solution, Original solution, Answering Questions Involving "at Least" AVG function, Solution axiom of abstraction, Groups are distinct, Groups are distinct axiom of specification, Paradoxes axiom schema of separation, Groups are distinct axiom schema of subsets, Groups are distinct ### B bags, Paradoxes Barber Puzzle, Groups are distinct business logic, DB2, MySQL, PostgreSQL, and SQL Server ### C calendars, Solution CAST function (SQL Server), SQL Server CEIL function (DB2/MySQL/Oracle/PostgreSQL), DB2, Oracle, and SQL Server, PostgreSQL and MySQL CEILING function (SQL Server), DB2, Oracle, and SQL Server, Solution COALESCE function, Discussion, Discussion, Discussion, Solution, DB2, MySQL, PostgreSQL, and SQL Server complex retrieving records rows, Discussion CONCAT function (MySQL), Discussion, MySQL, MySQL concatenation columns, Discussion operator (+) (SQL Server), DB2, Oracle, PostgreSQL, SQL Server operator (||) (DB2/Oracle/PostgreSQL), SQL Server, DB2, PostgreSQL, and Oracle CONNECT BY clause (Oracle) alternatives to, Oracle in hierarchical structures, PostgreSQL and MySQL, PostgreSQL and MySQL, Problem inline views and, Oracle WITH clause and, DB2 and SQL Server, Oracle CONNECT_BY_ISLEAF function (Oracle), Oracle, Oracle CONNECT_BY_ROOT function (Oracle), Oracle, Oracle correlated subqueries, MySQL and SQL Server COUNT function, Solution, Solution, Paradoxes, Effect of NULLs COUNT OVER window function, DB2, Oracle, and SQL Server, A Simple Example CREATE TABLE command, DB2 CREATE TABLE... LIKE command (DB2), DB2 CSV output, Discussion, Discussion CUBE extension, Oracle, SQL Server, Solution CURRENT_DATE function (DB2/MySQL/PostgreSQL), DB2, PostgreSQL and MySQL, DB2 and SQL Server ### D DATE function (DB2), DB2 DATEADD function (MySQL), MySQL DATEADD function (SQL Server), SQL Server, SQL Server, SQL Server DATEDIFF function (MySQL/SQL Server), MySQL and SQL Server, SQL Server, MySQL and SQL Server, MySQL and SQL Server, MySQL DATENAME function (SQL Server), SQL Server, SQL Server, SQL Server, SQL Server, SQL Server DATEPART function (SQL Server), SQL Server, SQL Server, SQL Server, SQL Server, SQL Server dates arithmetic, Date Arithmetic, Discussion business days between dates, Solution, Oracle, Discussion, Discussion, Discussion difference between record and next record, MySQL and SQL Server, DB2, MySQL, PostgreSQL, and SQL Server, Oracle weekdays in year, counting, DB2, Oracle, SQL Server, DB2, DB2, MySQL, MySQL, Oracle, PostgreSQL, PostgreSQL, SQL Server, SQL Server format, Date Arithmetic manipulation, Date Manipulation calendar, DB2, DB2, Oracle, PostgreSQL, MySQL, SQL Server date ranges, identifying overlapping, Solution, Discussion, Discussion, Discussion leap year, Solution, DB2, DB2, DB2, PostgreSQL, MySQL missing dates, Problem, PostgreSQL, SQL Server, PostgreSQL, PostgreSQL, MySQL, SQL Server, Problem quarter start/end dates, Solution, PostgreSQL, DB2, Oracle, MySQL, Solution, PostgreSQL, DB2, DB2, PostgreSQL, MySQL, SQL Server weekdays, first/last in month, PostgreSQL, MySQL year, Problem, Solution, SQL Server, PostgreSQL ORDER BY clause and (DB2), DB2 and Oracle DATE_ADD function (MySQL), MySQL, MySQL, MySQL, MySQL, MySQL DATE_FORMAT function (MySQL), MySQL, MySQL, MySQL, MySQL, MySQL DATE_TRUNC function (PostgreSQL), PostgreSQL, PostgreSQL, SQL Server, PostgreSQL, PostgreSQL DAY function (DB2), DB2, DB2, MySQL DAY function (MySQL), MySQL, MySQL, MySQL, MySQL DAY function (SQL Server), SQL Server, SQL Server, MySQL DAYNAME function (DB2/MySQL/SQL Server), DB2, DB2 and MySQL DAYOFWEEK function (DB2/MYSQL), Oracle, PostgreSQL and MySQL, DB2 DAYOFYEAR function (DB2/MySQL/SQL Server), MySQL, DB2, DB2, MySQL, SQL Server DAYS function (DB2), Solution, DB2, Solution DB2 DATE values in ORDER BY clause, MySQL, PostgreSQL, and SQL Server DECODE function (Oracle), Oracle, Discussion DEFAULT keyword, Solution DEFAULT VALUES clause (PostgreSQL/SQL Server), Solution DELETE command, Solution, Solution deleting records all, Discussion that violate integrity, Problem with NULLs (DB2/Oracle/SQL Server), DB2, Oracle, and SQL Server with NULLs (PostgreSQL/MySQL), PostgreSQL and MySQL, PostgreSQL and MySQL delimited data, MySQL delimited lists, DB2, PostgreSQL, Discussion, Oracle, Problem DENSE_RANK function (DB2/Oracle/SQL Server), DB2, Oracle, and SQL Server, Oracle, Oracle DENSE_RANK OVER window function (DB2/Oracle/SQL Server), DB2, Oracle, and SQL Server, Solution, Solution, Discussion DISTINCT keyword alternatives to, Discussion, MySQL and PostgreSQL SELECT list and, Discussion, MySQL and PostgreSQL, Groups are distinct uses for, MySQL and SQL Server, Problem, Problem duplicates suppressing, Solution dynamic SQL, Problem ### E equi-join operations, Discussion, Problem exactly queries, Answering Questions Involving "Exactly", Discussion, Question 10, Discussion, Question 11, Answering Questions Involving "Any" or "All" EXCEPT function, DB2 and PostgreSQL, DB2 and PostgreSQL, Solution, DB2, Oracle, and PostgreSQL EXTRACT function (PostgreSQL/MySQL), PostgreSQL, PostgreSQL and MySQL extreme values, Problem ### F foreign keys, Discussion, DB2, MySQL, SQL Server framing clause, Solution, When Order Matters, The Framing Clause, The Framing Clause, A Framing Finale, A Framing Finale Frege, Paradoxes Frege's axiom, Groups are distinct, Paradoxes ### G GENERATE_SERIES function (PostgreSQL) alternatives to, PostgreSQL, Oracle, Oracle, PostgreSQL and MySQL GETDATE function (SQL Server), DB2 and SQL Server, DB2 and SQL Server GROUP BY clause, Discussion, MySQL and PostgreSQL, Relationship Between SELECT and GROUP BY, Relationship Between SELECT and GROUP BY, Relationship Between SELECT and GROUP BY GROUP BY queries, PostgreSQL and MySQL, Problem, DB2, Oracle, and SQL Server, DB2, Oracle, and SQL Server, PostgreSQL and MySQL, PostgreSQL and MySQL grouping aggregate functions and, Relationship Between SELECT and GROUP BY, Relationship Between SELECT and GROUP BY by time units, Discussion, Solution, Discussion, Discussion, Problem characteristics of, Definition of an SQL Group, Groups are distinct, Groups are distinct, Groups are distinct COUNT function and, Solution defined, Definition of an SQL Group examples, Grouping NULLs and, Paradoxes reasons for, Grouping SELECT clause and, Discussion, Relationship Between SELECT and GROUP BY, Relationship Between SELECT and GROUP BY, Relationship Between SELECT and GROUP BY SUM function and, Solution GROUPING function (DB2/Oracle/SQL Server), SQL Server and MySQL, DB2 and Oracle, Solution, Discussion GROUPING function (MySQL/PostgreSQL), MySQL and PostgreSQL GROUPING SETS extension (DB2/Oracle), Oracle, DB2, and SQL Server, Oracle, DB2, and SQL Server, Oracle, DB2, and SQL Server ### H hierarchies node type, Oracle, DB2, PostgreSQL, MySQL, and SQL Server, DB2, PostgreSQL, MySQL, and SQL Server, DB2, PostgreSQL, MySQL, and SQL Server, DB2, PostgreSQL, MySQL, and SQL Server, DB2, PostgreSQL, MySQL, and SQL Server, Oracle problematic nature of, Hierarchical Queries tree versus recursive structure, Solution HOUR function (DB2), DB2 ### I IF-ELSE operations, Problem indexes listing, DB2 information schema (MySQL/PostgreSQL/SQL Server), PostgreSQL, MySQL, and SQL Server inner joins, Discussion, Problem INSERT ALL statement (Oracle), Oracle INSERT FIRST statement (Oracle), Oracle INSERT statement, Solution, Discussion inserting records into multiple tables, Oracle, Oracle with default values, Solution INSTR function (Oracle), Solution, Solution, Solution INTERSECT operation, Solution, DB2, Oracle, and PostgreSQL INTERVAL keyword, PostgreSQL, Discussion IS NULL, Solution ITERATE command (Oracle), Oracle ITERATION_NUMBER function (Oracle), Oracle ### J JOIN clause in FROM clause, Discussion Oracle support for, Oracle joins anti-, Discussion equi-, Discussion, Problem inner, Discussion scalar subqueries and, Discussion selecting columns, Discussion ### K KEEP extension (Oracle), Oracle, Oracle, Oracle keys foreign, MySQL, Discussion Knight values, Problem, Solution Kyte, Discussion ### L LAG function (Oracle), Oracle LAG OVER window function (Oracle), Solution, Oracle, Oracle, Solution, Oracle, Oracle, Solution, Oracle LAST function (Oracle), Oracle, Oracle LAST_DAY function (MySQL/Oracle), Oracle, MySQL, Oracle, MySQL, Oracle LEAD function (Oracle), Oracle, Oracle LEAD OVER window function (Oracle) duplicates and, Oracle self joins and, Discussion, Discussion, DB2, MySQL, PostgreSQL, and SQL Server, Oracle uses, Oracle LIKE operator, Solution LIMIT clause (MySQL/PostgreSQL), MySQL and PostgreSQL, MySQL and PostgreSQL, MySQL and PostgreSQL logarithms, DB2 and Oracle loop functionality, Working with Strings LPAD function (Oracle/PostgreSQL/MySQL), Oracle, Oracle, PostgreSQL, and MySQL LTRIM function (Oracle), Oracle ### M MAX function, SQL Server MAX OVER window function, DB2, Oracle, and SQL Server, Oracle, Solution MEASURES subclause of MODEL clause (Oracle), Discussion MEDIAN function (Oracle), MySQL and PostgreSQL MERGE statement, Inserting, Updating, Deleting, Solution metadata, Metadata Queries columns in table, Problem data dictionary, Problem foreign keys without indexes, Problem MIN OVER window function (DB2/Oracle/SQL Server), PostgreSQL and MySQL, DB2, Oracle, and SQL Server, Oracle minimum values, Problem, Discussion, MySQL and PostgreSQL, Oracle MINUS operation, Oracle, Solution, DB2, Oracle, and PostgreSQL MINUTE function (DB2), DB2 MOD function (DB2), DB2 and SQL Server MODEL clause (Oracle) uses, Discussion modes, Oracle modifying records changing row data, Problem using queries for new values, Discussion with values from another table, Problem, Discussion, Oracle modulus (%) function (SQL Server), SQL Server, MySQL MONTH function (DB2/MySQL), DB2 and MySQL, DB2, DB2, PostgreSQL and MySQL MONTHNAME function (DB2/MySQL), DB2 and MySQL, DB2 MONTHS_BETWEEN function (Oracle), Oracle, Oracle and SQL Server multiple tables inserting data into, Problem retrieving data from, Working with Multiple Tables, Discussion, Discussion, DB2 and PostgreSQL, Problem, Solution, Discussion, Discussion, Problem, Discussion, Problem, Oracle, Solution, Oracle comparing, Solution, Discussion, MySQL and SQL Server, MySQL and SQL Server joins when aggregates are used, Problem, Solution, MySQL and PostgreSQL missing data from multiple tables, Problem, Solution outer joins when using aggregates, Solution, Oracle values nonexistant in all tables, Discussion, DB2 and PostgreSQL, MySQL and SQL Server, MySQL and SQL Server multisets, Paradoxes ### N names, Solution, MySQL negation queries, Answering Questions Involving Negation, Original solution, Original solution A only, Discussion, Question 3, Discussion, Original solution A or B but not both, Original solution, DB2, Oracle, and SQL Server, Discussion not A, Question 1, MySQL and PostgreSQL, Discussion, Original solution NEXT_DAY function (Oracle), Oracle, Oracle, Oracle NOT EXISTS, Solution NOT IN operator, MySQL and SQL Server NROWS function (DB2/SQL Server), DB2 and SQL Server NTILE window function (Oracle/SQL Server), Solution, Oracle and SQL Server, Oracle and SQL Server NULL paradox, Groups are distinct, Paradoxes, Paradoxes, Paradoxes NULLs aggregate functions and, Problem, Paradoxes, Effect of NULLs AVG function and, Discussion comparisons to, Problem, Discussion groups and, Paradoxes MIN/MAX functions and, Discussion sorting and, Solution, Oracle, Discussion window functions and, Partitions, When Order Matters numbers queries percentage of total, Solution, DB2, Oracle, and SQL Server percentage relative to total, Solution subtotals, DB2 and Oracle, DB2 and Oracle, SQL Server and MySQL subtotals for all combinations, Solution, Oracle, Oracle, DB2, and SQL Server, Oracle, DB2, and SQL Server, Oracle, DB2, and SQL Server, Oracle, DB2, and SQL Server, Oracle, DB2, and SQL Server, PostgreSQL and MySQL NVL function (Oracle), Oracle ### O OFFSET clause (MySQL/PostgreSQL), MySQL and PostgreSQL, MySQL and PostgreSQL Optimizing Transact-SQL: Advanced Programming Techniques (Rozenshtein et al.), Solution Oracle object types, Solution ORDER BY clause, Discussion, Solution, Solution, DB2 and Oracle, When Order Matters outer joins OR logic in, Problem, Oracle Oracle syntax, Oracle, Oracle, Oracle, Oracle, Oracle, Oracle OVER keyword, Discussion, A Simple Example ### P PARTITION BY clause, Partitions, Partitions, Partitions, Effect of NULLs partitions ORDER BY clause and, When Order Matters percentage calculations, DB2, Oracle, and SQL Server, Problem, Discussion PERCENTILE_CONT function (Oracle), Oracle, Oracle PIVOT operator (SQL Server), Discussion pivoting multiple rows, DB2, Oracle, and SQL Server, DB2, Oracle, and SQL Server, PostgreSQL and MySQL, PostgreSQL and MySQL, Solution ranked result sets, Solution, Discussion, Discussion, Problem subtotals, Solution, Discussion PostgreSQL PRIOR keyword (Oracle), Oracle ### Q QUARTER function (DB2/MySQL), MySQL, DB2, MySQL queries strings alphanumeric, Problem ### R RANDOM function, PostgreSQL random records, Problem, PostgreSQL RANGE BETWEEN clause, When Order Matters, The Framing Clause, The Framing Clause, A Framing Finale ranges consecutive, Working with Ranges, Problem differences between rows in group, DB2, MySQL, PostgreSQL, and SQL Server, Oracle, Oracle, Oracle missing values, Solution RATIO_TO_REPORT function (Oracle), Solution reciprocal rows, Discussion REGEXP_REPLACE function (Oracle), Discussion Regular Expression Anti-Patterns(Gennick), Discussion regular expressions (Oracle), Solution, Discussion relational division, Answering Questions Involving "Any" or "All" REPEAT function (DB2), DB2 REPLACE function, Oracle and PostgreSQL, Solution, Solution, Solution, Solution REPLICATE function (SQL Server), SQL Server result set, Solution, Discussion, Discussion, Problem retrieving data from multiple tables columns with same data type, Problem retrieving records complex, Solution aggregating over moving value range, DB2, Oracle, and SQL Server, DB2 and Oracle, DB2 and Oracle, DB2 and Oracle non-GROUP BY columns, returning, Problem, DB2, Oracle, and SQL Server, DB2, Oracle, and SQL Server, PostgreSQL and MySQL, PostgreSQL and MySQL repeating values, suppressing, Problem subtotals, Problem, SQL Server and MySQL simple, Discussion random, Solution, Oracle reverse pivoting result sets, PostgreSQL and MySQL ROLLUP extension of GROUP BY(DB2/Oracle), DB2 and Oracle, Solution, Solution row generation, Problem, Problem, DB2 and SQL Server, MySQL ROWNUM function (Oracle), Oracle, Oracle, DB2, Oracle, and SQL Server ROW_NUMBER function (DB2/SQL Server), SQL Server ROW_NUMBER OVER window function (DB2/Oracle/SQL Server) ORDER BY clause and, DB2, Oracle, and SQL Server uniqueness of result, DB2, Oracle, and SQL Server uses, DB2, DB2, Oracle, and SQL Server RPAD function (Oracle), Discussion RTRIM function (Oracle/PostgreSQL), Oracle and PostgreSQL RULES subclause (Oracle), Discussion running differences, MySQL, PostgreSQL, and SQL Server running products, Solution, DB2 and Oracle, DB2 and Oracle, MySQL, PostgreSQL, and SQL Server running totals, MySQL, PostgreSQL, and SQL Server, DB2 and Oracle, DB2 and Oracle Russell, Groups are distinct Russell's Paradox, Groups are distinct ### S scalar subqueries converting to composite (Oracle), Solution, Discussion joins and, Solution, Discussion scripts, Problem searching, Advanced Searching duplicates, Solution, DB2, Oracle, and SQL Server for text not matching pattern (Oracle), Discussion, Problem, Discussion, Discussion Knight values, Problem results, Advanced Searching, MySQL and PostgreSQL row values, Oracle, Oracle, Oracle rows, DB2, Oracle, and SQL Server, DB2, MySQL, PostgreSQL, and SQL Server, Oracle rows from table, DB2, Oracle, and SQL Server, MySQL and PostgreSQL, MySQL and PostgreSQL top n records, DB2, Oracle, and SQL Server, DB2, Oracle, and SQL Server SECOND function (DB2), DB2 SELECT statements DISTINCT keyword and, Groups are distinct GROUP BY and, Discussion, Paradoxes, Relationship Between SELECT and GROUP BY, Relationship Between SELECT and GROUP BY self joins alternatives to, Discussion, Discussion, Problem, DB2, MySQL, PostgreSQL, and SQL Server serialized data, Solution, Discussion set differences, Discussion set operations generally, Working with Multiple Tables, Discussion, Discussion SIGN function (MySQL/PostgreSQL), PostgreSQL and MySQL simple retrieving records columns, Problem, Discussion sorting records, Sorting Query Results, Problem, Discussion nulls and, DB2, MySQL, PostgreSQL, and SQL Server, DB2, MySQL, PostgreSQL, and SQL Server, DB2, MySQL, PostgreSQL, and SQL Server, Oracle, Oracle, Discussion on data dependent key, Discussion on multiple fields, Discussion on single field, Sorting Query Results strings, Solution, Discussion, Discussion specification, Groups are distinct START WITH clause (Oracle), Oracle, Oracle Stoll, Groups are distinct strings queries, Discussion, Oracle alphanumeric status, Solution, DB2, SQL Server, DB2, Oracle, and PostgreSQL, SQL Server initials, extracting from name, MySQL, DB2, Oracle and PostgreSQL, MySQL IP Address parsing, DB2, Oracle numeric content, Problem, DB2, Oracle, PostgreSQL, DB2, Oracle, and PostgreSQL, MySQL ordering by number, DB2, Oracle, Discussion, Problem parsing into rows, Solution searching for mixed alphanumeric, Discussion separating numeric and character data, Solution, Discussion, Discussion, Discussion STR_TO_DATE function (MySQL), MySQL subqueries correlated, MySQL and SQL Server SUBSTR function (DB2/MySQL/Oracle/PostgreSQL), DB2, MySQL, Oracle, and PostgreSQL, Solution, DB2 and SQL Server SUBSTRING function (SQL Server), SQL Server, SQL Server, SQL Server subtotals pivoting result set with, Discussion SUM function, Solution, Discussion SUM OVER window function (DB2/Oracle/SQL Server), DB2, Oracle, and SQL Server, Oracle, MySQL, PostgreSQL, and SQL Server, DB2 and Oracle, DB2, Oracle, and SQL Server SYS_CONNECT_BY_PATH function (Oracle), Oracle, Oracle, Oracle ### T tables creating and copying definition, Discussion testing for existence of value within group, Problem, Problem The Essence of SQL (Rozenshtein), Rozenshtein Revisited time grouping rows by, Solution, Discussion, Discussion TIMESTAMP types (Oracle), Discussion TO_BASE function (Oracle), Discussion TO_CHAR function (Oracle/PostgreSQL), Oracle, Oracle, Oracle, PostgreSQL and MySQL TO_DATE function (Oracle/PostgreSQL), Oracle, PostgreSQL TO_NUMBER function (Oracle/PostgreSQL), Oracle, Oracle TRANSLATE function (DB2/Oracle/PostgreSQL), MySQL and SQL Server, Solution, Solution, SQL Server, Solution transposing result sets (Oracle), Discussion, Discussion, Discussion TRUNC function (Oracle), Oracle, Oracle, Oracle, Oracle ### U underscore (_) operator, Discussion Understanding the WITH Clause(Gennick), DB2 and SQL Server UNION ALL operation, Solution, DB2 and PostgreSQL, Paradoxes UNION operation, Solution, Discussion, Discussion, Paradoxes UNPIVOT operator (SQL Server), Solution, Solution UPDATE statement, Solution, Solution, Solution, PostgreSQL, PostgreSQL, SQL Server, and MySQL ### V VALUES clause, Solution version differences Oracle CONNECT BY clause, Oracle, Oracle, Oracle, Oracle DEFAULT keyword, Solution JOIN clause, Oracle, DB2, MySQL, PostgreSQL, and SQL Server KEEP clause, Oracle, Oracle LEAD OVER window function, Oracle MEDIAN/PERCENTILE_CONT functions, Oracle, Oracle MODEL clause, DB2 and Oracle, Solution outer joins, Discussion ### W WHERE clause, Discussion wildcard (%) operator, Solution window functions aggregate functions versus, A Simple Example evaluation order, Order of Evaluation NULLs and, Effect of NULLs, Effect of NULLs ORDER BY subclause, When Order Matters partitions, Partitions reports and, Providing a Base timing of, DB2, MySQL, PostgreSQL, and SQL Server, Oracle, DB2, Oracle, and SQL Server WITH clause (DB2/SQL Server), Solution, DB2 and SQL Server, Problem WITH clause (Oracle), Oracle WITH ROLLUP (SQL Server/MySQL), SQL Server and MySQL ### Y YEAR function (DB2/MySQL/SQL Server), DB2 and MySQL, DB2, Problem, PostgreSQL and MySQL Young, Problem YS_CONNECT_BY_PATH function (Oracle), Oracle ### Z Zermelo, Groups are distinct ## About the Author Anthony Molinaro is a SQL developer and database administrator with many years experience in helping developers improve their SQL queries. SQL is particular passion of Anthony's, and he's become known as the go-to guy among his clients when it comes to solving difficult SQL query problems. He's well-read, understands relational theory well, and has nine years of hands-on experience solving tough, SQL problems. Anthony is particularly well-acquainted with new and powerful SQL features such as the windowing function syntax that was added to the most recent SQL standard. ## Colophon Our look is the result of reader comments, our own experimentation, and feedback from distribution channels. Distinctive covers complement our distinctive approach to technical topics, breathing personality and life into potentially dry subjects. The animal on the cover of _SQL Cookbook_ is an Agamid lizard. These lizards belong to the Agamidae family and have more than 300 species among them. Agamids can be found in Africa, Asia, Australia, and Southern Europe, and are characterized by strong legs and—in some varieties—the ability to change color. Unlike other species of lizards, agamids cannot regenerate their tails if they lose them. They can be found in varied environments from hot deserts to warm, wet tropical rainforests. Several species of agamids are popular as pets. Among these are the Bearded Dragon (genus _Pogona_ ). Calm, yet curious, these creatures grow to be only about 20 inches. Even with their small stature, they are still considered "giant" lizards, and therefore require ample space. Males are generally territorial and, although they are social animals, overcrowding can lead to stress, especially when the animals have no place to hide. Overcrowding can lead to injuries from fighting such as lost toes and tails, as well as a loss of appetite. The head of the bearded lizard is triangular in shape and features many spikes protruding from its chin. These spikes resemble whiskers (thus the name). The spikes are also found along its side. Bearded dragons open their mouths and display their spiky beards to scare predators and other beardeds. They also can flatten their bodies to appear larger. As pets, they may stop displaying their beards once they become comfortable with their owners and habitats. Although they originated in Australia, the bearded dragons sold by U.S. dealers are descendants of animals that were imported from Europe. This is due to Australia's strict export laws regarding wildlife. The Flying Lizard ( _draco volans_ ) is another varied example of an agamid lizard. Measuring slightly less than 12 inches, this animal has a long, thin body with flaps of skin along its ribs. The male flying lizard will claim two to three trees for its territory with one to three females living in each tree. In order to transport itself from one place to another, it glides from trees or other high places by extending its skin flaps like wings. However, it usually does not fly in rain or wind. When threatened, the flying lizard may also extend its skin flaps to appear larger. Another interesting variety of the agamidae family is the Red Headed Rock Agama ( _Agama agama_ ) found in sub-Saharan Africa. These creatures often live in groups of 10 to 20 with an older male acting as the group's "leader." At night, their coloring is dark brown, but at dawn, their bodies change to light blue with a bright orange head and tail. Their skin coloring changes with their mood, acting like a virtual mood ring. For example, when males fight, their heads will become brown, while white spots appear along the body. Darren Kelly was the production editor for _SQL Cookbook_. Kenneth Kimball was the copyeditor and Karmyn Guthrie was the proofreader. nSight, Inc. provided production services. Jamie Peppard and Genevieve d'Entremont provided quality control. Jansen Fernald provided production support Beth Palmer wrote the index. Karen Montgomery designed the cover of this book, based on a series design by Edie Freedman. The cover image is a 19th-century engraving from the Dover Pictorial Archive. Karen Montgomery produced the cover layout with Adobe InDesign CS using Adobe's ITC Garamond font. David Futato designed the interior layout. This book was converted by Keith Fahlgren to FrameMaker 5.5.6 with a format conversion tool created by Erik Ray, Jason McIntosh, Neil Walls, and Mike Sierra that uses Perl and XML technologies. The text font is Linotype Birka; the heading font is Adobe Myriad Condensed; and the code font is LucasFont's TheSans Mono Condensed. The illustrations that appear in the book were produced by Robert Romano, Jessamyn Read, and Lesley Borash using Macromedia FreeHand MX and Adobe Photoshop CS. The tip and warning icons were drawn by Christopher Bing. This colophon was written by Jansen Fernald. ## Special Upgrade Offer If you purchased this ebook from a retailer other than O'Reilly, you can upgrade it for $4.99 at oreilly.com by clicking here. ## # SQL Cookbook ### Anthony Molinaro #### Editor ### Jonathan Gennick Copyright © 2009 O'Reilly Media, Inc. O'Reilly Media 1005 Gravenstein Highway North Sebastopol, CA 95472 2013-09-26T12:08:38-07:00 # SQL Cookbook Table of Contents 1. Dedication 2. Special Upgrade Offer 3. A Note Regarding Supplemental Files 4. Preface 1. Why I Wrote This Book 2. Objectives of This Book 3. Audience for This Book 4. How to Use This Book 5. What's Missing from This Book 6. Structure of This Book 7. Platform and Version 8. Tables Used in This Book 9. Conventions Used in This Book 10. Using Code Examples 11. Comments and Questions 12. Safari® Enabled 13. Acknowledgments 5. 1. Retrieving Records 1. 1.1. Retrieving All Rows and Columns from a Table 2. 1.2. Retrieving a Subset of Rows from a Table 3. 1.3. Finding Rows That Satisfy Multiple Conditions 4. 1.4. Retrieving a Subset of Columns from a Table 5. 1.5. Providing Meaningful Names for Columns 6. 1.6. Referencing an Aliased Column in the WHERE Clause 7. 1.7. Concatenating Column Values 8. 1.8. Using Conditional Logic in a SELECT Statement 9. 1.9. Limiting the Number of Rows Returned 10. 1.10. Returning _n_ Random Records from a Table 11. 1.11. Finding Null Values 12. 1.12. Transforming Nulls into Real Values 13. 1.13. Searching for Patterns 6. 2. Sorting Query Results 1. 2.1. Returning Query Results in a Specified Order 2. 2.2. Sorting by Multiple Fields 3. 2.3. Sorting by Substrings 4. 2.4. Sorting Mixed Alphanumeric Data 5. 2.5. Dealing with Nulls when Sorting 6. 2.6. Sorting on a Data Dependent Key 7. 3. Working with Multiple Tables 1. 3.1. Stacking One Rowset atop Another 2. 3.2. Combining Related Rows 3. 3.3. Finding Rows in Common Between Two Tables 4. 3.4. Retrieving Values from One Table That Do Not Exist in Another 5. 3.5. Retrieving Rows from One Table That Do Not Correspond to Rows in Another 6. 3.6. Adding Joins to a Query Without Interfering with Other Joins 7. 3.7. Determining Whether Two Tables Have the Same Data 8. 3.8. Identifying and Avoiding Cartesian Products 9. 3.9. Performing Joins when Using Aggregates 10. 3.10. Performing Outer Joins when Using Aggregates 11. 3.11. Returning Missing Data from Multiple Tables 12. 3.12. Using NULLs in Operations and Comparisons 8. 4. Inserting, Updating, Deleting 1. 4.1. Inserting a New Record 2. 4.2. Inserting Default Values 3. 4.3. Overriding a Default Value with NULL 4. 4.4. Copying Rows from One Table into Another 5. 4.5. Copying a Table Definition 6. 4.6. Inserting into Multiple Tables at Once 7. 4.7. Blocking Inserts to Certain Columns 8. 4.8. Modifying Records in a Table 9. 4.9. Updating when Corresponding Rows Exist 10. 4.10. Updating with Values from Another Table 11. 4.11. Merging Records 12. 4.12. Deleting All Records from a Table 13. 4.13. Deleting Specific Records 14. 4.14. Deleting a Single Record 15. 4.15. Deleting Referential Integrity Violations 16. 4.16. Deleting Duplicate Records 17. 4.17. Deleting Records Referenced from Another Table 9. 5. Metadata Queries 1. 5.1. Listing Tables in a Schema 2. 5.2. Listing a Table's Columns 3. 5.3. Listing Indexed Columns for a Table 4. 5.4. Listing Constraints on a Table 5. 5.5. Listing Foreign Keys Without Corresponding Indexes 6. 5.6. Using SQL to Generate SQL 7. 5.7. Describing the Data Dictionary Views in an Oracle Database 10. 6. Working with Strings 1. 6.1. Walking a String 2. 6.2. Embedding Quotes Within String Literals 3. 6.3. Counting the Occurrences of a Character in a String 4. 6.4. Removing Unwanted Characters from a String 5. 6.5. Separating Numeric and Character Data 6. 6.6. Determining Whether a String Is Alphanumeric 7. 6.7. Extracting Initials from a Name 8. 6.8. Ordering by Parts of a String 9. 6.9. Ordering by a Number in a String 10. 6.10. Creating a Delimited List from Table Rows 11. 6.11. Converting Delimited Data into a Multi-Valued IN-List 12. 6.12. Alphabetizing a String 13. 6.13. Identifying Strings That Can Be Treated as Numbers 14. 6.14. Extracting the _n_ th Delimited Substring 15. 6.15. Parsing an IP Address 11. 7. Working with Numbers 1. 7.1. Computing an Average 2. 7.2. Finding the Min/Max Value in a Column 3. 7.3. Summing the Values in a Column 4. 7.4. Counting Rows in a Table 5. 7.5. Counting Values in a Column 6. 7.6. Generating a Running Total 7. 7.7. Generating a Running Product 8. 7.8. Calculating a Running Difference 9. 7.9. Calculating a Mode 10. 7.10. Calculating a Median 11. 7.11. Determining the Percentage of a Total 12. 7.12. Aggregating Nullable Columns 13. 7.13. Computing Averages Without High and Low Values 14. 7.14. Converting Alphanumeric Strings into Numbers 15. 7.15. Changing Values in a Running Total 12. 8. Date Arithmetic 1. 8.1. Adding and Subtracting Days, Months, and Years 2. 8.2. Determining the Number of Days Between Two Dates 3. 8.3. Determining the Number of Business Days Between Two Dates 4. 8.4. Determining the Number of Months or Years Between Two Dates 5. 8.5. Determining the Number of Seconds, Minutes, or Hours Between Two Dates 6. 8.6. Counting the Occurrences of Weekdays in a Year 7. 8.7. Determining the Date Difference Between the Current Record and the Next Record 13. 9. Date Manipulation 1. 9.1. Determining if a Year Is a Leap Year 2. 9.2. Determining the Number of Days in a Year 3. 9.3. Extracting Units of Time from a Date 4. 9.4. Determining the First and Last Day of a Month 5. 9.5. Determining All Dates for a Particular Weekday Throughout a Year 6. 9.6. Determining the Date of the First and Last Occurrence of a Specific Weekday in a Month 7. 9.7. Creating a Calendar 8. 9.8. Listing Quarter Start and End Dates for the Year 9. 9.9. Determining Quarter Start and End Dates for a Given Quarter 10. 9.10. Filling in Missing Dates 11. 9.11. Searching on Specific Units of Time 12. 9.12. Comparing Records Using Specific Parts of a Date 13. 9.13. Identifying Overlapping Date Ranges 14. 10. Working with Ranges 1. 10.1. Locating a Range of Consecutive Values 2. 10.2. Finding Differences Between Rows in the Same Group or Partition 3. 10.3. Locating the Beginning and End of a Range of Consecutive Values 4. 10.4. Filling in Missing Values in a Range of Values 5. 10.5. Generating Consecutive Numeric Values 15. 11. Advanced Searching 1. 11.1. Paginating Through a Result Set 2. 11.2. Skipping n Rows from a Table 3. 11.3. Incorporating OR Logic when Using Outer Joins 4. 11.4. Determining Which Rows Are Reciprocals 5. 11.5. Selecting the Top n Records 6. 11.6. Finding Records with the Highest and Lowest Values 7. 11.7. Investigating Future Rows 8. 11.8. Shifting Row Values 9. 11.9. Ranking Results 10. 11.10. Suppressing Duplicates 11. 11.11. Finding Knight Values 12. 11.12. Generating Simple Forecasts 16. 12. Reporting and Warehousing 1. 12.1. Pivoting a Result Set into One Row 2. 12.2. Pivoting a Result Set into Multiple Rows 3. 12.3. Reverse Pivoting a Result Set 4. 12.4. Reverse Pivoting a Result Set into One Column 5. 12.5. Suppressing Repeating Values from a Result Set 6. 12.6. Pivoting a Result Set to Facilitate Inter-Row Calculations 7. 12.7. Creating Buckets of Data, of a Fixed Size 8. 12.8. Creating a Predefined Number of Buckets 9. 12.9. Creating Horizontal Histograms 10. 12.10. Creating Vertical Histograms 11. 12.11. Returning Non-GROUP BY Columns 12. 12.12. Calculating Simple Subtotals 13. 12.13. Calculating Subtotals for All Possible Expression Combinations 14. 12.14. Identifying Rows That Are Not Subtotals 15. 12.15. Using Case Expressions to Flag Rows 16. 12.16. Creating a Sparse Matrix 17. 12.17. Grouping Rows by Units of Time 18. 12.18. Performing Aggregations over Different Groups/Partitions Simultaneously 19. 12.19. Performing Aggregations over a Moving Range of Values 20. 12.20. Pivoting a Result Set with Subtotals 17. 13. Hierarchical Queries 1. 13.1. Expressing a Parent-Child Relationship 2. 13.2. Expressing a Child-Parent-Grandparent Relationship 3. 13.3. Creating a Hierarchical View of a Table 4. 13.4. Finding All Child Rows for a Given Parent Row 5. 13.5. Determining Which Rows Are Leaf, Branch, or Root Nodes 18. 14. Odds 'n' Ends 1. 14.1. Creating Cross-Tab Reports Using SQL Server's PIVOT Operator 2. 14.2. Unpivoting a Cross-Tab Report Using SQL Server's UNPIVOT Operator 3. 14.3. Transposing a Result Set Using Oracle's MODEL Clause 4. 14.4. Extracting Elements of a String from Unfixed Locations 5. 14.5. Finding the Number of Days in a Year (an Alternate Solution for Oracle) 6. 14.6. Searching for Mixed Alphanumeric Strings 7. 14.7. Converting Whole Numbers to Binary Using Oracle 8. 14.8. Pivoting a Ranked Result Set 9. 14.9. Adding a Column Header into a Double Pivoted Result Set 10. 14.10. Converting a Scalar Subquery to a Composite Subquery in Oracle 11. 14.11. Parsing Serialized Data into Rows 12. 14.12. Calculating Percent Relative to Total 13. 14.13. Creating CSV Output from Oracle 14. 14.14. Finding Text Not Matching a Pattern (Oracle) 15. 14.15. Transforming Data with an Inline View 16. 14.16. Testing for Existence of a Value Within a Group 19. A. Window Function Refresher 1. A.1. Grouping 2. A.2. Windowing 20. B. Rozenshtein Revisited 1. B.1. Rozenshtein's Example Tables 2. B.2. Answering Questions Involving Negation 3. B.3. Answering Questions Involving "at Most" 4. B.4. Answering Questions Involving "at Least" 5. B.5. Answering Questions Involving "Exactly" 6. B.6. Answering Questions Involving "Any" or "All" 21. Index 22. About the Author 23. Colophon 24. Special Upgrade Offer 25. Copyright
{ "redpajama_set_name": "RedPajamaBook" }
3,379
{"url":"http:\/\/math.stackexchange.com\/questions\/215493\/division-by-two-in-set-theory","text":"# Division by two in set theory\n\nLet $A,B$ be two sets such that $2A \\cong 2B$ (here $2A := A \\coprod A$). Then $A \\cong B$. This can be proven without the axiom of choice, which means that one can explicitly construct a bijection $A \\to B$ out of a bijection $2A \\to 2B$. This is non-trivial and interesting, see the wonderful paper by Conway, Doyle, also for generalizations. The construction is infinitary, and therefore the following question comes into my mind.\n\nQuestion. Is the assertion also true in ZF - {Axiom of Infinity}?\n\n-\n\nThe axiom of infinity is equivalent to there being some infinite set. So either all sets are finite, in which case the result obviously holds by simple induction, or the axiom of infinity holds and one can apply the infinitary proof.\n\n-\nHm, I don't understand. How do you define \"infinite\" at all without refering to $\\mathbb{N}$? So what is the formalization of your first sentence in ZF? And how does your remark explicitly produce a proof of the assertion which does not use $\\mathbb{N}$? \u2013\u00a0 Martin Brandenburg Oct 17 '12 at 8:07\n@MartinBrandenburg: A set is infinite if it not finite. A set is finite if it has the same cardinality as a natural number. A natural number is a successor ordinal that has only zero and successor ordinals as predecessors. Induction with natural numbers works even when the set of natural numbers forms a proper class- just like induction on ordinals. \u2013\u00a0 Michael Greinecker Oct 17 '12 at 8:13\nZero is not a successor ordinal, though. \u2013\u00a0 Zhen Lin Oct 17 '12 at 10:10\n@ZhenLin That's true. So one has to add zero to this definition. \u2013\u00a0 Michael Greinecker Oct 17 '12 at 12:48","date":"2015-05-27 10:34:25","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.959125280380249, \"perplexity\": 193.8170720886346}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 20, \"end_threshold\": 5, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2015-22\/segments\/1432207928923.85\/warc\/CC-MAIN-20150521113208-00233-ip-10-180-206-219.ec2.internal.warc.gz\"}"}
null
null
\section{Introduction and Statement of Results} Given a finite, simple graph $G = (V(G),E(G))$, an independent set $I$ is a subset of $V(G)$ so that if $v,w \in I$, then $vw \notin E(G)$. The \emph{size} of an independent set is $|I|$. We will let $i(G)$ denote the number of independent sets in $G$ and $i_t(G)$ denote the number of independent sets of size $t$ in $G$. The quantity $i(G)$ has also been called the \emph{Fibonacci number} of $G$ \cite{ProdingerTichy} and the \emph{Merrifield-Simmons index} of $G$ \cite{MerrifieldSimmons}. There has been a large number of papers devoted to finding the maximum and minimum values of $i(G)$ and $i_t(G)$ as $G$ ranges over some family of graphs. For a sampling of these results, we refer the reader to two surveys \cite{Cutler,Zhao} and the references found therein. A \emph{proper vertex coloring} of a graph $G$ is an assignment of a color to each vertex so that no edge is monochromatic. A graph $G$ is \emph{$k$-chromatic} if there exists a proper coloring using $k$ colors but not one with $k-1$ colors. We call $G$ \emph{$k$-critical} if it is $k$-chromatic and every proper subgraph of $G$ is at most $(k-1)$-chromatic. Finally, a graph $G$ is \emph{$\ell$-connected} if $|V(G)|>\ell$ and any graph obtained by deleting fewer than $\ell$ vertices is connected. Recently Fox, He, and Manners \cite{FoxHeManners} proved an old conjecture of Tomescu by finding the $n$-vertex $k$-chromatic connected graph with the maximum number of proper vertex colorings that uses $k$ colors. This focus of this note is on maximizing $i(G)$ and $i_t(G)$ within the family of $n$-vertex $k$-chromatic $\ell$-connected graphs. When $\ell=0$ and $\ell=1$, the maximum number of independent sets, and independent sets of each fixed size $t$, in these families was determined in \cite{EngbersErey}. Our first result generalizes this to maximizing $i(G)$ when $\ell>1$ for $n$ large. Before we state it, we first define the extremal graphs for the various values of $k$ and $\ell$. Recall that for graphs $G_1$ and $G_2$, the graph $G_1 \vee G_2$ has vertex set $V(G_1) \sqcup V(G_2)$ and edge set $E(G_1) \cup E(G_2) \cup \{xy:x \in V(G_1),y \in V(G_2)\}$. We denote the complete and empty graphs on $n$ vertices by $K_n$ and $E_n$, respectively. \begin{definition} Fix $k \geq 2$ and $\ell \geq 1$. For $k \leq \ell$, let $G^*:= (K_{k-1} \cup E_{\ell-k+1}) \vee E_{n-\ell}$, and for $k > \ell$ let $G^* := K_\ell \vee (K_{k-\ell} \cup E_{n-k})$. See Figure \ref{fig-G^*}. \end{definition} \begin{figure}[ht!] \centering \begin{tikzpicture}[scale=.7] \node at (-1,3.75) {$G^*$ ($k \leq \ell$)}; \node (v1) at (1,1) [circle,draw] {\fontsize{7}{5.2}\selectfont {$k$-1}}; \node (v2) at (1,2) [circle,draw,scale=.4,fill] {}; \draw[densely dotted] (.35,.35) -- (.35,2.35); \draw[densely dotted] (.35,2.35) -- (1.65,2.35); \draw[densely dotted] (1.65,2.35) -- (1.65,.35); \draw[densely dotted] (1.65,.35) -- (.35,.35); \node (v3) at (3,0) [circle,draw,scale=.4,fill] {}; \node (v4) at (3,1) [circle,draw,scale=.4,fill] {}; \node (v5) at (3,2) [circle,draw,scale=.4,fill] {}; \node (v6) at (3,3) [circle,draw,scale=.4,fill] {}; \draw[densely dotted] (2.65,-.35) -- (3.35,-.35); \draw[densely dotted] (3.35,-.35) -- (3.35,3.35); \draw[densely dotted] (3.35,3.35) -- (2.65,3.35); \draw[densely dotted] (2.65,3.35) -- (2.65,-.35); \node at (3,3.75) {$n-\ell$}; \node at (1,2.75) {$\ell$}; \foreach \from/\to in {v1/v3,v1/v4,v1/v5,v1/v6,v2/v3,v2/v4,v2/v5,v2/v6} \draw (\from) -- (\to); \end{tikzpicture} \qquad\qquad\qquad \begin{tikzpicture}[scale=.8] \node at (0,3.75) {$G^*$ ($k>\ell$)}; \node (v1) at (1,.8) [circle,draw,scale=.4,fill] {}; \node (v2) at (2,2) [circle,draw,scale=.4,fill] {}; \node at (2,2.6) {$\ell$}; \draw[densely dotted] (1.7,2.3) -- (2.3,2.3); \draw[densely dotted] (2.3,2.3) -- (2.3,.7); \draw[densely dotted] (2.3,.7) -- (1.7,.7); \draw[densely dotted] (1.7,.7) -- (1.7,2.3); \node (v3) at (1,2.2) [circle,draw,scale=.4,fill] {}; \draw[densely dotted] (-.1,2.5) -- (1.3,2.5); \draw[densely dotted] (1.3,2.5) -- (1.3,.5); \draw[densely dotted] (1.3,.5) -- (-.1,.5); \draw[densely dotted] (-.1,.5) -- (-.1,2.5); \node at (.6,2.8) {$k-\ell$}; \node (v4) at (2,1) [circle,draw,scale=.4,fill] {}; \node (v5) at (4,2) [circle,draw,scale=.4,fill] {}; \node (v6) at (4,.5) [circle,draw,scale=.4,fill] {}; \node (v7) at (4,1.25) [circle,draw,scale=.4,fill] {}; \node (v8) at (4,2.75) [circle,draw,scale=.4,fill] {}; \draw[densely dotted] (3.7,.2) -- (4.3,.2); \draw[densely dotted] (4.3,.2) -- (4.3,3.05); \draw[densely dotted] (4.3,3.05) -- (3.7,3.05); \draw[densely dotted] (3.7,3.05) -- (3.7,.2); \node at (4,3.35) {$n-k$}; \node (v9) at (0.2,1.5) [circle,draw,scale=.4,fill] {}; \foreach \from/\to in {v9/v1,v9/v2,v9/v3,v9/v4,v1/v3,v1/v2,v2/v3,v2/v4,v4/v3,v1/v4,v4/v5,v4/v6,v4/v7,v4/v5,v2/v5,v2/v6,v2/v7,v2/v8,v4/v8} \draw (\from) -- (\to); \end{tikzpicture} \caption{The graph $G^*$ for the two possibilities for $k$ and $\ell$.} \label{fig-G^*} \end{figure} So, for example, when $k=2\leq \ell$ we have $G^*=K_{\ell,n-\ell}$, and the fact that $i(G) \leq i(G^*)$ for all $n$-vertex $\ell$-connected bipartite graphs $G$, with equality if and only if $G=G^*$, appears as Corollary 2.2 in \cite{AlexanderCutlerMink} (recall that an $\ell$-connected graph has minimum degree at least $\ell$). When $\ell=1$ and $k > 1$ the graph $G^*$ is formed from a $k$-clique with $n-k$ pendants attached to one vertex in the clique, and the fact that $i(G) \leq i(G^*)$ for all connected $k$-chromatic graphs $G$, with equality if and only if $G=G^*$, appears as Corollary 3 in \cite{EngbersErey}. (Viewing $G^*$ naturally as $K_k \cup E_{n-k}$ in the case where $\ell=0$, the analogous result appears as Corollary 2 in \cite{EngbersErey}.) We show that this result is in fact true for all $k>2$, $\ell \geq 1$, and $n$ large. \begin{theorem}\label{thm-i(G)} Let $k>2$ and $\ell \geq 1$ be fixed. If $n > 2(k+\ell+2)\binom{6(k+\ell)}{\ell}$ and $G$ is an $n$-vertex $k$-chromatic $\ell$-connected graph, then \[ i(G) \leq i(G^*)=\begin{cases} 2^{n-\ell}+k2^{\ell-k+1} -1, & \quad k \leq \ell \\ (k-\ell+1)2^{n-k}+\ell, & \quad k > \ell \end{cases}, \] with equality if and only if $G=G^*$. \end{theorem} In fact, we prove the following more general result, from which Theorem \ref{thm-i(G)} follows as $\ell$-connected graphs have minimum degree at least $\ell$. \begin{theorem}\label{thm-asympresult} Let $k>2$ and $\ell \geq 1$ be fixed. If $n > 2(k+\ell+2)\binom{6(k+\ell)}{\ell}$ and $G$ is an $n$-vertex $k$-chromatic graph with minimum degree at least $\ell$, then \[ i(G) \leq i(G^*)=\begin{cases} 2^{n-\ell}+k2^{\ell-k+1} -1, & \quad k \leq \ell \\ (k-\ell+1)2^{n-k}+\ell, & \quad k > \ell \end{cases}, \] with equality if and only if $G=G^*$. \end{theorem} The proof of Theorem \ref{thm-asympresult} uses a stability technique, and proceeds by showing that any graph $G$ satisfying $i(G) \geq i(G^*)$ must have a similar structure to $G^*$ in that $G$ must have a large complete bipartite subgraph $K_{\ell,cn}$ for some constant $c$. It then breaks into two cases depending on the values of $k$ and $\ell$, where the count of $i(G)$ is driven by those independent sets that completely avoid the size $\ell$ part of $K_{\ell,cn}$. \medskip In \cite{EngbersErey}, the authors ask what can be said in the family of $n$-vertex $k$-chromatic $\ell$-connected graphs for independent sets of size $t$ when $\ell>1$. We also provide some results here for specific values of $k$, $\ell$, and $t$. The first new case is that of $2$-connected $3$-chromatic graphs; we remark that results on maximizing $i(G)$ over all $n$-vertex $2$-connected graphs appear in \cite{HuaZhang}. \begin{definition} A \emph{theta graph} joins vertices $v$ and $w$ with three internally disjoint paths of (edge) lengths $a$, $b$, and $c$. We denote this graph by $\theta_{a,b,c}$. \end{definition} We have, for example, that $\theta_{2,2,2} = K_{2,3}$, and it is apparent that $|V(\theta_{a,b,c})| = a + b + c-1$. Note that when $a$ is even, the corresponding $vw$ path has an odd number of internal vertices. We now state the theorem. \begin{theorem}\label{thm-2con3chrom} Let $n \geq 4$, and let $G$ be an $n$-vertex $3$-chromatic $2$-connected graph. Then we have the following: \begin{itemize} \item if $n$ is odd, then $i_2(G) \leq i_2(C_n)$ with equality if and only if $G=C_n$; \item if $n$ is even, then $i_2(G) \leq i_2(\theta_{a,b,c})$, where at least one of $a$, $b$, or $c$ is even, with equality if and only if $G = \theta_{a,b,c}$ where at least one of $a$, $b$, or $c$ is even; and \item for all $3 \leq t \leq n-2$, $i_t(G) \leq i_t(K_2 \vee E_{n-2})$, and for $n \geq 5$ we have equality if and only if $G=K_2 \vee E_{n-2}$. \end{itemize} \end{theorem} The results for maximizing $i(G)$ amongst $3$-chromatic $2$-connected graphs are consequences of \cite{HuaZhang}, and we briefly discuss this at the beginning of Section \ref{sec-2con3chrom}. Also, as a fairly routine consequence of results for independent sets of size $t$ in $n$-vertex $\ell$-connected graphs, we show the following. \begin{theorem}\label{thm-bigt} Let $k \geq 3$, $\ell \geq k$, and $n \geq 2\ell$ be fixed. If $G$ is an $n$-vertex $k$-chromatic $\ell$-connected graph and $t \geq \ell$, then \[ i_t(G) \leq i_t(G^*). \] \end{theorem} \medskip Finally, we also consider the problem of maximizing the number of independent sets of size $t=2$ in $k$-chromatic $\ell$-connected graphs. Note that an independent set of size 2 induces an edge in the complement of the graph, so this problem is equivalent to minimizing the number of edges. The problem of minimizing edges has been studied for several related families of graphs. The minimum number of edges in a $k$-chromatic graph is clearly ${k \choose 2}$. The minimum number of edges in $\ell$-connected graphs is $\lceil \frac{n\ell}{2} \rceil$ due to Harary \cite{Harary}. The minimum number of edges in $k$-critical graphs was first studied by Dirac \cite{Dirac} and Gallai \cite{Gallai-I, Gallai} and subsequently in \cite{Kostochka,Krivelevich1,Krivelevich2}. Minimizing edges in $k$-chromatic $\ell$-edge-connected graphs was considered in \cite{Westetal}, where it was briefly noted that some of the bounds also hold for $\ell$-connected graphs. We present two sharp bounds for the minimum number of edges in $k$-chromatic $\ell$-connected graphs for the case that $k-1>\ell >1$. The first has the extra condition that $\ell \le n-k$ and our bound coincides exactly with the result in \cite{Westetal}, however, their proof relies on edge-connectivity. Furthermore, our techniques in the range $\ell \le n-k$ allow us to tackle the range $\ell > n-k$ as well; this appears as an unsolved case in \cite{Westetal}. All remaining cases for minimizing edges in $k$-chromatic $\ell$-connected graphs follow similarly to \cite{Westetal}, so we omit the results here. \begin{theorem}\label{thm-minedges1} If $G$ is a $k$-chromatic $\ell$-connected graph with $k-1>\ell>1$ and $\ell\leq n-k$ then \[\abs{E(G)}\geq \binom{k}{2}+\frac{(n-k+1)\ell}{2}\] and this bound is sharp. \end{theorem} \begin{theorem} \label{thm-minedges2} If $G$ is a $k$-chromatic $\ell$-connected graph with $k-1>\ell>1$ and $\ell>n-k$ then \[ |E(G)| \geq \binom{k}{2} + \binom{n-k}{2} + (n-k)(\ell-(n-k-1)) \] and this bound is sharp. \end{theorem} In the rest of the paper we present the proofs of our results. We prove Theorem \ref{thm-asympresult} in Section \ref{sec-asympresult}, and we consider 2-connected, 3-chromatic graphs in Section \ref{sec-2con3chrom} where we also prove Theorem \ref{thm-bigt}. Then we consider maximizing independent sets of size $t=2$ in Section \ref{sec:t=2}. Finally, in Section \ref{sec-conclusion}, we highlight some open questions related to the results in this paper. \section{Proof of Theorem \ref{thm-asympresult}} \label{sec-asympresult} In this section we will prove Theorem \ref{thm-asympresult}, and to do so we will use the following results from \cite{EngbersErey}. \begin{theorem}[\cite{EngbersErey}]\label{thm-EngbersEreyIndSets} Let $G$ be an $n$-vertex $k$-chromatic graph. Then \[ i(G) \leq i(K_{k} \cup E_{n-k}) = (k+1)2^{n-k} \] with equality if and only if $G = K_k \cup E_{n-k}$. \end{theorem} \begin{theorem}[\cite{EngbersErey}]\label{thm-EngbersEreyComponents} Let $G$ be an $n$-vertex $k$-chromatic graph with $d$ components. Then \[ i(G) \leq k2^{n-k} + 2^{d-1} \] with equality if and only if $G = (K_1 \vee (K_{k-1} \cup E_{n-k-d+1}))\cup E_{d-1}$. \end{theorem} We now move on to the proof. \begin{proof}[Proof of Theorem \ref{thm-asympresult}] Suppose that $G$ is an $n$-vertex $k$-chromatic graph with minimum degree at least $\ell$ which satisfies $i(G) \geq i(G^*)$. We investigate the structure of the graph $G$. First note that $i(G^*) > 2^{n-k-\ell}$ holds for each $k$ and $\ell$. \medskip \textbf{Step 1:} {\em Show that $G$ cannot contain a large matching.} Consider a maximum matching $M$ in $G$, and let $|M|$ denote the size of this maximum matching. In any independent set, at most one endpoint of each edge in $M$ is in the independent set, giving three possibilities across each edge in $M$. Therefore, by only considering the restrictions on the edges in $M$, we have \[ i(G) \leq 3^{|M|} 2^{n-2|M|} = \left( \frac{3}{4} \right)^{|M|} 2^n. \] If $|M| > 3k+3\ell$, then $\left( \frac{3}{4}\right)^{|M|} < \left(\frac{3}{4}\right)^{3k+3\ell} =\left( \frac{27}{64}\right)^{k+\ell}< \left(\frac{1}{2}\right)^{k+\ell}$ and so $i(G) < 2^{n-k-\ell}$, which contradicts the assumption that $i(G) \geq i(G^*)$. Therefore, we know that the maximum size of a matching $M$ in $G$ at most $3k+3\ell$. \medskip \textbf{Step 2:} {\em Show that there is a constant $c = c(k,\ell)$ so that $G$ contains $K_{\ell,cn}$ as a subgraph.} Let $M$ be a maximum matching. By Step 1, there are $2|M| \leq 6(k+\ell)$ vertices that are endpoints in $M$; call this set of vertices $J$. The set $I=V(G) \setminus J$ has size $|I| \geq n-6(k+\ell)$ and, by maximality of $M$, must form an independent set. Since $G$ has minimum degree at least $\ell$, each vertex in $I$ must have at least $\ell$ neighbors in $J$. The pigeonhole principle then produces some set $L$ of size $\ell$, with $L \subseteq J$, having at least $(n-|J|) / \binom{|J|}{\ell} \geq cn$ common neighbors in $I$ for some constant $c = c(k,\ell)>0$. Using that $n-|J| \geq n/2$ when $n \geq 12(k+\ell)$ and $\binom{|J|}{\ell} \leq \binom{6(k+\ell)}{\ell}$, we see that we can take $c = 1/(2\binom{6(k+\ell)}{\ell})$. This shows that $G$ contains a (not necessarily induced) subgraph $K_{\ell,cn}$. \medskip \textbf{Step 3:} {\em Estimate the number of independent sets in $G$ that include a vertex from $L$.} There are at most $2^{\ell}$ ways to include at least one vertex from $L$. Then none of the at least $cn$ common neighbors of $L$ can be in the independent set, so this gives an upper bound of \begin{equation}\label{eqn-vertexinL} 2^{\ell} \cdot 2^{n-cn-\ell} = \left( \frac{1}{2} \right)^{cn} 2^n \end{equation} independent sets that contain some vertex from $L$. \medskip \textbf{Step 4:} {\em Find an upper bound on the number of independent sets in $G$. } We have a bound from those independent sets that contain a vertex from $L$ above in \eqref{eqn-vertexinL}. Those that do not contain a vertex from $L$ correspond to the independent sets in $G'$, the graph obtained by deleting $L$. Note that $|V(G')| = n-\ell$. The chromatic number of $G'$ must be at most $k$, and so if the chromatic number is $m \leq k$ then by Theorem \ref{thm-EngbersEreyIndSets} we have at most $(m+1)2^{n-\ell-m}$ independent sets of this type, with equality if and only if $G - L$ is a complete graph on $m$ vertices with $n-\ell-m$ isolated vertices. To compare these maximal values for various $m$, note that for $m>1$ we have \begin{equation}\label{eqn-compare} (m+1)2^{n-\ell-m} = \frac{m+1}{2}2^{n-\ell-m+1} < m2^{n-\ell-m+1} = ((m-1)+1) 2^{n-\ell-(m-1)}. \end{equation} We now look at the two cases depending on the values of $k$ and $\ell$. \bigskip \textbf{Case 1 ($k > \ell$):} Suppose that $k>\ell$. We first argue that the chromatic number of $G'$ must be $k-\ell$. If not, then by the bound from \eqref{eqn-compare} the graph $G'$ has chromatic number at least $m=k-\ell+1$, and so at most $(k-\ell+2)2^{n-k-1}$ independent sets of this type. Combining this with \eqref{eqn-vertexinL} gives \[ i(G) \leq (k-\ell+2)2^{n-k-1} + \left( \frac{1}{2} \right)^{cn} 2^n = \left( \frac{k-\ell+2}{2} + \left( \frac{1}{2} \right)^{cn}2^k \right) 2^{n-k}. \] For $n>(k+1)/c$ (recalling also that $\ell \geq 1$), we have $i(G) < (k-\ell+1)2^{n-k}+\ell$, which is a contradiction. We now know that the chromatic number of $G'$ is $k-\ell$, and we next aim to show that $G'$ has many components. By Theorem \ref{thm-EngbersEreyComponents} an ($n-\ell$)-vertex $k$-chromatic graph with exactly $d$ components has at most $k2^{(n-\ell)-k}+2^{d-1}$ independent sets; note that this is an increasing function of $d$. Therefore, if $G'$ has at most $n-k$ components, we have \[ i(G) \leq (k-\ell) 2^{n-\ell - (k-\ell)} + 2^{n-k-1}+\left( \frac{1}{2} \right)^{cn} 2^n = (k-\ell)2^{n-k} + \left( \frac{1}{2} + \left( \frac{1}{2} \right)^{cn}2^k \right) 2^{n-k}. \] For $n > (k+1)/c$, we have $i(G) < (k-\ell+1)2^{n-k}+\ell$, which is a contradiction. Therefore, we know: \begin{itemize} \item the chromatic number of $G'$ is $k-\ell$; \item $G'$ has $n-\ell$ vertices; and \item $G'$ has at least $n-k+1$ components. \end{itemize} This is only possible if $G'$ has exactly $n-\ell - (k-\ell)+1 = n-k+1$ components, one component is $K_{k-\ell}$, and the rest are isolated vertices. Therefore $G'$ must be the graph $K_{k-\ell} \cup E_{n-k}$. Now, recall that $G$ has minimum degree at least $\ell$ and chromatic number $k$. The minimum degree condition forces each vertex in $L$ to be adjacent to each isolated vertex in $G'$. If some vertex in $L$ is not adjacent to some vertex in the complete component of $G'$, then those two vertices can be assigned the same color in a proper coloring and this can easily be extended to a $(k-1)$-coloring of the vertices of $G$, which contradicts the assumption that $G$ is $k$-chromatic. Therefore the vertices in $L$ must form a dominating set in $G$. Furthermore, they must all be adjacent, or similar argument shows that $G$ can be properly colored with at most $k-1$ colors. Therefore $G$ must be the graph $G^*$. \medskip \textbf{Case 2 ($k \leq \ell$):} Suppose now that $k \leq \ell$. Recall that $G'$ is the graph obtained from $G$ by deleting $L$, and that in this case $i(G^*)= 2^{n-\ell} + k2^{\ell-k+1} -1$. First suppose that $G'$ contains some edge $e$. At most one of the endpoints of $e$ can be in an independent set, and so this combined with \eqref{eqn-vertexinL} gives \[ i(G) \leq 3\cdot 2^{n-\ell-2} + \left( \frac{1}{2} \right)^{cn} 2^n = \left(\frac{3}{4} + \left( \frac{1}{2} \right)^{cn} 2^{\ell} \right) 2^{n-\ell}<2^{n-\ell} \] where the strict inequality holds for $n>(\ell+2)/c$. This is a contradiction to the assumption on $G$. Therefore $G'$ must be the empty graph. As $G$ has minimum degree $\ell$, this means that each vertex in $G'$ is adjacent to each vertex in $L$. Since $G$ is $k$-chromatic, the induced graph on $L$ must be $(k-1)$-chromatic. Since all edges are present between $G'$ and $L$, we have \[ i(G) = i(L) + 2^{n-\ell}-1. \] Now, $L$ has $\ell$ vertices and chromatic number $k-1$, and so we know from Theorem \ref{thm-EngbersEreyIndSets} that it has at most $i(K_{k-1} \cup E_{\ell-k+1}) = k2^{\ell-k+1}$ independent sets, with equality if and only if $L=K_{k-1}\cup E_{\ell-k+1}$. Therefore \[ i(G) = i(L) + 2^{n-\ell}-1 \leq k2^{\ell-k+1} + 2^{n-\ell} -1, \] with equality if and only if $L=K_{k-1}\cup E_{\ell-k+1}$, which implies that $G=G^*$. \end{proof} \section{$2$-connected $3$-chromatic and the Proof of Theorem \ref{thm-bigt}} \label{sec-2con3chrom} In this section we first completely classify the $2$-connected $3$-chromatic graphs that maximize the total count of independent sets and the total count of independent sets of each (non-trivial) fixed size. \subsection{Total count of independent sets} We first show that the result for the total number of independent sets is essentially a corollary to a result from \cite{HuaZhang}. There it is proved that if $G$ is a $2$-connected graph with $n \geq 4$, then $i(G) \leq 2^{n-2}+3$ with equality if and only if $G$ is $K_{2,n-2}$ or $C_5$. Since $C_5$ is $3$-chromatic and $K_{2,n-2}$ is not, it follows that if $n=5$ we have that $C_5$ is the $2$-connected $3$-chromatic graph with the most number of independent sets. For $n \neq 5$, note that $K_2 \vee E_{n-1}$ is $3$-chromatic and \[ i(K_{2,n-2}) = i(K_2 \vee E_{n-2})+1, \] so for $n\geq 4$ and $n \neq 5$ the characterization of equality implies that $K_2 \vee E_{n-2}$ is the (not necessarily unique) graph with the maximum number of independent sets. \subsection{Size $t$ independent sets} Now we move to independent sets of size $t$. For $t \geq 3$, we have the following results for $2$-connected graphs and graphs with fixed minimum degree $\delta \geq 3$. \begin{theorem}[\cite{EG}]\label{thm-EG} Let $n \geq 4$. For every $t \geq 3$, every $n$-vertex graph $G$ with minimum degree at least $2$ satisfies \[ i_t(G) \leq i_t(K_{2,n-2}). \] For $n \geq 5$ and $3 \leq t \leq n-2$ we have equality if and only if $G$ is $H \vee E_{n-2}$, where $H$ is any graph on two vertices. \end{theorem} \begin{theorem}[\cite{GLS}]\label{thm-GLS} Let $n \geq 2\delta$. For every $t \geq 3$, every $n$-vertex graph $G$ with minimum degree at least $\delta$ satisfies \[ i_t(G) \leq i_t(K_{\delta,n-\delta}) \] and when $3 \leq t \leq \delta$, $K_{\delta,n-\delta}$ is the unique extremal graph. \end{theorem} \begin{proof}[Proof of Theorem \ref{thm-2con3chrom}] First, we analyze the case when $t=2$; here to maximize $i_2(G)$ we want to minimize $|E(G)|$. A $2$-connected graph $G$ has minimum degree at least $2$, and so \[ |E(G)| = \frac{1}{2}\sum_v d(v) \geq n, \] with equality if and only if $G$ is $2$-regular, which implies that \[ i_2(G) \leq \binom{n}{2} - n = i_2(C_n). \] The equality characterization for $n$ odd follows readily as $C_n$ is the only $2$-connected $2$-regular graph. When $n$ is even and $G$ is 2-connected, we still have the bound of $E(G) \geq n$ with equality if and only if $G$ is $2$-regular if and only if $G=C_n$. Since in this case $C_n$ is not $3$-chromatic, this shows that \[ |E(G)| \geq n+1, \] which proves the inequality as for an $n$-vertex theta graph $\theta_{a,b,c}$ we have $|E(\theta_{a,b,c})|=n+1$. We now work on the cases for equality. Using that $G$ is not $2$-regular, by the handshaking lemma there must be at least two vertices of degree at least $3$, or one vertex of degree at least $4$. A single vertex of degree $4$ with the remaining vertices having degree $2$ is not possible in a $2$-connected $G$, as the deletion of the degree $4$ vertex disconnects the graph. So now suppose $G$ has degree $3$ vertices $v$ and $w$, and the remaining vertices of $G$ have degree $2$. If two of the edges out of $v$ are on a cycle that misses $w$, then again the deletion of $v$ disconnects the graph, which contradicts that $G$ is $2$-connected. So each edge out of $v$ must be on some path that ends at $w$, which implies that $G$ is a theta graph. Given that $G$ is a theta graph $\theta_{a,b,c}$, we need the conditions on $a$, $b$, and $c$ so that $G$ is $3$-chromatic. By coloring $v$ and $w$ with different colors and then the paths between them, we see that the chromatic number is $2$ when $a$, $b$, and $c$ are all odd. So at least one of $a$, $b$, and $c$ must be even, and by parity considerations not all of $a$, $b$, and $c$ are even, so one parameter is even and another is odd. These two paths form an odd cycle in the graph, which shows that $\theta_{a,b,c}$ is indeed $3$-chromatic. This implies the characterization of equality. Now we consider $t \geq 3$. When $n \leq 4$ there are no $n$-vertex $3$-chromatic graphs that have an independent set of size $t\geq 3$. Since $G$ has minimum degree at least $2$, Theorem \ref{thm-EG} implies that for every $n \geq 5$ and $t \geq 3$, we have \[ i_t(G) \leq i_t(K_{2,n-2}), \] with equality if and only if $G$ is $K_{2,n-2}$ or $K_2 \vee E_{n-2}$. Recalling that $K_{2,n-2}$ is bipartite, this proves the result and the characterization of equality for $n \geq 5$. \end{proof} \subsection{Proof of Theorem \ref{thm-bigt}} Suppose that $n \geq 2\ell$. By Theorem \ref{thm-GLS}, $K_{\ell,n-\ell}$ is an $\ell$-connected graph that has the most number of independent sets of size $t \geq 3$. When $t\geq \ell+1$, these independent sets consist of $t$ vertices from the size $n-\ell$ partition class. So if $k \leq \ell$, then $i_t(G^*) = i_t(K_{\ell,n-\ell})$, and therefore $i_t(G) \leq i_t(G^*)$ for all $k$-chromatic $\ell$-connected graphs, where $k \leq \ell$, $t \geq \ell+1$, and $n \geq 2\ell$. When $t = \ell \geq 3$, Theorem \ref{thm-GLS} gives that $K_{\ell,n-\ell}$ is the \emph{unique} $\ell$-connected graph with the most number of independent sets of size $t$. Since for $t=\ell \geq 3$ we have $i_t(G^*) = i_t(K_{\ell,n-\ell})-1$ and for $k$-chromatic $\ell$-connected $G$ we have $i_t(G)<i_t(K_{\ell,n-\ell})$, this shows that $i_t(G) \leq i_t(G^*)$. \begin{comment} \section{4-chromatic} When $k=4$, we know the result holds for $\ell=0$ and $\ell=1$ \cite{EngbersErey}. Suppose that $\ell=3$; here the graph $G^*$ is $K_3 \vee E_{n-3}$. Note that for $t \geq 4$ we have $i_t(G^*) = i_t(K_{3,n-3})$, and for $t=3$ we have $i_3(G^*) = i_3(K_{3,n-3})-1$. By Theorem \ref{thm-GLS} we know that $K_{3,n-3}$ is the unique 3-connected graph with the most number of independent sets of size $3$, this shows that if $G$ is an $n$-vertex $4$-chromatic $3$-connected graph with $n\geq 6$ we have $i_3(G) \leq i_3(G^*)$. (When $n \leq 5$ there is no $3$-connected graph with an independent set of size $3$, since deleting the at most two vertices outside the independent set would disconnect the graph.) TO DO: What about $\ell=2$; more precisely, what about $2$-connected $4$-chromatic graphs? In this case, the graph $G^*$ takes $K_{2,n-2}$ and adds two edges (one between the two vertices in the size 2 part). The number of independent sets of size $t \geq 3$ in $G^*$ is $\binom{n-2}{t} - \binom{n-4}{t-2} = \binom{n-3}{t} + \binom{n-4}{t-1}$, and it is worth noting that a $4$-chromatic graph $G$ has $\alpha(G) \leq n-3$, that the vertex set of a $4$-chromatic graph can be partitioned into four independent sets, and that deleting any single vertex does not disconnect the graph. If $\alpha(G) = n-3$, then the other three vertices must form a triangle. A size $t$ independent set can come from the maximal independent set or include one of the other three vertices (at most one, as they form a triangle). Is looking at various values of $\alpha(G)$ a good way to attack this problem? \end{comment} \section{The Case of $t=2$: Minimizing Edges}\label{sec:t=2} In this section, we consider maximizing the number of independent sets of size $t=2$ in $k$-chromatic $\ell$-connected graphs. As previously mentioned, this problem is equivalent to minimizing the number of edges in such graphs, so our results and proofs are stated as such. \begin{comment} Here's a chart with some of these minimizing/maximizing edge type problems for the sake of literature search: \begin{center} \begin{tabular}{c|c|c} &$k$-chromatic &$\ell$-connected\\ \hline minimizing edges &$\binom{k}{2}$ (proof by contradiction) &$\lceil\frac{nl}{2}\rceil$ (Harary)\\ \hline maximizing (consider critical case) &? &Ando and Egawa \end{tabular} \end{center} \textcolor{blue}{LK: Did we say anything about the $\ell=1$ case? Should be a $K_k$ with a tree/forest hanging off of it} \textcolor{red}{JE: We have $\ell=1$ in \cite{EngbersErey}; it is cited there from a different paper. When $k=3$ any unicyclic graph with an odd cycle works (so there are just more extremal examples).} \end{comment} \subsection{Proof of Theorem \ref{thm-minedges1}} We start by constructing a graph that achieves the bound. We make use of the $n$-vertex, $\ell$-connected Harary graph, which we denote by $H_{n, \ell}$. Recall that to construct $H_{n, \ell}$, place $n$ vertices $w_1$, $w_2$, \ldots, $w_n$ in order around a circle and join each vertex to the $\lfloor \frac{\ell}{2}\rfloor$ vertices closest to it in either direction. In the event that $\ell$ is odd, then also join each vertex to the vertex directly opposite (or as opposite as possible when $n$ is odd). The Harary graph $H_{n, \ell}$ has $\lceil n\ell /2 \rceil$ edges, which is the minimum number of edges over all graphs with the same number of vertices and connectivity \cite{Harary}. Consider the disjoint union of the complete graph $K_k$ and a Harary graph $H_{n-k, \ell}$. Since we are assuming $\ell < k-1$ and $\ell \le n-k$, we can choose $\ell$ vertices $v_1$, $v_2$, \ldots, $v_\ell$ from $K_k$ and $\ell$ adjacent vertices $w_1$, $w_2$, \ldots, $w_\ell$ along the circle in $H_{n-k, \ell}$ and connect these vertices via a matching, $v_iw_i$. Now starting with a terminal edge, $w_1w_2$, of the $\ell$-vertex path in $H_{n-k, \ell}$, we remove every other edge of the path. In the case where $\ell$ is odd and $n-k$ is also odd, then we use the one higher degree vertex from $H_{n-k, \ell}$ in our $\ell$-vertex path and delete both edges to the sides. Call this graph $G^*$ and let $H'_{n-k,\ell}$ denote the subgraph induced by the vertices of $H_{n-k,\ell}$. See Figure \ref{fig-}. The graph $G^*$ has \[{k \choose 2} + \left\lceil\frac{(n-k)\ell}{2}\right\rceil + \ell -\lfloor\ell /2\rfloor = \binom{k}{2} + \left\lceil \frac{(n-k+1)\ell}{2}\right\rceil \] edges and we claim this graph is $k$-chromatic and $\ell$-connected. \begin{figure}[h] \centering \begin{tikzpicture} \draw (-2.25,0) ellipse (1.5cm and 3.5cm); \draw (-2.25,-4) node {$K_k$}; \node (v1) at (-2,2.5) [circle,draw,fill,scale=.3] {}; \node at (-2.4,2.5) {$v_1$}; \node (v2) at (-2,2) [circle,draw,fill,scale=.3] {}; \node at (-2.4,2) {$v_2$}; \node (v3) at (-2,1.5) [circle,draw,fill,scale=.3] {}; \node at (-2.4,1.5) {$v_3$}; \node (v4) at (-2,1) [circle,draw,fill,scale=.3] {}; \node at (-2.4,1) {$v_4$}; \node (v5) at (-2,0.5) [circle,draw,fill,scale=.3] {}; \node at (-2.4,0.5) {$v_5$}; \node (vdots1) at (-2,0) {$\vdots$}; \node (vellminus1) at (-2,-0.5) [circle,draw,fill,scale=.3] {}; \node at (-2.4,-0.5) {$v_{\ell-1}$}; \node (vell) at (-2,-1) [circle,draw,fill,scale=.3] {}; \node at (-2.4,-1) {$v_{\ell}$}; \node (vellplus1) at (-2,-1.5) [circle,draw,fill,scale=.3] {}; \node at (-2.4,-1.5) {$v_{\ell+1}$}; \node (vdots2) at (-2,-2) {$\vdots$}; \node (vk) at (-2,-2.5) [circle,draw,fill,scale=.3] {}; \node at (-2.4,-2.5) {$v_{k}$}; \draw (2.25,0) ellipse (1.75cm and 3cm); \draw (2.25,-4) node {$H'_{n-k,\ell}$}; \node (w1) at (2,2.5) [circle,draw,fill,scale=.3] {}; \node at (2.4,2.5) {$w_1$}; \node (w2) at (2,2) [circle,draw,fill,scale=.3] {}; \node at (2.4,2) {$w_2$}; \node (w3) at (2,1.5) [circle,draw,fill,scale=.3] {}; \node at (2.4,1.5) {$w_3$}; \node (w4) at (2,1) [circle,draw,fill,scale=.3] {}; \node at (2.4,1) {$w_4$}; \node (w5) at (2,0.5) [circle,draw,fill,scale=.3] {}; \node at (2.4,0.5) {$w_5$}; \node (wdots1) at (2,0) {$\vdots$}; \node (wellminus1) at (2,-0.5) [circle,draw,fill,scale=.3] {}; \node at (2.5,-0.5) {$w_{\ell-1}$}; \node (well) at (2,-1) [circle,draw,fill,scale=.3] {}; \node at (2.5,-1) {$w_{\ell}$}; \node (wellplus1) at (2,-1.5) [circle,draw,fill,scale=.3] {}; \node at (2.5,-1.5) {$w_{\ell+1}$}; \node (wdots2) at (2,-2) {$\vdots$}; \node (wnminusk) at (2,-2.5) [circle,draw,fill,scale=.3] {}; \node at (2.5,-2.5) {$w_{n-k}$}; \foreach \from/\to in {v1/w1,v2/w2,v3/w3,v4/w4,v5/w5,vellminus1/wellminus1, vell/well, w2/w3, w4/w5, well/wellplus1} \draw (\from) -- (\to); \end{tikzpicture} \caption{The construction for $G^*$ when $\ell < k-1$ and $\ell \le n-k$.} \label{fig-} \end{figure} Now $G^*$ is $k$-chromatic since the subgraph $K_k$ requires $k$ colors. We show the graph is also $\ell$-connected since any two vertices $v$ and $w$ are connected by $\ell$ disjoint paths. This is true if $v$ and $w$ both belong to the subgraph $K_k$ since $k>\ell$. Suppose $v$ and $w$ both belong to $H'_{n-k,\ell}$. By construction, the Harary graph $H_{n-k,\ell}$ is $\ell$-connected, so there are $\ell$ disjoint paths between any two vertices. We extend these disjoint paths to $H'_{n-k,\ell}$ over deleted edges, $w_iw_{i+1}$, by instead using edges $w_iv_i$, $v_iv_{i+1}$, and $v_{i+1}w_{i+1}$ in $G^*$ (with the obvious modification if $\ell$ and $n-k$ are odd and the degree $\ell+1$ vertex is internal on one of the paths). This covers all cases except when $v$ itself has degree $\ell+1$, in which case $v=w_j$ for some $j$. But in this case since $v$ has degree $\ell+1$, we can find $\ell$ disjoint paths between $v$ and any other vertex that excludes one of the edges $w_{j-1}v$ or $vw_{j+1}$; these $\ell$ disjoint paths can be extended to $H'_{n-k,j}$ as above. Lastly, suppose $v$ belongs to the $K_k$ subgraph and $w$ belongs to the $H'_{n-k,\ell}$ subgraph. From $v$ there are $\ell$ disjoint paths to $H'_{n-k,\ell}$ each ending at one of $w_1$, $w_2$, \ldots, $w_\ell$. Since $H_{n-k,\ell}$ is $\ell$-connected, there exists $\ell$ disjoint paths from the subset of vertices $w_1$, $w_2$, \ldots, $w_\ell$ to the vertex $w$, and the same $\ell$ paths exists in $H'_{n-k,\ell}$. Therefore in all cases there are $\ell$ disjoint paths between the vertices $v$ and $w$. Since deleting the endpoints of the matching in $K_k$ disconnects the graph, this shows that $G^*$ is $\ell$-connected. \begin{proof}[Proof of Theorem \ref{thm-minedges1}] Sharpness follows from the graph $G^*$. To prove the lower bound, let $G$ be a $k$-chromatic $\ell$-connected graph. We will consider two cases: if $G$ is $k$-critical and otherwise. If $G$ is $k$-critical, then all vertices have degree at least $k-1$, so $G$ has at least $\frac{n(k-1)}{2}$ edges. Then the difference in the number of edges between $G$ and $G^*$ is at least \begin{align*} \frac{n(k-1)}{2}-\binom{k}{2} - \frac{(n-k+1)\ell}{2} &=\frac{1}{2}\left(n(k-1)-k(k-1)-(n-k+1)\ell\right)\\ &=\frac{1}{2}((k-1)(n-k)-(n-k)\ell-\ell)\\ &=\frac{1}{2}((n-k)(k-1-\ell) -\ell) \end{align*} Since $k-1>\ell$, we have $k-1-\ell\geq 1$, and combining this with $(n-k)\geq \ell$ gives $(n-k)(k-1-\ell)\geq \ell$. Thus, \[\frac{1}{2}((n-k)(k-1-\ell) -\ell)\geq 0\] and so the bound is correct in this case. Suppose $G$ is not $k$-critical. Then $G$ has an (induced) $k$-critical subgraph. This subgraph, $H$, has at least $k$ vertices and minimum degree at least $k-1$. Say $H$ has $k\leq x \leq n-1$ vertices. Then $H$ has at least $\frac{x(k-1)}{2}$ edges. Consider the vertices in $V(G)\setminus V(H)$. Since $G$ is $\ell$-connected, there must be at least $\ell$ disjoint paths between $V(G)$ and $V(G)\setminus V(H)$. This requires at least $\ell$ edges; assume there are $p \geq \ell$ edges with one endpoint in $V(H)$ and the other endpoint in $V(G) \setminus V(H)$. Moreover, every vertex in $V(G)\setminus V(H)$ has to have minimum degree at least $\ell$, since $G$ is $\ell$-connected. This requires a minimum of an additional \[ \dfrac{(n-x)\ell-p}{2}\] edges with both endpoints in $V(G)\setminus V(H)$. In total, $G$ must have at least \[ \frac{x(k-1)}{2} + p + \dfrac{(n-x)\ell-p}{2} \geq \frac{x(k-1)}{2} + \ell + \dfrac{(n-x)\ell-\ell}{2}\] edges. This bound is linear in $x$ with positive slope $\frac{k-1-\ell}{2}$, and so is minimized by the minimum value of $x$. Since $x\ge k$, we get \[ \frac{x(k-1)}{2} + \ell + \dfrac{(n-x)\ell-\ell}{2} \ge \frac{k(k-1)}{2} + \ell + \dfrac{(n-k)\ell-\ell}{2}\] proving the claimed bound in this case. This finishes the proof. \end{proof} \subsection{Proof of Theorem \ref{thm-minedges2}} We again start by constructing a graph that achieves the bound. Consider the disjoint union of the complete graph $K_k$ and the complete graph $K_{n-k}$. Fix $\ell$ vertices $v_{1},v_{2},\ldots,v_{\ell} \in V(K_k)$, and label the vertices in $K_{n-k}$ by $w_1,\ldots,w_{n-k}$. For a fixed $i$, add the $\ell-(n-k-1)$ edges joining $w_i$ and $v_j$ for each $j$ satisfying $i \leq j \leq i+(\ell-n+k)$. Call this graph $G^*$, and note that $G^*$ has $\binom{k}{2} + \binom{n-k}{2} + (n-k)(\ell-(n-k-1))$ edges. See Figure \ref{fig-G*}. \begin{comment} \textcolor{red}{JE: The motivation here is that we're trying to do a matching between vertices in $K_k$ and $K_{n-k}$ (like in the previous case; note that $K_{n-k}$ is a Harary graph!), but a matching isn't going to give the correct minimum degree condition, since $K_{n-k}$ vertices have ``small'' degree. So do a ``star-matching'' (my terminology?) with $\ell$ vertices from $K_k$: A matching uses $K_{1,1}$'s; here we're using $K_{1,\ell-(n-k-1)}$'s to get the correct minimum degree, and done systematically so the overlap of stars is straightforward and nothing degenerate happens. That was at least my thought here.} \end{comment} We first claim that $G^*$ is $k$-chromatic. It requires $k$ colors on $K_k$. And each vertex $w_i$ can be colored with the color on $v_{i-1}$ (where we consider $v_0$ to be the vertex $v_{\ell}$). This is a $k$-coloring of $G^*$. \begin{figure}[ht!] \begin{center} \begin{tikzpicture} \draw (-2,0) ellipse (1.5cm and 3.5cm); \draw (2,0) ellipse (1.7cm and 2cm); \coordinate(v1) at (-2,2.5); \coordinate(v2) at (-2,2); \coordinate(v3) at (-2,1.5); \coordinate(v4) at (-2,1); \coordinate(vdots) at (-2,.5); \coordinate(vellminus1) at (-2,0); \coordinate(vell) at (-2,-.5); \coordinate(vellplus1) at (-2,-1); \coordinate(velldots) at (-2,-1.5); \coordinate(vkminus1) at (-2,-2.5); \coordinate(vk) at (-2,-3); \coordinate(w1) at (2,1.5); \coordinate(w2) at (2,1); \coordinate(w3) at (2,.5); \coordinate(wdots) at (2,0); \coordinate(wnminuskminus1) at (2,-.5); \coordinate(wnminusk) at (2,-1); \fill (v1) circle (2pt); \draw (-2.25,2.5) node {$v_1$}; \fill (v2) circle (2pt); \draw (-2.25,2) node {$v_2$}; \fill (v3) circle (2pt); \draw (-2.25,1.5) node {$v_3$}; \fill (v4) circle (2pt); \draw (-2.25,1) node {$v_4$}; \draw (vdots) node {$\vdots$}; \fill (vellminus1) circle (2pt); \draw (-2.5,0) node {$v_{\ell-1}$}; \fill (vell) circle (2pt); \draw (-2.25,-.5) node {$v_{\ell}$}; \fill (vellplus1) circle (2pt); \draw (-2.5,-1) node {$v_{\ell+1}$}; \draw (velldots) node {$\vdots$}; \fill (vkminus1) circle (2pt); \draw (-2.5,-2.5) node {$v_{k-1}$}; \fill (vk) circle (2pt); \draw (-2.5,-3) node {$v_{k}$}; \fill (w1) circle (2pt); \draw (2.5,1.5) node {$w_{1}$}; \fill (w2) circle (2pt); \draw (2.5,1) node {$w_{2}$}; \fill (w3) circle (2pt); \draw (2.5,.5) node {$w_{3}$}; \draw (wdots) node {$\vdots$}; \fill (wnminuskminus1) circle (2pt); \draw (3,-.5) node {$w_{n-k-1}$}; \fill (wnminusk) circle (2pt); \draw (3,-1) node {$w_{n-k}$}; \tikzstyle{EdgeStyle}=[-,ultra thin] \Edge(v1)(w1); \Edge(v2)(w1); \Edge(v3)(w1); \Edge(v2)(w2); \Edge(v3)(w2); \Edge(v4)(w2); \Edge(v3)(w3); \Edge(v4)(w3); \Edge(wnminuskminus1)(vellminus1); \Edge(wnminusk)(vellminus1); \Edge(wnminusk)(vell); \tikzstyle{EdgeStyle}=[loosely dotted,ultra thin] \Edge(-1.5,.65)(w3); \Edge(-1.5,.1)(wnminuskminus1); \Edge(-1.5,.3)(wnminuskminus1); \Edge(-1.5,.1)(wnminusk); \draw (-2,-4) node {$K_k$}; \draw (2, -3) node {$K_{n-k}$}; \end{tikzpicture} \end{center} \caption{The graph $G^*$ when $\ell-(n-k-1)=3$; note that here $w_2$ is adjacent to $v_2$, $v_3$, and $v_4$.} \label{fig-G*} \end{figure} Next, we claim that $G^*$ is $\ell$-connected; note that removing $v_{1},\ldots,v_{\ell}$ disconnects the graph (as $\ell<k$). We claim that any two vertices $v$ and $w$ are connected by $\ell$ disjoint paths. This is clear if $v$ and $w$ are both in $K_k$, since $\ell<k-1$. It is also clear if $v$ and $w$ are both in $K_{n-k}$, as there are $n-k-1$ paths in $K_{n-k}$, and the $\ell-(n-k-1)$ edges to $K_k$ from each vertex lead to $\ell-(n-k-1)$ other edge disjoint paths. So assume $v$ is some vertex in $K_k$ and $w=w_1$. We know that $w$ has neighbors $v_i$ for $1\leq i \leq \ell-n+k+1$; those have disjoint paths (with $0$ or $1$ edge) to $v$. And furthermore the neighbors $w_m$, $m >1$, can use their edge to $v_{m+\ell-n+k}$ and then edge $v_{m+\ell-n+k}v$ to produce the remaining disjoint paths from $w$ to $v$. \begin{proof}[Proof of Theorem \ref{thm-minedges2}] Note that we must have $k \geq 4$, since $k \leq 3$ implies $\ell<2$, which contradicts the assumption of $\ell>1$. Also note that the inequalities together imply that $n<2k-1$. Furthermore, $n=k$ is not possible, as then $G=K_k$ which is $k-1$ connected, but $\ell=k-1$ is not allowed. Therefore we can assume $n>k$. Sharpness comes from the graph $G^*$. Suppose $G$ is a $k$-chromatic $\ell$-connected graph with $\ell>n-k$ and $k-1>\ell>1$. We use a result from Gallai \cite{Gallai}, which says that if $k \geq 4$ and $k+2 \leq n \leq 2k-1$, a $k$-critical graph on $n$ vertices satisfies \[ |E(G)| \geq \frac{1}{2}\left( n(k-1) + (n-k)(2k-n)-2\right); \] there is a characterization of equality given in that paper as well. It is noted in various places that no $k$-critical graph has $n=k+1$ vertices. We consider two cases: $G$ is $k$-critical and otherwise. If $G$ is $k$-critical, then since $k\geq 4$ and our ranges of $n$, $k$, and $\ell$ imply that $n<2k-1$, the result from Gallai \cite{Gallai} gives at least $\frac{1}{2}( n(k-1) + (n-k)(2k-n)-2)$ edges. Then the difference between $|E(G)|$ and $|E(G^*)|$ is at least \begin{align*} \frac{1}{2}&\left( n(k-1) + (n-k)(2k-n)-2\right) - \binom{k}{2} - \binom{n-k}{2} - (n-k)(\ell-(n-k-1))\\ &=\frac{n-k}{2}\left( (k-1) + (2k-n)-(n-k-1)-2\ell+2(n-k-1) \right) - 1\\ &= \frac{n-k}{2}\left( (k-1) + (2k-n)+(n-k-1)-2\ell \right) -1\\ &= \frac{n-k}{2}\left( (k-1) -\ell + (k-1)-\ell \right) -1\\ &= (n-k)(k-1-\ell) - 1. \end{align*} Now $k-1-\ell>0$ and $n-k\geq 2$ (as there is no $k$-critical graph on $n=k+1$ vertices), and so the above expression is positive, which implies that bound is correct in this case. Suppose now that $G$ is not $k$-critical. Then $G$ again has an induced $k$-critical subgraph $H$ with $k \leq x \leq n-1$ vertices. Since $n<2k-1$, if $x>k+1$ then the Gallai bound applies, so $H$ has at least $\frac{1}{2}( x(k-1) + (x-k)(2k-x)-2)$ edges. If instead $x=k$, the graph $H$ has $\frac{1}{2}k(k-1)$ edges. We cannot have $x=k+1$ as there is no $k$-critical graph on $x=k+1$ vertices. Consider the vertices in $V(G) \setminus V(H)$. Each vertex must have at least $\ell$ disjoint paths to $V(H)$, and so in particular must have minimum degree at least $\ell$. Therefore the degree sum of the vertices in $V(G) \setminus V(H)$ is at least $(n-x)\ell$. There can be at most $\binom{n-x}{2}$ edges that contribute two to this degree sum, coming from edges with both endpoints in $V(G) \setminus V(H)$. This means there must be at least $(n-x)\ell - (n-x)(n-x-1) = (n-x)(\ell-(n-x-1))$ edges between $H$ and $G-H$. And if there are $p$ edges missing inside the induced subgraph on $V(G) \setminus V(H)$, where $0 \leq p$, then we have at least $(n-x)(\ell-(n-x-1))+2p$ edges between $H$ and $G-H$. Therefore the total number of edges in $G$ is at least \[ \frac{( x(k-1) + (x-k)(2k-x)-2 \cdot \textbf{1}_{\{x\geq k+2\}})}{2} + \frac{(n-x)(n-x-1)}{2} - p + (n-x)(\ell-(n-x-1))+2p, \] where $\textbf{1}_{\{x\geq k+2\}}$ is the indicator function on the event $x \geq k+2$. Minimizing this, we take $p=0$, giving at least \[ \frac{( x(k-1) + (x-k)(2k-x)-2\cdot \textbf{1}_{\{x\geq k+2\}})}{2} + \frac{(n-x)(n-x-1)}{2} + (n-x)(\ell-(n-x-1)) \] edges. The expression \[ \frac{x(k-1) + (x-k)(2k-x)-2\cdot \textbf{1}_{\{x\geq k+2\}} + (n-x)(n-x-1) + 2(n-x)(\ell-(n-x-1))}{2} \] is a quadratic function of (real-valued) $x$ with leading coefficient $-1$. By the Extreme Value Theorem, the minimum occurs over $k+2 \leq x \leq n-1$ at $x=k+2$ or $x=n-1$. We also need to compare these values to $x=k$, the other possible value for $x$. (We remark that we separate out the case when $x=k$ as the indicator function is not continuous, and so we cannot apply the Extreme Value Theorem on $k \leq x \leq n-1$.) When $x=k$ we have the bound \[ \frac{k(k-1) + (n-k)(n-k-1) + 2(n-k)(\ell-(n-k-1))}{2}. \] We need to show that when $x=k+2$ or $x=n-1$, we have a larger bound. For $x=k+2$, the bound is \[ \frac{(k+2)(k-1) + 2(k-2)-2 + (n-k-2)(n-k-3) + 2(n-k-2)(\ell-(n-k-3))}{2} \] and when $x=n-1$ the bound is \[ \frac{(n-1)(k-1) + (n-1-k)(2k-n+1)-2 + 2\ell}{2}. \] Computing the $x=k+2$ count minus the $x=k$ count gives \[ 2(n-\ell)-7. \] Now for this bound we have $n \geq k+2$, so $\ell<k-1$ means $\ell < n-3$, or $4 \leq n-\ell$, so the difference in terms is positive in this case. Computing the $x=n-1$ count minus the $x=k$ count gives \[ (k-\ell)(n-1-k)-1; \] here $k-\ell\geq 2$ and $n-1>k$ (as $n \geq k+2$). This shows the difference is positive in this case. Therefore, the minimum value occurs for $x=k$, proving the claimed bound. \end{proof} \section{Concluding Remarks}\label{sec-conclusion} In this section we highlight a few open problems that are related to the contents of this paper. In Theorem \ref{thm-asympresult}, we characterized the $n$-vertex $k$-chromatic $\ell$-connected graph with the maximum number of independent sets for large $n$. We expect the result to hold for all $n$ for which the graph $G^*$ is $k$-chromatic and $\ell$-connected. \begin{conjecture}\label{conj-1} Let $3 \leq k \leq \ell$ and $n \geq 2\ell$. If $G$ is an $n$-vertex $k$-chromatic $\ell$-connected graph, then \[ i(G) \leq i(G^*). \] \end{conjecture} \begin{conjecture}\label{conj-2} Let $2 \leq \ell < k$ and $n\neq 5$. If $G$ is an $n$-vertex $k$-chromatic $\ell$-connected graph, then \[ i(G) \leq i(G^*). \] \end{conjecture} Conjecture \ref{conj-2} is true for $k=3$ and $\ell=2$ (for $n \neq 5$), as we showed in Section \ref{sec-2con3chrom}. There are also open questions related to the number of independent sets of size $t$. We expect the following to hold, which extends Theorem \ref{thm-bigt} down to $t \geq 3$. \begin{conjecture}\label{conj-3} Let $3 \leq k \leq \ell$ and $n \geq 2\ell$. If $G$ is an $n$-vertex $k$-chromatic $\ell$-connected graph and $t \geq 3$, then \[ i_t(G) \leq i_t(G^*). \] \end{conjecture} It is also natural to conjecture that this behavior holds for $k>\ell$ as well. \begin{conjecture}\label{conj-4} Let $k \geq 4$ and $k > \ell$. If $G$ is an $n$-vertex $k$-chromatic $\ell$-connected graph and $t \geq 3$, then \[ i_t(G) \leq i_t(G^*). \] \end{conjecture} These last two conjectures appeared as questions in \cite{EngbersErey}. We note that the corresponding results for $k=3$ and $\ell=2$ are shown in Theorem \ref{thm-2con3chrom}, and that the cases when $\ell=0$ and $\ell=1$ appear in \cite{EngbersErey}.
{ "redpajama_set_name": "RedPajamaArXiv" }
5,202
class MigrateRepoSize < ActiveRecord::Migration def up project_data = execute('SELECT projects.id, namespaces.path AS namespace_path, projects.path AS project_path FROM projects LEFT JOIN namespaces ON projects.namespace_id = namespaces.id') project_data.each do |project| id = project['id'] namespace_path = project['namespace_path'] || '' path = File.join(Gitlab.config.gitlab_shell.repos_path, namespace_path, project['project_path'] + '.git') begin repo = Gitlab::Git::Repository.new(path) if repo.empty? print '-' else size = repo.size print '.' execute("UPDATE projects SET repository_size = #{size} WHERE id = #{id}") end rescue => e puts "\nFailed to update project #{id}: #{e}" end end puts "\nDone" end def down end end
{ "redpajama_set_name": "RedPajamaGithub" }
259
According to our database1, Sören Sonnenburg authored at least 28 papers between 2001 and 2011. Hierarchical Multitask Structured Output Learning for Large-scale Sequence Segmentation. A new scatter-based multi-class support vector machine. The SHOGUN Machine Learning Toolbox. COFFIN: A Computational Framework for Linear SVMs. Optimized Cutting Plane Algorithm for Large-Scale Risk Minimization. The Feature Importance Ranking Measure. Efficient and Accurate Lp-Norm Multiple Kernel Learning. POIMs: positional oligomer importance matrices - understanding support vector machine-based signal detectors. Optimized cutting plane algorithm for support vector machines. Machine Learning for Genomic Sequence Analysis. Improving the Caenorhabditis elegans Genome Annotation Using Machine Learning. Accurate splice site prediction using support vector machines. Large Scale Multiple Kernel Learning. Computation of Similarity Measures for Sequential Data using Generalized Suffix Trees. Large Scale Hidden Semi-Markov SVMs. ARTS: accurate recognition of transcription starts in human. Classifying 'Drug-likeness' with Kernel-Based Learning Methods. A General and Efficient Multiple Kernel Learning Algorithm. RASE: recognition of alternatively spliced exons in C.elegans. Large scale genomic sequence SVM classifiers. New Methods for Splice Site Recognition. A New Discriminative Kernel From Probabilistic Models.
{ "redpajama_set_name": "RedPajamaC4" }
5,914
Q: In R, how to create a new column from the column headings of other columns based on their values I have a dataframe as below: Type Prob_A prob_B prob_C Vinyl .57 .43 0 Wood .2 .4 .4 Ceramic .12 .80 .08 I need to create a new column called Status. Check the probabilities and get the heading of the max value and call it as A, B or C. In my real data asset, I have 10 columns I need to compare. A: We can use max.col to get the column index of the first max values and select the substring of the column names df1$Status <- substring(names(df1)[-1], nchar(names(df1)[-1]))[max.col(df1[-1], 'first')] df1$Status #[1] "A" "B" "B" data df1 <- structure(list(Type = c("Vinyl", "Wood", "Ceramic"), Prob_A = c(0.57, 0.2, 0.12), prob_B = c(0.43, 0.4, 0.8), prob_C = c(0, 0.4, 0.08 )), class = "data.frame", row.names = c(NA, -3L))
{ "redpajama_set_name": "RedPajamaStackExchange" }
8,822
Q: How do I send files with Telegram Bots using AWS Lambda? I am trying to send an mp3 file using a telegram bot. When I run it locally using node in terminal this code works perfectly fine: 'use strict' const Telegraf = require('telegraf') const bot = new Telegraf('Token') bot.command('audio', (ctx) => { ctx.replyWithAudio({source: './media/song.mp3'}) }) const { PORT = 3000 } = process.env bot.startWebhook('/', null, PORT) However, when I deploy this as an AWS Lambda function I get the following error: Apr 29th 12:24:12pm ERRO staging 4 events.js:183 Apr 29th 12:24:12pm ERRO staging 4 throw er; // Unhandled 'error' event Apr 29th 12:24:12pm ERRO staging 4 ^ Apr 29th 12:24:12pm ERRO staging 4 Apr 29th 12:24:12pm ERRO staging 4 Error: write after end Apr 29th 12:24:12pm ERRO staging 4 at write_ (_http_outgoing.js:622:15) Apr 29th 12:24:12pm ERRO staging 4 at ServerResponse.write (_http_outgoing.js:617:10) Apr 29th 12:24:12pm ERRO staging 4 at MultipartStream.ondata (_stream_readable.js:639:20) Apr 29th 12:24:12pm ERRO staging 4 at emitOne (events.js:116:13) Apr 29th 12:24:12pm ERRO staging 4 at MultipartStream.emit (events.js:211:7) Apr 29th 12:24:12pm ERRO staging 4 at MultipartStream.Readable.read (_stream_readable.js:475:10) Apr 29th 12:24:12pm ERRO staging 4 at flow (_stream_readable.js:846:34) Apr 29th 12:24:12pm ERRO staging 4 at resume_ (_stream_readable.js:828:3) Apr 29th 12:24:12pm ERRO staging 4 at _combinedTickCallback (internal/process/next_tick.js:138:11) Apr 29th 12:24:12pm ERRO staging 4 at process._tickCallback (internal/process/next_tick.js:180:9) I am pretty sure this is because I don't understand how files are stored when I deploy the lambda function. How are directories saved so I can retrieve them? Is this even possible? My zip bundle contains the following directories: For this bot I used apex up to deploy and telegraf to write the code. A: If your MP3 is in the zip bundle you uploaded, then you can find that and anything else in the bundle when the lambda is running. In the lambda you can get the directory containing the unzipped bundle with process.env.LAMBDA_TASK_ROOT. Your file will be relative to that. bot.command('audio', (ctx) => { ctx.replyWithAudio({ source: process.env.LAMBDA_TASK_ROOT + '/media/song.mp3' }) })
{ "redpajama_set_name": "RedPajamaStackExchange" }
6,377
\section{Introduction}\label{sec:Intro} Inflation~\cite{Guth1981,Linde1983}, an epoch of exponential expansion, may have played an important role in the evolution of the very early universe (see Ref.~\cite{precursor-papers} for an incomplete list of precursor papers and Ref.~\cite{Mukhanov2005} for further references and discussion). The mechanism relies, however, on one crucial assumption [stated, for example, a few lines below Eq.~(3.7) in Ref.~\cite{Guth1981}]: the minimum of the total scalar potential is set to zero, i.e., the corresponding vacuum energy density (effective cosmological constant $\Lambda$) is assumed to vanish. In other words, it is taken for granted that a solution has been found to the main cosmological constant problem~\cite{Weinberg1988} (CCP1): why is the present value of $|\Lambda|^{1/4}$ negligible when compared with the known energy scales of elementary particle physics? The next cosmological constant problem (CCP2) is, of course, to explain the measured value $\Lambda^\text{exp} \sim(2\,\text{meV})^4$, but this question lies outside the scope of the present article. Following an earlier suggestion to consider vector fields~\cite{Dolgov1985-1997} and using the insights from the $q$--theory approach~\cite{KV2008-2010} to CCP1, a special model of two massless vector fields has been presented in Ref.~\cite{EmelyanovKlinkhamer2011}. The massless vector fields of the model cancel dynamically an arbitrary initial (bare) cosmological constant $\Lambda$ without upsetting the local Newtonian dynamics (a potential problem discussed in Ref.~\cite{RubakovTinyakov1999}). But, if any cosmological constant can be canceled dynamically, what happens to inflation in the very early universe? In order to address this issue, we investigate the simplest possible extension of the two-vector-field model by adding a fundamental scalar field with a quadratic potential, while keeping an initial cosmological constant $\Lambda$. The question is, then, whether or not it is possible to have an inflationary phase of finite duration. \section{Model}\label{sec:Model} The model of Ref.~\cite{EmelyanovKlinkhamer2011} has two massless vector fields $A_\alpha(x)$ and $B_\alpha(x)$. Now, a fundamental complex scalar field $\Sigma(x)$ is added. Equivalently, it is possible to work with two real scalars by defining $\Sigma(x)\equiv [\phi_1(x)+i\,\phi_2(x)]/\sqrt{2}$. The relevant effective action is ($\hbar=c=1$ \bsubeqs\label{eq:model} \beqa\label{eq:model-action} S_\text{eff}[A,\,B,\,\Sigma,\,g] &=& - \int{}d^4x\,\sqrt{-g}\; \Big( \textstyle{\frac{1}{2}}\,(E_\text{Planck})^2\,R + \epsilon(Q_A,\,Q_B,\,\Sigma) + \Lambda \nonumber\\[1mm] && -\partial_{\alpha}\Sigma\;\partial^{\alpha}\Sigma^\star +U\big(\Sigma\big) \Big), \\[2mm]\label{eq:model-QA-QB} Q_A &\equiv& \sqrt{A_{\alpha;\beta}\;A^{\alpha;\beta}}\,, \qua Q_B \equiv \sqrt{B_{\alpha;\beta}\;B^{\alpha;\beta}}\,, \\[2mm]\label{eq:model-E-Planck} E_\text{Planck} &\equiv& (8\pi\,G_N)^{-1/2} \approx 2.44\times 10^{18}\:\text{GeV}\,, \eeqa for a scalar potential which is real and nonnegative, $U\big(\Sigma\big)\geq 0$ with $U(|\Sigma_\text{min}|)=0$. Specifically, the following two functions $U$ and $\epsilon$ are used: \beqa \label{eq:model-scalar-pot} U\big(\Sigma\big)&=& \,M^2\,|\Sigma|^2 \,, \\[2mm] \label{eq:model-espilon} \epsilon(Q_A,\,Q_B,\,\Sigma) &=& (E_\text{Planck})^4\; \frac{Q_A^4-Q_B^4} {(E_\text{Planck})^8\,\delta_\text{eff}(\Sigma)+Q_A^2\,Q_B^2}\;, \\[2mm] \label{eq:model-delta-eff} \delta_\text{eff}(\Sigma) &\equiv& \delta\;\frac{|\Sigma|^2}{|\Sigma|^2+(E_\text{Planck})^2\,\eta}\;, \eeqa for $0<M\ll E_\text{Planck}$ and (small) positive constants $\delta$ and $\eta$. The motivation of using the particular function \eqref{eq:model-delta-eff} is that, even for a fixed positive value of $\delta$, the inverse vacuum compressibility $\chi^{-1}$ vanishes if $\Sigma\to 0$ and the standard local Newtonian dynamics may be recovered (see Ref.~\cite{EmelyanovKlinkhamer2011} for further discussion). The constant $\Lambda$ in the effective action \eqref{eq:model-action} includes the vacuum-energy-density contributions from the zero-point energies of the standard-model quantum fields (not shown explicitly). In principle, this effective cosmological constant $\Lambda$ can be of arbitrary sign and have a magnitude of order $(E_\text{Planck})^4$. For further discussion and references on the effective-action method, see Ref.~\cite[(c)]{KV2008-2010}. It is also possible to write \eqref{eq:model-action} in terms of the total potential, \beqa\label{eq:model-Utot} U_\text{tot}\big(\Sigma,\,\Lambda\big)&=& U\big(\Sigma\big)+\Lambda= M^2\,|\Sigma|^2+\Lambda \,. \eeqa \esubeqs As mentioned in the first paragraph of Sec.~\ref{sec:Intro}, this quantity $U_\text{tot}$ has been used in the previous discussions of inflation, with $\Lambda$ set to zero by hand. Here, we keep $\Lambda$ arbitrary but introduce vector fields which have the potentiality to cancel it. In order to provide this cancellation of the effective cosmological constant $\Lambda$, the vector fields must appear in \eqref{eq:model-action} via the derivative terms contained in $\epsilon$, at least, within the $q$--theory framework~\cite{KV2008-2010}. The isotropic \textit{Ansatz}~\cite{Dolgov1985-1997} for the vector fields $A_{\alpha}(x)$ and $B_{\beta}(x)$, the scalar $\Sigma(x)$, and the metric $g_{\alpha\beta}(x)$ i \bsubeqs\label{eq:Dolgov-Ansatz} \beqa A_0 &=& A_0(t)\equiv V(t)\,,\quad\; A_1=A_2=A_3=0\,,\\[2mm] B_0 &=& B_0(t)\equiv W(t)\,,\quad B_1=B_2=B_3=0\,,\\[2mm] \Sigma &=& \Sigma(t)\,,\\[2mm] (g_{\alpha\beta})&=& \text{diag}\big( 1,\,- a(t),\,- a(t),\,- a(t) \big)\,, \eeqa \esubeqs where $t$ is the cosmic time of a spatially flat Friedmann--Robertson--Walker (FRW) universe, with cosmic scale factor $a(t)$ and Hubble parameter $H(t)\equiv [d a(t)/d t]/a(t)$. Using appropriate powers of the reduced Planck energy \eqref{eq:model-E-Planck} without additional numerical factors, the above dimensionful variables can be replaced by the following dimensionless variables: \bsubeqs\label{eq:dimensionless-variables} \beqa \big\{\Lambda,\, M,\, U,\,\epsilon\,,\, t,\, H\big\} &\to& \big\{\lambda,\,m,\,u,\, \epsilondimless,\,\tau,\,h \big\}\,,\\[2mm] \big\{Q_A,\, Q_B,\, V,\, W,\, \Sigma \big\} &\to& \big\{q_A,\, q_B,\, v,\, w,\, \sigma \big\}\,. \eeqa \esubeqs From now on, an overdot stands for differentiation with respect to $\tau$, for example, $h(\tau)\equiv \dot{a}(\tau)/a(\tau)$. In terms of these dimensionless variables, the \textit{Ansatz} \eqref{eq:Dolgov-Ansatz} reduces the field equations from \eqref{eq:model-action} to a set of coupled ordinary differential equations (ODEs) for $v(\tau)$, $w(\tau)$, $h(\tau)$, and $\sigma(\tau)$. Three of these ODEs have already been given in (3.11) of Ref.~\cite{EmelyanovKlinkhamer2011}, except that (3.11c) now contains a dimensionless pressure term from the scalar field, specifically, $p_\sigma=|\dot{\sigma}|^2-u(\sigma)$. The fourth ODE is simply the standard FRW Klein--Gordon equation for $\sigma(\tau)$. The corresponding Friedmann equation is given by \bsubeqs \beqa\label{eq:Friedmann-ODE} 3\, h^2 &=&\lambda+r_\sigma + \big[\;\widetilde{\epsilondimless}(q_A,\,q_B,\,\sigma)\; \big]_{q_A=\sqrt{\dot{v}^2+3\,h^2\, v^2},\;\, q_B=\sqrt{\dot{w}^2+3\,h^2\, w^2}}\,,\\[2mm] \widetilde{\epsilondimless} &\equiv& \epsilondimless -q_A\,\frac{d \epsilondimless}{dq_A}-q_B\,\frac{d \epsilondimless}{dq_B} =\frac{\big(q_A^2\,q_B^2-3\,\delta_\text{eff}\big)\,\big(q_A^4-q_B^4\big)} {\big(\delta_\text{eff}+q_A^2\,q_B^2\big)^2}\;,\\[2mm] r_\sigma&=&|\dot{\sigma}|^2+u(\sigma)=|\dot{\sigma}|^2+m^2\,|\sigma|^2\,, \eeqa \esubeqs with $\delta_\text{eff}\equiv\delta\,|\sigma|^2/(|\sigma|^2+\eta)$ from \eqref{eq:model-delta-eff} and $r_\sigma$ corresponding to the dimensionless energy density from the scalar field. In conjunction with the four ODEs mentioned in the previous paragraph, \eqref{eq:Friedmann-ODE} acts as a constraint equation: if \eqref{eq:Friedmann-ODE} is satisfied by the initial boundary conditions, it is always satisfied~\cite{EmelyanovKlinkhamer2011}. Observe that, in terms of dimensionful variables, the vacuum energy density $\widetilde{\epsilon}$ on the right-hand side of \eqref{eq:Friedmann-ODE} differs from the vacuum energy density $\epsilon$ entering the action \eqref{eq:model-action}. The possible difference of $\widetilde{\epsilon}$ and $\epsilon$ is one of the main results of $q$--theory (see the original article Ref.~\cite[(a)]{KV2008-2010} or the one-page summary of Appendix~A in Ref.~\cite{KV2011-review}). \section{Results}\label{sec:Results} Numerical solutions of the reduced field equations are presented in four figures. All of these results are obtained from a single model, specified by the action \eqref{eq:model-action} and \textit{Ansatz} \eqref{eq:Dolgov-Ansatz}, and are differentiated only by their model parameters (e.g., $\Lambda$ zero or not) and initial boundary conditions (e.g., initial vector-field values zero or not). In principle, the numerical calculation must be performed for a small but nonzero value of $\eta$ (for example, $\eta=10^{-4}$), but the numerical calculation at large values of $\tau$ is speeded up by taking the value $\eta=0$. Figure~\ref{fig:1new} shows an inflationary epoch, followed by a standard FRW-like expansion phase with $h \sim (2/3)\,\tau^{-1}$ due to the fact that $\sigma(\tau)$ rapidly spirals inward towards the minimum $\sigma_\text{min}=0$.\footnote{Generically, $\sigma(\tau)$ does not hit $0$ at a finite value of $\tau$ and the same holds for $\delta_\text{eff}$ from \eqref{eq:model-delta-eff}. This is the reason for using a complex scalar rather than a single real scalar which passes through $0$ many times.} (The main characteristics of this particular type of slow-roll inflation, for the case of a single real scalar field, are discussed in Sec.~5.4.1 of Ref.~\cite{Mukhanov2005}.) Here, the total scalar potential $U_\text{tot}$ in \eqref{eq:model-Utot} has its minimum energy fine-tuned to zero, that is $\Lambda=0$. Figure~\ref{fig:2new} shows that removing the fine-tuning by changing $\Lambda$ to a positive value leads to eternal inflation without a subsequent FRW-like phase, due to the presence of a nonzero value of the vacuum energy density (effective cosmological constant) even if $\sigma(t)\to 0$. Figure~\ref{fig:3new} shows that having small but nonzero initial values of the vector fields leads to the termination of the inflationary phase by the eventual vector-field cancellation of the initial cosmological constant $\Lambda\ne 0$. Changing the value of $\lambda\equiv \Lambda/(E_\text{Planck})^4$ from $0.01$ to $0.03$ or to $0.0075$ gives similar results. Returning to $\lambda=0.01$, it has also been verified that setting $\eta=10^{-4}$ gives essentially the same results as for $\eta=0$ up to $\tau=450$. Figure~\ref{fig:4new} shows the absence of a significant inflationary phase for large enough initial values of the vector fields, due to the immediate and complete vector-field cancellation of $\lambda+u(\sigma)$. Again, it has been verified that setting $\eta=10^{-4}$ gives essentially the same results as for $\eta=0$ up to $\tau=10^4$. Two final comments are as follows. First, it is seen that $\tau^{-1}\,v(\tau)$ in Fig.~\ref{fig:3new} or Fig.~\ref{fig:4new} peaks when $\tau\,h(\tau)$ first drops to $1$, the position and height of the $\tau^{-1}\,v(\tau)$ peak depending on the initial conditions. Strictly speaking, this observation also holds for Fig.~\ref{fig:2new}, with the position of the peak moved off towards infinity. Second, extending the numerical solutions of Figs.~\ref{fig:3new} and \ref{fig:4new} to $\tau=10^6$, the asymptotic behavior appears to be $v\sim (q_{A0}/2)\,\tau$, $w\sim (q_{B0}/2)\,\tau$, and $h \sim 1/\tau$. If confirmed, this asymptotic behavior would correspond to a different branch than the one found numerically in Ref.~\cite{EmelyanovKlinkhamer2011} (for the theory without scalars) and would in fact correspond to the standard $q$--theory branch~\cite[(c)]{KV2008-2010} with constant vacuum variables $q_A\equiv \sqrt{\dot{v}^2+3\,h^2\, v^2}=q_{A0}$ and $q_B\equiv \sqrt{\dot{w}^2+3\,h^2\, w^2}=q_{B0}$. \section{Discussion}\label{sec:Discussion} The results of Fig.~\ref{fig:4new} were to be expected. The surprising (and encouraging?) results are those of Fig.~\ref{fig:3new}, with an inflationary phase of some 10 $e$-foldings of $a(\tau)$ for the model and parameters chosen. (Different initial conditions have been seen to give some 30 $e$-foldings and Fig.~\ref{fig:2new} can be interpreted as having infinitely many $e$-foldings.) Qualitatively, the Hubble parameter $h(\tau)$ of the top right panel in Fig.~\ref{fig:3new} ($\lambda \ne 0$) resembles that of Fig.~\ref{fig:1new} ($\lambda = 0$), even though the detailed behavior differs as shown by the respective bottom right panels. The results of Fig.~\ref{fig:3new} are, of course, only exploratory. It remains, for example, to analyze the nonlinear dynamics displayed in Fig.~\ref{fig:3new} and to rigorously establish the $\tau\to\infty$ limit for the $\eta=10^{-4}$ case, corresponding respectively to an early phase with inflation\footnote{Possible observable effects may come from the dynamics of density perturbations with near-horizon wavelengths (cf. Ref.~\cite{Mukhanov2005}), as the dynamics can be expected to be modified by the interaction between the scalar (inflaton) field and the vector fields needed for the cancellation of the \mbox{bare cosmological constant $\Lambda$.}} and a late (FRW-like) phase with standard local Newtonian dynamics. The main result of this article is that, in principle, it appears to be possible to have both an early phase with inflation and a late phase with a dynamically canceled cosmological constant $\Lambda$. The details of the model are of secondary importance. What matters is the general mechanism which relies on the dynamics of the massless vector fields (or possibly massless tensor fields). The physical origin of these massless vector (tensor) fields needs to be clarified. \newpage \begin{figure*}[th \begin{center} \hspace*{-6mm} \includegraphics[width=1.05\textwidth]{ccp1-inflation_fig1_v4.eps} \end{center} \vspace*{-5mm} \caption{Numerical solution of the reduced field equations for model \eqref{eq:model} and \textit{Ansatz} \eqref{eq:Dolgov-Ansatz}. The dimensionless model parameters are $m=0.01$, $\delta=10^{-6}$, $\eta=0$, and $\lambda=0$. The boundary conditions are $a(1)=1$, $\{\varphi_1(1),\,\dot{\varphi}_1(1),\,\varphi_2(1),\,\dot{\varphi}_2(1)\}$ $=$ $\{10,\, -0.25,\, 0,\, -0.433013 \}$, and $v(1)=\dot{v}(1)= w(1)=\dot{w}(1)=0$. [The real scalars $\varphi_n$ are defined by $\sigma\equiv (\varphi_1+i\,\varphi_2)/\sqrt{2}$.] The value of $h(1)$ follows from the Friedmann equation \eqref{eq:Friedmann-ODE}. With these boundary conditions, the reduced field equations have the exact solution $v(\tau)=w(\tau)=0$ for $\tau \geq 1$. The top right panel shows an $h(\tau)$ plateau corresponding to an inflationary phase. The bottom right panel shows that, long after inflation, $h(\tau)$ asymptotically goes as $(2/3)\,\tau^{-1}$. \vspace*{0cm} } \label{fig:1new} \end{figure*} \begin{figure*}[h \vspace*{0cm} \begin{center} \hspace*{-6mm} \includegraphics[width=1.05\textwidth]{ccp1-inflation_fig2_v4.eps} \end{center} \vspace*{-5mm} \caption{Same as Fig.~\ref{fig:1new}, but now with nonzero cosmological constant, $\lambda=0.01$. Same boundary conditions as Fig.~\ref{fig:1new}, so that the exact solution $v(\tau)=w(\tau)=0$ persists. The Friedmann equation \eqref{eq:Friedmann-ODE} gives the asymptotic value $h(\infty)=\sqrt{\lambda/3}\approx 0.05774$. \vspace*{-4cm} } \label{fig:2new} \end{figure*} \newpage \begin{figure*}[th \begin{center} \hspace*{-6mm} \includegraphics[width=1.05\textwidth]{ccp1-inflation_fig3_v4.eps} \end{center} \vspace*{-5mm} \caption{Same parameters and boundary conditions as Fig.~\ref{fig:2new} (e.g., $\lambda=0.01$), except for small but nonzero starting values of $v$ and $w$. Specifically, the boundary conditions at $\tau=1$ are $\{a,\,v,\,\dot{v},\,w,\,\dot{w},\,h,\, \varphi_1,\,\dot{\varphi}_1,\,\varphi_2,\,\dot{\varphi}_2\}$ $=$ $\{1,\,2\times 10^{-4},\,2\times 10^{-4},\,2\times 10^{-4},\,2\times 10^{-4}$, $0.216025$, $10,\, -0.25,\, 0,\, -0.433013 \}$. The total vacuum energy density entering the right-hand side of the Friedmann equation \eqref{eq:Friedmann-ODE} is given by the sum of the two panels in the middle column and vanishes asymptotically. \vspace*{1\baselineskip}} \label{fig:3new} \end{figure*} \begin{figure*}[h \vspace*{0cm} \begin{center} \hspace*{-6mm} \includegraphics[width=1.05\textwidth]{ccp1-inflation_fig4_v4.eps} \end{center} \vspace*{-5mm} \caption{Same parameters and boundary conditions as Fig.~\ref{fig:3new} (e.g., $\lambda=0.01$), except for relatively large starting values of $v$ and $w$. Specifically, the boundary conditions at $\tau=1$ are $\{a,\,v,\,\dot{v},\,w,\,\dot{w},\,h,\, \varphi_1,\,\dot{\varphi}_1,\,\varphi_2,\,\dot{\varphi}_2\}$ $=$ $\{1,\,0.0799201,\, 0.01998,\, 0.08,\, 0.02$, $0.216961$, $10,\, -0.25,\, 0,\, -0.433013 \}$. \vspace*{-4cm} } \label{fig:4new} \end{figure*} \newpag \section*{\hspace*{-4.5mm}ACKNOWLEDGMENTS} \noindent It is a pleasure to thank G.E. Volovik for numerous discussions on the cosmological constant problem, V. Emelyanov for a valuable suggestion, and S. Thambyahpillai for helpful comments on the manuscript.
{ "redpajama_set_name": "RedPajamaArXiv" }
5,669
Bavarois â la Framboise or Bavarian Cream with Raspberry Coulis. A few weeks ago, I introduced zabaglione, an Italian dessert made with egg yolks, sugar and wine and a few months ago, sabayon, a french dessert that is the same exact thing. Today, I am talking about another dessert that depends upon whisked egg yolks and sugar, only mixed into boiled milk. Each get the same heavy whisking, but this process is called créme anglaise. You will recognize this as the base of ice cream. Interestingly though, a gelatin is mixed in and then this is cooled before whipped heavy cream is folded in. At this point the entire mixture is turned into a mold, chilled for several hours and is now called bavarois. Serve with a raspberry coulis and it is Bavarois â la Framboise. Did you get all that? If I sound very smart, like I've been making sabayon, and bavarois all my life, take heart. Until two weeks ago, I had never made a zabaglione, and if you take a good look at the picture, you can clearly see that until today I never made a bavarois. I never read enough ahead to realize that it went into a mold. This is an example of making something completely blind. Le Cordon Bleu at Home did not show a picture of this, and in all honesty, I had no idea what it was supposed to be. To further the kitchen fiasco, two little two-year olds were under foot, watching my every move. The infatuation with the mixer, and the whisking, which believe it or not I was doing at the same exact time, kept my audience still, at least for enough time to whip the cream. At one point, one little boy had to be held during the remaining whisking and help a little to see what was going on. There was a moment the beater with whipped cream was on the floor, and when I read that I needed a mold, I just laughed and made my memorable mistake. Once you pour your bavarian cream (bavarois) into a mold, do not touch it. Once your bavarois is poured, you have a few seconds to smooth it out with a spatula and that's it. The smooth texture will change, similar to marshmallow cream. This doesn't affect the taste at all, which is heavenly. How could it not be with milk, cream, egg yolks, vanilla bean, sugar and lots of whisking? Unlike sabayon or zabaglione, which is soupy, the gelatin gives this it's body, so it has a thicker texture and will hold up in a pastry. I can only dream for such a pastry as I write this, but it will give me a future reason to revisit bavarois and perhaps perfect it. The recipe instructions can be found in Le Cordon Bleu at Home.
{ "redpajama_set_name": "RedPajamaC4" }
4,337
TAKE THE PLEDGE AND JOIN US TO PROTECT NORTH CAROLINA'S BIRDS. Nearly 200 species of birds found in North Carolina are at risk because of the damaging effects of climate change. If we don't take action now many of those birds might be gone forever. Audubon's Birds and Climate Change Report found that 1 in 5 of our birds in the continental US and Canada are at risk of suffering severe declines by 2050 without immediate action to reverse climate change. That is within our children's lifetime. But armed with this science, we have an opportunity to create a different outcome. Audubon is sounding the warning bell, and we are inviting everyone to join us. The time is now to make real and lasting change for the future – for birds, for ourselves and for generations to come. All of Audubon's work in North Carolina to protect habitats and birds, to drive public policy and to engage citizens becomes even more important as birds are forced to make changes while adapting to the effects of climate change. It will take all of us acting together to secure a better future for the birds we care about. Climate change is affecting many of the birds we love. Among the species listed as climate threatened or endangered are the Brown-headed Nuthatch, Wood Thrush, American Oystercatcher and many more. Learn about a few of the birds and our work to protect them. Birds are stepping up once again to be our watchdog and to give us hope. Climate change can seem like such a large and daunting issue, but birds can show us the way to solutions and motivate us to change. It's not too late. Join us, and pledge to take action to help climate threatened birds. Small changes will add up to a brighter future for birds and for ourselves. So encourage your friends, family, church and work communities to take the pledge too. Pledge to help protect North Carolina's birds against climate change. Take flight with this important news! Ask your friends to join you and take the pledge to protect birds from climate change.
{ "redpajama_set_name": "RedPajamaC4" }
6,832
HMS M28 був одним з моніторів типу M15. Корабель потоплений у ході битви при Імбросі 1918 року. Конструкція Призначений для обстрілів берегових цілей, в якості основного озброєння M28 отримав одну 9.2 дюймову гармату Mk X, зняту з крейсера типу Едгар HMS Grafton. Крім того, на моніторі встановили 76,2 мм гармату, а також 57 міліметрову зенітку. Корабель мав чотирициліндровий Боліндера потужністю 640 кінських сил, який дозволяв розвивати швидкість до 11 вузлів. Екіпаж складався з 69 офіцерів і матросів. Будівництво HMS M28 був закладений на верфі Sir Raylton Dixon & Co. Ltd в Говані 1 березня 1915 року. Корабель спущено на воду 28 червня 1915 року, а завершено в серпні 1915 року. Служба Протягом більшої частини служби в Першій світовій війні М28 входив до Егейської ескадри та виконував завдання з обстрілів прибережних турецьких позицій. 21 жовтня 1915 року вона обстріляла болгарський порт Дедеагач. 20 січня 1918 року корабель знаходився бухті Кусу на острові Імброс, коли цю стоянку атакували напали два турецькі кораблі. Колишні SMS Goeben та SMS  Бреслау вдалося заблокувати М28 і "Раглан" в бухті і потопити їх. М28 затонув, загинуло 11 членів екіпажу, решту врятували інші кораблі. Посилання Література Colledge, J. J.; Warlow, Ben (2006) [1969]. Ships of the Royal Navy: The Complete Record of all Fighting Ships of the Royal Navy (Rev. ed.). London: Chatham Publishing. ISBN 978-1-86176-281-8. OCLC 67375475. Jane's Fighting Ships of World War One (1919), Jane's Publishing Company Dittmar, F. J. & Colledge, J. J., "British Warships 1914–1919", (Ian Allan, London, 1972), Кораблі 1915 Картки суден без зображення 28
{ "redpajama_set_name": "RedPajamaWikipedia" }
9,588
Q: php script to scrape emails for appointments and generate a .ics file to be emailed to relevant User for easy scheduling I work in a business where we have a hosted CRM which sends out jobsheets we are trying to code a script in php which emails us calendar entries for jobs assigned to us currently the code (below) scrapes our email and emails us a .ics but it's output while a valid .ics file (we can manually import them) doesn't appear in the email as an acceptable invite so we can simply accept the entry Advice & codesnippets appreciated --Original code-- $mbox=FALSE; $imap_username="User@tbclaunceston.com.au"; $imap_password="Password"; $connection="{".$server.":".$port."}".$path; $mbox=imap_open($connection, $imap_username, $imap_password); $messages=imap_search($mbox, 'UNSEEN SUBJECT "Commtrak: Job Card"'); foreach($messages as $message){ //var_dump(imap_header($mbox,$message)); $bodynormal = imap_body($mbox,$message); $body = str_replace(" "," ",strip_tags($bodynormal)); $to = $imap_username; $subjectsearch = array("Company Name:","Job ID:"); $subject = locatedata($body,"Company Name:","Job ID:"); $organizer = 'CommTrak'; $organizer_email = 'testaccount1@tbclaunceston.com.au'; $participant_name_1 = 'User'; $participant_email_1= $imap_username; if(strpos($body,"Sales Contact:")!=false){ $search = "Sales Contact:"; } else{ $search = "Customer Contact:"; } if(locatedata($body,"Site Address:",$search)=="As Above"){ $location = locatedata($body,"Customer Address:","Site Address:"); } else{ $location = locatedata($body,"Site Address:",$search); } $date = "20".implode('', array_reverse(explode("/",locatedata($body,"Date:","Time:")))); $startTime = locatedata($body,"Time:","For:"); $endTime = date("H:i",strtotime($startTime." +".str_replace("hrs","hours",locatedata($body,"For:","JOB DESCRIPTION:")))); $startTime = str_replace(":","",$startTime); $endTime = str_replace(":","",$endTime); $desc = locatedata($body,"JOB DESCRIPTION:","CO Number:"); $headers = "From: CommTrak Jobs <testaccount1@tbclaunceston.com.au>\n"; $headers .= "MIME-Version: 1.0\n"; $headers .= "Content-Type: text/calendar; charset=utf-8; name=jobcard.ics; method=REQUEST\r\n"; $headers .= "Content-Disposition: inline; filename='jobcard.ics'\r\n"; //$headers .= "Content-class','urn:content-classes:calendarmessage"; $headers .= "Content-Transfer-Encoding: base64"; $message = "BEGIN:VCALENDAR\r\nMETHOD:REQUEST\r\nPRODID:Microsoft Exchange Server 2010\r\nVERSION:2.0\r\nBEGIN:VTIMEZONE\r\nTZID:Tasmania Standard Time\r\nBEGIN:STANDARD\r\nDTSTART:16010101T030000\r\nTZOFFSETFROM:+1100\r\nTZOFFSETTO:+1000\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=4\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nDTSTART:16010101T020000\r\nTZOFFSETFROM:+1000\r\nTZOFFSETTO:+1100\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=10\r\nEND:DAYLIGHT\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nORGANIZER;CN=".$organizer.":mailto:".$organizer_email."\r\nATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=".$participant_name_1.":MAILTO:".$participant_email_1."\r\nDESCRIPTION;LANGUAGE=en-US:".$desc."\r\nUID:".md5(uniqid(mt_rand(),true))."tbclaunceston.com.au\r\nSUMMARY;LANGUAGE=en-US:".$subject."\r\nDTSTART;TZID='Tasmania Standard Time':".$date."T".$startTime."00\r\nDTEND;TZID='Tasmania Standard Time':".$date."T".$endTime."00\r\nCLASS:PUBLIC\r\nPRIORITY:5\r\nDTSTAMP:".gmdate('Ymd').'T'.gmdate('His')."Z\r\nTRANSP:OPAQUE\r\nSTATUS:CONFIRMED\r\nSEQUENCE:0\r\nLOCATION;LANGUAGE=en-US:".$location."\r\nX-MICROSOFT-CDO-APPT-SEQUENCE:0\r\nX-MICROSOFT-CDO-OWNERAPPTID:1787906015\r\nX-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE\r\nX-MICROSOFT-CDO-INTENDEDSTATUS:BUSY\r\nX-MICROSOFT-CDO-ALLDAYEVENT:FALSE\r\nX-MICROSOFT-CDO-IMPORTANCE:1\r\nX-MICROSOFT-CDO-INSTTYPE:0\r\nX-MICROSOFT-DISALLOW-COUNTER:FALSE\r\nBEGIN:VALARM\r\nDESCRIPTION:REMINDER\r\nTRIGGER;RELATED=START:-PT15M\r\nACTION:DISPLAY\r\nEND:VALARM\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; //$headers .= $message; $message = base64_encode($message); mail($to, $subject, $message, $headers); break; //echo $message."\r\n***********************\r\n"; } ?> --Current Code Iteration $connection="{".$server.":".$port."}".$path; $mbox=imap_open($connection, $imap_username, $imap_password); $messages=imap_search($mbox, 'UNSEEN SUBJECT "Commtrak: Job Card"'); foreach($messages as $message){ //var_dump(imap_header($mbox,$message)); $boundary=uniqid("np"); $bodynormal = imap_body($mbox,$message); $body = str_replace("&nbsp;"," ",strip_tags($bodynormal)); //$to = $imap_username; $to = "testaccount@gmail.com"; $subjectsearch = array("Company Name:","Job ID:"); $subject = locatedata($body,"Company Name:","Job ID:"); $organizer = 'CommTrak'; $organizer_email = 'testaccount1@tbclaunceston.com.au'; $participant_name_1 = 'a User'; $participant_email_1= $imap_username; if(strpos($body,"Sales Contact:")!=false){ $search = "Sales Contact:"; } else{ $search = "Customer Contact:"; } if(locatedata($body,"Site Address:",$search)=="As Above"){ $location = locatedata($body,"Customer Address:","Site Address:"); } else{ $location = locatedata($body,"Site Address:",$search); } $date = "20".implode('', array_reverse(explode("/",locatedata($body,"Date:","Time:")))); $startTime = locatedata($body,"Time:","For:"); $endTime = date("H:i",strtotime($startTime." +".str_replace("hrs","hours",locatedata($body,"For:","JOB DESCRIPTION:")))); $startTime = str_replace(":","",$startTime); $endTime = str_replace(":","",$endTime); $desc = locatedata($body,"JOB DESCRIPTION:","CO Number:"); $headers = "From: CommTrak Jobs <testaccount1@tbclaunceston.com.au>\n"; $headers .= "MIME-Version: 1.0\r\n"; $headers .= "To:".$to."\r\n"; $headers .= "Content-type:multipart/alternative;boundary=".$boundary."\r\n\r\n--".$boundary."\r\n"; $headers .= "Content-Type: text/calendar; charset=utf-8; name=jobcard.ics; method=REQUEST\r\n"; $headers .= "Content-Disposition: inline; filename='jobcard.ics'\r\n"; //$headers .= "Content-class','urn:content-classes:calendarmessage"; $headers .= "Content-Transfer-Encoding: base64; //boundary=".$boundary."\r\n"; $message = "BEGIN:VCALENDAR\r\nMETHOD:REQUEST\r\nPRODID:Microsoft Exchange Server 2010\r\nVERSION:2.0\r\nBEGIN:VTIMEZONE\r\nTZID:Tasmania Standard Time\r\nBEGIN:STANDARD\r\nDTSTART:16010101T030000\r\nTZOFFSETFROM:+1100\r\nTZOFFSETTO:+1000\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=4\r\nEND:STANDARD\r\nBEGIN:DAYLIGHT\r\nDTSTART:16010101T020000\r\nTZOFFSETFROM:+1000\r\nTZOFFSETTO:+1100\r\nRRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=10\r\nEND:DAYLIGHT\r\nEND:VTIMEZONE\r\nBEGIN:VEVENT\r\nORGANIZER;CN=".$organizer.":mailto:".$organizer_email."\r\nATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=".$participant_name_1.":MAILTO:".$participant_email_1."\r\nDESCRIPTION;LANGUAGE=en-US:".$desc."\r\nUID:".md5(uniqid(mt_rand(),true))."tbclaunceston.com.au\r\nSUMMARY;LANGUAGE=en-US:".$subject."\r\nDTSTART;TZID='Tasmania Standard Time':".$date."T".$startTime."00\r\nDTEND;TZID='Tasmania Standard Time':".$date."T".$endTime."00\r\nCLASS:PUBLIC\r\nPRIORITY:5\r\nDTSTAMP:".gmdate('Ymd').'T'.gmdate('His')."Z\r\nTRANSP:OPAQUE\r\nSTATUS:CONFIRMED\r\nSEQUENCE:0\r\nLOCATION;LANGUAGE=en-US:".$location."\r\nX-MICROSOFT-CDO-APPT-SEQUENCE:0\r\nX-MICROSOFT-CDO-OWNERAPPTID:1787906015\r\nX-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE\r\nX-MICROSOFT-CDO-INTENDEDSTATUS:BUSY\r\nX-MICROSOFT-CDO-ALLDAYEVENT:FALSE\r\nX-MICROSOFT-CDO-IMPORTANCE:1\r\nX-MICROSOFT-CDO-INSTTYPE:0\r\nX-MICROSOFT-DISALLOW-COUNTER:FALSE\r\nBEGIN:VALARM\r\nDESCRIPTION:REMINDER\r\nTRIGGER;RELATED=START:-PT15M\r\nACTION:DISPLAY\r\nEND:VALARM\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"; //$message = base64_encode($message); $message .= "\r\n\r\n--".$boundary."\r\n"; mail($to, $subject, $message, $headers); break; //echo $message."\r\n***********************\r\n"; } ?> --Resultant Message output Delivered-To: testaccount@gmail.com Received: by 10.140.163.3 with SMTP id j3csp923632qhj; Tue, 21 Apr 2015 17:26:48 -0700 (PDT) X-Received: by 10.68.111.35 with SMTP id if3mr38633671pbb.70.1429662408016; Tue, 21 Apr 2015 17:26:48 -0700 (PDT) Return-Path: <root@tclp-28.localdomain> Received: from tclp-28.localdomain (totalc92.lnk.telstra.net. [120.151.44.165]) by mx.google.com with ESMTP id u7si5131112pbs.1.2015.04.21.17.26.47 for <testaccount@gmail.com>; Tue, 21 Apr 2015 17:26:47 -0700 (PDT) Received-SPF: none (google.com: root@tclp-28.localdomain does not designate permitted sender hosts) client-ip=120.151.44.165; Authentication-Results: mx.google.com; spf=none (google.com: root@tclp-28.localdomain does not designate permitted sender hosts) smtp.mail=root@tclp-28.localdomain Received: by tclp-28.localdomain (Postfix, from userid 0) id 8C7EED40968; Wed, 22 Apr 2015 10:26:45 +1000 (AEST) To: testaccount@gmail.com Subject: ROBERT FINDLAY X-PHP-Originating-Script: 1000:ICSconverter3.php From: CommTrak Jobs <testaccount1@tbclaunceston.com.au> MIME-Version: 1.0 To:testaccount@gmail.com Content-type:multipart/alternative;boundary=np5536eac52d6fe Message-Id: <20150422002645.8C7EED40968@tclp-28.localdomain> Date: Wed, 22 Apr 2015 10:26:45 +1000 (AEST) --np5536eac52d6fe Content-Type: text/calendar; charset=utf-8; name=jobcard.ics; method=REQUEST Content-Disposition: inline; filename='jobcard.ics' Content-Transfer-Encoding: base64; //boundary=np5536eac52d6fe BEGIN:VCALENDAR METHOD:REQUEST PRODID:Microsoft Exchange Server 2010 VERSION:2.0 BEGIN:VTIMEZONE TZID:Tasmania Standard Time BEGIN:STANDARD DTSTART:16010101T030000 TZOFFSETFROM:+1100 TZOFFSETTO:+1000 RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=4 END:STANDARD BEGIN:DAYLIGHT DTSTART:16010101T020000 TZOFFSETFROM:+1000 TZOFFSETTO:+1100 RRULE:FREQ=YEARLY;INTERVAL=1;BYDAY=1SU;BYMONTH=10 END:DAYLIGHT END:VTIMEZONE BEGIN:VEVENT ORGANIZER;CN=CommTrak:mailto:testaccount1@tbclaunceston.com.au ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE;CN=a User:MAILTO:testaccount@tbclaunceston.com.au DESCRIPTION;LANGUAGE=en-US:On site set-up for office 365. installing accounts/products on devices UID:c1cb622dd0d1ecdc9e93f778d0b7964atbclaunceston.com.au SUMMARY;LANGUAGE=en-US:Agent Smith DTSTART;TZID='Tasmania Standard Time':20150424T-00 DTEND;TZID='Tasmania Standard Time':20150424T100000 CLASS:PUBLIC PRIORITY:5 DTSTAMP:20150422T002645Z TRANSP:OPAQUE STATUS:CONFIRMED SEQUENCE:0 LOCATION;LANGUAGE=en-US:123 some where RD X-MICROSOFT-CDO-APPT-SEQUENCE:0 X-MICROSOFT-CDO-OWNERAPPTID:1787906015 X-MICROSOFT-CDO-BUSYSTATUS:TENTATIVE X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY X-MICROSOFT-CDO-ALLDAYEVENT:FALSE X-MICROSOFT-CDO-IMPORTANCE:1 X-MICROSOFT-CDO-INSTTYPE:0 X-MICROSOFT-DISALLOW-COUNTER:FALSE BEGIN:VALARM DESCRIPTION:REMINDER TRIGGER;RELATED=START:-PT15M ACTION:DISPLAY END:VALARM END:VEVENT END:VCALENDAR --np5536eac52d6fe A: Well you have a multipart/alternative containing only the text/calendar part which is OK but not very useful. Then you have a content-transfer-encoding when in fact your body part is not b64 encoded. You also have this strange comment line after the last header (" //boundary=np5536eac52d6fe"). Finally, your DTSTART is invalid: "20150424T-00"
{ "redpajama_set_name": "RedPajamaStackExchange" }
1,112
Q: Context getRealPath() for non-existent file Can someone explain what is the difference between the following two calls to ServletContext getRealPath() in Tomcat: * *context.getRealPath("/") + "\\songModified.wav"; *context.getRealPath("/" + "\\songModified.wav"); I have a very simple GET method on the server which reads a file on the server and copies the bytes into a new file in the location returned by the above call. On the client side I have an audio tag that references an audio file on the server, calls this method that creates a new file and changes the reference of the audio tag to this new file. The thing is that in the javascript callback this new file is not immediately referenceable if I store the file to the path that is returned from the second case of the above getRealPath call. Basically it returns a 404. If I store it to the returned path of the first case of the call then it is immediately referenceable and the audio tag normaly references the new file. Both of those calls to getRealPath() return exactly the same string: C:\Users\Mihael\apache-tomcat-9.0.31\wtpwebapps\AudioSimulator\songModified.wav I am passing this returned string to the FileOutputStream constructor further in the code. Thing to note here is that this file does not exist at the moment of the getRealPath() call so I am confused why is it returning anything at all in the second case of the call. I know this is not the recommended way of storing files so I am asking from a purely educational perspective. How can the second call to this method break my functionality if they both return exactly the same string to the rest of the code? EDIT: Here is a very simple Javascript and Java code for anyone who wants to test this. Javascript: <body> <script> function modifyRequest() { var xhttp = new XMLHttpRequest(); xhttp.onload = function() { var audio = document.getElementById("player"); var currentTime = audio.currentTime; audio.src = "http://localhost:8080/AudioSimulator/bluesModified.wav"; audio.currentTime = currentTime; audio.play(); }; xhttp.open("GET", "http://localhost:8080/AudioSimulator/rest/Test/testPath"); xhttp.send(); } </script> <audio id="player" src="http://localhost:8080/AudioSimulator/blues.wav" controls> Your browser does not support the <code>audio</code> element. </audio> <button onclick="modifyRequest()">Test</button> </body> Java: @Path("/Test") public class Test { @Context ServletContext context; @GET @Path("/testPath") public Response testPath() { File fileIn = new File(context.getRealPath("/") + "\\blues.wav"); File fileOut = new File(context.getRealPath("/" + "\\bluesModified.wav")); //if i write it like this it would work //File fileOut = new File(context.getRealPath("/") + "\\bluesModified.wav"); FileInputStream fis = null; FileOutputStream fos = null; try { fis = new FileInputStream(fileIn); fos = new FileOutputStream(fileOut); byte[] inArray = new byte[(int) fileIn.length()]; try { fis.read(inArray); fos.write(inArray); } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } finally { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } return Response .ok() .entity("Success") .header("Access-Control-Allow-Origin", "null") .build(); } } A: I have taken the time to dive into Tomcat source to find the cause for this. It turns out that getRealPath, in addition to retrieving the system path for a given virtual path, also works a bit with the Tomcat cache. NOTE: I know that my file separator usage is not good, but Tomcat is smart enough to validate the above call to produce /bluesModified.wav. So even if I call it like @rickz mentioned in the comments, the result would be the same and therefore that was not the issue. The issues I had with being unable to reference the file in the case of the following call context.getRealPath("/" + "\\bluesModified.wav") was the fact that in this case we are passing the file path to the method, while in the case that works we are passing in the directory path. What happens is that the call to getRealPath() first checks the cache for the existence of the resource identified by the webapppath /bluesModified.wav. Since it does not exist at the moment of the call, Tomcat will create an instance of the EmptyResource class which is basically a wrapper around File class and represents a file that does not exist, and it will then store the reference to this file in its cache. The issue here is that even though I create a file that will have the correct virtual path Tomcat will still have that empty resource representing a non existent file in its cache. In other words, if I reference the file from the client side like so http://localhost:8080/AudioSimulator/bluesModified.wav Tomcat will return the cached resource that represents the empty file, which actually means a 404 to the client even though the file exists. Waiting for 5 seconds, which is the time to live of Tomcat cache entries, and then trying to reference the file will revalidate the cache entry and produce a FileResource instead of EmptyResource in which case the referencing will work normally. It works in this case context.getRealPath("/") + "\\bluesModified.wav" since the path that is getting cached is a directory and the file name is simply concatenated. So the string I have here is just an absolute path to the file I am going to create with no cache entries colliding with it. My mistake was assuming that getRealPath() is just some "pure" method that will return a string I can use to create files while in fact it has a bit of side effects. These side effects are not documented and even though I might have done some things incorrectly the bottom line is this method is not that predictable to use when doing File IO stuff. A: The String returned by getRealPath from the ServletContext implementation is normalized. So when you call getRealPath("/") + "\blues.wav") only the String "/" is normalized, and the String concatenation "\blues.wav" is not. But when you call getRealPath("/" + "\blues.wav")) the full concatened String is normilized. public String getRealPath(String path) { if ("".equals(path)) { path = "/"; } if (this.resources != null) { try { WebResource resource = this.resources.getResource(path); String canonicalPath = resource.getCanonicalPath(); if (canonicalPath == null) { return null; } if ((resource.isDirectory() && !canonicalPath.endsWith(File.separator) || !resource.exists()) && path.endsWith("/")) { return canonicalPath + File.separatorChar; } return canonicalPath; } catch (IllegalArgumentException var4) { } } return null; } You can see WebResource resource = this.resources.getResource(path) will try to validate your path and will return a validated path : private String validate(String path) { if (!this.getState().isAvailable()) { throw new IllegalStateException(sm.getString("standardRoot.checkStateNotStarted")); } else if (path != null && path.length() != 0 && path.startsWith("/")) { String result; if (File.separatorChar == '\\') { result = RequestUtil.normalize(path, true); } else { result = RequestUtil.normalize(path, false); } if (result != null && result.length() != 0 && result.startsWith("/")) { return result; } else { throw new IllegalArgumentException(sm.getString("standardRoot.invalidPathNormal", new Object[]{path, result})); } } else { throw new IllegalArgumentException(sm.getString("standardRoot.invalidPath", new Object[]{path})); } }
{ "redpajama_set_name": "RedPajamaStackExchange" }
5,875
package org.apache.hadoop.yarn.server.nodemanager.security; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.classification.InterfaceAudience.Private; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.security.UserGroupInformation; import org.apache.hadoop.security.token.SecretManager; import org.apache.hadoop.yarn.api.records.ApplicationId; import org.apache.hadoop.yarn.api.records.ContainerId; import org.apache.hadoop.yarn.security.ContainerTokenIdentifier; import org.apache.hadoop.yarn.server.api.records.MasterKey; import org.apache.hadoop.yarn.server.security.BaseContainerTokenSecretManager; /** * The NM maintains only two master-keys. The current key that RM knows and the * key from the previous rolling-interval. * */ public class NMContainerTokenSecretManager extends BaseContainerTokenSecretManager { private static final Log LOG = LogFactory .getLog(NMContainerTokenSecretManager.class); private MasterKeyData previousMasterKey; private final Map<ApplicationId, ConcurrentMap<ContainerId, MasterKeyData>> oldMasterKeys; public NMContainerTokenSecretManager(Configuration conf) { super(conf); this.oldMasterKeys = new HashMap<ApplicationId, ConcurrentMap<ContainerId, MasterKeyData>>(); } /** * Used by NodeManagers to create a token-secret-manager with the key obtained * from the RM. This can happen during registration or when the RM rolls the * master-key and signals the NM. * * @param masterKeyRecord */ @Private public synchronized void setMasterKey(MasterKey masterKeyRecord) { LOG.info("Rolling master-key for container-tokens, got key with id " + masterKeyRecord.getKeyId()); if (super.currentMasterKey == null) { super.currentMasterKey = new MasterKeyData(masterKeyRecord); } else { if (super.currentMasterKey.getMasterKey().getKeyId() != masterKeyRecord .getKeyId()) { // Update keys only if the key has changed. this.previousMasterKey = super.currentMasterKey; super.currentMasterKey = new MasterKeyData(masterKeyRecord); } } } /** * Override of this is to validate ContainerTokens generated by using * different {@link MasterKey}s. */ @Override public synchronized byte[] retrievePassword( ContainerTokenIdentifier identifier) throws SecretManager.InvalidToken { int keyId = identifier.getMasterKeyId(); ContainerId containerId = identifier.getContainerID(); ApplicationId appId = containerId.getApplicationAttemptId().getApplicationId(); MasterKeyData masterKeyToUse = null; if (this.previousMasterKey != null && keyId == this.previousMasterKey.getMasterKey().getKeyId()) { // A container-launch has come in with a token generated off the last // master-key masterKeyToUse = this.previousMasterKey; } else if (keyId == super.currentMasterKey.getMasterKey().getKeyId()) { // A container-launch has come in with a token generated off the current // master-key masterKeyToUse = super.currentMasterKey; } else if (this.oldMasterKeys.containsKey(appId) && this.oldMasterKeys.get(appId).containsKey(containerId)) { // This means on the following happened: // (1) a stopContainer() or a getStatus() happened for a container with // token generated off a master-key that is neither current nor the // previous one. // (2) a container-relaunch has come in with a token generated off a // master-key that is neither current nor the previous one. // This basically lets stop and getStatus() calls with old-tokens to pass // through without any issue, i.e. (1). // Start-calls for repetitive launches (2) also pass through RPC here, but // get thwarted at the app-layer as part of startContainer() call. masterKeyToUse = this.oldMasterKeys.get(appId).get(containerId); } if (masterKeyToUse != null) { return retrievePasswordInternal(identifier, masterKeyToUse); } // Invalid request. Like startContainer() with token generated off // old-master-keys. throw new SecretManager.InvalidToken("Given Container " + identifier.getContainerID().toString() + " seems to have an illegally generated token."); } /** * Container start has gone through. Store the corresponding keys so that * stopContainer() and getContainerStatus() can be authenticated long after * the container-start went through. */ public synchronized void startContainerSuccessful( ContainerTokenIdentifier tokenId) { if (!UserGroupInformation.isSecurityEnabled()) { return; } int keyId = tokenId.getMasterKeyId(); if (currentMasterKey.getMasterKey().getKeyId() == keyId) { addKeyForContainerId(tokenId.getContainerID(), currentMasterKey); } else if (previousMasterKey != null && previousMasterKey.getMasterKey().getKeyId() == keyId) { addKeyForContainerId(tokenId.getContainerID(), previousMasterKey); } } /** * Ensure the startContainer call is not using an older cached key. Will * return false once startContainerSuccessful is called. Does not check * the actual key being current since that is verified by the security layer * via retrievePassword. */ public synchronized boolean isValidStartContainerRequest( ContainerTokenIdentifier tokenId) { ContainerId containerID = tokenId.getContainerID(); ApplicationId applicationId = containerID.getApplicationAttemptId().getApplicationId(); return !this.oldMasterKeys.containsKey(applicationId) || !this.oldMasterKeys.get(applicationId).containsKey(containerID); } private synchronized void addKeyForContainerId(ContainerId containerId, MasterKeyData masterKeyData) { if (containerId != null) { ApplicationId appId = containerId.getApplicationAttemptId().getApplicationId(); if (!this.oldMasterKeys.containsKey(appId)) { this.oldMasterKeys.put(appId, new ConcurrentHashMap<ContainerId, MasterKeyData>()); } ConcurrentMap<ContainerId, MasterKeyData> containerIdToKeysMapForThisApp = this.oldMasterKeys.get(appId); containerIdToKeysMapForThisApp.put(containerId, masterKeyData); } else { LOG.warn("Not adding key for null containerId"); } } // Holding on to master-keys corresponding to containers until the app is // finished due to the multiple ways a container can finish. Avoid // stopContainer calls seeing unnecessary authorization exceptions. public synchronized void appFinished(ApplicationId appId) { this.oldMasterKeys.remove(appId); } }
{ "redpajama_set_name": "RedPajamaGithub" }
5,379
WWE filmed their New Year's Eve show tonight in Detroit. There were a few notable matches and segments. If you'd like to read our complete spoilers, get those here. On that note, if you don't like spoilers turn back now. Thanks to one fan video, we've been able to get some good videos fro the show. So if you don't want to wait until Monday, you can get a very good picture about what goes down. They kicked things off this week with a cage match and Drew beat down Dolph Ziggler in a bad way. Ziggler was able to get some heat back on himself, but due to WWE's 50/50 booking, McIntyre got his win back. This was a pretty good cage match and they even pulled off a rather impressive superplex spot to open the show. Elias worked as a babyface as he has since October 22nd when he turned. However, he was still trolled by a fan pretty badly. Then Baron Corbin came down and the two of them ended up having a pretty fun brawl.
{ "redpajama_set_name": "RedPajamaC4" }
1,501
\section{Introduction and definitions} In 2017 \cite{klaassen} a definition of spiral tilings was given, thereby answering a question posed by Gr\"unbaum and Shephard in the late 1970s. The author had the pleasure to discuss the topic via e-mail with Branko Gr\"unbaum in his 87th year. During this correspondence the question arose whether a spiral structure (given a certain definition of it) could be recognized automatically or whether ``to some extent, at least, the spiral effect is psychological\textquotedblright , as Gr\"unbaum and Shephard had conjectured in 1987 (see exercise section of chapter 9.5 in \cite{grunbaum}). In this paper, an algorithm for automatic detection of such a tiling's spiral structure and its first implementation results will be discussed. Finally, the definitions for several types of spiral tilings will be refined based on this investigation. \begin{center} \includegraphics[width=12.5cm]{Fig1} \end{center} \begin{description} \small \item [{Figure\ 1}] Spiral structure ``by coloring'' (left) vs. ``by construction'' (right) \end{description} If in Figure 1 all colors of tiles were erased and only the tile structure remained, in the left tiling (of simple squares) nobody could find a spiral character. On the other hand, the right tiling contains the spiral structure by construction, although not so easily recognized without coloring. One key aspect of the definition of spiral tilings in \cite{klaassen} is that it gives a basis to distinguish between tilings in which the spirals were just introduced by coloring and those which incorporate a spiral structure. The two tilings of Figure 1 represent both types of spirals. For the latter type we will define a further distinction at the end of this paper. During this study, we assume that all tiles are closed topological disks. If not specified explicitly, we assume that no singular points exist, where the tiles are clustered. All investigated tilings without such singular points are assumed to be $k$-hedral, which means that there are only finitely many congruence classes. We will refer to the definitions from \cite{klaassen} throughout this paper, so, we decided to put them into the appendix to have them at hand. First we need the term \textit{L-tiling} which can be summarized using ordinary language: ``An \textit{L-tiling} allows a partitioning into several parts (called \textit{arms}), in each of which we can draw a continuous, unlimited curve (called \textit{thread}) running through the interior of each tile (of the part) exactly once and winding infinitely often around a certain point''. In the appendix the reader may have a look for this definition in strict mathematical terms, but for the further understanding this one-sentence-version should be sufficient. (The left hand part of Figure 1 serves as an example of an L-tiling.) Also the term \textit{S-tiling} from \cite{klaassen} can be summarized in ordinary words: ``An\textit{ S-tiling} must have the properties of an L-tiling plus an extra property that neighboring tiles within each arm are positioned to each other in a way that cannot occur with two neighbored tiles from different arms (except at the beginning of an arm)''. E.g., a closer inspection of Figure 1 (right) shows that within each arm (equal color) there are just two different constellations of neighboring tiles, and both constellations do not occur with tiles of different colors. So, this is an S-tiling. (See again the appendix for a more rigid definition.) Then for our algorithm we need another pair of definitions. \begin{spacing}{0} \noindent \begin{center} \includegraphics[width=10cm]{edg2} \par\end{center} \end{spacing} \begin{description} \small \item [{Figure\ 2}] 6-square subset \textit{M} with \textit{DG(M)} in grey (left) and \textit{CG(M)} (right) \end{description} \begin{description} \item [{Definition}] \textbf{\textit{direct contact graph (DG)}}\textbf{ and }\textbf{\textit{ contact graph (CG)}}\textbf{:} \end{description} Let $M$ be a connected set of some tiles of a tiling. Then the \textit{``contact graph of}$M$'' or \textbf{\textit{CG(M)}} is the graph in which each tile of $M$ is represented by a node and two of such nodes are connected by an edge iff the corresponding tiles ``have contact'', i.e., have non-empty intersection \cite{buchsbaum}. We can construct a subgraph of \textit{CG(M)} called ``\textit{direct contact graph of} $M$'' or \textbf{\textit{DG(M)}} by deleting all edges for each pair of tiles which share only a finite number of points of their boundaries. (In graph theory this would be called \textit{dual graph} where the tiling is interpreted as a planar graph.) Figure 2 shows a simple example of \textit{DG} and \textit{CG} for a small subset of the square tiling. Observe that \textit{CG} in many cases will not be planar. Both\textit{ DG} and \textit{CG} can be finite or infinite, depending on the choice of \textit{M}. \section{The algorithm} Looking at the above-mentioned definitions for S-tilings, we observe that they start with a partitioning of the tiling, but do not tell us how to find it (in our example in Figure 1 ``partition'' and ``coloring'' are equivalent). So, if any automatic recognition is possible, it must deliver a partitioning into ``spiral arms''. Given these partitions (or arms in terms of our definition) it is clear how to proceed further: Check whether a continuous curve (a so-called thread) can be found satisfying the necessary conditions. For practical reasons, we decided to search for Hamilton paths \cite{harel} within each candidate for a spiral arm. Although this is not equivalent to definition L or S, for a huge subset of S-tilings (maybe for all of them) the spiral arms can be regarded as Hamiltonian w.r.t \textit{DG} or\textit{ CG}. This can be easily implemented using graph libraries. (A Hamilton path within a connected component of \textit{DG} or\textit{ CG} means that we can walk through the component along its edges meeting every node exactly once.) Let us first describe the main ideas of the algorithm just by words: \begin{itemize} \item Build classes of neighboring tile pairs according to their relative position to each other \item For each possible subset of these classes cut the tiling at the intersection of each tile pair belonging to one of the selected classes \item After each cut check the resulting connected components whether they allow a Hamilton path running through each component of the (direct) contact graph winding around a central point \end{itemize} To give an example, in Figure 2.1 we can find four classes of tile pairs (one connected by a short edge and three others sharing a long edge in different ways). \begin{frame}{} \hbox{\hspace{-0.5em} \includegraphics[width=8cm]{F952B_new} } \end{frame} \begin{description} \small \item [{Figure\ 2.1}] Example: spiral tiling (left) and result from the algorithm (right) \end{description} It is obvious that just the connections via ``short'' edges had to be deleted by the algorithm to find the spiral structure. In this case it is a two-arm spiral where both arms meet at the center. We see (at the right half of Figure 2.1) the direct contact graph (\textit{DG}) of the tiling after the described cut. Now the more formal description must follow: For an algorithmic approach, we have to restrict our scope to finite portions of a given tiling. Throughout this section let $M$ be the investigated portion of a tiling that should be checked by our algorithm. In section 4 the appropriate choice of\textit{ M} will be addressed. Those tiles in $M$ which are (in the unlimited tiling) neighbors of tiles lying outside of $M$ are called the \textit{border} $B_{M}$. Then \textit{CG(M)} (or \textit{CG} for short) is the contact graph of \textit{M} and\textit{ DG(M)} (or \textit{DG}) the corresponding direct contact graph. We start with classifying all edges in these graphs depending on how their corresponding tile pairs in $M$ are positioned to each other: For each edge $k$ of $DG$ we form the class {[}$k${]} consisting of all the edges $k'$ of $DG$ for which the two tiles (determined by the endpoints of $k'$) are congruent to the corresponding tiles determined by $k$, through an orientation-preserving isometry of the plane (that is, by translation or rotation). Let the set of all such classes be denoted $K_{M}=\left\{ [k_{1}],[k_{2}],\text{\dots}\right\} $.\footnote{One could call such classes \emph{edge classes} or \emph{tile pair classes}, which is equivalent here.} (During the algorithm we will also need additional edge classes from $CG$, constructed in the same way.) For a class {[}$k${]} we consider the set $E(k)$ of edges in {[}$k${]}. For each subset of classes \textbf{\textit{K}} $\subset K_{M}$ we write \textit{E(}\textbf{\textit{K}}\textit{)} for the corresponding edge set as a union of $E(k)$. An edge from \textit{E(}\textbf{\textit{K}}\textit{)} between the tiles $T_1$ and $T_2$ should be denoted as $(T_1,T_2)$. For each of these subsets of edge classes in $DG$ we can check what happens if all these edges were deleted. How do the remaining connected components of $DG$ ``behave''? Several steps were included in order to exit the loops as early as possible. For shortness, we will use the term ``component'' for ``connected component''. \begin{description} \item [{Algorithm:}] First check whether there are at least three congruent tiles differing in orientation or reflection within $M$.\\ If not, end the algorithm with empty result.\\ Else, form the set of classes $K_{M}$ as described above. \\ Next we define an operation to be performed on each nonempty \textbf{\textit{K}}$\subset$\,$K_{M}$. \item [{Operation\ A:}] (using \textbf{\textit{K }}as input and returning either \textbf{\textit{K }}plus a graph or the result ``discarded'' if \textbf{\textit{K}} cannot fulfill a condition)\end{description} \begin{verse} Check whether all components of $\bigcup\limits_ {(T_i,T_j)\in E(\boldsymbol{K})} \!\!\!\!\!\!\!\!\! T_i \cap T_j \,\,\,$ are connected to the border $B_{M}$; [Remark: Represents boundaries of spiral arms.] if not, discard \textbf{\textit{K}} and finish Operation A with result ``discarded''; if yes, delete the edges \textit{E(}\textbf{\textit{K}}\textit{)} from $DG$, the result is called $G$; if all components of $G$ are connected to $B_{M}$ and allow a Hamilton path without self-intersections, go directly to ({*}); else, do the following steps with \textbf{\textit{K}} plus any combination of edge classes from $CG$, called ``\textbf{\textit{K}}-extension'', each of which generates a new $G$: If for such an extended \textbf{\textit{K}} a component of the new $G$ is not connected to $B_{M}$ or does not allow a self-avoiding Hamilton path, ignore this \textbf{\textit{K}}-extension and try the next possible one; if a tile in $M$ has more than two vertices where it meets other tiles at single points (being connected to these tiles by edges in the new $G$), ignore this \textbf{\textit{K}}-extension and try the next possible one; [Remark: Excluding cases like the checkers tiling in [1] Figure 3, where a spiral arm is not simply connected.] ({*}) If for each component of $G$ the number of tile equivalence classes w.r.t translation is less than 3 \textendash{} discard (extended) \textbf{\textit{K}} and continue with the next one (if extensions were needed); if extensions were needed, return all non-discarded variants of \textbf{\textit{K}} plus $G$ or ``discarded'' as result when all extensions were checked; else return (\textbf{\textit{K}}, $G$) if non-discarded or else return ``discarded''. (\textbf{End of A}) Perform Operation A with all nonempty subsets of $K_{M}$. All non-discarded subsets are candidates for spiral partitions. Sort the non-discarded subsets by the number of components of $G$ (= nbr. of arms) in increasing order.\end{verse} \begin{description} \item [{Operation\ B:}] (using each non-discarded $G$ as input if there is any)\end{description} \begin{verse} For each component of $G$: Find a continuous piece-wise linear curve through the corresponding tiles following the possible Hamilton paths and modify it to check whether the conditions for being a thread can be fulfilled. {[}Remark: this section of the algorithm is not difficult for the human eye but needs considerable programming efforts. On the other hand, by methods of computer graphics and optimization this task could be handled in principle. Since the above-mentioned ``psychological effect'' is not needed here, we decided not to code this section of the algorithm.{]} If one component does not allow a thread, $G$ has to be discarded. As a final result the components of $G$ each with a valid thread represent the spiral arms. \end{verse} \textbf{End of Algorithm} \ This algorithm (except for Operation B) was implemented in Python, which is by far not the fastest language but offers a lot of libraries for graph operations. Let us return to the example in Figure 2.1. The separation into two arms cannot be managed by the implemented algorithm, but the spiral structure was recognized. Only the direct contact graph is needed in this case, but there will be some examples with \textit{CG} in the following section. \section{Results\ } As a set of test cases we took several tilings from \cite{wichmann} with spiral structure. \begin{spacing}{0} \noindent \begin{center} \includegraphics[width=12.2cm]{Results} \par\end{center} \end{spacing} \begin{description} \small \item [{Figure\ 3.1a}] Tilings and resulting graphs from the algorithm \end{description} In the first and third column of Figure 3.1a and 3.1b we show the tilings and right hand besides them in the second and fourth column the resulting graphs from our algorithm. For the majority of tilings the algorithm works with \textit{DG}. The list of examples is continued with Figure 3.1b (still with usage of \textit{DG} instead of \textit{CG}). \begin{spacing}{0} \noindent \begin{center} \includegraphics[width=12.2cm]{results2} \par\end{center} \end{spacing} \begin{description} \small \item [{Figure\ 3.1b}] Tilings and resulting graphs from the algorithm \end{description} \begin{spacing}{0} \noindent \begin{flushleft} \includegraphics[width=12.2cm]{results4} \par\end{flushleft} \end{spacing} \begin{description} \small \item [{Figure\ 3.2}] Tilings and resulting graphs with usage of \textit{CG} \end{description} There are some rare cases where \textit{CG} is needed (see Figure 3.2). So, it is recommended to start with \textit{DG} and only if nothing could be found, a second round with \textit{CG} should be performed. It is interesting to note that the algorithm also works for one-armed spirals. Though the definition for this type differs slightly from Definition S (see Appendix: Definition O for more details) the algorithm (up to Operation B) can be applied without any changes. Operation B can be performed here in simplified version, since only the spiral boundary curve has to be checked if it is winding around its starting point. In the above-mentioned collection of spiral tilings \cite{wichmann} there are two examples for this case (Figure 3.3). \begin{spacing}{0} \noindent \begin{flushleft} \includegraphics[width=12.2cm]{results3} \par\end{flushleft} \end{spacing} \begin{description} \small \item [{Figure\ 3.3}] Tilings and resulting graphs for the one-armed case \end{description} There are some special situations, where the results indicate more than one spiral partitioning. In Figure 3.4 we show two different spirals for the same tiling that were both found by the algorithm \includegraphics[width=11cm]{F6A-6} \begin{description} \small \item [{Figure\ 3.4}] Two different S-partitions for the same tiling \end{description} The spiral arms on the right side of Figure 3.4 do not look very ``natural'' compared to the spirals on the left half, but they fulfill all conditions for an S-tiling. Only the heuristic argument could be applied that the partition with lower number of arms should be preferred. This is the reason for the final part of the algorithm, where a sorting of the resulting graphs has been proposed to find the result with lowest number of connected components. \section{Complexity and other algorithmic aspects} It is quite obvious that an algorithm containing a loop over all subsets of a given finite set must have exponential complexity (w.r.t. the number of edge classes $\vert K_{M}\vert$). Hence, there will be cases where the algorithm's runtime outruns all practical limits. It should be noted here that the whole investigation did not aim on efficient implementation, but to answer the question whether such an algorithm exists at all. What can be done now in cases of extremely long runtime? Such examples exist, but we are lucky that they are rare. For these few cases we propose to apply an algorithmic test ``by hand'' in a way that the following items should be checked to decide whether the algorithm will (or won't) be successful. We use again the simple structure of Figure 2.1 to illustrate the steps: \begin{itemize} \item classify all edges of the direct contact graph\textit{ DG} by assigning integers for each class of direct neighbors to define the edge classes $K_{M}$ (In Figure 2.1 there are four classes: Let us assign 1 to the neighbors sharing a short edge and 2, 3 and 4 to the other classes of neighbors sharing a long edge.) \item if spiral arms can be observed by the human eye: Consider the spiral arms as subsets of $M$ and run along their boundaries to find the specific subset \textbf{\textit{K}} of $K_{M}$. If a spiral arm locally shrinks to a single point, as in Figure 1 (right), go back to the previous item but use \textit{CG} (In our example in Figure 2.1 just \textit{DG} is needed and the arms' boundaries are easily characterized just by the short edges, so we choose \textbf{\textit{K}} = \{1\}.) \item check whether the chosen \textbf{\textit{K}} finishes Operation A without being discarded (This is easily checked in our example since the tiling contains more than three tiles with different rotation angles and each component of the resulting $G$ - after deleting the connections via short edges - can be naturally traversed by a Hamilton path. All these paths are connected to the outside border region, which is also true for the arms' boundary.) \item perform Operation B for the components of the non-discarded results of Operation A, i.e., find a thread - or maybe several of them - following the Hamilton path(s) (In our example this is done straight forward with two threads starting close to the tiling's center.) \end{itemize} If by these checks a single subset\textbf{\textit{ K}} is found not being discarded by Operation A, it is shown that the algorithm must find this result within finite time. All remaining tilings from the literature (less than 10) were investigated with the result that in all cases where definition S is satisfied, the algorithm will return a spiral partition. Also the somehow unexpected spiral structure within the Hirschhorn tiling can be detected by this analysis (discussed in the last section, see Figure 5.2). In the same section we will see another simple example which demonstrates the advantages of the algorithm's application ``by hand''. There is one interesting case in Brian Wichman's collection \cite{wichmann} showing kind of disrupted spiral arms (see Figure 4.1). The two arms indicated by two different colors are following a spiral structure from inside to outside, but it is not possible to draw a continuous path following the spiral within the interior of each arm. \ \begin{center} \includegraphics[scale=0.4, angle=90]{F19} \end{center} \begin{description} \small \item [{Figure\ 4.1}] A tiling from \cite{wichmann} with disrupted spiral arms \end{description} Our algorithm (here not by hand but by software) returned a negative result in this case, which is correct since neither definition S nor even L can be satisfied. By its nature, an algorithm working on a finite portion of the tiling cannot in all cases distinguish between ``true'' spirals and partitions which start like spirals but later stop the spiral behavior. (Figure 11 in \cite{klaassen} shows an example of such a pseudo-spiral partition.) Therefore one could start the algorithm with a smaller part of the tiling as described and then add further tiles outside of the so-called border region. Then one could check whether the orientation of the tiles within a spiral arm will further change or remains in one or two fixed angular positions. In addition, a further difficulty could occur: It is not sure that the spiral center is always placed in the middle of the finite portion of the tiling. So, one might first look for this center by searching for the part where the highest number of tiles with different orientation are clustered. The proposed refinements from this section are all possible in principle but the described version of the algorithm worked well enough without it. \section{Discussion and further refinements} The main result of this paper is the fact that an algorithm can be designed to decide whether a given tiling has or doesn't have a spiral structure. This is done by a method of partitioning into spiral arms. As we have seen in the results section, the proposed algorithm can be applied to a wide range of tilings. We can claim that all known spiral tilings from the literature (in the meaning of definition S or O resp.) can be detected by the algorithm. The vast majority was covered by our Python implementation while the remaining part (less than 10) could be analyzed ``by hand'' following the algorithmic check list described in the previous section. So, the algorithm is working as desired with the limitation of not being very efficient for all cases due to its exponential complexity. This application ``by hand'' can also be used to decide whether a given tiling contains more than one spiral structure. \begin{spacing}{0} \noindent \begin{center} \includegraphics[width=10cm]{Fig_one_armed4} \par\end{center} \end{spacing} \begin{description} \small \item [{Figure\ 5.1}] The algorithm applied ``by hand'' to analyze a tiling \end{description} We can demonstrate this with a tiling presented in \cite{klaassen} to find out whether more than one spiral arm exists in this case (see Figure 5.1). First, we cut the tiling at those edges shared by two tringles (= thick line) to get the left hand version (one spiral arm). Alternatively - on the right hand side - we cut the same tiling at those edges where a triangle meets a rhombus (= edges shared between dark grey and light grey tiles) to find the right hand partitioning (two spiral arms). This means that the algorithm ``by hand'' can also be used as a method to partition a given tiling for a better understanding of its structure. The concept of structure analysis developed in this paper can be used for other structures than spirals, as well. In any case the final result is a tile set partition, where in each part the tiles are positioned to each other in a different way than on the parts' boundaries. So, one could ask, what typical structures could be found in this way: For the large domain of periodic tilings, we will often find partitions in form of stripes or patches. For non-periodic tilings, especially with rotational symmetry - but not restricted to those - we will detect ring-like structures, where each ring is surrounded by a larger one. For such ring partitions, we distinguish two types which can be defined in a way analogous to definition L and S. \begin{description} \item [{Definition}] \textbf{\textit{weak ring partition}: } A tile set partition of a plane tiling into infinitely many parts is called a \textit{weak ring partition} if each part (as union of its tiles) contains a closed Jordan curve $\theta$ (called \textit{thread}) around a fixed central point, $\theta(t)=r(t)\exp{(i\varphi(t))}$ with the plane identified with $\ensuremath{\mathbb{C}}$, $r(t)>0$, $t\in [0,1]$ and $\varphi$ being monotonic with $\varphi([0,1])= [0,2\pi]$. For each tile $T$ in the part the intersection of the interior of $T$ with the image of $\theta$ is nonempty and connected. The threads do not meet or cross each other. \end{description} Note that this definition could also be used for tilings with a singular point, where arbitrarily small tiles are clusterd. Apart from this, a huge number of tilings allow weak ring partitions, however, it is not a simple question how to characterize the family of tilings that share this property. We can pose this as an open problem so far. For the further analysis we need a stronger version of this definition. The condition is analogous to S2 from definition S with `arm' replaced by `part': \begin{description} \item [{Definition}] \textbf{\textit{strong ring partition}: } A tile set partition of a plane tiling with all properties of a weak ring partition is called a \textit{strong ring partition} if an additional condition holds: If any two tiles $T_{1},T_{2}$ in a part are direct neighbors and can be respectively mapped by an operation $\tau$ (composed of translation, rotation or scaling) onto another tile pair $\tau(T_{1})$ and $\tau(T_{2})$, these must also be direct neighbors within a part. ($T_{1},T_{2}$ from the same part are called \textit{direct neighbors} if $T_{1}\text{\ensuremath{\cap}}T_{2}$ is cut\footnote{Here and in all other occurrences "cut by the thread" means that the thread (by passing from $T_{1}$ to $T_{2}$) intersects $T_{1}\text{\ensuremath{\cap}}T_{2}$, which might also be just a single vertex.} by the part's thread or contains more than a finite number of points.) \end{description} Figure 5.2 (left) shows an example of a strong ring partition. The scaling operation was inserted here to make this definition applicable also in the context of tilings with singular points, see below in this section. It is obvious that by the techniques of the algorithm presented in section 2 one could automatically check whether a tiling allows or doesn't allow a strong ring partition. Now we can separate tilings with a spiral structure from those with a ring structure, which sometimes can both occur simultaneously. \begin{spacing}{0} \noindent \begin{center} \includegraphics[width=11cm]{Hirschhorn2} \par\end{center} \end{spacing} \begin{description} \small \item [{Figure\ 5.2}] A tiling with strong ring partition (left) and S-partition (right) \end{description} \begin{description} \item [{Definition:}] A $k$-hedral tiling is called a \textit{strong spiral tiling} (respectively \textit{strong S-tiling} or \textit{strong O-tiling}) if it is an S- or O-tiling and additionally \textit{doesn't} allow a strong ring partition. (Hence, strong spiral tilings and strong ring partitions exclude each other.) \end{description} A closer inspection shows that most of the known S- or O-tilings are also strong S- respectively strong O-tilings. A famous example where this is \textit{not} the case is the Hirschhorn tiling. In Figure 5.2 we can observe on the left side the obvious ring structure and on the right side the spiral arms allowing an S-partition. In the context of tilings with one singular point, we can do the same to separate the ring structure from the spirals. \begin{description} \item [{Definition:}] A tiling with one singular point and finitely many similarity classes is called a \textit{strong spiral tiling} (or \textit{strong P-tiling}) if it allows a partition according to definition P but \textit{doesn't} allow a strong ring partition. \end{description} Tilings with strong ring partition and spiral structure - regardless of having a singular point or not - as shown in Figure 5.2 or in \cite{staana} often have the property that the spirals are in some sense hidden or visually dominated by the ring structure. They can be viewed as ``picture puzzles''. So, though we have demonstrated that spirals (and other structures) can be detected principally without human aid by algorithms, in the context of perception the quote from the beginning remains true that ``to some extent, at least, the spiral effect is psychological\textquotedblright. \section*{Acknowledgements} Although it is no longer possible in person, I would like to express my gratitude to the late Branko Gr\"unbaum for the fruitful discussion during the development of this paper and thanks to Brian A. Wichmann for his support with the tilings from his great collection.
{ "redpajama_set_name": "RedPajamaArXiv" }
2,903
Assembly Reform Group Will Miss Own Deadline December 18, 2015 | by David Howard King (photo via the governor's office on flickr) The Assembly working group on operations, participation, and transparency is set to miss its self-imposed December deadline to issue recommendations on how to make the chamber more accommodating to the public and rank-and-file members. Assemblymember Gary Pretlow, the group's co-chair, told Gotham Gazette: "We wanted to get it out before the end of December but that's not gonna happen." The 12-member group was put together by newly-minted Assembly Speaker Carl Heastie in April as a concession to pressure from reform-minded members and good government groups. The group has gotten off to a slow start and it is unclear how promising the endeavor will be. In August Pretlow told Gotham Gazette that he and fellow co-chair Brian Kavanagh had only solicited ideas from members via email and not had much response. Heastie defended the group's pace that month. "The idea was for them to meet and have conversations and come back to us with recommendations in the next session. So I've left that to the 12 members of the committee...they have time," Heastie was quoted by State of Politics. However, by Pretlow's description, only two of the members have had any real say so far. Pretlow says things have picked up for at least himself and Kavanagh, if not the rest of the working group. "Assemblyman Kavanagh and I have been wading through 15 pages of recommendations. We've been meeting about every week. We didn't want to bring everyone to Albany every week because then you guys would say we were milking per diems. So it's damned if you do, damned if you don't," Pretlow told Gotham Gazette. Pretlow said he hopes to present the 12 other members of the group with recommendations within the next two weeks and then share what they agree on with the full Assembly when it returns to session January 6. Proposals the group could be considering include ones that would more equally distribute resources amongst members, allow for a more open committee process, mandate use of the internet to better publicize important hearings, and allowing rank-and-file members to more easily advance their bills. The group has faced criticism for not including Assembly Republicans who have long complained of having their voices silenced in legislative committees and bills killed before they reach a vote. Pretlow said that he and Kavanagh have met with some groups with outside interest in reforms, "We met with the so-called good government groups to take their suggestions and we looked for input from the public but we haven't got any," Pretlow said. When asked how the group solicited public input, Pretlow said he thought perhaps there was "something on the internet," and encouraged Gotham Gazette to contact Kavanagh for specifics. Kavanagh's office did not return request for comment. "We've gots lots of recommendations from what's been in the press," said Pretlow. "It's not like this is a secret group." Representatives of good government groups had slightly varying takes on their meeting with the working group but agreed it wasn't particularly eventful. Blair Horner, of The New York Public Interest Research Group, said it was hard to read the pair either way and that he felt they were on a "fact-finding mission." "It was hard to read the tea leaves, they played it close to vest and they were non-committal," said Horner who noted that the working group can't make promises as the Democratic conference will have to approve the recommendations. Other attendees felt the pair outright rejected many of their proposals without even the slightest consideration and that it seemed they were more concerned with perception and political power than moving on major reform. "We essentially read a list of proposals to these guys and they told us why they can't, or won't, do them," said one attendee. Some reformers were hoping the group would have recommendations that would have been debated in public hearings, and agreed on in time to pass during their first day in session. It is more likely the conference will discuss the recommendations for the first time as a body on that day. "The only thing I have to say is that now is clearly the time for Heastie and the Assembly Democrats to make a clean break with a very corrupt and undemocratic past," said John Kaehny, executive director of Reinvent Albany, when told about the delay. "It's on the Assembly Democrats to change the culture and the rules that have been a breeding ground for scandal after scandal. We hope Speaker Heastie is up to the challenge." Heastie, who replaced his predecessor, Sheldon Silver, when Silver was indicted (he has since been convicted on federal corruption charges), has received praise from a number of his younger members for listening to a wider range of legislators than Silver and for empowering rank-and-file members. "Since becoming Speaker, I have made a special effort to create issue specific workgroups and a new subcommittee structure that promotes member participation while exploring new ideas to move New York forward," said Heastie in a statement announcing the creation of the working group. "Members have a lot of great ideas, and the creation of this new workgroup is an opportunity for us to build on the strong processes already in place that promote transparency and accountability." However, there is growing concern among reformers in and out of the Assembly that Heastie is essentially punishing Kavanagh for pushing for more reforms, which could theoretically weaken Heastie as leader, by sticking him with a group that is meant to be a dog and pony show. Pretlow told Gotham Gazette in August that he wanted to make sure the group didn't do anything to infringe on Heastie's "power." "This has got to be torture for the guy," said a fellow Democrat of Kavanagh, "He actually wants change and Carl is making him pay for it." by David King, Albany editor, Gotham Gazette @DavidHowardKing
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
5,259
\section{\label{introduction} Introduction} \emph{Introduction.}--Improving the measurement precision \cite{GiovLM04,Naga07beating,HiggBBW07,GiovLM11,XianHBW11,Slus17unconditional} is one of the major driving forces for technology and science. The precision of a measurement scheme is ultimately bounded by the available resources \cite{caves1981quantum,yurke19862}, which are typically quantified by the number of uses of a discrete-time dynamics, $N$, or by the evolution time of of a continuous-time dynamics, $T$. The best precision of a classical scheme, known as the quantum Shot-Noise-Limit (SNL), scales as $1/\sqrt{N}$ or $1/\sqrt{T}$ for discrete and continuous dynamics respectively. The SNL is already constraining the performance of current state-of-art precision measurements, such as LIGO interferometer \cite{caves1981quantum,schnabel2010quantum,abadie2011gravitational,aasi2013enhanced}. By exploring quantum effects, quantum metrology can surpass the SNL \cite{Mitchell04super,walther2004broglie,GiovLM04,GiovLM06,GiovLM11}. For example, by preparing the probe state as the NOON state in the entangled parallel scheme \cite{Boll96optimal,Lee02a}, it can achieve the Heisenberg precision which scales as $1/{N}$\cite{GiovLM04,Naga07beating,Okam08beating,GiovLM11,XianHBW11}. In practise, however, preparing large entangled states are extremely challenging. To date, the largest NOON state prepared deterministically in optical experiment is $N=5$ \cite{Afek10high}, while the largest NOON state that has been implemented for quantum metrology is only $N=4$(2) with(without) the postselection \cite{Naga07beating,Okam08beating,XianHBW11}. \begin{figure}[t] \center{\includegraphics[width=0.46\textwidth]{theory_3d_generator.pdf} \caption{\label{fig:scheme} {Generators in the direct and control-enhanced sequential schemes.} (a) Direct sequential scheme; (b) Control-enhanced sequential scheme with $N$ controls. Both schemes consist of three steps: state preparation(green module), evolution(blue) and measurement(purple). (c) The evolution of the Bloch vectors $\vec{s}_T^{(N)}$ for the generators ${S}_T^{(N)}$, here $N$ denotes the number of controls. Without the controls the path of $\vec{s}_T$ is a helical line. The controls change the velocity and increase the length of $\vec{s}_T^{(N)}$. (d) The evolution of the generators at the plane orthogonal to $\vec{n}_h$. Without the controls $\vec{s}_T$ has a uniform circular motion at the plane orthogonal to $\vec{n}_h$. The controls change the motion and increase the length, as shown by the paths of $\vec{s}_T^{(N)}$.} \end{figure} The direct sequential scheme, in which the probe state evolves under the same dynamic multiple times as shown in \fref{fig:scheme}(a), can achieve the same (Heisenberg) precision if the dynamics commute with each other at different values of the parameter. For example, for the usual phase estimation, the dynamic is given by $U=e^{-\mathrm{i}\phi H}$, which commute with each other at different values of $\phi$, the direct sequential scheme can then achieve the Heisenberg precision for the usual phase estimation\cite{GiovLM06,GiovLM11,Berr09how}. The sequential scheme is practically more scalable as entanglement is not necessarily required. Higgins \textit{et al.} \cite{HiggBBW07} have experimentally implemented the direct sequential scheme for the estimation of an optical phase, demonstrate a Heisenberg-limited precision. The direct sequential scheme, however, can not achieve the Heisenberg precision under general dynamics that do not commute at different values of the parameter (which we will refer as noncommuting dynamics). It can have even worse performances than the shot-noise limit\cite{pang2014}. \citet{Haid15optimal} showed the Heisenberg precision can be restored under general noncommuting dynamics by adding additional quantum controls as in \fref{fig:scheme}(b). Here we first investigated this control-enhanced sequential scheme in a more intuitive and geometrical way to show how the generator of the parameter is coherently accumulated and how quantum control can increase the norm of the generator. We then identify some sweet spots in time at which the optimal controls can be pre-fixed without the need of adaptation. This simplifies the practical implementations significantly. We then experimentally implement the control-enhanced scheme and achieve a precision near the Heisenberg limit for the estimation of the orientation of an optical plate whose dynamics is non-commuting. \emph{Control-enhanced sequential scheme for general dynamics.}--The precision limit in quantum metrology can be calibrated by the quantum Cramer-Rao bound(QCRB)\cite{GiovLM11,Hole82book,Hels76book} as $\delta\hat{\phi}\geq \frac{1}{\sqrt{nJ}}$, where $\delta\hat{\phi}=\sqrt{E[(\hat{\phi}-\phi)^2]}$ is the standard deviation of an unbiased estimator, $n$ is the number of times the measurement is repeated, $J$ is the Quantum Fisher Information(QFI) which bounds the precision limit\cite{Hels76book}. For a general unitary dynamics, $U_t(\phi)=e^{-iH(\phi)t}$, QFI is determined by the variance of its generator as \begin{equation}\label{key} J=4\<\Delta S_T^2\> \end{equation} where the generator $S_T$ is defined as $S_T=\mathrm{i}[\partial_\phi U_T(\phi)]U^\dagger_T(\phi)$ and $\<\Delta S_T^2\>=\bra{\psi} S_T^2\ket{\psi}-\bra{\psi} S_T\ket{\psi}^2$\cite{pang2014}. For general time-independent Hamiltonian we have \cite{pang2017optimal} \begin{equation}\label{eq:generator} S_T=\int_{0}^{T}V_{t}d{t}, \end{equation} where $V_{t}=U^\dagger_{t}(\phi) V_0 U_{t}(\phi)$ with $V_0=\partial_\phi H(\phi)$. $S_T$ can be regarded as an overall signal strength which is coherently accumulated from the instantaneous signal $V_{t}$ over a period of time. For commuting dynamics, where $[U_t(\phi),U_t(\phi+d\phi)]=0$, we have $[H(\phi),\partial_\phi H(\phi)]=0$, $V_{t}=V_0$. In this case $S_T=V_0T$, $\<\Delta S_T^2\>=T^2\<\Delta V_0^2\>$, which scales as $T^2$ and leads to the Heisenberg limit. For noncommuting dynamics, however, things are more different. We consider a general Hamiltonian $H$ on a qubit, which can be written as $H=\vec{h}\cdot\vec{\sigma}$, $\vec{h}=(h_1,h_2,h_3)$ and $\vec{\sigma}=(\sigma_1,\sigma_2,\sigma_3),$ where \[\sigma_1=\left( \begin{array}{cc} 0 & 1 \\ 1 & 0 \\ \end{array} \right),\quad \sigma_2=\left( \begin{array}{cc} 0 & -\mathrm{i} \\ \mathrm{i} & 0 \\ \end{array} \right),\quad \sigma_3=\left( \begin{array}{cc} 1 & 0 \\ 0 & -1 \\ \end{array} \right)\] are Pauli matrices. Similarly we can write $S_T=\vec{s}_T \cdot\vec{\sigma}$ and $V_t=\vec{v}_t \cdot\vec{\sigma}$. The Bloch vectors $\vec{s}_T$ and $\vec{v}_t$ can be regarded as the displacement and the velocity respectively. As shown in \fref{fig:scheme}(c)(see Supplemental Material for derivation), the trajectory of $\vec{s}_T$ is a helical line, its parallel component along $\vec{h}$ is a uniform rectilinear motion with the speed $\vec{v}_0\cdot\vec{n}_h$, $\vec{n}_h=\vec{h}/|\vec{h}|$, its perpendicular component has a circular motion with the radius $\frac{\sqrt{\left|\vec{v}_0\right|^2-(\vec{v}_0\cdot\vec{n}_{h})^2}}{2|\vec{h}|}$ and the angular speed $2|\vec{h}|$. The variance of $S_T$, $\<\Delta S_T^2\>=|\vec{s}_T|^2-\bra{\psi}S_T\ket{\psi}^2$, is upper bounded by (see Supplemental Material) \begin{equation} |\vec{s}_T|^2=\left(\vec{v}_0\cdot\vec{n}_h \right)^2T^2+\frac{\left|\vec{v}_0\right|^2-(\vec{v}_0\cdot\vec{n}_{h})^2}{|\vec{h}|^2}\sin^2 |\vec{h}T|, \end{equation} which is smaller than $\left|\vec{v}_0\right|^2T^2$. However, if additional controls are available, we can use the controls to change the velocity and increase the length of the generator as shown in \fref{fig:scheme}(c,d). Under such control-enhanced sequential scheme the total dynamics is given by $U_{T}^{(N)}(\phi)=U_{ct}^N$ with $U_{ct}=U_cU_{t}(\phi)$, here $t=T/N$ and $U_c$ is the added control after each evolution of time $t$. The generator for this controlled dynamics at time $T$ is \[S_{T}^{(N)}=\mathrm{i} \left[U_{ct}^N\right]^\dagger\partial_x U_{ct}^N=\sum\limits_{k=0}^{N-1} \left[U_{ct}^{k}\right]^\dagger S_{t}U_{ct}^{k},\] where we use $S_{T}^{(N)}$ to denote the generator after adding $N$ controls and $S_T$ as the generator of the free evolution. When $N=1$, i.e., no controls added during the evolution(only one control at the end of the evolution which does not change the QFI), $t=T/N=T$, $S_{T}^{(1)}=S_T$ which leads to the result in \eref{eq:generator}. With general $N$ controls, to maximize the variance of $S_{T}^{(N)}$, we can choose $U_c=e^{-\mathrm{i}\alpha\vec{s}_{t}}U_{t}^\dagger(\phi)$, where $\alpha$ can be chosen arbitrarily and is typically set as $0$. In this case $[U_{ct},S_{t}]=0$ and $S_{T}^{(N)}=NS_{t}=NS_{T/N}$. The variance of the generator is then \begin{eqnarray} \aligned &\<\Delta (S_T^{(N)})^2\>=N^2\<\Delta S_t^2\>\\ =&N^2\left[\left(\vec{v}_0\cdot\vec{n}_h\right)^2\frac{T^2}{N^2}+\frac{\left|\vec{v}_0\right|^2-(\vec{v}_0\cdot\vec{n}_{h})^2}{|\vec{h}|^2}\sin^2 |\vec{h}\frac{T}{N}|\right]. \endaligned \end{eqnarray} When $N\to\infty$, this goes to $\left|\vec{v}_0\right|^2T^2$ which restores the Heisenberg limit. \begin{figure*}[t] \center{\includegraphics[width=1\textwidth]{exp_3d_one_control.pdf} \caption{\label{fig:setup}{Experimental setup.} The module of preparation prepares the probe state using the polarization degree of a heralded single photon from SPDC process. The probe state then undergoes the evolution and the control in the module of evolution. The state is then measured in the module of measurement. Key devices in the setup: BBO--$\beta$-barium-borate crystal, QWP--quarter-wave plate, HWP--half-wave plate, PBS--polarizing beam splitter, APP--adjustable phase plate.} \end{figure*} \emph{Experimental setup.}--Our control-enhanced experiment has three modules: preparation, evolution and measurement, as shown in \fref{fig:setup}. In the preparation module, a 1-mm-long $\beta$-barium-borate(BBO) crystal crystal, cut for type-\uppercase\expandafter{\romannumeral1} phase-matched spontaneous parametric down-conversion (SPDC) process, is pumped by a 40-mW horizontally polarized beam at 404~nm to generate heralded single photons at the rate of 3500 Hz \cite{Kwia99ultrabright}. We then use a combination of a half-wave plate(HWP) and a quarter-wave plate(QWP) to prepare the photon in any desired polarization, which is used as the probe state. In the evolution module, we use an adjustable phase plate(APP), which is realized with a Soleil-Babinet Compensator, to generate the noncommuting dynamics on the polarization of the photon. When the optic axis of APP is deviated from the horizontal direction by an angle, $x$, the two polarization states, in the basis of the horizontal and vertical polarization with $\ket{0}=\ket{H}$ and $\ket{1}=\ket{V}$, can be written as $\ket{o}=\cos x\ket{0}+\sin x\ket{1}$ and $\ket{e}=-\sin x\ket{0}+\cos x\ket{1}.$ When a photon passes through the phase plate with a $2t$-phase shift, it undergoes a unitary evolution $U_t(x)=\ketbra{o}{o}+e^{\rmi2t}\ketbra{e}{e},$ which can be rewritten as $U_t(x)=e^{-\mathrm{i}(\sin2x\sigma_1+\cos2x\sigma_3)t}$ in the basis of the horizontal and vertical polarization. By controlling the phase $t$, this is equivalent to a time evolution governed by the Hamiltonian $H=\sin2x\sigma_1+\cos2x\sigma_3$, here the parameter $x$ represents the angle between the optical axis of the phase plate and the horizontal direction. The estimation of $x$ thus corresponds to the estimation of the orientation of the phase plate. The control is realized by a combination of two QWPs and a HWP, which is capable of generating arbitrary unitary operation on the polarization. Multiple passes of the qubit are realized by a cavity loop made of four mirrors. The number of controls is deterministically controlled by moving the translation stage of one mirror, which can be realized without affecting the coupling efficiency in the measurement module (see Supplemental material). The module of measurement consists of the HWP, QWP, PBS and two single-photon detectors which can perform the projective measurements along any desired direction. \emph{Pre-fixed control at the sweet spots in time.}--The optimal control in general depends on the parameter and can only be realized adaptively, but there are some cases the adaptation is not required. In our experiment, the noncommuting dynamics is governed by the Hamiltonian $H(x)=\sin2x\sigma_1+\cos2x\sigma_3$. It is easy to obtain $V_0=\partial_xH(x)=2(\cos2x,0,-\sin2x)\cdot \vec{\sigma}$. The vector, $\vec{v}_0=2(\cos2x,0,-\sin2x)$, is orthogonal to the Hamiltonian vector $\vec{n}_h=(\sin2x,0,\cos2x)$, where $H=\vec{n}_h\cdot\vec{\sigma}$. Thus, without controls the generator only has a perpendicular component in a circular motion as shown in \fref{fig:scheme}(d). The largest variance of $S_T$ is $4\sin^2T$ at time $T$, which is much lower than the Heisenberg limit $4T^2$ \cite{Haid15optimal}. Under the control-enhanced sequential scheme with $N$ passes through the dynamics and control, the QFI can reach $16N^2\sin^2t$. In real experiments, the number of controls are always limited. The maximal QFI that can be achieved with $N$ controls is $16N^2$, where the minimal $t$ attaining this maximal value is $t=\frac{\pi}{2}$. Under $N$ controls, $T=Nt=\frac{\pi}{2}N$ is the smallest total time to achieve the maximal value. In addition, at these time points the optimal control can all be taken as $U_c=\mathrm{i} \sigma_3$, which is independent of $x$ and can be prefixed without adaptation. This control works for all $x$ at $t=\frac{\pi}{2}$, as $U_{ct}=\mathrm{i} \sigma_3e^{-i\frac{\pi}{2}H(x)}=e^{\mathrm{i} 2x\sigma_2}$ commute with $S_t=2\sigma_2$ for all $x$. Thus when $N$ controls are used, at $T=\frac{\pi}{2}N$, the QFI can achieve the maximal value $J_T^{(N)}=16N^2$ with the pre-fixed control $U_c=\mathrm{i} \sigma_3$ \begin{figure}[t] \center{\includegraphics[scale=0.65]{fisher_std_one.pdf} \caption{\label{fig:adaptive}{Precision with the optimal and adaptive controls.} (a) QFI; (b) The standard deviation; The performances with $N=1, 2$ and $4$ controls are demonstrated, which are denoted by blue, purple and red colors, respectively. Experimental results for ideal controls (dots) and adaptive controls (circles) are close to optimal theoretical values (solid lines). The error bars are discussed in Supplementary material.} \end{figure} \begin{figure}[t] \center{\includegraphics[scale=0.5]{figure_sweet.pdf} \caption{\label{fig:probability exp}{Experimental results at the sweet spots in time}. (a)Probability distribution with respect to $x$. Red and black dots show frequencies measured experimentally with 50000 measurements at sweet time $t$ and non-sweet time $0.5t$, respectively. The solid lines show the theoretical probability distribution. From upper to bottom, the four subplots correspond to control number $N=1,2,4$ and 8. Error bars are calculated from measurement statistics and too small to be visible. (b) The QFI for the case of $N=8$ is plotted, at both the sweet spot in time $T_8=4\pi$ and the non-sweet spot in time $0.5T_8=2\pi$. The solid lines are theoretical value and dots are experiment results.} \end{figure} \emph{Experimental results at any given time with different number of controls.}--In the first set of experiments, we demonstrate the precision scaling with respect to the evolution time $T$ when different number of controls are used. For any given $T$, if $N$ controls are used ($t=\frac{T}{N}$), the QFI under the control-enhanced scheme can reach $J_{T}^{(N)}=N^2J_{t}=16N^2\sin^2\frac{T}{N}$, which increases with $N$. We first consider the scenario when $x$ is known to be within a very small neighborhood so that we can choose ideal controls. In the experiment $x$ is close to $0$ and the optimal probe states, controls and measurements are prepared according to $x=0$ and $t=T/N$ (see detailed experimental implementation in Supplementary material). We make $n(=50)$ measurements to get the probabilities of the two outcomes. To get the statistics of $\hat{x}$ experimentally, we repeat the process 1000 times to get the distribution of $\hat{x}$, from which the standard deviation of the estimator, $\delta\hat{x}$, is obtained. As shown in \fref{fig:adaptive}(a), the experimental precision (dots) saturates the theoretical optimal value. It can also be seen that when the number of controls increases from 1 to 4, the precision beats the shot noise limit (see Supplemental material) and gets closer to the Heisenberg limit. In the second scenario, $x$ can be any value within an interval, where the size of the interval is only restricted by phase ambiguities\cite{HiggBBW07,Berr09how} (see Supplemental material). In this case we used adaptive controls. For each round we make $5$ iterations of the adaptation. Specifically, we make new estimations of the parameter after each $10$ measurements. The controls in the first $10$ measurements are designed according to $\hat{x}=\pi/4$, the middle point of $[0,\frac{\pi}{2}]$, as $U_c=U_t^\dagger(\frac{\pi}{4})$, then are adaptively updated (see Supplementary material for experimental implementation) based on the new estimated value $\hat{x}$ obtained with the maximum likelihood estimation, which maximizes the posterior probability based on the obtained data. In \fref{fig:adaptive}, we plotted the precisions (circles) achieved by the adaptively controlled scheme. It can be seen that for $N=1$ and $2$, the obtained precision is almost the same as the theoretical optimal value; for $N=4$, the precision is slightly smaller, but already quite close to the the theoretical optimal value, i.e., the adaptive controls are already close to be optimal after five iterations. The results also clearly show that the precisions beat the shot noise limit and get closer to the Heisenberg limit. \emph{Experimental results with a given number of controls at the sweet spots in time.}--In the second set of experiments, we carry out the experiments under any given number of controls and show the advantages at the sweet spots in time. At general time points, the controls typically depend on the actual value of the parameter, thus need to be updated adaptively. With a given number of controls, at the sweet spots in time they can all be pre-fixed. Specifically, the optimal probe state at the sweet spot in time is $\ket{\psi}=\ket{H}$, the optimal control is $U_c=\mathrm{i}\sigma_3$ and the optimal measurement is the projective measurements on the eigenvectors of $\sigma_1$. They are all independent of the actual value of the parameter. If $N$ controls are used, then the probabilities of the two measurement outcomes are $\frac{1\pm\cos4Nx}{2}$ (see Supplementart material). We plot the probability distributions of the measurement results (red dots in \fref{fig:probability exp}(a)) at different $x\in[-\frac{\pi}{2},0]$(it is symmetrical for $x\in [0,\frac{\pi}{2}]$). For comparison, we also carry out the experiments with the same control at some non-sweet spot in time, and plot the probabilities of the measurements results as black dots in \fref{fig:probability exp}(a). It can be seen that at the non-sweet spot in time the periods of the distributions get larger and the interference visibility gets smaller when the actual value of $x$ deviates from $0$. However, at the sweet spots in time the probability fringes remain the same for all values of $x$. In \fref{fig:probability exp}(b), we plot the QFI for the case of $N=8$, it can be seen that at the sweet spot in time $T_8=4\pi$, $\sqrt{J}$ is close to $\sqrt{16N^2}= 32$ for all x(here $N=8$), while at the non-sweet spot in time, only when $x$ is near $0$, $\sqrt{J}$ is close to the optimal value $\sqrt{16N^2\sin^2\frac{4\pi}{8}}\approx 22.63$, the value decreases when $x$ deviates from $0$ It is worth to mention that in the control-enhanced sequential scheme the optimal measurements are simple local projective measurements, which can be easily implemented with high quality(see Supplemental material). For example, for the case of $N=8$ the visibility in our experiment is larger than $0.984$, while the visibility of the post-selected $N-$photon entangled states decreases rapidly when $N$ increases\cite{Wang16tenphoton}. \emph{Discussion}--We provided an optimal procedure for a scalable control-enhanced sequential scheme that can achieve the Heisenberg precision for general dynamics. We experimentally implemented the scheme for the estimation of the orientation of a phase plate, and showed that the scheme can achieve the Heisenberg precision for general noncommuting dynamics. We also identified the sweet spots in time at which the scheme can be realized with pre-fixed controls without any adaptation. This pushes forward both theoretical and experimental studies of quantum metrology under general non-commuting dynamics. We expect the results will have wide implications in various applications of quantum metrology. The work at USTC is supported by the National Key Research And Development Program of China (Grant No.2018YFA0306400), the National Natural Science Foundation of China under Grants (Nos. 11574291, 11774334, 61327901 and 11774335), the National Key Research and Development Program of China (No.2017YFA0304100), Key Research Program of Frontier Sciences, CAS (No.QYZDY-SSW-SLH003), Anhui Initiative in Quantum Information Technologies and China Postdoctoral Science Foundation (Grant Nos.2016M602012 and 2018T110618). The work at CUHK is supported by the Research Grants Council of Hong Kong(GRF No. 14207717).
{ "redpajama_set_name": "RedPajamaArXiv" }
6,388
# **AUSTIN SAN ANTONIO & THE HILL COUNTRY** **JUSTIN MARLER** ## **Contents** Index List of Maps Discover Austin, San Antonio & the Hill Country Austin The Hill Country San Antonio Background Essentials Resources Photo Credits Copyright cooling off in the Guadalupe River grab a pair of cowboy or cowgirl boots ## **DISCOVER Austin, San Antonio & the Hill Country** Planning Your Trip Austin in a Long Weekend Austin's Music Scene CRAFT BEER BOOM Texas Pride Hill Country Road Trip Family Fun Continental Club in Austin. When Austin is mentioned in casual conversation, all eyes light up. Those who have been to Austin can't help but chime in with enthusiasm, and those who have never been have heard only amazing things about this alluring city in the heart of Texas. What makes Austin so memorable and so liked? Austin is perhaps the most diverse city in Texas, and probably all of the American South. It is the land where John Wayne meets Andy Warhol. Here cowboys drive pickup trucks with abstract murals painted on the side, Christmas lights are on year-round, bizarre landmark art is everywhere, and hip youngsters and old country folk two-step together in honky-tonks. Absolutely anyone can come here and feel right at home. The closet cowboys can safely pretend they are real cowboys without fear of looking out of place. Messy-haired hipsters can stagger down urban streets lined with clubs, diners, and music stores, while fans of folk art and Americana pillage countless boutiques and curiosity shops. The voices of passionate politicos boom throughout grand halls, while sports fans hoot 'n' holler at UT Longhorn games in jam-packed stadiums. Music fans of all genres fall in love with countless musicians and venues in a wildly eclectic scene that never shuts off its amps. Texas State Capitol in Austin hot rod at the Lonestar Roundup Car Show live music in Austin The capital city dances to the beat of many tunes, but the fun doesn't stop at the Austin city limits. This colorful town is the porch overlooking the gorgeous Texas Hill Country. This lush region at the center of the state is lined with vast rolling hills spotted with fields of wildflowers, grazing cattle, and historic little towns founded by German pioneers who brought accordions and schnitzels to the Wild West. Folks from all over come to the region's sleepy hamlets to hunt for antiques, ride horses, explore caves, go wine-tasting, and hide out in bed-and-breakfasts. At the southern reaches of the Hill Country is the Graceland of Texas history—San Antonio. Here pilgrims from all over venerate the legendary Alamo, stroll down the beautiful and romantic River Walk, and spend the day at massive theme parks and world-class museums. Given half a chance, Austin, San Antonio, and the Hill Country are guaranteed to suck you in and take you for a spin, like a cow in a twister on the plains. Where else can you see Willie Nelson perform, go wine-tasting, explore underground caves, visit The Alamo, see ancient dinosaur bones, dance to German polka music, and catch a Mexican rodeo—all in one weekend? Nowhere else but deep in the heart of Texas. Texas pride in Gruene The Alamo. The Hill Country is known for juicy peaches ### **Planning Your Trip** No matter how much time you have, it's best to know what you want out of your travel experience. **If you want an urban experience** filled with live music, tall buildings, late-night escapades, and socializing, stick to the Austin metropolitan area. **If you want to explore the great outdoors,** including many hiking and biking trails, lakes and streams, fields of wildflowers, plus maybe some wineries, you can find all this in the surrounding Hill Country. **If you want a family vacation** filled with museums and theme parks, you'll probably stick to Austin and San Antonio. Or, **if you're looking for the very best way to experience it all,** take a road trip through the entire Hill Country, from Austin to San Antonio. All this requires is an operable automobile (with air-conditioning), your favorite Willie Nelson album, a full tank of gasoline, and the will to meander. An important thing to consider before heading to Austin, San Antonio, and the Hill Country is lodging. Because of the many festivals and events, **hotels are often booked months in advance.** The earlier you book your lodging, the better chance you have of staying in the property of your choice, or having a place to stay at all. Getting to Austin and San Antonio is easy, as both destinations have **international airports** with flights offered by most of the larger carriers. However, getting to the Hill Country isn't as easy. Due to the lack of public transportation in the rural areas, you will need to **rent a car** for your **Hill Country** road trip. As for getting around **Austin,** a great **metro system, pedicabs, taxicabs,** and **ride-hailing apps** make navigating pretty simple. Getting around **San Antonio** is much more complicated. There is a metro system, but everything is so spread out that you will have more fun and waste less time by renting a **car.** San Antonio's famous River Walk #### **Where to Go** ##### **Austin** Although Austin is geographically south of the center of Texas, it's definitely the **heart of the state.** The Austin metropolitan area is situated at the eastern edge of the Hill Country on the I-35 corridor. The **Colorado River** winds its way through town and has been dammed off, creating a lush and beautiful lake that is the focal point of downtown. Austin is the **state capital** and the commercial heart of several industries, one of which is live music. Here in the "Live Music Capital of the World," a thriving music and nightlife scene is to be found at the base of the city's skyscrapers. The combination of rural and urban is what attracts people to Austin. The city experience offers museums for the day-tripper and a flourishing nightlife when the sun sets. ##### **The Hill Country** The remarkably beautiful region called the Hill Country, to the west of Austin and north of San Antonio, is the **Napa Valley of Texas.** This sprawling, slow-paced region is filled with small towns—some frozen in time, others catching up. Nearly all these wide spots in the road have the signature Hill Country feature at the center of town—a beautiful, historic, ornate limestone courthouse. Between many of these towns there are **pristine parks, wineries, antiques shops,** and **roadside fruit stands.** The industry in these parts is farming, ranching, winemaking, and tourism. As you drive around the Hill Country you may notice exotic animals such as **zebras, bison,** and **antelope** grazing in fields. Many ranches in the Hill Country have become home to these rare animals. ##### **San Antonio** The age-old city of San Antonio is just to the south of the Hill Country, southwest from Austin. If you look at a map of this vibrant, **historic city** you will notice that all roads lead to San Antonio. This river town is one of the 10 largest cities in the United States. It's also home to Texas's most visited tourist attraction— **The Alamo** —as well as the famous **River Walk,** which cuts its way through downtown, and several **Spanish missions.** The Mexican border is only 175 miles away; this proximity has given San Antonio an incredibly rich **Latino heritage.** #### **When to Go** Many locals say that south-central Texas has only two seasons: winter and summer. For the sake of simplicity, we'll do like the locals and lump fall and spring in with summer since they're so short. The best time to come to Austin, San Antonio, and the Hill Country is during this **long summer season,** which starts in **March** and wraps up by the end of **October.** Although June, July, and August are hellishly hot, these are the peak months for tourism. Central Texas is overflowing with people. The warm, laid-back climate and the uncanny number of **festivals** and **music events** draw thousands to the area from all over the country. Everyone is kept alive during the summer months by drinking lots of water and by air-conditioning. Anywhere you go indoors the air is a cool 74°F, and outdoors there are many swimming holes, lakes, rivers, and pools in which to keep cool. Besides the long summer heat, the only other thing to keep in mind when planning to visit south-central Texas is **allergies.** The Hill Country is rife with **wildflowers** and trees that come to life in the spring. Sure, it's beautiful, but for the person who suffers from seasonal allergies, it can be hard to enjoy. The peak allergy times are December-January (mountain cedar), March-April (oak), and September-October (ragweed). If you plan to come during these months, be prepared to buy an antihistamine. Although folks visit the region year-round, winter is definitely the quiet season. In Austin you can always find fun things to do; however, San Antonio and the Hill Country are pretty sleepy this time of year. ### **Austin in a Long Weekend** Austin is a city that can easily be explored in a weekend. It's so alive and accessible that it takes little effort to be completely immersed in its life and culture. ##### **Day 1** This is probably the only day you will wake up early. First thing on the agenda is a hearty breakfast at the **Magnolia Cafe.** To walk off all the calories you just consumed, head straight out the door of Magnolia Cafe and down the street to **Lady Bird Lake** (formerly Town Lake). Enjoy walking the overgrown trails, watch the turtles and ducks putter in the lake, and take in the stunning view of Austin's skyline. Along the trail you can pay homage to Austin music legend **Stevie Ray Vaughan** at his famous statue. statue of Austin legendary musician Stevie Ray Vaughn by artist Ralph Helmick Next make your way to one of the most popular record stores in the United States, **Waterloo Records,** and check out their extensive collection of Texas music. After buying a Willie Nelson CD, walk across the street to **Whole Foods** world headquarters and buy some granola, energy bars, or dried fruit to consume the following day on a hike. A first day in Austin must include a visit to the **Texas State Capitol.** Walk the grounds, stand beneath the dome, and take in the gubernatorial history. If it's between 2pm and 4pm, make your way over to the **Governor's Mansion** for a tour of the historic home that some think is haunted. Texas State Capitol Before evening descends, get a copy of the _Austin Chronicle_ and look at the entertainment section. Pick a show—any show—and plan to have your socks blown off by a great night on the town. For an authentic Austin night out, catch a country band at the **Broken Spoke.** If you have the guts and gumption, try your hand at two-stepping. ##### **Day 2** The first half of Day 2 is devoted to an education in Texas pride by visiting the **Bullock Texas State History Museum.** After you're all Texased out, have lunch at nearby **Texas Chili Parlor,** then walk over to Austin's world-class repository for art, the **Blanton Museum of Art.** After admiring the Picassos, make your way down to the **Driskill,** Austin's famed haunted hotel. Even if you don't stay here you can marvel at the architecture and the creepy vibe, and get a confection at the **1886 Café & Bakery.** Cross over Lady Bird Lake and keep going until you arrive at the city's most popular strip, **South Congress Avenue,** which is lined with funky shops, trendy boutiques, and restaurants. If you get hungry, order a margarita with shrimp fajitas at popular **Güero's Taco Bar.** Check out the oddity shop **Uncommon Objects** and marvel at the $3,000 cowgirl boots at **Allens Boots.** As a side note, staying at one of the trendy hotels on South Congress is highly recommended. By this time the music scene is getting revved up. Check out music listings in the _Austin Chronicle_ and catch some live music at the **Continental Club** on South Congress or any of the venues on **6th Street** or **Red River Street,** such as **Stubb's Bar-B-Q, The Mohawk,** or **The Parish.** Peruse the music listings for Austin City Limits Live at The Moody Theater. This is a great way to see a world-class act and get close to the famous Austin City Limits stage. ##### **Day 3** Day 3 is kicked off with a trip to the most visited presidential library in the United States, the **LBJ Library and Museum.** You're sure to be moved by the exhibit about the president's life, and may well up with tears when you walk into the JFK assassination exhibit, or feel a sense of pride at seeing the pen LBJ used in signing the Civil Rights Act. Follow up the LBJ experience with lunch at **Rudy's Country Store and BBQ** for some smoky beef brisket. If it's not over 100 degrees, make your way to **Wild Basin Wilderness Preserve,** which is close by. Walk the hills and learn about Central Texas flora and fauna through interpretive trails. At the end of the trail be sure to sit on the bench and enjoy the view of the city skyline for as long as you can. Once you've acquired peace of mind, take a walk through **Zilker Botanical Garden.** Consider how this area was the stomping grounds of dinosaurs in the **Hartman Prehistoric Garden,** and then get a bite to eat at nearby **Shady Grove Restaurant.** Once you've filled up on great Tex-Mex, head downtown to famous **Alamo Drafthouse Cinema.** Order a pitcher of beer and watch a random movie or attend a Michael Jackson sing-along. ##### **Day 4** Your final day in Austin will start with a trip to **Zilker Park,** where you'll take a ride on the **Zilker Zephyr.** This mini-train takes both mini and full-size passengers throughout the park. If you're lucky your train ride will include a brief performance by "the man with the guitar in the cutoff shorts." Assuming it's a hot summer day, get off at the Barton Springs stop and jump in **Barton Springs Pool.** Plan to splash around in the constantly 68-degree water and people-watch for a couple of hours. Before evening sets in, make your way to Lady Bird Lake and watch the **bats of Congress Avenue Bridge,** which take flight just before sundown. A great way to view them is by taking a ride on **Lone Star Riverboat,** a genuine double-decker paddle wheel riverboat. Follow this up with a visit to Austin's burgeoning **Warehouse District.** First stop off at the Irish pub **Fado's** or the popular pub **The Ginger Man** and drink a pint of beer produced by local brewhouse **Live Oak Brewing Company.** It's your last night, so if you still have ears for music, check out some more bands and musicians. Or if you prefer a calm evening, walk over to **Halcyon Coffeehouse** to roast marshmallows and make s'mores at your table. ##### **Day 5** If you can squeeze one more day into your long weekend, a trip to **San Antonio** to visit **The Alamo** is essential. The drive is just two hours to downtown. After exploring Texas's most sacred site, walk down to The Esquire Tavern, a spot famous for pub grub and for having the longest bar in Texas. Afterwards enjoy a stroll on San Antonio's greatest feature, the **River Walk.** If you still have some time to kill before heading back to Austin, drive the **Mission Trail.** ### **Austin's Music Scene** Austin is the undisputed Live Music Capital of the World. With an unprecedented number of live music performances happening every night of the week throughout the year, it has earned the title. Touring national acts, local favorites, and unknowns perpetually fill Austin's venues, clubs, and bars as well as unusual places such as clothing stores, supermarkets, and even the airport. ##### **The Quintessential Austin Music Experience** Musical styles and tastes vary greatly, making it difficult to suggest one quintessential music experience, but here's a start. The proper accommodations are crucial for the live music fan. They need to be cheap, centrally located, and near a restaurant that serves breakfast all day. Musicians and fans alike love to stay at the **Austin Motel** on South Congress Avenue because it meets all these criteria. Once you arrive in town, immediately consult the music section of the **_Austin Chronicle._** All venue listings and festival and event information are found in the pages of this weekly rag. After a night of live music followed by a visit to one of Austin's many dive bars, you'll probably wake up after noon. If you stay at the Austin Motel, saunter up the street to **Home Slice Pizza** or **Güero's Taco Bar** for great grub. If you want to continue with a music-themed visit to Austin, check out one of the most popular music stores in the country, **Waterloo Records.** If you're a vinyl collector, explore **Antone's Record Shop** or **End of an Ear.** While in town it's imperative that you pay your respects to local music legend **Stevie Ray Vaughan** on the south-shore trail of Lady Bird Lake. On the banks of the Colorado stands a life-size bronze statue of the guitar god. Austin Motel Dale Watson is Austin's legendary and hardest working honky-tonk musician. While in Austin all music lovers invariably ask themselves, "I wonder how to get tickets to a taping of **_Austin City Limits_**?" You have a better chance of sprouting wings than acquiring tickets to a taping of this famous PBS program. However, on off nights, the famous stage with the Austin skyline as the backdrop is utilized as a traditional venue called the **Moody Theater,** where anyone can see great national acts perform. ##### **Venues** Austin has over a hundred places that offer live music from both regional and national acts, and nearly all of them are worth checking out. Most are in the downtown area on 6th Street, Red River Street, and South Congress Avenue. Venues generally come alive after dark, except during special benefit shows and during SXSW. Most venues have something going on every night of the week, so don't expect the good shows to be only on weekends. You're sure to catch something interesting virtually any time doors are open at the following venues. **Antone's** has been Texas's outlet for the blues for decades. In recent years it's expanded its repertoire to include pop, rock, and indie, bringing in some major national acts. **Stubb's Bar-B-Q** serves up both great barbecue brisket and superb big-name rock and indie bands in a historic limestone building; this is where the hip parties go down during SXSW. There's an intimate indoor stage for smaller acts, while the big outdoor stage features national acts such as Drake, Death Cab for Cutie, and Queens of the Stone Age. Antone's weekly Blue Monday jam For traditional country and two-step dancing, there's the legendary **Broken Spoke.** This real honky-tonk will blow your Stetson off when you walk through the door. The crowd is a perfect mix of country folk, young hipsters, and everyone in between, which makes it all-inviting. The premier intimate venue for all things unplugged is the **Cactus Cafe.** Big-name acoustic, singer-songwriter, country, and folk acts have graced the small corner stage for over 70 years. The space is small, upscale, and outfitted with a full bar in the back. For those who like it loud and grungy, **Emo's** is Austin's outlet for punk, metal, and indie rock. If you don't know where to go or who to see, the best place to experience Austin's own is the **Continental Club** on South Congress Avenue or **Saxon Pub** on South Lamar Boulevard. Lastly, if you want to see the big headliners such as Taylor Swift or Iron Maiden, the **Frank Erwin Center** or the Formula 1 racetrack **Circuit of the Americas** is where it will happen. ##### **Festivals** Out of all the **music festivals** that happen in and around Austin there are a few you simply can't miss if you happen to be in town. ###### **SXSW** In March, one of the biggest music festivals in the nation takes over Austin—SXSW, also known as **South by Southwest.** For one week the city is overrun by hundreds of musicians and celebrities and thousands of music fans. Restaurants, clubs, music stores, and barbecue joints are teeming with greasy-haired, tattooed, ripped-jean-wearing rock stars and rock star wannabes. The festival features literally hundreds of big names and up-and-coming artists in alternative, indie rock, and even pop. This isn't your typical music convention held in a convention center. Shows happen in all Austin venues from midday to the wee hours. You have to purchase pricy wristbands to get into venues, but it's well worth it. Oh, and good luck getting a hotel if you haven't booked it months in advance. ###### **ACL MUSIC FESTIVAL** The biggest festival on Austin's calendar is the **Austin City Limits Music Festival.** For three days in September nearly 200,000 people fill Zilker Park and overdose on music and sun. Spun out of the famous public television show, ACL Fest features top acts, bands, performers, and musical legends in nearly all genres of music. Passes are available for all three days or for single days. Bring sunscreen and be prepared to sit in the Texas summer heat for this one. ###### **FUN FUN FUN FEST** In the fall, Waterloo Park becomes the site of **Fun Fun Fun Fest** , which features neo-punk, indie pop, electronic, metal, and random icons from punk's bygone era. Along with a messy hairdo, be sure to bring sunscreen and a penchant for FUN. **Craft Beer Boom** For almost 20 years Austin and the surrounding region has been at the forefront of the Texas craft beer boom. In the spirit of Texas do-it-yourself attitude, many creative and entrepreneurial folks developed their own beers in basements and small warehouses with antiquated systems, and these brews have quickly sprung into the mainstream. Austin-area beer producers have exploded, in large part because beer and live music are inseparable. Real Ale Brewing Co. has even created a beer and named if after its employees' favorite local metal band, The Sword. The history of DIY beer in the state started in 1909 with Texas's oldest independent brewery, Spoetzl Brewery, best known for its diverse line of Shiner beers; since Prohibition, Shiner and Lone Star have been the preferred beers of the locals. However, it must be disclosed that Lone Star, Texas's most famous beer, was owned by Anheuser-Busch since 1895 and is now owned by Pabst Brewing Co. It wasn't until the late 1990s that the modern boom started with breweries such as Live Oak Brewing and Real Ale Brewing Co. Today there are numerous craft breweries and brewpubs in the region. In addition, there are many festivals dedicated to hops and drinking, such as the Texas Craft Brewers Festival in Austin and Oktoberfest in Fredericksburg. Most of the beers below can regularly be found at bars and grocery stores. The best beer bars and pubs to sample in downtown Austin include Bangers (79 Rainey St.), The Ginger Man (301 Lavaca St.), which has the largest selection on tap, and Craft Pride (61 Rainey St.). **BEST MICROBREWS** • **Live Oak Brewing** (taproom at 1615 Crozier Ln., Austin, www.liveoakbrewing.com) Live Oak Brewing • Recommended: Big Bark (amber lager), Hefeweizen • **Hops and Grain** (tasting room at 507 Calles St. #101, Austin, www.hopsandgrain.com) • Recommended: Zoe (lager), Greenhouse IPA • **Real Ale Brewing Co.** (taproom at 231 San Saba Ct., Blanco, www.realalebrewing.com) • Recommended: Fireman's 4 (blonde ale), Full Moon (rye IPA) • **Austin Beerworks** (3009 Industrial Ter., Ste. 150, Austin, www.austinbeerworks.com) • Recommended: Fire Eagle, Black Thunder, Heavy Machinery IPA • **Independence Brewing Co.** (3913 Todd Ln. #607, Austin, www.independencebrewing.com) • Recommended: Austin Amber, Bootlegger Brown (brown ale), Convict Hill Stout (oatmeal stout) • **Jester King Brewery** (13187 Fitzhugh Rd., Austin, www.jesterkingbrewery.com) • Recommended: Das Wunderkind, Atrial Rubicite ###### **OLD SETTLERS MUSIC FESTIVAL** To kick off spring with some two-steppin', the **Old Settlers Music Festival** is held in April. For a four-day weekend banjos will be plinkin' and fiddles will be fiddlin' at the Salt Lick BBQ Pavilion in Driftwood just outside of Austin. The festival features more than two dozen of the top performers of bluegrass and Americana music on four stages. ###### **KERRVILLE FOLK FESTIVAL** One of the biggest folk festivals in the nation, the **Kerrville Folk Festival** happens out in the Hill Country every May. This 18-day folk celebration draws the biggest names in Americana, folk, bluegrass, acoustic rock, blues, and country. Fans mill around in fields all day long listening to folk legends past and present. Most festivalgoers camp on-site. ### **Texas Pride** Texans have lot of reasons to be proud. Much of this pride stems from the state's history. Texas was created in a revolution against a brutal dictator and stood alone for almost 10 years as an independent nation. Eventually Texas joined the United States as a result of a treaty between two sovereign nations, not because it was a conquered territory or constituted land purchased from a European power. It's understandable that the original Texans were proud of what they created and have passed on that pride to later generations and new arrivals. Most of Texas pride finds its roots in Austin and San Antonio. ##### **Austin** Since Austin is the capital of the Lone Star State, much of Texas pride has been generated, legislated, and spurred here. The **Texas State Capitol** alone is a testament to Texas self-adulation. After all, it's taller than the nation's capitol. Here you can gaze at the portraits of all the state's governors and peer into Texas politics. Not too far from the capitol building are the **Old State Capitol Building Ruins,** which tell ghost tales of the founding of the State of Texas. And one can't forget the **Governor's Mansion,** which is an original Abner Cook design still inhabited by presiding governors and their families. Just a stone's throw from the state capitol is the grandest testament to Texas in all the world, the **Bullock Texas State History Museum.** Inside this enormous domed shrine are historical exhibits, dioramas, and a multimedia experience—all promoting the richness of Texas pride. From Austin all the way out into the Hill Country is what's known as LBJ Land. Lyndon B. Johnson, the 36th president of the United States, was a proud native son of Texas. Austin is home to the **LBJ Library and Museum,** the nation's most visited presidential library. Texans are proud of LBJ, and his library/museum is a sort of mecca for them. The exhibits follow LBJ's story, from a small-town Texas upbringing to carrying the presidential torch through the civil rights movement. The best way to actively experience it is by dancing two-step at Austin's premier honky-tonk, the **Broken Spoke.** Dance to live country bands and drink Texas longneck beers (Lone Star or Shiner) in a friendly environment. ##### **The Hill Country** Just west of Austin, in a wide spot in the road called Driftwood, is one of Texas's most famous barbecue joints, **The Salt Lick.** People drive from miles around to eat ribs, brisket, and smoked turkey in this ancient converted ranch house. Just up the road, in the town of Johnson City, is the **Lyndon B. Johnson Boyhood Home** and **LBJ State Park and Historic Site,** which is the site of LBJ's ranch and his **Texas White House.** Texas German heritage is celebrated each October with the sounds of accordions at **Oktoberfest** in the Hill Country's most popular town, **Fredericksburg.** This three-day bratwurst, schnitzel, and German beer extravaganza draws big crowds to Fredericksburg. Two stages, two tents, great food, polka and waltz contests, and music with an oompah make this a great Texas Hill Country celebration. Texas is where the art of ranching was invented and perfected. One of the state's most famous and historic ranches is **Y. O. Ranch,** with longhorn cattle drives, a classy lodge-style resort, cowboys, and zebras. Whether you stay here or just take a wildlife tour, your experience will be quintessentially Texan. ##### **San Antonio** Out of all points of interest related to Texas pride, the one that is most revered, most iconic, and embodies the most legend is **The Alamo.** This is where the revolution went down, the independent spirit was ignited, and the pride was grafted. Ponder where and how Davy Crockett may have died, and marvel at the bravery of those men who faced certain slaughter. The Alamo, San Antonio's famed pilgrimage sight Also in San Antonio is the **Institute of Texan Cultures,** which features exhibits on all the peoples that have lived in Texas and occupied prominent places in the state's history. For Texas dinosaur history there's the **Witte Museum.** Lastly, a visit to Texas wouldn't be complete without seeing the **Texas Pioneer and Ranger Museum.** You can't talk about Texas pride without talking about Mexico and Latino heritage. The experience of Mexican food is best had at **Mi Tierra.** The old building is festively decorated with strings of lights and tinsel, and a mariachi band often strolls around the tables. Be sure to sit in the dining room, which is painted with masterfully executed murals telling the story of Mexico and Texas. The most spectacular festival in all of Texas is **Fiesta San Antonio.** For 10 days in April San Antonio has a citywide celebration in honor of the heroes of Texas history. The festivities include carnivals, sports, fireworks, entertainment, feasts, art exhibits, and parades that float down the San Antonio River. Lastly, Texas history can't be more enjoyable than when experienced through a simulated helicopter experience in the **Tower of the Americas** 4-D theater ride **Skies Over Texas.** ### **Hill Country Road Trip** A road trip in the Hill Country is an adventure into both beautiful parks with natural wonders and tiny towns that meticulously preserve remnants of Americana and the Wild West. Get ready to do some serious wine-tasting, antiques hunting, horseback riding, and hiking. Before setting out, do some planning. It may be wise to arrange for accommodations ahead of time as well as prearrange activities such as horseback riding. ##### **Day 1** Start your road trip with a splash by taking a dip in **Hamilton Pool Preserve.** From Austin drive west on Highway 290, and then go north on Highway 71. If it's hot, take a dip; if it's cold, gawk for a while at the beauty. Afterward, head south on Highway 12 through Dripping Springs en route to Johnson City and eat some great Texas barbecue at **Ronnie's Ice House.** Before leaving town stop at **Whittington's Jerky,** because no road trip is complete without some additional beef to gnaw on. Swing by the old limestone jail, which was built in 1894 and is still in use, and then proceed westward on Highway 290 toward Stonewall to **LBJ State Park and Historic Site.** This ranch was President Lyndon B. Johnson's retreat from the world. While here see the **Texas White House** and watch an old movie about the 36th president. Once you're back on Highway 290, stop off at **Becker Vineyards** to do some wine-tasting. After buying a bottle, continue westward on Highway 290, but make sure the poor sap who didn't drink is behind the wheel. Fourteen miles down the road you'll come to the German hamlet of **Fredericksburg.** For dinner there's schnitzel, beer, and German polka music at **Auslander Biergarten.** If there's a jazz band playing at the **Hangar Hotel,** head out to the airport for a swinging time. You can also stay at this World War II-era hangar for the night. ##### **Day 2** Walk Fredericksburg's Main Street to check out the various shops and boutiques, and pay a visit to the **Pioneer Museum** and funky **Gish's Old West Museum.** If you're a World War II buff, check out the **National Museum of the Pacific War,** where you can see artillery used in the war. Then head north on RR 965 to one of the Hill Country's most precious natural wonders, **Enchanted Rock State Natural Area.** Take the time to hike the face of the enormous granite-domed rock to check out the view and ponder the myths and legends that were born here. If it's not past noon, take a drive on the most scenic country road in Texas, the **Willow City Loop.** From Fredericksburg your journey will continue south on Highway 16 to Kerrville and on to RR 1340 toward Hunt. Out here you'll be looking for **Stonehenge II,** a small version of the mysterious rock formation in Salisbury, England. After pondering this oddity, head back to Kerrville, where you'll head south on RR 173 to get to your final destination, the Cowboy Capital of the World, known as **Bandera.** Once in Bandera, have a meal at **O. S. T. Restaurant.** The food is down-home country cooking in the presence of John Wayne memorabilia. One of the area's many dude ranches, such as the **Mayan Dude Ranch,** is where you'll want to stay. ##### **Day 3** Start the day with a big cowboy-style breakfast at the dude ranch mess hall, followed by a horseback ride. A guide will take you into the backcountry on trails that have been trodden under hoof for eons. After lunch in the mess hall and a siesta, head downtown and explore the strange Western shops that line Bandera's dirt sidewalks. Also pay a visit to the **Frontier Times Museum.** Once you've seen Bandera, leave town by way of Highway 46, toward the historic German pioneer town of **Boerne.** This lovely spot on Cibolo Creek is a great place to hunker down for the rest of the day. The main activity here is walking Main Street, known to locals as **Hauptstrasse.** Here you'll find dozens of antiques shops, boutiques, and eateries, all in historic limestone buildings built by the German pioneers. When you get hungry, walk over to the river, turn left, and walk down to the **Dodging Duck Brew Haus.** Dinner with a beer on the outdoor patio is the only way to go. Most folks who come to Boerne stay in a bed-and-breakfast. A reservation service can help you find the right lodgings for your budget. picturesque Boerne ##### **Day 4** The first thing you'll want to do in the morning is drive north on RR 474, where you'll explore the **Cave Without a Name.** The cave is full of intriguing rock formations, stalagmites, and stalactites. After this head back to Boerne, and then go east on Highway 46. Along the way you'll encounter **Guadalupe River State Park.** Stop off here for some incredible scenery, or even better, go tubing down the **Guadalupe River.** Afterward, make your way to New Braunfels and the charming town of **Gruene.** Explore Gruene's quaint buildings full of antiques and a few restaurants overlooking the beautiful Guadalupe River. At the base of the old town is the **Gristmill River Restaurant & Bar,** situated in the ruins of an old cotton gin. A grand finale to your road trip should be famous **Gruene Hall.** This old structure with chicken-wire windows is Texas's oldest dance hall. Country music legends still fill this joint with great foot-stomping music. ### **Family Fun** Central Texas has a wide variety of activities, events, and sights that are sure to keep the kids stimulated and the adults fascinated. From theme parks and curiosity shops to museums with interactive exhibits and mysterious caves, it would take a family two weeks to soak up all the fun. ##### **San Antonio** San Antonio is known the world over as a family town. The imaginations of both parents and children are sparked when visiting **The Alamo,** along with the other historic Spanish missions on the **Mission Trail.** A boat ride on the **River Walk** is another great experience for the whole family. The Alamo and River Walk aside, San Antonio is known by kids the world over for its internationally recognized **San Antonio Zoo and Aquarium.** All the animals kids have read about and imagined are here, ready to be viewed up close. While at the zoo, climb aboard the **Brackenridge Eagle,** a miniature train that travels a two-mile route around Brackenridge Park. San Antonio also has two gigantic theme parks. First there's **Six Flags Fiesta Texas,** which has over 200 acres of fun for the whole family. Older thrill-seekers will enjoy the wild rides, and for the younger bunch there are less-scary kiddie rides. Six Flags also puts on campy shows that kids will clamor to see. The other mega theme park is **SeaWorld San Antonio.** The main attraction here is the killer whale Shamu, who performs in front of an audience. Be prepared to be soaked if you sit in the first rows. San Antonio also has some popular indoor family hot spots, such as the children's museum, **The DoSeum.** This huge indoor and outdoor campus has hands-on exhibits where children can pretend, explore, imagine, and discover. There's also the popular **Witte Museum.** Inside the grand halls of the Witte the whole family will marvel at _Triceratops_ and _Tyrannosaurus rex_ bones, mummies, dioramas, and history and natural science exhibits. There's even a big tree house. Witte Museum in San Antonio One of the more obscure things in town for the family is the **Texas Transportation Museum.** Here the kids will be enthralled by the miniature scale-model train sets meticulously built, painted, and erected with a frightening attention to detail. The scale models and their detailed environments are a must-see for the train geek and the curious. Although your kids may not jump for joy at the idea of an evening of dancing, I guarantee if you drag them to **Leon Springs Dancehall** they will have the time of their life. Here families dance two-step to a live country band along with hundreds of other folks. This family-friendly dance hall has a massive 18,000 square feet of wooden floor that's packed Friday and Saturday nights. Every January the San Antonio River is drained, and the **River Walk Mud Festival** begins. All weekend this mud-based festival puts smiles on faces. A king and queen of mud are elected to preside over events that include music, games, and all sorts of festivities. After a long day of fun, enjoy a meal at **Liberty Bar.** Parents can enjoy a great lunch or dinner with upscale food, while the kids will enjoy eating in a unique two-story house. (Think Alice in Wonderland.) Another popular place to eat with kids is **Mi Tierra.** Mexican food and ambience reach a zenith here. ##### **Austin** Family fun in Austin begins with watching the flight of the **bat colony of Congress Avenue Bridge.** This is a surefire way to get the kids excited on a summer evening. Indoor fun is to be had at the **Bullock Texas State History Museum,** where families can have a multimedia sensory overload. Also indoors is **The Thinkery,** Austin's children's museum. Here kids can come completely unglued in a safe environment. **Toy Joy** is a toy store for adults as well as kids. Kids are crazy about dinosaurs. There are three great places where you can learn about these prehistoric animals. First there's the **Texas Memorial Museum,** which has an entire room filled with dino bones as well as pickled critters. A good way to get the kids interested in a walk through a botanical garden is by bringing them to the **Hartman Prehistoric Garden** in **Zilker Botanical Garden.** Lastly in the dino field, there's the **Austin Nature and Science Center,** where kids can become mini paleontologists and dig for prehistoric bones. A train ride can do a family a lot of good. You can't help but smile ear to ear while riding the **Zilker Zephyr,** a miniature train that runs through Zilker Park. If mini doesn't satisfy, there's the real deal, the **Austin Steam Train.** This old locomotive takes passengers into the Hill Country on a chugging ride to remember. A fun place to take the whole family for lunch or dinner is Tex-Mex **Chuy's.** Kids can marvel at the junk hanging from the ceiling and color with crayons while parents can sip margaritas. ##### **The Hill Country** The primary sights in the Hill Country for both kids and adults are the various caves and caverns. Everyone will be interested in walking through the **Natural Bridge Caverns** or the **Cave Without a Name.** For more of a theme park spin on a natural-cave experience there's **Wonder World Caverns** in San Marcos. If you prefer being high up in the trees, there's **Cypress Valley Canopy Tours.** Here the whole family can travel on cables, up in the treetops, for thrilling views along with adventure. The historic German pioneer town of New Braunfels is home to Texas's largest water park, **Schlitterbahn.** A good way for a family to cool down in the summer is to ride chutes and tubes of water, and to splash in pools for a day. West from New Braunfels, in the art town of Wimberley, everyone loves to visit **Wimberley Glass Works.** Watch the world-renowned glass artists blow melted glass into beautiful shapes in a matter of minutes. In Fredericksburg, take the family to eat at the **Auslander Biergarten,** which has a Texas-meets-schnitzel menu and outdoor and semi-outdoor seating. A fun place for the whole family to stay in the Hill Country is at the **Mayan Dude Ranch.** Families can take horseback rides in the country, eat in Wild West-style mess halls, go on hayrides, and hear ghost stories told around a campfire. view of Austin and Lady Bird Lake ## **Austin** HIGHLIGHTS PLANNING YOUR TIME ORIENTATION Sights DOWNTOWN SOUTH AUSTIN CENTRAL AUSTIN EAST AUSTIN OLD NORTH AUSTIN Live Music and Nightlife LIVE MUSIC BARS AND CLUBS PUBS GAY AND LESBIAN Entertainment and Events THEATERS AND EVENTS CENTERS PERFORMING ARTS CINEMAS COMEDY CLUBS OTHER ENTERTAINMENT FESTIVALS AND EVENTS Shopping CLOTHES, SHOES, AND ACCESSORIES MUSIC BOOKSTORES ART GALLERIES WEIRD GIFTS AND ODDITIES FOR KIDS RETRO, VINTAGE, AND ANTIQUES Recreation S LADY BIRD LAKE LAKE TRAVIS HIKING AND BIKING HORSEBACK RIDING ROCK CLIMBING SPELUNKING GOLF DISC GOLF SPECTATOR SPORTS TOURS Food AMERICAN AND DINERS BARBECUE, STEAK, AND SAUSAGE BREAKFAST & BRUNCH MEXICAN TEX-MEX AND SOUTHWESTERN ITALIAN OTHER INTERNATIONAL FOOD HEALTHY AND VEGETARIAN FINE DINING DESSERTS AND CONFECTIONS COFFEE SHOPS Accommodations UNDER $100 $100-150 $150-250 OVER $250 Information and Services TOURIST INFORMATION EMERGENCY INFORMATION PUBLICATIONS INTERNET AND WI-FI MUSICIANS' RESOURCES LAUNDRY POST OFFICE MONEY Transportation GETTING THERE GETTING AROUND vintage amps at Austin Vintage Guitars. **Highlights** Look for S to find recommended sights, activities, dining, and lodging. S **Texas State Capitol:** The stately pink granite building is impressive both historically and visually (click here). S **Barton Springs Pool:** The most popular way to cool down when it's over 100 degrees? Splashing, diving, and swimming in this perpetually 68-degree water (click here). S **6th Street:** Catch a wide variety of live music and meet uninhibited partiers on Austin's version of Bourbon Street (click here). S **The Bats of Congress Avenue Bridge:** Before dusk, pack a picnic dinner and head downtown to the bridge to watch the cloud of flying mammals swoop off into the night (click here). S **LBJ Library and Museum:** No one has had more impact on recent Texas history than President Lyndon B. Johnson. Explore his life and his presidency—and even hear a mechanical LBJ tell some jokes (click here). S **Blanton Museum of Art:** Check out the largest public collection of Latin American art in the country, along with works by notable artists like Pablo Picasso and Peter Paul Rubens (click here). S **Bullock Texas State History Museum:** Texas's vibrant history is captured in dioramas, historical artifacts, and educational exhibits that dazzle the imagination (click here). S **South Congress Avenue:** Stroll down this popular avenue lined with unique stores, boutiques, curiosity shops, and restaurants (click here). S **Alamo Drafthouse Cinema:** Sip pints of beer, eat burgers, and screen independent films and long-forgotten B movies introduced by the stars and directors themselves (click here). S **Lady Bird Lake:** Walk the many trails around the lake, paddle out in a kayak, or take a ride on a genuine paddle wheel riverboat (click here). At the end of the 19th century, in one of his short stories, the great American author O. Henry referred to the then small municipality of Austin as the "city of the violet crown." In a single phrase, he captured the striking violet sunsets that often surrounded Austin in the evenings. Today this colorful evening show is the backdrop to Texas's most alluring city. The core of Austin's life revolves around a few things: the capitol, the university, the high-tech industry, and the music. The most prominent of these is its role as the capital of Texas. If Texas were a nation, its economy would rank as the eighth largest in the world. Austin provides the stage for this powerful political and economic evolution and has hosted politicians and their ideas for well over a century. The second most important driving force of the city is the University of Texas (UT), which has always functioned as its main repository of knowledge and disseminator of progressive ideas. Consistently ranked as one of the top universities in the nation and the world, UT draws people from all walks of life to Austin, adding to the city's diverse character. Third is the high-tech industry that was first planted here by IBM and later exploded with UT graduate Michael Dell's founding of Dell Computers. For the past few decades the tech industry has grown to such proportions that Austin has been dubbed "the Silicon Hills." Lastly is everybody's favorite, the music. Austin is proud to crank up the volume and loudly proclaim itself as the Live Music Capital of the World. With thousands of musicians, hundreds of clubs and venues, and an entire population of devout music lovers, the title is well deserved. Austin has proven that when you combine politics, education, high technology, and music you get an extraordinary concoction. With these elements Austin has successfully forged its own unique identity and stands in stark contrast to the rest of the state. It's a city that was built with spare parts from the Wild West, pop culture, and Americana. It's urban, and it's rural; it's a big city but somehow retains a small-town vibe; it's rich in history, but forward-looking; it's progressive but laid-back. All the above makes this Central Texas town a thrill to visit. Exploring Austin is like being the steel ball in a Rube Goldberg invention. You simply slide down the chute and go for the ride, not fretting about what is around each twist and turn. #### **PLANNING YOUR TIME** If a long three- to four-day weekend is all you have to explore the town, it can help to plan your time a little. However, the best way to experience Austin is to let yourself meander. As a weekend traveler, you can plan to spend most of your time right in the downtown area because all that you could ever want is within arm's reach. Most attractions are within walking distance, such as the state capitol, 6th Street, and the museums, and everything else is accessible by an inexpensive cab ride. On foot or by cab, in a weekend you can check out some of the galleries and museums, walk around Lady Bird Lake, poke your head into some of the intriguing curiosity shops on South Congress Avenue, and eat some delicious Tex-Mex. Above all, plan on staying up late, walking down 6th Street, and catching some live music at the many varied venues downtown. Music is absolutely everywhere, and is usually good, often great. If you plan to be in Austin for a couple weeks or longer, I would suggest a whole different approach to planning your time. Figure out where you would like to stay and settle in. Make a home base where you can leave your things and not worry too much about anything. Immediately upon checking in and unloading your luggage grab a free copy of the _Austin Chronicle_ and look through the music and events pages. There's so much going on that there's bound to be something of interest for everyone. Once you've made some mental notes on events to catch, take your time exploring the town and scouring the surrounding area. Catch one of the creepy ghost tours downtown, hike in the greenbelt, relax at Barton Springs, take a ride on Lady Bird Lake in an authentic double-decker paddle wheel riverboat, and spend half a day out at the Lady Bird Johnson Wildflower Center. After all this, if you still have a day to spare take a road trip out into the Hill Country. #### **ORIENTATION** Austin has several distinct areas where most of the attractions, restaurants, and accommodations are found. These areas are defined by neighborhoods and their streets—some of these streets being sights in their own right. Although Austin has several highways fanning out into the surrounding country, the two main highways that box in the city are I-35 and Highway 1. I-35 is on the east side of downtown, and is notorious for traffic accidents and congestion; Highway 1, known to locals as Mo-Pac (Missouri-Pacific Railroad), is to the west. Most of Austin's sights, best restaurants, hotels, and live music are somewhere between these two freeways. Since there's no definitive way to explain the geographical areas that Austin comprises, it's broken up here in a way that should make it easy for the newcomer to get around. ##### **Downtown** The first and foremost area is downtown, which encompasses the area north of Lady Bird Lake between I-35 and Lamar Boulevard. Downtown hot spots include **Congress Avenue,** which rolls down from the state capitol into town. Then there's the historic and infamous bar-studded **6th Street,** which is Austin's version of New Orleans's Bourbon Street. Sixth Street features bars, live music venues, and some tourist shops that sell junk that doesn't reflect Austin at all. For some reason tourists love 6th Street while locals are way "over it." Just on the west side of Congress Avenue is the **2nd Street District,** which has become one of Austin's well-known dining and shopping areas. The area is noted for being the home to the _Austin City Limits_ TV show, the W Hotel, and Willie Nelson in bronze. **Austin Fast Facts** • Founded in 1838 • Population: 931,830 (2016 U.S. Census Bureau data) • Land area: 297 square miles • Time zone: GMT/UTC-6 (Central Time) • Fourth-largest city in Texas • 11th-most populous city in the United States • County: Travis • Ethnicity: 49 percent white, 35 percent Hispanic, 8 percent African American, 8 percent other • Sunshine: Austin averages 300 days of sun every year • Average temperatures: 42-62°F in winter, 75-95°F in summer • Average rainfall: 32.49 inches annually • Major employers: City of Austin, Dell, federal government, Motorola, IBM, State of Texas, University of Texas at Austin, Apple, AMD, Applied Materials, Samsung, and 3M • Area colleges and universities: The University of Texas at Austin, Huston-Tillotson College, St. Edward's University, Concordia University at Austin, Southwest Texas State University, Austin Community College, Southwestern University • Median home price in 2016: $335,000 • Sales tax: 8.25 percent Bordered by West 7th, West 8th, Guadalupe, and San Antonio Streets is the **Bremond Historic District,** a middle-class neighborhood of old Victorian homes situated under ancient oak trees. Under the glow of the Frost Building, the most distinctive structure in Austin's skyline, there's the **Warehouse District,** also known as 4th Street. In the late 1800s this was the brothel district, then it was turned into an industrial area, and in recent years has reverted to the spirit of its origins and is now lined with upscale bars and pubs. The burgeoning **Rainey Street District** is a tiny pocket neighborhood fixed between downtown and I-35. Charming old houses have been tastefully converted into bars and eateries. Just west of downtown is **West End,** which includes **Enfield** and the restaurants on **West Lynn Street.** Lastly, there's the **Red River District** on Red River Street. Just a few years ago this area was the quietest part of downtown, but today it's a bustling street of clubs, bars, and live music in the alternative/punk/metal/hipster vein. ##### **South Austin** The cherished favorite for locals is South Austin. Here you have the ever-popular **South Congress Avenue,** which has some great curiosity shops, restaurants, clothing boutiques, and music clubs. A few streets west there's **South Lamar Boulevard,** where you can find some of Austin's many vintage and retro shops. South Austin is also popular for outdoor activities, with the gigantic grassy fields of **Zilker Park,** as well as trailheads to the beautiful hiking and biking area called the **Barton Creek Greenbelt.** Also in this area is Austin's premier feature, **Barton Springs.** ##### **Central Austin** Central Austin is largely dominated by the **University of Texas** campus. The campus features some excellent museums, the LBJ presidential library, sports stadiums, and performing-arts theaters. The street that connects the UT area to downtown is **Guadalupe Street,** known to locals as **The Drag.** This used to be a main artery of action but in recent years has little pulse. Here you'll find some chain clothing stores, freak and chic shops, some cheap eats, and some bars. Also in Central Austin is the **Hyde Park** area, which is home to beautifully restored Victorians and neighborhood restaurants on **Duval Street.** ##### **East Austin** Also referred to as the East Side, East Austin is the area in town that's experiencing growing pains. This is the "sketchy" part of town that's getting gentrified with the help of chic restaurants and city development. What Austinites consider sketchy is tame compared to similar areas in other cities. The East Side has some fine restaurants, a few boutique shops, some art spaces, and a few bars and music clubs, and is home to many of Austin's artists. ##### **Old North Austin** Old North Austin is just starting to realize its potential. Visitors to Austin probably won't find themselves in this area without special effort. It's just north of the UT campus area, and only five miles from downtown. Although there are no sights to speak of, there are some interesting shops, boutiques, antiques stores, and "old-time" eateries. The area is popular among locals because it has a weird '70s time warp appeal. In Old North Austin there's **Old Burnet Road** (pronounced "BURN-it"), which has some of Austin's more unusual businesses and the area's best dive bars. There's also **East North loop,** which is a small bend in the road. This tiny area of shops doesn't look like much, but give it a chance and your sense of curiosity and adventure is sure to be piqued. ### **Sights** Austin has an eclectic and multifarious array of sights and attractions that include all of what one might expect from a large U.S. city, such as museums, grand architecture, botanical gardens, and monuments to historical figures. These are all what I would call the "typical" sights. Then there are the "atypical" sights, such as the ghostly bronze statue of Angelina Eberly firing her cannon and single-handedly saving Austin; the Cathedral of Junk; the Umlauf Sculpture Garden; the 500-year-old Treaty Oak tree, a survivor of chain saws and poisoning; and the famous bat colony of Congress Avenue Bridge. From typical to unique to downright strange, all Austin's attractions singularly and collectively stir the imagination, summon the bizarre, and foster new curiosities. Austin's main attraction is simply nature. The parks and gardens, the lakes and streams, the hiking and biking trails, and the wildflowers and oaks are most worthy to behold, especially at twilight when Mother Nature's coronation ceremony fills the city skyline with the violet crown. #### **DOWNTOWN** ##### S **Texas State Capitol** The **Texas State Capitol** (1100 Congress Ave.) is the nucleus of Austin, both historically and visually. When you see the massive statehouse on the skyline, consider that it almost never was. Over a hundred years ago a tug of war between the cities of Houston and Waterloo (Austin was initially named Waterloo) went on for years, and every so often the state government would shift between the cities. Austin eventually won the title of state capital, and this decision has since shaped the city's development. When the capitol building was first erected back in 1888 it was believed to be the seventh-tallest building in the world. Today it supposedly stands taller than the U.S. Capitol, a detail Texans are proud to point out. The interior of the capitol exudes a hushed dignity. Each component, from the grand marble pillars down to the door hinges, is an example of the fine craftsmanship of a bygone era. Old battle flags, sculptures, and portraits of historical figures and significant events in Texas history grace the entryways, walls, and legislative chambers, leaving visitors with strong visual images of Texas's story. A large, colorful marble terrazzo covers the floor of the capitol rotunda, depicting the six sovereign flags that have flown over Texas and 12 battles significant in the history of the state. The rotunda is also home to portraits of all the Texas governors. During the 20th century, as the state of Texas grew, so did its government, and the capitol became increasingly hard-pressed for space. Over the years quick fixes were made to accommodate the demands placed on the century-old building. Successive additions of new technologies like telephones, air conditioners, and computers, and the need for more offices, led to a maze of false walls and generations of wiring. No one was surprised when a fire broke out in 1983. The event highlighted the need for renovation and expansion. After 10 years of bureaucracy, funding woes, and architectural debate, excavation and construction finally started. In 1993, the underground expansion of the capitol was dedicated. The results of this project are truly a sight to behold. To build the 620,000-square-foot subterranean extension, nearly 700,000 tons of rock had to be removed, and a 130-foot-long, 32-foot-deep trench had to be dug through solid limestone to connect the original building to the new extension without harming the original foundation or structure. Today, the opulent capitol and the beautiful surrounding 22-acre grounds are well worth a visit. The capitol is free and open to the public 7am-10pm weekdays, 9am-8pm weekends. Free guided tours are offered 8:30am-4:30pm Monday-Friday, 9:30am-3:30pm Saturday, and noon-3:30pm Sunday. Plan on spending about two hours at the capitol grounds to take in the history, monuments, and architecture. ###### **CAPITOL VISITORS CENTER** If you're itching for more information on the capitol, walk over to the **Capitol Visitors Center** (112 E. 11th St., 512/305-8400, 9am-5pm Mon.-Sat., noon-5pm Sun., free), at the southeast corner of the capitol grounds. Here you'll find exhibits, a video presentation on the secret rooms and spaces in the capitol, and a salute to O. Henry. ###### **OLD STATE CAPITOL BUILDING RUINS** Directly across from the capitol, at Congress and 11th, are the remains of Austin's first statehouse, the **Old State Capitol Building Ruins.** There's not much there but the original crumbling foundation and a cistern. It's also where University of Texas classes were held back in the late 1800s. ###### **GOVERNOR'S MANSION** Not too far from the capitol is the **Governor's Mansion** (1010 Colorado St., 512/305-8524, 2pm-4pm Wed.-Fri., free, by reservation only). This Greek Revival-style house has been the home for every governor since it was designed and constructed back in 1856. Built with Austin-made bricks and timbers from Bastrop, this fine architectural work has survived years of politics, stuffy decor, and renovations. Today the mansion is the oldest standing public building in downtown, and is the fourth-oldest continuously occupied governor's mansion in the United States. Over the years paranormal activity has been reported, and in plain English that means some have seen "dead people." Some think it's the ghost of Sam Houston, while others think it's the ghost of a lovesick 19-year-old who shot himself in the guest room. The mansion suffered extensive damage from a fire in 2008 but reopened to visitors in 2013. Visiting hours can vary throughout the year so be sure to check hours online or by calling ahead. ##### S **Barton Springs Pool** In the dead of summer, when few Austinites stray too far from the air-conditioning, there's one place that's sure to be a cool 68 degrees, and that's **Barton Springs Pool** (2101 Barton Springs Rd., 512/867-3080). This age-old artesian spring-fed pool in Zilker Park has faithfully provided Austinites with a cool place to swim, relax, and socialize for over 100 years. On any given summer day Barton Springs Pool is packed with families, flirting teenagers, sunseekers, and daredevils at the diving board showing off their tricks. Barton Springs Pool The 1,000-foot-long swimming hole is fed by several underwater springs. When the springs were dammed off to create the pool, the rock and gravel bottom was wisely left unaltered, preserving the natural ambience. If you're concerned about pollution or hygiene, you'll be glad to hear the pool has a legion of advocates (the Save Our Springs Coalition) that closely guard this precious resource. When it comes to pollution Barton Springs' pure waters have been tirelessly defended from the constant threat of damaging development on the aquifer that feeds the pool. As for hygiene, the pool is closed when the fecal coliform count is high. The pool is open daily (except Thursdays) 5am-10pm in the summer. Access to the pool is $3 for adults, $2 for ages 12-17, and $1 for seniors and kids 11 and under. Remember this is a cash-only operation. Swimming before 8am is free but "swim at your own risk"; lifeguards are on duty only during the fee periods. There are two ways to access the pool, with the main entrance off Barton Springs Road. For the back entrance off Barton Springs Road, turn away from Lady Bird Lake on Robert E. Lee Drive, go up the hill, and park at the gravel parking area next to the baseball field. Words of advice: Call before you go to make sure the pool is open, check the hours (which change seasonally), and don't bring food (eating on the grounds is prohibited). Hanging out at the pool can easily be a half-day leisure event, that is if you enjoy swimming, sunbathing, and people-watching. ##### S **6th Street** Besides bats, Austin is probably most known for **6th Street,** which is Austin's version of New Orleans's Bourbon Street. It features bars, pubs, live music venues, and sidewalk pizza kiosks. After dusk live music comes from every crack and crevice. On Thursday, Friday, and Saturday nights around 10pm, the Austin police department closes off the street and the party begins. The scene on 6th Street is pretty rowdy, with hordes of wasted college kids and scantily clad girls. There's always a contingent of men roaming about, afflicted with an acute case of machismo, looking for a date, a fight, or both in one. The scene can get pretty sketchy later in the night—a good time to bail on this scene is around midnight, and especially before the bars close at 2am. **Austin Quirks** There are many subtle and strange things you may notice while exploring this town that prides itself on being weird. Here's a list in no particular order. • **Yard Art and Lawn Statuary:** While driving around town you may notice Austin's pervasive veneration for yard art and lawn statuary. Popular yard decorations are pink flamingoes, metal kinetic art, bizarre sculptures, and yard gnomes, some of which have an uncanny resemblance to George W. Bush. • **Freak Storms:** Austin, as well as the Hill Country, is notorious for freak mini storms that pass through the area in a matter of minutes. One second it's a nice evening at about 70°F and the next the wind will whip up and lightning will fill the skies. Then the next thing you know hail the size of golf balls is plummeting to the earth. In an hour or so the sky clears up as if nothing happened. • **Liberal Bumper Stickers:** If you had to figure out which city you were in solely by the bumper stickers on cars you would probably guess you were in Berkeley, California. A city in Texas would be your last guess. This is one of the great conundrums of Austin. The capital of the conservative state of Texas is liberal Austin. • **_Bosom Buddies_ Theme Song:** You have to completely tap into your subconscious to catch this one. When you are about town, shopping for groceries at H.E.B., in the lobby of a motel, or even sitting in a piano bar, you will begin to notice Billy Joel's lyrics, "I don't care what you say anymore, this is my life. Go ahead with your own life, and leave me alone." This melody is a subliminal and curious soundtrack to Austin life. Besides clubs and bars there's also a slew of terrible tourist shops that feature belt buckles, Texas memorabilia with the state flag screen-printed on everything, samurai swords (don't ask why), shot glasses, and ridiculous touristy T-shirts that say things like "F*** Y'all, I'm from Texas," which doesn't represent Texas or Austin in even the slightest way. Sure, there are some good live music spots here, but you have to put up with lots of nonsense to enjoy it. If you like spring break at Daytona Beach or New Orleans during Mardi Gras, you'll probably like 6th Street, in which case you will probably want to plan for 5 hours as you may want to catch a late dinner down here before enjoying the live music and nightlife until after midnight. ##### S **The Bats of Congress Avenue Bridge** Austin's main attraction isn't always rock stars. **Bats** are the stars of the show every evening when they fly out from under Congress Avenue Bridge by the thousands in search of bugs. When the bridge was reconstructed in the 1980s no one had any idea this spot would become the largest urban bat colony in North America. These Mexican free-tailed bats migrate each spring from central Mexico to various roosting sites throughout the southwestern United States, their favorite being here in Austin. Out of the 1.5 million bats in this colony, most are females, who produce one offspring each June. Every night they eat somewhere between 10,000 and 30,000 pounds of insects. You can catch the bats' dramatic exit into the night from March to early November, but the best months are July and August. Best spots for viewing the bat flight are the **Bat Observation Area** at the _Austin American-Statesman_ (at the southeast corner of the Congress Avenue Bridge), at the Radisson Hotel (11 E. 1st St.), on Lady Bird Lake from a **canoe** (rent from Zilker Park Boat Rentals for $12 an hour, www.zilkerboats.com), or on an authentic **double-decker paddle-wheel riverboat** (Lone Star Riverboat, 512/327-9721, $10 per person). Best time for viewing is sunset, and parking is offered at the _Austin American-Statesman_ after 6pm. No public restrooms are available. For more information on the bats, such as flight times, call the Bat Hotline at 512/327-9721, ext. 3636. Be prepared to hang around the bridge for a couple of hours so you can get a good spot; in the summer, the bridge can often be packed. ##### S **LBJ Library and Museum** Considered the most visited presidential library in the United States, the **LBJ Library and Museum** (2313 Red River St., on the University of Texas campus, 512/721-0200, www.lbjlibrary.org, 9am-5pm daily, $8 adults, $5 seniors and retired military, $3 college students and children 13-17) explores the life and politics of Lyndon Baines Johnson. If you know little to nothing about LBJ, the permanent exhibit that recounts his life is sure to capture your interest and foster an appreciation of the 36th president. Midway through the exhibit, expect an emotional sucker punch when the exhibit commemorates the assassination of JFK in a moving way. From here on out it explores the period in U.S. history that ushered in a new era in culture and politics—the 1960s. When you surface in the gigantic main room and look up, your breath will be taken away by a towering wall of glass, behind which are floors of red archives containing everything LBJ ever wrote, did, and darn near thought. Be sure to listen to the mechanical LBJ tell jokes. Plan on spending at least two hours for the exhibits and in the gift shop. The LBJ Library and Museum is the most visited presidential library in the US. ##### S **Blanton Museum of Art** The only art museum in Austin with a permanent collection to speak of is **Blanton Museum of Art** (200 E. Martin Luther King Jr. Blvd., on the UT campus, 512/471-7324, 10am-5pm Tues.-Fri., 11am-5pm Sat., 1pm-5pm Sun., $9 adults, $7 seniors, $5 ages 13-21, free every Thurs. with extended hours on the third Thurs. of each month). Located at the edge of the university campus in downtown Austin, the Blanton is the largest university museum in the United States. Inside the 180,000-square-foot complex are both temporary and permanent exhibits, and outside is an attractive public plaza with views of the state capitol. The Blanton's permanent collection includes some 17,000 works of art, including old master paintings and contemporary American art, and is proud to be one of the largest public collections of Latin American art in the United States. Works by notable artists include those of Pablo Picasso, Peter Paul Rubens, and Fernando Botero. Plan on spending at least two hours for the exhibits and the gift shop. ##### S **Bullock Texas State History Museum** Texas state pride is bigger than Texas itself. It's fitting that the museum devoted to the big spirit of Texas is gigantic, and adorned with a 35-foot-tall bronze Lone Star. In the grand polished stone halls of the **Bullock Texas State History Museum** (1800 N. Congress Ave., 866/369-7108, www.thestoryoftexas.com, 9am-5pm Mon.-Sat., noon-6pm Sun., $13 adults, $11 seniors, military, and college students, $9 youth 4-17), the "Story of Texas" is told. From the indigenous people who first inhabited the region to the Spanish explorers of the 1500s and the legendary battle at The Alamo, through the oil boom to the present day, Texas's history is chronicled in life-size dioramas and interactive exhibits. The facility also houses two theaters. The Texas Spirit Theater provides a multimedia, cinematic experience complete with special effects that bring Texas's story to life. The museum also boasts Austin's only IMAX theater, which operates independently of the museum. Plan on spending at least 2 hours for the exhibits and the gift shop and 3-4 hours if you also include a visit to IMAX theater. History is taken to a sacred level at the Bullock Texas State History Museum. So who was Bob Bullock, the museum's namesake? He was a highly regarded state politician who eventually became the lieutenant governor. His vision and passion for all things Texas brought the museum into fruition. Admission prices vary. I recommend buying tickets to the museum and the Texas Spirit Theater's 20-minute movie ($5 adults, $4 students, seniors, and youths 4-17). For those who haven't acquired Texas Pride, or just aren't in the mood for a multimedia Texas experience, "never mind the Bullocks." There are many other museums to saunter through. ##### **Harry Ransom Humanities Research Center** There's only one place in the world where you can see a Gutenberg Bible, the world's first photograph, an original manuscript by James Joyce, and a painting by Frida Kahlo all in one place, and that's the **Harry Ransom Humanities Research Center** (21st and Guadalupe St., on the UT campus, 512/471-8944, www.hrc.utexas.edu, 10am-5pm Mon., Tues., Wed., and Fri., 10am-7pm Thurs., noon-5pm Sat.-Sun., free). Self-billed as "one of the world's finest culture archives," the Harry Ransom Center is a place where scholars conduct research alongside tourists and the curious. The center houses a robust collection of over 36 million literary manuscripts, including ones by Ernest Hemingway, James Joyce, T. S. Eliot, and Tennessee Williams, and over 100,000 works of art that are rotated into view. Along with showcasing its own collections, the center also has temporary exhibits. Parking is at the Dobie Center parking garage on the corner of 21st and Whitis. ##### **Mexic-Arte Museum** The **Mexic-Arte Museum** (419 Congress Ave., 512/480-9373, www.mexic-artemuseum.org, 10am-6pm Mon.-Thurs., 10am-5pm Fri.-Sat., noon-5pm Sun., $5 adults, $4 seniors, $1 children 12 and under) has emerged as the official Mexican and Mexican American fine-art museum of Texas. You can encounter works by contemporary Mexican, Latino, and Latin-American artists in the museum's three gallery spaces. Mexic-Arte offers a permanent collection, but the primary focus here is special exhibits and shows that both educate and get people thinking. On any given day the art here is poignant, colorful, and inspiring, offering a glimpse into the inner life of Latino culture through the arts. ##### **O. Henry Museum** The prolific American short-story writer O. Henry (1862-1910) made Austin his home for a brief stint. His little house, now the **O. Henry Museum** (409 E. 5th St., 512/472-1903, noon-5pm Wed.-Sun., free but donations encouraged), is a beautiful Queen Anne cottage containing some of O. Henry's personal items. Born William Sydney Porter in Greensboro, North Carolina, he came to Austin when he was 20 years old. Here he started a humorous weekly called _The Rolling Stone_ (not to be confused with the pop-culture magazine of today), fell in love, married, and moved into this house, which was owned by his new wife's family. Ten years later he found himself in an Ohio prison, where his writing started taking off. Upon leaving the penitentiary he changed his name to O. Henry and moved to New York City, where his life fizzled out, with a second failed marriage and alcohol problems. The master of surprise endings eventually died of cirrhosis of the liver. the O. Henry Museum ##### **The Contemporary Austin** All things related to modern and cutting-edge art are presented at **The Contemporary Austin** 's two locations. The large indoor exhibition space at the **Jones Center** (700 Congress Ave., 512/453-5312, <http://thecontemporaryaustin.org>, 11am-7pm Tues.-Sat., noon-5pm Sun., $5) is an indoor museum and art space dedicated to promoting and exhibiting contemporary art. Founded in 1911 to promote the works of locally celebrated artist **Elisabet Ney** (whose house is now an Austin museum), the gallery space currently has exhibitions and programs geared toward educating. The **Laguna Gloria** location (3809 W. 35th St., 512/458-8191, 10am-4pm Tues.-Sun.) is at a mansion nestled on a stunning site near the lake at Mayfield Park and Preserve. This extension of the Contemporary Austin features an outdoor sculpture park and a small indoor exhibition space. As a side note, the mansion was built by Clara Driscoll, who is dubbed "the savior of the Alamo" because she bought the historic grounds in San Antonio to prevent developers from leveling the site. ##### **Austin History Center** Austin's rich history has been collected, archived, and made available by the **Austin History Center** (810 Guadalupe St., next to the Austin Public Library, 512/974-7480, 10am-6pm Tues.-Sat., noon-6pm Sun., free). Housed in a historic neoclassical building, the collection consists of millions of photos, maps, architectural drawings, documented customs, newspapers, and records, and is the main repository for history in the Central Texas region. ##### **Austin Nature and Science Center** Ever wanted to pretend you're a scientist? **Austin Nature and Science Center** (301 Nature Dr., in Zilker Park just off Stratford Dr., 512/974-3888, 9am-5pm Mon.-Sat., noon-5pm Sun., $2 donation) offers many different ways to discover and explore for a day. Here you can learn about the plants, animals, and geology of Central Texas. The Discovery Lab has several mini science labs that engage and educate through hands-on exhibits. In the Dino Pit you can become a paleontologist and dig up dinosaur bones. ##### **Museum of the Weird** If you are fascinated by the unusual and the bizarre, or you are just plain curious, this small storefront "museum" on 6th Street will fill your head with all sorts of crazy images and thoughts. **Museum of the Weird** (412 E. 6th St., Austin, 512/476-5493, 10am-midnight daily, $12 adults, $7 children under 8) is the only place in the world where you can view up close a mermaid-monkey creature, skeletons, shrunken heads, and lots more creepy stuff. If you take the tour you can also stroll up to the top floor and watch sideshow performances in a small room. A tattoo-covered performer may swallow a sword or electrocute himself. On the way up the stairs you'll have the opportunity to swallow a giant Madagascar hissing cockroach, and you can view the room where Johnny Depp stayed when he was in town filming a movie. If all this isn't enough, for a couple extra bucks you can see the museum's most prized treasure: the giant frozen body of a prehistoric, Sasquatch-type man-creature known as the Minnesota Iceman. This specimen is frozen in a block of ice inside a specially designed coffin/freezer. Peering through the glass at this mangy face brings up all sorts of thoughts from, "is this real?" to "will he come alive if the ice is thawed?" to "this is just plain ridiculous!" Viewing hours for the Iceman are limited, so it's best to call in advance. ##### **Emma S. Barrientos Mexican American Cultural Center** Austin is proud to have a vibrant Latino community comprising families, business owners, politicians, musicians, and artists. **Emma S. Barrientos Mexican American Cultural Center** (600 River St., 512/974-3772, www.ci.austin.tx.us/macc, 10am-6pm Mon.-Thurs., 10am-5:30pm Fri., 10am-4pm Sat.) is emerging as the official Mexican American cultural center in Austin. Here you can encounter works by contemporary Mexican, Latino, and Latin-American artists, participate in classes, and screen films from Mexico's Golden Age era of film. ##### **Texas Memorial Museum** For the kids and parents alike there's the **Texas Memorial Museum** (2400 Trinity St., on the UT campus, 512/471-1604, www.utexas.edu/tmm, 9am-5pm Tues.-Sat., $3, $1 military, 2 and under is free), which has four floors of exhibits dedicated to the natural sciences. The big draw here is the dinosaur exhibit, which features dinosaur models, including a 40-foot-long pterosaur, fossils of saber-toothed tiger kittens, and dinosaur footprints. The 1st floor has fossils, gems, and minerals, with a paleontologist on site to answer questions; the 2nd floor displays rare specimens; the 3rd floor features wildlife exhibits with mounted birds, animals, reptiles, and amphibians; and the 4th floor has an exhibit featuring colorful and unusual insects, microscopic cave fauna, and fish. Parking is available at the UT parking garage at 2500 San Jacinto Boulevard, just north of the museum. ##### **Treaty Oak** When you arrive at this sight you may wonder why an old tree with a plaque on it is worth seeing. Well, the venerable 500-year-old Treaty Oak is a source of legend, history, and drama, with a story of religion, truces, chain saws, poison, and endurance. It is the last survivor of the Council Oaks, a grove of trees that was once a place of religious ceremony for the area's Comanche and Tonkawa populations. According to legend, it is also the site where Stephen F. Austin signed a boundary treaty with local Native Americans in the 1800s. In the 1920s, when the Council Oaks were being cleared for urban growth, this one ancient tree was saved from a violent death by chain saw and was consecrated a historic U.S. tree by the American Forestry Association. The Treaty Oak is remembered by most folk not for having witnessed Austin's history, but for what happened to it in the 1980s when a lovesick lunatic poured lethal amounts of poison on the tree to get back at a lover. Don't ask why. In the ensuing months the Treaty Oak made national headlines as dendrite doctors tried to save the tree. Now about 35 percent of the tree is alive, and the Treaty Oak has become a symbol of endurance for Native Americans and Anglos alike. If you want to see this historic tree there's no need to make a special trip. Just check it out while you're eating at Z'Tejas Southwestern Grill. The Treaty Oak is on Baylor Street between 5th and 6th Streets, just west of Lamar Boulevard. ##### **Mount Bonnell** What is considered a hill by some is a mountain to others. Since Texas doesn't have much in the way of mountains, I suppose **Mount Bonnell** (Mount Bonnell Rd.) has earned its title. Towering 785 feet above Austin, Mount Bonnell offers a spectacular panoramic view of the city, the Colorado River, and the surrounding area. The 200-foot limestone escarpment is a strenuous climb but worth the effort. When you are on top of the mount, consider how it was once called "Antoinette's Leap" in remembrance of a settler who jumped off the cliff rather than perish during a Native American attack. Don't expect any snowcapped peaks, and don't try to find Mount Bonnell by driving toward "the mountain," as you can't see it from anywhere. It's accessed from Mo-Pac Expressway/Highway 1 by exiting at 35th Street and heading west. On your way back down the mountain, stop off at **Dry Creek Saloon** (4812 Mount Bonnell Rd., 512/453-9244) for a beer. #### **SOUTH AUSTIN** ##### S **South Congress Avenue** The bat colony at Congress Avenue Bridge marks the beginning of a strip of curiosity shops, eateries, and clubs on South Congress Avenue. If 6th Street is too touristy for you, you'll love this street. Enjoy strolling around with a cup of coffee from the parking-lot kiosk Jo's Cafe. Be sure to always look up as you walk along South Congress, because many of these businesses have great signs and sculptures attached to their roofs and storefronts. For example, there's a cowboy made out of a muffler, riding a giant rabbit, and a zebra dressed up like Carmen Miranda. You can get lost for hours in the multifarious shops and boutiques, like the folk-art gallery Yard Dog, the vintage shop Uncommon Objects, the costume shop Lucy in Disguise with Diamonds, and the Western-wear shop Allens Boots. South Congress is fun during the day for window-shopping and at night for restaurants and live music. The absolute best day of the week is the first Thursday of each month when the businesses stay open late (most until 10pm). The streets are full of vendors and artists selling their wares, and bands play on the sidewalks. If you want to enjoy the shops and get a bite to eat, you can easily lose yourself for 2-4 hours exploring fajitas, bizarre taxidermy, hip clothing, luchador masks, vintage shops, and musty Elvis costumes. Walking up and down South Congress Avenue is a great way to let a day slip away. ##### **Lady Bird Johnson Wildflower Center** Come spring, Austin and the surrounding Hill Country have some of the most varied and beautiful wildflowers in the state. It's no surprise there's a center devoted to these little guys. In 1982 the **Lady Bird Johnson Wildflower Center** (4801 La Crosse Ave., 512/232-0100, www.wildflower.org, 9am-5pm Tues.-Sat., noon-5pm Sun., $10 adults, $8 seniors and students, $4 children 5-17) was founded under a different name, and at a different location, by two spry advocates of native plants, former First Lady of the United States Lady Bird Johnson and a friend. In 1995 the center was moved to its current location on 279 acres southwest of Austin, and in 1998 it was renamed in honor of Lady Bird Johnson. The main grounds include 16 carefully placed and meticulously maintained gardens, all designed around the region's natural landscape, using native plants. The gardens weave through and around several stone buildings that serve as educational centers and galleries, and lead to even more gardens with wisteria-covered pergolas and flower-lined promenades. The center isn't in Austin proper, but it's well worth the drive. Since it all hinges on wildflowers and seasonal native plants, don't bother visiting in the fall or winter when everything is dead. ##### **Zilker Park** The heart of Austin's outdoor action is **Zilker Park** (2100 Barton Springs Rd.). The park's beautiful setting is unparalleled, with 351 acres of green grass at the edge of Lady Bird Lake, groves of old oak trees, and a dramatic view of Austin's city skyline rising from the trees in the distance. Most of the city's outdoor events happen here, such as the Austin City Limits Music Festival, Austin Symphony July 4th Concert and Fireworks, Trail of Lights, Zilker Park Christmas Tree, and the Zilker Park Kite Festival, which has been held here for almost 80 years. On the grassy knoll next to Barton Springs Pool, classical, rock, and everything in between can be heard at the **Zilker Hillside Theater,** which also is home to the **Zilker Summer Musical** and **Shakespeare in the Park.** Down the parking lot from the theater and at the entrance to Barton Springs is the depot for the **Zilker Zephyr,** a miniature open-air train that weaves through the park—a huge hit with kids. Past the Zephyr and down the riverbank you can rent a canoe and paddle around on **Lady Bird Lake** and get a unique view of Austin. **Blues on the Green** happens on alternating summer Wednesdays at the **Rock Garden,** which is in the middle of the large grassy area that is bordered by Barton Springs Road. The park is also home to the **Austin Nature and Science Center,** where everyone can participate in interactive wildlife, nature, and science displays. Zilker Park also has an entrance to the **Greenbelt,** which has trails for hiking and biking. At any given day throughout the year, Zilker Park is a safe bet for a day in the outdoors. Parking lots are available, but it's nearly impossible to find a spot during major festivals. **Austin's Jack the Ripper** Early Austin history has many shades, characters, and shady characters. One of Austin's darkest chapters took place in 1885 when the young city was haunted by the shadiest character in all the town's history. Lurking in the shadows was a serial killer who is now known as the Servant Girl Annihilator. For an entire year there was a chill of horror on the streets of Austin. This Texas version of Jack the Ripper was never seen, nor caught, but his trail of blood was everywhere. He brutally murdered seven servant girls of poor origins and one man; all were hacked to death with an ax. The bodies turned up in alleys and behind homes, and one of the bodies was found on what is now West 6th Street. Headlines for that year were horrifying, and all the city's residents could do was hope and pray that either the killing spree would stop or the murderer would get caught. On Christmas Eve the last murder took place, and after that there were no more. Eventually three arrests were made and one suspect went to trial, but he was acquitted. All of the murders have remained unsolved. The uncanny twist to this tale is that three years after the Austin murders, Jack the Ripper began his infamous spree in England. If this bit of Austin's history interests you, novelist Steven Saylor's historical fiction work **_A Twist at the End_** (St. Martin's Minotaur, 2001) probes into this dark tale. You can also walk in the footsteps of the Servant Girl Annihilator with **Austin Ghost Tours** (512/853-9826, www.austinghosttours.com). ##### **Zilker Botanical Garden** The unique climate around the south shore of Lady Bird Lake has made a perfect location for the diverse gardens at **Zilker Botanical Garden** (2220 Barton Springs Rd., 512/477-8672, www.zilkergarden.org, 7am-7pm daily, $3 general admission, $2 Austin residents, $1 children 3-12 and seniors ages 62 and older). Gardens include the waterfall, ponds, and bridges of the Taniguchi Oriental Garden; the Cactus and Succulent Garden; the Rose Garden; the Butterfly Trail and Garden; and the City of Austin's Green Garden. Lastly, there's the garden that interests the whole family, the **Hartman Prehistoric Garden,** located on the site where dinosaur tracks were found in 1992. Plants in this garden represent those that existed at the time of the dinosaurs. To jump-start the imagination, small-scale bronze statues of dinosaurs that roamed here have been placed throughout the gardens. The Garden Center complex houses a little gift shop with items for kids and those with a green thumb. Parking is available. ##### **Umlauf Sculpture Garden and Museum** The **Umlauf Sculpture Garden and Museum** (605 Robert E. Lee Rd., 512/445-5582, www.umlaufsculpture.org, 10am-4pm Tues.-Fri., noon-4pm Sat.-Sun., $5 adults, $3 seniors, 12 and under free) is truly a one-of-a-kind Austin sight. Never heard of Charles Umlauf? Well, you're not alone. The prolific and internationally recognized artist donated his home and many of his works to his own cause, and I'm glad he did. Strolling around the grounds of this museum piques the imagination and sparks curiosity. The style of Umlauf's sculpture is evocative and emotional, with subject matter ranging from alien-looking angels to pieces that tell a story about the Nazi invasion of Poland. ##### **Cathedral of Junk** History will one day refer to our age as the age of waste, and when future archaeologists discover the **Cathedral of Junk** (4422 Lareina Dr., 512/299-7413), they may think we worshiped the gods of garbage. In the backyard of a small house in South Austin is artist Vince Hannemann's life work. Here you'll find over 60 tons of post-market-consumer junk weaved, stacked, stuffed, twisted, and screwed together, all amid overgrown vegetation. The final effect is astonishing. This temple of refuse has been featured in motion pictures such as _Spy Kids 3D,_ and has been the backdrop for top-model photo shoots as well. The artist didn't create this masterpiece to express some profound point about our consumer culture of obsolescence, or because he believes in worshiping transcendental refuse. In his own words, he did it "because it was kinda cool." Bravo! The cathedral was nearly scrapped when the city tagged it as a blatant code violation. Luckily the city and the artist figured out how to retrofit the structure to make it safer so it could be preserved. The artist opens the cathedral to the public Saturday and Sunday noon-6pm, and by appointment during the week. ##### **South Austin Museum of Popular Culture** It should come as no surprise that there's a homespun **South Austin Museum of Popular Culture** (1516 S. Lamar Blvd., 512/440-8318, 1pm-6pm Thurs.-Sun., free) in Austin. The best way to explain this place is by completely dismantling its name. First of all, this DIY museum is really more of a shrine than a museum—a shrine to 1960s and '70s music. And it's actually not about pop culture per se, but about the counterculture. The only thing that's correct in the title is that it is, in fact, in South Austin. Here you can marvel at the incredible world of music from the pioneering age of sex, drugs, and rock 'n' roll. The walls are filled with posters, T-shirts, and memorabilia from this era. For those who don't think poster art is fine art, the founder of this museum says, "'Fine' is a four-letter word. It's the F-word of the art world." #### **CENTRAL AUSTIN** ##### **Elisabet Ney Museum** The oldest museum in Texas, and one of the most interesting smaller museums in Austin, is the **Elisabet Ney Museum** (304 E. 44th St., 512/458-2255, noon-5pm Wed.-Sun., free). In the late 1900s this castlelike home was the only building in the Hyde Park area, and was the home to German-born sculptress Elisabet Ney. Now you can walk through the bright rooms and view more than 80 statues and busts of characters from Texas history as well as both known and unknown characters from Europe. ##### **University of Texas Campus** The three things that drive this city are politics at the state capitol, live music, and the University of Texas. UT is big in both size and state importance. Founded in 1883 on 40 acres just north of downtown, the campus now occupies over 350 acres and draws some 50,000 students to the main campus alone. Many of Austin's main attractions and museums are located on campus, including the **LBJ Library and Museum, Harry Ransom Center, Texas Memorial Museum, Frank Erwin Center,** the **Battle Oaks,** the **Cactus Cafe** for live music, and the **UT Tower and observation deck.** Along with these, UT sports draw a phenomenal number of people to Austin and the campus. **Signs of Longhorn Pride** There are a few things the newcomer to Austin will notice around town that may cause some confusion, or at least raise some questions. Now is as good a time as any to clarify a few points. First of all, let me explain the color orange. It's technically called **burnt orange** and is more of a rusty color. This sacred hue is seen everywhere in Austin. People even paint their houses and cars with it. It's so pervasive that it's darn near the official color of the city. However, it's actually the official team color of the University of Texas Longhorns. Local sports fans bleed orange in Austin. Secondly, the outsider may notice the simple iconic image of **steer horns** plastered all over town. This image is just as pervasive as burnt orange, popping up on city street signs, on most cars on the roads, in advertisements, and on flags that are simultaneously flown with the Texas state flag. Again, the image of the steer—or more correctly the longhorn steer—isn't the city's official logo; it belongs to the celebrated college football team the UT Longhorns. Finally, the most confusing thing for the outsider is the popular **hand sign** that Austinites display. This gesture, with pinky and index fingers raised, resembles the sinister hand sign of devil horns attributed to heavy metal and Satanism. But in Austin, and Texas in general, this is called the "Hook 'em Horns" and has nothing to do with old Beelzebub. In fact, in other cultures it has less evil meanings: In Buddhism it's a prayerful symbol that wards off evil, in parts of Africa it's a curse, and in sign language it means "bullsh—." In Austin this symbol is the hand sign of UT fans, devised back in the 1950s, which definitely predates heavy metal. Visitor parking is available at seven garages. Garages are located on Brazos Street (the only parking garage open 24 hours), Manor Avenue (for Bass Concert Hall and sporting events), San Jacinto Street (for Bass Concert Hall), Speedway, Trinity (for Frank Erwin Center), 27th Street (for football games), and San Antonio Street. Rates are $3 for 0.5-1 hour, $6 for 1-2 hours, $9 for 2-3 hours, $12 for 3-12 hours, and less than 30 minutes is free. For more information visit the **UT Visitor Center** (405 W. 25th St. on the 2nd floor of Walter Webb Hall, 8am-5pm Mon.-Fri., 9am-noon Sat.). Advance registration is required for tours. ##### **The Drag** Every campus needs its slightly seedy commercial area where students can get textbooks and booze. The busy section of Guadalupe Street that runs along the western edge of the University of Texas campus, aptly called the Drag, is Austin's version. Although not as wild as in earlier years, the Drag is a bustling area similar to Telegraph Avenue near the University of California, Berkeley, with students mixing with street folk at late-night cafés, record stores, clothing outlets, live music venues, and bars. It may have passed its prime, and is no longer the cultural epicenter it once was, but there's still lots to see and do here. There are several chain clothing shops clinging to any remaining threads of trendiness, great bars such as **Hole in the Wall,** tattoo shops such as **Diablo Rojo,** restaurants like **Kerby Lane** and **Madam Mam's,** and a couple of notable vintage clothing outlets. The Drag is where _Austin City Limits_ and Dell computers began: The giant square, dark, ominous brown building across from Madam Mam's was home to the famous _Austin City Limits_ studio where all the classic live performances were taped (before the studio moved downtown), and the Dobie Center (UT dorms) is where Dell computer corporation was cooked up. Parking on and near the Drag can be challenging, so plan on driving in circles and eventually parking a couple blocks away. #### **EAST AUSTIN** ##### **The Thinkery** Who needs tons of sugar to get kids amped up when there's the **Thinkery** (1830 Simond Ave., 512/469-6200, <http://thinkeryaustin.org>, 10am-5pm Tues.-Fri., 10am-6pm Sat.-Sun., $10, free for 0-23-month-old babies)? This is just about the most fun place in Central Texas for kids. What started out as a grassroots organization for children (without a facility) eventually became a fancy million-dollar institution, thanks to the Dell Corporation. Inside are two stories with several permanent and temporary exhibits, all very cartoon-esque, but learning oriented. Kids are bedazzled by colors, sounds, and hands-on exhibits that spin, bounce, roll, swoosh, tumble, and squeak. Caution to parents—a day here will likely end with a climactic post-fun meltdown. Along with the exhibits, the museum offers events and programs for children and families, all with the goal of inspiring the joy of learning and constructive play. Parking is available for free at the Mueller Town Center parking garage just north of the museum. ##### **George Washington Carver Museum and Cultural Center** The **George Washington Carver Museum and Cultural Center** (1165 Angelina St., 512/974-4926, 10am-6pm Mon.-Thurs., 10am-5pm Fri.-Sat., free) is celebrated as the first black neighborhood museum in Texas. Exhibits include the country's only permanent exhibit dedicated to the history and development of Juneteenth, the Texas-born day of jubilee celebrating the end of slavery. An in-depth exhibit explores the lives of 10 African-American families who have contributed to Austin and Central Texas history. #### **OLD NORTH AUSTIN** ##### **Neill-Cochran House Museum** Austin's 19th-century high-society lifestyle has been petrified and is on display at the **Neill-Cochran House Museum** (2310 San Gabriel, 512/478-2335, www.nchmuseum.org, 1pm-4pm Tues.-Fri., $10 adults, $8 seniors, $5 college students and youth 12-18, children under 12 free). This old mansion built by famed Austin architect Abner Cook in Greek Revival style offers an interesting glimpse into the past. All visitors are guided through the house by NCHM staff or a trained docent (allow 45 minutes). Here you can see just how stuffy life was "back in the day," with Victorian doilies to hand wash and collars to starch. The styles of interior decoration represented here are colonial, empire, rococo revival, and Victorian. Over the years this house has functioned as a Civil War hospital and an institute for the blind. **Abner Cook: Master Builder** When exploring Austin you will undoubtedly notice the many elegant historic homes—or should I say mansions—that summon images of a more genteel era. The person behind some of these architectural masterpieces is the master builder Abner Cook (1814-1884). In 1837, the young Cook arrived in the small city of Austin, where he worked as a carpenter building coffins and furniture and later log cabins. Eventually Cook worked his way to the top and became Austin's foremost master builder and architect, and he was a pioneer of the Greek Revival style in Texas architecture. During his career he was involved in many projects that shaped the overall aesthetic of the city, such as homes, businesses, buildings on the University of Texas campus, a state mental hospital, a state penitentiary, and the state capitol building. Many of Cook's buildings have been destroyed to make way for more modern development, but some of his elaborate and stately mansions of the late 1800s can still be seen around town. These magnificent homes are exquisite examples of his popular Greek Revival style and bear his unique trademarks, such as the X-and-stick balustrade motif on exterior rails and Greek Ionic details. Abner Cook houses that have survived are the **Woodlawn House,** also known as Pease Mansion (6 Niles Rd.); the **Swisher-Scott House** (2408 Sweetbrush); the **West Hill House** (1703 West Ave.); the **Hotchkiss-Graham House** (2605 Salado St.); the **Donnan-Hill House** (2528 Tanglewood); the **Neill-Cochran House** (2310 San Gabriel), which is open to the public; the **Old Depot Hotel** (504 E. 5th St., now Carmelo's Italian Restaurant); and the **Governor's Mansion** (1010 Colorado St.). ### **Live Music and Nightlife** At night Austin lights up like a pinball machine. Downtown transitions from all business and politics to neon lights, live music, techno-thumping bars, dressed-up folks, honky-tonks, comedy clubs, fine dining, curbside pizza, and drunks young and old doing the bar crawl. All of this happening at one time and place can provide a vibrant backdrop to one's night. Under Austin's city glow you can have an evening that consists of eating at an expensive restaurant, catching a performance of a local singer-songwriter, and having a drink at a swank bar. Or you can eat a slice of pizza on a street corner and catch a metal band, do some dive bar-hopping, and wake up at 11am the following day on a stranger's kitchen floor. There are a few areas with the greatest concentration of action. In downtown there's famous (becoming infamous) **6th Street,** which is Austin's version of New Orleans's Bourbon Street. It features bars, live music venues, tattoo parlors, and some tourist shops (traps). This is largely dominated by UT college students, tourists, and crazies looking for craziness. On Thursday, Friday, and Saturday nights around 10pm, the Austin police department closes off the street. The scene on 6th Street can get pretty rowdy, especially after midnight. For a less sketchy scene downtown, where you'll find men who pluck their eyebrows and women who prefer tapas to an entrée, there's the **Warehouse District** on West 4th Street and the bars on West 6th Street. Historically, the Warehouse District was the brothel district, but today the scene is a bit more upscale, with classy bars, dance clubs, live music, gay bars, and pubs. These are all in converted warehouses with entrances that have steps and concrete landings that are uneven and hard to navigate after you've had a few drinks. The area where new music can be found is the **Red River District.** Just a few years ago this area was the dead tooth of downtown—now it's a bustling center for the more alternative and indie forms of live music. Some of the best live music venues in town are all within a two-block radius, which makes sampling different bands and drinks easy and fun. The scene here is mostly rockers, punks, and hipsters. Don't let the tattooed folks wearing black and sporting extreme piercings deter you, as the scene here is generally friendly and fun. **Must-See Local Musicians** The city of Austin prides itself on being the Live Music Capital of the World, and for a very good reason: It _is_ the live music capital of the world. There are more venues, musicians, and music lovers here than anywhere else outside of heaven. There are over 2,000 recording acts and a total of almost 9,000 musicians in all genres of music, but I've narrowed the list down to the top artists and bands that live and perform here. If you see any of the following names in the music section of the _Austin Chronicle,_ be sure to check them out. • **And You Will Know Us by the Trail of Dead:** This punk-influenced alternative rock band got its start by playing Emo's as much as possible, but somehow they became more popular in the rest of the country before they really got recognized in Austin. Occasionally they still play in front of a sold-out crowd at Emo's and other venues around town. • **Asleep at the Wheel:** Austinites, and all Texans for that matter, have always tapped their toes to the traditional country music pumped out by Asleep at the Wheel. This prolific Grammy Award-winning band has survived the terrors of Nashville by sticking to their cause of keeping western swing alive and kicking. If you can catch them at Gruene Hall in the Hill Country you are sure to enter western nirvana, and the only way to get there is by dancing. • **Band of Heathens:** This group is a true Austin singer-songwriter collective. Their unique performances feature all three singer-songwriters up front. These great vocalists can do soul, blues, rock, and country, and they deliver it all with heart. Catch them any time they play at one of the many venues around town. • **Del Castillo:** A renowned Austin Latin group fronted by Rick del Castillo and Mark del Castillo, Del Castillo is a high-energy band that blends many styles, including flamenco, rock, Latin, and world music. From their live performance you will never forget the dueling Latin guitar solos. Del Castillo has performed with many legendary acts, such as Don Henley and Willie Nelson. • **Dixie Chicks:** Everyone has heard of the popular but controversial self-made all-girl country band the Dixie Chicks. Although they generally have to stick to stadiums, they occasionally surface around town. • **Joe Ely:** Ely, a country, bluegrass, and rock 'n' roll artist, grew up in Lubbock. He later relocated to Austin to pursue his musical aspirations. Over his career, Ely has been in numerous bands in a variety of genres. He has performed and toured with Chuck Berry, Carl Perkins, Merle Haggard, Bruce Springsteen, and The Clash. • **Alejandro Escovedo:** Musicians the world 'round are huge fans of Escovedo, but somehow this remarkable singer-songwriter never lands a hit song on the radio. In his case, this is a good thing. As a Hispanic coming out of the late-'70s punk rock movement, Escovedo blends what he knows into a fascinating, moving arrangement of words, melodies, and rhythms that reach all audiences. The best place to see him is at the Cactus Cafe. • **Patti Griffin:** This spectacular singer-songwriter has been deep in the background of the music industry and hasn't fully walked onto the mainstream stage for reasons unknown. She has performed with and written songs for some of today's top folk and country acts, such as the Dixie Chicks, Lucinda Williams, and Emmylou Harris. • **Iron & Wine:** Soft-spoken alternative folk master Sam Beam lives in the beautiful Texas Hill Country. This Sub Pop artist doesn't perform live that often, so if his name is listed in the _Chronicle_ you'd best buy your tickets ASAP. • **James McMurtry:** Blue-collar singer-songwriter James McMurtry is a staple around town. He's perpetually performing, and people are perpetually enamored by his unique folk- and blues-based songs that talk about real down-home people in tough real-life situations. • **Willie Nelson:** Country music legend Willie Nelson is one of the hardest-working artists in Texas. He performs all over Austin and the Hill Country. Seeing him perform here is seeing him perform in his own backyard, and his comfort on local stages really comes through. In fact, despite his age he cuts loose and takes his audience on a ride through his standards, coupled with lots of country classics, all faster and juiced up. • **Bruce Robison:** The tradition of country ballads of love gone wrong is carried on by Bruce Robison. But don't expect a Stetson and boots on Bruce because he's more of a quiet, contemplative, urban guy who resembles John Cusack. Catch him at the Broken Spoke and other Hill Country venues. • **Charlie Robison:** Contemporary country that I like to call tractor pop is provided by Charlie Robison. He's a strong country staple for Central Texas, and he performs all over the state and the United States. The best place to see him live is at Gruene Hall in the Hill Country. • **Bob Schneider:** An artist who has the power and charisma to reach fans of many music genres is Bob Schneider. He's a skillful songwriter who puts on a spectacular show and somehow comes across as honest in his search for mainstream appeal. His folksy rock approach sounds like Neil Young meets Beck. • **Charlie Sexton:** Not many Austinites have graced the cover of _Rolling Stone_ in their teens, but Charlie Sexton is one of those few. This prodigy had a hit in the 1980s with "Beat's So Lonely," which was an MTV favorite, and then he seemed to vanish. For most of the '90s and into the 21st century he was a studio musician and songwriter for some top artists, such as Bob Dylan. In 2005 Charlie released a folk/alternative record to much acclaim. • **Spoon:** Alternative rock band Spoon is Austin's music scene personified. They've been around for years and years performing and recording records that fly beneath the radar. It wasn't until 2005 that they finally broke into the mainstream, and this didn't break their original sound as mainstream success often does. They pop up around town for a low-key show from time to time. • **The Sword:** Heavy metal and stoner rock has found its way to Austin with the rise of The Sword. These young, semi-nerdy, fully cool kids blast audiences with riff after riff—the kind that made Black Sabbath scary. If you catch them at Emo's be sure to wad up some toilet paper in your ears unless you enjoy tinnitus. • **Jimmie Vaughan:** Grammy Award winner and brother of Stevie Ray Vaughan, Jimmie has become a blues and rockabilly legend in his own right. He plays around town all the time. The best venue to catch his performance is the Continental Club on South Congress. Tickets can be costly, but it's worth it to see a legend perform. • **Stevie Ray Vaughan:** This American blues guitar legend passed away back in 1990, but I'm confident his ghost is cruising all around Austin's music venues. You can pay homage to one of the most influential electric blues musicians in history by visiting his life-size statue on Lady Bird Lake. • **Dale Watson:** Country music has been carefully preserved by local legend Dale Watson. When Nashville gave the boot to country legends such as Johnny Cash and Willie Nelson and started pumping out atrocious pop sounds, Dale dug deep into the classics for inspiration. Dale is best enjoyed while sipping on a Lone Star at the Broken Spoke or the Little Longhorn Saloon. Outside of downtown there are a couple areas where you'll find action. First there's **South Congress Avenue.** It offers a few clubs, some local bars, and some restaurants featuring live music. Far away from the young angst of downtown, this area is a safe bet for a low-key and predictable night on the town. Austin's newer scene, being pioneered by hipsters and do-it-yourselfers, is **East Austin.** This area, just on the other side of the freeway from 6th Street, is where all the artsy musician locals like to hang out. Strewn about on what has historically been considered the sketchy side of town you'll find alluring dive bars, food trucks, music venues, and unusual shacks and backyard patios to explore. Whatever your preference is for a night on the town in Austin, before stepping out the door, grab a free copy of the _Austin Chronicle_ (issued every Thursday) and check out what's happening in the events section. With the _Chronicle,_ coupled with the listings here, tailor an evening that best suits you, or just wander around and let the night be a "Choose Your Own Adventure" type of experience. #### **LIVE MUSIC** Austin is compulsive about music. After all, it's simply and indisputably the best U.S. city for live music, and has the distinguished honor of being the Live Music Capital of the World. The town is forever inundated with touring national acts, local favorites, and unknowns crawling out of the woodwork seeking their 15 minutes of expression. Venues, clubs, and bars all across town have something going on every night of the week. Live music is so pervasive here that you'll find it in unusual places, such as clothing stores, supermarkets (Central Market), the airport, and even the post office. I've noticed many venues offering two stages, one smaller stage inside and a bigger stage outside for larger national acts. This makes sampling music a blast. Although venues are everywhere, the greatest concentration of music is downtown. No matter where you stand in the downtown area the sounds of live music can be heard, merging in stereophonic cacophony, and the sound is sweet. The concentration gets thick on 6th Street and Red River, where you can stand on any corner and hear blues, pop, and heavy metal all at once. Thanks to Austin's multifarious musical palate the venues and acts are diverse. There's a thriving scene here for absolutely every kind of musical taste. It's hard to say how live music got its footing in Austin and how it has become so extraordinary over the years. But, from Willie Nelson to Janis Joplin to _Austin City Limits,_ from Stevie Ray Vaughan to Alejandro Escovedo to Spoon, Austin has been greatly blessed in its calling to live music greatness. With this calling comes great responsibility, and Austinites take this seriously by religiously supporting local music. It's not uncommon for someone to catch a live act every night of the week and during the day maintain a "normal" life at the office. Tickets for most concerts and venues can be purchased at **Waterloo Records** (600 N. Lamar Blvd., 512/474-2500) or online at venue websites. Also, tickets can be purchased online at **Front Gate Tickets** (www.frontgatetickets.com) or **Ticketmaster** (www.ticketmaster.com). Tickets purchased online are often cheaper than at the venue. For smaller venues tickets are sold only at the door or at venue websites. ##### **Big Venues** The term "big" is relative when it comes to venues. The following listings are venues I consider to be "big" because of their size and seating capacity, and/or "big" because they feature big-name national acts. Tickets can range from $15 to $55 depending on the act or lineup and the night. **Antone's** (2015 E. Riverside Dr., 512/800-4628, www.antonesnightclub.com) has been Texas's outlet for the blues for decades. They've expanded their repertoire to include pop, rock, and indie, bringing in some major national acts. This is the best place to catch Austin's own Jimmie Vaughan. The club's founder, Cliff Antone, had his highs and lows, operating the venue for 30 years until his death in 2006. Highs included receiving an award from the National Blues Foundation for his contribution to the blues, and lows included doing prison time for drugs. The record store on Guadalupe Street with the same name is owned by the venue. Scene: national acts, local legends, blues, rock, pop, and country. **Emo's** (2015 E. Riverside Dr., 512/800-4628, www.emosaustin.com) is the town's premier punk, metal, stoner, and indie venue and has been for a long time. You can't use the word "alternative" to describe this scene or the music, as this term is sacrilegious, and people will smirk. Spoon and Trail of Dead got their start at Emo's, and even Johnny Cash has played here (at the original location). Parking can be tricky, so come a little early. Scene: punk, heavy metal, indie. **Frank Erwin Center** (1701 Red River St., 512/471-7744, www.uterwincenter.com) is Austin's stadium for mega entertainment. The coliseum can seat up to 18,000 people, so don't expect an intimate show. The center hosts acts like George Strait, Metallica, and Lady Gaga, and has also hosted the Dalai Lama and the Ringling Bros. and Barnum & Bailey circus. This is also the home of UT sports. Scene: mega entertainment of all kinds. **The Moody Theater** (310 Willie Nelson Blvd., 512/225-7999 venue, 877/435-9849 tickets, www.acl-live.com) is the new home of the famous _Austin City Limits_ stage. Located in the 2nd Street district at the W Hotel, this live music venue and studio has made ACL accessible to the masses. The Moody Theater is a state-of-the-art facility with a capacity of 2,700-plus people. Scene: rock, pop, alternative, country, folk, world. **Stubb's Bar-B-Q** (801 Red River St., 512/480-8341, www.stubbsaustin.com) is the place to get famous barbecue sauce and famous national acts. Housed in a historic limestone building, Stubb's is where the hip parties go down during SXSW. There's a small indoor stage and a big outdoor stage in the backyard. Scene: national acts, local acts, rock, alternative. ##### **Small Venues** There are so many smaller venues in town that it's not practical to give them all a nod here, so I've distilled the list to the very best. Generally doors open for these venues sometime around 8pm-9pm, and there's almost always a cover charge that is somewhere between $5 and $20. **Beerland Texas** (711½ Red River St., 512/479-7625, www.beerlandtexas.com) is one of the older rock venues in the Red River District. The proprietors best describe their own place by saying, "Rock & roll club seeks bands, fans, and hangers-on for all-out orgy of loud music and cheap beer." Also here are arcade games and pool. Scene: rock. **Broken Spoke** (3201 S. Lamar Blvd., 512/442-6189, www.brokenspokeaustintx.com) really should be a sight as well as a venue. This remarkable local institution will blow your Stetson off when you walk through the door. Remember John Travolta in _Urban Cowboy_? Well forget it, because the Broken Spoke is the real deal. First-timers have a hard time blending in because they end up standing there with their jaws hanging. This authentic honky-tonk is an original Texas dance hall where people still come to dance to live country bands. A front-room restaurant serves up home cooking, but the real reason for being here is the humble dance floor, under a low ceiling that I swear is going to cave in in the near future. Finally there's the makeshift museum, containing dusty artifacts from country music legends and photos of the proprietor with famous folks. No one ever seems to go in there, except for newcomers and nerds. Word for the nerd: If the lady bartender asks, "What can I get ya, sugar?" she's not asking you if you want sugar. Scene: country, dancing. **Cactus Cafe** (Texas Union on the UT campus, 2247 Guadalupe St., 512/475-6515) is the premier intimate venue for all things unplugged (nowadays everything's actually semi-plugged). Big-name acoustic, singer-songwriter, country, and folk acts have graced the small corner stage for over 70 years. Among them are Janis Joplin, Bob Dylan, Lyle Lovett, Bill Monroe, Ralph Stanley, Ani DiFranco, and Sean Lennon. The space is small, upscale, and outfitted with a full bar in the back. People tend to dress up a bit for shows at the Cactus. It's a safe bet that any show here is worth seeing. Scene: unplugged, singer-songwriter, folk, Americana, bluegrass, and jazz. **Cedar Street Courtyard** (208 W. 4th St., 512/495-9669), in the Warehouse District, always has a groove on. The space is like none other in town: It's an open courtyard flanked by basement bars that have a party-in-the-dungeon vibe. Music on the stage is always groovy and upbeat, and dancing is unavoidable. Scene: jazz, funk, tango, groove. **Continental Club** (1315 S. Congress Ave., 512/441-2444, www.continentalclub.com) is Austin's legendary retro hookup that has been around since the 1950s. With a steady lineup of regular local musicians as well as touring acts in a throwback atmosphere, the Continental is another venue where you're sure to catch something good on any given night. Patrons love showing up on their hogs or in their classic cars, looking like a million bucks. Regular acts include Dale Watson and Jon Dee Graham. Scene: country, blues, rockabilly, rock, singer-songwriter. The best way to experience live jazz music is in the basement of the **Elephant Room** (315 Congress Ave., 512/473-2279, www.elephantroom.com). Jazz lovers come from all over to descend into this unique environment and sink back in a chair for a couple hours of toe tapping. The Elephant Room has a full bar with more than 20 drafts and wine by the glass. Scene: jazz, big band, swing, smooth. **Elysium** (705 Red River St., 512/478-8385, www.elysiumonline.net) is the venue for goth and industrial music. Here the unspoken dress code is black, makeup, and chains, and the attitude is depressed and sullen. For the most part this is a dance club with a beat going on, but there's also live music. Scene: goth/industrial dance club. **Empire Control Room** (606 E. 7th St., www.empireatx.com) is a punk/rocker/DIY scene that's gaining a foothold in the Red River District. Like Emo's and the Mohawk, Empire is the place to be during SXSW or Austin Free Week. Here you'll find three stages and a bar that's often so packed you can't see the bartender. There's a loud PA system, and bands push it to the limit. Toilet paper wadded up and stuffed in the ear won't save your hearing because the sound will travel straight through your skull. Be warned, the bathrooms are usually disgusting. Scene: punk, indie rock, techno, stoner rock. **Flamingo Cantina** (515 E. 6th St., 512/494-9336, www.flamingocantina.com) is the premier reggae venue in town. This 18-and-up roots venue has big-name acts from all over the United States and from "the islands." Scene: reggae, hip-hop, funk. **Hole in the Wall** (2538 Guadalupe St., 512/477-4747, www.holeinthewallaustin.com) is a historic little venue on the Drag that puts on all sorts of music in an average bar atmosphere. As for history, Stevie Ray Vaughan played here. The $1 beer special on Monday is crucial for the students. Scene: alternative rock, country, pop, singer-songwriter, bar bands. If Dracula lived in a loft in Manhattan it would probably look a lot like **The Mohawk** (912 Red River St., 512/666-0877, www.mohawkaustin.com). This space has been through many incarnations over the years—from club after club, to swank bar, to full-on cocaine den. This time around the Mohawk is a micro-scene unto itself. One of Austin's bustling two-stage venues, this is the place to let your hair down and head bang, to shoe gaze, and to drink. Catch touring bands such as Bad Brains, Sleep, or No Name, or discover popular local indie acts such as The Authors or Stereo Is a Lie. Scene: punk, metal, indie, rock. **Nightlife Tips** Before embarking on a night on the town in Austin there are a few things you should take into consideration. • Be sure to always have your ID with you. Clubs, venues, and bars have very strict ID policies, and you will get carded no matter what. If you don't have a valid ID you will definitely be barred from having a great night out in Austin. • Drink lots of water in the summer months because you will quickly find yourself dehydrated, especially if you are seeing performances in the hot outdoors and drinking alcohol at the same time. All clubs, venues, and bars are eager to hand out water, and often you can find a self-serve water bucket somewhere. • Have enough cash in your pocket before you start out. ATMs at bars and on the street charge a bundle for cash withdrawal. However, if you are caught in a jam, my favorite ATM is the one sticking out of an old wood fence at Stubb's Bar-B-Q on Red River Street. It charges a big fee, but it's entertaining pulling money out of a fence. • If you are underage, be aware that bartenders, bouncers, and door dudes aren't fools. Consider the experience of one of George W. Bush's daughters, who was caught drinking at Chuy's bar. • If you're merrily drinking at bars and clubs, don't get bent out of shape if a bartender cuts you off and won't give you another drink. According to Texas state law, bartenders are liable for those who stagger out of bars, and liable for their actions. They are very cautious about this and are looking out for the best interest of everyone. • Don't drink and drive, and watch out for drunk drivers. It's not uncommon to see someone completely wasted struggling to find the keyhole in a car door. **The Parish** (214 E. 6th St. upstairs, www.theparishroom.com) is one of the newer live venues on the 6th Street scene. The upstairs venue caters primarily to the punk/alternative scene, and often features the type of bands that take themselves too seriously. If you are a band playing here be sure to have roadies, because you have to carry everything up a flight of stairs. Scene: indie, punk, hard rock. **The Sidewinder** (715 Red River St., 512/474-1084, www.thesidewinderaustin.com) is one of the tried-and-true venues in the Red River District. Formerly called Red Eyed Fly, this place has two stages and a jukebox featuring Jane's Addiction, Son Volt, Tool, Fugazi, Johnny Cash, The Shins, and Queens of the Stone Age. Scene: punk, metal, indie rock. **Saxon Pub** (1320 S. Lamar Blvd., 512/448-2552, www.thesaxonpub.com) is a venue down South Lamar that's guarded by a giant knight in shining armor. The best of Austin's local musicians are found here, both enjoying music and playing it. Besides being a great venue it's also a pub complete with darts, pool, and microbrews. Scene: folk, Americana, blues, country, bluegrass, light rock. Touted as the oldest continuously running beer joint in Central Texas, **Scoot Inn** (1308 E. 4th St., 512/394-5486, www.scootinnaustin.com) is the East Side's quintessential dive bar music venue. Supposedly this shack was built in 1871 and was a place where weary pioneers would party. If someone from then visited now they might feel right at home. Patrons are sweaty, unshaven, and look like they rode in on mustangs. A full selection of Hill Country microbrew Real Ale is on tap, which is a treat, and staff are nice. Scene: rock and alternative. **Threadgill's** (301 W. Riverside Dr., 512/472-9304, www.threadgills.com) is one of Austin's venues with the most history, as the young Steve Miller, Janis Joplin, and The Doors, among many others, have played here. In fact, Threadgill's claims to have been the first outlet in town for the '60s counterculture movement. Today, you can find all sorts of acts here as well as Austin's new residents, the Neville brothers and family, who relocated here after New Orleans was flooded by Hurricane Katrina in 2005. Scene: country, rockabilly, Americana. **311 Club** (311 E. 6th St., 512/477-1630) has been the top venue for blues on 6th Street for over 20 years. This 21-and-up venue features local and national acts every night of the week in a bar atmosphere. Scene: blues, R&B, cover bands. #### **BARS AND CLUBS** Texas has many counties that are dry or partially dry, but Austin is definitely not in a dry county. There are thousands of bars here—some local dive bars with Merle Haggard on the jukebox, others ultra-swank clubs that feature DJs. The following are the best watering holes in town. The high-end multilevel lounge experience has been made perfect by **The Belmont** (305 W. 6th St., 512/476-2100). This popular joint is plush and custom, outfitted with Vegas overtones and Manhattan undertones. If Dean Martin were alive, and if he were cool enough to live in Austin, he would probably be found smoking in one of the private nooks or on the outdoor patio—slightly hammered, of course. The signature drink is the Belmontini, which features locally made Tito's vodka and pineapple juice, and live music often helps to set the tone. One of the more popular watering holes for creative people is **Cheer Up Charlie's** (900 Red River St., 512/431-2133). What started in a small building in East Austin is now housed in the former location of the defunct Club De Ville. Inside feels a lot like being at a sophisticated party in a darkroom for developing photos. The best feature here is the patio in the backyard, chiseled out of limestone cliffs. This is one of the better spaces in the Red River District for sipping and chatting with friends. Here you have a great vegan food truck, free live music, beer and wine, DJs, and an outdoor movie screen that shows everything from kung fu to cult classics. Or better yet, _The Wizard of Oz_ synched up with Pink Floyd's _The Dark Side of the Moon._ On the quieter side of downtown toward Mo-Pac/Highway 1 is **Donn's Depot** (1600 W. 5th St., 512/478-0336). This fantastic old-time bar is housed in a former train depot and a real choo-choo. The crowd is very diverse, with old folks looking for a dance as well as spry youngsters seeking a cultural experience. Live and canned music is generally jazz, big band, bluegrass, country, and porch. Donn himself has two bands that perform here. Amid all the live music is **Plush** (617 Red River St., 512/478-0099), Austin's premier DJ, mix, and hip-hop dance club. Toward the wee hours people can get a little too crazy and loose—think _Jersey Shore._ Yes, pumping beats, sexy dancing, and throwing up in the bathroom. It's always packed to the gills, so if you're claustrophobic you may freak out. If so, head to the secret chill spot in the back. If it's vacant you will be pleased to kick it in here, near to but at a safe distance from the craziness of the main dance floor. It's hard to pigeonhole **Halcyon Coffeehouse** (218 W. 4th St., 512/472-9637, www.halcyonaustin.com, 7am-2am Mon.-Thurs., 7am-3am Fri., 8am-3am Sat., 8am-2am Sun.) as anything specific. This lack of definition is what makes it one of my favorite places to hang out any night of the week. Halcyon (pronounced HAL-see-yon) is a night-owl café, a classy bar, a sophisticated art gallery, and a laid-back smoke shop all rolled into one Zig-Zag. The front half is a great café space with low-lying chairs and couches, the back is the bar with loud music thumping, and on the side is a fish bowl that contains the tobacco shop. Everywhere in this place you will find great artwork hanging on the walls and people surfing wireless Internet and socializing. If you're craving sweets, staff will bring fire to your table so you can roast marshmallows and make s'mores. **Politicians, Prostitutes, and Secret Tunnels** During the last quarter of the 19th century Austin had a blossoming red-light district on the west side of Congress Avenue, in the area now referred to as the Warehouse District. Official city documents of the time called this area the First Ward, but everyone really called it Guy Town. With several brothels, slews of hard-working prostitutes, and a client base that consisted of city council members, legislators, and businessmen, Guy Town flourished under the noses of an unsuspecting genteel society. In order to conceal the identities of the "upright citizens" that were patrons of Guy Town, many brothels had tunnels that connected to secret locations. But Guy Town wasn't just for the well-to-do; it was also a place for gamblers and outlaws, and some of Austin's dubious chapters unfolded in the streets, buildings, and tunnels of Guy Town. Only one remnant of Austin's era of prostitution can be found in town, and it's actually not in the historic area of Guy Town, but north of downtown at 1601 Guadalupe Street. This historic stone structure known as the Bertram Building (currently housing Clay Pit, the finest Indian restaurant in Austin) has a basement tunnel that historically led to a conveniently located brothel next door. If the downtown 6th Street scene is wearing on you, simply walk under the freeway to **The Liberty** (1618½ E. 6th St., 512/600-4791). Here you have an unfriendly jukebox joint with potent but cheap drinks. So why suggest this place? Because the unfriendly vibe and stiff drinks will toughen you up! The space out back with picnic tables is huge, and the East Side King food truck is here too. This food truck has a connection to famed local restaurant Uchi. Another great spot on the east side of the freeway is **Shangri'La** (1016 E. 6th St., 512/524-4291). The drinks aren't fancy but they are cheap and strong. This place is fun because it's often packed, has a great jukebox, and has pool tables. Like most joints east of the freeway, this place is generally free of college folks. Some of the bars on 6th Street are into gimmick to a degree that is stupid. Although **The Library Bar** (407 E. 6th St., 512/236-0662, www.librarybars.com) is guilty of this, it's one of the better places to hang out downtown. The library theme is cleverly integrated into the vibe, inspiring college students to visit the "library" to do homework. Under the illusion of study, the drinks are well mixed and the tone is upbeat. This place is not afraid of lighting, either. This is good because too many bars are into dark and moody environments. **Lucky Lounge** (209A W. 5th St., 512/479-7700, www.theluckylounge.com) is a trendy bar with '60s decor and occasionally good live music. If you want to lounge around, have live background music, and sip apple martinis, you're in luck at Lucky's. The crowd is primarily heterosexual singles looking to schmooze and flirt in a sophisticated way. One of the best martinis in town is at **Speakeasy** (412D Congress Ave., 512/476-8017). The entrance is in the alley, which harkens back to the Prohibition era. Suave and divine is a way of life here, with live music, a relaxed atmosphere, a brick-and-wood interior, and walls covered in vintage posters. The bar for aspiring singers is **Ego's** (510 S. Congress Ave., 512/474-7091). Tucked away in a parking garage off South Congress, Ego's always has a wild cast of vocalists, drinkers, and people-watchers who are willing to let their guard down and be silly. The combination of karaoke and dive bar is genuine here. Karaoke starts at 10pm Sunday-Thursday, 9pm Friday-Saturday. I suggest stopping by when it's hosted by Diamond Karaoke. Ego's is also home to a competitive karaoke league, Downtown Division of the National Karaoke League, on Thursday nights. **Little Woodrow's** (520 W. 6th St., 512/477-2337), on the quieter side of 6th Street, is a great place to hang out with friends for an extended stay. Sports fans will be pleased to find that there are distracting TVs everywhere, and others will enjoy the great outdoor space with picnic tables. Unlike at the dive bars and hipster hangouts in town, the beer selection is broad, so there's always something here for everyone. **Valhalla** (710 Red River St.) is a cigarette loosely hanging from the bottom lip on Red River Street. It's not cool to smile too much here, or to be exuberant. The scene is a mix of denim-overall-wearing tattooed folks, cow-punks, and hipsters. Just stand around with a drink in hand and gently bang your head to the music. The wagon-wheel bar is an interesting feature that divides the bar from the live music. ##### **Dive Bars** Have you recently been dragged through the briar patch of love? Have you lost faith in humankind because humans don't seem to be kind? Or are you just lonely and want to sit around with others who are lonely, pretending you don't want to be bothered, when you're really crying out for human contact? Austin's world-class dive bars can help you. Some of these joints have historical significance, although you would never know it from the outside—they look like they've been closed since REO Speedwagon broke up. Many of these drinking institutions are owned and operated by spry older ladies who've created their own unique cultures in their bars. For obvious reasons these places dredge up images from Nick Cave ("Jangling Jack"), Frank Sinatra ("Strangers in the Night"), and Johnny Cash ("Sunday Morning Coming Down"). Be sure to bring cold hard cash to these places because most of the following joints don't take plastic. If your inner child likes to drink, check out the age-old **Carousel Lounge** (1110 E. 52nd St., 512/452-6790). The circus theme is taken to the limits with a big pink ceramic elephant, circus murals, and a mini carousel. Jukebox joint **Deep Eddy Cabaret** (2315 Lake Austin Blvd., 512/472-0961) will make you feel at home. Here you can swim in your own head while listening to the eclectic tunes on the jukebox. We've all heard of Elvis (both Costello and Presley), but what kind of dive bar patron has heard of Edith Piaf (often confused with eat a pilaf)? The early-20th-century French singer gone heroin addict surprisingly adds a nice depressed touch to this dive bar experience. Pitchers of Lone Star are only $6, and snacks consist of hot nuts and pretzels. **Dry Creek Saloon** (4812 Mount Bonnell Rd., 512/453-9244) is one of the oldest bars in town. This rustic shack is nestled among extravagant, million-dollar homes, but I assure you that all the patrons come from elsewhere. Only a couple kinds of beer are available, so don't expect marvelous microbrews on tap. The saloon is high up Mount Bonnell Road, but don't expect some great mountain peak 'cause this is a Texas mountain, measuring in at a whopping 780 feet above sea level. This doesn't, however, diminish the fact that there's an extraordinary view from the saloon's rooftop deck. You don't have to be drunk at a Christmas party to see elves dancing over the bar, because it's always Christmas at **Lala's Lounge** (2207-09 Justin Ln., 512/453-2521). Years of cigarette smoke and liquor-stained carpets produce a marvelous smell. Just like the patrons, the Christmas tree is always lit, with presents under its branches—and the skeleton over the pool table is riding a giant beer bottle. There's hidden symbolism in all this, I'm sure. Frank Sinatra and Dean Martin provide the soundtrack for this joint. The legendary mini honky-tonk **Little Longhorn Saloon** (5434 Burnet Rd.) is a place steeped in character, booze, and bird poop. Local mother to the bar divers, Ginny Kalmbach was the owner/operator for over 30 years when she retired and sold the windowless joint to local country legend Dale Watson. Besides being known as a place to get a drink and to hear real country music (as opposed to country pop), Little Longhorn is famous for Chicken S#!t Sunday. This is when a specially designed bingo board is placed on the pool table along with a chicken in a cage. People place bets on a number, and if the chicken poops on your number you win the pot. The soundtrack is provided by a live performance by Dale Watson and his Lone Stars. **Chicken S#!t Bingo** The game of bingo, which is the ultimate game of chance and boredom, has become a lively way to spend an afternoon at **Little Longhorn Saloon** (5434 Burnet Rd.). Every Sunday night this tiny honky-tonk features an amusing game of Chicken S#!t Bingo that relies entirely on the unpredictable bowels of a chicken in a cage on a pool table. Contestants throw down hard-earned cash on a number and cheer and jeer for about an hour waiting for that special moment, while Austin's favorite country act, Dale Watson and his Lone Stars, perform and provide commentary. Free chili and hot dogs are served, along with cheap Lone Star Beer. The lucky winner can walk away with up to $100. If you want to participate in this spectacle, plan on showing up early and hanging around for a while. The band starts at 4pm and tickets go on sale at 5pm. The winner is announced when the chicken takes a dump. Don't confuse Chick S#!t Bingo with craps. If you thought poodles and heavy metal had no place being together, check out **The Aristocrat Lounge** (6507 Burnet Rd., 512/465-9468). You know you're there when you see a seemingly abandoned building with a giant mural of a poodle on the outside, which is a homage to its former name, The Poodle Dog Lounge. This place has a wacky scene of bearded hipster locals and grouchy bartenders. On one hand it seems like it's an old bar in its death throes, and then on Friday nights the place springs to life. This dive features several tall booths, pool tables, and games for those that enjoy activities while they are drinking. Just up the road is Top Notch Hamburgers, which was one of the shooting locations for the movie _Dazed and Confused._ #### **PUBS** A pub with dark nooks and crannies similar to an English pub, **Dog & Duck Pub** (2400 Webberville Rd., 512/479-0598) has 35 beers on tap, including the local Celis line, and dozens of bottled beers to choose from. The Austin Beer Club and the Homebrewing Club both meet here, which says a lot about the pub. Besides being a great place to suck down pints, Dog & Duck is a great place for the whole family. And just as in an English pub the food is greasy and is good only because it goes with beer. On St. Patrick's Day, Dog & Duck is packed. Drink specials are offered throughout the week. The Warehouse District is full of great pubs, bars, and restaurants. The pub that most successfully replicates English-pub atmosphere is **The Draught House** (4112 Medical Pkwy., 512/452-6258, www.draughthouse.com). Dark spaces, a good selection of microbrews and commercial beers, and a mellow atmosphere make this one of the best pubs in town. It has its own Old World-style brewhouse where they cook up some excellent beers using traditional recipes. Ask for a taste before ordering one of their micros. Every day of the week they offer great deals that draw crowds. For instance, on Wednesdays if you buy a pint you keep the glass, and Saturdays there's free bratwurst, and Tuesdays all pints are $3. The pub lets people take their brews outside, which has spawned a unique lawn-chair-parking-lot social scene. After dark don't drive in with your headlights on, as this will elicit the evil eye from patrons. **Fado** (214 W. 4th St., 512/457-0172) in the Warehouse District is hailed as one of the most popular Irish pubs in town. Guinness may flow in rivers here, but that doesn't make it Irish, or even a pub for that matter. The interior is faux Irish pub, featuring four different motifs: Victorian Dublin, the Gaelic Pub, the Traditional Pub, and the Irish Country Cottage Pub. You might expect to trip over a faux "Irish" sheep as you walk to the bathroom. However, this doesn't diminish Fado's popularity and the fact that it's consistently hopping and always packed after dark. **The Ginger Man** (301 Lavaca St., 512/473-8801) is another one of my favorite pubs in town. Knowledgeable staff serve up bottles and pint glasses of brew produced at local breweries, as well as the ones you're most familiar with. This is the place downtown with the largest selection of beer on tap. Last I heard the number was around 82. No matter where you sit—at the booths inside or on the outside patio—Ginger Man is a comfortable place to hang out with family or friends, or when you're all alone. Legacy and history make **Scholz Garten** (1607 San Jacinto, 512/474-1958) Austin's one and only _biergarten._ Established in 1866 over an old boardinghouse by a German immigrant, Scholz became a cultural center with beer as the communal glue. Scholz is still a cultural center, and the beer still flows. Along with being one of Texas's oldest continuously operated businesses, Scholz also has the distinction of being one of the top 25 best sports bars in the United States according to a _Sports Illustrated_ article. True to the German _biergarten,_ Scholz offers schnitzels, along with American fare. Out back is a huge space with a stage for live music and picnic tables, which makes this a grand place for big crowds of family and friends to gather. A great place to have a beer under a covered outdoor patio perched on the side of a busy South Austin street is **Black Sheep Lodge** (2108 S. Lamar Blvd., 512/707-2744). As the name implies, this place is for the weird ones of Austin, which I suppose is most people in this town. Somehow they pull off an old lodge-style atmosphere in a tiny 1970s strip mall. This description may sound odd, but I promise, the place is a gem. Local beer on tap, good American pub-style food, $2 "white trash cans," and hefty picnic tables offer tons of character. Lastly, the place is South Austin's best place to watch the game. Honestly, it's so comfortable that it's easy to waste away your whole evening here. #### **GAY AND LESBIAN** You may be thinking, "Austin is in Texas. There can't be a gay scene!" Well, all you have to do is close your eyes, click your heels, and pretend you're not in Texas, and voilà—a thriving gay and lesbian scene is before your eyes. Austin's propensity for open-mindedness has allowed lots of room for a unique gay scene that is completely unrivaled—at least in Texas. Where else in the world can you see a room of cowboys in Stetsons two-step dancing with each other? Nowhere, my friends! The North Austin neighborhood is home to a sophisticated sports bar in **'Bout Time II** (6607 N. I-35, 512/419-9192, www.bouttime2.com). Here you can play volleyball, drink draft beers, and enjoy the company of friendly, good-humored bartenders. Want a safe and friendly place to be a big bear of a man and dance without a shirt to music spun by DJs? Make your way down to Austin's premier gay bar, **The Iron Bear** (121 W 8th St., 512/482-8993). Not everyone who comes here sports a beard or a 'stache, but it's definitely on tap. The folks here are friendly and all are welcome. The gay men's nightclub is **Oilcan Harry's** (211 W. 4th St., 512/320-8823, www.oilcanharrys.com). This Warehouse District staple has lots of attitude Thursday-Sunday, from DJs spinning dance hits to the Malebox. The patio area is a great place to meet your mate or hang with your mates. Check out the website for drink specials and a calendar of events. Also in the Warehouse District is the lounge bar **Rain** (217 W. 4th St., 512/494-1150). It's a classy martini joint with a disco and snooty bartenders. Some nights there's dancing and some nights live music. Happy hour is every night of the week. ### **Entertainment and Events** There's much more besides live music going on in Austin. After all, this is a world-class city with opera, symphony, ballet, and roller derby. Tickets for most concerts and events can be purchased at **Waterloo Records** (600 N. Lamar Blvd., 512/474-2500) or online at **Front Gate Tickets** (www.frontgatetickets.com) or **Ticketmaster** (www.ticketmaster.com). The outlet for theater, music, and dance tickets is **Now Playing Austin** (512/247-2531, www.nowplayingaustin.com). Tickets can also be purchased at the venues depending upon availability, but purchasing online is often cheaper. #### **THEATERS AND EVENTS CENTERS** The City of Austin's Convention Center Department operates two massive facilities that provide space for some of the area's biggest indoor events. The bigger space is the **Austin Convention Center** (500 E. Cesar Chavez St., 512/404-4000), and the smaller space is **Palmer Events Center** (900 Barton Springs Rd., 512/404-4500). Both host a wide variety of events such as conventions, consumer shows, conferences, roller derby, concerts, public dances, and trade shows. For a comprehensive calendar of events for both venues check out www.austinconventioncenter.com. **Bass Concert Hall** (23rd St. at 2350 Robert Dedman Dr. on the UT campus, 512/471-2787 or 800/687-6010 for ticket information) is the largest space in UT's Performing Arts Center. This venue has the best acoustics in town, and although it's big, you don't feel far from the stage even in the back seats. Here's where most of the classical and dance performances take place, including touring Broadway acts, and on occasion big stars such as Tony Bennett take the stage. The UT campus parking lots on Manor Avenue and San Jacinto Street are the most convenient places to park. If you are driving on I-35 and wonder what the gigantic cylinder that resembles the spaceship from _Close Encounters of the Third Kind_ is, it's the **Frank Erwin Center** (1701 Red River St., 512/471-7744). This megavenue hosts UT sports and big-name performers, such as Metallica, Lady Gaga, George Strait, and the Harlem Globetrotters. Parking can be downright depressing during a major event; there are a few garages in the area (San Jacinto St.), but don't count on there being a space for you. Austin's glorious venue for the higher arts is **The Long Center** (701 W. Riverside Dr., 512/474-5665, www.thelongcenter.org). This classy facility for cross-cultural classics has events ranging from opera to modern performance arts, making the Long Center the premier venue for big and bold acts. Although the performances inside can ennoble, the grand promenades outside, which offer breathtaking views of Lady Bird Lake and the downtown skyline, are just as inspiring. Also, there's not a bad seat in the house. On the outskirts of town is the beautiful **One World Theatre** (7701 Bee Caves Rd., 512/330-9500, www.oneworldtheatre.org). This is a favorite for world-class performers in all genres of music. Here you can see the Cowboy Junkies, the Doobie Brothers, Ricky Skaggs, George Winston, and world music and dance. The theater is housed in one of the most famous green/eco-friendly buildings in the area, designed by Marley Porter, and proves that comfort and world-class entertainment can take place without impacting the environment too much. Parking is available. **Paramount Theatre** (713 Congress Ave., 512/472-5470, www.austintheatre.org), in the center of downtown near the capitol, is a beautiful historic theater that hasn't changed much since World War I. It still hosts some of the town's best shows, offering a wide variety of entertainment, such as country, folk, jazz, and classical music; comedy shows; dance; spoken word; and theater. This is also the place to see classic movies and random cult classics on the big screen. The art deco interior, ornate ceilings, and original red curtain from the early 1900s make for a great environment in which to be entertained. Downtown garage parking is available. Paramount Theatre is one of Austin's oldest venues. Wonder where John Tesh performs when in Austin? **Riverbend Centre** (4214 N. Capital of Texas Hwy., 512/327-9416, www.riverbendcentre.com) on the edge of town hosts all sorts of events, including Austin Symphony performances such as the Christmas Sing-A-Long, world music, and entertainment. The center is in a beautiful spot, and the facility is a stunning limestone-and-wood structure that makes performances here a treat. **The State Theatre** (719 Congress Ave., 512/472-5143, www.austintheatre.org), next door to the Paramount, primarily offers theater. This is the home of the State Theatre Company, which provides the community with high-quality plays September-June. Wine, beer, and other beverages are sold in the lobby and are allowed in the theater, which makes for a great experience. Downtown garage parking is available. **Zachary Scott Theatre Center** (1510 Toomey Rd., 512/476-0541, www.zachscott.com) is Central Texas's oldest and most popular residential theater. Here audiences are captivated by some of the best plays and musicals put on in the state. The season runs September-August, offering about eight performances by an award-winning cast. Parking is available. **Circuit of the Americas** (9201 Circuit of the Americas Blvd., <http://circuitoftheamericas.com>) is one of Austin's megavenues. With the installation of the Formula 1 racetrack came this ginormous outdoor venue where rock bands perform and large-scale performance art takes place. In 2014 the X Games were held here. #### **PERFORMING ARTS** Austin may not have a world-renowned performing-arts scene, but that is bound to change in the future as the community's various companies, troupes, and organizations keep putting on world-class performances. Austin's young opera scene is quickly gaining a footing thanks to **Austin Opera** (512/472-5992 or 800/316-7372, www.austinopera.org). This remarkable troupe is pushing the envelope with avant-garde versions of Mozart's _Don Giovanni,_ more traditional expressions of Verdi's _Il Trovatore,_ and modern operas such as _Dead Man Walking._ All operas are held at the Long Center on Lady Bird Lake (701 W. Riverside Dr., www.thelongcenter.org). Tickets range $15-100 depending on the seat and the day of the week. Tickets can be purchased by phone or at the box office (901 Barton Springs Rd.). **Austin Symphony** (512/476-6064, www.austinsymphony.org) is keeping classical music alive and well in Austin. Throughout the year the symphony has performances and series with a wide range of interests. They offer the Classical Series, which is strictly classical music performed at Bass Concert Hall on the UT campus, and the Pops Series, which is a fun and eclectic combination of arrangements in conjunction with contemporary artists at Riverbend Centre and Palmer Events Center. For the whole family there's the Family Series, which includes the Halloween Children's Concert at Paramount Theatre and a Family Concert in June at Symphony Square Amphitheatre. Finally, there are the ever-popular Holiday Concerts, including Handel's _Messiah_ in December and the July 4th Concert and Fireworks at Zilker Park, which is probably the most popular symphonic event of the year. Tickets range from free to $42 depending on the event and the venue. Proving its wide range of cultural interests, Austin also has **Ballet Austin** (501 W. 3rd St., 512/476-2163, www.balletaustin.org). The _Washington Post_ proclaims Ballet Austin "one of the nation's best-kept secrets." Productions include staples such as _The Nutcracker,_ but you can also catch more innovative productions as well. Most of the bigger events take place at Bass Concert Hall on the UT campus, and smaller events take place at the Paramount Theatre. #### **CINEMAS** ##### S **Alamo Drafthouse Cinema** The place in town where you can get dinner, draft beers, and a movie all under one roof is **Alamo Drafthouse Cinema** (320 E. 6th St., 512/861-7020, 1120 S. Lamar Blvd., 512/861-7040, 2700 W. Anderson Ln., 512/861-7030, www.drafthouse.com). What used to be Austin's great secret is now public info, as even _Bon Appétit_ has said, "The Drafthouse empire is the pinnacle of the movie/food experience." This legendary independently owned "empire" offers the usual blockbuster Hollywood movies complete with explosions and drama, as well screenings of cult classics. The Alamo's schedule also has some off-the-wall stuff, such as the Michael Jackson Sing-Along or a viewing of _Fast Times at Ridgemont High_ with a special guest appearance by the pizza delivery boy. Seating begins 45 minutes before screening, which is just enough time to order food and drinks and settle in. The theater has a clever system of writing down requests to keep the food and beer coming during the film with little distraction. Plan spending at least 3 hours and be sure show up at least 40 minutes early to order food. Also, be sure to purchase tickets well in advance as seats usually sell out during busy times. Check out the website for schedule and locations. Alamo Drafthouse Cinema ##### **Other Cinemas** Austin's only IMAX theater is the **IMAX Theatre** at the Bullock Texas State History Museum (1800 N. Congress Ave., 512/936-4649 or 866/369-7108, www.thestoryoftexas.com). Unlike many IMAX theaters, this one is equipped with an IMAX projector that has both 2-D and 3-D capabilities. Tickets range from $17 to $14. If you plan on visiting the Bullock Texas State History Museum, you might consider buying a package that includes tickets to both the museum and the IMAX theater. The **Paramount Theatre** (713 Congress Ave., 512/472-5470, www.austintheatre.org) is the venue in town that screens classic and cult classic movies. In the comfort of the art deco theater you could catch a screening of _Gone with the Wind,_ take in a stand-up comedy act by Penn and Teller, or see Chris Isaak perform live. Tickets are on sale at the box office in front of the theater and or online at tickets.austintheatre.org. Ticket prices vary. #### **COMEDY CLUBS** Austin's comedy district consists of two venues on the corner of 6th and Red River Streets. Life offers so much to laugh at, and **Esther's Follies** (525 E. 6th St., 512/320-0553, www.esthersfollies.com) mixes it up, boils it all down, and flings it in the face of the audience. Named after Esther Williams, the famed actress and water ballet pioneer whose career sank like a stone in the 1960s, this comedy troupe is composed of a wide variety of clever folks from the community. Esther's dishes out dangerously funny satire, spoofs, and monologues bedecked with costumes, clever wit, and cunning. Shows are held 8pm-midnight Thursday-Saturday. Tickets cost $20 for open seating and $25 for special reserved seating. A $2 discount is offered for students and seniors. Next door to Esther's is Austin's stand-up and open-mic comedy club, **The Velveeta Room** (512 E. 6th St., 512/469-9116, www.thevelveetaroom.com). Local and visiting comics take the stage here and showcase their stuff. This is definitely not for the kiddies. Admission is $10. #### **OTHER ENTERTAINMENT** Miniature golf enthusiasts will enjoy putting around at **Peter Pan Mini-Golf** (1207 Barton Springs Rd., 512/472-1033, call for hours). Founded in 1948, this small course on a hill overlooking the world's great fast-food chains is a great place to battle pirates, the skull bunny, and a dinosaur, all with the mighty putter. Considering the age of this institution, the course and holes are in surprisingly decent shape. Before or after golfing here, instead of eating at one of the fast-food joints go up Barton Springs Road to Green Mesquite or Shady Grove restaurants. A friend once said to me, "If you want to take the pulse of America, put your finger on the artery of any bowling alley in the nation. Bowling alleys are a microcosm of the whole US-of-A." If that's true, then the country is in a strange state of affairs. Shoe- and ball-sharing, meals from vending machines, and carpet murals on the walls keep us all coming back to the ancient subculture of knocking down pins. Legendary bowler Ernie McCracken of _Kingpin_ fame would endorse the following bowling alleys. **The Goodnight** (2700 W. Anderson Ln., 512/459-5000, www.thegoodnightaustin.com, 11am-midnight Sun.-Thurs., 11am-2am Fri.-Sat.) is Austin's retro-hip place to have a plush meal with cocktails, sing some karaoke, and knock down pins. This dimly lit place is covered in upholstery and chock-full of all kinds of folks looking for an unusual evening. I find it funny that they self-promote as "vintage bowling," because this sport and culture is by definition vintage no matter where you go. The culture never moved forward into the 21st century. The Goodnight seems to bring it to the present. If you want a bowling experience that is less hip and more gutter visit **Dart Bowl** (5700 Grover Ave., 512/452-2518, 9am-midnight daily). This 32-lane bowling alley, with big TV screens and a popular restaurant that serves an award-winning steak, draws a diverse crowd. Also in North Austin, up past all the dive bars, is **Highland Lanes** (8909 Burnet Rd., 512/458-1215, 9:30am-midnight Sun.-Thurs., 9:30am-1am Fri.-Sat.). The culture here is a bit more underbelly, and the food is terrible. Here's where you can find the best carpet mural in Texas, which covers two entire walls. **Austin City Limits** With the advent of PBS's popular and long-running program, _Austin City Limits_ , Austin walked on to the U.S. stage and became a household name. Since the first live taping back in 1976, the program has showcased only the very best artists, musicians, and bands, and has single-handedly chronicled the greatest musicians of our time. It's futile to list all the acts that have performed in front of the famous backdrop of Austin's skyline in the studios of KLRU, but here's a sampling: Ray Charles, B. B. King, Johnny Cash, Leonard Cohen, The Flaming Lips, Beck, Coldplay, Pearl Jam, and Austin's own Willie Nelson and Stevie Ray Vaughan. In 2011, the _Austin City Limits_ stage moved to the 2nd Street District and is now located at the W Hotel on Willie Nelson Boulevard. The move was a massive shift in direction for the legendary show, but they felt that it was time to allow for growth, and to give the public more access. The new studio, called the Moody Theater (310 Willie Nelson Blvd., 512/475-9077, www.austincitylimits.org), is a state-of-the-art live music venue and studio set with a capacity of 2,700-plus people. Live tapings are free—that's right, _free!_ Unfortunately, you have a better chance at going on a bike ride with the president than you have of getting tickets to a live performance at ACL. Available seats are limited, and these are taken by "insiders" and people "in the know." However, if you like playing the lottery, here's how it works: Ticket giveaways are posted about a week before a taping at acltv.com/upcoming-tapings. Here you can fill out the form to enter for the drawing. Multiple submissions will disqualify you. If you are visiting Austin, the chances of you being in town for a taping are slim, and your chances of actually winning tickets are slimmer, but it's worth a try. Two tickets per person are allowed, but a ticket doesn't guarantee admission to a taping. Since the new location doubles as a live music venue, buying tickets to see a live show is a great way to gain access. For more information about live music visit www.acl-live.com. The scene where all walks of life merge for the pool, shuffleboard, darts, and foosball is **Buffalo Billiards** (201 E. 6th St., 512/479-7665, noon-2am Mon.-Sun.). This downtown entertainment joint for the 21-and-older crowd is a great place to either begin or end an evening on the town. Here you can shoot pool, eat burgers, and drink a few beers or down hard liquor. A word to pool and snooker professionals: The tables and cues are not well maintained, because this joint is for drunks and amateurs out for a good time. A word to drinkers: The drinks aren't sophisticated. However, the place is a blast once you're tipsy, and then everyone feels like a pool shark. #### **FESTIVALS AND EVENTS** Thanks to the great weather that Austin enjoys for most of the year, the calendar of events is chock-full of things to do. Texans love their festivals. In fact, it seems there's a festival for just about anything you can think of, from kite flying to German festivals that salute the sausage, and from jamborees that honor various fruits such as peaches and apples to festivals that venerate the wide variety of spring wildflowers. And one can't forget the many rodeos and local fairs that feature vats of chili, clouds of cotton candy, zany rides, and sunburned families with smiling, nauseated children. In step with Austin's reputation of being diverse and eclectic one can take in pink tutus, Harley-Davidsons, and gay pride all in a single weekend, by walking the Austin Pride Parade during the day, catching Ballet in the Park in the evening, and partying at the ROT Biker Rally the next day. Many of the festivities happen right in Austin. For a complete guide to absolutely everything going on in Austin throughout the year, check out www.austin360.com and click on the calendar link, or go to www.austintexas.org and click on the events link. ##### **January** The very best way to sample a wide range of Austin bands and musicians is by stumbling through all the Red River/6th Street venues during **Austin Free Week.** It is, as its name implies, a completely free week of live music. This started out as a way to cure the postholiday music industry blues and has grown into a smorgasbord for music lovers. There are no cover or door charges at venues such as the Mohawk, Sidewinders, Beerland, Empire Control Room, and the Scoot Inn during the first week of January. ##### **February** For over two decades, every February **Carnival Brasileiro** (www.sambaparty.com) has brought Austin a party straight out of Brazil. Hailed as one of the city's weirdest and wildest celebrations, Carnival Brasileiro features only Brazilian music played on Brazilian instruments and sung in Portuguese, all for a crowd of drinking gringos. The event takes place at Palmer Events Center. Tickets can be purchased at local outlets Lucy In Disguise (1506 S. Congress Ave.) and Waterloo Records (600 N. Lamar Blvd). Tickets are $40, or $45 at the door. ##### **March** In Texas the county fair historically was the big event of the year, when the whole town gathered to eat barbecue, be mesmerized by snake oil salesmen, and get sick on rides. The vestiges of this era can still be seen at **Star of Texas Fair and Rodeo** (512/919-3000, www.rodeoaustin.com). The fair is held at the Travis County Exposition Center (7311 Decker Ln.). The rodeo is the real deal, and the people that come out of the woodwork are the real deal too. Pressed jeans and Stetsons is what I'm talking about. Parking is available in an adjacent field. It's an amazing sight to see thousands of kites in the sky with the Austin skyline as the backdrop. **Zilker Park Kite Festival** (www.zilkerkitefestival.com) has been going on since 1929. Not much can beat a glorious day under the sun in Zilker Park eating hot dogs, people-watching, and trying not to get your kite entangled in the trees or thousands of strings connected to the sky. The day is packed with scheduled events, such as kite building for kids and a kite contest featuring stunt kite-flyers. The festival is free and is the first Sunday in March unless it's rained out. Parking gets close to impossible as the day progresses. Hoards of people get tangled up at the annual Zilker Park Kite Festival. **SXSW** Imagine a major U.S. city handing over its streets, Mexican restaurants, barbecue joints, and public areas to hundreds of musicians, celebrities, rock stars, and thousands of fans for two weeks. Picture a backdrop of fireworks and dozens of film premieres. Sounds amazing, but impossible, right? Well, every spring all of this takes place in Austin during the spectacular event called **South by Southwest,** hitherto referred to as SXSW. This music and film festival has grown to mythic proportions and is now the premier event in the nation for new music and independent films. **HISTORY** SXSW started back in 1986 when the founders of the local weekly magazine _Austin Chronicle_ came up with the brilliant idea of creating a music conference dedicated to independent artists. At the time, the music industry was in dire need of change, as power-ballad groups like Cinderella and Bon Jovi dominated the airwaves. The idea was quite simple: bring amazing music from outside the mainstream to one place (Austin), organize a conference with discussions about contemporary music, invite industry folk as well as fans, and have lots and lots of bands perform in venues all over town. The end result: The shape and sound of modern music has been altered forever. Over the years SXSW has successfully brought attention to quality music that existed below the radar of the music industry. Wisely, the organizers opened the festival and conference to all genres, making the festival a cornucopia for all music lovers. Because of this, bands and musicians that have been featured at the festival over the years vary widely. A small sampling would include Jayhawks, Lucinda Williams, Mudd Puppies, Dixie Chicks, Beck, Wilco, Guided by Voices, The Fugees, Queens of the Stone Age, Trail of Dead, The Hives, The Shins, Black Eyed Peas, White Stripes, and Death Cab for Cutie. All these acts were buzz bands at the festival way back before they became household names. One of the greatest highlights in the history of SXSW was in 1994, when Johnny Cash played an acoustic set at punk rock club Emo's. A rediscovery of Cash ensued that made him a hero and icon for a new generation. Today, SXSW is the biggest festival for new music in the world. It includes a conference with keynote speakers, private parties for indie record labels, and hundreds of shows featuring the very best new artists. SXSW has been known to have over 1,600 bands performing in 60-plus venues—and that's just the official numbers. On the periphery is a whole world of unofficial shows, parties, and showcases that take place in small juke joints, barbecue restaurants, bars, and vacant parking lots all over town. SXSW has expanded its vision to include film. Theaters all over town premiere cutting-edge and innovative independent films, accompanied by panels and discussions on the indie film industry. **ACCESS BADGES** To attend the SXSW music or film conference you must buy an access badge. There are several different types of badges for varying levels of access for both the music and film portions of SXSW. Prices range $495-1,700. A badge gets you access to certain SXSW festival events, showcases, and the SXSW Trade Show. You also get a "Big Bag" filled with magazines, CDs, and souvenirs, as well as the program book with a directory of registrants. Buying your badge in advance is recommended, as walk-up prices are higher. To attend both the film and music conferences it's best to buy a platinum badge. This offers access to all music, film, and interactive events. Platinum badges cost $1,295-1,695. The easiest way to register for SXSW is online at www.sxsw.com, but registration forms can also be mailed in. Keep in mind that tickets are cheaper the earlier you buy them, and students can buy film badges at a discount. Badges are picked up at the Austin Convention Center when the festival begins. **TIPS** • There are hundreds of free shows and "unofficial" shows all over town. Some are low-key and some are major events. Before the festival begins, a schedule of free shows is circulated among those who have "connections." If you can get your hands on it, you can enjoy SXSW without buying an expensive badge. Mind you, you can't be as selective and won't get to see many of the "official" shows, but the free show circuit is a great way to experience SXSW. • Everyone shows up the first day of the festival to pick up their badges. The wait in long lines can be brutal, so pick up your badge a day early if you can. • For both music and film events that are getting lots of buzz, it's important to show up early and get in line. Admission is subject to venue capacity, and when big-name acts and films are being showcased, it can be very disappointing when you can't get in after paying big bucks for the "all access" badge. • Finally, if you are itching to see somebody famous, your best bet is to eat lunch at Güero's Taco Bar or Lamberts barbecue any day during the festival. Every year spring comes unusually early in the Hill Country, and with it springs up a vast array of spectacular wildflowers. Every March **Wildflower Days** (www.wildflower.org) begin at Lady Bird Johnson Wildflower Center (4801 La Crosse Ave., 512/292-4100). The gardens and facility are extraordinary—a must-see for those who love the outdoors and who have allergy medication. From mid-March through the end of April the center is open 9am-5:30pm every day. The biggest festival of the year—the mother of all mothers—is **South by Southwest** (www.sxsw.com). For one week (usually mid-March) the city of Austin is completely overrun by hundreds of musicians and celebrities and thousands of music fans. The town is plastered with the festival's acronym, **SXSW** , and the restaurants, clubs, music stores, and barbecue joints are teeming with greasy-haired, tattooed, ripped-jean-wearing rock stars and rock star wannabes. What once was a unique underground event tailored for the ambitious DIY musician has now become a beer-sponsored, globally recognized event that includes independent film as well. If the earth opened up and swallowed Austin whole (God forbid) any day in mid-March, nearly all indie rock bands would be erased from the face of the earth, along with a few celebrities. ##### **April** At the beginning of the month local artists, as well as artists from across the country, are peddling their wares at **Art City Austin** (www.artallianceaustin.org, $8 adults, children under 12 free). Here you'll find sculpture, metal and woodwork, crafts, and painting in all media. This art festival is a big deal. The event takes place all weekend at Palmer Events Center, and artists set up booths so art lovers and the curious can mull about in a daze looking at all the swirling colors as they eat fair fare and live music sets an upbeat mood. The best hot rod and classic car show in Texas is the **Lonestar Rod & Kustom Round Up** (<http://hlonestarroundup.com>). Every April hot rod enthusiasts, paint and piston fanatics, dolled-up pinup girls, and greased-up guys gather at the Travis County Exposition Center (7311 Decker Ln.) for a homegrown outdoor car weekend. Be warned, there are no muscle cars here: all registered vehicles are from 1963 or earlier. Cars are slammed, chopped, loud, and some even spit fire. Live music often features Jimmy Vaughan and other rockabilly bands. The event includes booths with hot rod merchandise, food trucks, beer and margaritas, mini-bike races, and a swap meet. At the end of the weekend the trophies are passed out, as are many of the attendees. General admission is $15, kids under 12 are free, and parking is free. **Eeyore's Birthday Party** (512/448-5160, www.eeyores.com) is one of the more popular and interesting citywide birthday parties held throughout the year. Founded by hippie UT students decades ago, this family festival has grown into an extravaganza of costumes, cake, and live entertainment, all in honor of the depressed donkey friend of Winnie the Pooh. He's getting up there in age so try to catch one of these before he dies. Proceeds go to nonprofit groups in town. For the wine and food connoisseur willing to throw down some bucks there's the **Austin Food and Wine Festival** (www.austinfoodandwinefestival.com). Sponsored by the Austin Food & Wine Alliance, this three-day extravaganza showcases local and national wine and food artisans who converge in Austin to share their culinary creations. The festival takes place in venues all over town. Tickets range $55-450 depending on how much of the event you want to experience. A favorite rite of spring for Austinites is running the **Statesman Capitol 10K** (<http://cap10k.com>), a 10K race on foot that begins in downtown Austin and ends on Auditorium Shores. Some run, some walk, and some just parade about in silly getups. If you have bad knees or just don't like running or walking 10 kilometers, it's worth watching the start of the race at Congress Bridge as the thousands of participants clog the arteries of downtown. The event happens the first Sunday of April and early registration costs $30-50. Every participant is actually placed and timed, so it's possible to cross the finish line in 5,142nd place. Every April the Clyde Littlefield **Texas Relays** are held on the UT campus. This event is one of the nation's largest and most prestigious track-and-field meets. The four-day event features high school, collegiate, and professional athletes from across the nation. It is one of the earliest outdoor meets of the year, and the combination of pleasant weather and high-profile athletes draws sellout crowds. At the end of April, down-home acoustic music enthusiasts make the **Old Settlers Music Festival** (18300 Farm to Market Road 1826, www.oldsettlersmusicfest.org) their home for a four-day weekend where the banjos will be plinkin'. Held at the Salt Lick Pavilion in Driftwood just outside of Austin, the festival features over two dozen of the top performers of bluegrass and Americana music on four stages. Camping at the festival is encouraged, but reserve your tent or RV spot in advance. Admission varies. The **Austin Reggae Festival** (www.austinreggaefest.com), the city's premier reggae event, celebrates the legacy of peace, world unity, and great reggae music that Bob Marley introduced to the world. Held at Auditorium Shores, this Rasta mecca includes performances by reggae artists along with food vendors offering Caribbean delicacies. Bring something to sit on, sunscreen, and a Hacky Sack. A day pass costs $20, and a weekend pass is $40. A portion of the ticket sales goes to the Capital Area Food Bank. Get in touch with your more sensitive and expressive side at the **Austin International Poetry Festival** (www.aipf.org). Held at various venues throughout town, this competition brings in over 200 poets from around the world for a four-day event dedicated to rhyme and time. For those with a green thumb, or plant and garden lovers in general, **Zilker Garden Festival,** held at Zilker Botanical Garden (2220 Barton Springs Rd., 512/477-8672, www.zilkergarden.org) in Zilker Park, is a great way to learn about the latest trends in gardening. Best described as a garden, plant, and craft fair, this event includes plant vendors and garden-equipment suppliers, along with purveyors of other various garden-themed goods such as jewelry, books, and games. Garden Fest is held in either April or May so check the schedule in advance. Admission is $10 adults, $4 children age 4-12, under 4 free. Parking is $5. **Wildflower Days** at Lady Bird Johnson Wildflower Center continues through April. ##### **May** If your sense of humor is on the level of Bazooka Joe gum wrappers (I used to work in a blanket factory but it folded . . .), and if you enjoy clever wit, check out the **O. Henry Pun-Off World Championships** (<http://punoff.com>, 512/472-1903). This duel of puns between a slew of clever word butchers is held in the backyard of the O. Henry Museum (409 E. 5th St.) with some 2,000 pun fans watching. Admission is free. **Zilker Garden Festival,** held at Zilker Botanical Garden in Zilker Park, sometimes takes place in May. Every year during the **Pecan Street Arts Festival** (www.pecanstreetfestival.com), 6th Street is shut down and the arts become king. Featuring some 300 vendors selling arts and crafts, live music stages in the streets, children's carnival games, street performers, and the smell of beef in the air, 6th Street becomes an Austin-style bazaar. This free event is held every spring on the first weekend of May and every fall on the last weekend of September, between 11am and 8pm. ##### **June** The first weekend in June, women in pink tutus and men in tights are gracefully dancing about under the starry Texas sky. **Ballet Under the Stars** (512/246-6047, metamorphosisdance.org) is a free, open-air ballet featuring talented local dancers at the Zilker Park Hillside Theatre. For over a decade Austin Dance Ensemble has put on this nimble affair the first Friday and Saturday of June at 8:30pm. Hailed as the biggest biker parade and street party in Texas, the **Republic of Texas Biker Rally** (www.rotrally.com) fills Austin with acres of hogs, custom choppers, leather, facial hair, and sheer brawn for an entire week. The event stretches over a four-day period at the Travis County Exposition Center (7311 Decker Ln.). Entertainment includes monster-truck rallies, white-knuckle motorcycle stunts, and live music. Headliners in the past have included Charlie Daniels, Hank Williams Jr., and George Thorogood. On Friday night the rally proceeds through downtown with a police escort and ends at Congress Avenue. Traffic is shut down for the ensuing all-night biker bash. Tickets for the Expo Center are $45; the party on Congress Avenue is free. 6th Street and all of downtown is overrun by bikers during the Republic of Texas Biker Rally. Starting this month, the local rock station KGSR 107.1 (www.kgsr.com) brings the blues to Zilker Park for **Blues on the Green.** Free shows are put on every other Wednesday 7:30pm-9:30pm, mid-June to mid-August. As for all events in the dead of summer, bring sunblock and lawn chairs. ##### **July** Strike up the band and let our independence be commemorated! A grandiose way to celebrate July 4 is to attend the **Austin Symphony 4th of July Concert and Fireworks** (www.austinsymphony.org) on Auditorium Shores' outdoor stage. A free, two-hour classical music performance culminates in Tchaikovsky's famous 1812 Overture, accompanied by the firing of 75-millimeter howitzers and ending with a spectacular fireworks show over Lady Bird Lake. ##### **August** In August it's too darned hot to do anything outside. Nevertheless, the _Austin Chronicle_ cranks up the heat with the **Austin Chronicle Hot Sauce Festival.** This is an amateur and professional hot sauce competition that includes live music and great food at Waterloo Park. Warning: The combination of the 100-degree heat and hot sauce may make you feel like you're trapped in a structure fire. During **Bat Fest** (www.roadwayevents.com), Congress Avenue Bridge turns into a fair with more than 100 booths featuring arts, crafts, and food, and more than 20 musicians and bands perform on two stages. All this is in honor of North America's largest urban bat colony, which lives under the bridge during the summer months. The bridge and Congress Avenue, Cesar Chavez Street, and Barton Springs Road near the bridge are all closed from 2am Saturday to midnight Sunday. Admission is $3 a day. A portion of the proceeds goes to Bat Conservation International. ##### **September** Imagine the symbol of Texas—the Lone Star—on a rainbow backdrop, or a giant Texas-shaped rainbow flag proudly carried as a standard of victory by men dressed up like Cher. At the **Austin Pride Parade,** gay pride is as big as Texas. Held annually since 1991, this is an important event that is all about tolerance, acceptance, and being proud of who you are. The parade is a family event replete with floats, music, and classic cars, but it can have moments that aren't necessarily rated G. The fall occurrence of the **Old Pecan Street Arts Festival** is held on 6th Street the last weekend of September. For more details see the complete entry in May section. ##### **October** Spun out of the famous public television show, the **Austin City Limits Music Festival** (www.aclfestival.com) is the biggest music fest of the year. For three days the festival features top acts, bands, performers, and musical legends in nearly all genres of music. In the past the festival has featured artists such as REM, Ben Harper, and Coldplay, and the list goes on. The scene: 200,000 people, portable potties, the smell of sunscreen, parking miles away, dust in every orifice, and heat exhaustion, all in beautiful Zilker Park. Tickets can be purchased for one of the three days (Friday, Saturday, or Sunday), or you can throw down more cash for a three-day pass. In the spring an early-bird ticket special is offered, but these sell out in a matter of hours. After that tickets can be bought at a premium online. There's a long list of things that won't pass security; check the website before you bring all kinds of stuff to survive the weekend. Founded by former librarian and First Lady Laura Bush, the **Texas Book Festival** (www.texasbookfestival.org) has become one of the biggest literary events in the Southwest. Book signings, awards ceremonies, celebrity-author book readings, and a black-tie Literary Gala including cocktails and dinner provide a great weekend that benefits the Texas Public Libraries. Tickets range $50-75, and the Literary Gala is $350 per person. Austin has been attracting quite a bit of attention from the film industry. The event that highlights Austin and celluloid is the **Austin Film Festival** (www.austinfilmfestival.com). For eight days hundreds of film-industry folk, celebrities, and silver-screen fans converge in downtown Austin's many cinemas and hotels to view some 100 films. The festival also includes a screenwriter's conference. Local cyclist, cancer survivor, and all-around controversial figure Lance Armstrong hosts **Ride for the Roses** (512/236-8820, www.livestrong.org) every October. This hugely popular event brings out crowds of cyclists, fans, celebrities, and spectators for a whole weekend of cycling-related events, all to raise money for cancer research. Perhaps the most obscure event that goes on in these parts is the **Texas Gourd Society Show and Sale** (www.texasgourdsociety.org). Talk about niche: This society is made up of artists that enjoy painting and decorating gourds. The show and sale also includes a competition. Whoever has the most gourd-geous gourd wins! Believe me, some of these gourds are pretty spectacular. When writing up events for Austin's calendar in October one can't omit **Halloween on 6th Street.** Some 60,000 dressed-up freaks and ghouls take over downtown's historic 6th Street. Overstimulated by sugar and whatever else, people party all night. The costumes are unbelievable. If you want to trick-or-treat but don't want to put time into inventing a costume, rent something from **Lucy in Disguise with Diamonds** (1506 S. Congress Ave., 512/444-2002). ##### **November** The funnest festival in Austin is **Fun Fun Fun Fest** (www.funfunfunfest.com). Or at least it's pretty fun for all who are interested in indie rock, punk rock, hardcore, metal, and hip-hop/DJ. The festival, which started in 2006, is held in Austin's Waterloo Park close to downtown. The promoters of this show have an uncanny knack for getting bands from the bygone era of rock underground to resurface and put on amazing shows. Past lineups have included Slayer, Jane's Addiction, 7 Seconds, The Hold Steady, Descendents, High on Fire, Spoon, Explosions in the Sky, and Ice T. Even Weird Al Yankovic has done his thing, whatever that is. There are multiple stages for music and one for stand-up comedy. The event also includes BMX and skateboard half-pipes and even an amateur-wrestling ring. A great way to sneak a peek into the lives of Austin artists is by touring artists' studios during **East Austin Studio Tour** (www.eastaustinstudiotour.com). Over a hundred artists, galleries, and studios participate in this East Austin event in mid-November each year. All media and styles are represented, from serene landscapes to bizarre abstract art. A map of the tour is available on the East Austin Studio Tour website. ##### **December** Austin's beloved holiday tradition, the **Zilker Park Tree Lighting,** draws thousands to Zilker Park to see the park decorated in lights and watch the lighting of the 165-foot Christmas tree. The Trail of Lights, which is a mile-long display of holiday and wintertime scenes, is an Austin bucket list experience. Most locals consider spinning under the tree and eating funnel cake the only way to usher in the Christmas spirit in Austin. The tree-lighting ceremony takes place on the first Sunday of December, and the Trail of Lights is open until the New Year. The **Armadillo Christmas Bazaar** (512/447-1605, www.armadillobazaar.com, 10am-10pm daily) is a uniquely Austin holiday market where artists and artisans from Texas and the Southwest sell their works. This Austin original has been encouraging the public to buy from local artists since 1976. Besides all kinds of weird, wacky, original, and pop forms of art, the bazaar features great food and live music, and it all takes place at the Palmer Events Center. The bazaar operates the second half of December. Parking is available at the Palmer Events Center Garage, accessed off Riverside Drive. ### **Shopping** Before you defer your shopping fantasies to New York, Los Angeles, or Paris, I recommended you give Austin a full-hearted leap of shopping faith, keeping in mind one thing: Austin is the splendid crossroads of country, kitsch, and pop culture. For shopping this means obscure, secondhand vintage clothing shops, cowboy boots and Western wear, and boutiques featuring the latest in contemporary fashion. Because of all this, Austin is one of those places where the stylists of rock stars and celebrities find some of their clients' greatest fashions. Beyond the fashion boutiques, Austin has a wide variety of other shops, such as toy stores, galleries, music stores, and curiosity shops, all displaying their wares with personalized weirdness and flair. Concept shops that I would describe as weird gift shops and oddity boutiques are springing up everywhere. They're a hip and zany version of Hallmark stores for the 21st century, peddling weird trinkets, Japanese toys, pop memorabilia, reissued lunchboxes, and risqué cards. These do-it-yourself shops are run by creative folks who parlay their personal fetishes, hobbies, and interests into viable businesses. Austin also has outlets of many of the big national chains, but in this book we will focus our attention on the one-of-a-kind Austin boutiques, as these are what make Austin so fabulous. Although there are great shops all over town, there's a concentration of good stores in a few pockets of the city. The most famous shops are on **South Congress Avenue,** which is lined with funky storefronts, vintage boutiques, and trendy clothing and accessory shops. For fashionable new clothes and home decor items the shops in **2nd Street District** downtown, **6th and Lamar,** and **Guadalupe Street** are popular. For vintage and retro stuff there are the shops on **South Lamar** and **North Loop.** And for tacky touristy junk there's a smattering of shops on **6th Street.** Finally, in North Austin there's the shopping mecca of the **Arboretum,** which is a contemporary outdoor strip mall with all the big retail giants such as Gap and Pottery Barn. Hours for most of these shops are generally 10am-7pm daily. On the first Thursday of every month merchants on South Congress keep their doors open until 10pm. So get on out there and support local business at any of the following choice establishments. Allens Boots on South Congress Avenue #### **CLOTHES, SHOES, AND ACCESSORIES** South Congress is home to one of the area's finest western-wear shops, **Allens Boots** (1522 S. Congress Ave., 512/447-1413, 9am-8pm Mon.-Sat., noon-6pm Sun.). Once you open that door, be prepared to be knocked down by the smell of cow skin. Inside this wood-paneled, leather-lined cowboy emporium, you'll find everything for your modern cowboy, the closet cowboy, and the wannabe, such as classy belt buckles, bolo ties, western shirts for men and women, and did I mention boots? Allens has the most extraordinary cowboy and cowgirl boot collection in the United States. With over 4,000 boots on display, they have everyday boots for the working cowboy, but they specialize in dress boots with ornate patterns, colors, and designs, fetching up to $6,000. Even if you don't want to own a pair of cowboy boots, poke your head in here and marvel. Finally, there's a clothing shop that sells nothing but black. Gothic meets country at fashionable **Blackmail** (1202 S. Congress Ave., 512/804-5881, 11am-7pm daily). What two words personify the style here? Johnny Cash. Here you can buy anything from a black leather jacket to a pair of black jeans to black accessories for both men and women. They even have black lotion. The only color to be found in here is in the back, where they sell vintage cowboy boots. For fashion-conscious women and men with a fat wallet there's the local institution of fashion known as **By George** (524 N. Lamar Blvd., 512/441-8600, 10am-7pm Mon.-Sat., noon-6pm Sun.). Owned and operated by the same folks since 1977, By George has had its pulse on the state of fashion for decades. They offer the latest hip rags from contemporary big-name designers as well as some up-and-coming designers. No dusty vintage duds and faux vintage here, just the guilty pleasures of passing fads. **Eco-wise** (110 W. Elisabeth St., 512/326-4474, 9:30am-6:30pm Mon.-Fri., 10am-6pm Sat., noon-5pm Sun.) is the place to shop for all things green, and by this I don't mean the color green, I mean made with hemp. As people become increasingly environmentally conscious, shops like Eco-wise are important places to get just about anything. This place carries a small collection of clothes and accessories, as well as natural duds for kids, but don't expect much in the way of flashy design. All products are down-to-earth in the truest sense of the phrase. Here you'll also find hand creams, building supplies, toys, flooring, and other items for the home, all environmentally friendly. **Creatures** (1206 S. Congress Ave., 512/707-2500, 11am-7pm daily) is a favorite for the ladies. Here you can buy cute casual dresses, flashy shoes, gifts and jewelry, all stylish for the day. I love this place because they are dedicated to supporting local and independent artists. When shopping in Austin, get some brownie points by buying locally made goods in support of local designers from **Parts and Labour** (1117 S. Congress Ave., 512/326-1648, 10am-9pm daily). The little shop is filled with edgy designs, clever and trendy graphic T-shirts, and unusual accessories. There is no specific "look" that the proprietor is going for fashion-wise, which in turn has created a look that is totally unique. This is achieved by simply stocking the space with all locally made designs and fashions. Finally, a boutique for the fashion-conscious male: **Service Menswear** (1400 S. Congress St., 512/447-7600, 10:30am-8pm Mon.-Sat., 11am-6pm Sun.) is a small space that is easy to overlook. In here men can buy designer, surf, and skate apparel made by Spiewak, Ben Sherman, Tyler Speed, Almost Evil, and old standbys Vans and Penguin. Service is known for its great collection of graphic T-shirts and vintage belt buckles. Another clothing store for men in at the South Congress area is Stag Provisions for Men (1423 S Congress Ave, 512/ 373-7824, 11am-7pm Tues.-Thurs., 10am-8pm Fri.-Mon.). This high-end outlet features trendy men's clothes by designer labels in classic and modern styles. If you're young and have a handlebar moustache and a fat wallet this place is for you. #### **MUSIC** Being the music-lovin' town that it is, Austin has some great music caches around town that have it all—vinyl, CDs, cassettes, and even eight-tracks, in any and every genre of music. For the vinyl fiend there are some excellent record stores. Remember when record stores carried records? Remember that distinct smell of cardboard and plastic? It still exists at **Antone's Record Shop** (2928 Guadalupe Ave., 512/322-0660, 10am-10pm Mon.-Sat., 11am-8pm Sun.), where vinyl junkies are sure to find some old records they've been looking for. Besides having the biggest collection of vinyl in town Antone's also has a great selection of Texas music. So dig in that junk drawer and find your yellow 45 adapters. Vinyl enthusiasts will be pleased when they visit Austin's true indie record store **End of an Ear** (4304 Clawson Rd., 512/462-6008, www.endofanear.com, 11am-9pm Mon.-Sat., noon-8pm Sun.). Although the space seems small, the collection of vinyl is full of surprises. Dig a little and you will uncover more "must-haves" than you can afford. Besides LPs and 7-inches, they also carry record players, used and new CDs of your favorite punk and metal bands, and a meager selection of country, metal, and jazz. The folks here are experts in vinyl and can help troubleshoot or answer questions. Austin's most popular source for both new and used music is **Waterloo Records** (600A N. Lamar Blvd., 512/474-2500, 10am-11pm daily). It specializes in the most current releases in pop, country, and indie, and offers a great selection of Texas artists. Besides peddling CDs, Waterloo is the place to get tickets for local concerts, and they even put on their own live shows in-house. #### **BOOKSTORES** The largest bookstore in Texas is **BookPeople** (603 N. Lamar Blvd. at 6th St., 512/472-5050, 9am-11pm daily). It has everything that a major chain has, and then some. Here you'll find new books in every category, by nearly every author, as well as gifts, journals, children's books, magazines, and a café. BookPeople is also the area's top venue for author book signings, lectures, and literary information. As the name implies, it's a community bookstore and resource. For the ladies, and the ladies who like ladies, there's **BookWoman** (5501 N. Lamar, 512/472-2785, 10am-8pm Mon.-Sat., noon-6pm Sun.). This female-oriented bookstore and community information center stocks feminist, gay and lesbian, and women's studies books, as well as T-shirts and gifts. The area's biggest used-book resource is **Half Price Books** (5555 N. Lamar Blvd. at Koenig, 512/451-4463, www.halfpricebooks.com, 9am-10pm Mon.-Sat., 10am-9pm Sun.). Along with racks and shelves of used books you will also find new overstock coffee-table books, color folio books, and best sellers at a discount. In the back is a rare-book room for the collector in search of that first-edition _Wizard of Oz._ For other locations visit the website. Want to bring down "the man"? Need a copy of _The Anarchist Cookbook_? **Monkeywrench Books** (110 North Loop Blvd., 512/407-6925, noon-6pm Mon.-Fri., noon-8pm Sat.-Sun.) carries literature for the counterculture and the cultural revolution. Monkey has a wide variety of zines, punk and pop-culture journals, and socialist and anarchist books. #### **ART GALLERIES** Every outlet for creativity abounds in Austin. Although music takes center stage, the fine arts also deserve a nod. A slew of galleries around town represent all types of artists in all mediums and styles. However, the most prevalent style is contemporary folk art best described as John Wayne meets Andy Warhol. **Wally Workman Gallery** (1202 W. 6th St., 512/472-7428, 10am-5pm Tues.-Sat.) is the gallery in town where you can always find something beautiful and captivating to look at no matter what your tastes may be. Every month this small gallery in an old retrofitted Victorian house has a new exhibition that features upcoming and innovative artists. Local artist Todd Sanders has created a little world for himself at **Roadhouse Relics** (1720 S. 1st St., 512/442-6366). A while back he bought the corner storefront location, plunked a trailer in the back, and hunkered down. Now he flings paint and neon where he wants without worrying about a thing. He opens his world to the public by appointment or by chance. If you drop by and he's not there, peek into the backyard at the giant chicken, the huge "Austin" neon sign, and all the other bizarre things Todd has collected. His stuff is best described as vintage neon and decor. Austin's only outlet for master artists of Europe is the **Russell Collection** (1137 W. 6th St., 512/478-4440, www.russell-collection.com, 10am-6pm Tues.-Sat.). This gallery is perfect for the art collector who wants to own a Chagall, Renoir, Manet, Pissarro, or Picasso but has a budget of around $1,000-5,000. You may shudder at this and ask how this is possible. The collection consists, for the most part, of signed lithographs and works on paper that were cranked out either during the artist's lifetime or were produced in recent years from the original plates. How about the original oils? Well, look closely at the name and you will see these are painted by relatives of the masters, not the masters themselves. **Yard Dog** (1510 S. Congress Ave., 512/912-1613, www.yarddog.com, 11am-5pm Mon.-Fri., 11am-6pm Sat., noon-5pm Sun.) is an art gallery that represents artists from around the country who create abstract folk art with a bite. The artwork in here is always amusing, quirky, and both colorful and off-color. Paintings, sculpture, and a unique array of things in between seem to take a tongue-in-cheek approach to Americana without becoming irreverent. #### **WEIRD GIFTS AND ODDITIES** Every travel destination has its particular souvenirs that folks bring back to their friends and families. For Austin it's all about music doodads, country-western stuff, or pretty much anything that's weird or unusual. The best touristy shop in the downtown area with all things music related is **Wild About Music** (615 Congress Ave. 512/708-1700, www.wildaboutmusic.com, 10am-9pm daily). This is the place to get your touristy music-related knickknacks such as snow globes, key chains, T-shirts, hats, buttons, and random oddities. You can also find tons of junk related to Willie Nelson and Stevie Ray Vaughan. **Electric Ladyland,** aka **Lucy in Disguise with Diamonds** (1506 S. Congress Ave., 512/444-2002, 11am-7pm Mon.-Sat., noon-6pm Sun.), is the biggest costume and prop outlet around. Here you can rent or buy costumes for anything, and this is not hyperbole. There's a wall of costume jewelry that can make any woman—or man for that matter—into Cleopatra, Carmen Miranda, or the Jolly Green Giant. Inside the showroom there's an amazing collection of theme-park-quality get-ups, such as Tweety Bird, which includes a big, fuzzy, unwieldy mask. There's also an entire room of scary rubber masks and prosthetics that range from a Freddy Krueger mask to a triple "breast"-plate. Monkeys are known for "aping" what others do, but **Monkey See, Monkey Do** (1712 S. Congress Ave., 512/443-4999, 11am-8pm daily) isn't copying anyone. This boutique filled with new junk, such as Japanese toys, silly kitsch, retro clocks, pop-culture books, and the largest refrigerator-magnet collection in Texas, fits in perfectly on South Congress Avenue. The shop with the most color is **Tesoros** (1500 S. Congress Ave., 512/447-7500, 11am-6pm daily), Austin's Latin American import extravaganza. Here tourists can be bedazzled by an enormous space filled with treasures, religious and superstitious items, and folk art, all imported from south of the border. This emporium of colorful kitsch is a great place to get unique gift ideas. The endless litany of items includes handmade jewelry, unusual trinkets, colorful wall hangings and tapestries, carved figures and figurines, Mexican wrestling masks, pottery, toys made from soda cans, ex-votos/ _milagros,_ religious paintings and art, woodblock prints, and much, much more. **Funky Signage** Driving around Austin one can't help but take notice of the numerous funky, creepy, bizarre, and clever signs that many Austin businesses are adorned with. When it comes to zoning laws for signage Austin is pretty laissez-faire, which has opened the door for some creative approaches to attract the passerby. These businesses and their signs have become landmarks for locals and tourists, and collectively give Austin an amusing and fascinating image. For example, what would normally be a very mundane light-bulb shop is completely transformed when topped with a three-dimensional bust of a giant, creepy, grinning man with a light bulb suspended over his head. Like a moth drawn to a light bulb one can't help but stroll into **The Light Bulb Shop** (6318 Burnet Rd.), even if there's no need for a light bulb. Just down the road is another peculiar sign worth noting. In front of **Atomic Tattoo** (5533 Burnet Rd.) is a pole topped with a skull, wearing a cap (not to be confused with a skullcap), mounted on an octopus. Eye-catching? Yes! But whether this makes one crave a tattoo or not is another story. The Light Bulb Shop Other signage worth mentioning would be the grotesque massive red bulging arm in full flex protruding from **Hyde Park Gym** (4125 Guadalupe St.). Or there's the much more soothing retro/hippie sign of **Groovy Lube** (3511 Guadalupe St.) or the lesser-known, daffy-looking boxer standing proud and tall above **Richard Lord's Boxing Gym** (5400 N. Lamar). One can't leave out the string of shops on South Congress Avenue. The sign and sculpture above **Uncommon Objects** (1512 S. Congress Ave.) begs the question, "What the heck were they thinking?" A cowboy made out of a muffler, riding a giant rabbit? Wow! Among all of Austin's landmark signs there are two vying for the position of sign diva. One is a little waitress girl with a big Fender guitar that used to be on top of **Fran's Hamburgers** (her whereabouts are unknown since Fran's closed); the other is the mother of all mothers, the colossal woman's bust with open arms beckoning all the world to enter **Maria's Taco Express** (2529 S. Lamar Blvd.). This sign features the actual likeness of the proprietress. Once you see Maria's open arms from the road it is highly suggested you pull over and let her embrace you with her delicious tacos. South Congress's Latin import connection is the **Turquoise Door** (1208 S. Congress Ave., 512/804-0618, 10am-7pm Mon.-Sat., 10am-6pm Sun.). This small retail space is chock-full of Latin American folk art, including hand-woven ceremonial Peruvian wall hangings, larger-than-life Oaxacan Día de los Muertos (Day of the Dead) figures, folk dolls, Mexican punched-tin art, religious items, wooden masks, and colorful and exotic jewelry. Chances are you aren't going in this place looking for something specific, but you'll like what you find. **Oat Willie's** (617 W. 29th St., 512/482-0630, 10am-midnight Mon.-Fri., closed Sat.-Sun.) is the oldest continuously operating smoke shop in town. Oat's straddles the fine line between selling tobacco and being a head shop. I tip my hat to all who smoke tobacco in a bong. #### **FOR KIDS** Austin is an all-around fun place with a persistent lightheartedness and an unspoken maxim: "Don't take things too seriously." That said, everything in town for children isn't exclusively for children. Frank Sinatra's famous song explains what I'm trying to say with this lyric: "For it's hard, you will find, to be narrow of mind, if you're young at heart." This is especially true if you are in **Toy Joy** (403 W. 2nd St., 512/320-0090, 10am-9pm Mon.-Fri., 10am-10pm Sat., 10am-8pm Sun.). Rated one of the top 10 toy stores in the nation by _Child_ magazine, Toy Joy is lined floor to ceiling and beyond with toys, gags, flying things, shooting things, noisemakers, squishy things, giant things, and tiny things, all in primary colors. One very important word of advice to grown-ups: Before you enter, leave your adult persona at the door. Open late at night, this is a great place to visit in the "wee" hours. Inside Toy Joy you'll find things that cheer up every girl and boy, such as: Things that go swish, things that go squish, flying birds, and swimming fish. Things that tumble, things that roll, and music by Raffi, not Dave Grohl. If the commercial plastic side of the toy industry has you turned off, consider visiting Austin's miniature haven of homemade wooden toys, **Rootin' Ridge Toymakers** (1206 W. 38th St., Ste. 1105, 512/453-2604, 10am-5pm Mon.-Sat.). This little shop, founded by husband-and-wife team Georgean and Paul in 1976, has all kinds of toys and games that seem like they were made for the set of _Little House on the Prairie._ The fun part of visiting this little shop is you can watch the toys being made on the spot. Another great locally owned toy store is **Terra Toys** (2438 W. Anderson Ln., 512/445-4489, 9am-8pm Mon.-Sat., noon-6pm Sun.). If you're a kid, it's as good as a candy store, and if you're a depressed and jaded adult, Terra Toys will cut a smile into your face. This collection of toys steers clear of the consumer garbage that has captivated kids for so long, such as action figures and Barbie. Instead, you can find educational toys, handmade toys, learning games, wooden toys, musical instruments for tots, and a small selection of expensive clothes. #### **RETRO, VINTAGE, AND ANTIQUES** Austin's love affair with kitsch is best experienced by strolling through the many shops and boutiques that specialize in wacky and rare retro furnishings, vintage clothing, and country and folk antiques. In any number of these shops you can throw down some hard-earned dollars for a musty old Western shirt that looks like something worn by a member of the Carter family on the stage of the Grand Ole Opry, an amoeba-shaped chair that looks like it came from Frank Sinatra's Las Vegas home, a hand-carved shrine to the Virgen de Guadalupe, or an antique stuffed rabbit perched on a lacquered piece of burl. And by "stuffed" I mean taxidermy—you can tell by the creepy smell. For the most part these shops are clustered together on a few of the main drags in town, which makes it easy to just step out on a street and follow your curiosity where it leads you. South of town there are some fantastic shops on South Lamar and South Congress, and just north of downtown there are a couple of shops on Guadalupe Street. Farther north there are some shops on Old Burnet Road and North Loop. Generally these places are close to great coffee shops and excellent places to break for lunch. For a complete list of vintage outlets in Austin check out www.vintagearoundtownguide.com. ##### **South Austin** First of all, I highly suggest kicking off your shopping on South Congress by fixing your caffeine maintenance at Jo's Cafe. Only then will you be able to focus properly for the transactions of the day. For upscale trinkets, **Off the Wall** (1704 S. Congress Ave., 512/445-4701, 10am-6:30pm Mon.-Sat., noon-6pm Sun.) has lots of oddities you can buy at collectors' prices. The proprietors have made a living out of treasure hunting. With 25 years of experience they've developed an excellent sense for what attracts the antiques moths to the virtual flame. Here you'll find furniture along with an intriguing array of collectibles ranging from swords to early versions of Mickey Mouse in porcelain, from weird inventions from bygone times to expensive antique ashtrays. The best curiosity shop in town is **Uncommon Objects** (1512 S. Congress Ave., 512/442-4000, 11am-7pm Fri.-Wed., 11am-9pm Thurs.). Here 18 purveyors of random items, knickknacks, oddities, trinkets, and collectibles peddle their weird stuff. Everything in this dark, 4,000-square-foot space is a conversation piece, such as vintage priest vestments, Victorian and cowboy clothes, human bones, bronze busts of whomever, and taxidermic animal corpses. Take your time browsing because there's stuff in every corner and junk hanging from the ceiling. You won't want to miss a thing. **Feathers** (1700-B S Congress Ave., 512/912-9779, 11am-7pm daily) has flawlessly merged vintage and modern fashion, without being too dusty or too slick. This small retail shop specializes in '70s to '90s' fashions and home knickknacks as well as jewelry. One of the long-time staples in Austin's vintage/retro scene is **Amelia's Retro-Vogue & Relics** (2213 S. 1st St., 512/442-4446, noon-7pm Tues.-Sat., noon-5pm Sun.). This is a favorite place for designers and stylists to the celebrities, musicians, and drag entertainers to get ideas. Inside you'll find dramatic glamour outfits from the 1950s show-business era, children's vintage clothes, and a massive hat collection. You know you have arrived at Amelia's when you see a giant wire globe in the front yard of an old house. For vintage and retro shopping for men and women, there's **Flashback** (1805 S. 1st St., 512/445-6906, 11am-7pm Thurs.-Sat., noon-5pm Sun.). Here you'll find an excellent collection of early-20th-century women's evening wear, men's shirts, and thrift-store art. The amount of vintage duds in here is phenomenal. The most interesting vest in the world is in here—a snake vest outfitted with pockets made from cobra heads (no joke). The owners of **Garment Modern+Vintage** (701-F S. Lamar Blvd., 512/462-4667, 11am-7pm Mon.-Sat., noon-6pm Sun.) go to great length to find vintage clothing of quality, rarity, and desirability. Find the perfect clothes to look vintage rock-n-roll or to exhibit some flare from the past. They also stock new and vintage wearable accessories and jewelry. ##### **North Austin** If you're out and about in Old North Austin and want to hunt for nothing in particular, make your way to the burgeoning North Loop DIY business district. This small bend in the road of a residential area is well worth your time. Here you'll find **Revival Vintage** (100 E. North Loop Blvd. #A, 512/524-2029, 11am-7pm daily), one of Austin's newest vintage stockpiles, featuring a small but well-curated collection of clothes, furniture, and stuff from the 1970s TV show _All in the Family._ Just across the street is **Room Service Vintage** (107 E. North Loop Blvd., 512/451-1057, 11am-7pm daily). Upon entering through the double doors one can't help but be overwhelmed by the lights, colors, and shapes in here. With over 3,500 square feet of "modern" amoeba-shaped furniture, 1950s light fixtures, costume clothes and jewelry, vinyl records, vintage _Playboy_ magazines, and paint-by-numbers artwork, everyone is bound to find something that tickles their fancy. Wrap up your North Loop retro shopping day at **Blue Velvet** (217 W. North Loop Blvd., 512/452-2583, 11am-8pm Mon.-Sat., noon-8pm Sun.). Blue Velvet, six-time winner of the _Austin Chronicle_ 's Reader's Poll for Best Vintage Store, is a one-stop shop for all your trendy clothing wants. In addition to the large collection of both new and vintage duds, this retro shop also sells costumes and unique handmade items from local DIY crafters. Close to the North Loop area is **New Bohemia** (4631 Airport Blvd #116, 512/326-1238, 11am-8pm daily). This thrift store is cool enough for teenagers and retro enough for the parents. The upbeat environment seems to draw customers in and keep them coming back. In here you will find old clothes one notch above Goodwill, art that appears to be inspired by the great Bob Ross (the public television guy with the afro), some furniture, and of course that classic junk-store smell that is similar to granny's living room. Hats off to whoever made the catchy sign out front. One man's junk is another man's treasure, especially at **Out of the Past** (5341 Burnet Rd., 512/371-3550, 10am-6pm Mon.-Sat., noon-5pm Sun.). This place wins the award for most stuff crammed into a small room. Browsing here is like digging through your uncle's garage and uncovering movie, music, and sports posters; collectible toys such as Star Wars, Barbie, and Hot Wheels; miniature furniture made from clothespins; and religious kitsch. They have the whole kit and caboodle—whatever that means. **Uptown Modern** (5111 Burnet Rd., 512/452-1200, 11am-6pm Mon.-Sat., noon-5pm Sun.) is Austin's emporium of mid-century modern furniture, art, and accessories. The showroom is so impressive you will wish the time machine that Austin Powers used was real so as to go back in time. Be warned that most of the items in here are pretty pricy. **Top Drawer Thrift** (4902 Burnet Rd., 512/454-5161, 10am-6pm Mon.-Sat.) is a secondhand store with a fashion sensibility. Paint-by-numbers art from the 1960s, old clothes and graphic tees, old appliances, and shelves of weird stuff are sitting around begging to find a home. ### **Recreation** Being in the most beautiful and diverse natural setting in Texas, Austin has become a favorite for lovers of the outdoors. Numerous lakes, rivers, hills, caves, trails, and parks have wisely been preserved for people to use and enjoy. There's kayaking, biking, backpacking, boating, scuba diving, spelunking, rock climbing, camping, rafting, skiing, golf, disc golf, tennis, volleyball, and numerous swimming holes—all for the taking. #### S **LADY BIRD LAKE** The greatest attraction Austin has to offer is the stretch of the Colorado River called Lady Bird Lake, formerly known as Town Lake. This wide, slow-moving river winding through the heart of downtown Austin is banked with lush vegetation, ancient trees, and wildlife, such as turtles, swans, and ducks. What makes Lady Bird Lake so remarkable? By taking just a few steps you can go from bustling urban downtown to an alternative world that's peaceful, beautiful, and natural. Canoeing on Lady Bird Lake is one of the best ways to spend a Saturday morning. Lady Bird Lake's hike-and-bike trails are some of the best urban trails in the country, with several loops over and around the lake that are in three 10-mile increments. Each loop's bridge provides a different view of Austin, the lake, and surrounding hills. Although the trails are fit for bikes as well as pedestrians, and during peak hours bikers find it pretty hard to navigate all the joggers and speed-walkers, everyone seems to sweat in harmony. The trails are all lakeside and have lots of shade, benches, water fountains, and Stevie Ray Vaughan. That's right! On the south shore of the lake is a life-size bronze statue of the Austin legend proudly standing as a sentinel with guitar in hand. Free water stations are set up at various locations along the trail. The trail is considered very safe, so no need to worry about crazy people doing crazy things. However, watch out for poison oak. The trail is laced with this evil plant, and if you are not paying attention, or decide to pet the cute dog running up to you, you may end up with some serious itching. During the peak months nice people will put little flags on branches to help identify the stuff. Other activities that take place on Lady Bird Lake include crewing, canoeing, kayaking, and stand-up paddleboarding, which are great ways to get up close to giant white swans and turtles. You might even catch a glimpse of the elusive gar. This is a long, prehistoric-looking fish with spots and a crocodile-like nose. From the water the city skyline looks pretty impressive—even breathtaking. For many locals, spending time on the lake in some sort of vessel is the best way to spend a Saturday. For visitors, planning your time here all depends on whether you want to take a leisurely walk for an hour or want to spend half of the day on the lake in a canoe or on a stand-up paddleboard. **Canoes** can be rented through **Zilker Park Boat Rentals** (512/478-3852, www.zilkerboats.com, 10am-dark Mon.-Fri., 9am-dark Sat.-Sun. in summer and early fall, 10am-dark Sat.-Sun. in winter as weather permits, $15 an hour or $45 per day) at Zilker Park near Barton Springs Pool. They have 17-foot Alumacraft, Grumman and Michicraft canoes, and both Frenzy (one-person) and Malibu Two (two-person) ocean kayaks. Paddles and life jackets are provided. If you prefer standing while traversing the lake, stand-up paddleboards can be rented from **Texas Rowing Center** (512/651-5710, www.texasrowingcenter.com, open daily during daylight hours). This boat rental go-to is located on the north side of Lady Bird Lake on the trail near Mo-Pac on Stephen F. Austin Drive across from Austin High School. The weird-looking recreational sport of standing on a surfboard has become very popular. Texas Rowing Center also has rentals for other water sports, such as canoes and kayaks. Rates for paddleboards are $15 per hour and $35 per day. Rates for kayaks are $10 per hour and $25 per day and canoes are $20 per hour and $45 per day. The most glorious way to experience the lake under the city skyline is by tour on a double-decker paddle wheel riverboat. **Lone Star Riverboat** (512/327-1388, www.lonestarriverboat.com, $10) operates this Mark Twain-style adventure March-October on weekends at 3pm. Lady Bird Lake's trails can be accessed at any of the downtown bridges and from several of the hotels on the river. The most convenient parking lot is at Auditorium Shores, on the south side of the lake at the foot of the 1st Street Bridge. However, a better place to park is in Zilker Park, on Stratford Drive under the Mo-Pac overpass. Peak recreation hours are before and after the workday, during the weekend, and on holidays. Swimming in Lady Bird Lake isn't allowed due to dangerous whirlpools. #### **LAKE TRAVIS** Just northwest of Austin along the Colorado River is the Highland Lakes area. Five winding lakes draw hordes of people from spring to fall: Lake Austin, Inks Lake, Lake LBJ, Lake Marble Falls, and Lake Travis. These lakes are wide spots in the Colorado River that became wider when six dams were built back in the 1930s and '40s. The primary function of these dams was to give water a place to go during flash floods. The lakes that have formed are all about recreation under the sun, the most popular lake being Lake Travis. Lake Travis is the second largest of the lakes and has an average surface area of nearly 19,000 acres to play on. People come from all over Texas to lie in the sun on and around Lake Travis and participate in every form of water recreation imaginable. There's swimming, boating, fishing, sailing, scuba diving, parasailing, and all kinds of water sports, as well as the only nude beach in the state. The best way to gain access to Lake Travis is through Travis County Parks locations. The most popular and largest facility is at **Mansfield Dam Park** (4370 Mansfield Dam Park Rd., 8am-dark daily, $10 for the day, $20 for primitive camping). It has four boat-launching ramps, swimming areas, barbecue grills, picnic tables, and restrooms. The other popular access to the lake is at **Pace Bend Park** (2011 N. Pace Bend Rd., Spicewood, 512/264-1482, sunrise-9pm daily, $10 for the day, $15 for primitive camping). With nine miles of Lake Travis shoreline and beautiful vistas only 45 minutes from downtown Austin, this park provides an easy way to experience the lake. You can camp, swim, hike, and launch boats. To get to Pace Bend from Austin take Highway 71 west 11 miles to RR 2322 (Pace Bend Park Rd.). Turn right on RR 2322 and travel 4.6 miles to the park entrance. If man-made water recreation is more your style there's **Shore Club Volente Beach** (16107 FM 2769, 512/258-5110, www.volentebeach.com, 10am-8pm daily Apr.-Oct., $16 for those shorter than 42 inches, $21 for those 42 inches and taller). This is the closest water park to Austin, and it has everything from waterslides to tropical-style swimming pools. To get to Volente Beach go north on Highway 183 then west on Anderson Mill Road, which turns into FM 2769. The park is seven miles up FM 2769. #### **HIKING AND BIKING** ##### **Barton Creek Greenbelt** If you want to disappear into nature but don't want to spend any time getting there, the **Barton Creek Greenbelt** (512/974-1250, 5am-10pm, free) has it all. Second in popularity only to Lady Bird Lake, this well-preserved stretch of wilderness along Barton Creek has mountain biking, hiking trails, swimming holes, and rock climbing. The Greenbelt is about 7.9 miles long and consists of 809 acres. The terrain is mostly rough with sheer cliff walls, lush vegetation, and a creek that is at its peak in the spring. Once you descend into the Greenbelt you feel far away from civilization, provided you don't look up and see the occasional home on the cliff. The trails are rocky and semi-primitive and cut through scenic wildflowers, trees, limestone cliffs, caves, meadows, swimming holes, and waterfalls. The trail varies from narrow ledges to wide walkways. Wildlife is abundant, which can make the park sound and look like the Amazon. The trail starts above Barton Springs Pool at Zilker Park and extends westward past Loop 360 to Lost Creek. There are several trailheads throughout the park, mostly in adjoining neighborhoods. The three easiest places to access the Greenbelt are **Spyglass Trail Access** on Spyglass Drive just off Mo-Pac; **Loop 360 Trail Access** at Loop 360 just south from Mo-Pac; and **Gus Fruh Trail Access** at 2642 Barton Hills Drive (wheelchair-accessible). Dogs are permitted on leash only. Mountain bikers must yield to hikers and stay on designated trails. In spring, creek crossings may require wading through water. When enjoying the Barton Creek Greenbelt, remember to pack your trash. Call for up-to-date trail conditions. ##### **Mayfield Park and Preserve** One of the more off-the-beaten-path outdoor areas is **Mayfield Park and Preserve** (3505 W. 35th St., 10am-10pm daily, free). This often-forgotten park, on a small stretch of Lady Bird Lake, is perfect for a casual evening stroll for families and couples. The winding network of paths twists through old groves of oak trees, across several footbridges, over small creeks, and through a lakeside grove of moss-draped oaks. Being next to the historic building of Laguna Gloria art museum just adds to the romance. The park has a paved parking lot, restroom facilities, and drinking fountains. The best way to get to Mayfield is by heading west from the 35th Street exit off Mo-Pac. ##### **Wild Basin Wilderness Preserve** The perfect antidote to a busy schedule is **Wild Basin Wilderness Preserve** (805 N. Capital of Texas Hwy., 512/327-7622, www.wildbasin.org, trail hours sunrise-sunset, office hours 9am-4pm Tues.-Sun., $3). Smaller in scope than the Barton Creek Greenbelt and less crowded than Lady Bird Lake, Wild Basin is a favorite secret Austinite retreat. The 2.5 miles of hiking trails on 227 acres are well maintained and generally quiet. The trails take you through a valley, over streams, and to a panoramic view. The trail also includes informative trail markers that give insight into the native plants and animals that live in the region. Interpretive trail brochures are available at the trailhead. Dogs and bikes aren't allowed. The entrance to Wild Basin is right off of Loop 360, which makes it an easy getaway. **Naked in Texas** There's only one place in Texas where you can "be as proud as you can be, of your anatomy" in public, and that's at **Hippie Hollow** on Lake Travis. This little Garden of Eden on the lake is the only clothing-optional public park in the state. The park is in a secluded spot that offers spectacular views of Lake Travis, a paved walking trail, and a hiking trail that hugs the cliffs. Although the shoreline itself is pretty steep and rocky, Hippie Hollow is good for sunbathing, swimming, and fishing. Whether you're a first-timer curious about strutting in the nude, or a dedicated nudist, only the serious are welcome here—it's not a place to gawk or giggle at people. Speaking of gawking, one time a boat passing by Hippie Hollow capsized because everyone rushed to one side of the boat to get a better view. The park is 20 minutes from I-35. From Mo-Pac or I-35, take RM 2222 west to Highway 620. Turn left on Highway 620 and go 1.3 miles. Turn right at the first traffic light onto Comanche Trail. Travel two miles to the park entrance on the left. A paved parking area, drinking water, and restrooms are available. #### **HORSEBACK RIDING** At the very top of the short list of things a traveler to Texas should do at all costs is a trip on horseback through the countryside. Fortunately, there is an easy way to include horseback riding in your visit to Austin without dedicating an entire day venturing way out into the Hill Country. On the southern edge of Austin is **Texas Trail Rides** (9606 Farm to Market 1826, 512/697-9722, www.texastrailrides.com). Setting aside just two hours, wannabe cowboys and cowgirls can get acquainted with a horse, saddle up, and enjoy an awe-inspiring trail ride, all before lunch. Their signature Ranch Trail Ride is a guided tour through a nature preserve that includes a water crossing, scampering up bluffs, spectacular views, and fields of wildflowers, and there's even one point on the trail where the Austin city skyline is visible in the distance. The Ranch Trail Ride takes about two hours and costs $125 per rider. #### **ROCK CLIMBING** Out of the four basic types of rock climbing—sport climbing, traditional climbing (aka Trad), gym climbing, and bouldering—sport climbing is, by far, the most popular and best represented in the Austin area. The **Barton Creek Greenbelt** has a decent number of routes that have their own names, like Seismic Wall, Gus Fruh Wall, and New Wall. They are all very short (30-40 feet max), but really, you can't beat it considering that you don't have to leave the city limits. This sort of "urban cragging" (climber speak for climbing in urban areas) has really put Austin on the map for being a place where you can climb right after work and still make happy hour somewhere. **The Austin Rock Gym** (8300 N. Lamar Blvd., Ste. B-102, and 4401 Freidrich Ln., Ste. 300, 512/416-9299, www.austinrockgym.com, noon-10pm Mon.-Fri., 10am-10pm Sat., 10am-7pm Sun.) is the only gym that is exclusively dedicated to climbing. There are a couple of great online resources, such as www.bloodyflapper.com. Here you'll find lots of good information, a bulletin board for hooking up with other climbers, and great descriptions of all the rock-climbing spots in the Austin area. Another website that has some good info is www.texasclimbers.com, which has a set of rough topographical maps and area descriptions that can be really handy. **Whole Earth Provision Company** (1014 N. Lamar Blvd., 512/476-1414, 10am-8pm Mon.-Fri., 10am-8pm Sat., 11am-6pm Sun.) offers an extensive line of climbing equipment and shoes. There aren't a whole lot of places where you can rent used gear in town, since climbers' lives depend on the condition of their gear. #### **SPELUNKING** If you enjoy being in dark places in the belly of the earth, Austin has some good caves to explore. There are two known caves in town. First, there's **Airman's Cave** in the Barton Creek Greenbelt. This is the longest known cave in the county. Here you'll see the Keyhole, which is a tight space that can freak out even the most advanced spelunkers, and the Aggie Art Gallery, which is a room full of clay art that has been preserved in this underground environment. The other cave in town is at **Goat Cave Preserve** (3900 Deer Run) in southwest Austin. For more information on caving in Texas check out www.utgrotto.org. #### **GOLF** Austin is a golf town—after all, it has been home to Harvey Penick, the legendary golf pro and teacher, as well as Ben Crenshaw, Tom Kite, and Hilary Lunke, a U.S. Women's Open champion. There are world-class courses in the area, both public and private. The following are the best golf courses in Austin. **Hancock Golf Course** (811 E. 41st St., on 38th St., 512/453-0276, dawn-dusk daily, $14 for 9 holes) was built in 1899 and is the oldest course in Texas. The 9-hole, par 35 course is in the heart of Austin in the Hyde Park area. No reservations are required. Another course that's been around for a long time is **Lions Golf Course** (2910 Enfield Dr., 512/477-6963, sunrise-sunset daily, $16-29). This 6,001-yard, 18-hole, par 71 course requires reservations. **Grey Rock Golf Club** (7401 Hwy 45, 512/288-4297, greyrockgolfandtennis.com, hours vary by season, call ahead) is one of the best public courses in Texas. A picturesque Hill Country setting, covered biergarten, and a casual yet elegant clubhouse make this a safe bet for visiting golfers. The Salt Lick barbecue restaurant is nearby, and a stop here after golf would finish your day perfectly. In South Austin there's the tiny but popular **Butler Park Pitch and Putt** (201 Lee Barton Dr., 512/477-4430, $9-11). This 9-hole, par 27 course is perfect for getting in a quick golfing fix. You only need three clubs carried in hand and a couple of golf balls in your pocket. The best golf gear shop is **The Golf Club** (1315 W Ben White Blvd., 512/916-4653). **Sporting Goods Stores** • Sports & Outdoor Recreation: **REI** (601 N. Lamar Blvd., 512/482-3357; 9901 N. Capital of Texas Hwy., Ste 200, 512/343-5550) • Hiking & Outdoor Recreation: **Whole Earth Provision Company** (2410 San Antonio St., 512/478-1577) • Running & Jogging: **Luke's Locker** (115 Sandra Muraida Way, 512/482-8676) • Canoe & Kayak Gear: **Austin Canoe and Kayak** (9705 Burnet Rd., Ste. 102, 512/719-4386) #### **DISC GOLF** When driving past Pease Park on North Lamar Boulevard, you may notice small gatherings of young folks throwing Frisbees into chain hoops with complete concentration, solemnity, and earnestness. This is the fairly young outdoor recreational sport called disc golf, also known as Frisbee golf. Austin has several courses that are very popular to folks who play this niche sport. On the surface this sport seems a bit funny, but people take this very seriously. The most centrally located course is at **Pease Park** (Lamar Blvd. at 24th St.). Other courses in town are at **Bartholomew Park** (51st St. near I-35 in East Austin) and **Mary Moore Searight Park** (Slaughter Ln. in South Austin). For more information, check out www.hookshot.com. #### **SPECTATOR SPORTS** Austin may not have a major-league franchise, but that doesn't stop this sport-loving town from hosting some of the biggest sporting events in the state. Most of the athletic world in Austin circles around the UT football and baseball teams; both are among the top programs in the nation. UT's sports program also includes tennis, golf, swimming, volleyball, track and field, and women's softball. Besides university games, Austin is also home to the popular minor-league baseball team Round Rock Express, a hockey team called the Ice Bats, and the outlandish return of women's roller derby, which is becoming a wildly popular cult spectator sport. ##### **Football** From the small rural towns where absolutely every citizen can be found in the stands on Friday night to the pro-football mania of the Cowboys, football is Texas's version of the Roman gladiators. Austin happens to be home of **UT Longhorns Football** (www.texassports.com), one of the most popular college football teams in the United States. This excellent program commands higher ticket prices than pro football teams, and the networks have hopped on this bandwagon and paid handsome amounts to broadcast Longhorn games. Football season is September-November, and home games take place at **Darrell K Royal-Texas Memorial Stadium** (1701 Red River St.). Tickets are very hard to get, and the ones available are sold as season passes, but it's possible to land tickets for one event for $55-75. Tickets can be purchased at the UT Athletics Ticket Office (2100 San Jacinto Blvd., on the UT campus), by phone at 512/471-3333 or 800/982-2386, and online at www.texasboxoffice.com. ##### **Baseball** Baseball may not be as big as football, but it still has an important place in Austin. The **UT Longhorns Baseball** team produces some great ballplayers, some of whom go on to the majors. The Longhorns have won six national championships. UT Longhorns baseball season is February-June, and games take place at Disch-Falk Field (corner of MLK and I-35). Tickets are $8-12 and can be purchased at the UT Athletics Ticket Office (2100 San Jacinto Blvd., on the UT campus), by phone at 512/471-3333 or 800/982-2386, or online at www.texasboxoffice.com. The other baseball team worthy of mention is the **Round Rock Express** (www.roundrockexpress.com). This AAA affiliate of the Texas Rangers was founded by Nolan Ryan and computer kingpin Michael Dell. The Express is gaining popularity to such an extent that they often break minor-league attendance records. The team plays about 70 home games April-September at the **Dell Diamond** (3400 E. Palm Valley Rd.) in Round Rock. ##### **Basketball** The hoops scene in town is dominated by **UT Longhorns Basketball,** with both men's and women's teams. Both men's and women's basketball games take place at the **Frank Erwin Center** (1701 Red River St., 512/471-7744). Tickets run $6-15 and can be purchased at the UT Athletics Ticket Office (2100 San Jacinto Blvd., on the UT campus), by phone at 512/471-3333 or 800/982-2386, or online at www.texasboxoffice.com. ##### **Roller Derby** One of Austin's hottest and most distinctive forms of entertainment is the roller derby. Put on by **Texas Rollergirls** (www.texasrollergirls.com), this skater-owned and -operated league comprises four very competitive teams: Hotrod Honeys, Honky Tonk Heartbreakers, Hell Marys, and the Hustlers. The roller derbies take place every spring and summer at **Austin Convention Center** (500 E. Cesar Chavez St.) and skating rinks throughout Texas. Typically there are two bouts per night, and every bout starts at 6pm, but you should plan on showing up an hour early. The Convention Center has two parking garages, on 2nd and 5th Streets. Street parking downtown is also available. General admission is $15 and kids are charged $5. **Roller Derby Revival** The most outrageous form of entertainment of the golden 1970s, roller derby, is back! The skates are laced up, the short shorts are donned, the roller rink is aflame, and the catfights have begun. But instead of disco, punk and heavy metal are the soundtrack to this over-the-top spectacle. Austin's unique and dazzling form of underground entertainment is put on by a legion of feisty women from all walks of life. A few years back these ladies started skating for fun and found that people loved the idea of roller derby and would pay to see them beat each other up in the rink. Seeing a grassroots opportunity to resurrect a spectacle sport that died with disco, they organized and started taking it seriously. A flurry of attention ensued, such as a cover story in _Rolling Stone_ and an A&E TV show. Today there are two Austin-based, skater-owned and -operated leagues: **Texas Lonestar Rollergirls** and **Texas Rollergirls.** A sampling of team names includes: Hotrod Honeys, Cherry Bombs, Honky Tonk Heartbreakers, Hell Marys, Holy Rollers, and the Texecutioners. With all manner of theatrics, these ladies get dressed up in crazy getups composed of fishnet stockings, plaid skirts, and war paint, and take on various personalities, such as Lucille Brawl, Rice Rocket, Kitty Kitty Bang Bang, Cherry Chainsaw, and Dinah-Mite, to name a few. So what exactly is roller derby? Don't expect this to be a WWE-style choreographed event. This is real women going in circles at high speeds on skates, knocking each other down to win. In brief, here's how it works. There are three positions: the pivot sets the pace for the pack and is the last line of defense; blockers try to stop the jammer and knock around the opposing team's blockers; and the jammer sprints through the pack, scoring points by passing members of the opposing team. The pack starts with a pivot from each team in front, three blockers from each team in the middle, and a jammer from each team in the back. When the whistle blows, the pack takes off, and on a second whistle, the jammers start fighting their way through the pack in an attempt to be named lead jammer. The jammers lap the pack, and when they reenter the pack they receive one point for each member of the opposing team that they pass. A jam lasts a maximum of two minutes, but the lead jammer has the right to call off the jam at her discretion. If you're feeling brave the best seating is rinkside. There are no rails, and very few seats, so plant yourself down on the rink just outside the ring of flashing lights. At rinkside you can get up close to the action, so much so that you can smell the BO as it mixes with the smell of popcorn. Always be on guard and keep your eyes on the women on skates. They often crash, wipe out, or barrel off into the crowd. Spacing out even for one moment can cost you your fingers. The roller derbies take place every spring and summer at **Palmer Event Center** (900 Barton Springs Rd.) and **Austin Convention Center** (500 E. Cesar Chavez St). Ticket prices are usually $15 a seat and doors usually open at 6pm. A band always performs at halftime. For times and dates and more information check out www.txrollergirls.com and www.txrd.com. #### **TOURS** ##### **Walking Tours** Austin is best imbibed by strolling around on foot. Most points of interest are within walking distance of one another, and the town is easily traversed thanks to good city planning and pedestrian-friendly motorists. Free guided walking tours are put on by **Austin Convention and Visitors Bureau** (512/454-1545 or 866/462-8784, www.austintexas.org). They offer tours of Congress Avenue, 6th Street, the state capitol grounds, and Bremond Block. Tours are offered March-November at the capitol's south steps and take about an hour. Call for tour schedules and information. Austin has enough ghosts in its closet that **Austin Ghost Tours** (512/853-9826, www.austinghosttours.com, $20) came along to give these ghouls their due recognition. Tour organizers have pieced together the past and organized several fascinating tours that include the Haunted 6th Street Tour, Servant Girl Annihilator Tour, and Graveyard Tour, to name a few. Tour guides walk the curious through the streets of Austin and unfold the darker side of town. Tours are about 90 minutes and take place outside for the most part, and all are wheelchair-accessible except for the Haunted Pub Crawl Tour. Tickets generally cost $20. Reservations are required for all tours; call in advance. ##### **Sightseeing Cruises** The best view of Austin is from Lady Bird Lake, and the best way to be on the lake is by floating in an authentic double-decker paddle wheel riverboat. **Lone Star Riverboat** (512/327-1388, www.lonestarriverboat.com) offers narrated sightseeing cruises March-October on Saturday and Sunday at 3pm. Boarding begins at 2:15pm and costs $10 for adults, $8 for seniors over 60, and $7 for children under 12. Lone Star also offers Friday night tours at 10:30pm (boarding time 9:45) for $10. You can BYOB for this cruise. Along with the riverboat, Lone Star also has a pontoon boat that offers a sunset cruise for a buck less. This is the best seat in town for watching the bats fly out of Congress Avenue Bridge. Departure time for the evening pontoon boat cruise is 30 minutes before sunset and the cruise costs $10. Also offering aquatic tours on Lady Bird Lake is **Capital Cruises** (512/480-9264, www.capitalcruises.com). Public sightseeing cruises depart Saturday and Sunday at 1pm, and bat-watching cruises depart before sunset. Rates are $10 for adults, $8 for seniors, and $5 for kids 3-12. Also available is a dinner cruise with cocktails and entertainment. Rates range $26-100 depending on options. The local phone book has a 20 percent discount coupon. Both Capital Cruises and Lone Star Riverboat offer cruises March-October, and docks for both are on the south side of Lady Bird Lake between the 1st Street Bridge and Congress Avenue Bridge near the Hyatt Regency. ##### **Land Tours** **AO Tours** (512/659-9478, www.aotoursaustin.com) offers great comprehensive 90-minute tours of town in a brightly colored minibus. Tours include more than 30 points of interest and are narrated by a father-son team of Texas history buffs who know their stuff. Tickets are $25 for adults and $17 for children 12 and under, and can be purchased online. Departure locations are 615 Congress Ave. (Wild About Music) or 602 E. 4th Street (Austin Visitors Center). Be sure to arrive 20 minutes early. Perhaps the most touristy thing to do in Austin is to take the amphibious tour of town with **Austin Duck Adventures** (209 E. 6th St., 512/477-5274, www.austinducks.com). Board a domesticated British Alvis Stalwart (amphibious military vehicle from the 1960s) and traverse both land and water, exploring Austin's main sights, such as the state capitol, Congress Avenue, and 6th Street, before splashing into Lake Austin. For a nostalgic chug into the past the **Austin Steam Train** (401 E. Whitestone Blvd., Ste. A-103, Cedar Park, 512/477-8468, www.austinsteamtrain.org) is a great way to see the beautiful countryside north of town. The Austin Steam Train Association operates two classic steam trains on a leg of the original Southern Pacific railroad between Austin and the town of Llano. The boarding location is in Cedar Park, which is 20 minutes northwest of Austin. In addition to regular hours (9am-4pm Mon.-Fri.), the ticket office is also open 90 minutes before each train departure. Although walk-up tickets can be purchased at the boarding locations, advance reservations are recommended. Fares range $38-53, depending on the route and the train. Call or go online for schedules and fares. A horse-drawn carriage is the most romantic way to see downtown, provided you don't feel guilty for making the horses sweat. Companies vying for your business include: **Austin Carriage Service** (512/243-0044, www.austincarriage.com), **Angeli Carriages** (512/659-0591, www.acarriage.com), and **Die Gelbe Rose Carriage** (512/477-8824). The carriages are drawn by Belgian and Percheron horses and charge $100 per hour and $50 for half-hour tours. Carriages can always be seen around downtown, especially in the evenings. You can schedule a ride or just pick one up out front of the Driskill Hotel on 6th Street, or you can call and have one dispatched to a restaurant, nightclub, or wherever you are. Drivers can include narrative on the tours, but they are pleased to shut up if couples want a more romantic ride. A new and unusual way of touring the town is on a Segway Personal Transporter (PT). **Gliding Revolution** (512/495-9250, www.glidingrevolution.com, $66 for a downtown tour) offers these two-wheel tours complete with Segway training and a standing jaunt through the downtown sights with a tour guide. If a tour of building facades and Lady Bird Lake is too mundane for you, consider going on the Ghost Tour for $59. ##### **Adventure Tours** A brilliant idea has come to fruition with **Cypress Valley Canopy Tours** (1223 Paleface Ranch Rd., Spicewood, 512/264-8880, www.cypressvalleycanopytours.com). Out in the Hill Country in Spicewood, just 30 miles west of Austin, this outfit offers an adventure on wires high up in the trees. The tours include three sky bridges and six zip lines that land on tall platforms amid the trees. Guides prepare the adventurous by running them through a detailed orientation explaining the gear and the tour. Tours cost $75 per person. Reservations are necessary. Special rates are available for families, but children under 10 are not permitted. During the summer the facility is open every day except Monday, and in the fall and spring it's open only on weekends. ### **Food** In Austin, eating out is a pleasure and a pastime. There's an endless amount of breakfast tacos, barbecue brisket, microbrews, organic veggies, and confections waiting to be devoured, and it's "all good." Austin is chock-full of hundreds of eateries, many of which have their own unique story and funky spin on ambience and food, keeping in step with the town's flavor for weirdness. On occasion the gimmick of the restaurant is better than the food. Although you might think that a Texas town such as this would be all about meat and potatoes, Austin takes care of the herbivores too. In 2013 Paul McCartney himself awarded Austin for being the most accommodating city in the country for vegan diets. The former Beatle said, "The influx of forward-thinking musicians and techies, the thriving University, and the food trucks all over the city run by young veg-friendly hipsters have made Austin the absolute cutting-edge place for green eating." One word of caution is offered: Your money goes a long way in Austin's eateries, making it easy to eat out until you either burn out on restaurants, burn a hole in your wallet, or simply explode. With the exception of fine dining, your average meal will cost somewhere between $10 and $15. Hours of most establishments are typical: Breakfast joints open around 6am, lunch is generally served 10:30am-4pm, and dinner happens 5pm-10pm, with some eateries staying open as late as midnight. So come hungry—all the eateries mentioned here are sure to satisfy. #### **AMERICAN AND DINERS** Austin is inundated with burger joints and diners that offer up hearty plates of American standards. Texas has proven that anything can be chicken fried and that acid reflux is a virtue. Due to Austin's love of health, there are some eateries that offer healthier versions of these standard plates. But let the salt pour, the oil flow, and the butter fry, 'cause it's all about good old-fashioned sodium and cholesterol at some of these greasy spoons. **Food Truck Scene** Austin has fallen head over wheels for the new food truck craze. Carts, trucks, silver bullets, and even wagons are strategically set up all around town, making a variety of foods readily available. Besides amazing taco trucks, you can also find trucks that serve up Indian food, duck, _pho,_ crepes, and even cupcakes. There are even a couple of farm-to-market trucks that specialize in fresh and organic foods. New carts are popping up everywhere, almost daily it seems. Although trucks can be found on sidewalks and street corners all over downtown, there are miniature food trailer parks on South Congress, South Lamar, South 1st, and on Red River just south of downtown. The best way to sample food truck cuisine is by attending Austin's festival dedicated to these mobile food vendors, **Gypsy Picnic Trailer Food Festival,** which takes place in the fall. It should be noted that most of these trailers don't serve alcohol, and some are BYOB establishments. Also, it's a good idea to show up with cash, not plastic. The best resource for food truck info, hours, maps, and reviews can be found online at www.austinfoodcarts.com. Here is a list of some local favorites. • **East Side King** (1618½ E. 6th St. behind Liberty Bar and The Grackle, 512/407-8116) has unusual Asian fusion plates, such as fried beets, brussels sprout salad, and pork belly buns. • **Four Brothers ATX** (2201 S. 1st St., 512/550-5650) serves arepas and other Venezuelan favorites in a parking lot with outdoor picnic tables. • **Hey Cupcake** (1720 Barton Springs Rd. and 1511 S. Congress Ave., 512/476-2253) has—you guessed it—cupcakes! • **Holy Cacao** (1311 S. 1st St., 512/851-2253) serves cake balls and other sweet stuff. • **Kebabalicious** (1720 Barton Springs Rd. and W. 3rd St. at Congress Ave., 468-1065) has chicken, beef, and lamb kebabs and other Middle Eastern foods. • **La Barbecue** (1906 E. Cesar Chavez St., 512/605-9696) is the best food truck for brisket, ribs, and barbecue sandwiches. • **Not Your Mama's Food Truck** (2209 E. Cesar Chavez) features fancy fried comfort food. • **Luke's Inside Out** (1109 S. Lamar Blvd., 512/589-8883) features globally influenced griddled sandwiches, like brisket banh mi and Szechuan chicken. • **Torchy's Trailer Park** (1311 S. 1st St., 512/366-0537) is the best taco truck in town. For the fickle person who has a hard time deciding what to eat, **Austin Java** (1206 Parkway at 12th and Lamar, 512/476-1829, 301 W. 2nd St., 512/481-9400, and 1608 Barton Springs Rd., 512/482-9450, www.austinjava.com, 7am-11pm Mon.-Fri., 8am-11pm Sat. and Sun., $10) has an eclectic menu that has something for everyone for either breakfast, lunch, or dinner. If after looking at the soups and salads you still can't decide what you want, you can piece together a lunch combo that suits your taste buds. Thai sesame salad, smoked-gouda bacon burger, and Cajun-blackened crawfish pasta are among the favorites. Then there's the wide variety of organic coffees of various blends, flavors, and colors. In Old North Austin everybody loves **Billy's** (2105 Hancock Dr. at Burnet Rd., 512/407-9305, 11am-midnight Mon.-Fri., 11am-1am Sat., noon-midnight Sun., $12). Here sports fans, neighborhood locals, and families can eat burgers, drink the best beers on tap, and see Billy sweeping the floor. Happy hour is 2pm-7pm Monday-Friday. There's also a huge deck outside, beer specials, a jukebox, and a pool table, and the game on TV. For the cheapest meal in town there's **Dirty Martin's** (2808 Guadalupe St., 512/477-3173, 11am-11pm daily, $8). Dirty's is one of the older continuously owned and operated eateries in Austin. This doesn't necessarily mean that as with wine, the food at Dirty's is better with age. But the onion rings and fries are homemade, the hamburger meat is fresh, and the shakes and malts are terrific. S **Hoover's Cooking** (2002 Manor Rd., 512/479-5006, 11am-10pm Mon.-Fri., 8am-10pm Sat.-Sun., $12) is a classic place to eat barbecue on Sunday after church in East Austin. Hoover describes his cooking influence as "Home cooking—nicely seasoned vegetables, smoked foods, pan-fried dishes, and spicy foods with a nod toward Tex-Mex and Cajun." Hoover's has the best meatloaf in Austin and the Jamaican jerk chicken is sent from Jah. This is a popular brunch and breakfast spot so a wait may be necessary, but it's well worth it. After going through many decades of transformations (from drive-in to Mexican to lounge), **Hut's Hamburgers** (807 W. 6th St., 512/472-0693, 11am-10pm daily, $12) finally settled on the American staple—hamburgers. There's a reason Hut's is always packed at mealtime. The menu is "outside the bun" with items such as the Ritchie Valens Burger: guacamole, grated cheese, chopped tomatoes, onions, and jalapeños. Their vintage/retro decor of seminude photos, pop memorabilia, sports heroes, and music posters only adds to this distinctive flavor. Another burger joint that begs mention is **Hopdoddy Burger Bar** (1400 S. Congress Ave., 512/243-7505, 11am-11pm daily, $15) on South Congress Avenue. The focus of the menu is the perfection of pairing beer and burgers. The plates are sophisticated and creative, and the beer selection is high caliber. You must be forewarned though: The lines are super long to even get in the door, the wait is absurdly long, and the process to get the food is not conventional. Patience is required for all the above, but it's worth the hassle. Favorite burgers are The Greek, Buffalo Bill, and The Diablo (hot and spicy), and the truffle fries are amazing. **Magnolia Cafe** (2304 Lake Austin Blvd., 512/478-8645, and 1920 S. Congress Ave., 512/445-0000, <http://themagnoliacafe.com>, 24 hours daily, $10) is a good bet for a good dish any time of the day or night. Great breakfasts, hamburgers, sandwiches, soups, and salads, as well as some Tex-Mex dishes, can be ordered any time, as this is Austin's best 24-hour grub facilitator. The best milk shake in town happens to be in an inconspicuous establishment—the pharmacy. Decades ago **Nau's Enfield Drug** (1115 W. Lynn St., 512/476-1221, 7:30am-8pm Mon.-Fri., 8am-7pm Sat., $8) was the place to get a burger, a shake, and your prescriptions, and nothing has changed in the past half a century. The hamburger is one of the world's most profound culinary creations. It is inexpensive yet rich with flavor, it is globally accepted yet markedly strange in how it is made, how it is eaten, and what it tastes like. I have no fear in going out on a limb by saying that Austin is home to the world's greatest hamburger. It is cooked up at a burger joints scattered around town called **P. Terry's** (404 S. Lamar Blvd., 512/473-2217, 3303 N. Lamar Blvd., 512/371-9975, 11am-11pm daily, $8). The owner opened his first burger stand near Barton Springs after reading the book _Fast Food Nation._ The burger is simple and old-fashioned, and made of 100 percent all-natural Black Angus beef and all-natural ingredients. The focus here is simplicity, quality, and taste, so don't expect a flashy menu. The architecture for each P. Terry's location is unique, retro, and pretty cool. The crossroads of Louisiana and Texas is on North Lamar at **Shoal Creek Saloon** (909 N. Lamar Blvd., 512/474-0805, 11am-midnight daily, $12). This sports bar was transformed when chef Bud George moved in from Louisiana, bringing with him authentic Cajun cuisine. Gumbos, fried catfish, crawfish étouffée, oysters, and hush puppies flow like the bayou. Wait—does the bayou flow? Daily specials are a great value, and happy hour is 11am-7pm Monday-Friday. At **South Congress Cafe** (1600 S. Congress Ave., 512/447-3905, 10am-4pm and 5pm-10pm daily, $13) the approach to things is minimalist. They don't believe in dramatic decor, fancy signs and logos, or anything of a commercial nature. They simply offer quality food and service in a modern, sophisticated atmosphere. Items on the menu vary from crab cakes to pan-seared tuna salad, which sounds expensive, but don't be deceived by the fancy-sounding menu—it's affordable. **Star Seeds Cafe** (3101 N. I-35, 512/478-7107, 24 hours daily, $7) is one of those places in town that completely personifies Austin. This 24-hour joint has no pretense, just past tense, as it seems to be frozen in time. Here you can eat greasy, nothing-fresh diner food, such as sandwiches, burgers, nachos, and breakfast. Effortlessly funky and offbeat, Stars is a great place to eat after waking up at noon, without showering or brushing your teeth. If you've just finished a tour of the Texas State Capitol and you're fixin' to eat, stroll down the street to the S **Texas Chili Parlor** (1409 Lavaca St., 512/472-2828, 11am-2am daily, $10). This sports bar is where Texas politicians, UT students, and UT sports fans converge to enjoy a beer and some food. Obviously it is known for the chili, which comes in three variations of spiciness: X for mild, XX for medium, and XXX for habanero hell. They may even make you sign a release form when you order the XXX. Note for non-Texans: There are no beans in Texas chili, just meat and sauce. One restaurant that is a historic landmark in its own right is **Threadgill's Home Cooking** (301 W. Riverside Dr., 512/472-9304, 11am-10pm Mon.-Thurs., 11am-10:30pm Fri.-Sat., 10am-9:30pm Sun., $12). Founded in 1933 by bootlegger Kenneth Threadgill after obtaining the county's first alcohol license, this down-home kitchen became a local favorite for hootenannies and old-time cookin'. In the 1960s, Threadgill's was one of Austin's cultural epicenters for live music. Hippies and rednecks alike would converge here to watch the cultural revolution go down. It's said that Janis Joplin even developed her unique singing style here. As for the down-home cooking, it's just like granny makes it—lots of butter and oil, meat and potatoes, sodium and white bread. Threadgill's is especially famous for its meatloaf, chicken-fried chicken, and chicken-fried steak. **Upper Crust Bakery and Cafe** (4508 Burnet Rd., 512/467-0102, 6:30am-6:30pm Mon.-Fri., 7am-5pm Sat., 7am-1pm Sun., $7) serves gorgeous baked goods and sandwiches. You don't have to take my word for it; the _Austin American-Statesman_ ranked the avocado sandwich one of the top 10 sandwiches in Austin. This is easily the best place in town for any kind of sandwich. #### **BARBECUE, STEAK, AND SAUSAGE** Eating meat in Austin can be a profoundly gluttonous experience. At many barbecue joints you order brisket by the pound, choose from a selection of sides such as coleslaw, beans, and potato salad, and eat it all off butcher paper. This approach to eating can pose a hazard to those whose eyes are bigger than their stomachs. Texans love their beef, and you will too at the following restaurants. **Austin Land and Cattle Co.** (1205 N. Lamar Blvd., 512/472-1813, 5:30pm-10pm Sun.-Thurs., 5:30pm-11pm Fri.-Sat., $30) is Austin's most popular steak house. Although the menu offers enough choices for everyone (except the vegetarian), people come here for beef. It can be served up in many different ways, but the best is the 22-ounce bone-in rib eye or sirloin cooked medium rare. The white stucco walls and exposed-beam ceiling make for a comfortable environment. The staff knows the menu and can guide you through your beef-eating experience. As for the sides, they tend to be a notch above your average steak house, such as baby spinach leaves sautéed in olive oil and carrots julienne. The portions are so big you might as well ask for a to-go bag when you order. S **Banger's Sausage House & Beer Garden** (79 Rainey St., 512/386-1656, 4pm-11pm Mon.-Wed., 11am-2am Thurs.-Sat., 11am-2am Sun., $13) is a must-eat Austin establishment. Here are a few things that make a perfect Austin dining experience: exotic game sausages and a wall of beer on tap, all consumed under trees on picnic tables. This is the only place where you can sample unusual sausages such as wild boar, duck, bacon and fig, and the flavorful "currywurst." Jalapeño mac-and-cheese is a pleasant surprise too. Every weekend a random event takes place, like yodeling, baton twirling, or pig roasting. And here's a tip for the late-night partiers: If you're out on the town and it's 11pm and you decide you're hungry, this place is profoundly satisfying. Banger's creative sausage plates have to be paired with a locally made beer. If you have a car to get there, the **County Line BBQ Restaurant** (5204 FM 2222, 512/346-3664, 11:30am-2pm and 5pm-9pm daily, $14) is a terrific spot on Bull Creek near Lake Austin that feels rural but is close to town. The waterfront patio looks out onto limestone cliffs and dense tree cover. After chowing down on great barbecue everyone will have a blast feeding the ducks and turtles that come right up to the dock. The food is a little pricy but very tasty. In South Austin there's **Green Mesquite** (1400 Barton Springs Rd., 512/479-0485, 11am-10pm Sun.-Thurs., 11am-11pm Fri.-Sat., $10). Standard, inexpensive barbecue, burgers, and some Cajun food are what's on offer at this staple Austin lunch and dinner joint. It's near Zilker Park and has a friendly staff, a relaxed atmosphere, and live music on Friday, Saturday, and Sunday nights. This is a good place for families with children. Fancy and barbecue usually are a contradiction in terms. However, S **Lamberts** (401 W. 2nd St., 512/494-1500, lunch 11am-2:30pm Mon.-Fri., dinner 5:30pm-10pm Sun.-Wed. and 5:30pm-10:30pm Thurs.-Sat., brunch Sat.-Sun. 11am-2pm, $12) has concocted a combination that works. A location in the up-and-coming 2nd Street shopping district makes Lamberts an easy springboard for a night on the town. Besides barbecue, chefs Louis Lambert and Larry McGuire have put together some classic dishes in true Austin form—casual but classy—such as steak and seafood with family-style sides accompanied by locally made microbrews. Downtown Austin has been in dire need of a kick-ass barbecue joint. **Franklin Barbecue** (900 E. 11th St., 512/653-1187, 11am-1pm Tues.-Sun., $10) has risen out of the food truck/trailer trend to deliver the best cracked-peppercorn brisket and ribs in central Austin. The founder started as a Texas kid helping out with his dad's barbecue joint, then did the trailer thing, and now has a wildly successful restaurant going. The brisket slices are thick and the pork ribs are salty with the right amount of large cracked pepper chunks. The ribs are so tender you don't have to roll up your sleeves and get messy to eat 'em. Just pull the meat off with your plastic fork. The vibe in here is unpretentious but with the right amount of retro to be comfortable, the music is old country classics playing loud, and local Live Oak beers are on draft. There's only one drawback: Franklin is only open until it sells out of food. Most days this happens by 1pm. There's also **Iron Works** (100 Red River St., 512/478-4855, 11am-9pm Mon.-Sat., $9), a local favorite for barbecue. Set in a historic iron shop, this is the one meat joint where you can counterbalance all the beef with all-you-can-eat salad. Nearly every barbecue spot in the state has a shingle out front that claims, "Best BBQ in Texas." But **Rudy's Country Store and BBQ** (2451 Capital of Texas Hwy., 512/329-5554, and 11570 Research Blvd., 512/418-9898, 7am-9:30pm daily, $10) gladly proclaims "The Worst Bar-B-Q in Texas." Don't be fooled by this slogan and the fact that Rudy's is a chain, albeit a small Texas franchise. The barbecue is fabulous and the beans are musical. No dishes required—just fingers, a fork, and the need for beef. After fully glutted, wash your hands and face in the industrial-size kitchen sink in the dining room. The area's best barbecue is provided by S **The Salt Lick** (18300 FM 1826, Driftwood, 512/858-4959, 11am-10pm daily, $15). It's so far out of town that it's in another town, but that shouldn't stop you from enjoying an Austin tradition. Eating here is one of the great experiences Central Texas has to offer. Here's why: It's located in an old limestone ranch house, the recipe is ancient, the barbecue pit is the dining room, you bring your own alcohol, and the barbecue is brutally good. The menu also offers sausage, turkey, ribs, the usual sides, white bread, and those pickles that every barbecue restaurant seems to have. Warning: There is no air-conditioning. For some this adds to the appeal, but for those who fear perspiration it can ruin their day. Otherwise, sit in front of the fan, relax, and eat beef. Salt Lick accepts only cash, so be sure to bring greenbacks if you plan to drive all the way out there. In the downtown area there's **Stubb's Bar-B-Q** (801 Red River St., 512/480-8341, 11am-10pm Tues.-Wed., 11am-11pm Thurs.-Sat., 11am-9pm Sun., $12). Yes, this is the establishment behind the famed Stubb's barbecue sauce. Christopher Stubblefield founded the first Stubb's restaurant in Lubbock, Texas, where he combined good live music and barbecue. Perfect combo! Artists such as Johnny Cash, John Lee Hooker, and Muddy Waters would "play for their supper." Stubblefield eventually moved to Austin, bringing with him his concept of live music and barbecue. Today Stubb's Bar-B-Q is one of Austin's premier live music venues and still serves up great barbecue. #### **BREAKFAST & BRUNCH** A true Austin breakfast experience can be had at historic **Threadgill's Home Cooking** (301 W. Riverside Dr., 512/472-9304, 11am-10pm Mon.-Thurs., 11am-10:30pm Fri.-Sat., 10am-9:30pm Sun., $12). The breakfast menu is as down-home as you can get, featuring lots of butter and oil, meat and potatoes, and pancakes and eggs in an all-American atmosphere. Breakfast on Sunday is highly recommended, as there is a live gospel band in the back serving up classic hymns. The **Omelettry** (4631 Airport Blvd #131A, 512/453-5062, 7am-5pm daily, $8) is one of Austin's best-kept secrets. Slackers, students, old-timers, and young families have chosen it as the best place to start a weekend morning. It's a no-frills restaurant that specializes in tasty omelets and pancakes that prove that crepes are just too flat. Don't expect flashy decor or bells and whistles, just great breakfast food. One of the top picks of a former U.S. president is S **Moonshine Patio Bar and Grill** (303 Red River St., 512/236-9599, 11am-10pm Mon.-Thurs., 11am-11pm Fri.-Sat., 10am-10pm Sun., $14). Popular for making typical American fare classy and a little pricy, Moonshine is always a hub of important folks. Although this is a great spot for dinner, Austin's best Sunday brunch can be found here. The buffet tables are chock-full of every breakfast food imaginable, all cooked to please those with a refined appetite. There's southwestern-style eggs, sausage links, waffles, buckets of fruit, smoked salmon, goodies from the bakery, and jugs of sauces and syrups. It's pricy, but darn worth it. Local favorite mini diner is the notch in the wall that is **Counter Café** (626 N. Lamar Blvd., 512/708-8800, 7:30am-4pm daily, $12). The name says it all: It's literally one long, very narrow counter with café/diner food. Seating is limited, which makes for a cozy and/or claustrophobic dining experience. Food here is fancier than your average greasy spoon. Although all-day breakfast is always good, they are nationally known for their cheeseburger. Be warned that street parking can be challenging. The local favorite for Mexican breakfast, brunch, and lunch is **Juan in a Million** (2300 E. Cesar Chavez St., 512/472-3872, 7am-3pm daily, $8). The experience at this hole-in-the-wall (said with deep affection) begins with a greeting at the door from Juan himself. You then take a seat and order, but before you do, understand that everything here is huge and heaping. If you're thinking this place is familiar, it landed on the map when Adam Richman of _Man v. Food_ was unable to eat eight of the breakfast tacos. Remember, I said they were heaping. #### **MEXICAN** Austin is only 250 miles from the border, giving the town a great advantage over most places for serving up excellent Mexican as well as creative variations on south-of-the-border foods. These variations need some clarification. First, there's good old-fashioned Mexican food, which is rice, beans, tacos, enchiladas, chopped beef, chicken, and salsa. Second, there's Texas's version of Mexican, called Tex-Mex. All you do is add catfish to the enchiladas, corn to the rice, and smoke to the salsa. Finally, there's a new hybrid that has emerged, which I call gringo-Mex. This is an upscale Mexican and Tex-Mex combination where you "encrust" the enchiladas, "sear" the meats, add citrus to the sauces, and charge more. Think Pancho Villa but replace the bandolier with a silk scarf. East Austin's best place for upscale Mexican is S **El Chile** (1809 Manor Rd., 512/457-9900, 11am-10pm Mon.-Sat., 11am-9pm Sun., $12). The food is very sophisticated gringo-Mex. Everything on the menu is well crafted, from the smoky salsa that's so tasty I wish they had it on IV drip, to their signature spicy, orange-infused margaritas (the best in town); El Chile is worthy of high accolades. Although it's upscale, the atmosphere is casual. Happy hour is 4pm-7pm. Parking is kitty-corner from the restaurant. For more casual and affordable Mexican, El Chile opened up a small taco shop, **El Cilito** (2219 Manor Rd., 512/382-3797, $6), just down the street. It offers street versions of El Chile's award-winning food. This place is great for takeout or relaxing in the outdoor covered patio. No indoor seating means no air-conditioning. Braised pork and carne asada tacos are top menu picks. While on South Congress, after a day of shopping for retro clothes and antiques, stop off at the best Mexican/Tex-Mex restaurant in Austin: S **Güero's Taco Bar** (1412 S. Congress Ave., 512/447-7688, 11am-11pm Mon.-Fri., 8am-11pm Sat.-Sun., $15). In 1994 the old Central Feed & Seed building was transformed into this fabulous taqueria. The aged brick walls are adorned with giant photos from the Mexican Revolution. The dining is casual, the handmade corn tortillas are excellent, and the margaritas are a local favorite. The portions are hearty, and the food, such as the shrimp fajitas, is truly mind-blowing. Let's not forget the self-serve salsa bar, which is a crucial part of the experience. Former president Bill Clinton loved this restaurant—hence his favorite dish is called the El Presidente. It should be noted that Güero's also successfully wears two hats: one is for Mexican food (a sombrero), and the other is for an excellent live music venue (a cowboy hat). Next door they have a great casual outdoor stage and bar with free live music. Güero's Taco Bar The closest you can come to having Mexican food on a beach is at **Takoba** (1411 E. 7th St., 512/628-4466, 11am-10pm Mon.-Fri., 10am-10 Sat.-Sun., $11) in East Austin. Yes, there is a beach in the side yard—or should I say large sandbox. The food is fresh authentic Mexican with homemade chips, creative drinks (white sangria), and some of the best fish tacos around. The ambience is a little polished and gringo, but makes for a pleasant environment for a friendly lunch or dinner. South Austin's **Polvos** (2004 S. 1st St., 512/441-5446, 7am-11pm daily, $10) is famous for build-your-own enchiladas, its salsa bar, and margarita pitchers. The atmosphere is loud, and the patio is big, which can be fun for some and overwhelming for others. Parking and wait times can be tricky, so plan ahead. S **Torchy's Tacos** (2801 Guadalupe St., 512/494-8226, and 1311 S. 1st St., 512/366-0537, 1822 S. Congress Ave., 512/916-9025, $7) started out as a food truck on South 1st Street. They have the predictable tacos and burritos, along with a more creative menu that features mouthwatering combinations such as the Jamaican jerk chicken taco. Their most popular plates are the green chili pork tacos and the Trailer Park, which is fried chicken with pico de gallo. They are also famous for amazing breakfast tacos heaped with cheese and bits of bacon, and _migas_ (Mexican-style scrambled eggs) tacos. For SXSW folks Torchy's is the morning hangover cure. Everybody's favorite breakfast taco comes from **Maria's Taco Express** (2529 S. Lamar Blvd., 512/444-0261, 7am-3pm Mon., 7am-3pm Tues.-Fri., 8am-3pm Sat., 9am-4pm Sun., $8). Now run by Maria's son, this taco shack has become legendary for its cheap Mexican fare, fast service, and friendly neighborhood clientele. During SXSW Maria's is overtaken by musicians and fans who come here to start off their day. Although Maria's is the best place to go in the morning with a hangover, it also serves up great Mexican dishes for lunch and dinner. The beautiful hacienda setting makes **Matt's El Rancho** (2613 S. Lamar Blvd., 512/462-9333, 11am-10pm Sun.-Mon. and Wed.-Thurs., 11am-11pm Fri.-Sat., $13) a safe bet for Mexican for the family. It's one of the older Mexican restaurants, as it's been in business since 1952. The food gets passionately mixed reviews, yet the restaurant has been an Austin tradition for decades. Try the Bob Armstrong dip, steak _tampiqueña_ , and a margarita. A great way to enjoy 6th Street and Mexican food in the early evening hours is by rooftop dining at **Iron Cactus** (606 Trinity St., 512/472-9240, 11am-11pm Mon.-Sat., 10am-10:30pm Sun., $15). Out on the second-level balcony the view of the hustle and bustle of Austin's famous street is unmatched. This popular upscale Mexican grill doubles as a tequila bar with a mind-numbing array of specialty drinks and creative Mexican dishes. Eat pulled pork and shrimp enchiladas and enjoy spicy tequila, in an ambience of sirens from the street below, under the glow of the city's neon skyline. Yes, better Mexican food can be found elsewhere in town, but the experience and location are unmatched. #### **TEX-MEX AND SOUTHWESTERN** Near the capitol is popular lunch spot **Arturo's Bakery and Cafe** (314 W. 17th St., 512/469-0380, 7am-2:30pm Mon.-Fri., 10am-12pm Sat., 10am-3pm Sun., $8). Don't let _bakery_ or _café_ in the name fool you, as this place is much more than either. The fare is reliable southwestern/Tex-Mex and some American items. This basement restaurant looks like a New York loft, with modern art hanging on brick walls and a hip clientele. With low-key but hip decor and a diverse yet affordable menu, Arturo's has become a favorite downtown breakfast and lunch spot. For Tex-Mex with a thrift-store Elvis flair, **Chuy's** (1728 Barton Springs Rd., 512/474-4452, 11am-10pm Sun.-Thurs., 11am-11pm Fri.-Sat., $12) will make your hips shake. The first thing one sees when entering Chuy's is a grandiose shrine to Elvis built into the entrance. From this point on it's all an experience. Yes, this establishment is heavy with gimmick, with its ceiling covered in hubcaps and fish and its retro/Salvation Army decor, but the food is great and the service is fast. They're famous for their handmade tortillas, fajitas, margaritas, overstuffed enchiladas, and Mexi-Cobb salad. Order their charro beans instead of refried. Tex-Mex at Chuy's is an essential Austin experience. Trying to place some food establishments in a particular category can be tricky. **Freebirds World Burrito** (515 S. Congress Ave., 512/462-3512, and 1000 E. 41st St., 512/451-5514, 11am-10:30pm Sun.-Thurs., 11am-10pm Fri.-Sat., $7) is free of categorization. It's not Mexican, it's not Tex-Mex, it's not American, and it's definitely not Eritrean, but it is good, filling, and cheap. This place was built with spare parts from a Harley-Davidson, your local Mexican joint, Whole Foods, and of course, the remaining members of Lynyrd Skynyrd. If you don't like what you eat, it's your fault, because you build your own burritos, tacos, and wraps here. S **Shady Grove Restaurant** (1624 Barton Springs Rd., 512/474-9991, 11am-10pm Sun.-Thurs., 11am-11pm Fri.-Sat., $14) is one of the best places in town to dine al fresco. A stylized 1950s theme mixes with reliably good Tex-Mex, American, and health-nut fare. This place can get extremely crowded, so go when you have time to wait for a table. Have a beverage, enjoy the outdoors, and watch the beautiful people. Through the summer months Shady Grove is a great spot to see top-notch local musicians perform for the "Unplugged at the Grove" concert series presented by local radio station KGSR. With a friendly environment that is light on the gimmick and heavy on taste, **Z'Tejas Southwestern Grill** (1110 W. 6th St., 512/478-5355, 11am-10pm Mon.-Thurs., 11am-11pm Fri., 10am-11pm Sat., 10am-10pm Sun., $12) is the eatery extraordinaire of Austin. A culinary zenith can be reached by sitting outside under the trellises on a sunny afternoon while eating their famous blackened-catfish enchiladas, stuffed pork tenderloin, crab-stuffed chicken, diablo chicken pasta, or virtually anything on the menu. After a big meal at Z'Tejas, walk down the street to the Treaty Oak and ponder the venerable tree's history. #### **ITALIAN** The genuine Italian food experience must have big tables, Italian songs tableside, oversized bowls of noodles, olives, cheerful waiters in white, wine, and lots of family. One might think this would be hard to find in Texas, but it's possible at the following Italian eateries. One of the best places to eat in the Hyde Park area is **Asti** (408C E. 43rd St., 512/451-1218, 11am-10pm Mon.-Thurs., 11am-10:30pm Fri., 5pm-10:30pm Sat., $12). This popular lunch and dinner spot looks like it was decorated by a graphic designer, not an Italian grandmother. Here you'll find classy versions of the Italian favorites, such as salmon and goat cheese pizza and penne with grilled chicken and spinach, along with a great wine list and the best fried calamari this side of the Colorado River. The best part about Asti? This upscale menu has great prices. The best upmarket pizza in town is at the **Brick Oven** (1209 Red River St., 512/477-7006, and 10710 Research Blvd., 512/345-6181, 11am-9pm Mon.-Sat., 5pm-9pm Sun., $18). The core of this casual family restaurant is the 100-year-old brick oven and the smoky thin-crust pizzas it produces. The crust is infused with "special ingredients" that the proprietors will not reveal. This lends to an amazing, soft, flavorful crust that is unparalleled in Austin. The menu also offers lasagna, chicken formaggi, ravioli, pasta primavera, and calzones. Being close to the capitol, 6th Street, and the UT campus makes Brick Oven an easy, safe pick for lunch or dinner. A great place to bring the family is **Frank and Angie's Pizzeria** (598 West Ave., 512/472-3534, 11am-9:30pm Mon.-Thurs., 11am-10pm Fri., noon-10pm Sat., 5pm-9:30pm Sun., $12). This downtown establishment has bizarre murals, Frank Sinatra memorabilia, and a patio overlooking Shoal Creek. Two-for-one specials are offered on Monday and Tuesday. The themed menu includes gourmet pizzas, pasta, calzones, and salads, all prepared well and at great prices. If you're on South Congress Avenue and "the moon hits your eye like a big pizza pie," make your way to S **Home Slice Pizza** (1415 S. Congress Ave., 512/444-7437, 11am-11pm Sun.-Thurs., 11am-3am Fri.-Sat., $8). This innovative pizzeria has mastered the art of interior decorating for the trendy crowd. Luckily, it's also mastered the world's most popular Italian dish. What makes this place so fabulous is that it's a great place to hang out with friends: They have Italian wines, a couple of beers on tap, and an upbeat environment. While waiting for the pie to cook kids can play with pizza dough. Just ask your server. The downtown Italian food scene is dominated by **La Traviata** (314 Congress Ave., 512/479-8131, 11:30am-2pm and 5pm-10pm Mon.-Fri., 5:30pm-10:30pm Sat., $15). During the day La Traviata is a popular business lunch spot, and at night it becomes a place for romance. Wine connoisseurs will be pleased to find there's an extensive wine list here, and fans of exquisite Italian dishes will be thrilled by the creative but traditional menu. It's a bit pricy, but worth it. Note for non-opera people—it's named after one of the best Italian operas of all time. A popular family-style Italian restaurant north of the UT campus area is **Mandola's Italian Market** (4700 W. Guadalupe St. #12, 512/419-9700, $12). Decked with fake Italian signs, plastic slabs of meat, and beadboard walls, Mandola's has authentic Italian food served amid bustling ambience. The lasagna is a personal favorite. Other menu items include gnocchi with meat sauce and chicken parmesan. After a super-unhealthy meal one can mosey over to the gelato bar or buy some imported Italian food—the market at the front of the store isn't just for looks. **Rounders Pizzeria** (1203 W. 6th St., 512/477-0404, 11:30am-10pm Sun.-Thurs., 11am-11:30pm Fri.-Sat., $12) has received an award for best pizza many times since its inception in 2002. This Las Vegas-themed pizzeria serves a special pie with unique presentation and a smile. The crust is crunchy, which soft-crust pizza fans won't admire. Besides pizza, Rounder's serves up classic arcade games such as Galaga and Ms. Pac-Man. #### **OTHER INTERNATIONAL FOOD** S **Clay Pit** (1601 Guadalupe St., 512/322-5131, 11am-2pm and 5pm-10pm Mon.-Thurs., 11am-2pm and 5pm-11pm Fri., noon-3pm and 5pm-11pm Sat., $12) is one of America's best Indian food restaurants, according to _Bon Appétit_ magazine, and I am in full agreement! This five-star restaurant serves contemporary Indian cuisine in a sophisticated atmosphere. The orgy of flavors includes several curries, naan, and tandoori dishes. Although this is a great spot for dinner, the affordable lunch buffet brings in hordes of folks looking for a bargain for top-notch Indian. Clay Pit is affordable yet upscale, which makes it a perfect place for any type of occasion. Imagine sitting at a table near a lake, drinking mango margaritas and eating pupu, all in the presence of the Polynesian tiki gods. **Hula Hut** (3825 Lake Austin Blvd., 512/476-4852, 11am-10pm Sun.-Thurs., 11am-11pm Fri.-Sat., $10), situated on the banks of Lake Austin, is a world unto itself. The atmosphere is festive, especially on weekends when the weather is nice. The cuisine is a "unique mix of Mexican and Polynesian, otherwise known as Mexonesian." Getting into specifics, this means dishes such as Thai barbecue fajitas and mango poblano chili quesadillas. Sitting outside is an absolute must. **Madam Mam's** (2514 Guadalupe St., 512/472-8306, and 4514 W. Gate Blvd., 512/899-8525, 11am-10pm daily, $10) brings the noodle to Austin in an affordable and reliable way. Although the core of this place is Thai cuisine, with dishes such as pad thai, you can also order curry dishes with tangy lime and Chinese mushrooms. The versatility of the menu and the good prices make Madam Mam's a great place to come with friends before a night on the town. If you suddenly find yourself completely bored with food and flavor, and if nothing seems to tickle your palate anymore, I recommend going on a food adventure to Phoenician Resto Café (84 N. Interstate 35 Frontage Rd, 512/712-5904, 11am-10pm Mon.-Thurs., 11am-11pm Sat., 11am-9pm Sun., $10). This place is all about spice exploration, savory meats, soups, and sandwiches that will render anyone speechless. This Mediterranean café offers a healthy menu with variations of hummus, chicken, lamb, and veggies, all surprisingly inexpensive. Locals with diverse palates love to eat under the freeway at **Aster's Ethiopian** (2804 N. I-35, 512/469-5966, 11am-9pm daily, $9). The tender beef and greens mixed with lentils is super filling. With a wide variety of vegetarian and meat dishes, this is a great low-key place to bring a few friends and sample a variety of tasty and healthy dishes. The lunch buffet is all-you-can-eat, so be careful. S **Thai Kitchen** (3009 Guadalupe St., 512/474-2575, 11am-midnight Mon.-Thurs., 11am-1am Fri., noon-2am Sat., noon-midnight Sun., $12) simply has to be mentioned when expounding on Austin's Asian cuisine options. A popular place for both people and pigeons, Thai Kitchen has consistently been rated the best Thai restaurant by the _Austin Chronicle._ The food is surprisingly expensive for a dive Thai joint, but it's worth it. The Thai tea (often mispronounced as tai chi or chai tea) summons contentment and pleasure. The healthiest and tastiest meal on a shoestring is at **Zen** (3423 Guadalupe St., 512/300-2633, and 1303 S. Congress Ave., 512/444-8081, 11am-9:30pm Mon.-Sat., 11:30am-9pm Sun., $8). Their motto is "Japanese Food Fast." It may be fast, but it's healthier than fast food. What can beat four-piece California rolls for $3 or a bowl of spicy chicken with noodles for $5? And what beats sushi prepared by gringos? The restaurants are clean, the decor is modern, and the concept is brilliant. For a unique indoor/outdoor Indian food dining experience try **G'Raj Mahal** (73 Rainey St., 512/480-2255, 5pm-10pm Mon., 11am-midnight Tues.-Thurs., 11am-1am Sat.-Sun., $15), tucked away in the Rainey Street District just south of 6th Street. Here you can dine in tents with stylish pillows and aromas that transport you far from Texas. Traditional fresh Indian plates are flying out of the tandoor oven. **Whole Foods** Well before eating healthy and organic was trendy, Austin was a center for everything all-natural. People are always surprised to hear that this Texas town was the place where organic supermarket giant Whole Foods got its start back in 1980. At the time there were fewer than half a dozen natural-food supermarkets in the United States. These stores were pricy and relegated to the hippie fringes of our society. Thanks to the popularity of eating organic, the profile of healthy foods has become accessible to all. Whole Foods may still be pricy, but food tastes so much better when it hasn't been genetically modified, manipulated, and bleached to death. The Whole Foods corporate headquarters is above the **flagship store** (525 N. Lamar Blvd.) at the corner of Lamar and 6th Street, west of downtown Austin. Folks from out of town are consistently bedazzled, enamored, and overwhelmed by the sheer quantity and quality of the products here. If you're in the neighborhood it's suggested you poke your head in and look around. Or better yet, stay and have lunch. #### **HEALTHY AND VEGETARIAN** Being the Berkeley of Texas, Austin has some great fare for the health nut, vegetarian, and vegan. Many of these establishments have been around for a long time and are tried and true. Remember, Paul McCartney himself awarded Austin for being the most accommodating city in the country for vegan diets—and for good reason! In East Austin there's **The Eastside Cafe** (2113 Manor Rd., 512/476-5858, 11:15am-9:30pm Mon.-Thurs., 11:15am-10pm Fri.-Sat., 10am-9:30pm Sun., $10), which has its own vegetable garden on-site, meaning extraordinarily fresh produce graces the plates. Patrons have the choice of eating in the soothing garden room or the classy antique interior of a converted bungalow. Delicious menu options include baked brie with chutney, sesame catfish, and salmon dumplings with coconut curry sauce. On weekends, an extremely popular brunch is offered 10am-3pm with scrumptious choices like apple almond waffles and smoked salmon Benedict. It's wise to make a reservation, especially on the weekends. South Austin's morning-all-day, breakfast-all-day hangout is S **Bouldin Creek Coffee House** (1900 S. 1st St., 512/416-1601, 7am-midnight Mon.-Fri., 9am-midnight Sat.-Sun. $9). The previous location was basically a shack chock-full of Austin's weirdest. Now Bouldin has officially entered the mainstream, and to me this is a good thing. The food is fantastic, and the vibe is electric with artists, students, and shoe gazers getting jacked on coffee. Along with scrambled tofu or eggs, the menu includes some creative plates that are uniquely hippie Tex-Mex. Examples: tofu chorizo tacos, hummus, gluten-free offerings, and the Slacker's Banquet. Most of the menu is or can be made vegan. A great choice for healthy food for everyone is **Kerbey Lane** (3704 Kerbey Ln., 512/451-1436; near UT campus at 2606 Guadalupe St., 512/477-5717; and in south Austin at 2700 S. Lamar Blvd., 512/445-4451, 24 hours daily, $8). Here you can have vegetarian fare and your friends can have meat if they prefer. Expect locally grown, organic, pesticide-free vegetables and free-range beef and pork, prepared with precision. Kerbey Lane is known for its excellent queso, salads, and unusual entrées. All this is available 24 hours a day. **Mother's Cafe and Garden** (4215 Duval St., 512/451-3994, 11:15am-10pm Mon.-Fri., 10am-10pm Sat.-Sun., $9) is the oldest and probably the best. All dishes are prepared with the highest-quality ingredients and without any meat products. Many items on the menu can be prepared vegan as well. The food is so good here that the skeptic of vegetarian fare is sure to forget that the food is vegetarian. The owners take great pride in the eclectic menu choices, which range from enchiladas to stir-fry to quiche. For pauper vegetarians and nonvegetarians broadening their horizons, **Veggie Heaven** (1611 W. 5th St. #135, 512/457-1013, 11am-9pm Mon.-Fri., noon-9pm Sat.-Sun., $6) offers up a fresh, Asian-based vegetarian menu that's quite overwhelming. Most dishes have textured vegetable protein or tofu, and they're so well put together even carnivores can walk away satisfied. This sunken little restaurant is popular, and usually so packed the windows are completely steamed up. Oh wait—maybe that's just grime. Service is curt and to the point, but it's hard to complain because it's so cheap. If you are vegetarian or vegan, and you're on the verge of backsliding, quickly make haste to **Mr. Natural** (1901 E. Cesar Chavez St., 512/477-5228, 8am-8pm Mon.-Sat., $6). This humble restaurant in East Austin is nondescript, but don't pass it over. Vegetarian and vegan Mexican has been perfected by Mr. Natural. Each intelligently designed plate is filled to the brim with all-natural ingredients and flavors. Besides great vegan meals, Mr. Natural also has a vegan bakery, with sweets such as tofu cheesecake and tres leches cake (a brilliant contradiction!). Mr. Natural is sure to seduce any questioning vegan back to the healthy side. #### **FINE DINING** Of the five senses we humans are equipped with, the one that is the most finicky to please is the sense of taste. Luckily, fine dining in Austin satisfies, with open kitchens, chef hats, long wine lists, Texas-style hospitality, and brilliant tastes whose origins you can't quite pin down. True to Austin's laissez-faire approach to everything, most fine-dining establishments have no dress expectations. In fact most high-end restaurants don't even want to be classified as "fine dining"; they just want you to be comfortable and enjoy the ride. Plan on bringing plenty of money because the ride can be pricy. Austin's most enduring high-end restaurant is the S **Driskill Bar and Grill** (604 Brazos St., 512/391-7162, 5:30pm-10pm Tues.-Sat., $40), located inside the Driskill Hotel. The Driskill has been winning awards for years. The interior is dark and Victorian with a rich Texas flair. Popular among the city's elite, such as musicians, politicians, actors, and local celebrities, the Driskill has mastered fine dining. Chef David Bull has developed a three-course menu that includes duck, seared foie gras, baked Alaska halibut, and tenderloin. Here you can find nothing but the very best in service and taste. The Driskill is a perfect place to start a romantic evening, followed by a horse-drawn carriage ride. The tradition of Southern hospitality and fine dining has been well maintained for decades at **Green Pastures** (811 W. Live Oak St., 512/444-1888, 11am-2pm and 6pm-10pm daily, $30). South Austin's best-kept secret, this large estate features ancient oaks and an old Victorian house. In the 1950s the house was converted into a restaurant for Austin's elite. Eating here is like being a guest in a grand Southern home. Sip wine and savor small portions of artistically presented French-inspired gourmet cuisine, while looking around at all the antiques, pictures, and manicured lawns with peacocks. Reservations are highly recommended, as the place quickly fills up. When you see the giant fork in the sky you know you have arrived at **Hyde Park Bar and Grill** (4206 Duval St., 512/458-3168, 11am-midnight daily, $18). The interior is swank, the staff is professional, and all meat products are organic. The cows may not be drinking fine wine and getting massages, but they are range fed and hormone-free. Hyde Park is famous for its batter-dipped fries, chicken-fried steak, and peach pudding. The restaurant and bar are open until midnight every day. Being at the center of the state of Texas you may think good, fresh seafood just isn't a possibility in Austin. **Eddie V's Edgewater Grill** (301 E. 5th St., 512/472-1860, 4pm-11pm Mon.-Thurs., 4pm-midnight Fri.-Sat., 4pm-10pm Sun., $40) proves all logic wrong. Every day fresh fish is flown in from Boston, because Eddie V's motto is "we won't serve it unless it's fresh." When the menu is five pounds and leather bound, you know it's fine dining. This steak and seafood menu includes Chilean sea bass steamed Hong Kong-style, snapper and crab, seared Pacific ahi tuna steak, broiled Georges Bank sea scallops, roasted rack of Colorado lamb, and filet mignon. The menu is à la carte, which adds up pretty quickly, but once you have a nice glass of wine in front of you, you won't even think about it. If you want to instantly feel like you've come to the right place, go to **Jeffrey's** (1204 W. Lynn Ave., 512/477-5584, 6pm-10pm Mon.-Thurs., 5:30pm-10:30pm Fri.-Sat., 6pm-9:30pm Sun., $40). A creative and gregarious chef is behind the menu, and this comes through in each dish. New American and southwest flavors, coupled with wine and total confidence, make this menu superb. For starters there are crispy oysters on yucca-root chips and ginger beef dumplings. Entrées include duck and shrimp with a rice pecan cake, beef tenderloin with rosemary potatoes, and Alaskan halibut with linguine, trumpet royale mushrooms, and orange champagne cream. Is your mouth watering yet? It should be! A mainstay for upscale Mexican food is **Fonda San Miguel** (2330 W. North Loop Blvd., 512/459-4121, 5:30pm-9:30pm Mon.-Sat., 11am-2pm Sun., $30). The environment is quite impressive, with its extravagant hacienda interior complete with original Mexican paintings, tall ceilings, lush foliage, and large tin lanterns. Everything on the menu is excellent, but my favorite is the _carne asada a la tampiqueña_. The beef is the best-tasting meat in town. All of the above is why Fonda San Miguel has been one of Austin's premier restaurants since 1975. Be sure to make a reservation for Fonda San Miguel, as the seats fill up quickly. If you enjoy a bustling dining experience with a big wine and cocktail list and small entrées, S **Vox Table** (1100 S. Lamar Blvd. #2140, 512/375-4869, 5pm-10pm Mon.-Thurs., 5pm-11pm Fri.-Sat., brunch 11am-2pm Sat.-Sun., $18) is waiting for you—if there is an open table. Although in the spirit of tapas, this place serves up small creative dishes in a modern but not snooty environment. Dishes like pork cracklins and octopus and noodles come glazed and garnished with crisp, crunch, and savor. Along with tasty food, Vox Table has a great wine and beer list, an inventive selection of house cocktails, and a bar that is always active and inviting. If this is your main meal, be sure to order enough for everyone so you don't walk away hungry at the end of the night. Also, a word of warning for the person new to tapas: Since the food is light and spread out over the course of the evening, the wine tends to kick in at plate 3 of 8, so spread it out. Reservations are recommended on weekends. Also in the Warehouse District is **Truluck's** (400 Colorado St., 512/482-9000, 5pm-10pm Mon.-Thurs., 5pm-11pm Fri.-Sat., 5pm-9pm Sun., $40). The classy atmosphere includes waiters in chef coats and art deco decor. With a wide variety of wines, perfectly prepared seafood dishes, and big-band music piped in, Truluck's will convert seafood haters to lovers. The first time I'd ever eaten lobster was here, and it was a profound experience. Perhaps the most popular dining venue in the city is **Vespaio** (1610 S. Congress Ave., 512/441-6100, 5pm-10pm daily, $18). This darling of all the critics, and glamorous favorite of the people, is housed in a small space on popular South Congress. The kitchen is run by celebrated chef Alan Lazarus, who engineers brilliant Italian food by mixing innovation with tradition. The wine list is excellent, the food is perfectly designed and prepared, the atmosphere is lively—and did I mention the food is perfect? Italian flavor reaches a climax with dishes like veal ravioli, gnocchi with duck, cioppino (Livorno-style seafood stew), and spaghetti alla carbonara with handmade noodles. _Vespaio_ is Italian for beehive, and the restaurant lives up to its name by always buzzing with action. There aren't many tables in this small space, and they're guaranteed to be full every night of the week, so the wait may be long, but it's worth every second. According to _Texas Monthly_ magazine, S **Uchi** (801 S. Lamar Blvd., 512/916-4808, 5pm-10pm Sun.-Thurs., 5pm-11pm Fri.-Sat., $30) was one of the top five best new restaurants in Texas the moment it opened. It's considered Japanese, but don't expect the usual Japanese fare. It's actually Asian fusion with a dramatic, original flair. I consider Uchi the best white-knuckle eating experience I've ever had. If you have a fat wallet and razor-thin nerves, order anything from the menu and explore the mind of highly decorated chef Tyson Cole. Every item on the menu is extremely flavorful, wildly unique, and highly recommended. Warning to the squeamish—you may end up going away hungry. Praise for the brave—you will walk away an enriched person. The one item on the menu that deserves mention is the sawagani. This is a plate of several miniature freshwater crabs cooked whole to perfection and eaten like popcorn. You'll be surprised how easy the shell crunches and pincers go down the hatch. The founders of Lamberts go fishing with the owners of the fancy South Congress seafood joint **Perla's** (1400 S. Congress Ave., 512/291-7300, 11:30am-3pm and 5:50pm-10pm daily, $20). This is Austin's best place for raw or fried oysters. Sampling the different oyster sauces with wine out on the front deck is the height of decadence. Notable menu items include lobster stock grits, calamari, and escolar. The decor gives you the impression you're eating with the rich in the Hamptons. Perla's is a great choice for seafood far from the sea, for either brunch, lunch, or dinner. #### **DESSERTS AND CONFECTIONS** There are just a few boutique dessert and confection shops in town, and S **Amy's Ice Creams** (1012 W. 6th St., 512/480-0673; 5624 Burnet Rd., 512/538-2697; and 3500 Guadalupe St., 512/458-6895, www.amysicecreams.com, 11:30am-midnight daily, $4) is the queen of them all. Amy's uses natural ingredients and a local dairy, and offers 16 flavors daily. One of the tricks to this parlor's popularity is that they manually smash and blend your favorite candy bars into your choice of ice cream using a dramatic process that happens before your eyes. There are nine locations in Austin. One of the grand additions to the South Congress strip is **Big Top Candy Shop** (1706 S. Congress Ave., 512/462-2220, 11am-7pm Mon.-Fri., 10am-8pm Sat., 11am-7pm Sun., $2-25). These folks have created a bizarre and wonderful atmosphere that can only be described as a 19th-century circus of candy that has an honest-to-God soda fountain. Everyone under 60 who never had the chance to experience this "back in the day," should rush here. Besides hand-jerked sodas, there are bins of hard candy, rivers of malts, and mountains of chocolate. For classy and refined fineries there's **Dolce Vita** (4222 Duval St., 512/323-2686, 8am-midnight daily, $10). If you have dinner at any of the restaurants in the Hyde Park area, such as Hyde Park Grill or Asti, a stop here is essential. Dolce Vita offers espresso along with a selection of ever-changing gelato, ice creams, pastries, and chocolate desserts. It also has an exceptional assortment of scotches and liqueurs that can't be found anywhere else in town. Austin's original socializing parlor is the S **1886 Cafe and Bakery** (116 6th St. at the Driskill Hotel, 512/391-7066, 7am-midnight daily, $8). With a checkered floor, stained glass, dark woodwork, pillars, and arches, the interior looks like it hasn't changed much since 1886. Although this historic café offers breakfast, lunch, and dinner, the reason for coming here is the pastries and desserts. With a great location in the center of downtown in the Driskill Hotel, this is a great place to go if you get a craving for coffee and something sweet. Imagine eating a small tower of chocolate mousse in a flower shop without flowers with Sandra Bullock. Sounds like heaven, right? It's actually **Walton's Fancy & Staple** (609 W. 6th St., 512/542-3380, 7am-8pm Mon.-Fri., 8am-8pm Sat., 9am-5pm Sun., $6). Although Walton's is actually a deli, I recommend this place for the sweet stuff. Baked goods are absurdly decadent, and sodas are in bottles, which means they are sweeter. Everything is sweet about this place, including the fact that it was founded by Ms. Bullock. For bizarre treats on 6th Street you can't pass up **Voodoo Doughnut** (212 E. 6th St., 512/215-8586, open 24 hours, $8). This is a great place to have a random experience after midnight. The décor of this place is weird, and the doughnuts are even weirder. There's the Pot Hole (their take on the chocolate bar), a maple bacon bar, and even a dark chocolate doughnut of a voodoo doll. #### **COFFEE SHOPS** In this day and age, when nearly everyone has a daily caffeine maintenance, cafés are everywhere. Some frequent cafés to sip coffee with friends, some to surf wireless Internet, some to read the paper or a book, but all just want a place to go. Humans, like fish, are social creatures, and humans drink lots of water, only many humans like their water to be filtered through the "bean." Here are some of the top places to hang out and drink coffee. **Wright Bros. Brew and Brew** (500 San Marcos St. #105, 512/493-0963, 8am-midnight daily, $5) is a perfect place to hang out, read the _Austin Chronicle,_ and drink a cup of coffee after waking up at noon. This coffee shop features a menu of AeroPress, drip and espresso, featuring beans from local roaster Flat Track. S **Halcyon Coffeehouse** (218 W. 4th St., 512/472-9637, www.halcyonaustin.com, 7am-2am daily, $5) is a night-owl café, a bar, an art gallery, and a smoke shop in one, and a great place to hang out. People come here to surf wireless Internet, to socialize, and to meet people. If you happen to have a random craving for s'mores, staff will bring fire to your table, as well as chocolate and marshmallows, so you can satisfy that craving. Seriously! Make your own s'mores at Halcyon Coffeehouse. **Jo's Cafe** (1300 S. Congress Ave., 512/444-3800, 7am-9pm Sun.-Fri., 7am-10pm Sat., $2-5) is the boy who can do no wrong on South Congress. This outdoor café is strategically positioned in the best area of the bustling street, near all the great curiosity shops and boutiques. Jo's is a shack, albeit a stylish shack, that offers only outdoor seating in a parking lot. Jo's has a conventional coffee shop in the 2nd St. District (242 W. 2nd St., 512/469-9003). They're proud to serve up hot coffee, a few food items, and cold beer to a stream of people all day. The café with the absolute best location is **Mozart's Coffee** (3825 Lake Austin Blvd., 512/477-2900, 7am-midnight Mon.-Thurs., 7am-1am Fri., 8am-1am Sat., 8am-midnight Sun., $6). Set on a quiet part of Lady Bird Lake, with outdoor seating, an in-house bakery, classical music playing, and coffee being roasted in the background, Mozart's is simply marvelous. Baked desserts are $6 and sweet pastries are $3. Wireless Internet is available. The only drawback is that parking can require patience. **Pacha** (4618 Burnet Rd., 512/420-8758, 7am-9pm Mon.-Fri., 8am-9pm Sat.-Sun., $5), north of downtown, is one of those charming little homespun cafés that everyone prays will survive. Everything in here, from the tables to the hand-forged doorknobs, was made by family and friends of the two owners. Besides great coffee, Pacha sells imported Bolivian handmade arts and crafts from two cooperatives. Buying any of these crafts helps families in rural Peru and Bolivia. Doesn't matter if it's morning or nighttime, one of my favorite places to hang out is **Spider House Cafe** (2908 Fruth St., 512/480-9562, www.spiderhousecafe.com, 11am-2am daily, $5). This mostly open-air café features coffee, breakfast, beer, and free Wi-Fi, all in one of Central Austin's best patio settings. The food is not so great, but the coffee and beer are excellent when enjoyed on the outdoor patio. Junk is stuffed in every corner of this place, Christmas lights are on year-round, and sometimes there is live music on the tiny stage. ### **Accommodations** A fly on the wall in any of Austin's motels, hotels, and bed-and-breakfasts would probably report seeing all kinds of folks coming and going throughout the year, such as families, politicians, sports fans, celebrities and movie industry folk, business professionals attending conferences, and leisure travelers. It's risky putting words in a fly's mouth, but I would venture to say the type of traveler a fly would report seeing the most is musicians. Being the Live Music Capital of the World, Austin generates an unprecedented amount of band traffic. That said, Austin has a place to stay for everyone. Here you can find a room in a quiet Victorian with doilies, down pillows, and blueberry muffins, or a room in a plush four-star luxury hotel with a rooftop pool, whirlpool bathtubs, and impeccable room service. So what's the best area to lay your head? Downtown is the most desirable area because this is where everything is happening. All the chain hotels know this and their prices reflect it. Rates vary depending on the season and whether there's an event taking over the town. But those desiring comfort and a deal shouldn't lose heart. The upswing of this is that bed-and-breakfasts are plentiful and affordable, and many are within close range of downtown. The main thing to keep in mind when planning your trip to Austin is to book your reservations way in advance. When there's an event in town it can be difficult, and sometimes nearly impossible, to find a place to stay at the last minute. To be sure you have a good chance of getting a reservation where you prefer to stay, book your lodgings at least 2-3 months in advance if possible. Also, all hotels and rooms are much more expensive when the town is overrun by people when there is a major festival or event going on, which is practically every month. #### **UNDER $100** The most affordable bed in town is at **HI Austin Hostel** (2200 S. Lakeshore Blvd., 512/444-2294 or 800/725-2331, $22-65). Set on the banks of Lady Bird Lake near downtown, this spacious hotel is comfortable and clean. Of course, it has dormitory-style accommodations. Rates are $22 per night for HI members, $25 per night for nonmembers. Private rooms are available for a $75 a night. Bed linens and parking are included in the rate, and towels rent for a buck. Bicycle, canoe, and kayak rentals are available, as is Internet access. Front desk hours are 8am-10pm. Dormitories are open 2pm-11am. No curfew. There's something about staying in a dingy motel in Austin that's very appealing, and even romantic, especially for the Sid-and-Nancy-type couples. Let's start off with the good ol' American roadside mainstay **Super 8 Motel** (1201 I-35 at 12th St., 512/472-8331, www.super8.com, $65-139). I put this entry in here simply because it's cheap and close to downtown. With rates like these, don't expect anything except a bed, clock radio, coffeemaker (with bad coffee), TV, bathroom, and a Gideon Bible. #### **$100-150** A little more money can go a long way. While in Austin, $100-150 is what you will spend if you want to stay in accommodations that don't feel budget, but still offer value for your buck. If you want the motel atmosphere minus some of the dubious activities we all know go down in motels, there's the **Austin Motel** (1220 S. Congress Ave., 512/441-1157, www.austinmotel.com, $105-150). This family-owned Austin institution has a unique and quirky style, and is in a great location on South Congress Avenue. The motel's motto is "So close yet so far out." The Austin Motel is a favorite place to crash for musicians because it's safe, cheap, and sorta-kinda clean, but has all the charm and charisma of a total dive. Situated in one of Austin's older neighborhoods north of downtown is **Adam's House** (4300 Avenue G, 512/453-7696, www.theadamshouse.com, $149-199). This beautiful, historic home was tastefully converted into a bed-and-breakfast that offers five charming rooms decorated with antiques. Located in the historic area of Hyde Park, just north of downtown, it's not too far from the Elisabet Ney Museum and the excellent restaurants of Duval Street. Adam's House is an excellent place to stay for romance. During the weekdays a light breakfast of granola, cereals, homemade muffins, and juices is offered, and on the weekends a full breakfast is served in the dining room. Pets and children under 12 are not welcome. Texas residents get the "state traveler discount." The bed-and-breakfast closest to the action downtown is the **Brava House** (1108 Blanco St., 512/478-5034, www.bravahouse.com, $149-195). This old Victorian decked with art deco flair is classy, clean, and understated. Brava House offers appealing prearranged packages for an additional fee. For example, there's the "Enchanted Evening," where champagne, chocolate-covered strawberries, and candles are waiting for you in your room; "Romance in the Air," where an entire romantic evening is arranged that includes dinner for two at a local restaurant followed by a carriage ride through downtown; or the "Spa Getaway." Also north of downtown is **Austin Folk House B &B** (506 W. 22nd St., 512/472-6700, www.austinfolkhouse.com, $130-280). This cheerful bed-and-breakfast offers clean rooms and great hospitality. Breakfasts are a few notches above most bed-and-breakfasts, as they offer _migas_ (Mexican-style scrambled eggs), ginger pancakes, crepes, and a few fruit-based dishes such as banana enchiladas. The **Star of Texas Inn** (611 W. 22nd St., 512/472-6700, www.staroftexasinn.com, $130-250) is run by the same people who operate the Austin Folk House B&B, and here you will have the same great hospitality, clean bedrooms, and of course the breakfast, all with a down-home touch. **Extended Stay America Austin-Downtown-Lady Bird Lake** (600 Guadalupe St. on 6th St., 512/457-9994, www.extendedstayamerica.com) is a cheap choice for centrally located lodgings downtown. What this place lacks in charm it makes up for in privacy and location. Each unit has a full kitchen, wireless Internet, and cable TV, and laundry is available on the premises. Weekly rates are $85-149 per day, and daily rates start at $175. A cheap hotel downtown is **Holiday Inn Austin-Lady Bird Lake** (20 N. Interregional at I-35, 512/472-8211, www.holidayinn.com). Located on Lady Bird Lake, this archetypal hotel has it all: outdoor pool, a restaurant, Internet access, on-site fitness center, and views of the city, all for around $150 a night. A kayak rental shop is close by, making kayaking on the lake an easy day excursion. The one drawback with this hotel is it's hovering over I-35. If you stay here ask for a room away from the freeway. Also in this no-frills hotel genre is **La Quinta Inn-Austin Capitol** (300 E. 11th St., 512/476-1166, www.laquinta.com, $109-149). Here you get just the usual inexpensive hotel amenities you would expect from a budget hotel. It's a cheap place to stay, and centrally located, as it's next to the capitol. But don't be surprised if the paint is moldy in the bathroom. Also, you may see the flashing lights of Austin PD in the parking lot at night, as it can get slightly shady after dark. Nonsmoking rooms are available upon request. One of Austin's best deals for chain hotel lodgings downtown is at **Embassy Suites Downtown** (300 S. Congress Ave., 512/469-9000 or 800/362-2779, www.embassysuites.com, $139-219). Located at the crossroads of South Congress and Barton Springs Road, this hotel is within walking distance of many of Austin's prime attractions. All the suites here have a separate room for entertaining with a bedroom in the back, and a complimentary cooked-to-order breakfast is included. Austin has always been at the forefront of environmental awareness. **Habitat Suites** (500 East Highland Mall Blvd., 512/467-6000 or 800/535-4663, www.habitatsuites.com, $100-187) is a natural outcome of this local ecofriendly movement. Here you can enjoy all the pleasures of a four-star hotel and feel good about not contributing to the world's environmental problems. The hotel provides nontoxic, phosphate-free, natural shampoos and soaps for guests, and uses natural cleansers. The solar-power system used here is the largest of its kind used at a U.S. hotel. The facility is a nonsmoking, pet-free environment, and a member of Green Hotels Association (www.greenhotels.com). The one drawback is that it's up in Old North Austin, which is about five miles north of downtown. For inexpensive accommodations near Austin-Bergstrom International Airport there's **La Quinta Inn & Suites-Austin Airport** (7625 E. Ben White Blvd., 512/386-6800, www.laquinta.com). If you have a flight leaving early in the morning, stay here and catch a free shuttle to the airport. This La Quinta is all about convenience, not four-star comfort. Rates can be as low as $109 even in the high season. On the shores of beautiful Lake Travis is **Lakeway Resort and Spa** (101 Lakeway Dr., Lakeway, 512/261-6600 or 800/525-3929, www.lakewayresortandspa.com, $140-199), a premier resort designed to make guests do absolutely nothing except bask in leisurely delights. The resort is in the small town of Lakeway, which is about 20 miles from Austin. You have access to top-notch private golf courses, spas, and tennis courts, and can even charter a sailboat for a day on the lake. Getaway packages for golf, families, and romance cost more but offer more. Note that during droughts the lake levels can get pretty low, which affects the views at the resort. #### **$150-250** Perhaps the most popular locally owned hotel in town is S **Hotel San Jose** (1316 S. Congress Ave., 512/444-7322, www.sanjosehotel.com, $145-300). This place is so hip it's almost an entire pelvis. Hotel San Jose is highly rated due to its chic vibe with minimalist decor that I would describe as postmodern Japanese rustique. Some would say Hotel San Jose is all pretense, while others would say it's all romance. You decide. The snooty staff can be unpleasant, but the wisteria-covered arbors and quiet atmosphere are pleasant. The hotel offers a great deal that is often overlooked: If you aren't opposed to sharing a bathroom you can get a posh room for only $145. A top-notch B&B in the South Congress Avenue area is **The Fairview** (1304 Newning Ave., 512/402-6214, fairviewaustin.com, $199-300). The Fairview is a calm place for the leisure traveler. Sitting on the porch or patio and reading a book or having a gluten-free breakfast outside is the way to go. The plantation-style house has many modern updates inside. Décor is clean and modern but still Texan. Each room has modern king-size beds with organic mattresses, Wi-Fi and HDTV. In the downtown area there are several luxury chain hotels. They may lack historic charm but they have boilerplate luxury-hotel service and amenities. They're big, they're fancy, and totally predictable, which is what some travelers prefer. At the crossroads of downtown and South Austin is the **Hyatt Regency Austin** (208 Barton Springs Rd., 512/477-1234, www.hyatt.com, $180-350), one of the city's four-star hotels. Perched on the banks of Lady Bird Lake, the Hyatt is in close range of the Palmer Auditorium, Austin Convention Center, and the great shops and restaurants of South Congress Avenue as well as 6th Street. A good choice for the health-conscious traveler, the Hyatt has a fitness center and a pool and is close to the trails around Lady Bird Lake. The rooms on the north side have views of bats flying out from under Congress Avenue Bridge in summer months. The open atrium inside and artificial creek running through the restaurant make this a classy place to meet and do business. Another luxury hotel is **Hilton Austin** (500 E. 4th St., 512/482-8000, www.hilton.com, $150-240). Hilton's downtown location, with a terrace pool on the roof of the 8th floor, a fitness center, an in-house steak and seafood restaurant, and extravagant decor, will make you forget all the complications of life. Views are spectacular, service is high caliber, and comfort is unavoidable. Promotional rates can sometimes be as little as $100. The hotel with the best central location is the **Sheraton Austin** (701 E. 11th St., 512/478-1111, www.sheraton.com, $200-299). Although it's not at the heart of downtown, the Sheraton Austin provides easy access to everything, such as the capitol, 6th Street, the Red River District, the business district, many attractions, and the University of Texas main campus. Because of this, the Sheraton is a great place to hunker down for a few days. The views are great and the restaurant isn't bad either. **Omni Austin Hotel Downtown** (700 San Jacinto Blvd. at 8th St., 512/476-3700 or 888/444-6664, www.omnihotels.com, $200-300) is a four-diamond hotel in the heart of downtown. A favorite of celebrities, rock stars, and rich folks, the Omni is 20 floors of elegance topped with a rooftop pool and hot tub. Guests are spoiled rotten by the in-house fitness center, on-site massage, sauna, cocktail lounge, and restaurant. The **InterContinental Stephen F. Austin Hotel** (710 Congress Ave., 512/457-8800, www.austin.intercontinental.com, $209-299) embodies the best of old and new in Austin luxury lodgings. The historic hotel is smack-dab in the middle of all the downtown action but retains a calm, upscale vibe, standing serenely above it all. Everything is within a stone's throw—the capitol, music clubs, great restaurants, and museums. The hotel was built in 1924, and although it has gone through major renovations, it still retains the historical class of a bygone era. Besides offering guests elegant rooms with amenities that pamper, the hotel has a balcony bar that is very popular, especially with legislators. There's also a health club featuring a lap pool, a Mediterranean-themed café called Julienne, and a restaurant called Roaring Fork, which serves first-class southwestern cuisine. **Radisson Hotel on Lady Bird Lake** (111 E. Cesar Chavez St., 800/395-7046, www.radisson.com, $198-300) is one of the better downtown accommodations in this price range. This centrally located hotel offers great views of the city and quality service. If you stay here you simply must take the time to walk around Lady Bird Lake, which is just out the back door. Breakfast and rooms with stunning views will cost you a tad more; rooms on the south side have views of Austin's famous bats in summer months. Booking online can get you better rates. The TGI Friday's restaurant in the hotel is one of the best spots in town to watch the bats fly from their roosts on summer evenings. If you are less interested in Austin downtown nightlife and want to be near the UT campus or Austin's museums, consider a stay at **AT &T Hotel & Conference Center at the University of Texas** (1900 University Ave., 512/404-1900, $219-300). The hotel is modern, with all expected amenities. The best thing about this place is the location. Situated in the heart of Austin, it is within walking distance (a city block or two) of the Bullock Texas State History Museum, Blanton Museum of Art, the UT campus, and the Drag at Guadalupe Street. The Texas State Capitol is pretty close by as well. Just remember this is a run-of-the-mill hotel. Nothing weird here, which is what some folks need when traveling. On the West End is S **Austin's Inn at Pearl Street** (809 W. Martin Luther King Blvd. at Pearl St., 800/494-2261, www.innpearl.com, weekday rates from $165, weekend rates from $355). With wicker chairs, kitsch in every nook and cranny, floral patterns on the walls, and a calm, spiritual feel, this establishment personifies the bed-and-breakfast. There are 12 rooms, each with a different theme, such as safari, Oxford, Venetian, and even tree house. Does Shirley MacLaine live here? No—but it sure does seem like she's the decorator. There's a two-night minimum on weekends. For a rustic and romantic experience outside of town there's **Lost Parrot Cabins** (15116 Storm Dr., 512/266-8916, www.austincabinrentals.com, $225-285), which is situated on eight acres near Mansfield Dam, about 1.5 miles from Lake Travis. This wildly colorful little Mexican-style villa is a perfect place to get away from it all. All cabins are private, complete with hammock and rocker, and to make it even easier you can park next to your cabin. Pets are welcome with an additional fee. The best weekend-getaway bed-and-breakfast at Lake Travis is **Robin's Nest** (1007 Stewart Cove, 512/266-3413, www.robinsnestlaketravis.com, $149-250). Beautiful views of the lake, comfortable lodgings, and proximity to water sports, fishing, and swimming holes make this nest an easy choice for an excursion away from town. Lodgings include three homes and nine guest rooms. #### **OVER $250** Romantic fine dining, horse-drawn carriages, and old Western Gothic architecture collide right in the heart of downtown at S **The Driskill Hotel** (604 Brazos St., 512/474-5911 or 800/252-9367, www.driskillhotel.com, $290-390). The Driskill has been Austin's premier luxury hotel since 1886. They've mastered Texas charm, opulence, and drama by providing guests with lavish rooms decked with gigantic curtains, fancy tile bathrooms, and ornate beds. The hotel also has an award-winning restaurant, a piano bar, and a fitness studio. With a great downtown location right on 6th Street, there's access to bars, live music, museums, touristy shops, and the capitol. Out front you can catch a horse-drawn carriage for a romantic tour through downtown. Rates vary depending on room and season, but an average rate can start at around $300 a night and go as high as $1,000. The Driskill Hotel Finally, someone brought the dusty old bed-and-breakfast model into the 21st century. Say good-bye to Bob Newhart and say hello to Mork and Mindy! Sleek, modern, whitewashed, and downright soothing, the **Kimber Modern** (1220 S. Congress Ave., 512/441-1157, www.kimbermodern.com, $285-450) is a choice high-end place to stay off South Congress. You can shop, eat, catch some music, and return to your futuristic digs and soak in a tub. The lady who runs the place is friendly, the breakfast is fresh and healthy, and the common lounge is an excellent space to read and sip coffee. Austin's classiest four-star hotel is **The Four Seasons** (98 San Jacinto Blvd., 512/478-4500, www.fourseasons.com/austin, $300-900). This is a luxury hotel for the crème de la crème, the beau monde, the privileged class, and for celebrities—as well as the average Jack or Jill who wants to spend some hard-earned cash on a fancy bed. Okay, the Four Seasons is more than a bed, it's a swank hotel set on a quiet piece of Lady Bird Lake, affording a tranquil space, rooms with unforgettable views of the skyline, private balconies, oversized cotton bath towels, down pillows, terry-cloth bathrobes, and bend-over-backwards hospitality. The Queen of England stayed here when she visited Austin. If it's good enough for the queen. . . . One of the top 10 best spa resorts in the world is right here just outside Austin. According to _Travel + Leisure_ magazine, **Lake Austin Spa Resort** (1705 S. Quinlan Park Rd., 512/372-7300 or 800/847-5637, www.lakeaustin.com) is world class. Located only 25 minutes from downtown Austin on a quiet spot on the shores of Lake Travis, this resort is an extraordinary place to immerse yourself in yourself. In their own words, this is "an exquisite escape into natural beauty and personal discovery." Thanks to soothing minimalist architecture, classy modern Asian flair, beautifully manicured gardens, and exquisite hospitality, you can't help but completely forget about the outside world. Although they offer vacation packages, they also offer day packages. So what goes down here? Water aerobics, water yoga, swimming in indoor and outdoor pools, tai chi classes on the shores of the lake, kayaking, cooking classes, boat cruises, and relaxing in hammocks. Vacation packages can be 3-7 days, and rates vary depending on what you want to experience, ranging $1,400-2,300. Guests are free to participate as much or as little as desired. Austin's fancy place to stay downtown is the S **W Austin** (200 Lavaca St., 512/542-3600, www.starwoodhotels.com). Besides being the hotel in the middle of Austin's newer downtown 2nd Street District, where shopping and restaurants are plentiful, the LEED-certified W Austin shares a roof with the new _Austin City Limits_ studio, where live performance taping happens. Guests can expect the ultimate in service with the hotel's signature Whatever/Whenever service, pampering guests with "whatever you want, whenever you want it." Rates range $300-400 depending on room size and amenities. If you are a rock star or want to be treated like one, you can enjoy one of the Marvelous Suites for $1,000 per night. New to Austin is the trendy **Hotel Van Zandt** (605 Davis St., 512/542-5300, $300-450). Yes, this place is a little pricy, but for the upper-class traveler there's a lot you can get for the money. The decor is beautiful and the location can't be beat: It is situated in the Rainey Street District, which has great bars, restaurants, food trucks, and fabulous nightlife. The hotel has a stunning pool area with city views and free daily happy hour of wine and margaritas in the lobby is also something that has to be mentioned. Also, free bicycle rentals are available. If you want stylish lodgings near the action on South Congress Avenue, **South Congress Hotel** (1603 S. Congress Ave., 512/920-6405, $250-400) is highly recommended. The overall tone of this place is alluring, with its midcentury modern design and classy but friendly atmosphere. There are few things better than walking out of a retro hotel and down South Congress to the funky shops or to catch a show at the Continental Club. Because of its location, you can do all the above with a buzz and simply walk back to your room. The hotel features an outdoor pool, a bar in the lobby, a café, and a full-service bar and grill. **Hotel Ella** (1900 Rio Grande St., 512/495-1800, www.hotelella.com, $250-350) has historical charm and modern class. Just northwest of downtown in a quiet neighborhood near the UT campus, this converted mansion, which was built in the late 19th century, has spacious contemporary rooms, an interior courtyard with a pool, private cabanas, a fine-dining restaurant, fitness center, and a lounge. Some rooms have an added touch of romance with balconies overlooking the hotel grounds and courtyard access. All you could need for a pleasant, romantic, relaxing evening is right here. The world got you drained? A weekend getaway to a wellness spa is a great way to recharge your inner battery. **Travaasa** (13500 FM 2769, 877/261-7792, www.travaasa.com/austin, $250-475), just 20 miles northwest of Austin, offers peaceful accommodations along with a busy schedule of workshops and conferences for guests. This is the only place in the area where you can enjoy spa treatments, mechanical-bull-riding workouts, cooking classes, horseback riding, and learning to dance the Texas two-step. The breathtaking 205-acre campus has hiking trails, pools, green architecture, and a spectacular view of Lake Travis. Guests are welcome to just shack up here or get involved. A discount is offered for those who combine spa and/or workshops with accommodations. ### **Information and Services** #### **TOURIST INFORMATION** The **Austin Convention and Visitors Bureau** (800/926-2282, www.austintexas.org) is a great resource for travel and tourism information before you land in Austin. The easy-to-navigate website offers lots of concise information, and the person at the other end of their toll-free number can offer advice and information on anything Austin-related as well. For a brick-and-mortar information center, there's the **Austin Visitor Center** (602 E. 4th St., 512/478-0098, 9am-5pm daily) The knowledgeable staff can help you find the right accommodation on short notice, supply maps of the town, and help with anything else necessary for survival in Austin. You can call **Austin's 311** information line (512/974-5000) to get answers to most questions about Austin, transportation, and even lost and found. #### **EMERGENCY INFORMATION** In the event of an emergency involving injury or danger dial **911.** Other nonemergency numbers are as follows: **Austin Police Department** (311 or 512/974-5000); **Brackenridge Hospital** (601 E. 15th St., 512/324-7000), downtown; **St. David's Hospital** (919 E. 32nd St., 512/476-7111), north of downtown; **Seton Medical Center** (1201 W. 38th St., 512/324-1000), near the UT campus; **Dell Children's Medical Center of Central Texas** (4900 Mueller Blvd., 512/324-0000); and **People's Community Clinic** (2909 N. IH 35, 512/478-4939 or 512/478-8924), for uninsured patients who pay on a sliding scale. If you're on vacation and have a shoe emergency there's **Austin Shoe Hospital** (720 Congress Ave., 512/477-5078). In addition to the downtown location there are several others in the Austin area where they can fix your sole. #### **PUBLICATIONS** The local newspaper, the **_Austin American-Statesman,_** is an average medium-size-city newspaper—nothing to write home about. The _Statesman_ covers all the basics, including local, national, and international news; sports; business; classifieds; and entertainment. Every Thursday the paper has an entertainment section called "Xlent." The _Statesman_ can be found anywhere in town. The city's alternative weekly rag, the **_Austin Chronicle,_** on the other hand, is excellent. What it lacks in design and layout it makes up for in colorful, opinionated content. Look to the _Chronicle_ for information on music, events, films, the arts, food, kids' activities, and local politics. The _Chronicle_ comes out every Thursday and is free for the taking at almost every restaurant, café, and shopping center in town. Many U.S. cities take a stab at having a classy, sophisticated, hip magazine, and most totally fail. But **_Austin Monthly_** is a high-caliber city magazine that works. In here you'll find articles that cover everything current, including culture, politics, entertainment, and tasteful celebrity cover stories. The full-color, glossy magazine **_Texas Monthly_** is the best state magazine in the country. It can be purchased at most supermarkets and corner stores and is a great resource for state news, politics, and celebrity gossip. It offers a great listings section in the back with restaurant reviews. #### **INTERNET AND WI-FI** Internet access is so readily available in Austin that it's literally in the air. If you have a laptop with a wireless card you will be pleased to know that Austin has more free Wi-Fi hot spots than anywhere else on the planet. Walk into almost any café in town and chances are you can surf for free on your own computer. Businesses in the downtown area sure to have wireless Internet are: **Halcyon Coffeehouse** (218 W. 4th St., 512/472-9637), **Jo's Cafe** (1300 S. Congress Ave. and 242 W. 2nd St., 512/444-3800), **Mozart's Coffee Roasters** (3852 Lake Austin Blvd., 512/477-2900), **Wright Bros.** (500 San Marcos St., 512/493-0963), **Dominican Joe** (515 S. Congress Ave., 512/448-3919), **Thunderbird Coffee** (2200 Manor Rd., 512/472-9900), **Austin Java** (1608 Barton Springs Rd., 512/482-9450, and 1206 Parkway, 512/476-1829), **La Tazza Fresca** (519 W. 37th St., 512/453-0403), and **Spider House** (2908 Fruth St., 512/480-9562). Most hotels have Internet service as well. For those without a laptop there are many outlets to get connected. All Austin public libraries offer free Internet access provided you have a valid ID such as a driver's license and one other form of ID. For locations call 512/974-7400. For everyone else there's a **FedEx Office** (327 Congress Ave. #100, 512/472-4448) downtown and elsewhere around Austin. Rates are $0.20 or $0.40 per minute depending on the computer. #### **MUSICIANS' RESOURCES** Since thousands of bands and musicians make their way through Austin on tour every year, it seems fitting to offer some tips on where to get your guitar set up, where to rent gear, and where to sneak in a rehearsal. The largest selection of equipment and gear rental is offered by **Rock N Roll Rentals** (1420 Oltorf St., 512/447-5305, www.rocknrollrentals.com). Here you'll find guitars, basses, amps, drums, and keyboards. When festivals are happening gear can be hard to find, so reserve equipment in advance. If you are on tour and want to work on new material or brush up on your chops, **Music Lab** (1306 Oltorf St. and 500 E. St. Elmo Rd., 512/326-3816, www.musiclab.net) offers affordable rehearsal rooms by the hour. Prices range $12-15 per hour and rooms include PA and mic stands. Any gear beyond this can be rented for reasonable hourly rates. Several shops in town offer guitar and amp repair but most are generally booked out a few days. The best shops in town for guitar repair are **Austin Vintage Guitars** (6555 Burnet Rd., 512/428-9100), **Strait Music** (2428 W. Ben White Blvd., 512/476-6927), and **South Austin Music** (1402 S. Lamar Blvd., 512/448-4992). The best shops in town for amp repair are **Austin Vintage Guitars** (6555 Burnet Rd., 512/428-9100) and **Audiotech Austin** (2213-B S. 1st St., 512/673-7141). With many vintage guitar boutiques and new music shops in Austin, buying new and used gear can be a blast. Amazing selections of vintage guitars and basses can be found at **Austin Vintage Guitars** (6555 Burnet Rd., 512/428-9100) and **South Austin Music** (1402 S. Lamar Blvd., 512/448-4992). The place to buy drums and accessories is **Tommy's Drum Shop** (1100 S. 8th St., 512/444-3786). Lastly, the music store that offers just about everything is **Strait Music** (2428 W. Ben White Blvd., 512/476-6927). #### **LAUNDRY** For coin-operated laundry machines in central Austin there's **Laundry Works** (606 W 29th St., 512/482-9274). In South Austin there's **Quick Wash Laundry** (6800 West Gate Blvd #129, 512/609-8858), and near UT campus there's **Convenience Coin Laundry** (909 W 24th St.). For environmentally friendly dry cleaning there's **EcoClean** (4012 N. Lamar Blvd., 512/236-8645). #### **POST OFFICE** The centrally located post offices are as follows: **Downtown** (823 Congress Ave. Ste. 150, 512/473-8334); **Capitol Station** (111 E. 17th St., 512/477-7082) downtown near the capitol; **Central Park Station** (3507 N. Lamar Blvd., 512/420-0310) in Central Austin; and **University** (2201 Guadalupe, West Mail Building, 512/232-5488) on the UT campus. For information on other locations call 800/275-8777. UPS Stores are all over town. For locations call 800/742-5877 or visit www.ups.com. #### **MONEY** It takes money to get money. ATM kiosks are everywhere, but beware: The ATMs you find on the street, such as on 6th Street, Red River, and Congress Avenue, all charge extraordinarily high fees. It's always best to get money from your own banking institution, but if your bank isn't to be found, at least use a national bank. You may still incur a fee, but it will be much less than at kiosk ATMs. My favorite ATM in town, and possibly in the world, is the one planted in the rickety old wooden fence on Red River Street at Stubb's Bar-B-Q. I would never get money from it—it's just an interesting sight to behold. Also, Austin doesn't seem to have a problem with pickpocketing, so you don't need to be looking over your shoulder like you do in other cities. ### **Transportation** #### **GETTING THERE** ##### **Air** The main airport that services the Austin metropolitan area is **Austin-Bergstrom International Airport** (300 Presidential Blvd., 512/530-2242), eight miles southeast of downtown. This converted air force base offers international connections that can get you to anywhere in the world. Major passenger airlines include America West (800/235-9292), American Airlines (800/433-7300), Delta (800/221-1212), Frontier Airlines (800/432-1359), Southwest (800/435-9792), and United (800/241-6522). The airport terminal has several restaurants (including the famous barbecue of the Salt Lick), coffee shops, and, of course, the usual airport gift shops filled with irritating flying toys, paperbacks, coffee mugs, tourist T-shirts, and key chains. There's one shop that is worth making an attempt to check out if you aren't running to catch a plane, and that's the **Austin City Limits** store. And, true to Austin's love of live music, the airport often has live music. Because of this Austin's airport has landed on _USA Today_ 's list of "10 great places to hang out during a layover." The one big drawback to Austin-Bergstrom International Airport is that passengers often have a connecting flight, and this can eat up most of a travel day. There are only 52 destinations with nonstop service to and from Austin, and nearly all are domestic cities that are "lesser traveled." However, what ABIA is lacking in connections is made up for by convenient parking, which is close to the terminal and easily accessed, with no wait and no hassle. Airport parking is free for the first 30 minutes, $3 each additional hour, and $7 per day. The day rate for the close-in covered parking garage is $23 per day. Travelers heading to Austin-Bergstrom can call the airport for parking availability and other airport information 24 hours a day. There are several ways to get from the airport to town. The most economical way is **SuperShuttle** (512/258-3826 or 800/258-3826), which costs about $18 to take one person to the downtown area. Taking a cab to downtown costs about $22-25. An alternative way to get to the city is by using a ride-hailing company/app. Uber and Lyft left Austin in 2016. However, **Ride Austin** (rideaustin.com) and **Fasten** (fasten.com) are recommended. Ride Austin is a nonprofit raising money for local Austin charities, so you get a ride and do some good. The fare from the airport to downtown is around $17. To drive from the airport to downtown, exit the airport and take Highway 71 west. Follow Highway 71 until you get to Interstate 35 and go north. The drive takes 20 minutes. ##### **Car** If you are driving from Dallas to Austin, take Interstate 35 south, which goes through the heart of downtown Austin. The drive takes about 3-4 hours. If you are driving from Houston to Austin, take Highway 290 west. Once you arrive in Austin, take Interstate 35 south to downtown. The drive takes about 2.5-3 hours. If you are driving from San Antonio to Austin, take Interstate 35 north, which will take you right to the heart of downtown Austin. The drive takes about 2.5-3 hours. ##### **Bus and Train** If you have a fear of flying, a low budget, or a fascination with the underbelly of America, there's always ground transportation to get you to and from Austin. The two bus lines available are **Greyhound** (800/231-2222, www.greyhound.com), which services just about anywhere in the contiguous United States, and **Kerrville Bus Company** (800/474-3352), which serves many of the smaller Texas towns, including many in the Hill Country. Using Greyhound bus service to get to Austin from Dallas, Houston, or San Antonio is very affordable and travel times are surprisingly efficient. This is also a great way to see the countryside and meet some interesting folks. Buses to Austin from Dallas, San Antonio, and Houston are available every 2-3 hours. The bus ride from Dallas takes about 3-3.5 hours and the standard fare is around $20-25. The ride from San Antonio takes about 1.5 hours and the standard fare is $11-16. The ride from Houston takes about three hours and the standard fare is $16-22. The **bus station** (916 E. Koenig Lane, 512/458-4463) is inconveniently located far north of downtown. Capital Metro bus 15 (Red River) or 7 (Duval) going south can get you from the bus station in North Austin to downtown; the buses run approximately every 30 minutes and the fare is about $1. Traveling by train via **Amtrak** (250 N. Lamar Blvd., 800/872-7245, www.amtrak.com) is also a great and nostalgic way to make your way to and from Austin. However, travel times can be much longer than via bus. Trains to Austin from Dallas are available daily and leave around noon. The travel time is about 6.5 hours and the standard fare is $35. Trains to Austin from San Antonio are available daily and leave at about 7am. The travel time is about 2.5 hours and the standard fare is $17. Trains to Austin from Houston are available twice a day, one in the morning at 7am and one in the evening at 7pm. The travel time is about 2-5 hours, depending on scheduled stops along the way, and the standard fare is $51. The Amtrak **train station** (250 N. Lamar Blvd., 512/476-5684) is conveniently located right in the heart of downtown, near Lady Bird Lake. #### **GETTING AROUND** It's fairly easy to get around Austin, which makes for less time traveling and more time enjoying the city. Most everything is conveniently accessible either by foot, bus, cab, or bike. However, if you plan on hiking some of the trails in and around Austin, visiting the Lady Bird Johnson Wildflower Center, or exploring the Hill Country, you'll want to rent a car. ##### **Car** Getting around Austin by car is not necessary, but a car can provide the most freedom and is the best way to make the most of your time. There are only a few major freeways in the metropolitan area, and only a few major streets connect everything to downtown, which makes it easy to find your way around. One minor drawback to using a car is downtown parking, which can require patience and a good eye. Fee parking garages are available to eliminate parking woes. All the usual rental car companies are represented on the ground floor at Austin-Bergstrom International Airport as well as around town. Car rental agencies include **Advantage Rent-A-Car** (800/777-5500), **Alamo Rent-A-Car** (800/462-5266), **Avis Car Rental** (800/331-1212), **Budget** (800/527-0700), **Dollar Rent-A-Car** (800/800-3665), **Enterprise** (800/261-7331), **Hertz Rent-A-Car** (800/654-3131), **National Car Rental** (800/222-9058), and **Thrifty** (800/847-4389). If you prefer not having a rental car as a ball and chain, a practical and effective way to get around in by using a ride-hailing company/app. Uber and Lyft left Austin in 2016. However, **Ride Austin** (rideaustin.com) and **Fasten** (fasten.com) are operating. Garage parking rates, hours, and allowed length of stay vary by location. Outside of special events, rates are typically a minimum of $5. The best parking for the 2nd Street Shopping District and for ACL Moody Theater is the **City Hall Garage** (200 Lavaca St., open 24 hours, $4 per hour). The best parking for live music in the Red River District is **Lot 119** (500 E. 8th St., open 24 hours, $6 per hour). The best garage for the 6th Street District is **Car Parked** (615 San Jacinto Blvd., open 24 hours, $14 per day). The best garage for visiting the capitol building and grounds is the **Capitol Visitors Parking Garage** (1201 San Jacinto Blvd., open 24 hours, first 2 hours free, $1 each additional 30 minutes, $8 per day). ##### **Bus** Austin's public transportation system, **Capital Metro** (512/474-1200, www.capmetro.org), is intuitive, easy to get the hang of, and inexpensive. Buses operate 24 hours for most main lines. Most individual rides are $1 (exact change only), but you can get the most for your money if you buy a $9 seven-day pass that offers unlimited rides for a week. Passes are available at any H.E.B. grocery store and at the **Capital Metro Transit Store** (323 Congress Ave.). Capital Metro's very informative website is a great place to get schedule and route information. This information can also be found at most supermarkets in town and at the Capital Metro Transit Store. A map of the bus lines can be downloaded at www.capmetro.org. A printed map can be picked up at the **Austin Visitor Center** (602 E. 4th St., 512/478-0098). ##### **Taxi** Taxi service is available 24 hours a day, seven days a week. Smoking and nonsmoking cabs are available thanks to city regulations. Hailing a cab downtown can take some time, so I recommend calling one of the following cab companies to get faster service: **Yellow Cab** (512/452-9999), **Austin Cab** (512/478-2222), and **Lone Star Cab** (512/836-4900). Fares are $4.50 for the first mile and $2.40 for each additional mile. ##### **Bicycle** Austin is a bicycle-friendly town, but it hasn't always been that way. Before Lance Armstrong became a celebrity athlete, cyclists were considered an inconvenience out on the motorways. Now Austin has miles of designated bicycle lanes and very respectful motorists. The City of Austin's Bicycle and Pedestrian Program (www.ci.austin.tx.us/bicycle) has a helpful map of suggested routes. It's also good to note that all Capital Metro buses are equipped with bike racks. However, if you plan to use a bicycle to get around, be forewarned that Austin has a dreadful problem with bike thievery. Cycling around downtown Austin can be a great way to see the sights and get from South Congress to the metro area. Austin has introduced a cool bike-sharing service called **Austin B-cycle** (512/954-1665, austin.bcycle.com). With a network of 24/7 on-demand bicycle stations throughout downtown, Austin B-cycle provides an easy, fast way to navigate the city core. To access the network of bikes you need to purchase a weekly pass online or purchase a day pass at any of the stations. Day and week pass holders swipe the credit card they used to purchase the pass at the station kiosk to check out a bike. When you are done riding, return your bike to any station in the system and plug it into any empty dock in the station. Annual memberships are $80, weekly passes $25, and day passes $8. Your access pass or membership gives you unlimited checkouts up to 30 minutes at no charge for the access period. Bike-share locations can be found all over downtown and on South Congress. Check the website for more details or download the handy app for iPhone or Android. Other bike rental services are available. The premier place to rent a bicycle for the day is **Bicycle Sport Shop** (517 S. Lamar Blvd., 512/477-3472, 10am-7pm Mon.-Fri., 9am-6pm Sat., 11am-5pm Sun.). They rent just about anything, including mountain bikes, road bikes, tandems, kids' bikes, and trailers. Prices range $28-35 for four hours and $18-50 for 24-hour rentals. Rates vary depending on the type and make of bike. For quick and easy transportation around downtown, **Heart of Texas Pedicab** (512/930-8791), **Capital Pedicab** (512/448-2227, www.capitalpedicab.com), and **Metrocycle** (512/825-1276) can sweat it out for you. Service is available primarily around 6th Street, Congress Avenue, and the Warehouse District. Pedicab rates vary; a trip from one part of downtown to another can be $10-20, not including tip. Hamilton Pool ## **The Hill Country** PLANNING YOUR TIME HIGHLIGHTS ORIENTATION Central Hill Country HAMILTON POOL ROAD S THE SALT LICK PEDERNALES FALLS STATE PARK JOHNSON CITY S BECKER VINEYARDS S FREDERICKSBURG S ENCHANTED ROCK STATE NATURAL AREA COMFORT OLD TUNNEL BATS BOERNE GUADALUPE RIVER STATE PARK S NATURAL BRIDGE CAVERNS AND WILDLIFE RANCH Western Hill Country KERRVILLE WEST OF KERRVILLE LOVE CREEK ORCHARDS BANDERA VANDERPOOL S LOST MAPLES STATE NATURAL AREA UVALDE Eastern Rim MCKINNEY FALLS STATE PARK SAN MARCOS WIMBERLEY NEW BRAUNFELS GRUENE Transportation inside Gruene Hall, one of Texas's oldest dance halls. The central region of Texas, known as the Hill Country, is perhaps the most lush, beautiful, and culturally interesting area in the state. It's characterized by rolling hills, oak trees, dance halls, wildflowers, wineries, abandoned cars in fields, honky-tonks, dude ranches, state parks, and frontier towns scattered throughout the hills. Every square mile and every corner of the Hill Country is spilling over with history and legend. From clashes between the native Apache and Spanish settlers, to the founding of towns by German settlers, to old ranches as large as 50 square miles, the history here is rich and compelling. Over the years the Hill Country has been home to many wildly interesting characters, such as outlaws, pioneers, presidents, rodeo cowboys, and musicians. Today the Hill Country is a place where people come to get away and have a unique Texas experience. In the Hill Country you can be a cowboy for a weekend at one of Bandera's many dude ranches; hike to the top of an enormous pink granite rock at Enchanted Rock State Natural Area; see an original Rembrandt hanging on a wall in a bank in Uvalde; go horseback riding in the Hill Country State Natural Area; catch a live performance at Gruene Hall, Texas's oldest dance hall; tube down the Guadalupe River in New Braunfels; and encounter the German heritage of Central Texas by visiting Fredericksburg. Although it's expected that visitors will romanticize the Hill Country as being a living Wild West, it's still 21st-century America. Some areas in the Hill Country look like scenes from the movie _Deliverance,_ while some are reminiscent of Napa Valley. This combination is what makes this region so interesting. #### **PLANNING YOUR TIME** Because all the points of interest in the Hill Country are spread out, it's wise to plan your time before setting out on your journey. There are two ways people experience this region; the most common is by choosing a town and settling in for the weekend. This approach is great for a weekend getaway because it is low stress, low travel, and totally relaxing. The other approach, which is less common but becoming more and more popular, is road-tripping through the Hill Country. It can take up to seven days to fully explore the whole region as outlined in this chapter. However, a three- to four-day weekend can be sufficient for a road trip that includes major attractions. **Highlights** Look for S to find recommended sights, activities, dining, and lodging. S **Hamilton Pool Preserve:** The grotto-like pool is a great swimming hole is the most beautiful spot in all of Hill Country—and a gorgeous place to hike (click here). S **The Salt Lick:** This famed barbecue mecca offers a Civil War-era brisket recipe, unmatched hospitality, and a remote setting that is worth the drive (click here). S **Becker Vineyards:** Sip a glass of wine on the porch at sunset and be sure to walk away with at least one bottle of Texas's best wine (click here). S **Fredericksburg:** With bed-and-breakfasts, quaint shops, schnitzel, and polka music this Texas version of Bavaria bewitches and bedazzles visitors (click here). S **Enchanted Rock State Natural Area:** Legend and mystery surround this giant pink granite dome, which affords spectacular panoramic views (click here). S **Natural Bridge Caverns and Wildlife Ranch:** The Hill Country is beautiful on the outside and dark and mysterious on the inside—in the many caves at Natural Bridge Caverns (click here). S **Stonehenge II:** In a field in the middle of nowhere is a smaller version of the mysterious monument in Salisbury, England. This version wasn't created by aliens or druids, but by a local attorney with a crazy idea (click here). S **Lost Maples State Natural Area:** This remote state park explodes with color in the fall (click here). S **Tubing the Guadalupe River:** In the summer you'll find thousands of folks sunning, relaxing, and drinking as they bob down the river (click here). All towns in the Hill Country are a one- to two-hour drive from Austin and/or San Antonio. The distance between towns is generally under 50 miles, with some as close as 30 miles, which is great because drive time doesn't eat up too much of the day. Out of the dozens of towns in the Hill Country, there are only a few that will lure you in for a night or two: Fredericksburg, Bandera, Kerrville, Boerne, Gruene, New Braunfels, and Wimberley. For these towns plan on setting aside a full day for exploring, eating, and just meandering. All the little towns in between are good for some barbecue, roadside peaches, antiques, and maybe an hour or two of poking around. #### **ORIENTATION** Although there is no agreed-upon boundary that circumscribes the Hill Country, it can generally be defined as the incredibly vast area smack-dab in the center of the state of Texas. The area of the Hill Country with towns and attractions that merit mention as travel destinations is best broken into the following regions: the **Central Hill Country,** which includes some of the more touristy spots; the **Western Hill Country,** which stretches as far as Vanderpool; and the **Eastern Rim,** also known as the Austin-San Antonio corridor, which travels along I-35 south of Austin en route to San Antonio. ### **Central Hill Country** The gateway to the Hill Country is the small town of Dripping Springs on Highway 290 west of Austin. This little backgammon-loving, slow-moving wide spot in the road is known to locals simply as Drippin'. Dripping Springs once was a country-bumpkin ranch town, but it's quickly being swallowed by Austin. People are buying acreage, building mansions, and driving SUVs to and from the "big city." Once you pass through Dripping Springs into the Hill Country, all its grandeur rolls out like a red carpet before your very eyes. #### **HAMILTON POOL ROAD** Just north of Dripping Springs, about 30 miles west of Austin, there's FM 3238, better known as Hamilton Pool Road. Out on this rural country thoroughfare are three main attractions that are drawing increasing numbers of outdoors lovers, and there are caves, waterfalls, rivers, swimming holes, and trails all within a few miles of each other. This off-the-beaten-path region of outdoor activities has been discovered and developed only in recent years. As this area's popularity grows I hope and pray it doesn't get overrun. From Dripping Springs go north on Highway 12 and turn left on FM 3238 (Hamilton Pool Rd.). From Austin take Highway 290 west, then go north on Highway 71. When you come to FM 3238 (Hamilton Pool Rd.), turn left. Everything is about 10 miles up the road near the Pedernales River. ##### S **Hamilton Pool Preserve** This preserve may be over 230 acres, but the main attraction is a swimming hole. Whether you want to take a dip or not, **Hamilton Pool** (Hamilton Pool Rd., FM 3238, Dripping Springs, 512/264-2740, 9am-5:30pm daily, $10 per vehicle, cash only) is a sight worth seeing. It's considered the most beautiful natural swimming hole in Texas because a majestic 45-foot waterfall spills into a deep, grotto-like pool that was formed when the dome of an underground river collapsed hundreds of years ago. In the hot summer months the preserve is usually filled to capacity. The parking lot can fit about 75. Because the park is so small and ecologically sensitive, reservations are required to enjoy Hamilton Pool during peak travel months. The park is often full, so making reservations online well in advance is recommended. You can do so at parks.traviscountytx.gov/reservations. **Hill Country Festivals and Events** Thanks to the great weather that the Hill Country enjoys for most of the year, the calendar of events is chock-full of things to do. **APRIL** Folks in Wimberley love butterflies so much they have a day dedicated to these little larvae that turn beautiful. On a weekend in April the **Emily Ann Theatre Butterfly Day** (1101 FM 2325, 512/847-6969, www.emilyann.org) becomes the focus of town. There's live music, plays and skits, and fun for kids and the whole family. Wimberley offers a peek into the studios of some of its artists during **Arts Fest** (Wimberley Visitors Center, 512/847-2201, www.wimberleyartsfest.com). Near the Blanco River, Wimberley's Waters Point Retreat is filled with booths and arts spaces visited by over 3,000 art lovers. Artists represent a number of media, including oil painting, watercolor, mixed media, and sculpture. Most artists are locally, nationally, and even internationally renowned. **MAY** The biggest and longest-running festival in the Hill Country is the **Kerrville Folk Festival** (830/257-3600, www.kerrville-music.com). Starting the Thursday before Memorial Day, this 18-day folk implosion draws the biggest names in Americana, folk, bluegrass, acoustic rock, blues, and country. Live music, arts and crafts, fun for the kids, camping, and food and beverages are all within arm's reach. The festival takes place at Quiet Valley Ranch, nine miles south of Kerrville on Highway 16. Tickets vary by day but generally run $30 in advance and $40 at the gate. Tickets for all 18 days can be $400-600. **JUNE** For a peach of a time, the town of Stonewall has its annual **Peach JAMboree and Rodeo** (830/644-2735, www.stonewalltexas.com). At the height of peach season, locals get together for live music and dancing in honor of the fuzzy fruit. **SEPTEMBER** **Celebrate Bandera** (www.celebratebandera.com) is where to be on Labor Day weekend in the Hill Country. Every year the town of Bandera becomes a giant celebration that includes a real cattle drive, an intertribal Native American powwow, bull-riding competitions, concerts, parades, rodeos, and a Bloody Mary street party. Some events charge a fee and some are free. Check out the website for specific information. At the Quiet Valley Ranch is the **Kerrville Fall Music Festival** (830/257-3600 or 800/435-8429, www.kerrville-music.com). Songwriters and entertainers from all around the United States make their way to Kerrville for this three-day festival, which includes camping. The ranch is nine miles south of Guadalupe River on Highway 16 between Medina and Kerrville. Tickets are $25 in advance and $30 at the gate. Fredericksburg hosts the **Renewable Energy Roundup & Green Living Fair** (830/997-2350, www.theroundup.org). This green-building fair features exhibits, demonstrations, and workshops all espousing the new products and technologies related to the field of renewable energy and green building. It's hard to determine whether this environmental awareness spills out from Austin's liberal hippie-ness, or whether it comes from Texas's long history of DIY independence from everything. Nevertheless, this event is essential for the green do-it-yourselfer. The roundup is held downtown at Market Square; tickets cost $10 each for Friday and Sunday and $12 for Saturday. **OCTOBER** Festivals abound in the historic German settlement town of Fredericksburg, but the one that gets everyone's lederhosen in a bunch is **Oktoberfest** (830/997-4810, www.oktoberfestinfbg.com). Held every year during the first weekend in October, this three-day bratwurst, schnitzel, and German beer extravaganza draws big crowds. Two stages, two tents, great food, polka and waltz contests, smiles, and music with an oompah make this a great weekend getaway for the family. Oktoberfest takes place at Marktplatz in the center of downtown. Hours are 6pm-midnight Friday, 10am-midnight Saturday, 10am-6pm Sunday. Tickets are sold at the entrance and cost $8 for single-day passes, $14 for two-day passes, and $18 for three-day passes. Children 7-12 are $1, and ages 6 and under are free. At the end of the month there's the **Fredericksburg Food and Wine Fest** (830/997-8515, www.fbgfoodandwinefest.com), a celebration of Texas food and wine that includes live music, specialty booths, and lots of clinking of glasses. The festival is held at Marktplatz in downtown Fredericksburg. Admission is $25. At Love Creek Orchards is one of Texas's largest and most popular pumpkin patches, The Great Hill Country Pumpkin Patch (14024 State Hwy. 16 North, Medina, 10am-4pm, admission $6). With a scheduled full of family-fun events, this is worth the drive. **NOVEMBER** For over 50 years Bandera has hosted the annual **Hunters BBQ and Outdoor Expo** (3862 TX-16, Bandera, 830/796-3280, www.banderahuntersbbq.com). Everyone gets all gussied up in camo and heads out to Antler Oaks Lodge for barbecue and beer and hunter-gatherer fellowship. The expo includes interactive exhibits, demonstrations of the latest hunting equipment, wildlife exhibits, and a live auction. The best fest in New Braunfels is **Wurstfest** (800/221-4369, www.wurstfest.com, 4pm-11:30pm opening day, 11am-midnight Saturdays, 11am-9:30pm Sundays, 5pm-11:30pm Thursdays and Fridays). This 10-day salute to sausage features accordion music, dancing, and, of course, bratwurst. It takes place at Landa Park; admission is $10 for adults, while children 12 and under are free. The Saturday after Thanksgiving the historic downtown of Comfort is taken over by **Christmas in Comfort** (830/995-3131, 10am-9pm, free). Over 150 vendors sell arts, crafts, and homemade foods, all to the soundtrack of live music. A trolley brings shoppers to the various businesses around the downtown area. **DECEMBER** The month of December means the **Lights Spectacular** in Johnson City. The Blanco Country Courthouse at the center of Johnson City's downtown is bedecked with 100,000 Christmas lights that remain lit the entire month. It's a remarkable show of BTUs and candlepower worth checking out. Local homes and businesses also get into the spirit. Thanks to a diligent parks and recreation department, the pool is carefully protected, and visitors are asked to be respectful of the environment. Swimming is allowed only when the water quality meets safe standards, so it's best to call for swimming information before trekking out to the preserve. The preserve also offers limited day use for picnicking, hiking, swimming, and nature study. Pets are not allowed, even on leashes. Drinking water and concessions are not available at the preserve, but there are toilets. Hamilton Pool Preserve is about 30 miles west of Austin. ##### **Westcave Preserve** Just down the road from Hamilton Pool Preserve is **Westcave Preserve** (24814 Hamilton Pool Rd., 830/825-3442, westcave.org), another natural spot that demonstrates the dramatic topography and geographical history of the Hill Country. At this well-preserved, often-overlooked park, there's a cave, spectacular waterfalls, and an award-winning environmental learning center. The trail in the park can only be accessed with a guide. Canyon trail tours are offered Saturday and Sunday at 10am, noon, 2pm, and 4pm and cost $5 for adults, $2 for children under 12, and $15 for families. No pets are allowed on the grounds, even in cars. Toilets are available but there is no drinking water. ##### **Milton Reimer's Ranch Park** **Milton Reimer's Ranch Park** (23610 Hamilton Pool Rd., 512/264-1923, 7am-sunset, $10 per vehicle) has exploded onto the scene as a popular spot for outdoor recreation in the Hill Country. Reimer's was originally a privately owned ranch where people could pay a few bucks to do some fishing, camping, and rock climbing. Mountain bike trails have increased the list of activities. The ranch is on the banks of the beautiful Pedernales River, which makes for a great place to cool off on hot days. Getting to the ranch can be tricky. On Hamilton Pool Road there's a sign that says Milton Reimer's Fishing Ranch. Turn here and follow the rugged dirt road until you come to a gate. Go through the gate and stop at the house, where someone will come out to take your money. Then park and play. #### S **THE SALT LICK** Animals on the ranch congregate around what's called a salt lick, which is a big block of sodium sitting in a field. Humans in Central Texas have a place to congregate too, and it's called **The Salt Lick** (18300 FM 1826, Driftwood, 512/858-4959, www.saltlickbbq.com). If barbecue was a religion, its devout followers would make this age-old landmark their hallowed pilgrimage site. This mecca for the golden calf of brisket is nearly 45 minutes outside of Austin in a wide spot in the road called Driftwood. The Salt Lick's award-winning barbecue is truly legendary, as its recipes have supposedly been handed down since the Civil War. With time-tested and time-honored beef brisket, sausage, smoked pork tenderloin, moist smoked turkey, potato salad, and beans on the menu, it's hard to find something even remotely close to this Texas tradition elsewhere. Besides having the best barbecue in the Austin vicinity, the Salt Lick is also known for its remarkably beautiful location. Situated on an old ranch in rolling hills of oak trees, the restaurant is housed in old buildings made of stone quarried from the ranch. The setting is almost European in feel. Legendary barbecue is cooked up at The Salt Lick. One important thing to know before driving all the way out to the Salt Lick is that you need to bring cash—they don't take credit or debit cards. However, there are some ATM machines that charge a hefty fee. Also, if you like beer with your beef, you must bring your own beverages, as the Salt Lick doesn't sell alcohol (they do have nonalcoholic drinks available). It may seem weird to some to show up with your own beer, but that's the way it's done here. Lastly, if you arrive at suppertime, be prepared to wait at the outdoor picnic tables for up to an hour to get seated. This is the time that your BYOB comes in handy. From Austin take MoPac (Hwy. 1) south. MoPac will turn into Highway 45 and dead-ends at FM 1826. Turn left on FM 1826 and the Salt Lick is about seven miles down the road on the right. If for whatever inexcusable reason you can't make it out to the Salt Lick during your visit, you can have a mini Salt Lick experience at Austin-Bergstrom International Airport. However, nothing is as good as driving out to the original barbecue mecca in the Texas Hill Country. #### **PEDERNALES FALLS STATE PARK** Along a dramatic and twisting part of the Pedernales River is **Pedernales Falls State Park** (2585 Park Rd 6026, 830/868-7304 or 800/792-1112, 8am-10pm daily, $6 per person). This rugged 5,000-acre park, featuring cypress-lined riverfront, waterfalls, and nature trails, is located just east of Johnson City and was acquired from private owners in 1970. The main attraction here is the falls, viewed from a scenic overlook at the north end of the park. Crashing down over a distance of about 3,000 feet onto limestone, the falls are most dramatic after a heavy downpour. Besides the waterfall, the park also offers hiking, mountain biking, fishing, bird-watching, horseback riding, and picnicking, and there are some wide spots in the river that are great swimming holes. The park is between Dripping Springs and Johnson City. From Austin take Highway 290 past Dripping Springs and go north on RR 3232. From Johnson City take RR 2766 east until you come to the entrance. Leisure camping with restrooms, showers, water, and electrical hookups is available as well as primitive camping, and both are on a first-come, first-served basis when the park isn't full. Reservations are suggested. #### **JOHNSON CITY** The Podunk town of Johnson City (pop. 1,700) is far from being a city. Things haven't changed a whole lot in the past 50 years in these parts. A testament to this resistance to change is that the old limestone jail built back in 1894 is still in use. The town center, where the jail is located, is a relic from the past. It's laid out in the typical town square fashion with the historic limestone county courthouse at the center surrounded by old businesses, most of which are windswept and vacant. the home where LBJ grew up in Johnson City So what's the reason for mentioning this little town? Johnson City was the boyhood home of President Lyndon B. Johnson (LBJ), which is a big deal to small-town Texas. Although Johnson City was originally named after an ancestor of his, LBJ has become its patron saint. Everything around these parts revolves around him and his memory in one way or another. ##### **Sights and Activities** The main attraction in Johnson City is the **Lyndon B. Johnson Boyhood Home** (100 E. Ladybird Ln., 830/868-7128, 9am-noon and 1pm-4:30pm daily, free) in the heart of downtown just two blocks south of Highway 290. LBJ lived in this old house from age 5 to 26, when he married. Today the house is furnished with items from LBJ's childhood, such as photos and quilts made by relatives. Unfortunately, it's hard to get inside the house due to funding and staff cuts. Nevertheless, the history buff may find the home interesting. **The Story of LBJ** Most people agree that in the 20th century, the 1960s were the tipping point in American history for social and political change. The one man at the center of this was Lyndon Baines Johnson, a native son of the Hill Country. His story is one that both exemplifies and defines the character of this heartland of Texas. Johnson was born in 1908 in the small town of Stonewall, between Johnson City and Fredericksburg. When he was five years old his family moved to Johnson City, where he graduated from high school. He received a college education in San Marcos at Southwest Texas State Teachers College, where he supported himself by working as a janitor. Lyndon Baines Johnson A few years later Johnson ended up in Washington DC, where he landed a job as the secretary to a U.S. congressman. Here he learned the trade of politics and acquired a taste for public office. In 1934, while visiting his hometown of Johnson City, he met Claudia Alta Taylor, better known as Lady Bird; shortly thereafter they got married in San Antonio. The following year his political career took off when President Franklin D. Roosevelt appointed LBJ as the Texas director of the National Youth Administration (NYA). In 1937 LBJ was elected to Congress, and he would ultimately serve five more terms in the House of Representatives. After the bombing of Pearl Harbor in 1941, Johnson became the first member of Congress to volunteer for active duty in the armed forces, and he received the Silver Star from General Douglas MacArthur for heroic efforts during an aerial combat mission over New Guinea. After World War II, LBJ was elected to the U.S. Senate. In 1960, John F. Kennedy was elected president, with LBJ as his running mate; the accomplishment LBJ is most noted for during his stint as vice president is jump-starting the space program's goals of getting a man on the moon. On November 22, 1963, President Kennedy was assassinated in Dallas. Beneath a shroud of turmoil, tragedy, and mourning, high up on Air Force One, Johnson was sworn in to the office of the presidency. LBJ's career in politics culminated in the highest office, in the lowest of circumstances. In 1964, he was elected president in his own right. His presidency has been characterized as one of the most complex. He achieved many great things, such as furthering the U.S. space program, signing the Civil Rights Act of 1964, signing the Voting Rights Act, creating the Great Society program, and ushering in landmark legislation such as Medicare. It's also important to note that he was the first president to host a barbecue on the White House lawn. The more complex side to his term in office relates to his ushering in the Vietnam War, along with the cultural upheaval that ensued. In 1969, LBJ's presidency ended. He chose not to run for another term, and instead he retired to his ranch outside Johnson City. He died only three years later. LBJ is characterized by his love of his Texas roots. The Hill Country, or as he called it, "a special corner of God's real estate," was where he hung his hat and left his heart. Today you can hear a virtual LBJ tell stories and jokes at the LBJ Library and Museum in Austin. You can also visit his ranch in the Hill Country and his boyhood home in Johnson City. Between Johnson City and Fredericksburg is the land of LBJ known as **LBJ State Park and Historic Site** (199 Park Road 52, off Hwy. 290 near Stonewall, 830/644-2252, 8am-5pm daily, free). This beautiful sprawling ranch belonged to LBJ and his wife, Lady Bird, and was their special retreat from the world. Highlights of the park include the old house where LBJ was born, the house the president had built called the **Texas White House,** his presidential plane and cars, and the cemetery where he is buried. There are also old metal trailers where Secret Service used to reside. LBJ referred to his Hill Country ranch as a "special corner of God's real estate," and this hasn't changed. The visitors center has lots of great information about the life of LBJ and his ranch. You can also watch a 25-minute movie presentation that shows LBJ driving around the ranch explaining the history and telling stories about the area. Guided bus tours of the ranch are available. During the winter holidays the beautiful old county courthouse downtown is draped with thousands of Christmas lights. People all around the Hill Country come to gaze at the dramatic display of holiday cheer that's called **Lights Spectacular.** The lights are on sunset to sunrise from the end of November to January. The most popular local business in town is **Whittington's Jerky** (604 Hwy. 281/Hwy. 290, 877/868-5500). Founded in 1963, this country jerky maker has a little store on the highway where you can find all sorts of Texas-style canned goods, country knickknacks, gifts, and of course, the jerky. It comes in several flavors, including original beef jerky, garlic beef jerky, teriyaki jerky, and turkey jerky, all smoke-dried the traditional way. The result is sticks of meat that are dry and tough to chew—perfect for gnawing during a road trip in the Hill Country. If you find yourself in town at lunchtime, stop by **Ronnie's Ice House** (211 Hwy. 281, 830/868-7553). Some of the area's best barbecue can be had in this humble and unassuming roadside eatery. The meats are flavorful and fall off the bone, and desserts such as banana pudding and buttermilk pie will make you feel like a fatted calf before you crawl out the door. Road-trippers, beware! Designate a driver, someone who won't fill up on smoked meats and sugar—driving after this meal is a challenge because the urge to sleep is mighty. #### S **BECKER VINEYARDS** It should come as no surprise that one of the most beautiful settings in the Hill Country is at a winery. Visiting **Becker Vineyards** (464 Becker Farms Rd., 830/644-2681, www.beckervineyards.com, 10am-5pm Mon.-Thurs., 10am-6pm Fri.-Sat., noon-6pm Sun.) is like being transported to Napa Valley in Northern California. Honestly, you would never know you were in the heart of Texas. At Becker Vineyards the hills are golden and the fields are rife with grapes on the vine. The wine-tasting room and attached wine production area are housed in buildings made of limestone, with expansive porches affording spectacular views. Wine-tasting fees are $12 for six samples. A quintessential Hill Country moment is had sitting on this porch with a glass of wine at sunset. The winery is four miles west of Stonewall, off Highway 290 on Jenschke Lane. #### S **FREDERICKSBURG** The most popular getaway destination in Central Texas is Fredericksburg (pop. 10,800). This big town, one of the largest in the Hill Country, is spilling over with German charm, Wild West allure, and Texas hospitality. Main Street, which runs straight through town, is lined with historic limestone buildings with wrought-iron balconies, vintage storefronts, and German _biergartens,_ all in a Wild West setting. In a few words, Fredericksburg is Roy Rogers in Bavaria. This German frontierism isn't just made up for tourism—it's the real deal. In the mid-1800s after annexation, Europeans, most of whom were German, were the first white folks to settle this frontier region. These pioneers brought with them all their traditions, including schnitzel, oompah music, and beer. The vestiges of this German heritage haven't eroded over time—on the contrary, they have become what defines Fredericksburg. **Luckenbach, Texas** Between Johnson City and Fredericksburg, just a few miles south of Highway 290, is the sleepy town of Luckenbach. Not much is happening here, but this dusty old town deserves some sort of a nod. After all, it was the subject matter for a hit song by Waylon Jennings and Willie Nelson called "Luckenbach, Texas." Ironically, the chaps who wrote the song were a couple of songwriters from Nashville who had never been to the remote, out-of-the-way, three-building town. In fact, Waylon had never been there either. So how did it merit mention in a country song? Maybe the songwriters threw a dart at a map of Texas? Today the town is a small grid of streets lined with old trees, creating neighborhoods of historic houses and bungalows. These neighborhoods are small-town America at its height, and remind one of the sentimental paintings of Thomas Kinkade. Main Street is lined with shops and boutiques that peddle all sorts of stuff for the middle class, such as home furnishings and decor, Western wear, country kitsch, and frontier-themed souvenirs. There are also a few interesting museums and historic sights to meander through, antiques stores in which to find treasures, and wine-tasting shops, as well as hundreds of bed-and-breakfasts to pamper you during your stay. Just north is Enchanted Rock State Natural Area, which adds to the town's draw. Because there is a lot to see and do here, and I recommend spending the weekend in Fredericksburg. Two nights in a B&B, wine-tasting, window shopping, hiking, and reminiscing about the pioneer days and WWII can all be enjoyed at a relaxed pace. However, if you only have one night and a day, skip the calorie burning/hiking. The **Fredericksburg Convention and Visitors Bureau** (302 E. Austin St., 830/997-6523, www.fredericksburg-texas.com, 8:30am-5pm Mon.-Fri., 9am-5pm Sat., noon-4pm Sun.) is your local source for information. **Texas Hill Country Wine Trail** For thousands of years grapes have grown on the banks of rivers and streams all over Texas. The climate is so conducive to the vine that there are more grape species here than anywhere else on the planet. Of the 36 species of vines in the world, 15 are native to Texas. For some strange reason, when the Spanish arrived in the 1500s, they never took advantage of these local varieties. They made the first wine on American soil in El Paso with a variety brought over from Europe. It wasn't until the 1800s that the grape potential of Texas was recognized. It all began when German immigrants in the Hill Country started fermenting the local grapes, as well as producing wine from grapes brought from the Old World. By the late 1800s wine research and production in Texas was fully underway. At the same time in Europe the phylloxera epidemic was wreaking havoc on French grape crops, threatening the future of French wine production. A grape researcher by the name of Thomas V. Munson of Denison, Texas, discovered that American species were resistant to the insect and brought vines from Texas to France, essentially saving the French wine industry. Ironically, 40 years later the U.S. Congress was successful in killing the Texas wine industry when it enacted Prohibition. The Texas Department of Agriculture lists 21 wine varieties grown in Texas. Cabernet sauvignon and chardonnay have the highest number of plantings in the state, followed by merlot, syrah, and muscat canelli. Texas is also home to zinfandel, tempranillo, sangiovese, and viognier plantings. The Texas Hill Country has rediscovered its viticulture roots. Wineries have been cropping up all throughout the state, 27 of which happen to be west of Austin in the beautiful Hill Country. These wineries have joined forces to create what is called the **Texas Hill Country Wineries Trail** (866/621-9463, www.texaswinetrail.com). Here are a few of the best wineries in this region. • **Becker Vineyards** (464 Becker Farms Rd., Stonewall, 830/644-2681, www.beckervineyards.com) Location: four miles west of Stonewall, off Highway 290 on Jenschke Lane • **Chisholm Trail Winery** (2367 Usener Rd., Fredericksburg, 830/990-2675, www.chisholmtrailwinery.com) Location: 9 miles west of Fredericksburg on Highway 290 west, then 2.4 miles south on Usener Road • **Driftwood Vineyards** (4001 Elder Hill Rd./CR 170, Driftwood, 512/692-6229, www.driftwoodvineyards.com) Location: six miles south of Highway 290 on RR 12 between Dripping Springs and Wimberley • **Duchman Family Winery** (13308 FM 150 W., Driftwood, 512/858-1470, www.duchmanwinery.com) Location: two miles south of Driftwood on FM 150 • **Dry Comal Creek Vineyards & Winery** (1741 Herbelin Rd., New Braunfels, 830/885-4121, www.drycomalcreek.com) Location: six miles west of New Braunfels off Highway 46 West • **Fredericksburg Winery** (247 W. Main St., Fredericksburg, 830/990-8747, www.fbgwinery.com) Location: downtown Fredericksburg • **Grape Creek Vineyard** (97 Vineyard Ln., Stonewall, 830/644-2710, www.grapecreek.com) Location: nine miles east of Fredericksburg on Highway 290, three miles west of Stonewall • **Sister Creek Vineyards** (1142 Sisterdale Rd., Sisterdale, 830/324-6704, www.sistercreekvineyards.com) Location: 12 miles north of Boerne on FM 1376 • **Solaro Estate** (13111 Silver Creek Rd., Dripping Springs, 832/660-8642, www.solaroestate.com) Location: north of Dripping Springs off Highway 12 • **Texas Hills Vineyard** (878 RR 2766, Johnson City, 830/868-2321, www.texashillsvineyard.com) Location: one mile east of Johnson City on RR 2766 • **Torre di Pietra Vineyards** (10915 East US Hwy 290, Fredericksburg, 830/644-2829, www.torredipietra.com) Location: Highway 290 between Stonewall and Fredericksburg • **William Chris Vineyards** (10352 Hwy. 290, Hye, 830/998-7654, www.williamchriswines.com) Location: off FM 1320 between Johnson City and Fredericksburg ##### **Sights and Activities** One of the first U.S. Army outposts in Texas was **Fort Martin Scott** (1606 E. Main St., 10am-5pm Tues.-Sun., free), at the eastern end of Fredericksburg. There's not much here except for a few buildings in a field, but it does offer an interesting look at what a frontier Texas fort looked like before the Civil War. Only one original building remains; the rest are re-creations. The fort was active 1848-1853; once it closed as a military outpost it was used by Texas Rangers and homesteaders and was the site of the county fair for a few years. The fort grounds are open to the public. The most off-the-beaten-path attraction in town—which happens to be my favorite—is **Gish's Old West Museum** (502 Milam St., 830/997-2794, by appointment only, free). Joe Gish, collector of Wild West memorabilia and artifacts, has opened his collection to the public. The museum is in an old cabin on his private property. The place is covered from floor to ceiling in sheriff's badges, old rifles, saddles, cowboy hats, chaps, and spurs. Gish also has memorabilia from the silent-movie cowboys, as well as a fascinating collection of old photos of weathered faces from the frontier days. World War II buffs from all over come to Fredericksburg to visit the **National Museum of the Pacific War** (340 E. Main St., 830/997-8600, www.pacificwarmuseum.org, 9am-5pm daily, $14 general admission, $10 seniors and military, $6 students, under 6 free). The museum, dedicated exclusively to telling the story of the Pacific Theater battles of World War II, has over 1,000 artifacts from the Pacific War, including Allied and Japanese aircraft, tanks, and guns. The nine-acre complex also includes a shrine to WWII heroes in the **Admiral Nimitz Museum,** which is housed in the historic Nimitz Hotel. The grounds also contain the **George Bush Gallery;** the **Japanese Garden of Peace;** the **Pacific Combat Zone,** complete with artillery and a PT boat; **Veterans Walk of Honor;** the **Plaza of the Presidents;** and the **Center for Pacific War Studies.** The **Pioneer Museum** (325 W. Main St., 830/990-8441, 10am-5pm Mon.-Sat., 10am-5pm Sun., $5), is a must-see when in Fredericksburg. This well-put-together complex of historic buildings furnished with artifacts offers a rare glimpse into the day-to-day life of the pioneers of the Hill Country. The focal point of the complex is the historic home and store of the Kammlah family. All the other buildings were brought in for preservation. The museum and complex are run by a few elderly women in period clothes. They and their outfits add to the museum's charm by being stuffy and old-fashioned. ##### **Shopping** Although Fredericksburg has museums and historic sights, most people come here to stroll up and down Main Street and to meander through the many shops and boutiques. People who don't like shopping, don't panic! Don't think you'll be dragged through this street all day with nothing to do, because many of the shops have such a thick Wild West theme that your attention will surely be caught. And if you don't want to do the shopping thing at all, go hang out at a _biergarten._ The best place to get an edible souvenir is **Rustlin' Rob's** (121 E. Main St., 830/990-4750, 10am-5:30pm Mon.-Fri., 10am-6pm Sat.). This little old-style general store is chock-full of homemade canned and dried goods sourced from the region. **Scenic Drive: Willow City Loop** All roads in the Hill Country are beautiful and scenic, but a few are truly unbelievable. Willow City Loop is one of these. This 13-mile celestial drive takes the road-tripper through heavenly landscapes of wildflowers, wildlife, and terrain that seems too beautiful to be real. The road travels along a ridge for many miles, then drops down into what's called the Devil's Kitchen. This valley has a large crater in the ground that was formed by a meteor. Although it's a rural country road, in the spring Willow City Loop can have a surprising number of bicycles, motorcycles, and cars, so don't think this is some unsung Shangri-La. To get to Willow City Loop from Fredericksburg, go north on Highway 16 for about 12 miles, then turn east on FM 1323. About three miles up the road at the small town of Willow City, look for the sign that marks the beginning of the Willow City Loop. The most interesting clothing store for both men and women is **Parts Unknown** (146 E. Main St., 830/997-2055, 10am-6pm Mon.-Thurs., 10am-7pm Fri.-Sat., noon-6pm Sun.). Here you'll find fashions fit for upscale Texans, such as country western, rockabilly, and Patsy Cline-style cowgirl boots, men's bowling shirts, and sequins for the ladies and the men. The local art gallery that represents many Fredericksburg artists is **Fredericksburg Art Gallery** (314 E. Main St., 830/990-2707, 10am-5:30pm Mon.-Sat.). Original paintings and works of art are sold for reasonable prices. Although these artists probably won't become world renowned, the pieces here definitely capture the spirit of the Hill Country. **Amish Market** (410 W. Main St., 830/990-2977, 10am-5pm Sun.-Fri.) is an interesting place to pop your head in. This is the local outlet for handmade items from folks in the Amish and Mennonite communities. Things you'll find for sale here are Amish furniture, chests, curios, and arts and crafts. Everything here is made with care and craftsmanship. If you didn't take the time to visit any of the local wineries, you can taste products from them all at **Texas Vineyards and Beyond** (329½ E. Main St., 830/990-9199, 11am-7pm Mon.-Tues. and Thurs.-Fri., 11am-8pm Sat., noon-6pm Sun., closed Wed.). ##### **Food** Fredericksburg is, for the most part, an affluent community, and because of this the dining scene is of a high quality. City zoning and planning ensure there isn't a slew of fast-food restaurants on Main Street. With the German influence, many of the eateries have a Texas-meets-schnitzel menu, which makes eating here fun and unique. The place that personifies this combination is S **Auslander Biergarten** (323 E. Main St., 830/997-7714, 11am-9pm daily except Wed., $13). Although this eatery leans heavily toward the tourist crowd, locals also claim Auslander for themselves. The menu offers the best of the "wursts," such as knackwurst, pepperwurst, and the popular bratwurst. You can also get local favorite chicken-fried steak and other chicken and fish dishes. Outdoor and semi-outdoor seating is nice on a spring evening. Although the restaurant closes after the dinner crowd leaves, the bar is open until midnight. For gourmet German cuisine with beer or cocktails on an outdoor patio there's **Otto's German Bistro** (316 E. Austin St., 830/307-3336, 4pm-11pm daily, $15). The duck schnitzel or Wurst Platte are most popular dishes. Demi-glace and sauerkraut undress your American taste glands and then clothe them in lederhosen. The atmosphere here is cozy and inviting. The place on Main Street for authentic German cuisine and atmosphere is **Der Lindenbaum** (312 E. Main St., 830/997-9126, 11am-10pm daily, $13). Owned and operated by a feisty German woman who is a globally trained chef, Der Lindenbaum produces high-quality soups, salads, schnitzels, and upscale meat dishes. No reservations needed; seating is on a first-come, first-served basis. Considered by many to be the best brewpub in Texas, **Fredericksburg Brewing Company** (245 E. Main St., 830/997-1646, <http://yourbrewery.com>, 11:30am-9pm Mon.-Thurs., 11:30am-10pm Fri.-Sat., 11:30am-7pm Sun., $15) proudly serves fine microbrews and German and American foods. The founder researched breweries in Europe and eventually decided to pattern this establishment after the Bavarian _gasthhausbrauerei,_ which means bed and brew. The end result? Fredericksburg Brewing Company has beer vats in the restaurant and guest rooms upstairs. Many fine-dining establishments come and go in Fredericksburg, but one that endures is **Navajo Grill** (803 E. Main St., 830/990-8289, 5:30pm-9pm daily, $15). This local favorite is a safe bet for a fine-dining experience free of the German theme. The seasonal menu includes steak, pork chops, and crab cakes. It's casual-elegant, so you may want to primp or dapper up. The **Old German Bakery & Restaurant** (225 W. Main St., 830/997-9084, 7am-3pm daily, $12) is the place to get baked goods and casual German fare for breakfast or lunch. Housed in a historic building, this little local favorite serves up amazing German pancakes, potato pancakes, waffles, and omelets for breakfast. Lunch favorites include any of the schnitzels topped with eggs, mushrooms, or bell peppers with a side of German pan fries. If you want carbs for later, don't leave without some German bread. **Java Ranch** (114 E. Main St., 830/990-4517, 7am-5pm Mon.-Wed., 7am-6pm Wed.-Sat., 8am-5pm Sun., $8) is the local disseminator of Starbucks coffee. Besides having great coffee, this is the cheapest breakfast in town. Whether you're thirsty or not you have to poke your head in the door and check out the massive mural. Local folks, including the resident donkey, modeled for this excellent work of art. If you don't want to make a big deal about lunch and just want a burger, there's **Wheeler's Restaurant** (204 E. Main St., 830/990-8180, 11am-3pm daily, $11). Here you can get familiar and affordable American or German food. Consider Texas chili with onion rings or chicken-fried steak. ##### **Accommodations** There are hundreds of bed-and-breakfasts, ranches, and guest cottages in and around Fredericksburg. A few clever people have created companies that help connect travelers to accommodations with an easy one-stop-shop approach. These reservation services have been so successful that it's hard to find lodgings without going through them. The thing that's good about these services is you can easily find just the right accommodation for your liking because the research is all done for you. The drawback is that the personal touch that bed-and-breakfasts are famous for can be lost in the process. If you like the one-stop-shop approach try **Gastehaus Schmidt** (231 W. Main St., 830/997-5612 or 866/427-8374, www.fbglodging.com), **First Class Bed and Breakfast Reservation Service** (830/997-0443, www.fredericksburg-lodging.com), **Main Street B &B Service** (830/997-0153 or 888/559-8555, www.travelmainstreet.com), or **Absolute Charm** (866/244-7897, www.absolutecharm.com). All these reservation services have access to hundreds of accommodations ranging from old farmhouses to historic limestone buildings and old Victorian homes. Perusing these websites is a great way to find the bed-and-breakfast that is right for you, as they have photos, maps, reviews, and amenity information. Reservation-service accommodations generally start at $129 a night and can go as high as $300. Whether you plan to use a reservation service or find a bed-and-breakfast to your liking on your own, it's important to book far in advance. One of the cheapest rooms in town is at the **Frederick Motel** (1308 E. Main St., 830/997-6050 or 800/996-6050, $99-109). The proprietors like to call themselves an "unconventional B&B" because they offer quality hospitality and a continental breakfast in the mornings. For a motel, the rooms are clean and well maintained; however, they are small and just off Highway 290. Smoking and nonsmoking rooms are available. A few blocks behind Main Street, in a quiet neighborhood, is S **Magnolia House** (101 E. Hackberry, 830/997-0306 or 800/880-4374, www.magnolia-house.com, $135-235). This bed-and-breakfast is housed in a historic landmark that's a perfect example of a Craftsman bungalow. The decor of the common rooms and the suites is country Victorian, and the breakfasts include American staples such as bacon, eggs, waffles, and coffee, all served on crystal. The backyard has a pleasant seating area under the trees and a small pond. There are five guest rooms in all, with the proprietors living in a cottage in the back. One of Fredericksburg's earliest pioneer homes is now a place to stay. The **Loeffler-Weber Haus** (508 W. Main St., 866/427-8374, www.fbglodging.com, $100-120) may be shockingly rustic and pastoral, but it can be alluring. This Ma and Pa Kettle-style log cabin has been altered just enough to be comfortable for today's traveler. The kerosene lamps are mostly for looks but can be fired up if you want an 1800s experience. Another place that specializes in rustic lodgings is **Barons Creekside** (316 Goehmann Ln., 830/990-4048, www.baronscreekside.com, $198-269). Just minutes from downtown Fredericksburg, this pastoral location features rolling hills with an assortment of little one-room cabins and an old Victorian house. The cabins are built out of logs from an old tobacco-drying barn from Kentucky and windows and doors from a 250-year-old house from Switzerland. The accommodations are a perfect combination of rustic and luxury for both couples and families: Think log walls and a whirlpool tub, where you can listen to the sounds of crickets while drinking a bottle of exceptional wine. Also, a trail leads down to a creek and a natural pool, and the cantilevered lookout can't be left out. The romantic place to stay in Fredericksburg is **Austin Street Retreat** (408 W. Austin St., 866/427-8374, www.austinstreetretreat.com, $185-215). This exotic and spectacular setting was originally a 19th-century family home made of Texas limestone. The home was meticulously converted into a lovely guesthouse with five private rooms, all under old pecan trees. Once you step off the street you feel like you're in a small village in Europe. Amenities can include fine linens, custom-designed bedding, whirlpool tubs, and private terraces. If you are traveling with a dog, you pet is welcome in some cabins for an additional $25. For a classic B&B experience just south of Main Street, there's **Das Garten Haus Bed and Breakfast** (604 S. Washington, 830/990-8408, <http://dasgartenhaus.com>, $150-265). This old Craftsman-style bungalow features three suites replete with doilies, pictures of flowers, and Wi-Fi, all under old pecan trees. Rooms are clean and well maintained, and have a great balance of charm and simplicity. The upstairs suite can house up to four guests. One of the best privately owned and operated bed-and-breakfasts in downtown is **Keidel Inn** (403 E. Main St., 866/244-7897, www.absolutecharm.com, $129-299). This charming villa-style home has rooms with great views, creature comforts such as big fluffy beds, and an outdoor area with a brick patio and a fountain. The historic home wasn't renovated to be a bed-and-breakfast, so most rooms share a bathroom with other guests. The best part about this inn is its location. Das Keidel is on Main Street, a block away from everything that's great about Fredericksburg. Picture the last scene in Casablanca—the airstrip, the old plane, and the romance of it all. The S **Hangar Hotel** (155 Airport Rd., 830/997-9990, www.hangarhotel.com, weekdays $119, weekends $149-189) at the Gillespie County Airport brings this scene to life in a unique way. Although this hotel looks like it's in an old World War II airplane hangar, it's actually completely new, with modern amenities worthy of a four-star hotel. All 50 rooms have a king-size bed, classy brass New York Library-style lamps, honeycomb-tile bathrooms, Egyptian cotton sheets, and army blankets, all in a South Pacific WWII motif. There's also a diner and a bar on the premises. All this, and you don't have to be a pilot, or even arrive by plane—you can drive up in a car. Rooms are quiet, which is surprising for being on an airstrip. For the quintessential Hangar Hotel experience, pilot John Barnett (210/844-4463) offers plane rides for $100 for 30 minutes. Gillespie County Airport is two miles south of Main Street off Highway 16. the Hangar Hotel For predictable, chain-style amenities, there's **La Quinta** (1465 E. Main St. on Hwy. 290, 830/990-2899, $115-179) and **Fredericksburg Inn and Suites** (201 S. Washington St., 830/997-0202 or 800/446-0202, www.fredericksburg-inn.com, $99-179). ##### **Getting There and Around** Most travelers arrive in Fredericksburg by car. However, there is a **Greyhound** station (2204 Hwy. 16 S., 800/231-2222), which can be an affordable way to get here from Austin and San Antonio. If you don't have a car you should know there is no bus system for this small town. However, taxi service is available through **Big Country Cabs** (830/307-0467) and **Bluebonnet Taxi & Shuttle** (830/998-2886). Since the area is small, cab fares probably won't exceed $10. #### S **ENCHANTED ROCK STATE NATURAL AREA** Just north of Fredericksburg is an amazing park called **Enchanted Rock State Natural Area** (16710 RM 965, 830/685-3636, 8am-10pm daily, $7, children 12 and under free). Once you drive around the bend and get your first glimpse of the massive outcropping of pink granite, I guarantee you will be amazed. A popular weekend expedition for locals is to walk up the face of the enormous dome to the top, which offers incredible panoramic views of the Hill Country. The rock is the size of a city block, and looks more like it should be set in Australia, or Utah—anywhere but Texas. Enchanted Rock State Natural Area Legend has it that the area was considered "enchanted" by the Tonkawa, who believed a ghost lived in the rock. The Tonkawa heard weird creaking and groaning at the site, which they attributed to spirits. Today's geologists say these sounds come from the rock contracting and expanding due to temperature changes. Another story is that a conquistador captured by the Tonkawa escaped by getting lost in the rock area. This gave rise to an Indian legend of a pale man who was swallowed by the rock and reborn as one of their own. Activities at the park include hiking, camping, picnicking, bird-watching, and rock climbing. Climbers love this spot because it's great for traditional climbing as well as crack climbing. The parking lot fills up early on weekends, and the park often reaches capacity and can be closed because of this. One can spend a couple hours here hiking and taking in the beauty. #### **COMFORT** Like most Hill Country towns, Comfort (pop. 2,300) was founded in the 1850s by German immigrants who left New Braunfels to settle more remote parts of the Hill Country. The name came about just as you might imagine—the location was a comfortable place to settle. The German word for comfort is _Gemütlichkeit._ They found this to be a little bewildering to non-Germans so they settled on the English translation. This group of settlers was different from other German pioneers in that they opposed slavery, and they weren't particularly religious. It took them over 40 years to build their first church, unlike other Hill Country towns that erected lots of churches quickly. Comfort hasn't changed much over the years. It's a small town with almost no tourism infrastructure and no attractions—just a collection of historic buildings and a few shops, one of which is the oldest general store in Texas. In a sense the town _is_ the attraction. For more information contact the **Comfort Chamber of Commerce and Visitors Center** (630 Hwy. 27, 830/995-3131, www.comfortchamber.com). ##### **Sights and Activities** Comfort's downtown **business district** is considered to be the most intact original business district in Texas. Taking a stroll around town and shopping for antiques is what visitors do here. All the old buildings are appealing to the eye and pique the imagination. Some have historical information inscribed in a cornerstone, or have a name and date in relief somewhere on the exterior. Current business owners often know the history of the buildings they occupy, while other buildings speak for themselves, such as the old post office. The only municipal monument to Union soldiers south of the Mason-Dixon line is in Comfort. The **Truer der Union Monument,** a simple obelisk erected in 1866, honors a group of German men slain by Confederate soldiers. The daring freethinkers refused to sign a Confederate oath of allegiance and fled to Mexico to escape. On their way south, they were discovered by Confederate soldiers. Most were executed, while a few escaped and later returned to tell the tale. But all were "true to the Union." **Attack at Enchanted Rock** The granite dome of Enchanted Rock was witness to some of the earliest Wild West showdowns in Texas. In 1841, Texas Ranger captain Jack Hays was exploring the region with a company of Rangers. They were looking for members of the Comanche tribe who had recently raided San Antonio. Hays decided to climb Enchanted Rock to get a better view of the surrounding countryside. He became separated from his men and while high up on the mountain was attacked by a large band of Comanche. In ordinary circumstances, this would have been a fatal error on the part of Captain Hays. On this day, however, he was armed with a brand-new weapon invented by Samuel Colt: a pair of five-shot Patterson Colt revolvers. These pistols were the most modern and innovative handguns yet created. The tactics of the Comanche were simple. They would rush a lone defender, causing that person to fire his single-shot weapon. Following this, the individual was at the mercy of the Indians. The Comanche charged Jack Hays, he fired his single-shot rifle, and they came at him with a vengeance. However, he used his Patterson Colts to great effect, and the stunned attackers fled in terror. They had never faced multi-shot weapons before. Ever after Hays was known as "Devil Jack." Having proven themselves in battle, Samuel Colt's revolvers became increasingly popular, and Colt subsequently became one of the most successful gun manufacturers in the country. ##### **Food** The sleepy town of Comfort may not be known for world-class dining, but the following spots will satisfy hunger and an appetite for charm. **Double D Family Restaurant** (1004 Front St., 830/995-2001, 8am-8pm Sun.-Wed., 8am-9pm Thurs.-Sat., $10) is popular for family-style dining. Here you can get sandwiches, hamburgers, and _migas_ for breakfast. A diverse menu that includes German and Cajun dishes is found at **Guenther's Creekside Grill** (220 Hwy. 473 at 6th St., 830/995-5370, 11am-2pm Tues.-Sat., 5pm-9pm, $10). The exterior may seem a little shabby, but this is probably a trick to keep nonlocals off the trail of great comfort food. Next to Hotel Faust is **814 A Texas Bistro** (713 High St., 830/995-4990, 6pm-9pm Thurs.-Sat., brunch 11:30am-2pm Sat.-Sun., $15). This upscale yet rustic place is housed in the historic post office building. Plates include lamb, Alaskan halibut, quail, and mussels, making 814 the most exotic restaurant in the region. ##### **Accommodations** An easy way to find bed-and-breakfast accommodations in Comfort is by going through **Meyer Bed and Breakfast** (845 High St., 888/995-6100, www.meyerbedandbreakfast.com, $120-200). Meyer has several suites in unique historic buildings on beautiful Cypress Creek. The historic building known as the Ingenhuett-Faust Hotel is home to an excellent bed-and-breakfast, **Hotel Faust** (717 High St., 830/995-3030, www.hotelfaust.com, $80-125). Buildings in the complex include log cabins, Victorian cottages, and old farm buildings, as well as some antiques shops. ##### **Getting There and Around** All travelers arrive in Comfort by the comfort of their own car or by hitchhiking. If you don't have a car you should know there is no bus system for this small town. Also, there are no taxi services. #### **OLD TUNNEL BATS** Between Fredericksburg and Comfort, inside an abandoned railroad tunnel called Old Tunnel, is a massive colony of Mexican free-tailed bats. Some say the bat count is over 3 million. The site has been preserved since train stopped using this rail line in 1942. Now the place is called **Old Tunnel State Park** (10619 Old San Antonio Rd., Fredericksburg, 866/978-2287, 6am-5pm daily, free). Every evening in the summer months the bat colony flutters off in search of bugs to eat. A few viewing areas have been designated by the park service, and on peak days someone will step out and give a presentation on the phenomenon. Another spot to view the bats is **Alamo Springs Café** (107 Alamo Rd., Fredericksburg, 830/990-8004, 11am-9pm daily, $8). Bat viewing is nightly May-October, but the Old Tunnel is open year-round from sunrise to sunset. The state park is eight miles east of Comfort off FM 473 on Old San Antonio Road/Old No. 9 Road. #### **BOERNE** The bucolic little town of Boerne (pop. 13,000), just 30 miles north of San Antonio, is one of the Hill Country's bastions of German heritage. Boerne (correctly pronounced BUR-nee) was originally a village called Tusculum, which was overrun in the mid-1800s by German pioneers who settled here, built a town, and named it after a German writer named Ludwig Börne. Today the attractive downtown features many old limestone buildings built in the 1800s, narrow streets, bridges, and old towering trees. On Main Street, which is also known by its German name of Hauptstrasse, there are many little shops, boutiques, art galleries, and antiques stores that draw tourists year-round. Although Hauptstrasse is a delight to take in, the town's most beautiful feature is Cibolo Creek, which flows right through the heart of Boerne. This creek—known to locals as "the river"—is home to ducks, geese, and other wildlife, making the setting almost too charming. For more information stop by the **Boerne Convention and Visitors Bureau** (1407 S. Main St., 888/842-8080, visitboerne.org, 8am-5pm Mon.-Fri., 10am-2pm Sat.). ##### **Sights and Activities** No one comes to Boerne for major attractions, grand museums, and big entertainment. People come here to stay in a bed-and-breakfast, walk through the shops, and visit the most beautiful attraction in Central Texas—nature. History and majesty are to be found in the caves at **Cascade Caverns** (226 Cascade Caverns Rd., 830/755-8080, www.cascadecaverns.com, 9am-5pm daily, $17.95 adults, $11.95 children 11 and under). These living caves have lots of stories to tell visitors. For example, the first cave was the secret hideout for a German recluse running from the law at the turn of the 20th century. Going back further in time, this same cave was a place for Native American ceremonies. Finally, going back to prehistoric times, the remains of a mastodon were found in the cave; its bones are still there. The cave tour lasts about an hour and ends at a 100-foot inner-cave waterfall. Cascade Caverns is south of Boerne just off Highway 10. Another cave in the area is the **Cave Without a Name** (325 Kreutzberg Rd., 830/537-4212, www.cavewithoutaname.com, 9am-6pm daily in summer, 10am-5pm daily in winter, $20 adults, $18 military and seniors, $10 children 6-12, children under 6 free). This spectacular underworld was discovered in the 1930s. Before it was opened to the public a contest was held to name the cave. Legend has it that a little boy said the cave is too beautiful to name. Thus the cave got its name, or didn't, depending on how you want to look at it. Inside these immense vaulted rooms are intriguing rock formations, stalagmites, stalactites, and delicate soda straws. The cave is northeast of Boerne on Kreutzberg Road, just off RR 474. The most intriguing thing in Boerne is the **Boerne Village Band**. Established in 1860, this outfit is the oldest continuously active German band in the country, and the second oldest in the world. This is one of the best obscure, historic traditions in the country. You can see the band perform for what's called **Abendkonzerte** every other Tuesday night in June and July at the Boerne Main Plaza. If you're in town, you have to see this. But don't expect 150-year-old folks on the tuba—the members have changed over the years. ##### **Shopping** Boerne is a main-street town lined with wine-tasting rooms, trendy boutiques, antiques shops, and art galleries, all housed in historic buildings made of limestone or wood. Walking up and down these sidewalks is an excellent way to not spend your time wisely, which is what this experience is all about. Most shops are open between 10am and 6pm daily. A shop that all must visit is **Carousel Antiques and Pickles** (101 S. Main St., 830/249-9306, 10am-5pm Mon.-Sat., noon-4pm Sun.). The great and unique combination of pickles and antiques is surprisingly brilliant. Other shops worth checking out are **Flashback Funtiques** (248 S. Main St., 830/331-2200, 10am-5pm daily), the Texana crafts-and-stuff store called **Calamity Jane's Trading Co.** (404 S. Main St., 830/249-0081, 10am-5pm Tues.-Sat., noon-5pm Sun.), and **The Green Bull Jewelry Store** (325 S. Main St., 830/249-7393, 10am-5pm Tues.-Sat.). ##### **Food** The local favorite spot to take visitors is **Po Po Restaurant** (829 FM 289, 830/537-4194, 7am-9pm Sun.-Thurs., 7am-10pm Fri.-Sat., $12). The world's largest plate collection in a restaurant covers the walls. American standards are served on the plates. A popular lunch spot at the center of Boerne, near antiques shops and boutiques, is **Cypress Grille** (170 S. Main St., 830/248-1353, 11am-2pm and 5pm-9pm Tues.-Sun., $12). The new American menu includes sandwiches, homemade soup of the day, and an assortment of salads. People come here to meet up, socialize, get a late start to a day downtown, and to eat home cooking. Across from Cibolo Creek is the S **Dodging Duck Brewhaus** (402 River Rd., 830/248-3825, 11am-9pm Sun.-Thurs., 11am-10pm Fri.-Sat., $11). Standard American fare, such as burgers, beef tenderloin, and salmon, is on offer. Dodging Duck also brews its own beers, which are quite good. Outdoor seating makes this a great place to relax any time of day. The local favorite breakfast joint is **Bear Moon Bakery** (401 S. Main St., 830/816-2327, 6am-5pm Tues.-Sat., 8am-4pm Sun., $10). Besides cooking up eggs, pancakes, and waffles, Bear Moon has the best baked goods in town. Boerne fine dining happens at **The Creek Restaurant** (119 Staffel, 830/816-2005, 11am-3pm Tues.-Sun., 5pm-9pm Tues.-Sat., $12 lunch, $28 dinner). The restaurant is housed in an old bungalow on the banks of Cibolo Creek. They've also added a water mill, pond, and outdoor decks, all smothered with southern charm that resembles Georgia more than Texas. The food is upscale but affordable, with a menu that has items such as mushroom fondue, crab cakes, and schnitzel. ##### **Accommodations** The most celebrated historic place to stay in the area is S **Ye Kendall Inn** (128 W. Blanco, 800/249-9954, www.yekendallinn.com, $119-249). In 1859 this grand limestone building rented rooms out to stagecoach travelers seeking upscale comfort in the rustic Hill Country. Today the tradition is carried on in the property's 30 rooms filled with antiques and decor that harks back to the pioneer days. There's a bar and a restaurant on the premises. A charming and centrally located place to stay is **The William** (170 S. Main St., 830/249-2138, www.thewilliamboerne.com, $200-300). Housed in one of Boerne's older landmark buildings in the heart of historic downtown, this newly renovated hotel is romantic and luxurious. If you came to Boerne for the window shopping and wine-tasting, this is the best place to stay—it's all right outside the front door. The best way to find a bed-and-breakfast in Boerne is by going through **Boerne Reservations** (132 S. Main St., 866/336-3809, www.boernereservations.com, 9am-10pm daily). This reservation service books rooms and cottages in and around town, and can easily match a lodging with a guest. The website has accommodation information, photos, rates, and amenities all in one place, which makes it easy to find the lodging that best suits your needs. The service is at no extra charge to guests. For chain hotel accommodations, there's **Best Western Texas Country Inn** (35150 Hwy. 10 W., 830/249-9791, $72-127). #### **GUADALUPE RIVER STATE PARK** A magical place for outdoor recreation of all kinds is **Guadalupe River State Park** (3350 Park Road 31, near Spring Branch, 830/438-2656, 8am-10pm daily, $7 pp). This 2,000-acre park has miles of river frontage in a spectacular setting, not too far from civilization (San Antonio). The thing that makes this place so magical is the Guadalupe River, which is lined with bald cypress trees and filled with wildlife. Visitors to the park enjoy a wide variety of outdoor activities, including canoeing, swimming, fishing, tubing, hiking, and camping. The park has a five-mile trail for horseback riding and mountain biking. Admission includes a two-hour guided tour through Honey Creek State Natural Area, where visitors learn about local plant life, geology, and wildlife. The tour is usually given Saturday at 9am; call to confirm. The park is off Park Road 31 just off Highway 46, eight miles from Highway 281. Guadalupe River State Park #### S **NATURAL BRIDGE CAVERNS AND WILDLIFE RANCH** If you've ever wanted to explore the belly of the earth in a safe and easy way, **Natural Bridge Caverns** (26495 Natural Bridge Caverns Rd., 210/651-6101, www.naturalbridgecaverns.com, 9am-7pm in summer, closes at 4pm the rest of the year, $21.95 adults, $13.99 children 3-11) has the experience all figured out. The three tours offered vary depending on your interest and level of claustrophobia. The most popular is the Discovery Tour, which is a 75-minute excursion that takes you underground for a half-mile exploration of massive caverns. The second is the Jaremy Room Tour, which is a short-and-sweet trip to a 120-foot-deep chamber—perfect for the whole family. Finally, there's the Adventure Tour, where the brave are outfitted with caving gear and lowered into the entry room by rope. They then proceed on a mile-long journey. All the caves are awe inspiring, from the stalagmites to the stalactites to the constant temperature of 70°F. Next door to Natural Bridge Caverns is **Natural Bridge Wildlife Ranch** (26515 Natural Bridge Caverns Rd., 830/438-7400, www.wildliferanchtexas.com, 9am-5pm daily, $22 adults 12 and up, $13.50 children 3-11, $20 seniors). Kids love to take the drive through this Texas-style African safari and see giraffes, rhinos, zebras, and many other exotic animals. For the driving tour factor in about 1.5 hours and add an additional 2 hours if you want to enjoy the petting zoo and include lunch in the restaurant. ### **Western Hill Country** Although all of the Hill Country shares the age-old brand of the Wild West, the western Hill Country is particularly wild and western. The farther west you travel, the more rural the scenery gets, and the more down-home the folks get. When exploring this region, expect to see things out of the ordinary, such as a replica of Stonehenge, folk music jamborees, and dude ranches with real cowboys. #### **KERRVILLE** All the hard work and the dreams of the western pioneers are fulfilled in the small main-street town of Kerrville (pop. 22,000), on the banks of the Guadalupe River. Although Kerrville wasn't founded by French settler Captain Charles Schreiner, he has become the iconic figure that everyone remembers. In the 1850s, after serving as a Texas Ranger since he was 15, Charles ended up in Kerrville and quickly became a successful businessman. At the peak of his career he found himself in banking, ranching, and promoting the value of mohair (the product of angora goats), and his empire stretched over 600,000 acres. Through his wealth many of the town's historic buildings were erected, and eventually Kerrville established itself as a viable mark on the map of Texas. Today Kerrville is considered by many to be the capital of the Hill Country. The town is a must-visit hamlet that promotes leisure, great music, and lots of outdoor activities. The revitalized downtown retains old-world charm but offers modern comfort and style. It's easy to get sucked in to the boutiques, galleries, shops, and cafés, which makes Kerrville a tourist trap in the truest sense of the word. But getting trapped here is exactly what you want. The town is sleepy and quiet until one of the many festivals held here injects hustle and bustle into the streets. Kerrville is situated on the banks of the Guadalupe River, at the quiet edge of the Hill Country just 104 miles from Austin and 65 miles from San Antonio. Because of the town's location, it's considered one of the healthiest places to live in the United States, boasting clean air, an unpolluted environment, and a great climate. Kerrville is just off Interstate 10, south on Highway 16. From Austin you would travel west on Highway 290 and at Fredericksburg take Highway 16 South. Once there, the **Kerrville Convention and Visitors Bureau** (2108 Sidney Baker St., 830/792-3535 or 800/221-7958, www.kerrvilletexascvb.com, 8:30am-5pm Mon.-Fri., 9am-3pm Sat., 10am-3pm Sun.) is a great place to start, as it offers copious amounts of information about the town and surrounding area, including easy-to-use maps, a great brochure on historic buildings of Kerrville, and a guide (with checklist) to local birds. ##### **Sights and Activities** In the center of historic downtown Kerrville is the **Schreiner Mansion Museum** (226 Earl Garrett St., 830/895-5222, by appointment only, free). Hailed as a pioneer of the region, Captain Charles Schreiner was a Frenchman who left his castle (literally), relocated to San Antonio, and eventually settled in the Texas Hill Country. This mansion—which was his castle, so to speak—is a museum piece itself, offering a glimpse into the life of the wealthier early settlers. Marvel at the elegance of the fiesta gowns worn by the ladies of Hill Country high society, the bronze fountain imported from France, the primitive Texas art, Civil War memorabilia, and molds used to make bullets by hand. People with money were able to pull off a highbrow way of life even though they were in a rugged frontier, thanks to laborers who performed the more arduous chores. The piano in the formal parlor was brought to Kerrville by covered wagon in the late 1800s. The talent of local artists is showcased at **Kerr Arts and Culture Center** (228 Earl Garrett St., 830/895-2911, 10am-4pm Tues.-Sat., 1pm-4pm Sun., free). Housed in the historic post office building, the slick gallery space displays high-quality works including pottery, paintings, quilting, woodwork, and jewelry. The headquarters of famed jeweler **James Avery** (145 Avery Rd. N., on the north side of Hwy. 10 off Harper Rd., 830/895-1122, 10am-8pm Mon.-Sat., noon-6pm Sun., free) is in Kerrville. Whether you're a jewelry buff or not, Mr. Avery's designs are sure to impress. Started in a two-car garage in 1954, this little homespun shop has grown into a national mail-order business. Designs include everything from bracelets to earrings to crosses, all bearing the unique style of the artist. Here you can visit his shop and purchase jewelry, but the most interesting thing is the visitors center, where guests can watch artisans at work. This riverside town's best natural feature lies just to the south at **Kerrville-Schreiner Park** (2385 Bandera Hwy., 830/257-5392). The Guadalupe River winds its way through the upper edge of the park, creating a lush and rugged landscape of rolling hills and live oaks. Camping, fishing, hiking, swimming, canoeing, picnicking, tubing, and wildlife-watching are why people come here. The hiking is easy, as most of the trails don't have much of an incline and are clearly marked. Wildlife you are bound to encounter include white-tailed deer, wild turkeys, rabbits, armadillos, and rare birds. Ornithologists should note that the Texas Hill Country is one of a few places to see rare birds such as the golden-cheeked warbler and the black-capped vireo. There are 58 designated tent sites with access to restrooms, 62 RV sites, and 23 mini-cabins available for rent. The entrance fee is adults $4, children $1, seniors $2, not to exceed $10 per vehicle. Camping is $10 a night, water and electric sites are $23, and full-hookup sites are $26. Reservations are recommended. The park is off Highway 173. **Scenic Drive: Route 16** The windy stretch of road between Kerrville and Medina is especially fantastic. At the start you may think, "what's the big deal?" But keep driving, because at a certain point you will feel like you drove straight out of small-town Texas and right into a Dr. Seuss book. This magical country road takes you through hill and dale, and through miniature gorges that are absolutely gorgeous. The hills are unusually bumpy and pointy, and the road is squirrelly to the point of nausea. The **Museum of Western Art** (1550 Bandera Hwy./Hwy. 173, 830/896-2553, www.museumofwesternart.com, 10am-4pm Tues.-Sat., $7 adults, children under 8 free) is a one-of-a-kind gallery that features contemporary art about cowboys and created by cowboys. Dramatic sculptures and paintings romanticize cowboys on the range in a way that captures the imagination and fosters a desire to eat rattlesnakes and drink coffee boiled over an open fire, without filters. The artistry and craftsmanship in all pieces on exhibit is spectacular and truly world class. For the kids there's the permanent exhibit featuring things used in the everyday life of a cowboy. The building is constructed of heavy timbers and limestone, and the grounds are dotted with life-size bronze statues, making this a long-lasting monument to the Wild West and the artistic tradition that captures it. The museum is on the southern side of the Guadalupe River. Cultural and natural history merge at **Riverside Nature Center** (150 Francisco Lemos St., 830/257-4837, www.riversidenaturecenter.org, 10am-6pm Mon.-Sat., free). This former farm is now a sanctuary for wildlife and native plants. Inside the main building are feature exhibits, educational programs, a gift shop, and a natural sciences library. Outside, on the grounds of the center, there's an arboretum of Texas trees, a wildflower meadow, butterfly gardens, and millions of insects. The gardens and trails are open daily from dawn to dusk. ##### **Food** Every Hill Country town has great barbecue. In Kerrville it's served up at **Bill's Bar-B-Que** (1909 Junction Hwy., 830/895-5733, 11am-7pm Tues.-Sat., $10). Bill's is _the_ local favorite for all meats barbecued to perfection. True to Texas form, your dining experience is among a flock of mounted deer heads on the walls. The local favorite for food downtown is the reliable **Rails—A Café at the Depot** (615 E. Schreiner St., 830/257-3877, 11am-9pm Mon.-Sat., $15) Expect burgers, wraps, salads, and some creative and mouthwatering dishes such as shrimp tostadas, beef masala, and tilapia tacos. The homey environment makes the experience fun. **Hill Country Café** (806 Main St., 830/257-6665, 6am-2pm Mon.-Fri., 6am-11am Sat., $9) is a local institution that serves American standards for breakfast and lunch only. Being smack-dab in downtown, it's popular and often packed. Marvel at a weird replica of Stonehenge that is out in the far reaches of the Hill Country. ##### **Accommodations** For an inexpensive bed with no fanfare there are a couple options: **Flagstaff Inn Motel** (906 Junction Hwy., 830/792-4449, $40-70) and **America's Best Value Inn** (1804 Sydney Baker St., 830/896-8200, $45-70). One of the Hill Country's most famous and historic ranches is S **Y. O. Ranch** (1736 Y. O. Ranch Rd., west of Kerrville, 830/640-3222 or 800/967-2624, www.yoranch.net). Picture longhorn cattle drives, a classy lodge-style resort, cowboys, and zebras, and you've envisioned Y. O. Ranch. This exotic game and hunting ranch spans 50 square miles, which is equivalent to 40,000 acres. Zebras, antelope, giraffes, and good ol' fashioned longhorns are among the 56 species of exotic and native animals that roam these parts. Established back in 1880 by Captain Charles Schreiner (of Kerrville fame), the ranch now offers exotic wildlife tours, horseback riding, rustic accommodations, and cowboy suppers featuring—you guessed it—meat and potatoes. Reservations are necessary. Guided hunts cost $250 a day for up to three people. Accommodations are around $150 per night, per person, and include three meals. Tours for wildlife viewing are $33 for adults, but if you are staying on the ranch tours cost only $18. The classiest place to stay in the Kerrville area is **Inn of the Hills Resort** (1001 Junction Hwy., 830/895-5000, www.innofthehills.com, $90-250). Amenities include room service, an Olympic-size pool and a kiddie pool, tennis courts, and a fitness club. There's also an upscale restaurant that offers breakfast, lunch buffets, and dinner daily. For a classic Texas cabin experience, **Trails End Guest Home** (180 Gay Dr. N., 830/995-2812, $129-194) offers rustic cabins in a quiet spot 15 miles outside Kerrville that makes for a great getaway. A big country-style breakfast is brought to your door each morning. For hot summer nights there's a pool, and some rooms have hot tubs. Farm animals linger on the property, adding to the ambience. ##### **Getting There and Around** Most travelers arrive in Kerrville by car. However, there is a **Greyhound** station (206 Schreiner St., 800/285-2425), which can be an affordable way to get here from Austin and San Antonio. If you don't have a car you should know there is no bus system for this small town. However, there is taxi service available through **Kerr Kab & Deliveries** (830/928-5222). Since the area is small, cab fares probably won't exceed $10. #### **WEST OF KERRVILLE** ##### S **Stonehenge II** The area's most peculiar attraction is **Stonehenge II.** Situated on a flat spot in a field a few miles west of Kerrville, before the small town of Hunt, is a 60 percent scale version of Stonehenge, the iconic rock structure near Salisbury, England. Unknowing folks traveling down this small Hill Country road who happen to see this amazing monument to God-knows-what are completely baffled, and unsure of what they're seeing. Just as mysterious as the original, this smaller version begs the question: "What were they thinking?" Was it created by aliens trying to contact their motherland? No! How about druids? Nope! Stonehenge II was conceived and constructed by two locals, Al Shepperd and Doug Hill. Material: concrete. Reason: none needed. The site is located on Highway 39 before the town of Hunt. Stonehenge II is on private property, but visitors are welcome during daylight hours. I recommend bringing a packed lunch and hanging out for about an hour. #### **LOVE CREEK ORCHARDS** If you plan on leaving the Kerrville area on Highway 16 going south you will probably want to stop off at **Love Creek Orchards Cider Mill and Country Store** (14024 State Hwy. 16, south of Medina, 830/589-2588, <http://lovecreekorchards.com>, 9am-5pm daily). This is a place where the apple is worshipped and glorified in its many forms. Although the orchards are lovely, the real reason why everybody comes here is the country store. To find it, follow the distinct smell of baking apples, which wafts down the highway. Once the unsuspecting visitor walks onto the grounds they are transported into a Norman Rockwell painting where America seems to be perfect and free of sin, at least until the apple is served up. Here you'll find apple pies, apple cider, applesauce, apple turnovers, apple muffins, apple rings, apple butter, and apple jellies and jams. In all, the folks at Love Creek produce more than 33 different products from apples. Yes, the temptation is great, but you can't blame Eve—this place is owned and operated by the Adams family. #### **BANDERA** The authentic, honest-to-goodness western town of Bandera (pop. 1,000) considers itself the Cowboy Capital of the World. When you show up you may wonder if this is true, because it can come across as a bleak little town at first. Sure, it's not a set from a spaghetti western, and it doesn't have a sexy hunk galloping down Main Street looking for the sheriff. But if you scratch the surface just a little, you will see there's much to discover and experience here that is truly western. According to legend, many bloody battles between Apache and Comanche and the Spanish conquistadors took place in Bandera Pass (now 12 miles north on Hwy. 173). Supposedly a red flag ( _bandera_ is Spanish for flag) marked the boundary between Spanish and Native American territory. In 1852 the town was officially founded, and Bandera became a staging area for western cattle drives, a Mormon colony, and the largest Polish settlement in the United States. **Back in the Saddle Again** Bandera is a popular place for saddling up and heading out into the country. Many of the dude ranches in and around Bandera offer horseback-riding packages with accommodations or day-trip horseback riding at an hourly rate. Experienced riders can head out on trails alone, and the inexperienced can ride with a guide. Most ranches don't have addresses, as they are out in the country, so it's good to look them up on the Internet or call to get directions before heading out. Children under six usually can't ride, and reservations are required. For a guided stroll through the countryside for a few hours, there's **Bar M Ranch** (RR 1077 W., 2.5 miles southwest of Bandera, 830/796-9096, www.bar-mranch.com, $35 per person per hour). Trails will take riders over brook and dale, through pastures, and in the shadows of cliffs. Wildlife abounds, so bring a camera. Rates vary by trail. Trails are generally 2-3 hours; those three hours and longer require experienced riders. Another ranch that offers hourly horseback riding is **Rancho Cortez** (RR 1077, 830/796-9339, www.ranchocortez.com, $35 per hour). Hourly rates are higher for rides in Hill Country State Natural Area. For a ride on the trails of the beautiful Hill Country State Natural Area, call **Desert Hearts Cowgirls Club** (830/796-7001, <http://desertheartscowgirlclub.yolasite.com>, $65 for the first two hours, $30 for each additional hour), founded by Jeanne Beauxbeannes (pronounced "BOH-bee-nee"). She's been riding the park longer than any of the rangers. Her idea of hiking in this park is simply hiking your leg over a saddle. Jeanne offers interpretive guided trail rides that last a minimum of two hours. Half-day and all-day rides are offered only in fall and spring. Today Bandera is still an emblem of the American frontier. It's home to world-champion rodeo cowboys, craftspeople who produce fine furniture and leather products, and old-style Texas dance halls. So what draws people here? The living spirit of the old West, camping under the stars, rodeos, kayaking and canoeing, catfish and bass fishing, honky-tonks and country music, horseback riding, and Texas-style R&R. Bandera's population hovers around 1,000. The downtown is small and the centerpiece is the Old Bandera County Courthouse, which is now the library. Its distinct Renaissance Revival architecture evokes the Spanish era, while the rest of the town harkens to the old West, demonstrating the richness of Bandera's history. For more information about Bandera there's the **Bandera County Convention and Visitors Bureau** (126 Hwy. 16 S., 830/796-3045 or 800/364-3833, www.banderacowboycapital.com, 9am-5pm Mon.-Fri., 10am-3pm Sat.). The helpful staff can assist in finding just the right lodgings for you as well as offer information about anything, from rodeo schedules to a historical walking tour of downtown. ##### **Sights and Activities** The best small-town museum in Texas happens to be in Bandera: the **Frontier Times Museum** (510 13th St., 830/796-3864, www.frontiertimesmuseum.org, 10am-4:30pm Mon.-Sat., $5 adults, $3 seniors, $2 children 6-17, under 6 free). This homespun museum is more like an antiques store where you can't buy anything—you can only look. Here you can imbibe the luster of the old days and breath in the scent of old wood and dusty artifacts from the Wild West's cowboy lore and Bandera's history. The 5,400 acres that make up the **Hill Country State Natural Area** (830/796-4413) were originally the site of the Merrick Ranch. Located 10 miles west of Bandera on FM 1077, this park has virtually nothing to offer in the way of amenities—just good ol' nature. Camping is permitted in a 20-acre designated area, but don't expect restrooms and showers here, as primitive camping is what this park is all about. Make sure you bring water, food, and toilet paper, bury all waste matter, and take all your trash with you when you leave. This largely undeveloped, nearly pristine park offers a rugged place for hiking, walk-in camping, backpacking, mountain biking, and horseback riding among canyons, springs, and rocky hills. More than 20 caves and 10 springs add to the majesty of the park. Six miles southeast of town on Highway 16 is **Polly's Chapel,** built in 1882 by José Policarpo Rodriguez. He came from Mexico to Texas and became famous as a scout for the U.S. Army and a mercenary. He later joined the Methodist church and became a licensed preacher and built this tiny chapel. José, known by locals as Polly, is buried in the graveyard. The chapel is often open to the public. Living up to the prestigious title of Cowboy Capital, Bandera hosts a wide array of **rodeos** from spring to fall. Every Tuesday and Friday night from Memorial Day weekend in May through Labor Day weekend in September, the **Twin Elm Guest Ranch** (810 FM 470, 830/796-3628, www.twinelmranch.com) hosts open rodeos. Professional rodeos are put on by the **Bandera Pro Rodeo Association** (www.banderaprorodeo.org) every year on Memorial Day weekend. One unusual activity that is highly recommended is venerating a jukebox in town. Yes, there are jukeboxes with George Jones and George Strait everywhere in the United States. However, this machine in the **Bandera County Kronkosky Library** (505 Main St., 830/796-4213) is special. This dusty little town has been home to many musicians over the years. Some locals organized and created the **Bandera Music History Project** to honor these folks. Their efforts resulted in a little shrine with a jukebox. ##### **Music and Dancing** Bandera is known for keeping honky-tonk alive with live country music, line dancing, and sawdust floors. Live dances are held Wednesday-Sunday nights throughout the year at the various honky-tonks and dance halls in and around town. Bandera is also known for jam sessions that grow into full-on hootenannies. Expect to see accordions, Stetsons, guitars, and beer bellies at the following bars: **Arkey Blue's Silver Dollar** (308 Main St., 830/796-8826), **Chikin Coop** (402 Main St., 830/796-4496), and the **11th Street Cowboy Bar** (307 11th St., 830/796-4849). ##### **Food** In Bandera, eating out is cheap and amusing. Sometimes the cuisine can be a bit too cowboy, though. By this I mean too greasy, meaty, and salty. You can expect to spend under $10 for a meal and a drink. For barbecue, there's **Busbee's Bar-B-Que** (319 Main St., 830/796-3153, 10:30am-8pm Sun.-Mon. and Wed.-Thurs., 10:30am-9pm Fri.-Sat., $7). They unabashedly declare themselves the cowboy's choice for barbecue, and if this is true, how can one go wrong eating here? Beef is served up by the pound with the usual sides. The landmark eatery in town is **O. S. T. Restaurant** (305 Main St., 830/796-3836, 6am-9pm Mon.-Sat., 7am-9pm Sun., $8), also known as Old Spanish Trail. Down-home cooking here includes chicken-fried steak, roast, meatloaf, and other American fare. One room in the restaurant is entirely devoted to the memory of Marion Morrison. Who's this, you might ask? The Duke—better known as John Wayne. ##### **Accommodations** Although Bandera has a couple of typical motels, the popular way to lodge is in a dude ranch or a guest ranch. For most people, staying in a dude ranch is a once-in-a-lifetime opportunity. Most ranches offer rustic accommodations and a wide range of activities, such as campfire storytelling, marshmallow roasting, horseback riding, swimming, and nature walks. Rates for dude and guest ranches are more than those of your average motel/hotel but often include up to three meals a day. For predictably clean and affordable accommodations within walking distance to shops and restaurants there's **Bandera Lodge** (700 St., Hwy. 16 S., 830/796-3093, $63-90). Nothing fancy here, just a TV, a bed, Internet access, and a bathroom. A comfortable ranch that offers hotel-style amenities is the **Flying L Guest Ranch** (800/292-5134, www.flyingl.com, $180-300). On over 700 acres, this ranch offers 41 cottages and suites, many with fireplaces. Here you can spend the day horseback riding along the San Julian Creek, swimming, fishing, and playing sports. The Flying L also has an 18-hole championship golf course and packages for golfers that make for a resort getaway with a ranch feel. All cottages and suites require a two-night minimum stay. Fun for the whole family is to be had at **Mayan Dude Ranch** (Pecan St., 830/460-3036, www.mayanranch.com, $130-150 for adults, $70-95 for children under 18). This ranch has been hosting people for decades, providing couples and families with rustic rooms and cottages, horseback riding, hayrides, tubing, fishing, hiking, golf, and tennis. The facility is huge, and it takes a lot of concentration to be bored here. Included in the price are three cowboy-style meals and a horseback ride. A dude ranch retreat isn't complete without spending some time with horses. Across from the Medina River are the cozy cottages of **River Front Motel** (1103 Maple St., 830/460-3690, $74-125). These semi-rustic, clean rooms are furnished by local craftspeople and offer convenience, location, and quiet. For rustic ranch lodgings, the **Twin Elm Guest Ranch** (Hwy. 470, 830/796-3628, www.twinelmranch.com, $105-115 adults, $80 teens, $65 children under 12) can draw the inner cowpoke right out of you. Twin Elm has 21 units, all clean and with air-conditioning; some have bunk beds and porches. Rates vary for high and low seasons. Rates include three big cowboy-style meals a day, access to the rodeos held every Tuesday and Friday night during the summer, marshmallow roasting, swimming, and relaxing in hammocks. For a few more bucks, guided horseback riding is offered. #### **VANDERPOOL** The small town of Vanderpool (pop. 91) is primarily a center for sheep, goat, and cattle ranching. Back in 1885, when a post office was established out here for settlers and ranchers, they decided to give this place a name. Not much has changed since then—the main feature here is still the post office. So what's out here? This quiet area at the western edge of Bandera County is exceptionally beautiful, with some of the most scenic rural roads in the Hill Country. The town, if it can even be called a town, is situated on the lazy Sabinal River near a state park that is a popular getaway for city folk. The only sight out here is the **Lone Star Motorcycle Museum** (Hwy. 187 N., four miles north of Vanderpool, 830/966-6103, www.lonestarmotorcyclemuseum.com, 10am-5pm Fri.-Sun., $5). This labor of love was pieced together by a motorcycle connoisseur who had extra money to spend on a hobby. The collection spans the entire history and evolution of the motorcycle, from the first motorized bicycles to the hogs of our time. The recent resurgence of the chopper and custom motorcycle has brought more traffic than usual to this small museum. The scenic roads leading up to the museum make this a great destination for a weekend motorcycle ride. #### S **LOST MAPLES STATE NATURAL AREA** The main reason for going as far west as Vanderpool is **Lost Maples State Natural Area** (37221 FM 187, 830/966-3413, 8am-10pm daily, $5 Dec.-Sept., $6 Oct.-Nov.). The beautiful bigtooth maples are the big attraction here, and they aren't "lost" or even hard to find. In the fall these delicate but enormous trees explode with color. Fall foliage is most dramatic in November, and that's when the crowds come. Hikers are encouraged to stay on trails, as the trees can be damaged by soil compaction. Bigtooth maples require very specific conditions and have shallow roots, making them rare and vulnerable. Lost Maples State Natural Area The park is home to three State Champion Big Trees: an escarpment chokecherry, a Texas ash, and a bigtooth maple, nominated by the American Forestry Association. Park facilities include campsites with water and electricity, picnic areas, and restrooms with showers. Primitive camp areas are also available, but you have to hike in about 11 miles to get to them. The park is four miles north of Vanderpool on FM 187. Plan on walking the park for about an hour. If you bring a packed lunch, make it two hours. #### **UVALDE** At the far reaches of the western Hill Country is the slow-paced town of Uvalde (pop. 16,000). This Wild West frontier town was first settled by the Spanish back in 1674 as part of a missionary effort to convert the Apache population. The Spanish bailed on this effort after repeated attacks by local Lipan-Apache; they returned in 1709 under the military leadership of Spanish governor Juan del Ugalde (Uvalde), who defeated the Apache. According to legend, Uvalde Canyon is the spot of this decisive battle. Although there are traces of the Spanish era, Uvalde is most remembered as a Wild West town, and as the stomping grounds of the notorious gunslinger, outlaw, and sheriff J. King Fisher. Although Fisher died in a gunfight in the Vaudeville Theater in San Antonio, he's buried here in Pioneer Cemetery. The other historical character who called Uvalde home was John "Cactus Jack" Garner, vice president under Franklin D. Roosevelt, whose home is now a museum. Uvalde is the most remote town covered in this guidebook. Although it's out in the middle of nowhere, Uvalde is the most noteworthy town at the farthest southwestern rim of the Hill Country, and it can make for an interesting day trip from both San Antonio and Austin. From San Antonio, go west 80 miles on Highway 90. From Austin, it's probably best to go through Bandera and take Highway 173 south to Highway 90, then go west. The **Uvalde Convention and Visitors Bureau** (300 E. Main St., 830/278-4115 or 800/588-2533, www.visituvalde.com, 9am-5pm Mon.-Fri.) is the best place to get information. ##### **Sights and Activities** Housed in a World War II-era hangar at the Uvalde municipal airport is the **Aviation Museum of Texas** (201 Sul Ross Blvd., hangar number 1 at Garner Field, 830/278-2552). See WWII aircraft and memorabilia, such as a disassembled Martin B-26, a Stearman, PT-17, Liason-4, 1946 Ercoupe, and a Fairchild. Due to a lack of volunteers museum hours are limited (9am-4pm Tues. and Fri., 1pm-4pm Sat., or by request); a donation of $2 will get you in. If you make it all the way out to Uvalde you have to check out **Briscoe Art and Antique Collection** (200 E. Nopal St., in the First State Bank, 830/278-6231, www.fsbuvalde.com, 9am-3pm Mon.-Fri., free). People are always surprised to find that out in this remote Texas town, inside a bank, there's an extensive, multimillion-dollar art collection that includes original masterpieces by Rembrandt and Gainsborough, and works by American Western artists Salinas and Warren. The collection was developed by rancher, oilman, banker, and former Texas governor Dolph Briscoe and his wife, and can be seen by simply strolling into the bank and looking around. For a guided tour, call in advance. Built in 1891, the **Janey Slaughter-Briscoe Grand Opera House** (100 W. North St., 830/278-4184, 9am-3pm Mon.-Fri., free) was once the center for cultural activity in southwestern Texas. The opera house is now an active performing-arts center. Whether there's something happening here or not, it's worth poking your head into this historic building. The stage and most of the interior have the original turn-of-the-20th-century decor. The **Briscoe-Garner Museum** (333 North Park, 830/278-5018, 9am-4pm Tues.-Sat., free) is in the home of John "Cactus Jack" Garner, vice president under Franklin D. Roosevelt. On display are items associated with Mr. Garner's life, including items from his political career as well as area history. A floor of the house is dedicated to Dolph Briscoe. ##### **Food** At the Amber Sky Motel is the **Amber Sky Coffee Shop** (2001 E. Main St., 830/278-3923, 6am-3pm Mon.-Sat., $7), where locals have been getting their coffee and conversation for years. Here you can get a delicious home-cooked meal, a pie and a paper, and slow start to the day. Long-time Uvalde tradition is offered at **Evett's Barbecue** (301 E. Main St., 830/278-6204, 10:30am-6pm Tues.-Sat., 10:30am-4pm Sat., $7). Choose smoked-to-perfection barbecue and sides, or a sandwich, all dirt cheap. For a plate of country cooking there's **Lunkers Grill** (810 E. Main St., 830/278-2060, 11am-9pm daily, $9). Satisfy your appetite with beef, green beans, and a side of carbs. ##### **Accommodations** **Amber Sky Motel** (2005 E. Main St., 830/278-5602, $52-62) is your roadside mainstay, with 39 units. A restaurant is on the premises. For slightly fancier accommodations there's the **Quality Inn** (920 E. Main St., 830/278-4511, $88). This hotel has a pool, an on-site restaurant, banquet rooms, and a cocktail lounge. For luxury in a bed-and-breakfast atmosphere let **Live Oaks Bed & Breakfast** (6 Tanglewood, 830/591-2340, www.liveoaksbnb.com, $100-130) take care of you. Live Oaks is nestled in a secluded meadow of tall mesquite and live oak trees on a six-acre plot on the outskirts of town. When you think of a bed-and-breakfast, you may think of an old converted Victorian house, but that's not what you'll find here. Think new construction, contemporary design, clean and simple rooms, and great service. ### **Eastern Rim** The Eastern Rim of the Hill Country is defined by I-35, which connects San Antonio to Austin, Dallas, and everything in between. The towns along the freeway were the original settlements of the first German immigrants back in the 1800s. Today these towns are getaway hot spots for city folk who want to tube the beautiful rivers, shop for antiques, and enjoy leisurely meals on outdoor patios. ##### S **Tubing the Guadalupe River** One of the main attractions in this corner of the Hill Country is the Guadalupe River, which winds its way from the west and passes through New Braunfels. This ancient resource has been attracting humans for centuries. From the native populations in ancient times to the fun seekers of today, this spectacular river has been a must-see for everyone. Besides being astonishingly beautiful and even majestic, the Guadalupe River is a virtual air conditioner for locals and visitors, as it's always cool and always running. Activities include swimming, tubing, and rafting. In the summer you'll find thousands of folks from all walks of life sunning, relaxing, and drinking as they bob down the river through groves of bald cypress and over mild white-water rapids. The Hill Country's natural AC is the Guadalupe River. The riverhead is at Canyon Lake, and New Braunfels and Gruene are the end of the line. The entire length is approximately 20 miles. On any given day May-October you'll find a mob of sunburned, exhausted, tipsy folks staggering out of the exit points along the river carrying inner tubes, ice chests, and empty beverage containers. It's a sight to behold. Floating the short circuit takes about an hour, and floating the long one can take about six hours. On the trip tubers encounter ancient cypress trees, miniature waterfalls, and serene settings around every bend. Businesses offer tube and raft rentals along with shuttle service to various starting and exiting points along the river. A local favorite is tubing the Horseshoe, which is an upper portion of the Guadalupe River near Canyon Lake. The best outfit for tube rentals and shuttling is **Whitewater River Tube Rentals** (11860 FM 306, 830/964-3800, www.floattheguadalupe.com). These folks offer the best two- to four-hour float service, along with canvas tubes (more comfortable than rubber), cooler tubes, and fast shuttle service. If you want to make a day of it, plan on departing in the afternoon so you can arrive and catch a live music show at their famed amphitheater, at the end of the line. The tubing fee of $20 a day includes tube, shuttle, and parking. Tubing also takes place on the stretch of the Guadalupe River around New Braunfels and Gruene. For tube rentals there's **Rockin' R River Rides** (1405 Gruene Rd., 830/629-9999 or 800/553-5628, www.rockinr.com) and **Gruene River Company** (1404 Gruene Rd., 830/625-2800 or 888/705-2800, www.toobing.com). Farther into New Braunfels is **Comal Rockin R** (193 S. Liberty., <http://comalrockinr.com>, 830/620-6262). Tube rentals for most outfits are around $15, coolers are $15, and cooler tubes are $18. Inflatable canoes run $30-55, and rafts for 3-6 people are $25. To reach the main locations for either of these companies from I-35, exit at Loop 337 and go north toward the town of Gruene. After you cross the Guadalupe River, turn right on Gruene Road. Drive up to the river and park. You can plan for a half day of tubing or you can spend a full day in the area tubing and afterwards enjoying food at a nearby restaurants. #### **MCKINNEY FALLS STATE PARK** A bucolic spot on the eastern side of I-35 between San Antonio and Austin is home to **McKinney Falls State Park** (5808 McKinney Falls Pkwy., 512/243-1643, 8am-10pm daily, $4). This beautiful area on Onion Creek was settled by one of Steven F. Austin's original 300 colonists, Thomas F. McKinney, back in the 1850s. Ruins of his original homestead have been preserved. Park facilities include 84 campsites with water and electricity, screened shelters with bunk beds, and picnic sites. There's also an interpretive hiking trail that's just under a mile long, as well as over three miles of paved trails. Mountain biking is available on designated trails. Camping costs $16 per site. #### **SAN MARCOS** Between Austin and San Antonio, on I-35, is the small river city of San Marcos (pop. 44,000). Over 12,000 years ago Native Americans lived in this area, making it the oldest continuously inhabited place on the continent. It's not hard to figure out why people have always lived here. This lush spot on the San Marcos River is where springs from an underground reservoir burst forth, creating the riverhead. The result: beauty and life. Today San Marcos is a town that wears many hats. It's home to Texas State University and the state's largest shopping outlet center, and it's a place for ranchers and country folk to get supplies. But San Marcos's most important aspect is the ancient river. For more information contact the **San Marcos Tourist Information Center** (617 I-35 N., 512/393-5930, www.sanmarcostexas.com, 8:30am-5pm Mon.-Fri.). **Scenic Drive: Devil's Backbone** One of many scenic drives in the Hill Country is Devil's Backbone, which is out in the country near Wimberley. This is a winding country road that cuts its way along a dramatic ridge and through a valley of rolling hills. This drive is at its visual climax in the spring. To get to Devil's Backbone from San Marcos, follow RR 12 west to RR 32, where the scenic drive travels west for about 14 miles. ##### **Sights and Activities** The fourth-most visited attraction in the state of Texas is the shopping mecca **Premium Outlets** (3939 I-35 S., exit 200, Centerpoint Rd., 512/396-2200, www.premiumoutlets.com, 10am-9pm Mon.-Sat., 10am-7pm Sun.). Every year more than six million shoppers visit the sea of concrete and buildings that make up the shopping center, in search of deals, steals, the new thing, the old thing at a discount, and an endless array of bargains. The 110-plus factory outlet stores offer everything from apparel and accessories to health and beauty items to home furnishings and housewares. The outlets have been developed with a Disneyland aesthetic, such as castle-like towers and gondola rides, that only adds to the draw. If you plan to join the hordes shopping here be sure to pick up a map of the complex as soon as you arrive, and plan on making a day of it. Texas State University's **Aquarena Center** (921 Aquarena Springs Dr., 512/245-7570, www.aquarena.txstate.edu, 10am-5pm daily, free) is Central Texas's contribution to the science of water. At the center there's an aquarium, an endangered-species exhibit, a wetlands boardwalk, and scientific diving, all to educate visitors about the fundamental element of all life—water. The highlight of the Aquarena is taking a tour in a glass-bottom boat to explore the watery underworld without getting wet. The 30-minute boat tour costs $9.75 adults, $8 seniors (62+), $6 children 3-12, and 2 and under are free. San Marcos's version of a theme park is **Wonder World** (1000 Prospect St., exit 202 off I-35, 512/392-3760, www.wonderworldpark.com). Along with dramatic caverns to explore, Wonder World also has an antigravity house, animals on the prowl, an observation tower, and a mini train to ride. Summer hours are 8am-8pm daily June-August; winter hours are 9am-5pm Monday-Friday, 9am-6pm Saturday-Sunday September-May. Ticket prices range $7-24 depending on what attractions you want to experience. One of the most popular activities in San Marcos is tubing down the San Marcos River. **Lions Club Tube Rental** (in City Park across from the university, 512/396-5466, www.tubesanmarcos.com) makes the experience easy. Just show up at their site, pick out a tube, and jump in the river. The Lions Club folks will pick you up at the Rio Vista Dam (one-hour trip) or Martindale Dam (six-hour trip) and drive you back to the start point at the Lions Club. Rental rates range $7-14 depending on the type of tube. Deposits are required. Summer hours are 10am-7pm daily June-August; winter hours are 10am-7pm on weekends only September-May. Last tube rental is always at 5:30pm. ##### **Food** The **Café on the Square** (126 N. LBJ, 512/396-9999, 6:30am-11pm Mon.-Sat., 8am-10pm Sun., $8) is where all the town's gossip goes down. Locals converge here all throughout the day and night, and sip iced tea and eat breakfast well past noon. This is the type of place where it's OK to occupy a table for hours. The food is standard American, delivered with above-standard hospitality. **Palmers** (218 W. Moore, 512/353-3500, www.palmerstexas.com, 11am-10pm Sun.-Thurs., 11am-11pm Fri.-Sat., $10) offers the classiest environment in San Marcos for lunch and dinner. The menu offers a diverse selection of entrées, from pastas to steaks, all served at tables situated among plants and trees. #### **WIMBERLEY** The wacky little valley town of Wimberley (pop. 2,600) is in an incredible setting on the Blanco River and Cypress Creek. Many residents of Wimberley don't think the outside world knows about their quirky little town, and they want to keep it that way. I hate to disappoint, but people are on to them and their town, and visit by the thousands. Some visit and love the place so much that they move there. Wimberley has become home to artists, authors, musicians, and people seeking a simple life away from the city. This has given rise to an organic community of artists, which has made Wimberley into a bona fide art town. This identity has been grafted to an old tradition of ranching, which gives Wimberley a funky, charming, and offbeat identity crisis. Wimberley has been struggling with its identity ever since its founding back in the 1850s. The town was first settled by a veteran of the Texas Revolution named Williams Winters, who built a mill on the location. The town was called Winters until a man named John Cade bought the mill and renamed the town Cade's Mill. A few years later a wealthy man from Llano named Pleasant Wimberley bought the mill and changed the name to Wimberley. For over a hundred years nothing changed much in the small town. Then in the 1970s and '80s hippies started showing up, giving way to the art scene. Today, you'll find a charming town; a fascinating little shopping area at **Wimberley Square,** where some artists peddle their wares; and over a hundred bed-and-breakfasts in the surrounding countryside. Although Wimberley's status as an art town draws people here, the real reason people come is to simply do nothing. For more information stop by **Wimberley Visitor Center** (14100 RR 12, 512/847-2201, 9am-4pm Mon.-Sat., 1pm-4pm Sun.). ##### **Sights and Activities** Wimberley's lifeline is the scenic **Blanco River,** which cuts its way through town amid extraordinarily beautiful surroundings. The best way to take in the Blanco River is to drive up River Road. It only offers about a mile of river frontage views, but it's well worth the trip. The other feature of town is also a natural one: Cypress Creek. The spot to see this creek at its best is at **Blue Hole** (RR 3237, north of town). This majestic piece of the river has been a popular swimming hole ever since this area was settled. It's called Blue Hole for a reason—the water is a deep cobalt blue. People from all over the area converge in Wimberley once a month for **Market Day at Lions Field** (RR 2325, in Lions Field, 6am-6pm first Saturday of the month April-Dec., free). More than 450 vendors set up booths under tree-covered paths. The scene is exotic bazaar meets country kitsch, with vendors peddling antiques, canned goods, furniture, art, and live music. A good view of the area can be had by hiking to the top of **Mount Baldy.** The prominence got its name because the trees stopped growing and the top is as bald as Kojak. There are 212 steps to the top. To get to the trailhead from RR 12, go west on Woodcreek Drive, then take your first right. You should see the stairs and a place to park. One of the weirdest things in Wimberley is **Pioneer Town** (333 Wayside Dr., off River Rd., $5 for parking). This is a small Wild West town created out of old buildings found in and around Wimberley. It all started when the founder of 7A Resort, old-timer Raymond Czichos, visited Knott's Berry Farm in California. He came back to Wimberley inspired, and over the course of several years built this bizarre mock town. Initially it had real businesses, run by folks in Western getups, but today it's more of a ghost town: 1960s-style mannequins from department stores, dressed up in Western attire, are the only remaining survivors of this dream. One of the top attractions in town is the studio at **Wimberley Glass Works** (6469 RR 12, 800/929-6686, www.wgw.com, 10am-5pm daily). Founded by Tim de Jong in the 1990s, this incredible space has become one of the premier art glass galleries in the Southwest. Handblown glass demonstrations take place daily, where master artists create lighting and art glass. Wimberley Glass Works is south of town on RR 12. ##### **Shopping** All the shopping in town takes place at Wimberley Square. Here you'll find hundreds of little boutiques filled with Texana crafts, home furnishings, vintage clothes, and antiques, along with a couple of art galleries. Your shopping strategy should be to park anywhere and spend a couple hours walking around. Shops often come and go within a matter of months in this area. Boutiques worth checking out are **Brocante** (14015 RR 12, 512/847-8577, 10:30am-5pm Mon.-Sat., 11:30am-5pm Sun.) and **Wall Street Western** (13904 RR 12, 512/847-1818, 10am-6pm daily). An interesting art gallery featuring folk art and wildlife sculptures is **Old Mill Store** (Wimberley Square RR 12, 512/847-3068, 10am-6pm Mon.-Thurs., 10am-7pm Fri.-Sun.). ##### **Food** **Blair House** (100 Spoke Hill Rd., 512/847-1111 or 877/549-5450, www.blairhouseinn.com, $65) offers the best fine-dining experience in the area. A five-star fixed menu is offered at 7:30pm each Saturday evening. Any restaurant that's only open one night a week and still gets the highest of accolades deserves the title of fine dining. Entrées have included coffee-braised short ribs with baked yams and pork tenderloin with orange sauce. **Cypress Creek Café** (320 Wimberley Square, 512/847-0030, 11am-9pm daily, $12) serves up American fare that keeps the locals coming back. Coconut shrimp, scampi, marlin, pork—all make this menu diverse and yummy. On beautiful Cypress Creek is **Ino'z** (14004 RR 12 on Wimberley Square, 512/847-6060, 11am-9pm daily, $8). The setting is the best in town as restaurants go; however, the food is nothing special. The reason to come here is to sit on the outside deck and have chicken-fried steak and a beer under the bald cypress trees next to the creek. **Miss Mae's BBQ** (419 FM 2325, 512/847-9808, 10:30am-7pm Mon.-Sat., $8) has the barbecue connection in Wimberley. The tradition started in 1957 in the founder's grandmother's kitchen. Using her recipe, Miss Mae's cooks up barbecue chicken, beef, ham, and turkey. ##### **Accommodations** There are over 100 different lodgings in and around Wimberley, including bed-and-breakfasts, guest rooms, cottages, and cabins. The reservation service **Texas Hill Country Reservations—All Wimberley Lodgings** (14500 Ranch Rd. 12 #13, 512/847-3909, <http://texashillcountryreservations.com>) can help match you with a lodging that suits your budget and needs. If you prefer not to use a service, the following accommodations come recommended. S **Blair House** (100 Spoke Hill Rd., 512/847-1111 or 877/549-5450, www.blairhouseinn.com, $125-275) is easily one of the top places to get away in the Hill Country. After all, _Condé Nast Traveler_ considers Blair House one of the top 25 inns in the country for a very good reason—or should I say several reasons. Here guests are seduced with all the pleasures one could wish for in a vacation getaway, with fine dining and fine linens in a fine location. In the evening, turndown service includes a beverage and a confection, and in the morning guests wake up to a gourmet breakfast. For budget travelers, **Mountain View Lodge** (RR 12, south of Wimberley, 512/847-2992, $85-95) has excellent rooms with balconies and views of the Wimberley Valley. Continental breakfast is included in the rates. Comfortable cottages and a serene setting are to be found at **Wimberley Inn** (200 FM 3237, 512/847-3750, www.wimberleyinn.com, $85-175). A night's stay here includes an upscale continental breakfast, along with great service. High-speed Internet access is available. #### **NEW BRAUNFELS** The German heritage of Central Texas all began in the town of New Braunfels (pop. 63,000), located in the Austin-San Antonio corridor off I-35. Back in the 1840s, German entrepreneurs bought a vast amount of acreage here with the intention of bringing in German colonists. The first settlers, led by Prince Carl of Solms-Braunfels in Germany, arrived to find the area far from the coast and populated by Native Americans, but they decided to settle the area anyway. These first German settlers brought their culture and traditions and integrated them into the story of the Texas Hill Country. These traditions have survived to the present day and define New Braunfels, making it the unique place that it is. Today people come to New Braunfels for many reasons. City folks in both Austin and San Antonio come here to relax, spend hot summer days at the enormous water park, and to imbibe the vestiges of German-meets-Texas culture. People also come here to do some serious antiques shopping. There are so many junk and antiques shops here that New Braunfels has been dubbed the Antique Capital of Texas. For more information on New Braunfels contact the **New Braunfels Visitors Center** (237 I-35 N. at FM 725, 830/625-7973, 9am-5pm daily). ##### **Sights and Activities** Most people come to New Braunfels for recreation that centers on water. Water fun comes in many forms and sizes here, such as tubing down the Guadalupe River, rafting, or fishing. For those who want water without the mud and in a totally artificial environment, there's **Schlitterbahn** (400 N. Liberty, 830/625-2351, www.schlitterbahn.com, 10am-8pm daily in peak summer months, 10am-6pm weekends at the beginning and end of season, $38 adults, $30 children 3-11). This mega-size water park with a German theme, open late April-September, draws people by the thousands all spring, summer, and fall. Featuring over 30 waterslides, pools, thrill rides, and all sorts of wet fun for the whole family, Schlitterbahn has become Texas's largest water park. **Cheating Death at the Guadalupe River** Driving north from San Antonio toward Austin on I-35, you will cross the Guadalupe River at the scenic town of New Braunfels. As you pass the bridge over the Guadalupe, imagine the winter of 1838. At that time, Noah Smithwick, a Texas Ranger, was making his way from San Antonio to his base in the community of Bastrop on the Colorado River. There were no bridges across the Guadalupe, and Smithwick was riding a mule. He thought he could get across, but unfortunately the river was deeper and swifter than he anticipated. He and his mule struggled but were unable to get across. After almost drowning, they both eventually emerged on the same side of the river where they had started. Unfortunately for Smithwick, he had lost his rifle, his gunpowder was wet, and he was soaked to the skin. The temperature was hovering at 30°F and a north wind was blowing at about 30 mph. The sun was going down and Smithwick was in danger of freezing to death. He could not get a fire started since he had no dry gunpowder and no flintlock to create a spark. It was at this time he remembered a story told to him by David Crockett. Crockett had been in a similar situation and survived by gathering enough armloads of tall grass to create a hay pile. Smithwick did the same and took off his wet clothes and dove into the middle of his fresh pile of grass. Amazingly, he soon became warm as toast and survived the cold night. In the morning he mounted his mule and headed back to San Antonio, where he discovered that he had escaped death three times within 24 hours. A large band of Comanche had struck San Antonio the previous day, and his friends in town thought that Smithwick had been caught alone on the prairie and killed by the Native Americans. This would probably have been his fate but for his mishap in the Guadalupe River. If he hadn't lost his rifle, he would have been able to make a fire and the Comanche would have spotted him. If he had successfully crossed the Guadalupe River, he would have run smack into their war party. Thus he almost died of drowning, freezing, and a Comanche attack all in the same day. Smithwick was a living example of that pioneer philosophy that what seems to be bad luck at first is sometimes the best thing that could happen to you. New Braunfels has a strange assortment of grassroots museums and historical sites that aren't necessarily worth driving for miles to check out. However, if you have an itch for curious historical things there are a couple places you may want to visit. The **Sophienburg Museum and Archives** (401 W. Coll St., 830/629-1572, 10am-4pm Tues.-Sat., $5) has an interesting collection of local artifacts, mostly relating to German pioneers and early folks in the history of New Braunfels. The museum is on the hilltop site where Prince Carl of Solms-Braunfels built a log fortress. There's also the **Museum of Texas Handmade Furniture** (1370 Church Hill Dr., 830/629-6504, 1pm-4pm Tues.-Sun. Feb.-Nov., $5), which features furniture items that were handmade in Texas during the 1800s. Finally, there's the **Lindheimer Home Museum** (491 Comal, 830/629-2943, 2pm-5pm weekends, $3), where visitors can tour the home of the father of Texas botany, Ferdinand Jakob Lindheimer (1801-1879). Just south of New Braunfels is **Animal World and Snake Farm Zoo** (I-35 exit 182 at Engle, 830/608-9270, www.awsfzoo.com, 10am-6pm daily Memorial Day-Labor Day, $12.75 adults, $11.75 seniors and military, $9.75 ages 3-12, children 2 and under free). Since 1967 this roadside shrine devoted to reptiles has been drawing in the curious from the highway. Inside the main facility there are over 300 reptile species. Some are endangered, some are poisonous, many you probably have never seen up close before, and all are intriguing and beautiful. All these curious creatures are stuck in small, dank aquariums, tanks, and cages that seem a bit precariously stacked and neglected. The smell in here is phenomenal. Snake Farm also has what I consider to be one of the weirdest gift shops in the state. As expected there's all kinds of snake-related memorabilia, as well as display cases that exhibit dusty souvenirs so old they've become relics in their own right. There's also a rattlesnake pit with live rattlesnakes. ##### **Food** In step with New Braunfels' German heritage is the popular **Alpine Haus Restaurant** (251 S. Seguin Ave., 830/214-0205, 11:30am-2pm and 5pm-9pm Tues.-Thurs., 11:30am-9pm Fri.-Sat., 11:30am-8pm Sun., $12). If you're expecting a super-authentic basic German food experience you may be disappointed—however, if you want a fun and fancy experience with beer and wine you will love this place. Alpine offers quite a selection of imported German beers and schnitzels, which makes for an enjoyable lunch or dinner. Want to eat beef at any time of day? **New Braunfels Smokehouse** (140 Hwy. 46 S., 830/625-2416, 8am-8pm daily, $8) has beef for breakfast, lunch, and dinner, and even for snack time. They specialize in German and American smoked meats. Here you can find any kind of meat you could ever crave—beef brisket, pork, chicken, ribs, turkey, and jerky—all hickory smoked. Housed in the old Palace Movie Theatre in historic downtown New Braunfels is **Myron's** (136 N. Castell Ave., 830/624-1024, 5pm-9:30pm Mon.-Thurs., 5pm-10:30pm Friday.-Sat., $30). People come here for great wine, Chicago prime beef, and a classy fine-dining experience. Myron's has a full bar as well as an extensive wine list. The atmosphere is casual but elegant. Reservations are recommended. Some of the best fish tacos in the area happen to be served up by surfers. The California-imported folks at **Wahoo's Fish Tacos** (6700 I-35, 830/627-7226, 11am-10pm Mon.-Sat., 11am-9pm Sun., $8) seem like fish out of water in Texas. The walls are lined with graphics of surfers, giant waves, and skateboarding stickers, and the vibe is straight from Santa Cruz, California. It's hard to wrap your head around the fish taco component, but the food is remarkably well put together and tasty, and the price is in the budget range. ##### **Accommodations** The best bed in town is at **Prince Solms Inn** (295 E. San Antonio St., 830/625-9169 or 800/625-9169, www.princesolmsinn.com, $125-150). This historic inn was built in 1898 and was known as the most romantic and most luxurious hotel in this area. It still deserves this distinction, with a great central location, fluffy pillows, wines, confections, and breakfast in the morning. If you stay here ask about the ghost tale, if you dare. Speaking of creepy stuff, the inn offers a unique experience called the murder mystery weekend, when folks rent out the inn and the staff hosts a clever whodunit evening. An excellent bed-and-breakfast just north of New Braunfels and Gruene is **Das Anwesen Bed and Breakfast** (360 Millie's Ln., 830/625-5992 or 866/526-1236, www.dasanwesen.com, $100-175). This prairie-style home is on historic Karbach Ranch, which was established when the German immigrants first settled New Braunfels in 1844. The interior of the home is filled with fine antiques, tasteful decorations, and country charm. Breakfast is served on antique china, crystal, and silver at 8:30am. For standard roadside accommodations in New Braunfels there's **Days Inn New Braunfels** (963 I-35 N. at exit 189, 830/608-0004, $54-150). One notch above the Days Inn is **La Quinta Inn and Suites** (365 Hwy. 36 S., 830/627-3333, $80) and the **Hawthorn Inn and Suites** (1533 I-35 N., 830/643-9300, $80). #### **GRUENE** One of the Hill Country's best-kept secrets is historic Gruene (pop. 20). Pronounced like the color green, this small bend in the river is technically a part of New Braunfels called the Gruene Historic District. The slogan on Gruene's promotional material speaks volumes about the town's forward-looking vision: "Gently resisting change since 1872." This happens to be the year the town was born, when German immigrant Henry D. Gruene bought the land to establish a cotton farm. The town's gentle resistance becomes very apparent once you take that last turn and drive into Gruene. Suddenly you find yourself smack-dab in the middle of an old-world downtown that's straight out of a bygone era. If you enjoy a leisurely day that includes great food, walking the carbs off, and window shopping, Gruene can steal half a day from you. If you combine this with river rafting, make it a full day. Gruene ##### **Sights and Activities** The town itself is the main attraction. It's nothing more than a few Wild West-style buildings with tin roofs, a large water tower, a historic mansion, and a few restaurants and specialty shops, all with laid-back country charm. This charm is due to the town's perfect combination of strict zoning laws that keep out big business and laissez-faire fire codes that allow nearly dilapidated buildings to continue to exist. Several of the businesses simply don't have air-conditioning. This may be a deliberate attempt at creating an old-world ambience, or maybe it's simply a way to save money. Either way it adds to the experience. A nice way to spend half a day is to simply meander through town, going in and out of the old buildings that house new businesses. If you're so inclined, buy some horseshoe art, some locally made wine, or some antiques. You never would guess it, but Gruene has one of the best venues for music in Texas, and one of the most distinctive venues in the whole United States. **Gruene Hall** (1281 Gruene Rd., 830/606-1281, www.gruenehall.com) is billed as the oldest standing dance hall in the state. I say "standing" with trepidation, as the building is so old and rickety it doesn't look like it's long for this world. The windows are chicken wire, the roof is tin, and the walls are those originally erected back in the 1880s. With chicken-wire windows there's no chance for air-conditioning, so the best way to cool down is with a cold beverage. Adorning the walls are hundreds of signed photos of the performers that have graced this old hall. Be sure to look for the two photos of Lyle Lovett, one when he was a young upstart without the big hairdo, and the other when he found his shtick. Many country legends and rock stars have performed here over the years, such as Willie Nelson, George Strait, Jerry Jeff Walker, Merle Haggard, George Thorogood, and the alt-country band the Old 97's. There's live music seven days a week in summer and 3-4 days a week the rest of the year, including Saturday and Sunday afternoons. ##### **Shopping** In a historic town like Gruene, it's only natural that there be antiques shops to add to the yesteryear flavor. If you enter town by way of Gruene Road, coming from New Braunfels, the first antiques shop you come to will be the **Gruene Antique Company** (1607 Hunter Rd., 830/629-7781, 10am-9pm daily). Housed in the original mercantile building is 8,000 square feet of antiques, collectibles, furniture, and gifts. Ask to see the original bank vault from the Henry D. Gruene days. Just up the road is a string of antiques shops, all in historic old houses, starting with **Dancing Bear** (1632 Hunter Rd., 830/629-2059, 10am-6pm Mon., daily). The proprietors are proud to offer unique finds, Texas trinkets, and decorative items for the country home, all at great prices. Next door is **Cactus Jacks** (1706 Hunter Rd., 830/620-9602, 10am-5:30pm Wed.-Mon.), which offers more furniture but with a European flair, along with some handmade gifts and things for the garden. ##### **Food** There are a few great eateries in town, a couple hovering above the Guadalupe River. These riverfront restaurants have seating outside on decks and porches under the groves of trees that line the river. One of the best restaurants in all of Texas, the S **Gristmill River Restaurant & Bar** (1287 Gruene Rd., 830/625-0684, 11am-9pm Sun.-Thurs., 11am-10pm Fri.-Sat., $15), is right here in Gruene at the base of the water tower. With a maze of terraced decks, porches, and covered areas that weave in and out of the ruins of an historic cotton gin, this top-notch restaurant is a must for dinner. Although there is no air-conditioning in most of the restaurant, once you sit down with a cold iced tea and relax, you can forget about the heat, sort of. The fare is standard, such as sirloin, trout, shrimp, and chicken-fried chicken, but all is above standard once it hits the palate. Gruene's Tex-Mex food establishment, **Adobe Verde** (1724 Hunter Rd., 830/629-0777, www.adobeverde.com, 11am-9pm Sun.-Thurs., 11am-10pm Fri.-Sat., $8), is a great place to bring the family or fill up before a show at Gruene Hall. I recommend relaxing on the covered patio while eating fajitas, chips and queso, or tortilla soup. ##### **Accommodations** If you aren't hurried and can stay the night in town, Gruene has a few great options for lodgings. The most famous and certainly the place with the most mystique is **Gruene Mansion Inn** (1275 Gruene Rd., 830/629-2641, www.gruenemansioninn.com), the original house that Henry D. Gruene built. This old mansion offers 30 different rooms, units, and nooks to stay in, ranging $159-209. Rooms are brightly colored, some outfitted with claw-foot tubs, hardwood floors, canopy beds, fireplaces, and views of the Guadalupe River. If an old mansion freaks you out, or if you prefer modern accommodations, **Gruene River Hotel & Retreat** (1235 Gruene Rd., 830/643-1234, www.grueneapple.com) has clean rooms with views of the river as well. Amenities in the rooms can include a whirlpool tub, fireplace, or a private balcony, and amenities available to all guests include a full-size swimming pool, a media room with theater, and an entertainment room including a pool table and library. Rates range $160-210 and include a hearty gourmet breakfast. Imagine cinnamon pecan-stuffed French toast, and you'll understand the use of the word _gourmet._ Other accommodations include **Gruene Homestead Inn** (832 Gruene Rd., 800/606-0216, www.gruenehomesteadinn.com), a collection of historic farmhouses and cabins on eight acres. Prices range $175-250 depending on the room and time of the year. There's also **Gruene River Inn** (1111 Gruene Rd., 830/627-1600, www.grueneriverinn.com, $125-195), located 100 feet above the Guadalupe River. Every room takes advantage of the great view of the river. And finally, for a great bed-and-breakfast, there's **Antoinette's Cottage** (1258 Gruene Rd., 830/606-6929, www.antoinettescottage.com, $150). ### **Transportation** The best way to get around in the Hill Country is by car. Having the freedom to go where and when you please is the only way you can truly sink your teeth into this big pie. Car rental agencies in Austin and San Antonio include **Advantage Rent-A-Car** (800/777-5500), **Alamo Rent-A-Car** (800/462-5266), **Avis Car Rental** (800/331-1212), **Budget** (800/527-0700), **Dollar Rent-A-Car** (800/800-3665), **Enterprise** (800/261-7331), **Hertz Rent-A-Car** (800/654-3131), **National Car Rental** (800/222-9058), and **Thrifty** (800/847-4389). On average, Hill Country towns are about 30-40 miles apart. You don't need to sweat filling up with a tank of gas at every town (that is, unless you are driving a 1960s Buick that gets 5-10 miles per gallon). That said, when you're in a small town and you're running below half a tank, it's a good idea to fill 'er up. Finding your way around the small roads in the Hill Country can be tricky if you're not from the area. Streets in town often have a name, but as they leave town they turn into numbered roads. On maps you may see unusual abbreviations. FM means Farm-to-Market, RM means Ranch-to-Market, and RR means Rural Road. Many dude ranches, state parks, and attractions out of town simply don't have street addresses. Instead they use old-fashioned ranch signs to mark their entrances. two views of San Antonio's famous ## **San Antonio** HIGHLIGHTS PLANNING YOUR TIME ORIENTATION Sights NORTH DOWNTOWN WEST EAST SOUTH Entertainment and Events LIVE MUSIC BARS AND CLUBS PERFORMING ARTS AND THEATERS CINEMAS COMEDY CLUBS FESTIVALS AND EVENTS Shopping CLOTHES, SHOES, AND ACCESSORIES MUSIC BOOKSTORES ART GALLERIES Recreation HIKING AND BIKING GOLF SPECTATOR SPORTS TOURS Food AMERICAN MEXICAN, TEX-MEX, AND SOUTHWESTERN OTHER INTERNATIONAL FOOD HEALTHY AND VEGETARIAN FINE DINING Accommodations UNDER $50 $50-100 $100-150 $150-250 OVER $250 Information and Services TOURIST INFORMATION EMERGENCY INFORMATION PUBLICATIONS INTERNET LAUNDRY POST OFFICE MONEY Transportation GETTING THERE GETTING AROUND River Walk. **Highlights** Look for S to find recommended sights, activities, dining, and lodging. S **San Antonio Zoo and Aquarium:** This zoo carved into the side of a cliff is a blast for the whole family. See lions, gorillas, alligators, and other exotic birds and animals (click here). S **Brackenridge Park:** This beautiful park is home to many of the city's main attractions, such as the San Antonio Zoo and Aquarium, the Witte Museum, the Texas Pioneer and Ranger Museum, the Japanese Tea Gardens, and a miniature train called the Brackenridge Eagle (click here). S **San Antonio Museum of Art:** Prehistoric art, Egyptian mummies, Roman statuary, antiquities, and American and European paintings by the masters are all housed in the former Lone Star Brewery building (click here). S **The Alamo:** The most sacred site on Texas soil is this old mission that became the site of one of the bloodiest showdowns in U.S. history (click here). S **River Walk:** Walk down the old stone steps to the River Walk to find shops, boats, and restaurants with umbrella tables, all lining the twisting San Antonio River (click here). S **La Villita:** The historic site of the first established village in San Antonio today houses art galleries, cafés, and funky shops (click here). S **HemisFair Park:** Once the World's Fair of 1968 was over, San Antonio was left with amazing attractions like the Institute of Texan Cultures, the Tower of the Americas, the water gardens, and the Schultz House Cottage Garden (click here). S **King William Historic District:** An excellent place for a lazy afternoon or evening stroll, this historic part of town was built by and for San Antonio's upper class. The mansions are still occupied, and a couple are even open to the public (click here). S **The Missions:** Stroll these sacred grounds and learn how the indigenous peoples lived before the arrival of the Spanish, and how missionaries changed them and their culture (click here). San Antonio is one of the oldest continuously inhabited places in Texas. Historically, this stretch of lush and scenic land along the San Antonio River was both beautiful and rich in resources, which made it a crossroads of many peoples and cultures, including Native Americans, Spanish settlers and missionaries, Latin Americans, and even German immigrants. Throughout the centuries, all this cultural exchange and diversity provided the stage for some of the more dramatic chapters in Texas's history. Today San Antonio has settled into its role as a laid-back, friendly, gritty, hardworking family town and is proud to still be a crossroads of cultures. It is a place where Mexico, the old Wild West, and the New World genuinely and successfully collaborate to create a unique culture and relaxed lifestyle that can't be found anywhere else. It's a place where Spanish colonial architecture and modern skyscrapers emerge out of the ancient San Antonio River's beautiful River Walk; where mariachi mass is still offered at one of the old Spanish missions; and where masterfully executed murals on city walls tell the story of Mexico and Texas. People are always pleasantly surprised by the remarkably unique charm this city has. Most people know of San Antonio as the home of the mother of all American pilgrimage sights—The Alamo. Sure, there's The Alamo, Davy Crockett, General Santa Anna, and the fight for independence—but there's also much more. There's the beautiful River Walk, the crumbling Spanish missions, world-class museums, and even overblown theme parks. Because of all this history, natural beauty, and fun, San Antonio has grown into the seventh-largest city in the United States and is Texas's most beloved town. #### **PLANNING YOUR TIME** San Antonio covers a massive area, but fortunately most of what people come here for is in or around downtown, which makes planning your time fairly easy. Most people prefer to stay at one of the many hotels along the River Walk to make it just that much easier. If you plan on seeing the sights downtown, your trip is a cinch to plan—in fact, you can figure it out as you go. Two days should be sufficient if you're focusing on downtown. However, if you want to take in sights outside of the downtown area, such as the San Antonio Zoo, the missions, the Witte Museum, or one of the two theme parks, you will want to plan your time more carefully. Going to any of the above can easily turn into a full-day excursion, once you factor in transportation time and meal breaks. **San Antonio Fast Facts** • Founded in 1731 • Population: 1,327,000 (2016 U.S. Census Bureau data) • Land area: approximately 460 square miles • Time zone: GMT/UTC-6 (Central Time) • Second-largest city in Texas • Seventh-largest city in the United States • County: Bexar • Ethnicity: 72 percent white, 63 percent Hispanic, 7 percent African American, 2.4 percent Asian, 13 percent other • Sales tax: 8.25 percent #### **ORIENTATION** San Antonio is only 80 miles south of Austin, just outside the Hill Country. The border of Mexico is 270 miles to the south, and the Gulf of Mexico is 140 miles to the southeast. The city itself is a massive, sprawling place that can be intimidating for the first-time visitor. For the most part, sights, activities, and points of interest are located in three main areas: downtown, Southtown, and the Brackenridge Park area. The downtown area is where you will likely spend most of your time. It's stunningly beautiful here, and most everything is within walking distance. Because of this, most visitors pitch their tent in one of the many hotels on the River Walk. This is where you'll find sights pertaining to the original Spanish settlement, such as The Alamo, the River Walk on the San Antonio River, La Villita, several museums, and Market Square. In Southtown you'll explore the mansions of the King William Historic District, modern art studios and galleries, and some of the best restaurants San Antonio has to offer. Southtown is also the starting point for the missions along the Mission Trail. The Brackenridge Park area is where you'll spend a good chunk of time if you have kids. This beautiful city park is home to the famous San Antonio Zoo as well as museums and botanical gardens geared toward families. Also in this area is the newer Pearl District, home to some of the city's best restaurants. Outside of these three areas is an endless urban and suburban sprawl with neighborhoods, strip malls, industrial complexes, and military bases. The three attractions worth mentioning among these areas are Six Flags Fiesta Texas, SeaWorld San Antonio, and Splashtown. **Two Days in San Antonio** If you have two days to devote to your stay in the large city of San Antonio, you will want to plan your time wisely. An itinerary to maximize time but not miss anything important would include focusing on the downtown area, the Brackenridge area, and the Mission Trail. Unless big theme parks are important to you I would skip them all together and enjoy the richer things the city has to offer. **Day 1:** Wake up at the Menger Hotel, get breakfast, and head over to The Alamo before the historic site gets crowded. Next up is window shopping in the old part of town, La Villita, which is close by. By now you're probably getting hungry, so a stroll through the Arneson River Theatre and down to the River Walk is recommend. After a riverside lunch at Boudro's, the rest of the day could be spent on a guided river cruise and traveling the Mission Trail by car or bike. **Day 2:** Start the day with breakfast at Guenther House in the King William District. Next is an excursion up to the Brackenridge Park area. Take time to meander through the Japanese Tea Garden followed by a visit to the Witte Museum. After a light lunch (we're saving our appetite for later), a couple hours could easily be spent at the San Antonio Zoo. Before evening comes, head to the Pearl District. Here you can enjoy shopping and dining at some of the city's best restaurants, such as Southerleigh Fine Food and Brewery. Lastly, one should spend his or her final late-night hours on the beautiful River Walk, maybe stopping by the Esquire Tavern before turning in. ### **Sights** San Antonio is Texas's most beloved city for all things touristy. Its rich history combined with a contemporary appeal keeps folks coming here year-round. Besides being home to the two most visited attractions in Texas, The Alamo and the River Walk, San Antonio also has world-class museums, mega theme parks, and quirky attractions that are sure to amuse even the most jaded traveler. #### **NORTH** ##### **Six Flags Fiesta Texas** A mega theme park in the San Antonio area is **Six Flags Fiesta Texas** (17000 I-10 W., 210/697-5050, www.sixflags.com, hours vary). With over 200 acres of fun for the whole family, Six Flags is a major draw for thrill seekers from all over the state. The park features rides for all ages, as well as campy shows and theme areas à la Disneyland. The whole park has a Texas spin, flavor, and look, with cartoon-style themed areas like a Hispanic village and a German town. The real reason people come here is to get sick and scared on the roller coasters or get wet on the waterslides and chutes. Families will like how the rides are laid out, mixing the adult rides with the children's rides. This makes for a fun day for everyone, all at the same time. I pity the folks who are walking around dressed up like cartoon characters in the middle of summer. Park hours and days of operation fluctuate, so call in advance. Tickets are $55 for general admission. Purchase tickets online for a discount. ##### **Texas Transportation Museum** The quirkiest attraction in town has got to be the **Texas Transportation Museum** (11731 Wetmore Rd., 210/490-3554, www.txtransportationmuseum.org, 9am-3pm Fri., 10am-5pm Sat.-Sun., $10 adults, $8 children 4-12, children under 4 free). Really, this is more a shrine and a personal passion dedicated to the great era of the locomotive. Here you can marvel at miniature-scale model train sets, both indoors and outdoors. The scale models and their detailed environments are a must-see for the train geek and a try-to-see for the curious. It's north of San Antonio Airport. If you can, give a donation on top of your admission to keep this independently owned operation alive. ##### **McNay Art Museum** San Antonio's best repository for paintings by the masters is the lovely **McNay Art Museum** (6000 N. New Braunfels St., 210/824-5368, www.mcnayart.org, 10am-4pm Tues., Wed., and Fri., 10am-9pm Thurs., 10am-5pm Sat., noon-5pm Sun., $20 adults, $15 students, seniors, and military, children 12 and under free). Safely hanging on the walls of a stunning old Spanish colonial revival mansion is a spectacular collection of art. The collection focuses on 19th- and 20th-century European and American art, including notable works by Picasso, Cézanne, O'Keeffe, Gauguin, and Van Gogh, and also features sculpture. The mansion is surrounded by well-tended gardens, making this one of the most scenic and breathtaking museums in Texas. The house and much of the collection belonged to a wealthy woman by the name of Marion Koogler McNay, who donated everything to the cause of "advancement of art" upon her passing in 1950. Subsequently, the McNay Museum was the first modern art museum in the state. Free parking is available. ##### **San Antonio Botanical Garden** The **San Antonio Botanical Garden** (555 Funston Pl., 210/536-1400, www.sabot.org, 9am-5pm daily, $10), northeast of downtown, is a whopping 33 acres of well-tended plants, all waiting to be admired, understood, and appreciated. Most of the plants are displayed outdoors in the vast landscape. A slew of well-planned theme gardens are carefully orchestrated, such as the Texas regional gardens, the Old-Fashioned Garden, the Rose Garden, the Sacred Garden filled with biblical plants, the Japanese Garden, and the brilliant Garden for the Blind. The uniquely shaped glass building that's the focal point of the grounds is the conservatory, which houses plants that have "special needs." Within a fully controlled climate the staff are able to create mini-ecosystems for plants that otherwise would perish in the San Antonio climate. Displays in the conservatory include exotic plants, ferns, desert plants, tropical plants, and palms and cycads. Outside, the conservatory is surrounded by a sunken courtyard and tropical lagoon filled with even more plants. The overlook happens to the highest point in San Antonio, 798 feet above sea level. ##### S **San Antonio Zoo and Aquarium** In beautiful Brackenridge Park is the glorious **San Antonio Zoo and Aquarium** (3903 N. St. Mary's St., 210/734-7184, www.sazoo-aq.org, 9am-5pm daily, until 6pm in the summer, $14.25 adults, $11.25 children 3-11). This world-renowned zoo is home to over 3,500 animals, with 750 species represented, including some endangered species. Virtually every animal that spurs the imagination the world over can be found here, lying around in small cages and faux environments. Popular residents are the lions, zebras, tigers, and gorillas. Along with gawking at those critters in captivity, one can also learn much here, as the zoo is set up to educate and foster a love of animals. To give the kids time to explore I recommend planning about three hours for your trip to the zoo. ##### S **Brackenridge Park** North of downtown is San Antonio's own Shangri-la, **Brackenridge Park** (3910 N. St. Mary's St., 210/207-7275, 5am-11pm daily, free). This beautiful city park has many features and attractions that make it a special place for kids, adults, and adults that act like kids. There's the nationally renowned **San Antonio Zoo and Aquarium,** a miniature train called the **Brackenridge Eagle** (210/735-7455) that travels a two-mile circuit around the park, the **Japanese Tea Gardens** (210/735-4648), also known as the **Sunken Gardens,** and the **Sunken GardenTheatre.** Brackenridge Park is also home to the **Brackenridge Golf Course** (210/226-5612), the oldest 18-hole public golf course in Texas. At the northeastern edge of the park are a trio of excellent museums, among them the **Witte Museum** (210/357-1900). Besides these attractions Brackenridge Park is the location of many springs that make up the headwaters for the San Antonio River, which brings the beauty of flowing, twisting lanes of water to the park. The old stone building over the river is the pump house that operated as San Antonio's first public water supply system. With a mini-amusement park, a mini-train to ride, boats to bob in, museums, and a zoo, who needs _Lost Horizon_? The park is approximately two miles north of downtown, and the main entrance is in the 2800 block of North Broadway. Although admission to the park is free, fees may apply to some of the attractions within the park. Plan on spending about an hour here appreciating the beautiful setting. ##### **Witte Museum** The museum that boasts the most is the **Witte Museum** (3801 Broadway St., 210/357-1900, www.wittemuseum.org, 10am-5pm Mon.-Sat., until 8pm Tues., noon-5pm Sun., $10 adults, $8 seniors and military, $7 children 4-11), north of downtown in beautiful Brackenridge Park. The correct pronunciation is like "witty," and coincidentally the museum is pretty clever. The Witte is a spectacular institution that features all sorts of fun and interesting exhibits that are sure to pique the interests of everyone. With real _Triceratops_ and _Tyrannosaurus rex_ bones, mummies, dioramas, history and natural science exhibits, national touring exhibits, family events, and overnight camp-ins for children, there's almost—dare I say—too much happening here. In fact, the Witte deserves nearly a day of your time, especially if you are bringing children. The biggest draw for kids is the H.E.B Science Tree House, which consists of four floors for the mini scientist and junior anthropologist in the family to explore. ##### **Japanese Tea Gardens** The most serene spot in town is the **Japanese Tea Gardens** (3875 N. St. Mary's St., 210/735-4648, free). Also known as the Sunken Gardens, this beautiful spot inside Brackenridge Park was the former site of a rock quarry that produced the limestone used to construct the Texas State Capitol in Austin. Someone with vision got the idea of making this beautiful and brought in a Japanese designer, Mr. Jingo, who designed and built the magnificent gardens. The gardens have been restored to their prime. Highlights of the Japanese Tea Gardens include winding walkways, a waterfall, and serene lily ponds with koi, turtles, and ducks. Walking the traditional stone Japanese bridges and exploring these tranquil, lush, overgrown gardens is a relaxing way to spend an afternoon. ##### S **San Antonio Museum of Art** Housed in the former Lone Star Brewery building, which dates to 1884, is the **San Antonio Museum of Art** (200 W. Jones Ave., 210/978-8100, www.sa-museum.org, 10am-5pm Wed.-Sun., 10am-9pm Tues., $10). Just North of downtown San Antonio, this truly world-class museum is one of the most comprehensive in the United States, with four floors of exhibits that contain perfectly displayed prehistoric art, Egyptian mummies, Roman statuary, antiquities, and American and European paintings by the masters. Along with all this, the museum is also home to the **Nelson A. Rockefeller Center for Latin American Art,** which is the most extensive collection of Latin American art in the nation. To give you an example of the caliber of the San Antonio Museum of Art, this museum is on the same touring-exhibit circuit as the New York Metropolitan Museum of Art and the Louvre in Paris. #### **DOWNTOWN** ##### S **The Alamo** The most revered historical site and most venerated landmark in Texas is **The Alamo** (300 Alamo Plaza, 210/225-1391, www.thealamo.org, 9am-5:30pm daily, and 9am-7pm daily in summer, free). Here legends and heroes of Texas history were born, died, and live on in our imaginations. Most visitors are surprised to see that The Alamo is small in size, but the history here is huge. On this hallowed ground in 1836, 188 brave Texans made their stand against 3,000 (give or take a few) of General Santa Anna's finest. For 13 days a bloody battle was carried out, culminating in the final assault on the morning of March 6. Famous Texans like Colonel William Travis, James Bowie, Juan Seguin, and, of course, the Tennessean Davy Crockett (a congressman and outdoorsman who was famous in his day for his exploits) made history by defying the dictator Santa Anna and staking their lives for freedom's sake. They lost the battle, but through their sacrifice a nation (the Republic of Texas) was born. The Alamo is Texas's most treasured historic sight. There is some controversy regarding what became of Davy Crockett, but whatever you do, don't let a revisionist historian tell you that Davy Crockett surrendered (the José Enrique de la Peña "diaries" were a forgery—Davy died swinging his rifle, Ol' Betsy, and that's my story and I'm sticking with it!). The defenders' famous stand bought precious time for the fledgling republic's first president, Sam Houston, who eventually was able to defeat Santa Anna at the Battle of San Jacinto, near Houston. Texas is the only state of the United States that was a sovereign nation before being annexed in 1845. **What Happened to Davy Crockett?** Some of the details of the battle at The Alamo are shrouded in mystery. The legend of Davy Crockett and The Alamo is perhaps the most controversial of these mysteries. History has offered us several conflicting accounts of what happened to Crockett. Did he die or was he taken as a slave? And if he died there, where did he die? A slave of William Travis's named Joe and one of the female survivors, Susanna Dickinson, reported seeing his body at The Alamo surrounded by several dead Mexican soldiers when they departed the chapel after the battle. In 1975, a diary of a Mexican officer by the name of José Enrique de la Peña surfaced. In the diary, de la Peña reported that Crockett was one of several men taken prisoner after the battle and put to death before Santa Anna "without complaining and without humiliating themselves before their torturers." The authenticity of the diary is subject to much dispute. The diary's account of Crockett's death conflicts not only with the observations of Travis's slave and Dickinson but also with those of the Mexican _alcalde_ (mayor) of San Antonio, Francisco Antonio Ruiz. Santa Anna put Ruiz in charge of collecting all the dead and burning their bodies. Santa Anna had him identify the bodies of Travis, Bowie, and Crockett, a task he would not have had to perform if Crockett had been killed in Santa Anna's presence. At the turn of the 20th century, The Alamo was almost converted into a hotel but was saved by the Daughters of the Texas Republic, who to this day impeccably maintain the historic site. Plan on spending about 1-2 hours at The Alamo to view the old limestone buildings, artifacts, and the exhibits on the Texas Revolution and Texas history. ##### S **River Walk** The greatest and most pleasant surprise San Antonio has to offer is the Paseo del Río, commonly referred to as the **River Walk** (www.thesanantonioriverwalk.com). This stretch of the San Antonio River winds and twists its way through the downtown area, in the shadows of the city's historic buildings and skyscrapers. With stone bridges, stone stairways, and winding pathways at the edges of the calm, teal-colored water, the River Walk is reminiscent of the smaller canals of Venice. Once you descend one of the many stairways and set foot on the River Walk you find yourself in a quiet, romantic, captivating subterranean world with shops, riverside cafés, bars, restaurants, hotels, and historic sites. The River Walk almost never was. Back in the 1920s, after a disastrous flood, the city nearly filled in this part of the San Antonio River. Thanks to city officials with vision and the brilliant design of Robert H. Hugman, what began as a catastrophe ended in 1941 as the Paseo del Río (River Walk). In 1968, just before the opening of San Antonio's World Exposition (HemisFair), a second extension and upgrade was completed, which helped put San Antonio on the map as a world-class city. Then, in the '70s, the River Walk superseded The Alamo in popularity thanks to a clever campaign by the city with the slogan "Forget the Alamo. Remember the River Walk." Today the River Walk is the historic, well-established centerpiece of downtown. The city's locals and frequenters can all too easily overlook this as something for the tourist. Sure, it has its touristy side, but it's also a unique and genuinely integral part of San Antonio. Although the River Walk is always active, it reaches a fevered pitch during Fiesta San Antonio and the winter holiday season. So many people are down on the stone walks that it's not uncommon to see someone fall into the river. To truly appreciate the River Walk, all you have to do is take a seat at one of the riverside cafés, sip a mojito, and watch the boats and people pass by. This River Walk area is so enjoyable I recommend strolling, enjoying dining riverside, and taking a cruise tour, all of which can add up to about four hours. ##### S **La Villita** While walking on San Antonio's famous River Walk you'll stumble on a historic yet touristy little spot called **La Villita** (418 Villita St., 210/207-8614, 10am-6pm daily, free). This is the original site of San Antonio's first neighborhood. It's believed it was founded as a settlement for Spanish soldiers under Santa Anna who were stationed at the Mission San Antonio (The Alamo). The buildings at La Villita are mostly historic; some have survived periodic floods and some have been transported to this location. Inside these relics there are galleries, shops, and cafés, all oozing charm. Also at La Villita is the historic outdoor **Arneson River Theatre,** which was cleverly constructed of stone with grass patches for comfortable seating, as was seen in the movie _Miss Congeniality._ Also in La Villita is the Cos House, which is believed to be the spot where General Perfecto de Cos signed the articles of capitulation for the Mexican Army after being defeated by the Texian Army. Plan on an hour or two for shopping and meandering. La Villita ##### **San Antonio Children's Museum** The stodgy museums of adults can get pretty boring for kids. If you make a pit stop at the **Doseum** (2800 Broadway St., 210/212-4453, www.thedoseum.org, 10am-5pm Mon.-Thurs., 9am-5pm Fri., 9am-6pm Sat., noon-5pm Sun., $12) you're sure to put a smile on their faces. This three-story museum has many hands-on interactive exhibits and creative programs. Here children can pretend to be artists, a grocery store employees, veterinary doctors, or construction workers, and learn at the same time. Although the museum is designed for children ages 2-12, adults can also get into this if you let go of your inhibitions and adultness and scream, run, and play. ##### **San Fernando Cathedral** The oldest cathedral sanctuary in the United States is at **San Fernando Cathedral** (115 Main Plaza, 210/227-1297, www.sfcathedral.org). Founded in 1731 by a group of families who came from Spain at the invitation of King Philip V, this picturesque, historic, gothic revival-style cathedral has seen much of San Antonio's history. Probably the most dramatic event was during the siege of The Alamo, when General Santa Anna raised the flag of "no quarter" from the rooftop. The cathedral has always been at the center of San Antonio's life, and it remains a cultural centerpiece. It is the seat of the Roman Catholic Archdiocese of San Antonio and offers mass in Spanish, English, and Latin. The popular mariachi mass is offered at 5:30pm every Saturday, and every Sunday several masses are offered. For the mass schedule visit the cathedral's website. ##### **Spanish Governor's Palace** The **Spanish Governor's Palace** (105 Plaza de Armas, 210/224-0601, 9am-5pm Tues.-Sat., 10am-5pm Sun., $5) is considered "the most beautiful building in San Antonio" according to the National Geographic Society. The "palace" is better described as a mansion. It's a beautiful Spanish colonial home with thick adobe walls and beautiful gardens. It was built as a result of an early-17th-century rivalry between Spain and France for dominance over the territory. No Spanish governor has ever actually lived here, but, as the pseudo-home of the local authority, the palace played host to all-important Spanish officials of the Province of Texas. In short, the palace was the crash pad for big shots. The interior is simply but elegantly decorated with period furnishings and unique objects from everyday 19th-century life. For some reason ghosts inhabit the fountain in the garden. According to my research, the gurgling that comes from the fountain isn't the ghosts. The strangely low admission fee makes this the cheapest thrill in town. ##### **Texas Pioneer Trail Driver & Ranger Museum** San Antonio wouldn't be complete without a special museum dedicated to the folks who founded and protected Texas in the beginning. The **Texas Pioneer Trail Driver & Ranger Museum** (3805 Broadway, 210/822-9011, 11am-4pm Mon.-Sat., noon-4pm Sun. Sept.-Apr., $5) is a commendable tribute that offers a rare glimpse into the early pioneer days, with exhibits that display items that kept the pioneers alive. The collection includes Texas Ranger artifacts and items from the old trail drivers. ##### **Buckhorn Museum and Texas Ranger Museum** The **Buckhorn Museum and Texas Ranger Museum** (318 E. Houston St., 210/247-4000, www.buckhornmuseum.com, 10am-6pm daily, $19.99 adults, $14.99 for children 3 to 11) is more amusing than an actual museum. Avoiding the confines and stuffiness of the conventional museum, this weird institution has been in continuous operation since 1881. The Buckhorn was founded by Albert Friedrich on Dolorosa Street as a saloon where a man could get a shot of whiskey in exchange for deer antlers. During Prohibition the saloon became a "museum" and resurfaced after Prohibition as a watering hole. Over the years the saloon's collection of horns and antlers grew to include trophy mounts, memorabilia and "artifacts" from the Wild West, furniture made of cattle horns, art made from the rattles of rattlesnakes, antique powder horns, and firearms. In all, there are more than 1,200 dead animals, making this a temple to the art of taxidermy. If you don't know whether to take this seriously or not, err on the side of tongue-in-cheek, and you'll have a laugh. Also located here is the Texas Ranger Museum. Here you'll get up close to hundreds of Texas Ranger artifacts, including revolvers, sawed-off shotguns, badges, and all things related to law enforcement in the early days of Texas. History buffs of the great state will be impressed. The highlight of the Texas Ranger Museum is Ranger Town, a re-creation of San Antonio at the turn of the 20th century. Explore this western town complete with a replica Buckhorn Saloon, a working jail cell, blacksmith shop, newspaper, and telegraph office. Ranger Town is also home to the Bonnie and Clyde exhibit—complete with a vintage 1934 Ford V8 Deluxe, the same make and model as the couple's famous getaway car. ##### **Tower of the Americas** The focal point in the San Antonio skyline is the **Tower of the Americas** (739 E. Cesar E. Chavez Blvd., 210/223-3101, www.toweroftheamericas.com, 10am-10pm Sun.-Thurs., 10am-11pm Fri.-Sat., $12). The 750-foot-tall tower is one of the many remnants of the HemisFair (World's Fair) that was held in **HemisFair Park** back in 1968, and it's still one of the tallest freestanding structures in the Western Hemisphere. No matter where you are in San Antonio you can see the 750-foot tower, which dwarfs the Space Needle by 87 feet and snubs the Washington Monument by 67 feet. In Texas everything is bigger—get used to it. The enormous Tower of the Americas is a great way to get your bearings while in San Antonio. The observation deck is some 59 stories high and offers the very best view in town. Buying a Tower Ticket for $12 ($10 seniors and military, $9 children 4-12 years, children 3 and under free) gives you all-day access to the observation deck and a 15-minute ride called **Skies Over Texas,** which is a stadium-seating 4-D adventure that offers a short Texas history lesson through a simulated helicopter ride over the state. The tower is also home to the **Chart House Restaurant** (210/223-3101, $30), a slowly revolving eatery with mediocre pseudo-fancy food, and a low-key cocktail lounge called **Bar 601** (210/223-3101). Drinkers will be pleased to know that, unlike the restaurant, the lounge doesn't revolve. Late hours make this a must for romantics. Parking is $8 at 701 Bowie Street. ##### **Institute of Texan Cultures** Texas, and more specifically the San Antonio area, has some of the continent's most ancient history. Many various peoples have inhabited, settled, and in some way contributed to the history and prehistory of the state. The **Institute of Texan Cultures** (801 E. Cesar E. Chavez Blvd., 210/458-2300, www.texancultures.com, 9am-5pm Mon.-Sat., noon-5pm Sun., $10 adults, $8 seniors, $8 children 6-17) has pulled all this history into one place and presented it in a dynamic and moving way. The populations of 26 cultural and ethnic groups are represented and explored through the items they left behind, such as tools, religious artifacts, and household items from daily life. In the 50,000-square-foot space the institute has developed fascinating permanent and rotating exhibits, educational programs, and even a multiscreen video presentation that unveils these cultures. The institute originally opened at the HemisFair back in 1968, but was so well received it has remained open since. Limited free parking is at the front of the building, and paid parking is available at 701 Bowie Street for $8. ##### S **HemisFair Park** One landmark event that put San Antonio on the map was the city's hosting of the World's Fair in 1968. The fair coincided with the city's 250th anniversary, and people saw this as an opportunity to boost San Antonio's profile as a world-class destination by pulling off a dramatic fair. Thus, **HemisFair Park** was created. Once the fair was over the city was left with some amazing features that were wisely preserved, such as the **Institute of Texan Cultures,** the **Tower of the Americas,** the **water gardens,** and the **Schultz House Cottage Garden.** In 1990 a children's playground was added that includes a wood-and-sand playground. HemisFair Park is downtown, adjacent to the convention center. Parking is $8 at 701 Bowie Street. Plan on spending about 2-3 hours at the park. This will give you time to experience the Tower of the Americas, the museum, and the gardens. If you want to include dinner tack on another 90 minutes. #### **WEST** ##### **SeaWorld San Antonio** The home of San Antonio's biggest celebrity is **SeaWorld San Antonio** (10500 SeaWorld Dr., 800/700-7786, www.seaworld.com), the biggest marine theme park in the world. And who might this celebrity be? Shamu, the gentle killer whale. Despite the controversy surrounding killer whales in captivity, the show that features Shamu is still the top-billed act at SeaWorld. With a two-story video screen, seven-million-gallon tank, and 3,800 seats, the show inundates viewers with thrills. Warning to all who like to drink water and not wear it—don't sit in the first 14 rows, where you will get seriously drenched. Shows take place throughout the day. Also at SeaWorld is a beluga show with dolphins and acrobats, the Aquatica water park with wave pool and water chutes, shark aquariums with large viewing windows, bird exhibits, and 100 resident penguins. There is also a large dolphin pool where little ones can feed dolphins. As if this isn't enough, the park also has several roller coasters. I'm not much of a fan of overblown, mega theme parks, especially ones founded by Anheuser-Busch, but the kids _love_ it! There's so much going on here that I highly suggest going online before your visit to help determine what you want to see. Also, plan on bringing swimsuits and a change of clothes because you will probably get wet. Hours fluctuate but generally are 10am-9pm in the spring and summer months. Ticket prices for day passes to SeaWorld are $55 ages 3-9 and $65 ages 10 and up; day passes to SeaWorld plus Aquatica are $80 ages 3-9 and $90 ages 10 and up. Deals can sometimes be had by buying tickets online. #### **EAST** ##### **Splashtown** A great place for the whole family to cool down in the hot summer months is **Splashtown** (3600 N. I-35, 210/227-1400, www.splashtownsa.com, hours vary, roughly 11am-8pm daily Apr.-Sept., $30 for general admission, $24 for children under 48 inches, $19 after 5pm). This 20-acre water theme park has hydro-related activities for every age, from Kid's Kove to the Wave Pool, from the seven-story Lone Star Luge to Starflight, a double-tube slide into total darkness. After the sun sets Splashtown offers a teen-oriented program that includes movies every Friday night and live Christian bands most Sunday afternoons. Lockers are available for a fee, and parking is free. #### **SOUTH** ##### S **King William Historic District** The amazing little neighborhood just south of downtown called the **King William Historic District** is the one place in town where you can marvel at historic mansions, visit some of San Antonio's best art galleries, and get a bite to eat at one of a few fantastic restaurants. At the end of the 19th century, this little bastion of opulence initially settled by German immigrants was where the rich and notable of San Antonio lived. Today this historic district is still lined with breathtakingly beautiful historic mansions, some set on the banks of the San Antonio River. Most of the mansions are Victorian and colonial revival in style and have well-manicured gardens. If you are curious about what the interior of these mansions looks like, you're in luck. Two of the mansions, the **Guenther House** (205 E. Guenther St., 210/227-1061, www.guentherhouse.com, 7am-3pm daily, free) and the **Edward Steves Homestead Museum** (509 King William St., 210/225-5924, www.saconservation.org, 10am-3:30pm daily, $7.50 adults, $5 seniors and students, children 11 and under free), are open to the public. The King William Historic District is circumscribed by Durango Street, St. Mary's Street, Alamo Street, and the San Antonio River. I recommend starting your day in the King William Historic District with breakfast at the Guenther House followed by a walk in the neighborhood. Plan for about 2-3 hours depending on your love of mansion gawking. ##### S **The Missions** Although San Antonio's history stretches back hundreds of centuries and beyond, the most visible and best-preserved relics from the past are the 18th-century Spanish missions established along the San Antonio River. There are five missions in all: Mission San Antonio de Valero (The Alamo), Mission Concepción, Mission San José, Mission San Juan, and Mission Espada. What's known as the **Mission Trail** historically connected the missions from the northernmost mission, The Alamo, to the southernmost mission, Espada—a distance of just over eight miles. Collectively these missions form the largest concentration of Catholic missions in North America. Established by Franciscan friars to convert the local native population, these missions were first built of stone, wood, and adobe and didn't have walls. Because of tensions between tribes and missionary occupants, stone walls were erected as a form of defense. Native Americans built these beautifully ornate buildings under the direction of craftsmen from Spain, using Spanish colonial architectural style. Today, the missions are surprisingly intact, although walls are crumbling and ornamental details have eroded. Mission San Antonio de Valero (The Alamo) is maintained and operated by the Daughters of the Republic of Texas, while the other four missions are active Roman Catholic parishes run in collaboration with the Archdiocese of San Antonio and the National Park Service. The Mission Trail has become an amazing outdoor attraction in itself. In the past the Mission Trail wasn't really an actual trail in the traditional sense of the word. The San Antonio River Authority (SARA) connected the **Mission Reach Hike and Bike Trail** to the Main Plaza near San Fernando Cathedral all the way down to Mission Espada in the south, making the mission trail a fun adventure by bike. Large portions of the trail are along the beautiful San Antonio River, which makes exploring the missions via bike or by foot very enjoyable. Although signage on roads helps cars and bikes navigate the trails and roads that make up the trail, it is a good idea to download a copy of the map at www.visitsanantonio.com. Be sure to bring snacks and water, as there aren't any stores to speak of along the trail. If you don't have the time or energy for the hike-and-bike trail, you can easily explore all the missions in a long afternoon via auto. Here's what I recommend: Do The Alamo separately, and then tackle the other four missions. There's a distance of about three miles between all the missions (excluding The Alamo), so travel time is quick, unless you get lost. From downtown, drive south on South St. Mary's Street to Mission Road, where you will land at Mission Concepción. Then take Mission Road south to Mission San José. Just outside the mission is a comprehensive visitors center with video presentations, exhibits, maps (the confusing one I mentioned), and artifacts from all the missions. Then exit the mission on Napier Avenue and head south on Mission Parkway, which will connect you to Mission San Juan and the farthest of the missions, Mission Espada. Visiting the missions is free of charge, and all are open 9am-5pm daily except Thanksgiving Day, Christmas Day, and New Year's Day. For more information contact the National Park Service's **mission headquarters** (210/534-8833, www.nps.gov/saan) or the **visitors center** (6701 San José Dr., 210/932-1001, free). Determining how much time the missions will take depends on the type of experience you want. If you walk or bike the trail and visit all the missions at a slow pace, plan on packing a lunch and snack because this can easily be a daylong adventure. If don't have a whole lot of time and want to sample the best missions via car, plan on allocating 2-3 hours. **The Legend of the Haunting Children** On the south side of San Antonio, in the vicinity of the Blue Star Arts Complex, there's a set of railroad tracks that are believed to be haunted. The story is that a bus full of children stalled on the railroad tracks and was hit by a train. All the children supposedly died. Although there is no record of this incident, people believe children haunt the tracks, especially at one crossing. Supposedly, if you go at night (especially Halloween), put baby powder on the trunk of your car, and put your car in neutral on the tracks, your car will be pushed by the ghosts of the kids. Their fingerprints are often seen in the baby powder. Local residents are tired of people stopping on the tracks and doing the baby powder test, so I won't disclose the location of this crossing. Just know that there may be the ghosts of children in the area. ##### **Mission Concepción** Transferred to its present location in 1731, **Mission Concepción** (807 Mission Rd.) is the largest of the missions. This mission served as the headquarters for all the San Antonio missions. At one time the facade of the mission church was adorned with elaborate, colorful frescoes and detailed artistry that has faded over time. Inside the sanctuary, remnants of this colorful past are still to be found. Some of the religious paintings on the walls contain a blend of Christian, Spanish, and native influences, and they reveal how the missionaries used traditional native and religious imagery in their Christian context, in order to convey Christian teachings. Mission Concepción ##### **Mission San José** Founded by Franciscan missionary Father Antonio Margila de Jesús in 1720, **Mission San José** (6701 San José Dr.) became the best known of the Texas missions. The colonial baroque architecture of the limestone mission church exceeded that of the other missions, as did its capacity as a social center. These combined to help the mission earn the name Queen of the Missions. Once the founding ceremonies for the mission took place, leaders of three Native American tribes were appointed governor, judge, and sheriff of the mission community, and mission inhabitants learned to use firearms to defend themselves against the Apache and Comanche. At its height, the mission housed over 350 neophyte Native Americans; had an efficient aqueduct system for irrigation, a Spanish colonial flour mill, and a granary; there were also maintained fields and herds of livestock. In 1824 it ceased to be a mission. ##### **Mission San Juan** Founded in 1716 in eastern Texas, **Mission San Juan** (9101 Graf Rd.) was transferred to its present location in 1731. San Juan eventually became a major regional supplier of produce. Outside the mission walls, orchards and gardens produced melons, grapes, sweet potatoes, beans, and even sugarcane. Within the mission walls Native American artisans produced cloth, iron tools, and other items for daily life. These products supported all the San Antonio missions as well as nearby settlements, and trade was established with surrounding states and throughout Mexico. ##### **Mission Espada** Founded in 1690 near present-day Weches, Texas, **Mission Espada** (10040 Espada Rd.) was the first mission in Texas. The mission was transferred to its present location in 1731 and is now the most remote and southernmost mission of the four. Here Native Americans were taught vocational skills such as carpentry, masonry, blacksmithing, and stonecutting. Mission Espada was the only mission to produce bricks, which were used throughout the region. Some claim these bricks can be found throughout many historical sites in the San Antonio area. The church has a unique entrance topped with a three-bell tower known as an _espadaña._ According to legend, the wooden cross to the left of the main doorway of the church was carried by parishioners in a procession around the compound as they prayed for rain during a time of drought. **Battle of Concepción** Approximately two miles south of downtown San Antonio is the historic Mission Concepción. Founded in 1716, the mission remains one of the oldest and best preserved of all the missions along the San Antonio River. In December 1835, it was the site of an important battle between the Texas colonists and the Mexican Army. The Texas revolution had just begun, and 600 colonists, led by Stephen F. Austin, marched on San Antonio to force the removal of General Cos and his 900 Mexican troops. As the Texans approached San Antonio from the south, Austin sent Jim Bowie ahead with 60 men to scout out the enemy. Bowie camped in the bend along the San Antonio River, a few hundred yards in front of Mission Concepción. The following day, Cos marched out with over 300 infantry and cavalry to surround and crush the Texas force. While lesser men might have considered surrendering, Bowie's inspired leadership led to a Texas victory. He had his men shelter behind the riverbank and prepare for the Mexican onslaught. The cannon fire of the Mexicans went over the Texans' heads and showered them with pecans from the trees along the bank. At each charge, the Texas long rifles fired and caused heavy casualties among the Mexican Army. After four unsuccessful assaults, the Mexicans retreated back to San Antonio, leaving their cannon behind. It was the first significant victory the Texas forces won over the Mexican Army, and it inspired the troops to subsequently attack the city of San Antonio and force the surrender of General Cos. It is remarkable that after all of these years the battlefield (so close to downtown San Antonio) remains virtually unchanged. With just a little imagination a visitor can easily envision the positions of the Mexican Army and the defending Texians and relive the historic battle. Look for the monument marking the place where the Texans suffered their first fatality of the revolution. ### **Entertainment and Events** San Antonio isn't known for having a crazy nightlife scene filled with live music and all-night dancing. This came about probably because at some point the family-oriented city let Austin take the lead for nightlife and entertainment. However, if you're "in the know," you can find some pretty spectacular places to spend a memorable night on the town. For complete listings of what's happening in San Antonio, pick up a free copy of the weekly alternative newspaper, the _San Antonio Current,_ or check out the Weekender section of the local newspaper, the _San Antonio Express-News._ San Antonio is one of the largest cities in the United States, so touring national acts often play here. Two mega entertainment venues host everything from hugely popular rock and country bands to monster-truck extravaganzas to Disney on Ice to all spectator sports. The biggest is the ginormous **Alamodome** (100 Montana St., 210/207-3663, www.alamodome.com), on the east side of I-35 near HemisFair Park. Next up is the **AT &T Center** (1 AT&T Center Pkwy., 210/444-5000, www.attcenter.com), which is home to the San Antonio Spurs and has a maximum capacity of 18,500. Finally, the big music venue downtown is **Sunset Station** (1174 E. Commerce, 210/222-9481, www.sunset-station.com). This entertainment complex is in the original San Antonio train station at HemisFair Park and can host 3,500 people. Tickets for large events can be purchased through **Ticketmaster** (210/224-9600, www.ticketmaster.com). #### **LIVE MUSIC** There's no real entertainment district to speak of in town. All venues for live music are scattered throughout the big city, and many venues double as restaurants and bars. For the most part bands strike up on weekend nights between 9pm and 2am, and cover charges vary. A popular music and food district has sprouted on North St. Mary's Street near Brackenridge Park. This popular hipster area is home to the great music and DJ club **Limelight** (2718 N. St. Mary's St., 210/735-7775, <http://thelimelightsa.com>). Upon entry you may be a tad intimidated by the tattoos and stares at the door, but hang in there as this place is one of the hottest venues in town for indie rock. Shoe gazers, loud amps, and nerd rebellions rattle this place with sometimes mediocre, but often intriguing, talent. Cover usually starts at $5. The other popular venue on North St. Mary's is **Mix Nightclub** (2423 N. St. Mary's St., 210/735-1313, <http://themix-sa.com>). This dive bar has a built-in scene that is alive most weekend nights starting on Thursday night. The beer is pretty cheap and the place is often packed. The best place to catch a great blues, roots, or Americana act is **Sam's Burger Joint** (330 E. Grayson St., 210/223-2830, www.samsburgerjoint.com, $12). Although the name is unassuming, this highly respected venue has a great sound system and a vibrant scene after dark. Local musicians and touring acts showcase their talent while bartenders serve up the best beers on tap. Every town has its legendary music venue. San Antonio's is **Floore's Country Store** (14492 Bandera Rd., north of San Antonio in Helotes, 210/695-8827, www.liveatfloores.com). This "country store" sells nothing but barbecue, beer, and foot-stomping country and rockabilly music. Artists such as Lyle Lovett and Willie Nelson have graced the outdoor stage time and again. Don't expect anything fancy here, just picnic tables in the dirt. A surefire way to have a great time on the town is by catching a DJ session or live jazz big band at **Tucker's Kozy Korner** (1338 E. Houston St., 210/320-2192). Originally opened in 1948 as a burger stand, today this local food and dance spot always provides patrons a memorable night on the town. On Monday nights catch the in-house seven-piece band headed by Jim Cullum, as the group faithfully performs early big-band jazz pieces covering greats such as Benny Goodman, Glenn Miller, and Louis Armstrong. **Leon Springs Dancehall** (24135 I-10 W., 210/698-7070, www.leonspringsdancehall.com) is where you can two-step to a live country band along with hundreds of other folks. This family-friendly dance hall has a massive, 18,000-square-foot wooden floor that's packed Friday and Saturday nights. Cover charge is only $5, making this a great place to take a date for a cheap but memorable night out. Minors are welcome but must be accompanied by an adult. Teen angst is best experienced at the famous **White Rabbit** (2410 N. St. Mary's St., 210/737-2221). Here a younger crowd sweats to indie rock, punk, and hard-core music. The venue is all ages and often there's no cover charge. Buy tickets by phone for a discount. #### **BARS AND CLUBS** Located in the hip Blue Star Arts Complex is the **Blue Star Brewing Company** (1414 S. Alamo, 210/212-5506). This inviting brewpub in the artsy enclave of Southtown is a welcome oasis from the hubbub of downtown. The brews cooked up here are best enjoyed on the large outdoor patio or 2nd-story balcony, where you can watch the artists and businesspeople. Just around the corner from The Alamo is three stories of par-tay at **Bonham Exchange** (411 Bonham St., 210/271-3811). With five bars, some named after heroes of The Alamo, and three dance floors, the Bonham has oodles of space to mingle. Wednesday is college night, also known as straight night. The rest of the week it's a popular gay hangout. Yes, the missions are old, but **The Esquire** (155 E. Commerce St., 210/222-2521) is old too. This bar is a San Antonio institution that has been around since 1933, the year Prohibition ended. Okay, so it closed for four years and was renovated, but the ancient long bar remains the main attraction. This historic saloon, which houses the second-longest wooden bar in Texas, is the oldest continuously running watering hole in the state (except for those four years I mentioned). There's a whopping 91 feet of stools, bar, and locals leaning up against it checking out the folks that walk through the door. It can be intimidating drinking a beer in this joint for the first time, because no matter who you are, "you're new in these parts," and you'll get the stare-down. The crowd in here is primarily locals and rough characters who practically live here. The ceiling is stamped copper, the walls are bordello-style, and the waiters sport black shirts and ties. The highest barstool in town is at **Bar 601** (739 E. Cesar E. Chavez Blvd., 210/223-3101). Located at the top of the Tower of the Americas, this classy bar with a view isn't for those who pinch pennies or have vertigo. A great spot to stop off after an evening walk in the King William Historic District is **La Tuna** (100 Probandt St., 210/212-5727). This ice house has an inviting atmosphere fit for the whole family. Drinking a beer at one of the outside tables in late spring is a popular way to be in denial about the forthcoming heat. Next door to The Alamo is a bar rich in history called the **Menger Bar** (204 Alamo Plaza, 210/223-4361), attached to the famous (and haunted) Menger Hotel. A replica of the House of Lords Pub in London, this small, dimly lit room covered in rich cherrywood is the perfect place to sit in a dark corner and have a drink. As you sit and sip, ponder how this pub was the location where Teddy Roosevelt recruited some of his Rough Riders. Who knows—maybe you'll see his ghost if you have enough drinks. For a modern spin on the Brat Pack approach to booze there's **Swig Martini Bar** (111 W. Crockett St. #2205, 210/476-0005). This martini bar is all about cocktails, cigars, and live music. Guys, you gotta have a collar on your shirt to not stand out here, and gals, you gotta be in pumps. With a patio overlooking the River Walk, the best selection of martinis in town, and live jazz bands to set the tone, this place is a class act. **The Tejano Accordion** The accordion is a 19th-century European instrument. So how did it become an integral part of Mexican music? It happened right here in Central Texas. The unusual instrument was patented in 1829 in Vienna. Only a few years later German pioneers headed out to the New World, ended up in Texas, and quickly established many of the Hill Country towns, such New Braunfels, Gruene, Boerne, and Comfort. They brought with them sauerkraut, schnitzel, and a strange new musical invention: the squeezebox. As the German and Mexican cultures mingled, a new style of music was pioneered. The final product was an accordion-based, Tex-Mex music that blended traditional Mexican forms such as the _corrido_ with European waltz and polka. San Antonio was the biggest city in the region and quickly became the experimental ground for this new music style called both **Tejano** and **conjunto.** In recent years it has adopted strong influences from rock, blues, and _cumbia,_ and is now not just regional ethnic music, but its own genre with wide appeal. #### **PERFORMING ARTS AND THEATERS** San Antonio has a slew of small performing-arts groups, as well as some more-established companies that keep the local performing-arts scene eclectic, entertaining, and cutting edge. The main performing-arts company in the arena of music is the nationally recognized **San Antonio Symphony** (210/223-8624, www.sasymphony.org). Most performances are held at newly renovated Majestic Theatre (224 E. Houston St., 210/226-3333, www.majesticempire.com). Classical music filling the extraordinarily ornate halls of the Majestic can be a breathtaking experience. When it comes to theater, San Antonio takes pride in having a handful of performing-arts companies. Most theatrical performances take place at one of several venues. The city's beloved **Majestic Theatre** (224 E. Houston St., 210/226-3333, www.majesticempire.com) is considered one of the most ornate theaters in the country, and its history alone seems to add to any drama. Built in the 1920s, this grand stage has been the center of the performing arts in San Antonio for decades. Today you can catch major Broadway productions as well as the San Antonio Symphony. The Majestic's sister theater is the **Empire Theatre** (226 N. St. Mary's St., 210/226-5700, www.majesticempire.com). This old opera house built in 1914 now puts on shows and performances of all kinds. The Trinity University campus is home to **Laurie Auditorium** (715 Stadium Dr., 210/999-8117). It's not possible to pin down all that happens in this performing-arts auditorium. People come here to see comics like Jay Leno as well as jazz concerts, and world-renowned lecturers speak to packed audiences on all topics imaginable. San Antonio's cutting-edge shows are put on at **Jump-Start** (108 Blue Star Complex, 210/227-5867, www.jump-start.org). This unique company focuses entirely on new creations that are dreamed up by local artists and writers. Most of what you'll see here is very avant-garde—and it all appropriately takes place on a stage in an old warehouse. Located downtown on the River Walk at historic La Villita is **Arneson River Theatre** (418 Villita St., 210/207-8610, www.lavillita.com). This well-designed outdoor amphitheater is in a spectacular setting. The San Antonio River separates the stage from the audience, who sit on cleverly designed stone seats that are filled with patches of grass for comfort. Arneson River Theatre #### **CINEMAS** For the magic and clarity of IMAX, there's **San Antonio IMAX Theatre** (849 E. Commerce St., 888/262-4386). Along with the usual movies Hollywood pumps out, this theater also screens those dramatic movies that make IMAX so famous. The one everyone has to see here is _Alamo, The Price of Freedom._ The theater is on the first level of Rivercenter Mall. Three hours of parking is free at the Rivercenter Mall with the purchase of an IMAX ticket. #### **COMEDY CLUBS** The one outlet for live laughs is **Rivercenter Comedy Club** (849 E. Commerce St., Ste. 893, at the Rivercenter Mall, 210/229-1420). Big-name acts come through here, such as Dennis Miller and comedians from Comedy Central and HBO. Local talent is also appreciated, especially during Comedy Potpourri on Monday. A night here can be complemented by dinner and drinks, as the club has a full kitchen and bar. Doors open at 4pm and shows begin at 8pm. Headliner shows are Wednesday-Sunday. Tickets can cost anywhere from $8 to $12 depending on the night of the week and the comedian or act. #### **FESTIVALS AND EVENTS** ##### **January** The yearly maintenance of the San Antonio River has turned into a filthy festival, the **River Walk Mud Festival** (210/227-4262). When the river is drained, a king and queen of mud are elected to preside over events that include music, games, and festivities related to mud. ##### **February** Every February the SBC Center is taken over for the 16-day **San Antonio Stock Show and Rodeo** (210/255-5851, www.sarodeo.com). See live music, livestock, and daring cowboys riding raging bulls. The week before Ash Wednesday, just before Lent, the River Walk features **Mardi Gras** (210/227-4262). Buy or browse arts and crafts made by local artists and artisans for an entire week. The end of the week is marked by the **Mardi Gras River Parade.** Watch a procession of decorated river barges transform the San Antonio River. Costumed revelers and live entertainment celebrate Mardi Gras San Antonio-style. ##### **March** **St. Patrick's Day** in San Antonio is celebrated with barrels of green dye and even more barrels of beer. As floats pour environmentally friendly green dye into the San Antonio River, the river is renamed "the River Shannon." This is followed by the St. Patrick's Day Parade, which in turn is followed by mass consumption of beer. An estimated 15,000 people flood the River Walk for the event. **Contemporary Art Month** (210/222-2787, www.contemporaryartmonth.com) is a monthlong contemporary arts festival—the only one in the nation. With more than 400 exhibitions taking place in more than 50 venues, such as galleries, museums, and studios, this celebration offers an amazing look at what's happening in the art world of San Antonio. ##### **April** The most spectacular festival of all is **Fiesta San Antonio** (www.fiesta-sa.org). For 10 days in April San Antonio has a party similar to New Orleans's Mardi Gras. The citywide celebration includes carnivals, sports, fireworks, entertainment, feasts, art exhibits, and parades that float down the San Antonio River. In the past the fiesta has attracted some three million participants and spectators from around the nation. The first Fiesta San Antonio event was back in 1891, which included a parade called the Battle of Flowers, honoring the heroes of Texas history. ##### **May** **Tejano Conjunto Festival** (210/271-3151, www.guadalupeculturalarts.org) is San Antonio's way of celebrating the unique form of music that developed in South Texas with both German and Mexican roots. The three-day festival features live performances from top conjunto and Tejano artists, all in Rosedale Park and on the Guadalupe Cultural Arts Center campus. ##### **June** **Texas Folklife Festival** (210/458-2300, www.texasfolklifefestival.org) is an annual four-day celebration of the diverse group of folks who settled Texas. Some 45 groups bring their cultures to the Institute of Texan Cultures. Everyone celebrates unity through diversity with crafts, music, dances, and foods. The most important celebration for African Americans of Texas is **Juneteenth** (www.juneteenthsanantonio.com). June 19, 1865, marked the day that Texas slaves received word of the Emancipation Proclamation. Observances include a picnic, jazz concerts, a parade, and other cultural festivities honoring the first step toward freedom for blacks. ##### **September** Marking Mexico's independence from Spain is **Diez y Seis** (800/447-3372, www.sanantoniovisit.com). Every September 16, San Antonio celebrates with a street parade with floats, marching bands, celebrations at Market Square and La Villita, and other activities. Jazz lovers from all over converge in San Antonio for **Jazz'SAlive** (210/212-8423). For two days the nation's top jazz entertainers, along with regional talent, perform in Travis Park. ##### **October** Connect with your loved ones who have passed on by celebrating **El Día de los Muertos**. Translated as Day of the Dead, this important and ancient celebration in Mexican culture is a ritual in which the family welcomes back departed loved ones. ##### **November** **Wurstfest** is a 10-day salute to sausage. You'll find a variety of entertainment options including a polka contest, games, rides, food, and drinks on the Wurstfest Grounds in Landa Park. ### **Shopping** San Antonio isn't necessarily a shopping town, but it does have a few interesting shops with local flavor that are worth checking out. Mexican markets, massive malls, funky galleries, and a few boutique shops are what's to be expected here. The markets are particularly interesting, especially for the first-time visitor to Texas and/or San Antonio. Although there are some shops downtown and on the River Walk, most of the interesting shops are spread out throughout town. Just south of downtown is the burgeoning San Antonio Arts District, also known as Southtown. A few boutiques and art galleries can be found on South Alamo Street. Shops are generally open 10am-6pm daily. The majority of major chain retail shops in downtown are located in **Rivercenter Mall** (849 E. Commerce, 210/225-0000, www.shoprivercenter.com, 10am-9pm Mon.-Sat., noon-6pm Sun.). This four-level shopping complex has more than 100 retailers, including restaurants and an AMC movie theater, all under one roof. The scene inside is stunning, as there are picturesque views of the River Walk below. The most interesting independently owned shops are in historic **La Villita** (418 Villita St., 210/207-8610, www.lavillita.com, shops open 10am-6pm daily). Here you'll find arts and crafts, souvenirs, upscale gifts and home decor, and art from all genres and media. Many of these shops are inside historic buildings from San Antonio's early days. The largest Mexican marketplace outside of Mexico is at **Market Square** (between Dolorosa and Commerce just west of downtown, 210/207-8600, 10am-8pm daily June-Aug., 10am-6pm daily Sept.-May). This entire city block of all things Mexico was originally an open-air market founded in 1840. Today Market Square is a little city unto itself, with great restaurants like Mi Tierra and La Margarita, outdoor courtyards, and covered malls that feature unique retail shops and purveyors of imports such as tin lamps, jewelry, knickknacks, Mexican papier-mâché, sombreros, handmade Mexican dolls, religious kitsch, and the popular Davy Crockett coonskin hats. Outside the market in the beautiful courtyards, local musicians perform and celebrations take place. **Council House Fight** As you stroll around Market Square in downtown San Antonio and admire San Fernando Cathedral, keep in mind that in March of 1840 a major Native American battle known as the Council House Fight took place here. A group of 65 Comanche (including 12 chiefs) came to town to negotiate a peace treaty with the Texans. The Native Americans had promised to bring with them all of their white captives as a sign of good faith. Unfortunately for them, they only brought one white captive, a 15-year-old girl named Matilda Lockhart. The Texans were put in a bad mood when they saw that Matilda's nose had been burned off by the Comanche. Then Matilda informed the Texans that there were numerous other captives and that it was the Comanche's intention to bargain for their release separately. The meeting took place in a one-story stone building on the east side of the square at Market Street. Colonel William Fisher was in charge of the Texan forces and marched a company of troops into the council room. He informed the Indians that their chiefs would be held hostage until they brought in all of the white prisoners. The Comanche chiefs refused to be held prisoner and fighting erupted. A bloody fight to the death occurred inside the council house with knives, guns, and bows and arrows. At the end of the struggle, all of the Comanche chiefs and warriors were killed. Seven Texans died in the struggle and eight were wounded. Twenty-seven Comanche women and children were captured and held hostage. Seven white captives were finally returned to the Texans in exchange for the Comanche hostages. The aftermath of the Council House Fight led to the greatest Comanche raid in the history of Texas. Late in May of 1840, over 600 Comanche (encouraged and guided by representatives of the Mexican government) raided the towns of Victoria and Linnville on the Gulf Coast. Linnville was burned to the ground and plundered, and many captives were taken by the Comanche. As the Native Americans tried to retreat to their Hill Country campgrounds, they were attacked by Texan forces at the Battle of Plum Creek, near present-day Lockhart. The Comanche suffered a stunning defeat. Subsequent attacks by the Texan forces followed the Comanche into the upper reaches of the Colorado River valley. There the Comanche suffered a string of defeats that weakened their power so much that they never again made such an attack in force against a Texas town. #### **CLOTHES, SHOES, AND ACCESSORIES** The craft, tradition, and art form of bootmaking has been upheld by two legendary boot companies based in San Antonio. In **Little's Boots** (110 Division St., 210/923-2221, 9am-5pm Tues.-Fri., 9am-1pm Sat.), a one-of-a-kind shop operating since 1915, prepare to stomp your feet with excitement over all the beautiful and ornate boots. Western footwear made from crocodile, alligator, kangaroo, eel, ostrich, and even lizard is sure to impress the imagination. Be sure to check out the custom and handcrafted boots here. They are great works of art in their own right. The other bootmaker in town is **Lucchese** (255 E. Basse Rd., 210/828-9419, 10am-7pm Mon.-Fri., 10am-6pm Sat., noon-5pm Sun.). Here you'll find high quality, precision craftsmanship, and class for the cowboy or cowgirl who enjoys getting gussied up. **Paris Hatters** (119 N. Broadway, 210/223-3453, 9:30am-6:30pm Mon.-Sat., 11am-5pm Sun.) is yet another historic business in San Antonio. Family owned and operated since 1917, this headgear shop has a large variety of new hats ranging from the iconic Stetson to Kangol to cowhide baseball caps. Although there is a large collection of hats in the store, this boutique specializes in custom headwear for those who have the money. #### **MUSIC** Swim through a vast sea of new and used CDs at the **CD Exchange** (3703 Broadway St., 210/828-5525, 10am-9pm Mon.-Sat., noon-7pm Sun.). Everything is relatively cheap and in abundance. Here you can also find those rare 1980s movies you've been searching for on DVD and VHS. For the vinyl aficionado, music purist, and counterculture hipster, **Hogwild Records, Tapes and CDs** (1824 N. Main Ave., 210/733-5354, 10am-9pm Mon.-Sat., noon-8pm Sun.) has an astounding collection of great records and tapes. This is also an outlet in town for underground press and literature. #### **BOOKSTORES** If you're in the mood for strolling around a bookstore, take a short trip up Broadway to **Half Price Books** (3207 Broadway, 210/822-4597, www.halfpricebooks.com, 9:30am-9pm daily), an emporium of cheap used books and a strange array of records. A great resource for Texana and regional books and literature is **The Twig Book Shop** (306 Pearl Pkwy., Ste. 106, 210/826-6411, 9:30am-6pm daily). Inside the Twig is a great children's bookstore called **The Red Balloon.** Books for all ages, from babies to tots to teens, are here. They also have children's book readings, which is great for parents and children. #### **ART GALLERIES** Perhaps the most innovative and noteworthy gallery in town is **ArtPace** (445 N. Main Ave., 210/212-4900). Hours vary depending on the ever-revolving door of artists and exhibits. This purely conceptual gallery puts a fresh twist on the idea of the art gallery, as it brings in artists from around the world, gives them a place to live above the gallery space, provides art supplies, and lets them go crazy. The stuff produced here is generally wildly bizarre but always amusing and thought provoking. The beating heart of contemporary Southtown is the **Blue Star Arts Complex** (between the San Antonio River and S. Alamo St., www.bluestarart.org). This abandoned industrial warehouse was brilliantly converted into spaces and galleries for local artists, and has become San Antonio's repository for contemporary arts. If you're in the market for cutting-edge and unique art in all media—painting, sculpture, and performing arts—you'll find it here. Gallery spaces and showings are at random times, but chances are, if you show up sometime in the afternoon something will be open. Galleries include **San Angel Folk Art** and **Joan Grona Gallery.** Art is to be appreciated and sometimes even worn. At the Gallery Shop of the **Southwest School of Art and Craft** (Ursuline Campus, 300 Augusta St., 210/224-1848, 10am-5pm Mon.-Sat.) you'll find an interesting collection of one-of-a-kind works of art made by students. Expect to find color, innovation, and flat-out strange stuff in here. ### **Recreation** For those looking for fun, the most popular activities are golf, spectator sports, and, of course, visits to the city's massive theme parks. There's not much in the way of outdoor recreation in San Antonio. For hiking, biking, rock climbing, and swimming, most people head out into the Hill Country. #### **HIKING AND BIKING** Perhaps the most convenient place to hike and bike is the **Mission Trail** (6701 San José Dr., 210/932-1001, www.nps.gov/saan). The trails that link some of the missions are, for the most part, scenic. However, some lengths of the trail cut through run-down urban areas that aren't too scenic. The only other place for outdoor activities in the San Antonio metropolitan area is **Brackenridge Park** (3910 N. St. Mary's St., 210/207-7275, 5am-11pm daily, free). Don't expect any dirt trails for hiking or mountain biking, though, as this park is primarily for families who want to picnic and walk a paved trail near the river. On the outskirts of town is beautiful **McAllister Park** (13102 Jones Maltsberger Rd., 210/207-7275, 5am-11pm daily, free). This wooded area 12 miles north of downtown is the best place to get away from the city and hike or bike in semi-seclusion. Lastly there's **Friedrich Wilderness Park** (21395 Milsa Dr., 210/207-7275, 5am-11pm daily, free), which offers 5.5 miles of trails for hiking. #### **GOLF** What San Antonio lacks in hiking and biking opportunities is made up for by several world-class golf courses. The favorite resort-golf mecca is **La Cantera Golf Club and Resort** (16401 La Cantera Pkwy., 800/446-5387). The two top-notch courses on the resort grounds are both classic Hill Country layouts. One overlooks Six Flags Fiesta Texas. One of Texas's best municipal golf courses is **Cedar Creek Municipal Golf Course** (8250 Vista Colina, 210/695-5050). Considered by some to be the poor man's La Cantera, Cedar Creek can get very crowded, so patience and a tee time are absolutely necessary. Lastly there's beautiful **Canyon Springs Golf Course** (24400 Canyon Golf Rd., 210/497-1770). No setting in golf is better than the approach to the signature 17th green and its waterfall backdrop. #### **SPECTATOR SPORTS** San Antonio's only major-league franchise is the ever-popular **San Antonio Spurs** (www.nba.com/spurs). This team has fought its way up the National Basketball Association food chain and has been the NBA champion five times (1999, 2003, 2005, 2007, and 2014). The season is October-May, and home games are played in the **AT &T Center.** Tickets can cost anywhere from $25 to $70, and can be purchased at the AT&T Ticket Office (1 AT&T Center Pkwy., 210/444-5819) or through Ticketmaster (210/224-9600, www.ticketmaster.com). Another popular spectator sport is **drag racing.** The venue for this rubber-smoking speed sport is the **San Antonio Raceway** (3641 S. Santa Clara Rd., 210/698-2310, www.sanantonioraceway.com). There's also a minor-league baseball team, the **San Antonio Missions** (210/675-7275, www.samissions.com), whose season is April-September. Games are played at **Nelson Wolff Stadium** (5757 Hwy. 90 W., 210/675-7275). San Antonio's megavenue is the **Alamodome** (100 Montana St., 800/884-3663, www.alamodome.com), which showcases anything from bull riding to football to the Texas Hunters Extravaganza. One of the most distinctive experiences in San Antonio is spending the day at the **_charreada,_** or Mexican rodeo (6126 Padre Dr., 210/846-8757, Mar.-Oct., $10, children 12 and under free). _Charreada_ is similar in many ways to American rodeo, but with a distinct Latin flair and showmanship. Among many _suertes_ (events) are _colas en lienzo_ (bull tailing), where a rider grabs the tail of a running bull, wraps it around his leg, and pulls the bull to the ground, and _paso de muerte_ (pass of death), where a rider jumps from his galloping horse onto the back of a galloping wild horse and rides it until it stops bucking. For more than 50 years the San Antonio Charro Association has been keeping this old-world sport alive, dazzling audiences with high-stakes horsemanship, daring bull roping, and live mariachi bands. Events are held at the association's ranch, which overlooks the San Antonio River. #### **TOURS** Touring the downtown stretch of the San Antonio River by boat is a hoot. Tours are offered by **Rio San Antonio Cruises** (210/244-5700, www.riosanantonio.com). There are three ticket and boarding locations along the River Walk: Holiday Inn River Walk, Rivercenter Mall, and Market Street Bridge. The tour takes passengers on a 2.6-mile excursion along the river in an open, flat-bottom barge. Tours last about 40 minutes and cost $8.25. If you get an experienced tour guide who incessantly shoots out facts and anecdotes about history, famous people, and infamous events, the touristy ride can be quite entertaining. If you prefer to take a ride without the monologue, Rio offers a river taxi service that has 39 stops along the river. Taxi stops are marked by Rio Trans signs along the River Walk. One-way rate is $5, a day pass is $10, and a three-day pass is $25. ### **Food** San Antonio's proximity to the Mexican border and its rich Latino history make this one of the best places for Tex-Mex and Mexican food. Even restaurants that aren't billed as Mexican offer enchiladas at the very least. When it comes to Mexican food, expect guacamole prepared tableside, margaritas, breakfast tacos, live mariachi music, handmade tortillas, and some gringo-Mex variations of all the above, all at great prices. If you are one of those few people in the world who don't like Mexican, or just want to try something different, there are lots of other eateries to choose from. Fabulous restaurants are scattered all throughout town, but many are in the downtown area. The River Walk is a popular place to eat for both locals and tourists, as the atmosphere is remarkably serene and alluring. The narrow winding paths along the river are lined with umbrella tables and charming eateries that are packed from spring to fall. There's also a slew of very popular restaurants that have popped up in burgeoning Southtown, along South Alamo Street. These special eateries, rich with character and bubbling with action, are favorite spots for hip locals and tourists in the know. #### **AMERICAN** A local favorite for brunch is **Madhatters** (320 Beauregard St. at S. Alamo St., 210/212-4832, 7am-9pm Mon.-Fri., 8am-9pm Sat., 9am-3pm Sun., $9). With a creative selection of sandwiches and salads, all made with breads baked in-house, as well as French toast and other breakfast items, Madhatters is the perfect place to relax in the King William Historic District. In spirit with _Alice in Wonderland,_ they also offer a large selection of fabulous teas under the trees. The best place to catch a great blues, roots, or Americana act and a burger is at **Sam's Burger Joint** (330 E. Grayson St., 210/223-2830, www.samsburgerjoint.com, $12). By day this place is a great burger joint with an upbeat atmosphere, and by night Sam's turns into a vibrant music scene. The cooks serve up top-notch food, such as the guacamole and jack burger, and bartenders serve up the best beers on tap. **The Invention of Fritos Chips** Legend has it that the tasty snack food known as Fritos Corn Chips was invented in San Antonio in the early 1900s. At the time, the city's Mexican restaurants were in the custom of frying up the day-old tortillas and selling them. One establishment that was peddling these recycled corn snacks was the Santa Rosa Macaroni Factory, which was owned by a distinguished Italian immigrant named Carmelo Ruffo. Some say it was a Mexican immigrant who created and sold the original recipe, but others say it was Ruffo, whose tantalizing day-old fried "Fritos" were made with his macaroni press. One day Ruffo was approached by an entrepreneur named Elmer Doolin, who offered Ruffo $100 for his fried chip recipe and the macaroni machine. Carmelo walked away with the $100 thinking to himself, "Who would buy those chips when everyone in town is making them already?" Well, the rest of the country bought into the idea and to this day munchers are suckered into paying for the unique taste of Fritos chips. One of San Antonio's best eating experiences can be had in the Pearl District at **Southerleigh Fine Food and Brewery** (136 E. Grayson St. #120, 210/455-5701, $15). The atmosphere is great here, as there is a lot to look at while you sip on one of their fine beers. The food is innovative and the décor is modern-retro. The cuisine is hailed as a modern take on Texas' cross-culture cuisine. Although it's a chain, albeit a small Texas chain, **The County Line** (111 W. Crockett St., 210/229-1941, $14) has some of the best barbecue in the downtown area. Beef brisket is moist and smoldering with flavor, and comes with the boilerplate smokehouse sides of potato salad, beans, and coleslaw. American, '50s-style _Leave It to Beaver_ home cooking is served up at **410 Diner** (8315 Broadway St., 210/822-6246, 11am-9pm Sun.-Thurs., 11am-10pm Fri., $8). This true diner is where you'll find meat loaf and vegetables, along with a few attempts at upscale menu items, such as snapper with artichoke hearts. Its proximity to the airport makes it a great stop before an evening flight out of town. The historic **Guenther House** (205 E. Guenther St., 210/227-1061, 7am-3pm daily, $7) offers high-society class at a great value. For under $10 one can have a fabulous meal in a mansion overlooking the San Antonio River, in the King William Historic District. The smell of breakfast with fresh baked goods wafting through the mansion's Victorian-style parlors is what keeps a steady fan base coming back. And it tastes as good as it smells. Patrons are generally older folks, but youngsters shouldn't be scared to claim this for their own. While there, be sure to take a tour of the gift shop and the historic Guenther House. The best place for lunch and a cocktail is S **Liberty Bar** (1111 S. Alamo St., 210/227-1187, 11am-10:30pm Sun.-Thurs., 10:30am-midnight Fri.-Sat., $12). With interesting food, house-baked breads, and one-of-a-kind ambience, Liberty is a bona fide San Antonio legend. Although it has moved from its previous location, which was a building that was near collapsing, the style and eating experience have not changed. If you want to impress someone, or yourself for that matter, have a classy lunch or dinner in this former convent. Crab cakes, a New York strip, or a portobello sandwich go with your choice of wine. Afterwards, a stroll through the King William Historic District seems like a given. North of town in Alamo Heights is **Olmos Pharmacy** (3902 McCollough, 210/822-1188, 4pm-midnight Mon.-Fri., 4pm-1am Sat., 10am-midnight Sun., $7), an old-style pharmacy serving up medicine in the form of milk shakes and burgers. Founded in 1938, this neighborhood fountain makes a mean root beer float at a price that hasn't changed in 30 years. Also consider the mashed sweet potatoes, which have a sweetness that melts in the mouth. If after a trip to the zoo you are craving a smokehouse dinner, up in the Brackenridge Park area is S **Augie's Barbed Wire Smokehouse** (3709 N. St. Mary's St., 210/735-0088, 11am-3pm Mon.-Tues., 11am-9pm Wed.-Fri., noon-9pm Sat., noon-6pm Sun., $10). I'm not implying that the zoo may trigger in you the desire to dine on endangered animals. However, one of the three square meals in Texas is barbecue. As at all excellent barbecue pits, the brisket and pulled pork are the best items on the menu, assuming you get there before they run out, which does happen. Nothing beats a deli sandwich for lunch, and nobody beats the classic yet upscale fixin's at **Schilo's Delicatessen** (424 E. Commerce St., 210/223-6692, 7:30am-7:30pm Mon.-Sat., $12). The interior of Schilo's (pronounced "SHEE-lows") is best described as caravan meets an Italian meat wagon. The food is remarkably tasty and summons authentic visions of German pioneers who settled in South Texas and transplanted their food heritage. Here you build your own sandwich, and between the slices of bread expect only the very best in sandwich craftsmanship. Be sure to try the homemade root beer. #### **MEXICAN, TEX-MEX, AND SOUTHWESTERN** Walk into S **Acenar** (146 E. Houston St., 210/222-2362, 11am-10pm Sun.-Thurs., 11am-11pm Fri.-Sat., 5pm-9pm Sun., $12) and let yourself be overwhelmed by the bright colors and delectable foods. The sophisticated menu is upscale and creative, and not traditional Mexican, which is refreshing. Be sure to ask for their famous guacamole made tableside. It's the best I've ever had. If it's not too hot, eat outside on the porch above the River Walk, and you're guaranteed to have one of those "life is good" moments. Caribbean and Latin American cuisine has been skillfully brought to the King William Historic District by **Azúca** (713 S. Alamo, 210/225-5550, 11am-9:30pm Mon.-Thurs., 11am-10:30pm Fri.-Sat., 5pm-9:30pm Sun., $18). This hip bar and restaurant is known for making potent mojitos and well-crafted meat dishes. On weekend nights Azúca is the place in town for live tango, salsa, and flamenco music and dancing. On the River Walk is upscale S **Boudro's** (421 E. Commerce St., 210/224-8484, 11am-11pm Sun.-Thurs., 11am-midnight Fri.-Sat., $15). This eatery on the river boasts a crafty menu, fancy drinks, fine wines, and high-caliber service. And what about that crafty menu? Try lamb T-bone with basil-lemon-mint sauce, grilled Gulf Coast yellowfin tuna, or whiskey-soaked bread pudding and you'll know what I mean. Boudro's is one of the best places to have a great lunch or dinner on the River Walk. Locals love how **El Mirador** (722 S. St. Mary's St., 210/225-9444, 6:30am-9pm Mon.-Thurs., 6:30am-10pm Fri.-Sat., 9am-2pm Sun., $9) cooks up traditional Mexican dishes with flair. Although the whole menu is above par, the main dish people rave about here is _sopa Azteca_ (Aztec soup). Tables fill up quickly, so either arrive before the mealtime rush or prepare to wait. Believe me, the wait is well worth it. One of San Antonio's most time-tested Mexican institutions is **La Fonda on Main** (2415 N. Main Ave., 210/733-0621, 11am-3pm and 5pm-9:30pm Mon.-Thurs., 11am-10:30pm Fri.-Sat., $9). Since 1932, Mexican food has been the reason people flock here. Today the menu is a combination of regional Mexican and Tex-Mex, offering standards such as chicken enchiladas and new creations such as spinach enchiladas, shrimp with butter squash, and smoky tenderloin. The bright and cheerful environment with outdoor patio seating makes La Fonda a popular meeting place for lunch and dinner. S **Mi Tierra** (218 Produce Row, 210/225-1262, 24 hours daily, $9) is the local institution that serves great Mexican food 24 hours a day. All dishes are made up of beans, meats, sauces, and handmade tortillas—the staples of Mexican food. The food is okay but gets better at around 3am, when you're desperate and hungry. The old building is festively decorated with strings of lights and tinsel, and a mariachi band often strolls around the tables. Sit beneath masterfully executed murals telling the story of Mexico and Texas (notice that the breasts and noses are strangely three dimensional), and lose yourself in enchilada sauce. The best Mexican restaurant is S **Rosario's** (910 S. Alamo St., 210/223-1806, 11am-10pm Mon.-Thurs., 11am-11pm Fri.-Sat., 11am-9pm Sun., $10). The proprietor has combined Mexican food with a chic, semi-retro, totally colorful dining space that makes a frequent customer out of everyone. On weekend nights chairs are removed from a portion of the dining area to make way for the dance floor, and the small stage is fired up with live salsa music. Favorite menu items are _pollo a la maria,_ chile relleno, and prickly-pear margaritas. #### **OTHER INTERNATIONAL FOOD** If you're not quite sure what you want, but you're sure you want a drink to go with it, there's **Cappyccino's** (5003 Broadway, 210/828-6860, 11am-11pm Mon.-Thurs., 11am-midnight Fri.-Sat., $10). Both the food and drink menus are diverse and very enticing. Food items include brick-oven pizza with feta cheese and a thick golden crust, Italian-style deli sandwiches, pita wraps, and crepes. As for liquor, this place is a fan of anything fermented; it has a huge selection of scotches, brews, and martinis, from which you're sure to find just the right beverage to accompany your meal. Texas and sushi don't sound like they go together, but **Koi Kawa** (4051 Broadway, 210/805-8111, 11am-10pm Mon.-Fri., noon-10pm Sat., noon-9pm Sun., $12) has proved all logic wrong. Two great things about this place: The chef is considered the best sushi chef in town, and the dining room affords spectacular views of Brackenridge Park and the San Antonio River. Artfully prepared black-widow rolls, devil rolls, and udon all scream healthy and tasty, and the wasabi just screams. Housed in a converted gas station in Southtown is **La Focaccia** (800 S. Alamo St., 210/223-5353, 11am-2:30pm and 5pm-10pm Mon.-Fri., noon-11pm Sat., noon-10pm Sun., $13). The Italian food here is family-style, with blue-blood heritage. The owner was born in Rome and brought family recipes cooked for Italian royals to San Antonio. Italian favorites such as calzones, lasagna, spaghetti, and pizzas are all worthy of a religious procession around the block. Asian food in Alamo Heights is best eaten at **Van's** (3214 Broadway, 210/828-8449, 11am-10pm daily, $10). The combination of sushi and Chinese is tastefully set forth in a menu that can bring even the most terrified sushi disdainer to his or her senses, literally. Rounding out the experience is a great wine list. Wine and sushi at a good price make this a great low-key pick for dinner with friends. #### **HEALTHY AND VEGETARIAN** San Antonio is a carnivore town. However, there is one safe spot for vegans and vegetarians, and that's **Green Vegetarian Cuisine** (200 E. Grayson St., Ste. 120, 210/320-5865, 7am-9pm Mon.-Fri., 9am-9pm Sun., closed Sat., $10), not far from Brackenridge Park. Healthy-minded folks can start their day here before exploring the museums or zoo. Most everything is organic, healthy, and tasty, and all is kosher too. The menu ranges from omelets to enchiladas. The chik-n fillets are awesome in their own right. #### **FINE DINING** Fine dining in San Antonio doesn't get much better than S **Prime 1718** (321 Alamo Plaza #300, 210/377-1718, 3pm-10pm Mon.-Thurs., 11am-10pm Fri.-Sun., $30). Here you can sample from a fantastic wine list and enjoy the best filet mignon, roast quail, or blackened salmon in town. The food and service is as good as it gets. Many of the tables have a view of The Alamo, which will make your dining experience iconic and memorable. Located inside innovative Hotel Valencia is swank **Citrus** (150 E. Houston St., 210/230-8412, 6:30am-2pm and 6pm-10pm daily, $30-50). For an amazing evening with friends, with a romantic date, or even alone, Citrus proves impeccable and divine. As soon as you are seated the knowledgeable staff makes you feel comfortable with your experience. Thanks to the brilliant selection of wines, the creative but down-to-earth entrées, and the minimalist decor, anyone can feel like a million bucks. Of course you have to have some cash to back it up, because it is expensive. Reservations are recommended. If you are a geek about flavor but fancy yourself a refined individual I recommend fine dining at **Tre Trattoria** (401 S. Alamo, inside the Fairmount Hotel, 210/223-0401, and 4003 Broadway near Brackenridge Park, 210/805-0333, $45-65). Eating here is a serious matter. Men should look dapper and women should primp, and everyone has to be on time and follow the lead of the waitstaff. Although classy it's still a personable place. If you're irritated by pomp you won't enjoy this, but if you're out to enjoy fine wines and masterfully designed entrées in the company of the crème de la crème of society, you will have one of the best fine-dining experiences San Antonio has to offer. Popular among locals with refined style and taste, **Silo** (1133 Austin Hwy., 210/824-8686, 11am-2:30pm and 5:30pm-10pm Sun.-Thurs., 11am-2:30pm and 5:30pm-10:30pm Fri.-Sat., $22) is the eatery that can do no wrong. This converted farmers market has a swank martini bar on the ground floor and a dining room accessed only by elevator. The short but upscale menu includes chicken-fried oysters, seared yellowfin tuna, and chocolate soufflé cake, to name a few options. Reservations are recommended. ### **Accommodations** San Antonio is a huge, sprawling city with accommodations everywhere. The most convenient area to stay for a visitor who plans on seeing sights is obviously downtown. All downtown hotels are within walking distance to most sights, and many are luxury hotels situated right on the banks of the famous River Walk. Rates for all hotels downtown generally start around $139. During the off-season and slow times many of these hotels offer discounts that can dip as low as $100, and deals can often be found online. Although it's almost impossible to find a room in the downtown area that is under $99, deals can be found at chain hotels and motels along the highways, just outside of downtown. #### **UNDER $50** The **Travelodge San Antonio Downtown** (1122 S Laredo St, 210/229-1133, $33) is by far the cheapest place to stay in town, but don't expect much in the way of accommodations other than a bed and bathroom. #### **$50-100** It's almost a joke having a category for $50-100 in San Antonio. Therefore I must give a disclaimer for the following cheap lodgings. Most of them aren't in the classiest and safest areas of town, and their rooms aren't particularly nice. As for amenities, expect nothing but some sheets, a small bar of soap, and maybe some lousy coffee. For affordability with some class **Hotel Indigo** (105 N Alamo St., 210/933-2000, $89-150) offers the most basic accommodations in town near The Alamo. The River Walk is just a couple blocks away. If you desire nothing but a bed, a TV, and an exceptionally low rate there's **Red Roof + San Antonio Downtown** (1011 E. Houston St., 210/229-9973 or 800/733-7663, $55-119). It's right off I-35, so expect some highway noise. There are a few exceptions in this price range. A place that has yet to be discovered by the masses of budget travelers is **La Quinta Inn & Suites San Antonio Downtown** (100 W. Cesar Chavez Blvd., 210/212-5400, $89-139). Your money can go a long way here. The rooms are spacious and clean, there's a pool for splashing around in, and the complimentary breakfast is a real breakfast with eggs and waffles. The location may not be in the River Walk, but it's still centrally located. Another affordable place to stay near all the River Walk action is the **O'Brien Historic Hotel** (116 Navarro St., 210/527-1111, $93-130). The O'Brien has the charm of being in an old building and is a step above the cheaper hotels in the price range. However, keep in mind that you get what you pay for. Nothing is superfancy here because it's more about the location and price. #### **$100-150** S **Best Western Sunset Suites** (1103 E. Commerce St., 210/223-4400 or 866/560-6000, $99-169) may not be at the center of all the River Walk action, but it's a safe bet for inexpensive accommodations with clean and comfortable rooms. Amenities include nice furnishings, TVs, and mini fridges. Also included in your stay is free breakfast and free local calls. **Arbor House Bed & Breakfast** (124 W. Woodlawn Ave., 210/736-4232, $140-180), situated comfortably between the King William District and the River Walk, offers the quintessential bed-and-breakfast experience. This romantic place to stay is just far enough from the hum of downtown but central to all that San Antonio has to offer. Along with all the pampering amenities of a top-class bed-and-breakfast there is a charming courtyard. Rooms are furnished with antiques, knockoff paintings, TVs, and high-speed Internet. A great deal on the River Walk is often found at **Drury Inn and Suites** (201 N. St. Mary's St., 210/212-5200, $90-189). Amenities include free hot breakfast (the kind with eggs and sausage), free beverages, free long distance for up to 60 minutes, and high-speed Internet access. It may not be classy, but the location and value are great for budget travelers. The **Gunter Hotel** (205 E. Houston St., 210/227-3241, www.gunterhotel.com, $99-189) is one of many hotels in the Sheraton chain. Housed in a historic landmark building in downtown, the Gunter looks like it might have back in 1909 when it was first built. Old San Antonio upscale charm makes this an enjoyable place to hang your hat for the weekend. Amenities aren't four-star, but who cares—when it comes to downtown hotels, this is the best deal. One of three classy bed-and-breakfasts operated by Noble Inns is the **Pancoast Carriage House** (209 Washington St., 210/223-2353 or 800/242-2770, www.nobleinns.com, $130-200). Located in the King William Historic District, this carriage house has only three suites, making for personalized service and quietude. Wake up late and take breakfast at your leisure, then relax and read in the garden, followed by a swim in the full-size pool. The large suites feature queen-size beds, separate living/dining areas, and full kitchens, all with privacy. Be sure to ask about the 1960 Rolls Royce, which can be hired for transportation to and from the airport or dinner. As you walk around downtown you will probably notice a neo-Gothic, wedge-shaped building that piques the curiosity. This is the historic **Emily Morgan Hotel** (705 E. Houston St., 210/225-5100, www.emilymorganhotel.com, $139-359), named after the Yellow Rose, a heroine of the Texas Revolution. This classy hotel is distinguished by art deco decor, spacious rooms with views, and classic jazz bebopping in the background. Amenities include Aveda skin-care products, cotton bathrobes, a full-service restaurant and bar, and whirlpool tubs. In the shadows of the hotel is the famous Alamo. Rooms on The Alamo side of the hotel offer the best views. Affordable yet classy bed-and-breakfast accommodations can be found at **Inn on the Riverwalk Bed & Breakfast** (129 Woodward Pl., 210/225-6333, www.innontheriverwalk.com, $79-199). These three properties at the end of a cul-de-sac are tucked away on a quiet street south of downtown right on the San Antonio River, which makes it feel as though it's a hideaway right in the heart of the city. #### **$150-250** A swank place to stay that has a turn-of-the-20th-century aesthetic is the **Fairmount Hotel** (401 S. Alamo St., 210/224-8800, $159-229). Conveniently located on the River Walk and across the street from HemisFair Park, just down the street from The Alamo, this old San Antonio hotel is housed in a historic brick building that has been renovated for convenience and comfort. There are three floors of charming Victorian-style rooms and suites, each uniquely designed with antiques, European silk fabrics, tiling, and flat-screen TVs. Be sure to request one of the rooms with a view. The best place to stay in town is the innovative S **Hotel Valencia** (150 E. Houston St., 210/227-9700, $159-300). This hotel is like none other in the state. In an age when all luxury hotels feel and look like they were cut from the same template, the Valencia appeared on the scene and completely inverted the model. The interior is dark, dramatic, luxurious, modern, vanguard, and somehow resembles a classy nightclub. The service and integrity here are the best in town, and the rooms are perfectly comfortable and unique. Faux mink throws, balconies, and bathrooms that look more like they're out of a design magazine than a hotel are all trademarks of the Valencia. It offers an upscale bar and an uptown restaurant called Citrus. Imagine all this style and class situated on a quiet bend on the River Walk and you've envisioned the Valencia. This is why celebrities stay here, and why _Condé Nast Traveler_ magazine rated the Valencia as one of the world's top 100 new hotels in 2004. Since then it has consistently made _Condé Nast Traveler_ 's list of the world's best places to stay. One of the ritziest ways to experience San Antonio is by staying in the King William Historic District at **The Jackson House** (107 Madison, 800/242-2770, www.nobleinns.com, $160-250). Feel wealthy for a day as you are pampered to the point of no return. Spend quiet time in the conservatory surrounded by Victorian stained glass windows; relax in the large, heated swim-spa; and return to your room to find a chocolate on your pillow. Be sure to arrange to have their 1960 Rolls Royce take you and your date to dinner. Literally next door to The Alamo is the historic five-story S **Menger Hotel** (204 Alamo Plaza, 210/223-4361, www.mengerhotel.com, $195-215). Whether you stay here or not the Menger deserves a visit, as the backstory here is worthy of an entire History Channel special. From the famous guests who have stayed here throughout the years, such as Teddy Roosevelt, Babe Ruth, and Oscar Wilde, to the legends that were born here, such as Robert E. Lee riding his horse into the main lobby, there's lots of history to encounter. The Menger also boasts more than 40 often-seen apparitions. The hotel features a romantic courtyard, large heated pool, and a full day spa. Rooms are somewhat tiny, but charming. There's also the Menger Bar, which is where Teddy Roosevelt recruited some of his Rough Riders for the Spanish-American War. The "giant" painting in the old lobby, by F. L. Van Ness, was featured in the Western classic _Giant,_ starring Rock Hudson and Elizabeth Taylor. Early-20th-century San Antonio comes alive at the **Hotel Havana** (1015 Navarro, 210/222-2008, www.havanasanantonio.com, $250-400). This historic landmark building on the River Walk was tastefully renovated and designed to evoke a combination of 1920s Texas and Cuba. Rooms are decorated with vintage photographs, furnishings from around the world, plantation shutters, ceiling fans, and brick walls. On the premises is one of San Antonio's most intimate bars, **Club Cohiba.** This Latin bar and tapas grill is a favorite hangout for locals and travelers on the town, in the mood, and on the lam. It's best enjoyed with a stogie in hand and a flower in the lapel. One of Texas's most historic bed-and-breakfasts is the **Oge House** (209 Washington St., 210/223-2353, www.ogeinn.com, $155-255). This boutique bed-and-breakfast mansion is in the King William Historic District and on the banks of the San Antonio River. The location is unparalleled. Thanks to grand verandas with views, dramatic halls lined with period antiques, and scarlet drapes, one is transported to the era of wealthy, high society, 19th-century Texas money. Most rooms have a fireplace and old-world charm with modern comfort and convenience. Prepare to be dazzled by a gourmet breakfast served on china and white linens. Another good value on the River Walk can be found at **Hilton Palacio del Rio** (200 S. Alamo St., 210/222-1400, $219-300). Hilton Palacio is the longest consecutive recipient of the AAA Four Diamond Award. All rooms feature Spanish decor and have access to private balconies with spectacular views of the city. The main lobby and common areas are a bit outdated, but the fitness center has been renovated. There's also a rooftop pool and hot tub with stunning views, a full-service business center, a restaurant, and a river-level bar featuring live music and booze. The four-star hotel on the San Antonio River is **The Westin River Walk** (420 Market St., 210/224-6500, $179-359). For high-end accommodations this is a good bet, as the service is impeccable and the comforts abound. From the valet parking service to the rooms with downtown views and the goose-down pillows, everything here is perfectly orchestrated. The entire hotel is decorated with art from local artists, and marble and stone are everywhere. Wireless Internet is available throughout, there's a fitness center on-site, shampoos and soaps are above average, and some showers feature spa-style double showerheads. Among the more unusual amenities is _la merienda_ , which is a Latin version of afternoon tea available to guests Tuesday-Saturday. Because of these comforts, this is one of two places where the rich and famous stay when in town. #### **OVER $250** For the luxury traveler, staying in the Pearl District at **Hotel Emma** (136 E. Grayson St., 210/448-8300, www.thehotelemma.com, $300-400) can't be beat. Here you can be close to all that Brackenridge Park has to offer as well as the amazing restaurant and brewery scene of the Pearl. Housed in a repurposed historic San Antonio building that was once a brewery, this modern industrial high-end hotel has a pool, terrace rooms, an in-house restaurant, and even a library. Have you ever wanted to stay overnight at Pottery Barn or Crate and Barrel? The **Hyatt Regency San Antonio** (123 Losoya St., 210/222-1234, $249-329) rooms reflect the most current trends in decor. The bustling grand lobby is an open-air atrium with waterfall, chichi bar, and mediocre service. The location is what this Hyatt is all about. It's both on the River Walk and at the center of downtown, just a stone's throw away from The Alamo. **La Mansión del Rio** (112 College St., 800/292-7300, www.lamansion.com, $239-379) is a Spanish hacienda-style hotel with everything you could want in a San Antonio stay. Of course, it comes at a hefty price. It's on one of the most beautiful stretches of the River Walk, within walking distance of all that downtown San Antonio has to offer. It has arches, antiques, verandas, wrought-iron balconies, scarlet drapes, rough-hewn beam ceilings, and amenities fit for General Santa Anna himself, and guests are encouraged to feel like world rulers. Rooms on the River Walk are very expensive and are often occupied by the rich and famous. By expensive I mean they can run upwards of $2,000. ### **Information and Services** #### **TOURIST INFORMATION** The **San Antonio Visitor Information Center** (317 Alamo Plaza, 800/447-3372, 9am-5pm daily) is conveniently located right across the street from The Alamo. The helpful staff here can provide you with maps, brochures about the city's attractions, and lodging information, and are pleased to answer any questions you may have. #### **EMERGENCY INFORMATION** In the event of an emergency involving injury or danger dial **911.** For nonemergency police needs there's the **San Antonio Sheriff's Department** (210/335-6000). The main hospital downtown is **Baptist Medical Center** (111 Dallas St., 210/297-7000). For information on other medical facilities call the **San Antonio Medical Foundation** (210/614-3724). #### **PUBLICATIONS** The best resource for all things hip, such as live music, art gallery openings, events, and festivals, is the local alternative rag, _San Antonio Current._ This free newsprint periodical can be found all over town. New editions hit the streets every Thursday. The paper with a local news focus is the _San Antonio Express-News._ Nothing special here, just politics, sport pages, funnies, and the usual _Citizen Kane_ stuff. The full-color glossy magazine _Texas Monthly_ is the best state magazine in the country. It can be purchased at most supermarkets and corner stores. This is a great resource for state news, politics, and celebrity gossip, and offers a great listings section in the back with restaurant reviews. #### **INTERNET** If you have a laptop with a wireless card you can access the Internet through hot spots in cafés. If you're staying in a hotel, chances are it has wireless or connections in rooms available to guests. For everyone else there's a **FedEx Office** (4418 Broadway, 210/821-6911) way up near Brackenridge Park. At $0.20 per minute this can get costly unless you just want to check email. For free Internet access downtown there's the **San Antonio Public Library** (600 Soledad St., 210/207-2500, 9am-9pm Mon.-Thurs., 9am-5pm Fri.-Sat., 11am-5pm Sun.). #### **LAUNDRY** For coin-operated laundry machines there's **E-Z Wash** (801 S. Hackberry St., 210/359-9274). Check the phone book for more listings. #### **POST OFFICE** Just across from The Alamo is the most conveniently located post office (615 E. Houston St.) downtown. For other locations call 800/275-8777. You'll need a zip code to get a location using this toll-free number. If you prefer paying slightly higher prices for your postal needs, the **UPS Store** (200 E. Market St. near HemisFair Park, 210/258-8950) has mailers, envelopes, copy machines, and even maps. #### **MONEY** ATM kiosks are everywhere, but beware—the ATMs you find on the street all charge extraordinarily high fees. It's always best to get money from your own banking institution, but if your bank isn't to be found, at least use a national bank's ATM. You may still incur a fee but it's much less than at kiosk ATMs. ### **Transportation** #### **GETTING THERE** Getting to San Antonio is a cinch. All you need is money for an airline, train, or bus ticket, or gas for a road trip. Being the seventh-largest city in the United States, San Antonio has lots of travel and commerce, by highway and by air. Since it's sort of in the middle of nowhere, with respect to the greater United States, the easiest way to get here is by air. ##### **Air** Located about eight miles north of downtown is **San Antonio International Airport** (9800 Airport Blvd., 210/207-3433, www.sanantonio.gov/airport). This is the region's largest airport and is an international hub with both direct flights and domestic connections that can get you to anywhere in the world. Nonstop flights are offered to 41 destinations, mostly major U.S. cities and a couple of cities in Mexico. Passenger airlines that service the airport include: Aerolitoral (800/237-6639), America West (800/235-9292), American Airlines (800/433-7300), Delta (800/221-1212), Mexicana (800/534-7921), Midwest (800/452-2022), Southwest (800/435-9792), and United (800/241-6522). The airport provides hourly, daily, and economy parking. For hourly parking, the rates are $2 for the first 30 minutes, $3 for 30 minutes to one hour, and $5 up to two hours. Long-term parking is $11 for 24 hours. There are several ways to get from the airport to town. The most economical way is by taking the **VIA Metropolitan Transit** bus 2. Buses run about every hour 8am-9:30pm, and it takes about an hour to get to downtown. The fastest and easiest way to get to downtown, especially if you have lots of luggage, is by buses service provided by **SA TRANS** (210/281-9900). One-way shuttle service to downtown costs $18 per passenger. For groups there's **Star Shuttle** (210/341-6000). Taking a cab costs about $25-30. Most hotels offer shuttle service free of charge. Be sure to ask your hotel about this before traveling. To drive from the airport to downtown, take Highway 281 south, which goes straight to downtown. It takes about 30 minutes to get to downtown from the airport via car, taxi, or shuttle. ##### **Car** San Antonio has been a crossroads for centuries, and this becomes apparent when you look at a current map of the state. Major highways fan out from the metropolitan area and shoot to all parts of the United States and Mexico. The main interstate highways that connect San Antonio to the world are I-35, I-10, I-37, and I-410. It's imperative to have both a regional map and a good city map to successfully get around. Signage is good, for the most part, but exits and exchanges can happen fast the closer you get to downtown. If you are driving from Austin to San Antonio, take I-35 south, which goes through the heart of downtown Austin to the heart of San Antonio. The drive is about 80 miles and takes about 1.5-2 hours, depending on traffic. If you are driving from Houston to San Antonio, take I-10 west. The drive is approximately 200 miles and takes about three hours. ##### **Bus and Train** On **Greyhound** (800/229-9424, www.greyhound.com), you can get to San Antonio from just about anywhere in the contiguous United States, provided you don't mind a long ride. Using the service to get to San Antonio from Dallas, Houston, or Austin is very affordable. Buses to San Antonio from Dallas, Austin, and Houston are available every 2-3 hours. The ride from Dallas is about 5-6 hours and the standard fare is $39. The ride from Austin is about 1.5 hours and the standard fare is $29. The ride from Houston is about 3 hours and the standard fare is $33. The **bus station** (500 N. St. Mary's St., 210/270-5824) is conveniently located downtown near hotels, restaurants, and attractions. For travel to and from many of the smaller Texas towns, including many in the Hill Country, there's **Kerrville Bus Company** (800/335-3733). The station for this bus line is shared with Greyhound. As for train access to San Antonio, there's always the old American staple, **Amtrak** (800/872-7245, www.amtrak.com). Trains to San Antonio from Dallas are available daily and leave around noon. The travel time is about 10 hours and the standard fare is $43. Trains to San Antonio from Austin are available daily and leave at about 7pm. The travel time is about 3.5 hours and the standard fare is $27. Trains to San Antonio from Houston are available daily and leave at 7pm. The travel time is about 5 hours and the standard fare is $34. The **train station** (350 Hoefgen St., 210/223-3226) is located on the eastern side of downtown. #### **GETTING AROUND** Deciding which mode of transportation you will need while in San Antonio entirely depends on what you plan on achieving while in town. The downtown area is a self-contained tourist world chock-full of things to see and do. If you can walk, it's entirely feasible to have an enjoyable experience without ever thinking about transportation. However, the city is sprawling, and some attractions are way out there. ##### **Car** For the first-time visitor, getting around the city via automobile can be confusing and frustrating. There are many major freeways in the metropolitan area and in the suburban sprawl. The city is best navigated and understood when compared to a wagon wheel. Two rings of highways circumnavigate the city, one in the center of downtown and the other at the outer rim of the city. Highways fan out from the center of town and shoot off into all parts of the state. The downtown area is inside the inner ring, which is defined by I-35, I-37, and I-10. Beyond this is greater San Antonio, which is circumnavigated by the outer ring, defined by I-410, also known as Loop 410. Parking can be frustrating in the downtown area. Metered parking is available on many streets, but spots are always hard to find. If you plan on tooling around the sights downtown you might as well leave your car at a parking garage and tour by foot. Centrally located parking garages are: **LAZ Parking** (122 N. Main Ave., 210/224-2468, and 151 Soledad St., 210/224-2468) and **Market Street Parking Garage** (421 W. Market St., 210/212-4011). Most attractions outside of downtown offer parking free of charge. All the usual rental car companies are represented at **San Antonio International Airport,** as well as around town. Car rental agencies include **Advantage Rent-A-Car** (800/777-5500), **Alamo Rent-A-Car** (800/327-9633), **Avis Car Rental** (800/831-2847), **Budget** (800/527-0700), **Dollar Rent-A-Car** (800/800-4000), **Enterprise** (800/736-8222), **Hertz Rent-A-Car** (800/654-3131), **National Car Rental** (800/227-7368), and **Thrifty** (800/847-4389). My hunch is Alamo Rent-A-Car gets the most business in this town. ##### **Bus** San Antonio's public transportation system, **VIA Metropolitan Transit** (210/362-2020, www.viainfo.net), is the cheapest way to get around, and fairly easy to get the hang of. VIA has both buses and touristy streetcars. VIA's hub-and-spoke system offers over 85 routes, with major hubs downtown fanning out into the metropolitan area. A ride costs $1.20 a trip, and transfers are $0.15. Buses and streetcars are in operation 5am-midnight. If you plan on using VIA as your primary form of transportation, I highly recommend getting a day pass for $4, which provides unlimited rides on both the buses and streetcars for a day. ##### **Taxi** Although taxi cabs can be hailed on the streets, you'll probably save time picking one up at the bus station downtown, by catching one at a hotel, or by simply calling in advance. **Yellow Cab** (210/222-2222) has the San Antonio cab monopoly. Cab rates start at $2.50 for the first mile, plus $2.65 for each additional mile, and there's a minimum of $3 for rides in downtown. The one-way fare from San Antonio International Airport to downtown is $25-30. fossilized dinosaur skeleton at the Witte Museum in San Antonio ## **Background** The Landscape GEOGRAPHY CLIMATE Plants and Animals PLANTS ANIMALS History PREHISTORY NATIVE AMERICANS OF TEXAS SPANISH AND FRENCH EXPLORATIONS (1519-1685) REVOLVING SOVEREIGN DOOR (1685-1690) SPANISH TEXAS, MISSIONS, AND AMERICANS (1690-1821) MEXICAN TEXAS (1821-1836) THE TEXAS REVOLUTION (1835-1836) REPUBLIC OF TEXAS (1836-1845) ANNEXATION (1845-PRESENT) Government and Economy POLITICS ECONOMY People and Culture POPULATION RELIGION LANGUAGE MUSIC AND ART wagon replica in Gruene. ### **The Landscape** #### **GEOGRAPHY** The impression most people have of Texas is that it's a dry, flat, and arid land fraught with twisters, dust bowls, and cacti. That may be true for the western part of the state, but that's far from what Austin, San Antonio, and the Hill Country are like. The region at the heart of the state, known as Central Texas or the Texas Hill Country, is a lush, green land with rolling hills, crystal-clear rivers and lakes, giant outcroppings of granite rock, and plentiful wildlife. Geologists claim this remarkably beautiful landscape was formed over the course of billions of years. Geological records tell a dynamic story of activity: inundation by inland seas, volcanic eruptions, the erosion process of rivers, and earthquakes. Thanks to this extraordinary process the region is filled with great beauty both on the surface and beneath the surface. Visitors can see Central Texas geography and geology at its best by visiting any of the many parks, such as Enchanted Rock State Natural Area, or by visiting some of the many caves throughout the region. #### **CLIMATE** Some people say Central Texas has three seasons: fixin' to be summer, summer, and just been summer. More-informed folks say there are four seasons: flood, hurricane, drought, and tornado. Combining these two theories provides an accurate, albeit unorthodox, description of the climate in this hot and meteorologically dramatic part of North America. When it comes to crazy weather, Austin and the Hill Country seem to be particularly prone to the drama of the Greek gods above. At any given moment the sky can go from meek and mild to a violent, spectacular show of lights, thunder, and hail. Although there are more tornadoes in Texas than any other state, they rarely rip their way through Austin. As for hurricanes, they generally downgrade to a tropical storm by the time they make it this far inland. The climates of Austin, San Antonio, and the Hill Country are very similar, with some slight variation. The Hill Country is often a few degrees cooler, San Antonio is always more humid, and Austin is somewhere in between. Average temperatures for all of Central Texas are: summer 85°F, fall 70°F, winter 50°F, and spring 70°F. Remember this is an average—don't be fooled by these numbers. In summer months expect average highs of 90-100°F. As for the rest of the year, the temperature can range anywhere from 40 to 70°F. Expect dramatic and crazy weather in the spring, late arrival of fall, moderate winters, and hot summers. Spring is a time when flash flooding is commonplace, hail can be the size of baseballs, and lightning starts fires. The summers are all that they're advertised to be. They're hot, and they're humid, and usually last about three months. The spring and the fall are the best times of year in terms of temperature and beauty. In the winter the weather is rarely the same for two days in a row. On occasion it will drop below freezing, and on the very rare occasion it will snow. **Ask the Weatherman** With freak hailstorms, flash floods, lightning, and thunder year-round, 90°F Novembers, 60°F Decembers, and 110°F summers, this type of climate needs a professional explanation. Local weatherman **Mark Murray,** chief meteorologist of KVUE News, has the answers. _Q: At any given moment throughout the year freak storms can envelop Austin. Flash floods, thunder and lightning, and even softball-size hail in the middle of summer. Why does Central Texas have such dramatic freak storms all year-round?_ A: We do get our share of severe storms, especially in the spring, and it has to do with our location. We're close enough to the Gulf of Mexico to get plenty of moisture, but we're also not too far from that dry desert air of West Texas. When that moist air from the Gulf meets the dry air from Texas, it creates something called a "dry line." When two different air masses come together—moist and dry in this case—that's what makes the fireworks. The dramatic storms that we get here often fire up along what's called the "West Texas Dry Line" and march into Austin, San Antonio, and the Hill Country. The dry line runs north and south, from West Texas all the way up to Nebraska. _Q: I've heard people say there's no spring or fall in Central Texas—it's all summer and winter. Can you explain the seasons here?_ A: Seasons can change rapidly here, it's true. Fall is beautiful, but short. It's generally mid-September through late October. It's still warm but the humidity drops quite a bit, and it becomes sunny and mild. Winter is mild. On average it freezes about 19 days a year. Every couple years we get just enough snow to cover the ground but it melts pretty quickly. Only two times has the temperature dropped below zero. Spring, which is mid-March through mid-June, is a great time because temperatures are mild and the wildflowers are in full bloom. This makes it a very pretty time of the year. Wildflower festivals are happening in the Hill Country, and people are outdoors all day. Summer, which is from mid-June to mid-September, is very hot and humid. If you're in Central Texas during the summer heat, you may want to plan your day a little differently. If you want to walk around Lady Bird Lake's hike-and-bike trail you may want to do this in the morning or the evening. _Q: When is the best time of year to visit Austin and Central Texas?_ A: You can do things outdoors in Austin pretty much year-round. Festivals and outdoor events are scheduled throughout the year here. However, spring and fall are the best times of year to visit. The weather is moderate and it's beautiful. _Q: When is the least desirable time of year to visit Austin and Central Texas?_ A: I think a lot of people would say the middle of summer, which is August and September. It's very hot and humid. _Q: What are the greatest meteorological threats to Central Texas?_ A: There are three main threats we're faced with. Flash flooding is our biggest threat. Weak tropical depressions can dump lots of rain very quickly. Lightning is the second-biggest threat. After these two, another threat we have is tornadoes. They generally don't last long and aren't that big, but they have caused damage. Central Texas has seen only two F5-class tornadoes. Hurricanes from the Gulf of Mexico aren't a threat here as they rarely hold their strength this far inland. However, hurricanes can create a tornado outbreak and can bring heavy, flooding rains. _Q: Why do you love Austin's climate?_ A: I love the weather here. When people ask me what kind of weather I like, I always say I like weather that changes. Being a meteorologist, I love to forecast the changes. _Q: What's the first thing you do every morning?_ A: Look outside to see if I was right. ### **Plants and Animals** #### **PLANTS** The climate in Central Texas has created a diverse plant ecosystem that includes everything from cacti to maple trees to an astounding array of wildflowers. All of the flora that exists here has the ability to survive drought conditions and extended periods of hot weather. The most common forms of plant life are oak trees, juniper (often mistakenly called cedar), and numerous varieties of wildflowers. Every spring the Hill Country explodes with wildflower color. Bluebonnets are the most prolific and popular of all Texas wildflowers. When they're in full bloom it's common to see families scrunched down in fields of bluebonnets along roads and highways taking photos. If you're tempted to pick these gorgeous flowers, be aware that this is frowned upon. (Most people think it's illegal to pick bluebonnets because they are the state flower, but this is a Texas myth.) Other common wildflowers include Texas paintbrush, the bright and delicate fuchsia-colored winecups, greenthreads (which are actually yellow), and the shockingly radiant Indian blanketflowers. The best way to experience wildflower season is by driving the Willow City Loop in the Hill Country, or by visiting the Lady Bird Johnson Wildflower Center just east of Austin. #### **ANIMALS** There are thousands of species of wildlife in Central Texas, but the ones that get the most press are bats, armadillos, and the longhorn steer. These have become larger-than-life icons that represent the region as virtual ambassadors. Of the three, bats are the most popular. There are more than two dozen species of bats in Texas, the most popular and well known being the Mexican free-tailed bat. The largest colony of Mexican free-tailed bats in North America happens to be beneath the Congress Avenue Bridge in Austin. These little mammals have helped put Austin on the map, as they have been drawing tourists and the curious to the city for decades. The prehistoric-looking armadillo is the most curious of Texas's creatures. Unfortunately, these armored mammals are known most for being roadkill. These low-key residents of the state feed on insects and vegetation. Although the ones we have today are about the size of cats, in prehistoric times they could get as big as a VW Bug. The skeletal remains of one of these monsters are at the Texas Memorial Museum in Austin. Perhaps the most iconic of all Central Texas animals is the longhorn steer. Once the symbol of Texas pioneer ranching, the longhorn steer is now best known as the logo for University of Texas sporting teams. These majestic-looking beasts can be seen fenced in on ranches all throughout the Hill Country, grazing in fields, and resting beneath ancient oak trees. Longhorn steer are raised primarily for beef, but their unwieldy horns are also desirable. On occasion you'll see them fixed to the front of a Cadillac. Besides bats, armadillos, and longhorn steers, Texas is also known to have more bird species than any other state in the United States. With over 600 documented bird species, including some rare birds that live only in this region, Texas has become one of the top bird-watching destinations in North America. This extraordinary number of birds is due primarily to the fact that Central Texas is a popular stopping point for migratory birds flying the Central Flyway, which runs from Canada to Mexico. ### **History** A history of Austin, San Antonio, and the Hill Country has to be told properly—it has to happen through the prism of Texas history. After the prehistory, the state's story unfolds in and around San Antonio and makes its way toward Austin being named the capital. Everything in between is pure drama. #### **PREHISTORY** Texas must have been a popular place for prehistoric creatures to congregate. Fossils and footprints of at least 16 types of dinosaurs have been discovered all around the state. According to current paleontology the following dinosaurs ruled the state: the huge and fierce _Acrocanthosaurus atokensis,_ the big-toothed, meat-eating _Tyrannosaurus rex,_ the plant-eating dinosaurs of the Ornithischia order, the giant crocodile-like _Deinosuchus,_ and the _Tenontosaurus,_ among many others. Artifacts found include bones of mammoths, horses, camels, ancient bison, giant short-faced bears, and giant armadillos. Most of the evidence of earliest human inhabitants dates back 10,000-13,000 years. These early "Texans" are believed to be of Asian origin, having come to the North American continent by way of the land bridge at the Bering Strait in Siberia and Alaska. They are believed to have been completely modern _Homo sapiens_ , as no evidence has been found in the New World that indicates evolutionary change. Archaeologists have determined four stages in development of early inhabitants: Paleo-Indian, Archaic, Woodland, and Neo-American. Perhaps one of the earliest tribes of indigenous peoples is the Caddoes. They were highly civilized and agricultural, had a highly defined social structure, and even participated in trade. #### **NATIVE AMERICANS OF TEXAS** Long before Europeans arrived in the area known today as Texas, various tribes of Native Americans occupied the region. Some migrated here from other parts of North America, while others are believed to be indigenous. The history of present Texas is inextricably linked to these native populations who were in the region when Spanish explorer Álvar Núñez Cabeza de Vaca landed in 1528, and to those who later swept down from the plains on horseback. Regrettably, the story of the indigenous natives is not a pleasant one. Tribes were either wiped out by the Spanish, French, Mexican, and Anglo settlers or simply merged into and became part of the Mexican and Hispanic populations, losing their tribal identities. ##### **Karankawans** _Karankawa_ was the designation for several bands of coastal tribes who shared a common language and culture. They were perhaps the most successful and long-lived of the indigenous tribes encountered by Cabeza de Vaca when he shipwrecked off Galveston Island. The Karankawa people were known for their distinctive physical appearance. The men were described as tall and muscular, unlike the other natives. They practiced ritualistic cannibalism but were repulsed by the fact that some of Cabeza de Vaca's companions ate their dead to avoid starvation. After Cabeza de Vaca's encounter with the Karankawans, the tribe didn't encounter Europeans for another 150 years. In 1685, the French explorer René-Robert Cavelier, Sieur de La Salle, established a fort near what is now Matagorda Bay in the heart of Karankawa country. The Karankawans eventually killed all of those settlers except for six children who were taken captive; two survived and returned to France and told of their life with the Karankawans. During the Spanish mission period an attempt was made to Christianize the Karankawans and to make them loyal Spanish subjects. La Bahía mission and presidio complex near present-day Goliad was established in 1749 for that purpose. However, the Spanish attempts to Christianize the Karankawans met with little success. The Karankawans were hostile toward everyone: the Spanish, the French, the Comanches, and Anglo Texans. Because of this the Karankawans were exterminated. In 1858, a Texan force attacked and annihilated the last organized bands of Karankawans near Rio Grande City. The last reported Karankawan, named Indian Tom, was raised from infancy by Anglo settlers in Matagorda County. Later he enlisted as a Confederate soldier in the Civil War. He was killed while being detained as a prisoner of war when he refused to obey his captor's commands. ##### **The Tonkawa** The Tonkawa occupied the majority of the Central Texas Hill Country, from Llano to San Antonio. They were very mobile and hunted buffalo, deer, and smaller game. Upon the arrival of the Apache and Comanche Indians, the Tonkawa were forced into the region between Austin and San Antonio, where they existed through the Spanish period and the subsequent Texan and American periods of history. It's believed they were the friendliest of the Native American tribes in the region. They shared living space, as well as water and food sources, with the Karankawa, as well other tribes that passed through the region. ##### **The Comanches** No tribe had a greater impact on Texas than the Comanches. The Comanches didn't exist when Cabeza de Vaca journeyed through Texas. In fact, the arrival of the Europeans was the genesis of the Comanche. Prior to that, anthropological evidence and linguistic studies indicate they were a branch of the Northern Shoshones. Originally, the Shoshones were typical pedestrian hunters and gatherers. When they obtained the horse in the late 1600s, a revolution occurred. This obscure branch of the Northern Shoshones evolved into a mounted and aggressive warrior culture that left their mountain home for the great plains of eastern Colorado and western Kansas, where game was plentiful. They eventually migrated south, attracted most likely by the warm climate and abundant buffalo, and the presence of less-aggressive indigenous tribes they could dominate. By the 18th century, much of north, central, and west Texas was Comanche country, also known as Comanchería. This is when they became known as Comanches, a name derived from a Ute word literally meaning "anyone who wants to fight me all the time." And fight they did. **Origin of the Word "Texas"** One of the indigenous Native American tribes present in eastern Texas when Spanish explorer Álvar Núñez Cabeza de Vaca arrived was the Caddo tribe. Their word _techas,_ which means "friend," turned into "Tejas," which eventually became "Texas." The Spanish began to use "Texas" as the name for that entire group of Native Americans—records show the word appearing as early as 1689. The transition from _Tejas_ to _Texas_ came easily, as the letters _x_ and _j_ have the same pronunciation in Spanish—the "h" sound in English. Thus, the Texas name is derived from a Caddo word, and the state's motto of "Friendship" reflects that heritage. ##### **Lipan-Apaches** The Apaches are believed to be descended from Athapaskan ancestors who migrated from the forests of western Canada into the southern Great Plains. When the Apaches came to the lands of what is today known as Texas and Mexico, they were constantly forced to move due to pressure from the Comanches. In Texas they came into contact with the new Spanish settlements. By the 1600s, the Spaniards had enslaved many Apaches to work ranches and mines, and the Apaches often retaliated by stealing horses. The Apaches found themselves under pressure from Anglo-American settlers from the north and east, the Mexican-Spaniards to the south, and the Comanches from every direction. By the 1740s, pressure from the Comanches prompted the Apaches to migrate toward the Rio Grande. Eventually, settlements such as San Antonio encroached on the Apaches' hunting grounds. This was a period of much violence between the Apaches, the Spanish missions, and the settlers. Avoiding the encroachment of these other groups and conversion to Catholicism, Apaches eventually retreated to the Rio Grande. **The Comanche Warriors** From the early 1700s to the late 1800s, a period of approximately 200 years, the Comanches' warrior culture changed the face and destiny of what is now Texas. The Apaches, who had previously dominated the region, were forced south by the Comanches and became their mortal enemies. The Comanches completely halted Spanish and Mexican efforts to colonize Texas during the mission period. In 1758, a force of approximately 2,000 Comanches attacked a Spanish mission built for the Apaches on the San Saba River in Central Texas near present-day Menard. They sacked and burned the mission and killed most of its inhabitants, including two priests. A Spanish expedition was mounted the following year to punish the Comanches, but it also met defeat. The Spanish were never able to successfully colonize Texas because of the Comanches' continued raids on their settlements for horses and captives. In 1821, Mexico won independence from Spain, but the armed, mounted, and aggressive Comanche warriors remained dominant. A series of unstable governments from Mexico City had no more success than their Spanish forefathers in projecting their power and presence in Texas. The dominance of the Comanche warriors in Texas, probably more than any other factor, was the reason the weak Spanish and Mexican governments enacted laws to encourage foreign immigration to Texas. They were attempting to create a buffer between them and the Comanches and seeking someone who could match the Comanches in aggressiveness and warrior mentality. The new tribe that was invited into the Texas territory to battle the Comanches and ultimately defeat them was the Anglo-Americans. The interdependence of the fate of Comanches and Europeans in Texas is clear. Without the horses brought by Europeans, the Comanches never would have risen to dominance, and without the Comanches, Anglo-Americans never would have come to the Republic of Texas, which evolved into the State of Texas. The Comanches still spread terror over much of Texas when Texans won their independence from Mexico in 1836. Sam Houston, the first elected president of the Republic of Texas, had lived with and was an adopted Cherokee. He wanted to institute a policy of peaceful coexistence with all the Native American tribes, including the Comanches. That policy was not favored by most Texans, including Sam Houston's successor in office, Mirabeau B. Lamar. Texans and Comanches remained enemies, committing brutal atrocities against each other until the Comanches were almost exterminated and were permanently removed from Texas to Indian Territory, now Oklahoma. Even after the Civil War, and after the Comanches entered into various peace treaties with the U.S. government, hostilities continued between them and the Texans. In reality, the Comanches and the Texans never considered themselves bound by such treaties. For them, it was a war until death or total subjugation, a war the Comanches could not win—which is why there is no Comanche presence in Texas today. #### **SPANISH AND FRENCH EXPLORATIONS (1519-1685)** As early as 1519 the coast of Texas was mapped. Under the service of the governor of Jamaica, Captain Alonso Álvarez de Pineda sailed the Gulf of Mexico and became the first person in recorded history to explore the region. Just a few years later, in 1528, exploration in Texas was resumed by Spanish explorer Álvar Núñez Cabeza de Vaca. _Cabeza_ is Spanish for head and _vaca_ is Spanish for cow. How appropriate that the written history of Texas begins with the fascinating adventure of a man with the name of "Cow's Head." Cabeza de Vaca was shipwrecked on the coast of Texas and washed up on the beach literally naked. He spent the next seven years wandering through what is now Texas. He lived with the native inhabitants until he arrived at a Mexican outpost near the Pacific coast in early 1536. Cabeza de Vaca arrived as a conquistador but during the course of his travels became a merchant, a slave, and a healer to the various small family bands of hunter-gatherers scattered throughout the region. In his role as a healer, Cabeza de Vaca removed an arrow from the chest of an Indian, for which the Texas Surgical Society honors him today as their "patron saint." He chronicled his odyssey in what is titled _La Relación_ (The Account), which was first published in Spain in 1542. In it, Cabeza de Vaca describes in detail the landscape he encountered and his observations of the native peoples' cultural practices, including how they ate, raised their families, and made love and made war, all before the land and its people were irrevocably altered by the European culture, its diseases, and the introduction of the horse. Cabeza de Vaca advocated to the Spanish crown not to enslave the natives. His precise route through Texas has been the subject of considerable study but is not exactly known. Some scholars have Cabeza de Vaca's route taking him through what is now Central Texas and the area including Austin, San Marcos, and San Antonio. The Center for the Study of the Southwest, at Texas State University in San Marcos, houses a rare 1555 edition of Cabeza de Vaca's _La Relación._ Artifacts from the natives of this era are on display at the Witte Museum in San Antonio. After Cabeza de Vaca's unintentional tour through Texas, Spain continued to have many contacts with Texas. Subsequent Spanish explorations of Texas were conducted by Francisco Vásquez de Coronado and Luis de Moscoso Alvadaro. Forty years later, Fray Agustín Rodríguez, a Franciscan missionary, and Francisco Sánches Chamuscado led an expedition through Texas and New Mexico. In 1681 the first permanent settlement in Texas was established in the El Paso area. **Discovery of La Belle** One of French explorer La Salle's ships, _La Belle,_ sank in Matagorda Bay in 1686. Over 300 years later, in 1995, Texas Historical Commission archaeologists discovered its resting place and erected a cofferdam around it to salvage its contents. They eventually recovered its hull, over one million artifacts, and the skeleton of one of the crewmembers. It is one of the most important shipwrecks ever discovered in North America. Many of its artifacts are on display at the Bullock Texas State History Museum in Austin. #### **REVOLVING SOVEREIGN DOOR (1685-1690)** With Spanish exploration, the region fell under the domain of Spanish rule. However, the Spaniards soon learned Texas didn't have the gold, silver, and other riches they sought, and the hostile environment of Texas wasn't providing sufficient incentive for them to wander far from the reasonable comfort of Mexico City. This left a gap for the French to try to lay claim to the New World. In 1682, French explorer René-Robert Cavelier, Sieur de La Salle, attempted to create a colony in Louisiana but mistakenly landed in Texas. La Salle's settlement was on Lavaca Bay just up the coast from present-day Corpus Christi. Hearing that France was establishing a presence with a colony, the Spanish government became very interested in Texas. In 1689 Spanish authorities sent Captain Alonso de León to confront the French and reclaim the region. When he arrived at the French colony, he found the settlement had been decimated by Indians and La Salle had been killed by his own men. Thus Spain realized it ruled the land once again. #### **SPANISH TEXAS, MISSIONS, AND AMERICANS (1690-1821)** In 1690 an expedition of Spanish soldiers and four Franciscan priests crossed the Rio Grande. The Spanish were coming to establish their own settlements, bring Christianity to the Indians, and, more importantly, prevent any other European powers from claiming what they believed was rightly theirs. Thus began in earnest the Spanish mission period in Texas. Between 1682 and 1793, 26 missions were established by Franciscan priests in Texas. The most successful were the five missions established in San Antonio: Mission San Antonio de Valero (The Alamo), Mission Concepción, Mission San José, Mission San Juan, and Mission Espada. Less successful but still with a significant presence was Mission Nuestra Señora del Rosario and its accompanying Presidio La Bahía, established on the lower San Antonio River in 1749 (the Goliad mission). The five missions on the upper San Antonio River still exist and are within a few driving miles of each other. Collectively these missions form the largest concentration of Catholic missions in North America. The goal of the missions was to convert the local native population. The buildings were first built of stone, wood, and adobe and didn't have walls. Because of tensions between tribes and missionary occupants, stone walls were erected as a form of defense. By the late 1770s it was clear that the efforts of the Spanish to civilize and colonize Texas through the mission system had been largely unsuccessful, if not an outright failure. The population of the weaker indigenous tribes who had been the mission recruits declined through high infant mortality rates, epidemics introduced by the Europeans, pressure from more aggressive invading tribes, and assimilation. Texas remained thinly populated and impoverished. Between 1824 and 1830, the first years of the Republic of Mexico, all the missions still in existence in Texas were officially secularized with the exception of the ones in El Paso. One of the greatest contributions of the mission system was the establishment of ranching in Texas. Early expeditions brought livestock to the missions, and within two to three decades thousands of cattle and horses roamed the pastures and prairies from central to south Texas. The horses and cattle were the genesis of the huge cattle drives after the Civil War and were managed by the _vaqueros_ (from which the term "buckaroo" is derived), who evolved into the quintessential Texas cowboy. Around the 1800s the first Anglo-Americans appeared on the scene. Initially they were tolerated by Spanish authorities, but Spain's grip on Texas began to weaken between 1790 and 1820 as Spain focused more on Europe and Mexico. This opened the door for Anglo-Americans to continue settling in Texas, which eventually morphed into unregulated colonization by Americans. #### **MEXICAN TEXAS (1821-1836)** Spain's efforts to colonize and populate Texas ended in failure. When Mexico gained its independence from Spain in 1821, it inherited the results of that failure. Only three towns existed and the population was estimated at approximately 2,500. The Comanches, Apaches, and other hostile tribes ruled Texas more than the government officials in Mexico City, whether they were Spanish or Mexican. To populate this northern frontier full of hostile natives, the Spanish and then the Mexican governments looked to Anglo-American immigration. In January 1821, the Spanish government gave Moses Austin of Missouri a contract to establish a colony with 300 families. When he died, his son Stephen F. Austin inherited the contract. The Mexican government confirmed Austin's contract after independence, and Austin and other _empresarios_ (those with contracts from the Mexican government) began immigrating into Texas. By 1835, there were 21 towns, and the Anglo-American population was estimated to be approximately 20,000, with the Hispanic Texans, called Tejanos, numbering fewer than 5,000. Antonio López de Santa Anna was elected president of Mexico as a liberal and a champion of the Constitution of 1824. However, by 1835, he replaced the existing congress with a new body dominated by centralists under his control. He then abolished the Constitution of 1824 and abolished the various state governments, including that of Coahuila y Texas. Mexico, like the United States, had then and has now a federal government and various state governments; even today, the official name for Mexico is Los Estados Unidos de Mexico (the United States of Mexico). Santa Anna had replaced the state governments with departments run by officials he appointed. When the state of Zacatecas (Texas) rebelled, Santa Anna's forces invaded the state. After defeating his opposition, Santa Anna allowed his soldiers to murder and rape the local citizens, killing thousands of them. By October 1835, Santa Anna had made himself supreme dictator of Mexico. The people of Texas, both Anglos and Tejanos, were in conflict with the policies of the brutal dictator. They had economic interests separate and apart from Mexico City and were used to little in the way of government interference. Facing the loss of their local government and the replacement of the liberal Constitution of 1824 with the arbitrariness of a supreme dictator, the Anglo-Texans, who called themselves "Texians" at that time, decided to rebel, with the support of a significant number of Tejanos. #### **THE TEXAS REVOLUTION (1835-1836)** ##### **The Battle at Gonzales** The flash point that ignited the Texas Revolution occurred in October 1835 in the town of Gonzales, on the Guadalupe River about 70 miles east of San Antonio. The town had a small cannon given to it by the Mexican Army to defend against the native tribes. Due to the Texians' rising frustration with Mexican dictator Santa Anna, the Mexican Army sent a contingent of 100 dragoons to retrieve it. The Texians rounded up volunteers to repulse the Mexicans under their makeshift banner with an image of the cannon on it and the words "Come and Take It." On October 2, the Texians and the Mexican Army faced off. The Texians fired their cannon and charged. The Mexican Army withdrew, suffering at most two fatalities. One Texian received a bloody nose when he fell off his horse. Although not a significant battle to say the least, this skirmish marked a point of no return. ##### **The Battle at San Antonio** Stephen F. Austin was in command of the volunteers that constituted the "Texian Army." He led his volunteers to San Antonio, where General Martín Perfecto de Cos, the brother-in-law of Santa Anna, had arrived and taken over The Alamo as his command center. The Texian volunteers decided to use Mission Concepción, just down the road from The Alamo, as their headquarters. The Texian Army wasn't a disciplined lot, and the lack of active fighting led to boredom among the troops, which led to lots of heavy drinking. At a point when the Texian Army was in danger of collapsing in total disarray, Stephen F. Austin was called to San Felipe, where a "Consultation" of the Texian colonists had been meeting. Edward Burleson, a veteran Native American fighter, was elected as the Texian Army's new commander in his absence. Burleson ordered an attack on San Antonio on December 3, but the troops refused to obey. Burleson decided to pull the troops out of San Antonio and winter in Goliad. Then one man stepped up and changed history. Benjamin Rush Milam, disgusted with the decision to withdraw, went through the remaining troops with the cry: "Who will follow old Ben Milam into San Antonio?" About 300 of the remaining volunteers joined Milam in an attack that began on December 5, 1835. The battle lasted three days with the Texians fighting house-to-house, cutting holes through the adobe walls to advance and gain control of San Antonio. They inflicted 150 casualties on the Mexican forces but not without loss of their own. Ben Milam himself was killed by a shot through the head on the third day of the battle. Mexico's past meets San Antonio's present in HemisFair Park. **Texas History Through the Flag** Texas has had a very interesting history filled with drama, power struggles, wars, and uprisings. From being Spanish territory to being part of Mexico to being its own republic, the state has worn many hats and flown banners of many different colors. In all, Texas has had eight changes in sovereignty and six different flags. The state flag that is in use today is the same flag that was used during the Republic of Texas period. This flag has become a popular iconic symbol, indelible in its simplicity. It's just red, white, and blue, with a large "Lone Star" on the left. A great way to see this radically shifting history is through the various incarnations of the flag that have flown over the state. • Spanish (1519-1685) • French (1685-1690) • Spanish (1690-1821) • Mexican (1821-1836) • Republic of Texas (1836-1845) • United States (1845-1861) • Confederate States of America (1861-1865) • United States (1865-present) On December 9, General Cos retreated back to The Alamo, where he chose to surrender. The Texians were generous and allowed General Cos and the Mexican troops to leave Texas with the promise not to "oppose the re-establishment of the Federal Constitution of 1824." Interestingly, the Texians weren't fighting for total independence from Mexico. They just wanted to be free from the dictatorial government of Santa Anna. ##### **The Battle at The Alamo** After Cos surrendered, most of the Texas Army of volunteers just went home. Approximately 100 defenders remained in The Alamo. The Consultation of 1835 had created a Texas regular army on paper and made Sam Houston commander in chief. The problem was that the regular army had no soldiers and the volunteers already in the field were not under Houston's command. The bigger problem was Santa Anna. Shortly after the new year of 1836, Santa Anna crossed the Rio Grande with an estimated 4,000 troops as well as cavalry and artillery, with the goal of punishing the Texians. The Texas Army at this time consisted of the 100 men in The Alamo and about 400 men under the command of James Fannin in Goliad, with Sam Houston as commander in chief. When Houston received word that Santa Anna had crossed the Rio Grande, he sent a courier to The Alamo with orders to remove the cannons, destroy The Alamo, and proceed to Gonzales. Sam Houston's order to abandon The Alamo was not carried out. Nineteen cannons that had been captured from Cos bolstered the Alamo defenses. Seeing that The Alamo could be defended, Houston's orders were overruled, and William Barret Travis was sent from San Felipe to reinforce The Alamo. In February of 1836, Travis reached The Alamo, but he only had with him an additional 29 men. David Crockett arrived from Tennessee about the same time in response to the call to arms. The Alamo's departing commander, James Neill, put Travis in charge. The men, however, were used to electing their leaders and chose Jim Bowie, who was popular among the resistance. Bowie and Travis compromised by agreeing to a joint command with Bowie commanding the "volunteers" and Travis the "regular" army. On February 24, Bowie ceded full command to Travis when he became seriously ill to the point of being bedridden. By this time Santa Anna's troops had made their appearance in San Antonio and the siege of The Alamo had begun. Santa Anna marked his arrival by raising a red flag above San Fernando Cathedral and demanding an unconditional surrender. Santa Anna had issued a decree that anyone rebelling against his rule was a "pirate" and should be shot. Captured pirates were not entitled to the status or protection afforded prisoners of war. The red flag meant "no quarter" would be given to any prisoner. Travis responded with a shot from his 18-pound cannon, the largest in The Alamo. The siege of The Alamo lasted 13 days and ended in the early-morning hours of March 6, when Santa Anna's troops overwhelmed the Alamo's defenders. Travis was one of the first to die, when shot through the head. Bowie was killed in his bed in the chapel, and Crockett most likely died while defending the wooden palisades erected just outside the entrance to the chapel. The Mexican _alcalde_ (mayor) of San Antonio, Francisco Antonio Ruiz, put the death toll of the Alamo defenders at 182. The number of Mexican losses will never be known for sure, but modern estimates place Santa Anna's casualties in the range of 600 dead and wounded. The importance of the battle of The Alamo as a military feat can be debated. What cannot be debated, however, is that The Alamo let all Texians know they were in a battle to the death, and it inspired them with a rallying cry and thirst for vengeance that they carried with them to victory at San Jacinto. ##### **The Battle at San Jacinto** The Consultation of 1835 called for a convention to meet at Washington-on-the-Brazos on March 1, 1836. On March 2, the delegates to the convention declared Texas a "free, sovereign, and independent republic." The news of the Declaration of Independence did not reach The Alamo before it fell, but the defense of The Alamo certainly gave the convention delegates the time and opportunity to meet and allowed the Republic of Texas to be born. The real military prize for Santa Anna was obtained after The Alamo, at Goliad. As Santa Anna marched on San Antonio he sent a smaller force under General José de Urrea on a southerly route through the populated areas of Texas toward Goliad. Houston ordered Goliad to be abandoned, but the 400 men under the command of James Fannin left too late. Just six miles outside of Goliad the Texians were surrounded and caught by Urrea's troops. After a brief and ferocious battle, Fannin accepted his fate and sought surrender under favorable terms. He surrendered after receiving what he thought were assurances that his men would be treated as prisoners of war. Fannin and his men were marched back to Goliad and imprisoned in the chapel at the Presidio La Bahía. Urrea reported the capture of Fannin and his men to Santa Anna and requested clemency for them. Santa Anna replied with a direct order to execute all the prisoners. At sunrise on Palm Sunday, March 27, 1836, the order was carried out and the men were marched out of the presidio and shot. After the initial volley of fire, 28 prisoners escaped to the woods and lived to tell the tale of the massacre. The dead counted 342, including Fannin. Fannin had requested only two things from his captors when he learned he would be executed: that he not be shot in the head and that his personal belongings be sent to his family. Fannin was not marched out of the presidio with his men. He was executed just outside the chapel by a shot to the head. His executioners stole his personal effects. Texas was now virtually defenseless, with no army in the field. Houston went to Gonzales and rounded up several hundred men that had gathered, originally with the idea of trying to relieve The Alamo. When word reached Houston that The Alamo had fallen and Santa Anna was approaching with as many as 5,000 troops, Houston, not wanting to defend fixed positions against overwhelming odds, decided to retreat. He burned the town and sank what few cannons were available in the Guadalupe River. Within days, he learned that the Texians at Goliad had all been executed and that his men were the only hope of survival for the fledgling Texas republic. Houston retreated to the east, passing over the Guadalupe River, the Colorado River, and the Brazos River. Many of his troops and commanders didn't like the tactic, as they wanted to fight and avenge The Alamo and Goliad. Santa Anna believed Houston and his army would not fight and were fleeing to the safety and protection afforded by United States troops at the Louisiana border. But when Houston learned that Santa Anna's force was fewer than 1,000 men, he shadowed it to Harrisburg, near present-day Houston. Santa Anna failed to capture the officials that now made up the Texas government in Harrisburg. They fled again to what was called "New Washington" on Galveston Bay. Eventually, Santa Anna and his troops, along with Houston and his troops, arrived on the San Jacinto River, where they faced off in open prairie of several hundred yards. On the morning of April 21, General Cos arrived with an additional 500 men. Santa Anna's forces now numbered over 1,300 while the Texas forces numbered almost 900. Santa Anna, assuming he would have to attack the Texians, let Cos's men rest after their long march while he awaited the arrival of his remaining troops. Houston, on the other hand, held his first council of war. He and his commanders decided to take the offensive. The Texians formed their line on the prairie around 3pm. The line included two small cannons (called the Twin Sisters) and a cavalry contingent under the command of Mirabeau B. Lamar. The Mexican troops were not expecting offensive operations, and many were enjoying their siesta. The Mexican sentries on duty detected the advance and opened fire with muskets and a 12-pound cannon. Most of the fire was without effect. The Texians were crouching low in the grass and were advancing through a small depression in the prairie. While riding his horse, Sam Houston was hit by a musket ball that fractured his leg just above his left ankle. The Twin Sisters fired once on the Mexican breastworks, and Houston led his men to within 20 yards of the Mexicans when the order to fire was given. After the one volley, the Texians did not reload but charged ahead. The Mexican line broke and ran. The battle lasted only 18 minutes, but the killing lasted until it was almost dark. The Texians, yelling "Remember the Alamo, Remember Goliad," ran down the fleeing Mexicans, clubbing and knifing them to death. Many were trapped in low wetlands where the Texians could reload and fire upon them from the dry shore as they struggled to get free from knee-deep mud. Houston tried to stop the slaughter, but most of his troops ignored his pleas. In all, the Texians killed 630 Mexican soldiers and captured another 730. The Texians had only two killed on the day of the battle; six more died later from the wounds they suffered. Santa Anna was captured the following day dressed in the clothes of a common soldier. When he was brought into camp, his true identity became known because the soldiers began addressing him as "El Presidente." He was brought before Houston. Many of the Texians wanted to kill him immediately, and there was no shortage of volunteers for the job. Houston, however, knew that Santa Anna was more valuable alive than dead. The remaining Mexican Army, which had more troops than were present at San Jacinto, was only miles away. Houston forced Santa Anna to sign a treaty that called for the Mexican Army to return to the other side of the Rio Grande. The freedom of Texas from Mexico won at the San Jacinto River led to annexation and the Mexican War, resulting in the acquisition by the United States of the states of Texas, New Mexico, Arizona, Nevada, California, and Utah, and parts of Colorado, Wyoming, Kansas, and Oklahoma. Almost one-third of the present area of the American nation, nearly a million square miles, changed sovereignty. #### **REPUBLIC OF TEXAS (1836-1845)** With the defeat of Santa Anna at San Jacinto, the Texians had at last been freed from the tyranny of the oppressive Mexican government. The land of Texas was theirs. Immediately a government was put in place. Within months voters of the new republic chose their first elected official. Sam Houston was elected president of the Republic of Texas, and he established the capital at his namesake city in eastern Texas. Shortly thereafter the first Congress of the Republic of Texas convened. Voters also overwhelmingly approved a referendum requesting annexation by the United States, but U.S. president Martin Van Buren refused to consider the request. **Birth of the City of Austin** Before the birth of the City of Austin, there was nothing at the location other than a low-water crossing on the Colorado River, where the Congress Avenue Bridge is today. To the east was blackland prairie, and to the west of the Colorado were the limestone hills marking the beginning of the Hill Country. Immense herds of buffalo migrated south from the Panhandle region following the Colorado River through Central Texas. In the early 1800s the Mexican government decided to allow Anglo-American settlers to immigrate to this part of Mexico to help populate the region and provide a buffer against Native American attacks on the town of San Antonio. Those early American settlers loved to hunt buffalo, and many quickly discovered the location on the Colorado where the buffalo herds would cross. These hunters set up campsites at the crossing, which grew into a small community that was known as Waterloo. One of those early buffalo hunters was Mirabeau B. Lamar. Years later Lamar was elected the second president of the Republic of Texas and chose the buffalo campsite of Waterloo as the location of the capital. A year later the Republic of Texas was officially recognized by the United States, and later by some European countries. The new republic faced many problems. The economy needed attention, local Native American tribes were fiercer than ever, relations with the United States had to be developed, and Mexico was itching for a war. General Santa Anna was in custody and the public demanded he be executed. Wisely, Houston kept him alive and eventually released him. In 1838 Mirabeau B. Lamar was elected president. He was notorious for spending lavishly and exacerbating problems with Native American tribes. Since he detested Sam Houston, he refused to reside at a capital named Houston. Therefore, the need arose to find a new capital for the Republic of Texas. Many communities wanted that honor, but not one was the clear favorite. As a result, Lamar decided to create a new capital where no city existed before. The site he chose was a buffalo hunting camp. In 1839, a new capital city was laid out between Waller Creek on the east, Shoal Creek on the west, and the Colorado River on the south. The original 200 residents of Austin resided in log cabins along the street that was grandly called Congress Avenue. Unfortunately for the settlers of early Austin, this part of Texas was Comanche territory (as well as buffalo territory) and thus Austin was a very dangerous place to live. The diaries of the early settlers confirm that many were killed and scalped when they strayed beyond the immediate confines of the capital city. Many times the Comanches came into the city itself to wreak havoc and terrorize the citizens. In 1841, Sam Houston was reelected president and quickly decided to move the capital back to Houston. Houston was pro-Native American and thought it was a ridiculous idea to stir up the Comanches by creating a capital in the middle of their territory. Furthermore, the Colorado River was not navigable that far upstream. Therefore no steamboats could travel to the capital city, leaving it quite isolated. Houston, a savvy politician, knew that the 200 residents of Austin would not be in favor of moving the capital, so he devised a plan to move it without their knowledge. He sent some Texas Rangers with a couple of wagons down to Austin with orders to sneak into town in the middle of the night, load up the archives of the republic, and take them back to Houston. Where the archives resided, so would reside the capital. All went well with this plan, and the archives were loaded up and moved out of town late one night. However, one woman, Angelina Eberly, remained awake. She was the proprietress of the Bullock Hotel, located on the northwest corner of 6th Street and Congress Avenue. She investigated what was going on, quickly discovered that the town had been robbed of the archives, and fired the cannon that the city had for protection against the Native Americans. The firing of the cannon woke up the community, and a large group armed themselves, mounted their horses, and rode out after the Rangers. They caught up with the wagons and at gunpoint turned them around. The archives headed back to Austin and the incident would forever be known as the "archives war." Thus, in spite of Sam Houston, the "Hero of San Jacinto," the archives remained in Austin and so did the capital. Houston may not have been successful in moving the capital from Austin, but he was successful at obtaining annexation. Houston courted Great Britain and France and both became interested in the idea. However, the United States was very uncomfortable with the prospect of a British or French presence in the middle of the country and quickly moved to annex Texas. In 1845 annexation to the United States took place and the Republic of Texas was dissolved. #### **ANNEXATION (1845-PRESENT)** The entry of Texas into the United States sparked the Mexican-American War. Mexican officials were angered at Texas's annexation because they felt the region was under negotiation. By this point, the relentless General Santa Anna had gained power in Mexico and felt it was time to take his revenge. The war lasted for two years and came to a close in 1847, when U.S. troops gained control of Mexico City. ##### **Settlers, Slaves, and Cowboys** In the 1850s the population of Texas almost doubled. This rapid growth came about primarily because of Germans and African American slaves. A significant number of German immigrants made their way to Texas, with the largest population moving to the Hill Country. They brought with them German culture, customs, and traditions. The other factor in the dramatic rise of the population came from folks migrating to Texas from the southern states, bringing with them thousands of slaves. Slavery wasn't customary in Texas until these wealthy slave-owners introduced the practice. During the Civil War (1861-1865), Texas seceded from the United States and joined the Confederate States of America. Texas contributed food, supplies, and some 80,000 men to the Confederate war effort. Although most of the battles took place outside of Texas, the Civil War left an indelible scar on the Lone Star State. With slavery abolished following the war's end in 1865, blacks did gain some rights, but they were limited. It was at this time that Texas found its calling in ranching. With the advent of the railway and the state's abundance of land, Texas's identity as ranching and cowboy country quickly developed. Land barons, businesses, and money poured into the state, and small pioneer towns quickly grew into cities. ##### **The 20th Century** In the second half of the 19th century oil was discovered in east Texas, but it was nothing to shake a stick at. It wasn't until 1901, when a drilling site east of Houston exploded with a gusher of oil, that Texas realized it was sitting on an abundant and extremely valuable natural resource. Just a few years later, Henry Ford was making his automobile available to the mass public. With millions of barrels of black gold shooting out of the ground, and amid great demand for the resource, oil made Texas rich. Although oil moguls scooped up a lot of this wealth, the tax revenues spilled into all aspects of local and state government. Schools were built, roads were paved, and homes were constructed. Then, with the fall of the stock market and the Great Depression in 1929, the state's progress and flow of money came to a screeching halt. The demand for oil hit rock bottom as the market became glutted and common people couldn't afford to fuel a car, much less own one. A section of Texas became part of what was known as the Dust Bowl, an area in the Southern Plains that was afflicted with severe drought, poverty, and agricultural decline in the wake of the Great Depression. Texas found its way out of the Great Depression during World War II, when several military bases were established. With the manufacturing industry on the rise and the federal government spending money in Texas, the state slowly regained its wealthy and influential status. Oil value increased and production followed right in step. The following two decades saw growth in the state's economy, population, and recognition. Texas remains a major oil producer and home to several massive military bases and facilities. Although ranching isn't as prevalent as it was in the past, the tradition still carries on. ### **Government and Economy** #### **POLITICS** Being the capital of Texas, Austin is the hub of the state's politics. The legislature meets every other spring and consists of a 31-member senate and a 150-member house of representatives. Texas had traditionally been a Democratic state, but this dramatically changed when George W. Bush became governor and later when he was elected president of the United States. Following Bush's election as president, Republican Rick Perry became the governor of Texas. Several problems plague the politics of the state capital. First, the legislative process is famous for getting bogged down and for not achieving its goals. Special legislative sessions are often called to try to tackle these important issues, but the "special sessions" often end with nothing getting accomplished except taxpayer dollars being spent while the feuding legislators get nothing done. Another problem in Texas politics is big business. It should come as no surprise that politics and business are fast friends, but in Texas this is downright cultural. Texas is home to some of the nation's largest and most powerful businesses, and their agendas are consistently integrated into legislation, right under the noses of the unvigilant and unaware public. #### **ECONOMY** The economy of Central Texas used to hinge on ranching and cotton, but today the region's main industries are higher education, government, and high technology. Top employers in Austin include the University of Texas, Dell Computers, the City of Austin, Motorola, Seaton Healthcare Network, and IBM. The economic force that people most associate with Austin is the high-tech industry, which took root when IBM moved here in the 1960s. Since then, Motorola, Texas Instruments, and Dell Computers have chosen Austin as their home. Today high technology is the third-largest industry in the region, and Central Texas is a major player on the global computer and technology scene. In recent years an economic shot in the arm has been coming from the movie industry. This burgeoning interest in Austin is for good reason. Filming and production work in Austin is less expensive than in the big cities, and the industry folks here are friendly. Films made in and around Austin include _Dazed and Confused, The Alamo, The Faculty, Texas Chainsaw Massacre I_ and _II, Miss Congeniality I_ and _II, Second Hand Lions, Spy Kids, Slacker, Waiting for Guffman, Office Space, How to Eat Fried Worms, Sin City, Machete, Boyhood, True Grit, Transformers,_ and many more. In addition, TV series such as _Friday Night Lights_ have been made in Central Texas. Lastly, one can't talk about Austin's economy without mentioning the music industry. Although there's no real "industry" to speak of, such as record companies, music executives, and tall buildings where musicians sell their souls, live music is a big source of revenue for the city. In 2012-2013, the music industry brought in an excess of $856 million per year, never mind the boost music gives the tourism industry. With high-profile festivals such as SXSW ($218 million) and Austin City Limits Festival ($102 million), live music revenue is something the city relies on. ### **People and Culture** Texans are bold, brash, and full of bravado. The bravado, however, is tempered with a large dose of hospitality and friendliness. The state's motto, "Friendship," has historical linguistic origins, but it is also reflected every day in its people. Who and what a Texan is can be summed up by two popular bumper stickers. One identifies the car's occupant as a "Native Texan" while the other boasts, "I wasn't born in Texas but I got here as fast as I could." To qualify as a true Texan you don't need established bloodlines like the Virginia planter class or the Brahmins in Boston. In fact, the founding fathers of Texas, almost to the man, came to Texas because they were running from the law, debts, failed careers, or failed marriages. Most will agree that being Texan is open to all classes, all races, and all religions. It is a spirit and an attitude, coupled with a pride associated with a special place that was conquered and cultivated by strong-willed and independent-minded people. Texan pride is due in no small part to the fact that Texas was created in a revolution against a brutal dictator and stood alone for almost 10 years as an independent nation. Texas joined the United States in 1845 as a result of a treaty between two sovereign nations, not because it was a conquered territory or constituted land purchased from a European power. It is understandable that the original Texans were proud of what they created and have passed on that pride to future generations and new arrivals. That is why as you travel around Texas you will see the Texas flag displayed prominently by its people at their homes and businesses. The strongest cultural influences that have informed Central Texas character come from Mexico and Germany. Mexico should come as no surprise, as the border is so close, and Latino heritage reaches far back into the state's history, but people are often surprised at the German heritage. Both cultures combined have shaped the cultural landscape. The Latino cultural and historical presence is especially apparent in Austin and San Antonio, where most of the food, art, and music draws heavily from Latino culture, and the German heritage is strongest in the Hill Country, where folks still dance to polka and eat schnitzels. One strong reminder of both German and Mexican heritage is in the regional Latin music, which features the accordion, introduced by early German pioneers. #### **POPULATION** The populations of Austin, San Antonio, and the Hill Country are largely composed of whites/Caucasians and Hispanics. Austin's significant demographic figures as collected during the last major census in 2010 are as follows: 49 percent white/Caucasian, 35 percent Hispanic, 8 percent African American, 8 percent other. San Antonio's demographics from the 2010 census are as follows: 63 percent Hispanic, 27 percent white/Caucasian, 7 percent African American, 3 percent other. #### **RELIGION** Religion is a major part of life in Texas. Beliefs and values are unquestionably integrated into secular culture, and a church-based way of life is the accepted norm. Texas is at the westernmost reaches of the Bible Belt, the region of the United States made up of communities that are predominantly Protestant and Evangelical. There isn't a definitive boundary for this belt, but most agree that it stretches from Dallas, Texas, down to Austin, which is at the western reaches, and continues east through the South. Although only part of Texas is in what's considered the Bible Belt, the Bible is the basis for beliefs and ideologies for the majority of Texans. According to _Churches and Church Membership in the United States,_ Texas has the most Evangelical Protestants in the nation, with California a distant second. Texas rankings with other religions as compared to the rest of the United States are as follows: third-largest number of Catholics, third-largest number of Buddhist congregations, fifth-largest number of Muslims, fifth-largest number of Hindu congregations, and tenth-largest number of Jews. At least 55 percent of Texans adhere to a particular religion. Being the most liberal piece of Texas, Austin has the most diverse representation of religions and is perhaps the most accepting and tolerant. San Antonio, on the other hand, is predominantly Catholic. This should come as no surprise due to its Mexican history and the proximity to the border. #### **LANGUAGE** The predominant language spoken in Central Texas is English. This may sound simple to those familiar with the language, but newcomers beware—the version of English expressed here isn't always as it seems. Besides being famous for their unique accent, Texans also have a tendency to pronounce words in a creative way. The most widely known example of this is the word "y'all." Although not exclusively Texan it has become synonymous with the state. Along with this, there's a long list of weird pronunciations that first-timers will encounter. At first this approach to English is amusing and takes a little getting used to, but its charm will win you over. Due to Central Texas's rich Mexican history and Latino and Hispanic culture, the Spanish language comes in a close second to English. Most Texans speak a little Spanish and many are fluent. The infusion of Spanish into Central Texas culture has created a unique lexicon that is to be found nowhere else. Spanish words have merged into the Texas lexicon and have taken on their own meaning. For example, the Spanish word _grande_ is pronounced like "grand" (e.g., Rio Grand), and Guadalupe is pronounced "gwada-LOOP." In Spanish "ll" is pronounced like "y," but no one would dare pronounce Amarillo with a "y" sound. The list of weird idiosyncrasies is long and amusing. Travelers, especially those with a background in Spanish, should try to go with the vernacular flow. #### **MUSIC AND ART** Music is a major part of the life and culture of Central Texas. Austin is the Live Music Capital of the World and San Antonio is considered the home of Tejano and conjunto music. I won't speculate as to how music and Austin became synonymous, but I will say that Austin has been greatly blessed in its calling to live music greatness. Today Austin is compulsive about music. Throughout the year Austin's hundreds of venues, bars, and clubs are full of touring national acts, local favorites, and wannabes seeking expression and recognition. Although the city is smack-dab in the middle of Texas there isn't much "tractor pop" (modern country) to be heard here. Austin is an independent artist and songwriter paradise that transcends all genres by offering music by the people, for the people. The scene is both diverse and tolerant, and most music fans here don't subscribe to any one genre. Austin may be known for its contribution to live music, but San Antonio and the Hill Country are known for Tejano and conjunto music. This unique form of music is the direct result of the Spanish, Mexican, Texian, and German cultures mixing over the course of two centuries in Central and South Texas. The final product is a Tex-Mex music that blends traditional Mexican forms such as the _corrido_ and the Western/European waltz and polka introduced by German and Czech settlers in the late 19th century. The most distinct element of this music is the accordion, which was introduced by the German settlers. Today Tejano and conjunto music reflects influences from rock, blues, and _cumbia,_ and has gone from being a local and ethnic form of music to its own genre with wide appeal in North America, Latin America, and Europe. At the core of Tejano and conjunto are songs about drinking, love, heartbreak, and dancing. Popular artists that have either pioneered or popularized the Tejano sound are Narciso Martinez, Isidiro Lopez, Joe Lopez y El Groupo Mazz, and Flaco Jimenez, who can still be seen performing around Austin and San Antonio. Folk art is second only to music in Central Texas. Although it is something that is not easily defined, it is widely accepted as simply art by and for the folk. In Austin folk art is pop paintings of Hank Williams Sr. on old fence boards, or junk from the landfill and car graveyards that is painstakingly fitted together to form a postmodern apocalyptic "sculpture," or retro-style neon signs mounted on tin with catchy statements that echo sentiments of the obscure, or a thought-provoking social/political painting of Elvis wired to light bulbs. In San Antonio a similar modern approach is taken to folk art, but with one difference—replace Elvis with the Virgin Mary. All the above expressions of folk art can be found in galleries, shops, boutiques, and restaurants, on urban walls, and in people's front yards all over Austin, San Antonio, and in some Hill Country towns. You'll know it when you see it. Elvis souvenir at the general store in Fredericksburg ## **Essentials** Transportation GETTING THERE GETTING AROUND ON THE ROAD Travel Tips WHAT TO PACK CONDUCT AND CUSTOMS WOMEN TRAVELING ALONE SENIOR TRAVELERS TRAVELERS WITH DISABILITIES GAY AND LESBIAN TRAVELERS TRAVELERS WITH CHILDREN Health and Safety FLOODS, LIGHTNING, AND TORNADOES SEASONAL ALLERGIES THINGS THAT BITE CRIME example of the "Don't mess with Texas" antilittering campaign. ### **Transportation** #### **GETTING THERE** Austin, San Antonio, and the Hill Country, collectively known as Central Texas, is situated in the heart of the state, which is in the heart of the United States. Getting to the region is easy and affordable for domestic travelers. One can drive in by car from another region in the United States. This is the classic way of traveling, often referred to as the road trip, and it can be nostalgic and adventurous. However, most travelers fly in to either Austin or San Antonio on one of the major airline carriers. ##### **Air** The main airports for the region are located in Austin and San Antonio: **Austin-Bergstrom International Airport** (300 Presidential Blvd., 512/530-2242, www.austintexas.gov/airport) and **San Antonio International Airport** (9800 Airport Blvd., 210/207-3433, www.sanantonio.gov/airport). Choosing which airport to arrive at depends on what you plan on doing in the region. If you plan on staying in Austin and sticking with the urban experience of live music and summer festivals, with a quick side trip to the nearby Hill Country, you should fly in to Austin-Bergstrom International Airport. If you plan on staying on the San Antonio River Walk, or going to SeaWorld, or traveling to the farther reaches of the Hill Country, you should fly into San Antonio International Airport. Austin's airport is a converted air force base. It offers international connections that can get you anywhere in the world. Major passenger airlines include America West (800/235-9292), American Airlines (800/433-7300), Delta (800/221-1212), Frontier Airlines (800/432-1359), Southwest (800/435-9792), and United (800/241-6522). San Antonio International Airport is the region's largest airport and is an international hub with both direct flights and domestic connections that can get you anywhere in the world. Nonstop flights are offered to 41 destinations, mostly major U.S. cities and a couple of cities in Mexico. Passenger airlines that service the airport include Aerolitoral (800/237-6639), America West (800/235-9292), American Airlines (800/433-7300), Delta (800/221-1212), Mexicana (800/534-7921), Midwest (800/452-2022), Southwest (800/435-9792), and United (800/241-6522). ##### **Bus and Train** Although traveling by air is often more practical, travel by bus or train may offer a more adventurous and colorful experience. **Greyhound** (800/231-2222, www.greyhound.com) bus lines and **Amtrak** (800/872-7245, www.amtrak.com) train service both have stations in Austin (Greyhound: 916 E. Koenig Ln.; Amtrak: 250 N. Lamar Blvd.) and San Antonio (Greyhound: 500 N. St. Mary's St.; Amtrak: 350 Hoefgen St.). Fares are anywhere from $11 to $36 to get from one city to another. ##### **Car** Because Texas is so darn massive, driving to Austin, San Antonio, or the Hill Country can be tedious. Depending on where you are coming from, the drive can be miles of straight and boring roadways with scorched and desert-like landscapes. Some stretches of highway are almost hypnotizing; be careful not to let yourself get sleepy. Also, filling stations and food can be scarce, especially in some East Texas regions. As you get closer to Central Texas, gas stations, roadside barbecue shacks, and rest stops become more frequent. Once you arrive in either Austin or San Antonio, Interstate 35, which is the primary highway that connects the two cities, can be backed up for miles at morning and evening commute hours. For both cities, it is best to plan your arrival time so as to avoid rush hour. #### **GETTING AROUND** Once you have arrived in Central Texas, getting around can require some planning. If you plan on staying in either Austin or San Antonio, renting a car is highly recommended. If you prefer not to rent a car but wish to explore the area, you will quickly discover the challenges of a region that doesn't have a cohesive public transportation system. Greyhound bus line and Amtrak train system are the two primary ways to hop from one city to the other. Getting around by car can provide the most freedom, and the best way to make the most of your time. There are only a few major freeways in the Austin metropolitan area, and only a few primary highways that connect Austin to the Hill Country and San Antonio. One minor drawback to using a car is downtown parking and freeway congestion in Austin and San Antonio. Interstate 35, which connects the two cities, can be backed up for miles at morning and evening commute hours. For both cities, it is best to plan any road trip or highway travel around these times. All the usual rental car companies are represented at both Austin-Bergstrom International Airport and San Antonio International Airport, as well as around town. Car rental agencies include Advantage Rent-A-Car (800/777-5500), Alamo Rent-A-Car (800/462-5266), Avis Car Rental (800/331-1212), Budget (800/527-0700), Dollar Rent-A-Car (800/800-3665), Enterprise (800/261-7331), Hertz Rent-A-Car (800/654-3131), National Car Rental (800/222-9058), and Thrifty (800/847-4389). As a region, most towns are 30 miles apart or less. Gas stations and mini-markets are easily found along routes between Austin and San Antonio, and throughout the Hill Country. You don't need to sweat filling up with a tank of gas at every town (unless you are driving a gas-guzzler). That said, when you're in a small town and you're running below half a tank, it's a good idea to fill 'er up. Also, if you plan on hitting the road, it's always a good idea to stock up on some food, snacks, and water before heading out. #### **ON THE ROAD** Folks in Central Texas drive very differently from folks in the rest of the country. The hospitality Texans are famous for definitely carries over to the streets. They can be some of the slowest, most patient, courteous drivers in the nation. Central Texas driving philosophy is summed up on a road sign seen throughout the state that says, "Drive Texas friendly." People who are used to roadway customs such as honking, aggressive driving, and a general lack of patience should try to slow down and take their time. ##### **Driving Courtesy** People on the roads of Central Texas are remarkably courteous. The two most important customs regarding this are waving and letting other drivers go. Locals have the hospitable practice of waving when changing lanes, when passing on two-lane roads, and sometimes for no reason at all. The rule of thumb for waving is, the smaller the road the more important it is to give people a nod or a wave. This simple howdy-with-the-hand is especially crucial in the Hill Country. It's also not uncommon to see people getting into courtesy stalemates at stop signs, waving on freeways, and holding up busy traffic to let someone in. Honking in Texas is a sign of an impending traffic accident, of a friend nearby, or of a child sitting behind the wheel of a parked car. People don't use the horn to say, "Get out of my way." Never start honking the second the light turns green; people will wonder what's wrong with you. If someone is sitting at a green light and not moving, be patient and just sit there until he or she starts moving. Road rage is a very rare occurrence here. **Central Texas Mileage** ##### **Traffic Police** The traffic police in Austin and the surrounding Hill Country are particularly notorious for being sticklers. Speed traps are unfairly set up all over the area, and unsuspecting folks who are good drivers are always getting tickets for going a little faster than the speed limit. Sometimes the speed cushion can be as low as four miles per hour over the speed limit. With this kind of speed enforcement, it's wise to drive at the speed limit at all times. For some reason police are particularly active on Sunday mornings when people are heading to church. This stringent enforcement creates piles of paperwork and loads of headaches. My suspicion is that some of this police zealotry is to increase city revenue, but maybe I'm just bitter because I got a speeding ticket recently. The Austin police are also known for going to dramatic lengths to catch people committing traffic violations by setting up sting operations. My favorite is the "beggar sting," when cops dress up like homeless beggars and stand at busy intersections for the purpose of peering into cars to look for laws being violated. The moral of the story: Drive with compulsive prudence while on Central Texas roads. ##### **Low-Water Crossings** Central Texas is prone to flash floods and mini-deluges. For some of the roads in the Hill Country this means flooding of roads and low-water crossings. In some cases these roads are designed to flood during heavy rains in order to divert water from buildings and communities. Never drive into a flooded roadway. You never have any idea how deep the water is or how fast it's moving. It doesn't take much more than a foot or two of water to sweep a car or an RV off the road and down the river. Every year people drive into these and get themselves into trouble. ##### **Freezing Conditions** People are surprised to hear that every year during winter there's an occasional freeze. When a freeze is in the forecast the city of Austin freaks out, schools close, and everyone hunkers down as if there will be nuclear fallout. Texans are the first to admit they are completely incompetent at driving on icy roadways. Although the city applies a chemical and gravel substance in order to prevent them, crashes, fender benders, and accidents are abundant. Bridges and freeway overpasses can be especially dangerous when icy. ### **Travel Tips** #### **WHAT TO PACK** When visiting during the warmer months bring lots of casual clothes. It is imperative to pack plenty of shorts, comfortable shirts, and sandals or flip-flops. Why lots of these, you may ask? Everything gets sweaty in a matter of minutes. In one day you can easily go through four changes of clothes: one for the morning, one for swimming, one for after swimming, and one for dinner out. If you'll be visiting the region between June and September, don't waste any room in your luggage with jackets, sweaters, or anything with long sleeves. Believe me, you won't get chilly, except for the kind that comes in a bowl. However, during the winter months, temperatures are sometimes near freezing, so be sure to bring warm clothes. #### **CONDUCT AND CUSTOMS** ##### **Texas Manners** In Texas chivalry, politeness, and manners are very much a part of everyday life. Men in Texas have a respect for women that harkens back to a bygone era. Opening doors for ladies, not talking vulgarly in their company, and addressing women with a respectful "ma'am" are customs that are alive and well. Cursing in public isn't as prevalent as it is in many other parts of the country, so it's best to keep the sailor talk to a minimum. Also, when walking down the street people look each other in the eyes and say "Hi." Yankees and West Coasters may take this the wrong way at first. If someone starts talking to you in line at the store, it doesn't mean they are mentally ill or they want your money. It's just good ol' Texas kindness. ##### **Tipping** An important part of the income of workers in the service industry comes from tips. It's considered rude to tip too little or with spare change. With the Texas minimum wage being a measly $7.25 an hour, don't be one of those cheapskates who tips low and tries to sneak out the back door. The following workers should be tipped based on the fare, bill, or fee: cab drivers 15 percent, restaurant workers 15-20 percent, bartenders 10-15 percent, bellhops $1 per bag. **Fast Facts for International Travelers** **Time:** Central Texas is in the central standard time zone (CST), which is GMT/UTC-6; one hour behind the East Coast and two hours ahead of the West Coast. **Measurements:** The metric system doesn't apply in the United States. Distances are measured in inches, feet, yards, and miles. **Weights:** Dry weights are measured in ounces (oz.) and pounds (lb.). **Temperatures:** Degrees are Fahrenheit, not Celsius. **Mail:** Currently domestic letters can be sent for $0.49, postcards for $0.34, and letters to most international destinations for $1.15 (except Mexico and Canada), but prices may change, so check with the post office. **Electricity:** The United States uses 110V to 120V at 60 cycles. Appliances brought from Europe or Australia won't work in the United States without a 110V transformer, which can be hard to find in this country. ##### **Liquor Laws** Liquor laws are the same throughout the United States when it comes to age and drinking and driving. However, specifics regarding what can be sold vary from county to county. Some counties in Texas prohibit the sale of distilled spirits, while others are totally dry. When it comes to these varying degrees of "dry," the counties where Austin and San Antonio are located are so wet they are drenched. You have to be 21 and older to drink in the United States, and driving while intoxicated is illegal, dangerous, and flat-out stupid. It's also illegal to have an open container in a vehicle. Also, note that you can't buy alcohol on Sundays or late at night—liquor stores close by 9pm and are closed on Sundays. ##### **Smoking in Public** Just a few years ago most restaurants, bars, cafés, and music venues had ashtrays on tables and a plume of smoke lingering in the rafters. Thanks to a growing concern for public health, Austin's smoking laws have been changing in favor of a smoke-free environment. Smoking is now prohibited in just about all indoor public places except for bingo parlors, pool halls, and bowling alleys. It was only in 2005 that voters banned smoking in music venues and bars, and only by a very narrow margin. ##### **Don't Mess with Texas** It's highly suggested that one not mess with Texas while visiting Austin. There are two meanings behind this directive. First off, don't litter. The popular phrase "Don't mess with Texas" was created as an antilitter campaign, which has been very successful. Because of this, the Lone Star State is beautiful and clean. The other meaning behind "Don't mess with Texas" is this: Don't slight, mock, dis, or make fun of the state in any way. Texans are very proud of their state and take great offense at people who come in from out of town and talk trash about Texas. #### **WOMEN TRAVELING ALONE** When traveling in Texas women should apply all commonsense safety precautions. It is no worse or better than other U.S. destinations in terms of risk. However, women who travel to Texas should be prepared for the duality of chivalry and chauvinism that can be found in Texan men. Women will find the "little darlin'" culture of Texas either charming or oppressive. The same guy who holds the door open for you might look you up and down as you walk past. In the hot summer months you won't want to wear much more than shorts and a T-shirt, yet the less you wear the more attention you will draw. #### **SENIOR TRAVELERS** Nearly all attractions and many hotels and airlines offer discounts for seniors. It is highly recommended to unabashedly ask for your senior discount wherever you go and whatever you do: It can save you a lot of money over the course of a week or two. What constitutes a senior? In most places a senior is someone over 60 or 65. #### **TRAVELERS WITH DISABILITIES** In Austin and San Antonio most attractions are easy to access. Austin is particularly easy to get around, as most of what's great about Austin is centrally located, and most museums, restaurants, and accommodations are wheelchair accessible. Although most San Antonio attractions are accessible, sights such as the Mission Trail and the attractions in Brackenridge Park are pretty spread out. The River Walk has a few accesses for wheelchairs and the city is continually improving access. As for the Hill Country, don't expect much in the way of easy access. Dirt roads, few wheelchair accesses, and just plain old rugged environs can slow you down and even be impassable. However, the bigger towns, such as Fredericksburg, Boerne, and New Braunfels, do have some ADA infrastructure. #### **GAY AND LESBIAN TRAVELERS** Austin is the one bastion of open-mindedness in the conservative state of Texas. The city boasts a strong, vibrant gay and lesbian community and the only kind of intolerance that's acceptable is of intolerance itself. This general open-mindedness has provided an excellent atmosphere for the gay community to flourish. With a wide array of clubs and venues, popular liberal bookstores, a viable presence in the _Austin Chronicle,_ and widely respected organizations that fight for gay rights in Texas, Austin is the San Francisco of the South. However, once you leave the Austin metropolitan area you're back in Texas. When it comes to safety, gay and lesbian travelers in Austin, San Antonio, and the surrounding Hill Country shouldn't worry. Although in the Hill Country people aren't necessarily accepting, they leave "different" folks alone. Outside Austin, public displays of affection will most certainly turn heads and possibly elicit a rude remark. #### **TRAVELERS WITH CHILDREN** Family is first in Texas, and people traveling with children will find this a great advantage when visiting the state. All restaurants, businesses, and attractions are very proud to be family oriented, which makes traveling with children easy. Folks in Central Texas love to compliment others on their children, so don't be freaked out if someone in line somewhere strikes up a conversation through a flattering remark about your child. When it comes to the necessities for children, such as food, bathrooms, and keeping them interested in the day's activities, Austin and San Antonio are full of resources. Food is easy here, as most kids like hamburgers and tacos, which can be found on every street corner; public bathrooms are easy to find and often outfitted with changing tables; and most attractions are family oriented. Traveling with children in the Hill Country takes a little more planning but can be well worth it. With family-oriented dude ranches, underground caves to explore, great state parks to run around in, and fun festivals held throughout the year, there's much here to create a lifetime of memories. Planning comes in handy because everything is a little spread out. Things to take into account are travel time, finding the appropriate accommodations, and making sure you land in town when the kids get hungry or need to go to the bathroom. ### **Health and Safety** #### **FLOODS, LIGHTNING, AND TORNADOES** The three biggest dangers in Central Texas are flash flooding, lightning, and tornadoes—the biggest being flash flooding. People refer to the region as "Flash Flood Alley" because every year there's an immense amount of water that gets dumped here. Moisture from the Gulf of Mexico and the rocky terrain of the Hill Country (covered by just a thin layer of soil) combine into excellent conditions for water to pour and collect. Flash flood watches and flash flood warnings are very common, especially in the spring. Most of Austin's infrastructure was designed specifically to avoid flooding danger. For example, the city has special five-foot storm drains everywhere as well as many massive culverts strategically placed throughout town. Lake Travis, the second-largest lake in the area, was designed as a flood-control lake. When all the regional rivers, such as Llano River, Colorado River, and Pedernales River, boil over with water they all dump it right into Lake Travis. The second-biggest danger is lightning, and the third is tornadoes. When a lightning storm is overhead, go indoors. Twisters are far down on the list of things to be paranoid about because they don't normally pass through the region with sustained force. The time to watch out for them is during and after a coastal hurricane. #### **SEASONAL ALLERGIES** According to many national surveys, Austin is one of the worst places in the United States for allergies. If you are prone to allergies, come prepared with your preferred medication or time your trip to avoid the worst periods. The peak allergy times are December-January (mountain cedar), March-April (oak), and September-October (ragweed). Adding to the irritation are numerous wildflowers and grasses. For day-by-day allergy levels and forecast information, check out www.kvue.com (click on the weather link, then the allergy forecast link). #### **THINGS THAT BITE** There are three main critters that bite humans in Texas: mosquitoes, chiggers, and venomous snakes. Mosquitoes are the most common and can be a nuisance during the spring and summer months. Few cases of West Nile virus have been found in Central Texas. If you plan on being outdoors for any length of time during the summer months it helps to have a mosquito repellent on hand. The most irritating of biting critters are chiggers (mites). These common skin parasites are found throughout the central part of the United States. They are members of the genus _Trombicula_. Chiggers are usually found in the highest numbers during the spring and fall in grassy areas. They are about the size of the head of a pin and are reddish orange in color. Their 50-day life cycle begins as an egg that's laid in soil and around vegetation. Larvae hatch from the egg and crawl onto a host animal, where they attach themselves, feed on fluids in the tissue for several days, and then drop off the host. Symptoms of chiggers include severe itching and irritation of skin. They prefer to attach in cozy lower regions of the body such as underneath sock bands, behind the knees, and around ankles. As gross as it may sound, the best treatment for chiggers is to let them run their course. One method of trying to get the little suckers to dislodge is to drown them in rubbing alcohol or cooking oil. The deadliest of all Texas creatures are venomous snakes, and the most common in Central Texas is the rattlesnake. They live under rocks, fallen trees, and in dark places in rural areas. People most often encounter snakes while hiking in parks and open spaces. Snakebites can be fatal, but if treated correctly and quickly you can survive. If you are bitten by a snake, there are a few things you should do. First of all, don't panic. Keep the area where the bite is stable and below the heart, and put a bandage over the infected area. Then quickly get to a medical facility. Antivenins are available and a full recovery is possible. If the snake that caused the bite is dead, and you have your wits enough about you to remember, bring the snake along as well. To help prevent snakebites, always be aware of your environment when in rural areas. Wearing hiking boots can help prevent contact with the venom and teeth of snakes. Along with insect and snakebites, there's one other danger to be aware of: rabies. Animals that carry rabies are raccoons, possums, skunks, dogs, cats, and bats. It's wise to avoid contact with any wild animals, no matter how cute they may look, because rabies can be fatal. #### **CRIME** For its size, Austin is a very safe place. It boasts low crime rates, especially for violent crimes such as homicide, assault, and rape. The crimes most committed here are burglaries of homes and cars and bike theft. San Antonio, on the other hand, has much higher crime rates. Although crime is less than in Dallas and Houston, San Antonio has enough crime to merit a gentle word of caution when exploring outside the downtown area, beyond the safety of the tourism infrastructure. When venturing into the outlying neighborhoods expect to see the seedier side of the city, and be a little more careful than normal. ## **Resources** Suggested Reading Internet Resources ### **Suggested Reading** Brands, H. W. _Lone Star Nation._ New York: Doubleday, 2004. The author brings to life the epic tale of the Texans' struggle for independence. All the great figures of the Lone Star State's history are brought to life, such as General Santa Anna, Stephen Austin, Davy Crockett, Jim Bowie, and Sam Houston. Brice, Donaly E. _The Great Comanche Raid._ Austin, TX: Eakin Press, 1987. Outlines one of the most famous Native American attacks in the Republic of Texas's brief history. Campbell, Randolph B. _Gone to Texas._ Oxford: Oxford University Press, 2003. This well-written tome on Texas history covers everything from the first arrival of humans in the Panhandle some 10,000 years ago to the dawn of the 21st century, offering an interpretive account of the land and the successive waves of people who have "gone to Texas." Favata, Martin A., and Jose B. Fernandez, eds. _The Account—Álvar Núñez Cabeza de Vaca's Relación._ Houston, TX: Arte Público Press, 1993. Perhaps one of the most insightful and historically important writings in early Texas history, this work documents the conquest of the region by both Spaniard and white man. Friedman, Kinky. _The Great Psychedelic Armadillo Picnic: A "Walk" in Austin._ New York: Crown, 2004. Famous humorist, author, and Texas politician Kinky Friedman takes the reader on a white-knuckle tour of Austin—poking, prodding, and overturning every social, political, and cultural rock in town. Greer, James Kimmins. _Colonel Jack Hays, Texas Frontier Leader and California Builder._ College Station: Texas A&M University Press, 1952. Tells the story of Texas Ranger Colonel Jack Hays, offering a peek into the pioneer Wild West version of Texas that has been immortalized in legend. Kownslar, Allan O. _European Texans._ College Station: Texas A&M University Press, 2004. Considers the contributions of those who immigrated to Texas from Europe in the early days of the state's history. Readers learn about the life and culture of French, English, Scottish, Irish, Dutch, Belgian, Swiss, Danish, Norwegian, Swedish, German, Wend, Polish, Czech, Hungarian, Italian, Greek, and Slavic Texans. Laird, Tracey. _Austin City Limits: A Histor_ y. Oxford: Oxford University Press, 2014. Chronicles the history of the longest-running musical showcase in the history of television, Austin City Limits, from Willie Nelson's pilot show through Season 35. Includes historical stories and anecdotes, including performances by BB King and Stevie Ray Vaughan, Bonnie Raitt, Johnny Cash, Ray Charles, Mumford & Sons, and Arcade Fire. Long, Joshua. _Weird City: Sense of Place and Creative Resistance in Austin._ Austin: University of Texas Press, 2010. Explores the social, political, and economic origins of Austin's obsession with being weird and hip, especially as it pertains to Austin's controversial "Keep Austin Weird" slogan and its attendant movement. Reid, Jan. _The Improbable Rise of Redneck Rock._ Austin: University of Texas Press, 2004. Chronicles the days when music hit Austin, Texas, in the early 1970s at now-legendary venues such as Threadgill's, Vulcan Gas Company, and the Armadillo World Headquarters. Smithwich, Noah. _The Evolution of a State or Recollections of Old Texas Days._ Austin: University of Texas Press, 1984. Read about Texas's early period from someone who was there. It covers the early days of Austin's colony to the aftermath of the Civil War. Some of the content may not be perfectly accurate but it does offer a personable glimpse into Texas myth, legend, and folklore. Wilbarger, J. W. _Indian Depredations in Texas._ Austin, TX: Eakin Press, 1985. A series of accounts of the turmoil on Texas soil when white men came along. The tales here are true accounts of the men involved in conquest and the desperate responses of the indigenous peoples being overrun and exterminated. ### **Internet Resources** **Austin Chamber of Commerce** **www.austinchamber.com** Includes general information about Austin. **_Austin Chronicle_** **www.austinchronicle.com** Comprehensive resource for music, arts, entertainment, classifieds, restaurant reviews, festivals, events, and weather for Austin. **Austin Convention and Visitors Bureau** **www.austintexas.org** Premier website for tourism in Austin. **Austin 360** **www.austin360.com** Online magazine with music, arts, and entertainment listings; restaurant reviews; festivals; and a calendar of events. **Culturemap Austin** **<http://austin.culturemap.com>** Website with Austin events calendar and stuff to do. **The Handbook of Texas—Online** **www.tshaonline.org/handbook/online** Texas state history and statistical information. **San Antonio Convention and Visitors Bureau** **www.visitsanantonio.com** San Antonio's primary resource for tourism information. **San Antonio River Walk** **www.thesanantonioriverwalk.com** Information about San Antonio's River Walk. **Texas Parks & Wildlife** **www.tpwd.texas.gov** The official Texas Parks & Wildlife site includes information on parks, camping, hiking, and park access and hours of operation. **Texas Tourism** **www.traveltex.com** The official site of Texas Tourism includes maps, guidebooks, highway information, and all tourism-related information about the Lone Star State. ## **Index** ### **A** Abendkonzerte: Admiral Nimitz Museum: Airman's Cave: air travel: Alamodome: , Alamo Drafthouse Cinema: , Alamo, The: , , , , alcohol: Allens Boots: , allergies: animals: Animal World and Snake Farm Zoo: 162-163 Antone's: , Antone's Record Shop: , Aquarena Center: Armadillo Christmas Bazaar: Arneson River Theatre: , art: 225-226 Art City Austin: AT&T Center: , Aus Chronicle Hot Sauce Festival: Auslander Biergarten: , , Austin: 25-121; maps 28-29, 34-35, , , , Austin and San Antonio, map of: 2-3 Austin Beerworks: _Austin Chronicle_ : , _Austin City Limits_ : , Austin City Limits Music Festival: , Austin Convention Center: , , Austin Film Festival: Austin Food and Wine Festival: Austin Free Week: Austin History Center: Austin International Poetry Festival: Austin Motel: , Austin Nature and Science Center: , , Austin Opera: Austin Pride Parade: Austin Reggae Festival: Austin Rock Gym: Austin Steam Train: , Austin Symphony: Austin Symphony 4th of July Concert and Fireworks: auto travel: 228-230 Aviation Museum of Texas: ### **B** Ballet Austin: Ballet Under the Stars: Bandera: , 150-153 Bandera County Kronkosky Library: Barton Creek Greenbelt: 87-88, Barton Springs Pool: , Bass Concert Hall: Bat Fest: bats: Austin 37-38; Hill Country 143-144 bats of Congress Avenue Bridge: , , 37-38 Battle Oaks: Becker Vineyards: , , beer/breweries: Austin ; Hill Country , , ; San Antonio , bicycling: Austin , , 87-89; Hill Country , , , , ; San Antonio 183-184, birds/bird-watching: , , , Blanco River: 159-160 Blanton Museum of Art: 38-39 Blue Hole: Blues on the Green: , Blue Star Brewing Company: boating: , Boerne: , 144-146 Boerne Village Band: 144-145 botanical gardens/arboretums: Austin ; San Antonio Brackenridge Eagle: , Brackenridge Park: 173-174, ; map Briscoe Art and Antiques Collection: Briscoe-Garner Museum: Broken Spoke: , , , Buckhorn Museum and Texas Ranger Museum: 180-181 Bullock Texas State History Museum: , , , bus travel: ### **C** Cactus Cafe: , , camping: Austin ; Hill Country , , , , , , , Capitol Visitors Center: Carnival Brasileiro: car travel: 228-230 Cascade Caverns: Cathedral of Junk: caves/caverns: Austin ; Hill Country , , , 146-147, Cave Without a Name: , , Celebrate Bandera: Center for Pacific War Studies: Central Austin: 46-49; map _charread_ (Mexican rodeo): children, activities for: 23-24 children, traveling with: Chisholm Trail Winery: Christmas in Comfort: Chuy's: , Circuit of the Americas: , climate: , , climbing: Austin , ; Hill Country , Comfort: 142-143 conjunto music: Contemporary Art Month: Contemporary Austin, The: 40-41 Continental Club: , , Cook, Abner: crime: Crockett, Davy: Cypress Valley Canopy Tours: , ### **D** Darrell K Royal-Texas Memorial Stadium: Devil's Backbone: Diez y Seis: disabilities, travelers with: Dodging Duck Brewhaus: , Donnan-Hill House: DoSeum: , Downtown Austin: 32-42; map 34-35 Downtown San Antonio: 175-182; map 176-177 Drag, The: Driftwood Vineyards: Driskill: , , Dry Comal Creek Vineyards & Winery: Duchman Family Winery: ### **E** East Austin: , East Austin Studio Tour: economy: 223-224 Edward Stevens Homestead Museum: Eeyore's Birthday Party: 1886 Café & Bakery: , electricity: Elisabet Ney Museum: emergencies: Austin ; San Antonio Emily Ann Theatre Butterfly Day: Emma S. Barrientos Mexican American Cultural Center: 41-42 Emo's: , Empire Theatre: Enchanted Rock State Natural Area: , 141-142, End of an Ear: , etiquette: ### **F** Fado's: , families, activities for: 23-24 fauna: Fiesta San Antonio: , fish/fishing: Austin ; Hill Country , , , , flora: Fort Martin Scott: Frank Erwin Center: , , , , Fredericksburg: , , 134-141; map Fredericksburg Brewing Company: Fredericksburg Food and Wine Fest: Fredericksburg Oktoberfest: , Fredericksburg Winery: Friedrich Wilderness Park: Fritos Corn Chips: Frontier Times Museum: , Fun Fun Fun Fest: , , ### **G** gay and lesbian travelers: geography: George Bush Gallery: George Washington Carver Museum and Cultural Center: Ginger Man, The: , Gish's Old West Museum: , Goat Cave Preserve: golf: Austin ; Hill Country ; San Antonio , government: Governor's Mansion: , , , , Grape Creek Vineyard: gratuities: Gristmill River Restaurant & Bar: , Gruene: , 163-166 Gruene Hall: , Guadalupe River: , , 156-158, ; map Guadalupe River State Park: , Guenther House: Güero's Taco Bar: , , Gus Fruh Trail Access: ### **H** Halcyon Coffeehouse: , , Halloween on 6th Street: Hamilton Pool Preserve: , , 128-130 Hamilton Pool Road: , 128-130 Hangar Hotel: , Harry Ransom Humanities Research Center: 39-40, Hartman Prehistoric Garden: , , haunting children, legend of: Hauptstrasse: , health: 234-235 HemisFair Park: , hiking: Austin , 87-89; Hill Country , , , , , , , , , , ; San Antonio 183-184, Hill Country: 122-166; map 126-127 Hill Country State Natural Area: Hippie Hollow: history: 211-223 Home Slice Pizza: , Hops and Grain: horseback riding: Austin ; Hill Country , , , , Hothkiss-Graham House: Hunters BBQ and Outdoor Expo: ### **IJ** Independence Brewing Co.: insect bites: 234-235 Institute of Texan Cultures: , international travelers: itineraries: 13-24 James Avery headquarters: Janey Slaughter-Briscoe Grand Opera House: Japanese Garden of Peace: Japanese Tea Gardens: , 174-175 Jazz'SAlive: Jester King Brewery: Johnson City: , 133-134 Johnson, Lyndon B., Jones Center: Jump-Start: Juneteenth: ### **KL** kayaking/canoeing: Austin , ; Hill Country , Kerr Arts and Culture Center: Kerrville: 147-150 Kerrville Fall Music Festival: Kerrville Folk Festival: , Kerrville-Schreiner: King William Historic District: 182-184; map Lady Bird Johnson Wildflower Center: Lady Bird Lake: , , , 85-86; map 86-87 Laguna Gloria: Lake Travis: 86-87; map language: Laurie Auditorium: La Villita: LBJ Library and Museum: , , , LBJ State Park and Historic Site: , , Leon Springs Dancehall: , lesbian and gay travelers: Liberty Bar: , Lights Spectacular: , Lindheimer Home Museum: liquor laws: Live Oak Brewing Company: , Lone Star Motorcycle Museum: Lone Star Riverboat: , 86-87, Lonestar Rod & Kustom Round Up: Long Center: Loop 360 Trail Access: Lost Maple State Natural Area: Love Creek Orchards: Luckenbach: Lucy in Disguise with Diamonds: Lyndon B. Johnson Boyhood Home: , ### **M** Magnolia Cafe: , mail: Majestic Theatre: manners: Mansfield Dam Park: Mardi Gras River Parade: Market Day at Lions Field: Mayan Dude Ranch: , , Mayfield Park and Preserve: McAllister Park: McKinney Falls State Park: McNay Art Museum: measurements: Mexic-Arte Museum: Milton Reimer's Ranch Park: Mission Concepción: Mission Espada: Mission Reach Hike and Bike Trail: 183-184 Mission San José: 184-185 Mission San Juan: Mission Trail: , , , Mi Tierra: , , Mohawk, The: , Moody Theater: , Mount Baldy: Mount Bonnell: Museum of Texas Handmade Furniture: Museum of the Weird: Museum of Western Art: music: 225-226 music scene, Austin's: 15-17, , 50-63; map ### **NO** National Museum of the Pacific War: , Natural Bridge Caverns: , 146-147 Natural Bridge Wildlife Ranch: Neill-Cochran House Museum: , Nelson A. Rockefeller Center for Latin American Art: Nelson Wolff Stadium: New Braunfels: 161-163 New Braunfels Wurstfest: O. Henry Museum: O. Henry Pun-Off World Championships: Old Depot Hotel: Old North Austin: Old Pecan Street Arts Festival: Old Settlers Music Festival: , Old State Capitol Building Ruins: , Old Tunnel State Park: 143-144 One World Theatre: O. S. T. Restaurant: , ### **P** Pace Bend Park: Pacific Combat Zone: packing tips: Palmer Events Center: , Paramount Theatre: Parish, The: , parks and gardens: Austin , , 86-88; San Antonio 173-174 Peach JAMboree and Rodeo: Pecan Street Arts Festival: Pedernales Falls State Park: Pioneer Museum: , Pioneer Town: planning tips: 10-12 plants: Plaza of the Presidents: politics: Polly's Chapel: population: postal service: Premium Outlets: ### **QR** rafting: 156-157 rail travel: Real Ale Brewing Co.: Red River District: , religion: Renewable Energy Roundup & Green Living Fair: 128-129 rental cars: Republic of Texas Biker Rally: resources: 236-237 Ride for the Roses: Riverbend Centre: Rivercenter Comedy Club: Riverside Nature Center: River Walk: , , 178-179 River Walk Mud Festival: , Rock Garden: roller derby: , Ronnie's Ice House: , Round Rock Express (baseball): Route 16: Rudy's Country Store and BBQ: , running/jogging: , ### **S** safety: 234-235 Salt Lick, The: , , 130-131 San Antonio: , 167-206; maps , , 176-177, San Antonio Botanical Garden: San Antonio Children's Museum: San Antonio El Día de los Muertos: San Antonio Mardi Gras: San Antonio Missions (baseball): San Antonio Museum of Art: San Antonio Speedway: San Antonio Spurs (basketball): San Antonio Stock Show and Rodeo: San Antonio St. Patrick's Day celebration: San Antonio Symphony: San Antonio Wurstfest: San Antonio Zoo and Aquarium: , San Fernando Cathedral: San Marcos: 158-159 Saxon Pub: , scenic drives: , , Schlitterbahn: , Schreiner Mansion Museum: Schultz House Cottage Garden: scuba diving/snorkeling: SeaWorld San Antonio: , senior travelers: Shady Grove Restaurant: , Shore Club Volente Beach: signage: 80-81 Sister Creek Vineyards: Six Flags Fiesta Texas: , 6th Street: , 36-37, , Skies Over Texas: , smoking: snakes: 234-235 Solaro Estate: Sophienburg Museum and Archives: South Austin: 42-46; map South Austin Museum of Popular Culture: South Congress Avenue: , 42-43, , Southerleigh Fine Food & Brewery: Spanish Governor's Palace: spectator sports: Austin 90-91; San Antonio 194-195 Splashtown: Spygrass Trail: Star of Texas Fair and Rodeo: state parks: , , 143-144, , Statesman Capitol 10K: State Theatre: Stonehenge II: , Stubb's Bar-B-Q: , , , Sunken Garden Theatre: 173-174 Sunset Station: swimming: Austin , , ; Hill Country , , , , , , , Swisher-Scott House: SXSW (South by Southwest): , 70-71 ### **T** Tejano Conjunto Festival: Tejano music: temperature measurements: Texas Book Festival: Texas Chili Parlor: , Texas Folklife Festival: Texas Gourd Society Show and Sale: Texas Hill Country Wineries Trail: 136-137 Texas Hills Vineyard: Texas Lonestar Rollergirls: Texas Memorial Museum: , , Texas Pioneer Trail Driver & Ranger Museum: , Texas Relays: Texas Rollergirls: , Texas State Capitol: , , 32-33, Texas Transportation Museum: , 172-173 Texas White House: , , Thinkery, The: , time: tipping: Torre di Pietra Vineyards: Tower of the Americas: , Toy Joy: , train travel: transportation: 228-230 Treaty Oak: Truer der Union Monument: tubing: 156-158, Twin Elm Guest Ranch: ### **UV** Umlauf Sculpture Garden and Museum: 45-46 Uncommon Objects: , University of Texas: 46-47 UT Longhorns athletics: UT Tower and Observation Deck: Uvalde: 154-156 Vanderpool: Vaughan, Stevie Ray: , 15-16, Veterans Walk of Honor: voltage: ### **W** Warehouse District: , waterfalls: Austin ; Hill Country , , Waterloo Records: , , , , weather: , , Westcave Preserve: West Hill House: Whittington's Jerky: , Whole Foods: , Wild Basin Wilderness Preserve: , 88-89 Wildflower Days: , wildlife/wildlife-watching: general discussion ; Austin 37-38, ; Hill Country 143-144, , William Chris Vineyards: Willow City Loop: , Wimberley: 159-161 Wimberley Arts Fest: Wimberley Glass Works: , Wimberley Square: wine/wineries: Austin ; Hill Country , , 136-137 Witte Museum: , , women travelers: Wonder World Caverns: , Woodlawn House: ### **XYZ** Y. O. Ranch: , Zachary Scott Theatre center: Zilker Botanical Garden: , , Zilker Garden Festival: , Zilker Park: , , Zilker Park Kite Festival: Zilker Park Tree Lighting: Zilker Summer Musical: Zilker Zephyr: , , zoos, animal parks, and aquariums: Hill Country , 162-163; San Antonio ## **List of Maps** **Front Map** Austin and San Antonio: 2-3 **Discover Austin, San Antonio & The Hill Country** Chapter divisions map: **Austin** Austin: 28-29 Downtown Austin: 34-35 South Austin: Central Austin: Austin Live Music and Nightlife: Austin Recreation: Lady Bird Lake: 86-87 Lake Travis: **The Hill Country** The Hill Country: 126-127 Fredericksburg: The Guadalupe River: **San Antonio** San Antonio: Brackenridge Park: Downtown San Antonio: 176-177 King William Historic District: **Background** Republic of Texas: ## **Photo Credits** Title page photo: © Justin Marler click here (top) © Justin Marler, (bottom left) © Justin Marler, (bottom right) © Justin Marler; click here © Justin Marler; click here (top left) © Justin Marler, (top right) © Justin Marler, (bottom) © Justin Marler; page 7 (top) © Justin Marler, (bottom left) © Justin Marler, (bottom right) © Justin Marler; click here © Justin Marler; click here (top) © Justin Marler, (bottom left) © Justin Marler, (bottom right) © Justin Marler; click here © Justin Marler; click here © Justin Marler; click here © Justin Marler; click here (top left) © Jackie Lee Young | Austin Motel, (top right) © Justin Marler; click here © Antone's; click here © Justin Marler; click here © W. Scott Mcgill | Dreamstime.com; click here © Justin Marler; click here © Witte Museum; click here (top) © Triciadaniel | Dreamstime.com, (bottom) © Justin Marler; page 27 © Justin Marler; click here—click here © Justin Marler; click here (top) © Justin Marler, (bottom) © Justin Marler; page 123 © Justin Marler; click here © Justin Marler; click here © Frank Wolfe | LBJ Library; click here—click here © Justin Marler; click here © Richard Mcmillin | Dreamstime.com; click here © Justin Marler; click here © Justin Marler; click here © Justin Marler; click here © Richard Mcmillin | Dreamstime.com; click here—click here © Justin Marler; click here (top) © Justin Marler, (bottom) © Justin Marler; page 169 © Justin Marler; click here © Justin Marler; click here © Crackerclips | Dreamstime.com; click here—click here © Justin Marler; click here (top) © Justin Marler, (bottom) © Justin Marler; click here © Justin Marler; click here (top) © Justin Marler, (bottom) © Justin Marler. ## **Also Available** **MOON AUSTIN, SAN ANTONIO & THE HILL COUNTRY** Avalon Travel Hachette Book Group 1700 Fourth Street Berkeley, CA 94710, USA www.moon.com Editor: Kimberly Ehart Series Manager: Kathryn Ettinger Copy Editor: Brett Keener Graphics Coordinator: Sarah Wildfang Production Designer: Sarah Wildfang Cover Design: Faceout Studios, Charles Brock Interior Design: Domini Dragoone Moon Logo: Tim McGrath Map Editor: Kat Bennett Cartographers: Stephanie Poulain, Karin Dahl, Brian Shotwell Indexer: Greg Jewett eISBN: 978-1-63121-644-2 ISBN-13: 978-1-63121-643-5 Printing History 1st Edition — 2006 5th Edition — September 2017 5 4 3 2 1 Text © 2017 by Justin Marler. Maps © 2017 by Avalon Travel. Some photos and illustrations are used by permission and are the property of the original copyright owners. Hachette Book Group supports the right to free expression and the value of copyright. The purpose of copyright is to encourage writers and artists to produce the creative works that enrich our culture. The scanning, uploading, and distribution of this book without permission is a theft of the author's intellectual property. If you would like permission to use material from the book (other than for review purposes), please contact permissions@hbgusa.com. Thank you for your support of the author's rights. Front cover photo: © ATMTX Photography Back cover photo: © Kan1234 | Dreamstime.com Avalon Travel is a division of Hachette Book Group, Inc. Moon and the Moon logo are trademarks of Hachette Book Group, Inc. All other marks and logos depicted are the property of the original owners. All recommendations, including those for sights, activities, hotels, restaurants, and shops, are based on each author's individual judgment. We do not accept payment for inclusion in our travel guides, and our authors don't accept free goods or services in exchange for positive coverage. Although every effort was made to ensure that the information was correct at the time of going to press, the author and publisher do not assume and hereby disclaim any liability to any party for any loss or damage caused by errors, omissions, or any potential travel disruption due to labor or financial difficulty, whether such errors or omissions result from negligence, accident, or any other cause. The publisher is not responsible for websites (or their content) that are not owned by the publisher. ## Contents 1. Cover Page 2. Title Page 3. Contents 4. Index 5. List of Maps 6. Discover Austin, San Antonio & the Hill Country 7. Austin 8. The Hill Country 9. San Antonio 10. Background 11. Essentials 12. Resources 13. Photo Credits 14. Copyright ## Contents 1. Cover Page 2. Contents 3. Title Page
{ "redpajama_set_name": "RedPajamaBook" }
2,818
Richard Murphy UK, Fiscal Policy 2015: A year in taxation This is Richard Murphy's contribution to the EREP review of the UK economy 2015, "the Cracks Begin to Show". The full report can be downloaded here. Taxation naturally lends itself to annual review: much of it is assessed on the basis of annual income. Tax policy is not so neatly delineated: when it comes to policy the issue is usually one of trajectories and their convergence and divergence, plus the odd significant sea-change that indicates major changes in direction. The Coalition government established a new direction for UK tax on its election in 2010. The concentration of power in the hands of the Conservative Party in 2015 has accelerated the process of change that was seen over the previous five years. The post-election 2015 strategy made three things clear. The first is that tax is at the core of whatever might be called the UK's industrial strategy. In 2010 the government declared that 'the UK was open for business' by starting to cut the UK's large company corporation tax rate. In 2015 this downward trajectory continued with announcement of plans for the rate to be cut to 18% - which is less than the basic rate of income tax. Coupled with changes made over the last five years to reduce the scope of UK tax to ensure that no profits arising outside this country need be taxed here, this reinforces what many have felt for a long time, which is that it is the government's plan to turn the UK into a tax haven. It is doing that by cutting the tax rate. It is also doing that by encouraging international tax competition. This represents the second clear strategy that emerged this year: tax is apparently to now be used to exacerbate economic inequality. In the process the UK government has become deeply antagonistic towards the international process run by the Organisation for Economic Cooperation and Development to tackle what is called 'Base Erosion and Profits Shifting'. Nowhere was this clearer than when in March 2015 the UK created the Diverted Profits Tax (or 'Google Tax') that directly undermines internationally agreed measures. It is also widely thought that the UK is a major opponent to EU plans to create tax harmony. That is unsurprising when it continues to support a range of captive tax havens in the Channel Islands and elsewhere. This policy of tax competition has, however, taken on a new guise domestically. The granting of corporation tax setting powers to Northern Ireland and Scotland opens the possibility of a domestic race to the bottom in profits taxation, and the extension of this policy to business rates, that will now be set by local councils with (in most cases) downward-only adjustments allowed, does much the same thing. The intended impact is obvious in all of these policies. The aim is to reduce the tax paid by business and capital and to shift it on to working people. Office for Budget Responsibility forecasts issued in July and November confirm this plan. Starving HMRC of resources reinforces the likelihood of this outcome, and represents the third clear strategy, which in this case is designed to reinforce the shrinking of the state. First, a shrunken HMRC will not have the resources to challenge businesses on their tax affairs. Second, a tax authority that cannot be accessed because people cannot, quite literally, get through to it is one that has a licence to make mistakes. Thirdly, newly announced plans to 'digitise' personal and small business taxation undermine the personal relationships needed to make tax work,and clearly signal an era when small business will be expected to pay its tax bills much sooner. This will suck them of much needed capital whilst also, perversely, encouraging more activity in the shadow economy and so an increasing tax gap that denies the state the resources needed to fund its social programmes. At a time when large companies have personal relationships with HMRC officers a clearer indication of the existence of a tax system in which everyone is very clearly 'not all in it together' could not be given. Tax, then, has come to the forefront of politics. Jeremy Corbyn made my work on the tax gap part of Corbynomics for that reason, using it to indicate that other options are available in this area. Demands in the EU Parliament for action on tax abuse in December 2015 are a direct challenge to the Commission that seems likely, along with the UK government, to implement as few as possible of the OECD's recommended measures to tackle international tax abuse. It is said that tax need not be taxing but the reality is that tax does, in very many ways, provide any government with the best opportunity to shape the society for which it is responsible and to which it is accountable. If that is true, then I believe that this government is saying it is on the side of the wealthiest and big business and it has little care for the rest. It's a tough message, and one that has to be challenged before the change it is promoting becomes deeply embedded in an even more divided society in 2016 and beyond. Newer Post2015: Economics, Energy and Climate Change Older Post2015: Monetary and fiscal policy discord
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
7,203
Die Dominican Republic International 2003 im Badminton fanden vom 7. bis zum 10. Juli 2003 in Santo Domingo statt. Medaillengewinner Weblinks http://tournamentsoftware.com/sport/tournament.aspx?id=B67829F5-06BE-4A63-9652-098236A3CF96 2003 Badminton 2003
{ "redpajama_set_name": "RedPajamaWikipedia" }
789
\section{Introduction} \label{sec:introduction} The concept of bone adaptation as a geometric flow is presented. The work presented here is a significant extension of a conference proceeding~\cite{besler2018bone}. Particularly, an artifact of signed distance transforms of sampled signals has been identified~\cite{besler2020artifacts} and solved in the case of computed tomography images of biphasic materials~\cite{besler2021constructing}. The mathematics have been expanded significantly to tightly link the model to the theory of geometric flows. \section{Adaptation as a Geometric Flow} It is assumed that bone changes occur at the interface of marrow and bone tissue. As a consequence of this claim, with an assumption of smoothness, many statements can be made about the underlying dynamics. Specifically, they can be modeled as a geometric flow where the flow rate has a historic and important meaning in the theory of bone adaptation. \subsection{Biology of Bone Adaptation} Bone adaptation occurs fundamentally at the surface~\cite{frost1969tetracycline,frost1987bone,frost2000utah}. This is in opposition to ontogenesis~\cite{berendsen2015bone} and indirect fracture healing~\cite{marsell2011biology} where endochondral ossification is replacing cartilage or intramembranous ossification is occurring directly from sheets of mesenchymal connective tissue. Functional adaptation refers to adaptation controlled principally through mechanics, typically coordinated by the osteocyte summarizable by a biological set point theory termed the mechanostat~\cite{frost1987bone}. Adaptation is separated into modeling (motion of the periosteal and endosteal surfaces through surface drifts) and remodeling (changes in cortical and trabecular bone through coordinated cell action)~\cite{frost1987bone}. The unit of remodeling is the basic multicellular unit (BMU) consisting of osteoblasts, osteoclasts, osteocytes, and other cells coordinated through cellular dynamics. Remodeling is coordinated differently in the lacunae of trabecular bone~\cite{raggatt2010cellular} and the osteon's of cortical bone~\cite{eriksen2010cellular}. Furthermore, a distinction is made between changes in shape (external remodeling) and changes in the material properties (internal remodeling)~\cite{beaupre1990approachtheory}. The principle concept is that adaptation occurs on the surface, which presupposed the existence of a surface as opposed to a density field and that adaptation can be modeled as a change in this surface over time. \subsection{The Bone Surface} \label{subsec:the_bone_surface} Let bone be described by a density field $\rho : \Omega \rightarrow \mathbb{R}^+$ defined on a domain $\Omega \subset \mathbb{R}^3$. It is assumed that bone is a biphasic material consisting of the marrow phase and the bone tissue phase, the domain is a union of the two phases $\Omega = \Omega_\text{Marrow} \cup \Omega_\text{Tissue}$ where $\Omega_\text{Marrow}$ and $\Omega_\text{Tissue}$ are the marrow and bone tissue components in the field, respectively. Importantly, since the bone is a biphasic material, its interface can be described as an orientable surface: \begin{equation} \mathcal{C} : \mathbb{R}^2 \rightarrow \mathbb{R}^3 \end{equation} where $\mathcal{C}$ is the surface. The consequence of having an orientable surface is that there is a defined inside and outside, so that a volume can be defined and area elements oriented. One additional claim is made that the surface is locally smooth, permitting differentiation. Since the surface is differentiable, the area is finite, a tangent plane can be defined at each point on the surface, and principle, mean, and Gaussian curvature defined. This constraint will be relaxed in Section~\ref{subsec:adaptation_as_a_geometric_flow} to permit topological changes during adaptation. \begin{figure*}[t] \centering \begin{tabular}{ccc} \subfloat[A Rod Resorbing]{ \includegraphics[width=0.3\linewidth]{Rods \label{fig:idealized:rod} } & \subfloat[A Plate Forming a Hole]{ \includegraphics[width=0.3\linewidth]{Plates \label{fig:idealized:plate} }& \subfloat[Periosteal Drift]{ \includegraphics[width=0.3\linewidth]{Drifts \label{fig:idealized:drift} } \end{tabular} \caption{Idealized surface changes in bone structure. (\ref{fig:idealized:rod}) Rods can resorb, changing topology; (\ref{fig:idealized:plate}) plates can form holes, causing rod-to-plate transition; and (\ref{fig:idealized:drift}) periosteal drift can change the gross morphometry.} \label{fig:idealized} \end{figure*} In contrast to differential geometry~\cite{kreyszig2019differential}, one could define bone using the theory of fractal geometry~\cite{mandelbrot1982fractal}. Fractal dimension is a well established morphometric parameter of trabecular bone~\cite{majumdar1993application,fazzalari1996fractal} defined from fractal geometry and there are strong arguments that bone has fractal properties~\cite{geraets2000fractal}. The coastline paradox is the quintessential natural experiment about the origin of fractals, where the measured length of a coastline depends on the size of the ruler you measure it with. The paradox is that the area continues to increase as the ruler decreases, all the way down to the scale of an atom, leading to one having a curve with finite volume but infinite area. In bone, the perimeter is replaced with surface area and the ruler with the resolution of the imager. While this behavior is confirmed at \textit{in vivo} resolutions~\cite{fazzalari1996fractal}, it is not clear if this trend would continue \textit{ad infinitum}. At some resolution --- say, the $\SI{100}{\nano\meter}$ scale --- the measured area is assumed to stabilize. Scanning electron microscopy confirms relatively smooth surfaces, albeit some surface roughness~\cite{boyde1986scanning}. While this theory holds that the surface is smooth, no claims are made on properties of the surface not exhibiting fractal-like behavior in the form of power laws, such as the distribution of pore size~\cite{jorgenson2015comparison}. \subsection{Adaptation as a Geometric Flow} \label{subsec:adaptation_as_a_geometric_flow} Having established the bone surface as an orientable, smooth surface, attention is placed on how to move the surface in time. This leads directly to an extrinsic geometric flow: \begin{equation} \label{eqn:curve_normal} \mathcal{C}_t = FN \end{equation} where $\cdot_t$ is a partial derivative in time, $F$ is a rate of surface growth that varies spatially across the surface, and $N$ is the normal of the surface. This equation captures motion only in the normal direction along the surface since tangential motion leads to a reparameterization of the surface and not a change in its geometry. With an initial surface, this presents bone adaptation as an initial value (Cauchy) problem: \begin{subequations} \begin{numcases}{}\label{eqn:ivp} \mathcal{C}_t = FN & \label{eqn:ivp:pde}\\ \mathcal{C}(x,0) = \mathcal{C}_0 & \label{eqn:ivp:surface} \end{numcases} \end{subequations} where $C_0$ is the initial bone surface. Such a formulation has been used extensively in computational physics~\cite{sussman1994level} and active contours~\cite{kass1988snakes}. Classic results of extrinsic geometric flows follow naturally from presentation of the Cauchy problem~\cite{huisken1984flow,gage1986heat,sethian1999level}. Changes in topology can occur as rods disconnect or holes form in plates. In finite time, the curve can develop sharp corners, which are continuous but not smooth, requiring special treatment through the theory of viscous solutions~\cite{crandall1983viscosity}. A complete contrast and comparison of geometric flows and their relation to bone adaptation is beyond the scope of this work and is an area of future interest. \subsection{The Adaptation Function, $F$} The principle consequence of considering bone as a geometric flow is that the quantity $F$, combined with the initial surface, completely describes the adaptation of bone. Due to its importance, we term the quantity $F$ the \textit{adaptation function}. \subsubsection{$F$ in Frost's mechanostat} $F$ is exactly the mechanostat graph of Carter~\cite{carter1984mechanical} and Frost~\cite{frost2001wolff}. Remodeling, lamellar bone drifts, and woven bone drifts are summarized in a single graph where changes in bone density (or surface) are a function of local mechanical strain. It is a summary of the BMU and changes spatially across the surface of bone. This paradigm has been used extensively to develop computational models of bone adaptation~\cite{adachi1997simulation,adachi2001trabecular,huiskes2000effects,schulte2011invivo,kameo2014modeling}. Attempts have been made to measure $F$ experimentally and establish the presence of lazy zones~\cite{christen2014bone}. \subsubsection{$F$ in Dynamical Systems} One paradigm for understanding skeletal health is to treat the basic multicellular unit (BMU) as a dynamical system. Hormones circulating in the blood stream (PTH, calcitonin, calcitriol, estrogens, etc.) and cytokines expressed locally (OPG, RANK, Wnts, TGF-$\beta$, etc.) control the rate of bone formation and resorption. Importantly, these substrates change the temporal dynamics of other substances, say through the down regulation of PTH as calcium leaves the bone and enters the blood stream or through the modified expression of RANK-L from osteoblasts, which leads to nonlinear effects in neighboring cells. Dynamical systems based on nonlinear partial differential equations have been used extensively to model coupled system. At the cellular level, dynamical models have explained paradoxes in experimental research~\cite{komarova2003mathematical} as well as predicting the response of bone to different cytokines~\cite{lemaire2004modeling,pivonka2010mathematical}. The adaptation function, $F$, is a continuous summary of the activity of discrete osteoblasts and osteoclasts, similar in concept to diffusion being a continuous summary of quantized particles moving from Brownian motion. In this paradigm, the adaptation function is the link between cellular- and tissue-scale dynamics~\cite{gerhard2009insilico,webster2001insilico}. \subsubsection{$F$ in Cellular Automata} Dynamical systems lead immediately to the paradigm of cellular automata (although not equivalent, taken here in spirit with complex adaptive systems and agent based modeling)~\cite{neumann1951general,langton1986studying,wolfram2002new}. The central concept of cellular automata is that complex behaviors can emerge from iterating simple rules, emerging in a way non-obvious by studying the rules in isolation. Such models have been used for predicting cortical remodeling~\cite{buenzli2012investigation}, posing bone adaptation as a topological optimization problem~\cite{tovar2005bone}, and simulating fracture healing~\cite{tourolle2019micro}. Viewed as agents, osteoblast and osteoclast cells can be thought to interact through simple rules, being defined by cytokines, local loading, and genetics. The system adapts through time, causing the spatial pattern of bone to emerge. In contrast to dynamical systems, this is a computational paradigm of bone adaptation. As in dynamical systems, the adaptation function $F$ is a summary of these local agents. \subsection{Remarks on Internal and External Models} There is a rich history in the development of models of bone adaptation. We differentiate those models that make the two-phase assumption from those that do not with Carter's terminology of internal remodeling~\cite{beaupre1990approach,huiskes2000effects} and external remodeling~\cite{cowin1985functional,adachi1997simulation,schulte2013strain}, respectively. There are models that make use of both~\cite{hart1984mathematical}. Equation~\ref{eqn:curve_normal} is the central equation for external remodeling while the central equation for internal remodeling is: \begin{equation} \rho_t = F \end{equation} where $\rho$ is the density field. In both cases, the adaptation function $F$ remains the central quantity of investigation. In internal remodeling methods, $F$ has dimensions of density per unit time ([Mass][Length]\textsuperscript{-3}[Time]\textsuperscript{-1}) while in external remodeling methods, $F$ has dimensions of length per unit time ([Length][Time]\textsuperscript{-1}). While these models are tightly coupled through $F$, their assumption on the density field have different consequences. For instance, internal remodeling can have a hole form in the center of a trabecula, not connected to the marrow space. Unless one relaxes the reinitialization condition (Section~\ref{subsubsec:reinitialization}), this cannot occur in external remodeling. A consequence of this is that the analytic models of Weinans~\cite{weinans1992behavior} and Cowin~\cite{cowin1981bone} are not equivalent. \section{Curvature-Based Bone Adaptation} We now present a specific model of bone adaptation for age-related bone loss. The model is based heavily on a prior model of age-related bone loss called simulated bone atrophy (SIBA)~\cite{muller1996analysis,mueller1997biomechanical,pistoia2003mechanical,muller2005long}. Using prior literature, it will be demonstrated that SIBA simulates mean curvature flow, providing a strong link to this geometric model. \subsection{The Model} Curvature-based bone adaptation models age-related changes in bone loss as a summation of advection of the surface and mean curvature flow. This gives the adaptation function: \begin{equation} \label{eqn:cbba} F = a - b \kappa \end{equation} where $a$ is the advection constant with dimensions [Length][Time]\textsuperscript{-1}, $b$ is the curvature constant with dimensions [Length]\textsuperscript{2}[Time]\textsuperscript{-1}, and $\kappa$ is the mean curvature with dimensions [Length]\textsuperscript{-1}. While $a$ can take on any value, $b$ can only take on positive values. Negative values of $b$ are consistent with inverse mean curvature flow, which is not defined for flat surfaces and becomes numerically unstable for non-flat surfaces. This is a two-parameter model defining a spatially varying adaptation function that depends only on the local geometry. The intuition behind Equation~\ref{eqn:cbba} is the same as in SIBA. Thin connections in the bone will resorb first not only because they are smaller, but because they have much higher curvature. Holes can form in plates causing plate-to-rod transition. Generally, changes occur on the surface, the trabecular bone surface erodes, and the rate at which bone changes varies across the surface. An important definition is when $F=0$ across the surface, as the bone will stop adapting. Rearranging Equation~\ref{eqn:cbba}, the stopping condition can be found: \begin{equation} F = b(\langle \kappa \rangle - \kappa) \end{equation} where $\langle \kappa \rangle = a/b$ is the average mean curvature across the surface. The bone will stop adapting when it is a surface of constant mean curvature, $\kappa = \langle \kappa \rangle$ everywhere. Such an equation is seen in the Young-Laplace equation~\cite{laplace1805traite,young1805essay} describing soap films, surface tension, and capillary rise. A closed form solution for curvature-based bone adaptation is difficult even for simple analytic surfaces. A solution is given for the sphere~\cite{besler2020sphere} and has been long known for the cases when $a=0$ or $b=0$. However, simple analytic surfaces are in someway unfaithful for developing intuitions on the equation. \subsection{Relation to Minimal Surfaces} A minimal surface is a surface of smallest area given a constraint. Equivalently, as mean curvature is the first variation of area, a minimal surface will have a mean curvature of zero everywhere. The first of such surfaces were Euler's catenoid and helicod. Later, Schwarz and Neovius described periodic minimal surfaces that extended infinitely. Schoen later classified these surfaces and discovered the gyroid~\cite{schoen1970infinite} Finally, surfaces of non-zero and spatially varying constant mean curvature were explored by Chopp and Sethian~\cite{chopp1991computing,chopp1993flow} using level set methods. Such surfaces have been used for designing scaffolds for tissue engineering~\cite{kapfer2011minimal} and lightweight but strong structures~\cite{zhang2018energy}. \subsection{Relation to SIBA} The relationship between curvature-based bone adaptation and simulated bone atrophy (SIBA) is now described. SIBA works on binary images of bone where the bone tissue phase is the foreground object and the marrow phase is the background object. A finite support Gaussian filtration is used to blur the object followed by a threshold to rebinarize the image. Physical interpretations were given to the variance of the Gaussian blur and threshold value based on osteoblast efficiency and resorption depth. The key methodological novelty of SIBA was that it naturally handled bone changing topology, where rods could resorb and plats could form holes. The intuitive similarities between SIBA and curvature-based bone adaptation is that Gaussian blurring moves the surface in a way that resembles mean curvature flow. Local changes on the bone surface are dependent on the magnitude and sign of the local mean curvature. As such, an advection term is used to model thresholding and a mean curvature term is used to model the Gaussian blurring. However, this link can be made concrete, and is done so now. The main result is that if a threshold of $0.5$ is used in SIBA, the method is equivalent to mean curvature flow in the limit as the product of kernel size and epoch time goes to zero. \subsubsection{Advection --- Threshold Link} \label{subsubsec:siba:advection} The link between advection and thresholding is derived following a previous derivation for Gaussian smoothed surfaces (Appendix of ~\cite{besler2021morph}). Consider a binary image, $I$, blurred with some Gaussian filter, $G_\sigma$: \begin{equation} \label{eqn:siba_blur} J = I * G_\sigma \end{equation} where $*$ is convolution and $J$ is the resulting grayscale image. We seek to understand how far the surface moves given a threshold $T$ of $J$. The intensity is normalized by forcing the binary image $I$ to take on values of $0$ or $1$. The curvature-dependence of the problem is removed by considering a blurring much smaller than the local mean curvature ($\sigma \ll |H|$) such that the surface is near flat (relative to the smoothing). Then, we can reduce the three-dimensional problem to a one-dimensional problem by considering the line along the surface normal, since blurring does not change the surface in the tangent plane. We define $I$ to be a unit step (Heaviside) function $\theta(x)$ with zero crossing at $x = 0$. The unit step is substituted into Equation~\ref{eqn:siba_blur} and the location of the $T$ level set is computed. \begin{eqnarray} J(x) &=& \theta(x) * G_\sigma \\ T &=& \frac{1}{2}\left(1 + \text{erf}\left(\frac{x}{\sqrt{2}\sigma}\right)\right) \\ \label{eqn:siba:advection} x &=& \sqrt{2}\sigma \text{erf}^{-1}\left(2T-1\right) \end{eqnarray} where $\text{erf}(\cdot)$ is the error function: \begin{equation} \text{erf}(z) = \frac{2}{\sqrt{\pi}} \int_0^z e^{-t^2}dt \end{equation} and $\text{erf}^{-1}$ the inverse error function. Note that the inverse error function is unique if $|z| < 1$, which corresponds to thresholds inside the dynamic range $[0, 1]$ specified for the binary image. Furthermore, $\text{erf}^{-1}(0) = 0$, corresponding to no change in the surface if $T=0.5$. Equation~\ref{eqn:siba:advection} gives an estimation of the distance the surface travels in flat areas for a given threshold $T$. Dividing this distance by the sample time, which is the inverse of activation frequency (AF) in SIBA, gives an estimate of the corresponding advection constant: \begin{equation} \label{eqn:siba:a} a = \sqrt{2}\sigma \text{erf}^{-1}\left(2T-1\right) \text{AF} \end{equation} \subsubsection{Mean Curvature --- Gaussian Filtration Link} \label{subsubsec:siba:mean} The relationship follows in two steps. First, consider the heat flow of the image: \begin{subequations} \begin{numcases}{}\label{eqn:heat} I_\tau = \alpha \Delta I & $\text{on }\Omega \times (0, \infty)$ \label{eqn:heat:pde}\\ I(x,0) = I_0 & $\text{on }\Omega \times 0$ \label{eqn:heat:iv} \end{numcases} \end{subequations} where $I_0$ is the original binary image, $\tau \in [0, \infty)$ is a time-like parameter, $\alpha$ is thermal diffusivity typically set to unity, and $\Delta = \nabla^2$ is the Laplacian operator. This defines a one-parameter family of images where the time-like parameter captures the scale of objects in the image~\cite{witkin1984scale,koenderink1984structure}. It is well known that the solution of the heat equation is Gaussian convolution: \begin{equation} I(x,\tau) = I_0(x) * G_\tau(x) \end{equation} where $2\alpha\tau = \sigma^2$ in Equation~\ref{eqn:siba_blur}. As such, one can work with $I(x,\tau)$ equivalently to the Gaussian blurring. The problem now reduces to comparing heat flow of the image to mean curvature flow of the surface. Realizing the link between Gaussian convolution and heat flow, SIBA is exactly the same as the BMO (Bence-Merriman-Osher) algorithm in computational physics for simulating mean curvature flow, except a threshold different from $0.5$ is selected~\cite{merriman1992diffusion}. BMO simulates mean curvature flow by blurring a binary image using the heat equation and rebinarizing the field with a threshold at $0.5$. Evans (Theorem 5.1, \cite{evans1993convergence}) proved that if $u$ is the viscous solution from mean curvature flow and $I(x,\tau)$ the solution from the diffusion equation, the two methods are equivalent in the limit of small $\tau$. The consequence is that for small values of $\sigma/\text{AF}$ and with $T=0.5$, SIBA simulates mean curvature flow. Following the methods of the BMO algorithm~\cite{merriman1992diffusion} in spherical coordinates, the mean curvature constant can be estimated as twice the thermal diffusivity constant: \begin{equation} b = 2 \alpha \end{equation} Note that $b$ and $\alpha$ have the same dimensions, [Length]\textsuperscript{2}[Time]\textsuperscript{-1}. Substituting into the relationship between $\alpha$ and $\sigma$: \begin{equation} \label{eqn:siba:b} b = \frac{\sigma^2}{\tau} \end{equation} where $\tau$ can be estimated as the inverse of activation frequency, as in the case of advection. The factors-of-two cancel because the surface is embedded in three dimensions. Finally, one can estimate the target mean curvature in SIBA by dividing Equation~\ref{eqn:siba:a} by Equation~\ref{eqn:siba:b}: \begin{equation} \langle \kappa \rangle = \frac{\sqrt{2} \text{erf}^{-1}\left(2T-1\right)}{\sigma} \end{equation} Noting the restriction in Section~\ref{subsubsec:adv_dis}, the algorithm will stop before this condition is met. \subsubsection{Limitations on these Similarities} It should be noted that the derivations in Section~\ref{subsubsec:siba:advection} and \ref{subsubsec:siba:mean} are approximate and not exact. Additional analysis is needed to derive bounds and convergence orders. Differences will arise because SIBA is compositional (Gaussin blur then thresholding) while the proposed model is additive (summing advection and mean curvature flow). Finally, SIBA was designed to be implemented in discrete space with a finite support Gaussian filter, causing differences to this continuous model. \subsubsection{Advantages and Disadvantages} \label{subsubsec:adv_dis} There are three primary advantages to curvature-based bone adaptation over simulated bone atrophy. The first advantage is a high-order representation of the bone surface. Since the surface is represented as a signed distance transform, gradients are available, and sub-voxel shifts can be tracked over time. In SIBA, the bone is represented by a binary image that is continually blurred and rebinarized. This inherently limits the representation to first order accurate, $\mathcal{O}(h)$, since information on the derivatives is lost by binarization. Furthermore, the bone surface can never traverse through voxel edges in very flat surfaces before being rebinarized, causing the surface to stop advecting artificially early (see Section 4 of~\cite{merriman1992diffusion}). This problem has an intricate link to anti-aliasing filters in computer graphics~\cite{blinn1989jim,besler2020artifacts}. The second advantage is well-defined mathematics for geometric flows. This gives us principled methods of understanding when the flow stops, if the flow minimizes an energy functional, and how the area and volume change with the flow. Further refinement of the link between dynamic histomorphometry~\cite{frost1969tetracycline,parfitt1987bone,schulte2011vivo} and geometric flows~\cite{sapiro2006geometric} as well as formulating energy functionals for bone adaptation~\cite{huiskes2000if} is an exciting future direction. The final advantage is that building load driven adaptation models based on the binary representation has the distinct disadvantage of requiring blurring to establish normal vectors~\cite{schulte2013strain}. The Gaussian filtration has an inherent trade-off where large blurs are needed to prevent quantization of the normal vector while small blurs are preferred to limit structural changes. Additionally, this causes an implicit mean curvature flow on top of the expected load driven adaptation, presenting difficulties in model validation. \begin{figure*} \centering \begin{tabular}{cccc} \subfloat[parameterization]{ \includegraphics[width=0.21\linewidth]{Spline_limitations_a \label{fig:parameterization:parameterization} } & \subfloat[Parameter Distribution]{ \includegraphics[width=0.21\linewidth]{Spline_limitations_b \label{fig:parameterization:distribution} } & \subfloat[Topology Change]{ \includegraphics[width=0.21\linewidth]{Spline_limitations_c \label{fig:parameterization:topology} } & \subfloat[Smooth Representation]{ \includegraphics[width=0.21\linewidth]{Spline_limitations_d \label{fig:parameterization:smooth} } \end{tabular} \caption{Disadvantages of using a parametric representation.~\ref{fig:parameterization:parameterization}) Complex structures such as cancellous bone are difficult to parameterize.~\ref{fig:parameterization:distribution}) Parameters will bunch during the flow.~\ref{fig:parameterization:topology}) Changes in topology require explicit merging and splitting rules.~\ref{fig:parameterization:smooth}) Surface representations are implicitely smoothed with differentiable parametric representation.} \label{fig:parameterization} \end{figure*} The two disadvantages of the proposed method are that it requires more memory and the algorithms are more difficult to implement. The memory requirement comes from needing to store the signed distance transform in a floating point representation where binary images can be stored with an unsigned 8-bit integer and massively compressed. Second, the proposed method requires specialized techniques for embedding and evolving, which are not yet standard in many image processing libraries. The tools required to implement SIBA exist in virtually all image processing libraries. Beyond contrasting, the two methods share a defining similarity: the ability to handle topological changes in bone during adaptation. This is the defining feature of any external remodeling algorithm and follows simply as a corollary of the assumption that bone adapts at the surface. If it adapts at the surface, topological changes will occur, and they must be treated appropriately. Any algorithm that cannot handle topological changes, such as those assuming diffeomorphisms, are not appropriate for modeling adaptation. This explains why successful methods in the field of brain imaging~\cite{ashburner2000voxel} and shape analysis~\cite{bookstein1997landmark} have had limited success in modeling bone adaptation. These methods make the explicit assumption of spatial normalization: that there exists a diffeomorphism between time points. While this appears true for brains, this is not true of bone microarchitecture within the same subject or between subjects. Similarly, adaptation simulation methods that used deformations of the grayscale data have an implicit weak form of the topology assumption that only holds for short time durations~\cite{pauchard2008european}. \section{Numerical Simulation} \label{sec:numerical_simulation} \subsection{Level Set Method} The level set method is used to simulate the geometric flow~\cite{dervieux1980fem,dervieux1981multifluid,osher1988fronts}. Primarily, the level set method represents the curve implicitly as the zero level set of an embedding function, $\phi$: \begin{equation} \label{eqn:zero_level_set} \mathcal{C} = \{ x \given \phi(x) = 0 \} \end{equation} This prevents many issues seen in parametric representations of surfaces~\cite{kass1988snakes}, described in Figure~\ref{fig:parameterization}. Importantly, an equation of motion can be computed for the implicit surface based on the curve evolution equation (Equation~\ref{eqn:curve_normal}) and taking the temporal derivative of the implicit contour (Equation~\ref{eqn:zero_level_set}): \begin{equation} \label{eqn:level_set_pde} \phi_t + F \lvert \nabla \phi \rvert = 0 \end{equation} Using this derivation, the equivalent initial value (Cauchy) problem can be stated using the implicit embedding function: \begin{subequations} \begin{numcases}{}\label{eqn:ls_ivp} \phi_t + F \lvert \nabla \phi \rvert = 0 \\ \phi(x,0) = \pm d(x, C) \end{numcases} \end{subequations} Instead of working with the curve directly, motion and morphometrics will be performed on the embedding, being able to recover the curve as the zero level set of the embedding at another time. The finite difference method will be used to solve Equation~\ref{eqn:ls_ivp} numerically. In general, the finite volume method is inappropriate for this solver as bone adaptation is not in general a conserved, hyperbolic system. This stems from the physiology where density does not flow through the domain like a fluid leaving or entering only at the boundary, but instead changes with sources (osteoblasts) and sinks (osteoclasts) scattered throughout the domain. Alternatively, the finite element method could be used but will in general be too computationally intensive. This section is motivated by considering the generalized problem of Equation~\ref{eqn:ls_ivp}: \begin{equation} \phi_t = L(\phi) \end{equation} Justification for these techniques can be found elsewhere~\cite{sethian1999level}. \subsubsection{Spatial Gradients} An approximation to the operator $L$ is needed. This is a sum of the advection and mean curvature terms. \begin{eqnarray} L(\phi) &=& -a + b \kappa \\ &=& L_\text{advection}(\phi) + L_\text{mean curvature}(\phi) \end{eqnarray} The mean curvature term can simply be expanded and appropriate finite difference subsituted into the equation: \begin{eqnarray} L_\text{mean curvature}(\phi) = b \kappa \lvert \nabla \phi \rvert \\ = \frac{ \begin{aligned} \left(\phi_{yy} + \phi_{zz}\right)\phi_x^2 \\ + \left(\phi_{zz} + \phi_{xx}\right)\phi_y^2 \\ + \left(\phi_{xx} + \phi_{yy}\right)\phi_z^2 \\ -2 \phi_x\phi_y\phi_{xy} -2 \phi_z\phi_x\phi_{zx} -2 \phi_y\phi_z\phi_{yz} \end{aligned} }{ \left(\phi_x^2 + \phi_y^2 + \phi_z^2\right) } \end{eqnarray} The advection term is more difficult because central-difference approximations to the gradient operator cause oscillations. Instead, an upwind solver must be used: \begin{eqnarray} L_\text{advection}(\phi) = - a \lvert \nabla \phi \rvert \\ = -a \sqrt{\phi_x^2 + \phi_y^2 + \phi_z^2} \\ \begin{split} = - a^+ \sqrt{(p^+)^2 + (q^-)^2 + (r^+)^2 + (s^-)^2 + (t^+)^2 + (u^-)^2}\\ - a^- \sqrt{(p^-)^2 + (q^+)^2 + (r^-)^2 + (s^+)^2 + (t^-)^2 + (u^+)^2} \end{split} \end{eqnarray} where $x^+ = \max(x,0)$, $x^- = \min(x,0)$, and $p$ through $u$ are one-sided differences: \begin{equation} \begin{matrix} p = D_x^-\phi & q = D_x^+\phi \\ r = D_y^-\phi & s = D_y^+\phi \\ t = D_z^-\phi & u = D_z^+\phi \end{matrix} \end{equation} These first-order derivatives can be replaced with weighted essential non-oscillator schemes if higher order accuracy is needed~\cite{liu1994weighted}. \subsubsection{Time Stepping} Next, the solution must be time stepped. This is done using a forward Euler approximation to the time derivative: \begin{equation} \phi^{n+1} = \phi^n + \Delta t L(\phi^n) \end{equation} This can be extended with the Runge-Kutta method if a more accurate solver is needed. \subsubsection{Courant-Friedrich-Lewy Condition} The method will be unstable if the Courant-Friedrich-Lewy (CFL) condition is not met~\cite{courant1928partiellen}. The CFL condition states that the ``numerical domain of dependence must include the physical domain of dependence''. In essence, this means that the surface cannot travel further than a voxel in a single iteration. The time step can be selected by the following equation: \begin{equation} \alpha = \Delta t \left(\frac{\lvert a \rvert}{\min(\Delta x, \Delta y, \Delta z)} + \frac{2 \lvert b \rvert}{\min(\Delta x^2, \Delta y^2, \Delta z^2)}\right) \end{equation} where $\Delta x$, $\Delta y$, and $\Delta z$ are the voxels edge lengths. $\alpha$ must be selected less than $1$ to satisfy the CFL condition and is selected to be $0.5$ in this work. \subsubsection{Reinitialization} \label{subsubsec:reinitialization} During evolution, the embedding can deviate from a signed distance transform. Reinitialization is the process of returning the embedding to a signed distance transform~\cite{sussman1994level}. In this work, a method is used that guarantees that the embedding does not change sign during reinitalization, and thus keeps volume conserved~\cite{peng1999pde}. This is achieved by solving the following partial differential equation with the same finite difference method: \begin{equation} \phi_\tau + S(\phi_0) \left(\lvert \nabla \phi \rvert - 1\right) = 0 \end{equation} where $\tau$ is a time-like parameter and $S(\cdot)$ is a regularized approximation to the sign function: \begin{equation} S(\phi) = \frac{\phi}{\sqrt{\phi^2 + \lvert \nabla \phi \rvert^2 h^2}} \end{equation} where $h = \min(\Delta x, \Delta y, \Delta z)$. The reinitalization equation is performed after every iteration, which could be relaxed if computation time was a concern. \subsection{Embedding} Attention is now placed on initialization the embedding, $\phi$. This is a challenging task as the signed distance transform of binary images exhibit quantization, limiting numerical accuracy of the flow and ability to measure curvatures~\cite{besler2020artifacts}. Instead, a previously developed method is used that instantiates the embedding directly from the density image, skipping binarization~\cite{besler2021constructing}. The method is quickly summarized below. The central idea is to construct an embedding $\psi$ that does not satisfy the Eikonal condition but shares a zero crossing with the desired embedding $\phi$. This is achieved by subtracting a density threshold to shift the desired density level set to zero. Furthermore, noise reduction methods can also be applied. This leads to the following definition of the intermediate embedding: \begin{equation} \psi = T - G_\sigma * \rho \end{equation} where $T$ is a density threshold, $G_\sigma$ is a Gaussian blur of size $\sigma$, and $\psi$ is an embedding whose zero level set is the implicit surface (Equation~\ref{eqn:zero_level_set}). Having the intermediate embedding, the closest point method~\cite{chopp2001some,ruuth2008simple,coquerelle2016fourth} is used to establish the narrowband distances, which are then marched to the remainder of the domain using the high-order fast sweeping method~\cite{zhang2006high}. The obtained embedding $\phi$ satisfies the recovery condition, Eikonal condition, is unique, and has an order of accuracy greater than unity~\cite{besler2021highorder,besler2021constructing}. \subsection{Density Component Estimation} Having the density and embedding image, the phase densities $\rho_\text{marrow}$ and $\rho_\text{bone}$ can be estimated. The central idea is that the density image can be constructed from the embedding image knowing the two phase densities and the embedding: \begin{equation} \rho = \rho_\text{bone} \theta(-\phi) + \rho_\text{marrow} \left[1 - \theta(-\phi)\right] \end{equation} where $\theta$ is the Heaviside step function. We follow here the method of Chan and Vese~\cite{chan2001active} to estimated $\rho_\text{marrow}$ and $\rho_\text{bone}$ from the density image $\rho$ an embedding $\phi$: \begin{eqnarray} \label{eqn:rho_bone} \rho_\text{bone} &=& \frac{\int_\Omega \rho(x) \theta(-\phi(x)) dV}{\int_\Omega \theta(-\phi(x)) dV} \\ \label{eqn:rho_marrow} \rho_\text{marrow} &=& \frac{\int_\Omega \rho(x) \left[1 - \theta(-\phi(x))\right] dV}{\int_\Omega \left[1 - \theta(-\phi(x))\right] dV} \end{eqnarray} It is assumed that the phase densities do not change during adaptation. As such, volumetric bone mineral density can be estimated from the volume fraction of bone: \begin{eqnarray} \text{BV/TV} &=& \frac{\int_\Omega \theta(-\phi(x)) dV}{\int_\Omega dV} \\ \text{vBMD} &=& \rho_\text{bone} \text{BV/TV} + \rho_\text{marrow} \left[1 - \text{BV/TV}\right] \end{eqnarray} We remark here that while masking is not explicitly performed in this study, it can be achieved using simple surface editing operators on signed distance fields~\cite{zhao2000implicit,museth2002level}. \subsection{Morphometry} Beyond densities, morphometry can be performed directly from the embedding using a previously developed technique~\cite{besler2021morph}. First, mean curvature can be computed using the divergence of the surface normals: \begin{equation} H = \frac{1}{2} \nabla \cdot \left( \frac{\nabla \phi}{\lvert \nabla \phi \rvert} \right) \end{equation} We remark that $H$ and $\kappa$ differ by a factor of the surface dimensionality: \begin{equation} H = \frac{\kappa}{2} \end{equation} $\kappa$ is the physicist's mean curvature while $H$ is the geometer's mean curvature. Next, Gaussian curvature can be computed on the implicit contour~\cite{sethian1999level}: \begin{equation} K = -\frac{\begin{vmatrix} \phi_{xx} & \phi_{xy} & \phi_{xz} & \phi_x \\ \phi_{yx} & \phi_{yy} & \phi_{yz} & \phi_y \\ \phi_{zx} & \phi_{zy} & \phi_{zz} & \phi_z \\ \phi_x & \phi_y & \phi_z & 0 \end{vmatrix}}{\lvert \nabla \phi \rvert^4} \end{equation} Using mean and Gaussian curvature with definition of the volume and area elements, the volume ($V$), area ($A$), surface average mean curvature ($\langle H \rangle$), total Gaussian curvature ($\bar{K}$), and \epc~characteristic ($\chi$) can be measured using previously developed methods~\cite{chan2001active,peng1999pde,besler2021morph,besler2021constructing}: \begin{eqnarray} V &=& \int_\Omega \theta(-\phi) dV \\ A &=& \int_\Omega \delta(-\phi) |\nabla \phi| dV \\ \langle H \rangle &=& \frac{\int_\Omega H \delta(-\phi) |\nabla \phi| dV}{\int_\Omega dV} \\ \bar{K} &=& \int_\Omega K \delta(-\phi) |\nabla \phi| dV \\ \chi &=& \frac{\bar{K}}{2\pi} \end{eqnarray} From these definitions, standard bone morphometric measures can be derived. The structure model index (SMI) can be computed from average mean curvature, volume, and area~\cite{hildebrand1997quantification,jinnai2002surface}, trabecular bone pattern factor (TBPf) can be computed from average mean curvature alone~\cite{hahn1992trabecular,stauber2006volumetric}, and connectivity density (Conn.D) can be computed from the \epc~characteristic and the total volume~\cite{odgaard1993quantification}: \begin{eqnarray} \text{SMI} &=& 12 \langle H \rangle \frac{V}{A} \\ \text{TBPf} &=& 2 \langle H \rangle \\ \text{Conn.D} &=& \frac{1 - \chi/2}{TV} \end{eqnarray} The purpose of the factor-of-two is outlined in the Appendix. Importantly, since connected component filtering cannot be easily implemented on the embedding and disconnected particles will form during the flow, Odgaard's constraints on the Betti numbers --- that there is no marrow cavities ($\beta_2 = 0$) and only one foreground particle ($\beta_0 = 1$) --- cannot be guaranteed~\cite{odgaard1993quantification}. The importance of this conclusion is outlined in the discussion. \section{Experiment} Two experiments are performed to demonstrate curvature-based bone adaptation. Ten cubes of bovine trabecular bone were previously sawed to 10 mm in edge length and imaged at a nominal resolution of $\SI{20}{\micro\metre}$~\cite{sandino2013trabecular}. Embedding was performed with a threshold of $T = 400~\text{mg HA/cc}$ and Gaussian filter of standard deviation $\sigma = \SI{20}{\micro\metre}$. This dataset was previously used to validate the embedding method~\cite{besler2021constructing}. Images were embedded and geometric flows simulated using the level set method. Two parameter sets are studied as described later. 30 years were simulated and morphometry was performed every 3 years directly from the embedding. Morphometry included the bone surface to volume ratio (BS/BV, $\si{\per\milli\metre}$), volumetric bone mineral density (vBMD, $\text{mg HA/cc}$), connectivity density (Conn.D, $\si{\per\milli\metre\cubed}$), and structure model index (SMI, $-$). For rendering, volumes were reduced to a $\SI{2}{\milli\metre}$ edge length cube in order to visualize individual trabeculae and the marching cubes algorithm~\cite{lorensen1987marching} was used to directly extract the surface at an isocontour of zero. \subsection{Assigned Flow} Model parameters are selected such that they represent physiologically plausible losses. Selecting $a = \SI{-1}{\micro\metre\per\year}$ and $b = \SI{100}{\micro\metre\squared\per\year}$ would erode a rod of thickness $\SI{100}{\micro\metre}$ roughly $\SI{2}{\micro\metre\per\year}$. Given that trabecular bone has an average thickness around $100 - 250~\si{\micro\metre}$, this is a reasonable loss over a human lifespan of 100 years. Of course, the process is non-linear, and more loss will be experienced. \begin{table} \centering \begin{tabular}{ccccc} \hline Subject & $\langle H \rangle~\si{\per\milli\metre}$ & $\kappa~\si{\per\milli\metre}$ & $b~\si{\micro\metre\squared\per\year}$ & $a~\si{\micro\metre\per\year}$ \\ \hline 1 & 2.21 & 4.42 & 100 & 0.442 \\ 2 & -0.13 & -0.26 & 100 & -0.026 \\ 3 & 1.27 & 2.53 & 100 & 0.253 \\ 4 & 0.31 & 0.62 & 100 & 0.062 \\ 5 & 0.37 & 0.73 & 100 & 0.073 \\ 6 & 1.25 & 2.51 & 100 & 0.251 \\ 7 & 0.56 & 1.12 & 100 & 0.112 \\ 8 & 2.11 & 4.22 & 100 & 0.422 \\ 9 & 1.35 & 2.70 & 100 & 0.270 \\ 10 & -0.02 & -0.04 & 100 & -0.004 \\ \hline \end{tabular} \caption{Per-subject parameters for curvature driven bone adaptation that produce a volume-preserving flow.} \label{table:parameters} \end{table} \subsection{Volume-Preserving Flow} Next, a volume-preserving flow is investigated. To ensure the flow is volume-preserving, the parameters $\left\{a, b\right\}$ are selected equal to the average mean curvature across the surface: \begin{equation} \frac{a}{b} = \langle \kappa \rangle \end{equation} The same curvature constant, $b = \SI{100}{\micro\metre\squared\per\year}$, is used but the propagation constant, $a$, is allowed to vary with each subject. These values are given in Table~\ref{table:parameters}. The volume-preserving flow is interesting because it implies changes in the bone surface that fundamentally cannot be measured by areal or volumetric bone volume fraction, requiring imaging of the microarchitecture. Furthermore, this suggests a deeper relationship between structure and calcium homeostasis where bone can be turning over but net calcium flux through digestion and excretion is zero. \begin{figure*} \centering \begin{tabular}{cc} \subfloat[BS/BV]{ \includegraphics[width=0.45\linewidth]{Flow-BSBV \label{fig:flow:bsbv} } & \subfloat[vBMD]{ \includegraphics[width=0.45\linewidth]{Flow-vBMD \label{fig:flow:vbmd} } \\ \subfloat[Conn.D]{ \includegraphics[width=0.45\linewidth]{Flow-ConnD \label{fig:flow:connd} } & \subfloat[SMI]{ \includegraphics[width=0.45\linewidth]{Flow-SMI \label{fig:flow:smi} } \end{tabular} \caption{Measured morphometry during curvature based bone adaptation with parametes $a = \SI{-1}{\micro\metre\per\year}$ and $b = \SI{100}{\micro\metre\squared\per\year}$. Bone (\ref{fig:flow:bsbv}) surface area to volume ratio, (\ref{fig:flow:vbmd}) volumetric minearl density, (\ref{fig:flow:connd}) connectivity density, and (\ref{fig:flow:smi}) structure model index are plotted every three years over 30 years of simulation. Connected lines are individual subjects.} \label{fig:flow} \end{figure*} \begin{figure*}[h!] \centering \begin{tabular}{cccc} \subfloat[$t = \SI{0}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_0 \label{fig:times:0} } & \subfloat[$t = \SI{3}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_3 \label{fig:times:3} } & \subfloat[$t = \SI{6}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_6 \label{fig:times:6} } & \subfloat[$t = \SI{9}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_9 \label{fig:times:9} } \\ \subfloat[$t = \SI{12}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_12 \label{fig:times:12} } & \subfloat[$t = \SI{15}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_15 \label{fig:times:15} } & \subfloat[$t = \SI{18}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_18 \label{fig:times:18} } & \subfloat[$t = \SI{21}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_21 \label{fig:times:21} } \\ \subfloat[$t = \SI{24}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_24 \label{fig:times:24} } & \subfloat[$t = \SI{27}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_27 \label{fig:times:27} } & \subfloat[$t = \SI{30}{\year}$]{ \includegraphics[width=0.15\linewidth]{LS2_SANDINO_BOV_03_30 \label{fig:times:30} } & \end{tabular} \caption{Visualization of the bone surface changing across the simulation timeframe. Rods disconnect exhibiting the ability of level set methods to capture topological changes. The medial subject by bone mineral density is displayed.} \label{fig:times} \end{figure*} \section{Results} \subsection{Assigned Flow} Morphometry during curvature-based bone adaptation is plotted in Figure~\ref{fig:flow}. Bone surface to volume ratio increases non-linearly with time. Similarly, structure model index increases with time. Owing to the inverse relationship between SMI and BS/BV, the changes in SMI must be driven by an increase in mean curvature across the surface. Bone mineral density decreases almost linearly and nearly at the same rate for all subjects. A subject specific response was seen in connectivity density. While a few subjects increased Conn.D across the time frame, others increased then decreased rapidly. The number of connections can rise when plates form holes, decrease when rods disconnect, and effectively decrease by the formation of isolated particles, making this morphometric outcome difficult to interpret. The surface of the median subject by density is visualized in Figure~\ref{fig:times}. Rods are seen disconnecting and resorbing, the structure thins throughout and becomes more porous. Furthermore, the surface looses roughness in the first 3 years consistent with noise being removed by mean curvature flow. \subsection{Volume-Preserving Flow} Morphometrics for the volume-preserving flow are plotted in Figure~\ref{fig:morph}. As expected, bone mineral density decreases only slightly, a result seen in a previous study~\cite{peng1999pde}. The ratio of surface area to volume decreases over time while structure model index increases. This is driven by the inverse relationship between SMI and BS/BV where surface average mean curvature is constant in the volume-preserving flow. Since volume is constant, the surface area must be decreasing, consistent with area being the first variation of volume. Finally, connectivity density increases for approximately 10 years then starts to decrease. This is consistent with particles forming, increasing the \epc~characteristic, followed by rods disconnecting. The initial, 15 year, and 30 year epochs of the median density subject are rendered in Figure~\ref{fig:image}. Structural changes are subtle, but thin rods can be observed disconnecting and negative curvature areas thickening. As in the non-volume-preserving case, noise on the surface is rapidly removed. \begin{figure*}[t] \centering \begin{tabular}{cc} \subfloat[BS/BV]{ \includegraphics[width=0.45\linewidth]{VolFlow-BSBV \label{fig:morph:bsbv} } & \subfloat[vBMD]{ \includegraphics[width=0.45\linewidth]{VolFlow-vBMD \label{fig:morph:vbmd} } \\ \subfloat[Conn.D]{ \includegraphics[width=0.45\linewidth]{VolFlow-ConnD \label{fig:morph:connd} } & \subfloat[SMI]{ \includegraphics[width=0.45\linewidth]{VolFlow-SMI \label{fig:morph:smi} } \end{tabular} \caption{Measured morphometry during the volume-preserving flow. Bone (\ref{fig:flow:bsbv}) surface area to volume ratio, (\ref{fig:flow:vbmd}) volumetric minearl density, (\ref{fig:flow:connd}) connectivity density, and (\ref{fig:flow:smi}) structure model index are plotted every three years over 30 years of simulation. Volumetric bone mineral density does not change as expected from the model. Connected lines are individual subjects.} \label{fig:morph} \end{figure*} \begin{figure*} \centering \begin{tabular}{ccc} \subfloat[Initial]{ \includegraphics[width=0.3\linewidth]{SANDINO_BOV_03_0 \label{fig:image:0} } & \subfloat[15 Years]{ \includegraphics[width=0.3\linewidth]{SANDINO_BOV_03_15 \label{fig:image:15} } & \subfloat[30 Years]{ \includegraphics[width=0.3\linewidth]{SANDINO_BOV_03_30 \label{fig:image:30} } \end{tabular} \caption{Visualization of the surface during volume-preserving flow at three epochs. Rods can be seen disconnecting, suggesting a decrease in mechanical competence.} \label{fig:image} \end{figure*} \section{Discussion} \label{sec:discussion} Bone adaptation is presented as a geometric flow. Curvature-based bone adaptation is presented as the continuous version of the discrete simulated bone atrophy method. The geometric flow can be simulated using the level set method, which naturally handles topological changes. Two parameter sets were investigated, one resembling age-related bone loss and another being a volume-preserving flow. The concretized model of curvature-based bone adaptation, and its predecessor simulated bone atrophy~\cite{muller1996analysis}, are unlikely to accurately predict \textit{in vivo} bone microarchitectural changes. This owes to the relationship of the models to the Young-Laplace equation of surface tension, giving bubble-like architecutres if the model runs longer than 30 years. However, the power of these models is in their clarity and computational abilities. As with simulated bone atrophy, topological changes can be handled naturally. Furthermore, the methods of simulated bone atrophy were central to developing a load-driven model that could handle topological changes~\cite{schulte2013strain}. In this way, the specific instantiation (curvature-based bone adaptation) and general theory (bone adaptation as a geometric flow) should be separated~\cite{dirac1963evolution}. Beyond a specific instantiation, there are limitations to describing bone adaptation as a geometric flow. The central assumption to treat bone as a geometric flow is that the bone is orientable and smooth. This assumption cannot be met during fetal development and fracturing healing where mineralization processes are not occurring on an existing surface. Generally, ontogenesis and fracturing healing will be well described by internal remodeling methods~\cite{carter1984mechanical} while modeling and remodeling will be well described by external remodeling methods. Such a situation alludes to a description that is not internal nor external remodeling. There should be an underlying process which gives rise to internal or external remodeling based on circumstance. In a search for the underlying dynamics of bone biology, a natural pattern similar to trabecular bone was sought. An astonishing similarity is seen between trabecular bone and Turing patterns~\cite{turing1952chemical}. Turing patterns emerge from simple reaction-diffusion equations, giving wonderfully complex shapes. The Gray-Scott model is arguably the most studied of these models~\cite{gray1984autocatalytic} and extensive work has been done to classify the patterns as a function of their parameters~\cite{pearson1993complex}. Another famous reaction-diffusion model is the Allen-Cahn equation~\cite{allen1979microscopic}, which was shown to converge to mean curvature flow~\cite{ilmanen1993convergence}. Understanding trabecular patterning as a consequence of the dynamics of biochemistry will provide a deeper understanding of the multi-scale link in bone biology~\cite{webster2011silico}. The obvious next step is to incorporate the level set method into a functional adaptation model. Developing a functional adaptation model using the signed distance embedding is a concatenation of the biphasic model~\cite{besler2021constructing} and existing load-driven models~\cite{huiskes2000effects,adachi2001trabecular,schulte2013local}. The key distinction is to perform finite element analysis on the density image constructed from the biphasic solution while having motion of the bone surface on the embedding. This has the major advantage of not having to perform connected components filtering for finite element analysis, where isolated parts of bone relevant for measuring changes in total calcium must be removed in order to permit a solution of the finite element model. Without binarizing the volume, it is difficult to perform connected components filtering during embedding or adaptation where isolated bone tissue components can arise. Connected components filtering is needed to meet the assumptions of Odgaard in measuring connectivity density~\cite{odgaard1993quantification}. The method presented here cannot assess the Betti numbers directly, but connectivity density is still estimated so the numerics are interpretable. However, alternative methods exist for computing the Betti numbers of an implicit curve~\cite{pascucci2002efficient}, which would allow the direct measurement of $\beta_1$ without connected components filtering. Furthermore, this method may be less sensitive than the total Gaussian curvature method used here. Together with performing finite element analysis on the constructed density image, this would permit the development of disconnected components during adaptation, which would be important for monitoring calcium homeostasis. Odgaard identified the issue of isolated bone particles during adaptation in his connectivity density work~\cite{odgaard1993quantification}: \begin{quote} During bone formation and bone healing isolated islands of bone may exist, but these and related exceptions will not be considered further. The main reason for neglecting these exceptions is that fully isolated bony strands do only contribute very little, if at all, to the mechanical competence of a cancellous bone region. \end{quote} A major question that remains to be resolved is how to incorporate a local strain field and a local advection force together. Existing models assume the magnitude of the diffeomorphism caused by the strain field is much smaller in magnitude than local changes in bone morphometry, consistent with the small-strain assumption of mechanics. It is not obvious how to validate this assumption, nor how to incorporate the two types of motion together. However, incorporating the strain field with the level set equation would provide a clear path to model dynamic behavior~\cite{turner1998three}, a currently under-modeled aspect of bone adaptation. Lastly, curvature-based bone adaptation is intricately linked to surfaces of constant mean curvature. These theories present a relationship between a functional being minimized (a Lagrangian) and a surface minimizing that Lagrangian, suggesting that bone can be a minimal surface of a measure different from curvature. The concept of bone being optimal in some sense dates back to Wolff, with early formalization of the problem using Lagrangians and optimal control theory dating to Carter~\cite{jacobs1997adaptive}. Early work on topology optimization given prescribed mechanical competence demonstrates structures remarkably similar to the cross-section of the humeral head~\cite{sethian2000structural}. Deriving Frost's mechanostat --- the adaptation function, $F$ --- as the Euler-Lagrange of a Lagrangian may finally answer Huiskes~\cite{huiskes2000if}: If bone is the answer, then what is the question?
{ "redpajama_set_name": "RedPajamaArXiv" }
4,304
Web and application developer, currently self-employed. 25 How to extract images from a SWF file? 24 Is it a good idea to use an integer column for storing US ZIP codes in a database? 17 Django: Does unique_together imply db_index=True in the same way that ForeignKey does?
{ "redpajama_set_name": "RedPajamaC4" }
4,453
MAQAM مقام is the world's largest producer of Arabic and Middle Eastern media including Arabic music, songs, radio, movies, keyboards, karaoke, books, gifts, and more! Saint John Hospital, Heliopolis, Cairo, Egypt. location: 34 Ismail Ramzy St., Heliopolis, Cairo, Egypt. SJH was founded by the Orthodox Christian Community and services all faith. A DREAM OF ARABIA is a Broadway style theatrical production of Arabic dance and music. 50 years of breeding the classic, Egyptian Arabian horse. Your business link to the Egyptian Industry. Explore the Egyptian Trading Directory to locate a huge number of Factories, Import and Export Companies, Agents, Banks, and Insurance Companies in Egypt. Dream of visiting Egypt? Travel to Egypt with Luminati Egyptian Travel for that Special Journey of your lifetime! Travel to Egypt with Luminati - Affordable Travel to Egypt offering exceptional journey packages for historical, archeological, esoteric, and sporting minded with Nile cruises, luxury hotel stays & more. egyptian jewelry cartouche Egyptian ankh jewelry Egyptian scarab jewelry eye of horus jewelry gold egyptian jewelry silver cartouche gold cartouche cartouches ankh udjat eye cartouches. Fine Egyptian jewelry and personalized Egyptian Cartouche jewelry handmade pendants with your name in hieroglyphic in silver and gold. Also glass Egyptian perfume bottles. Handmade jewelry designed by Jill Elizabeth with a dazzling array of beads and Austrian crystal wrapped in colorful wire inspired by the American Southwest and Egyptian and Indian mythology.
{ "redpajama_set_name": "RedPajamaC4" }
3,540
{"url":"https:\/\/phys.libretexts.org\/TextMaps\/Relativity_TextMaps\/Map%3A_General_Relativity_(Crowell)\/4%3A_Tensors","text":"$$\\require{cancel}$$\n\n# 4: Tensors\n\nWe now have enough machinery to be able to calculate quite a bit of interesting physics, and to be sure that the results are actually meaningful in a relativistic context. The strategy is to identify relativistic quantities that behave as Lorentz scalars and Lorentz vectors, and then combine them in various ways. The notion of a tensor has been introduced earlier. A Lorentz scalar is a tensor of rank 0, and a Lorentz vector is a rank 1 tensor.\n\n\u2022 4.1: Lorentz Scalars\nA Lorentz scalar is a quantity that remains invariant under both spatial rotations and Lorentz boosts. Mass is a Lorentz scalar. Electric charge is also a Lorentz scalar. The time measured by a clock traveling along a particular world-line from one event to another is something that all observers will agree upon; they will simply note the mismatch with their own clocks. It is therefore a Lorentz scalar.\n\u2022 4.2: Four-vectors (Part 1)\nThe basic Lorentz vector is the spacetime displacement. Any other quantity that has the same behavior under rotations and boosts is also a valid Lorentz vector.\n\u2022 4.2: Four-vectors (Part 2)\nA four-vector is an object with four components, which transform in a specific way under Lorentz transformations. Specifically, a four-vector is an element of a four-dimensional vector space considered as a representation space of the standard representation of the Lorentz group. The transformations that preserve this magnitude are the Lorentz transformations, which include spatial rotations and boosts.\n\u2022 4.3: The Tensor Transformation Laws\nWe may wish to represent a vector in more than one coordinate system, and to convert back and forth between the two representations.\n\u2022 4.4: Experimental Tests\nThe techniques developed in this chapter allow us to make a variety of new predictions that can be tested by experiment. In general, the mathematical treatment of all observables in relativity as tensors means that all observables must obey the same transformation laws. This is an extremely strict statement, because it requires that a wide variety of physical systems show identical behavior.\n\u2022 4.5: Conservation Laws\nIt is natural to ask how conservation laws can be formulated in relativity. We\u2019re used to stating conservation laws casually in terms of the amount of something in the whole universe, e.g., that classically the total amount of mass in the universe stays constant. Relativity does allow us to make physical models of the universe as a whole, so it seems as though we ought to be able to talk about conservation laws in relativity.\n\u2022 4.6: Things that Aren\u2019t Quite Tensors\n\u2022 4.E: Tensors (Exercises)\n\nThumbnail:\u00a0Standard configuration of coordinate systems; for a Lorentz boost in the x-direction. Image used with permission (Public Domain;\u00a0Gerd Kortemeyer).","date":"2018-03-19 06:53:31","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 1, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.9045240879058838, \"perplexity\": 350.15956290765394}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2018-13\/segments\/1521257646602.39\/warc\/CC-MAIN-20180319062143-20180319082143-00382.warc.gz\"}"}
null
null
La Fédération des chambres de commerce du Québec (FCCQ) est une organisation québécoise fondée en 1909 représentant près de 140 chambres de commerce et quelque 1100 membres corporatifs, soit, en tout, près de 50 000 entreprises et gens d'affaires. La FCCQ est membre de la American Chamber of Commerce Executives et fait partie de la Chambre de commerce du Canada. Historique La Fédération des chambres de commerce de la province de Québec (FCCQ) a été créée le par Isaïe Préfontaine afin de « promouvoir l'efficacité des diverses chambres de commerce de la province » et « assurer l'unité et l'harmonie quant aux mesures à prendre concernant l'intérêt commun ». Dans les années 1950, la FCCQ fut à l'origine de la création de la Commission Tremblay sur les relations fédérales-provinciales. Dans les années 1960, elle a contribué à la mise sur pied de la Commission Parent qui est à l'origine de la création du ministère québécois de l'éducation actuel. Durant cette même période, la FCCQ a prôné la libéralisation des échanges économiques avec les États-Unis dans le but d'accroître les perspectives d'exportation des entreprises québécoises. Ainsi, à la fin des années 1980, elle a appuyé vigoureusement l'accord de libre-échange avec les États-Unis et, au début des années 1990, a soutenu la création de l'ALENA. Plus récemment, la FCCQ a initié la création des corridors Québec – New York en 2001, Québec – Vermont en 2006 et Québec – Ontario en 2007. Notes et références Liens externes Fédération des chambres de commerce du Québec (FCCQ) Chambre de commerce du Québec Association ou organisme ayant son siège à Montréal
{ "redpajama_set_name": "RedPajamaWikipedia" }
2,447
{"url":"https:\/\/socratic.org\/questions\/how-do-you-write-an-equation-of-a-line-with-slope-3-and-y-intercept-6","text":"# How do you write an equation of a line with slope 3 and y-intercept 6?\n\nMay 18, 2018\n\n$y = 3 x + 6$\n\n#### Explanation:\n\n$\\text{the equation of a line in \"color(blue)\"slope-intercept form}$ is.\n\n\u2022color(white)(x)y=mx+b\n\n$\\text{where m is the slope and b the y-intercept}$\n\n$\\text{here \"m=3\" and } b = 6$\n\n$\\Rightarrow y = 3 x + 6 \\leftarrow \\textcolor{red}{\\text{is the equation}}$","date":"2020-09-22 07:48:21","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 6, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.92735755443573, \"perplexity\": 1165.2513142729626}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 20, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2020-40\/segments\/1600400204410.37\/warc\/CC-MAIN-20200922063158-20200922093158-00164.warc.gz\"}"}
null
null
Matelea neei är en oleanderväxtart som beskrevs av Morillo. Matelea neei ingår i släktet Matelea och familjen oleanderväxter. Inga underarter finns listade i Catalogue of Life. Källor Oleanderväxter neei
{ "redpajama_set_name": "RedPajamaWikipedia" }
5,273
Shindo.tests('HP::Network | networking router requests', ['hp', 'networking', 'router']) do @router_format = { 'id' => String, 'name' => String, 'tenant_id' => String, 'status' => String, 'admin_state_up' => Fog::Boolean, 'external_gateway_info' => Fog::Nullable::Hash } @router_interface_format = { 'subnet_id' => String, 'port_id' => String } n_data = HP[:network].create_network({:name => 'fog_network'}).body['network'] @network_id = n_data['id'] p_data = HP[:network].create_port(@network_id, {:name => 'fog_port'}).body['port'] @port_id = p_data['id'] tests('success') do @router_id = nil tests('#create_router').formats(@router_format) do attributes = {:name => 'my_router', :admin_state_up => true} data = HP[:network].create_router(attributes).body['router'] @router_id = data['id'] data end tests('#list_routers').formats({'routers' => [@router_format]}) do HP[:network].list_routers.body end tests("#get_router(#{@router_id})").formats({'router' => @router_format}) do HP[:network].get_router(@router_id).body end tests("#update_router(#{@router_id})").formats({'router' => @router_format}) do attributes = { :name => 'my_router_upd', :external_gateway_info => { :network_id => '11111111111' }, :admin_state_up => true } HP[:network].update_router(@router_id, attributes).body end tests("#add_router_interface(#{@router_id}, '1111111111', nil) - using subnet_id").formats(@router_interface_format) do HP[:network].add_router_interface(@router_id, '1111111111', nil).body end #tests("#remove_router_interface(#{@router_id}, '1111111111', nil) - using subnet_id").formats('') do # HP[:network].remove_router_interface(@router_id, '1111111111', nil).body #end tests("#add_router_interface(#{@router_id}, nil, #{@port_id}) - using port_id").formats(@router_interface_format) do HP[:network].add_router_interface(@router_id, nil, @port_id).body end tests("#add_router_interface(#{@router_id}, '1111111111', '2222222222') - using port_id and subnet_id").raises(ArgumentError) do HP[:network].add_router_interface(@router_id, '1111111111', '2222222222').body end tests("#remove_router_interface(#{@router_id}, nil, #{@port_id}) - using port_id").formats('') do HP[:network].remove_router_interface(@router_id, nil, @port_id).body end tests("#remove_router_interface(#{@router_id}, '1111111111', '2222222222') - using port_id and subnet_id").raises(ArgumentError) do HP[:network].remove_router_interface(@router_id, '1111111111', '2222222222').body end tests("#delete_router(#{@router_id})").succeeds do HP[:network].delete_router(@router_id) end end tests('failure') do tests('#get_router(0)').raises(Fog::HP::Network::NotFound) do HP[:network].get_router(0) end tests('#update_router(0)').raises(Fog::HP::Network::NotFound) do HP[:network].update_router(0, {}) end tests('#delete_router(0)').raises(Fog::HP::Network::NotFound) do HP[:network].delete_router(0) end tests("#add_router_interface(0, '1111111111')").raises(Fog::HP::Network::NotFound) do HP[:network].add_router_interface(0, '1111111111').body end tests("#remove_router_interface(0, '1111111111')").raises(Fog::HP::Network::NotFound) do HP[:network].remove_router_interface(0, '1111111111').body end end # cleanup # remove_router_interface method removes the port #HP[:network].delete_port(@port_id) HP[:network].delete_network(@network_id) end
{ "redpajama_set_name": "RedPajamaGithub" }
7,341
Q: Kd-Tree Insertion Order I am using a KD-Tree to optimize Range searching on a set of 2D points (x,y). To save time, I try to use Java Topology Suite's KD-Tree. However, the javadoc states that: Note that the structure of a KD-Tree depends on the order of insertion of the points. A tree may become imbalanced if the inserted points are coherent (e.g. monotonic in one or both dimensions). A perfectly balanced tree has depth of only log2(N), but an imbalanced tree may be much deeper. This has a serious impact on query efficiency So my question is: How to insert points to a KD-tree in such a way that minimizes the height of the tree? A: In wouldn't worry too much about it. It is a bit like hash maps which have in theory worst case O(n) lookup if all entries have to happen the same hash code. In reality this very unlikely to happen unless there is something wrong with the hash function. To avoid imbalance, you should make sure that your points are not ordered in any way. If they are, consider shuffling them before inserting them. Also, some kd-tree implementations have a rebalance() function that can be called after inserting (the bulk of) the data. This will rebalance the tree internally. Finally, if you really want to use a specific insertion order that avoids imbalance, you can do the following. Note that this approach is not optimal, it will avoid the worst case but will not typically result in a fully balanced tree: Sort the points by x-coordinate, then insert them using a binary split search. For example, if you have 15 points, sort them by 'x' to get a sorted list of point p0...p14. Then: * *Take the middle point in the range (p7) and insert it. *For each side of the split point, create a new range: p0-p6 and p8-p15 *Start over with 1) with each of the two ranges This results in the following insertion order: * *round: p7 *round: p3 and p11 *round: p1, p5, p9, p13 *round: p0, p2, p4, p6, p8, p10, p12, p14 Why is this not ideal? * *We completely ignore the y-coordinate. This approach only avoids imbalance with respect to the x coordinate. *Typical kd-trees split alternatingly between x and y. However, we do not know which comes first in the given implementation so we can only pretend that it always splits on x. This does no immediate harm, but it prevents more optimal insertion.
{ "redpajama_set_name": "RedPajamaStackExchange" }
9,035
Baselios Thomas (né le ) est l'actuel primat de l'Église syro-malankare orthodoxe (depuis le ). Voir aussi Articles connexes Église syro-malankare orthodoxe Liste des primats actuels des Églises orientales Liens externes Catholicos syro-malankare de l'Orient Naissance en juillet 1929
{ "redpajama_set_name": "RedPajamaWikipedia" }
2,088
{"url":"https:\/\/stacks.math.columbia.edu\/tag\/0DMP","text":"## 70.11 Geometrically reduced algebraic spaces\n\nIf $X$ is a reduced algebraic space over a field, then it can happen that $X$ becomes nonreduced after extending the ground field. This does not happen for geometrically reduced algebraic spaces.\n\nDefinition 70.11.1. Let $k$ be a field. Let $X$ be an algebraic space over $k$.\n\n1. Let $x \\in |X|$ be a point. We say $X$ is geometrically reduced at $x$ if $\\mathcal{O}_{X, \\overline{x}}$ is geometrically reduced over $k$.\n\n2. We say $X$ is geometrically reduced over $k$ if $X$ is geometrically reduced at every point of $X$.\n\nObserve that if $X$ is geometrically reduced at $x$, then the local ring of $X$ at $x$ is reduced (Properties of Spaces, Lemma 64.22.6). Similarly, if $X$ is geometrically reduced over $k$, then $X$ is reduced (by Properties of Spaces, Lemma 64.21.4). The following lemma in particular implies this definition does not clash with the corresponding property for schemes over a field.\n\nLemma 70.11.2. Let $k$ be a field. Let $X$ be an algebraic space over $k$. Let $x \\in |X|$. The following are equivalent\n\n1. $X$ is geometrically reduced at $x$,\n\n2. for some \u00e9tale neighbourhood $(U, u) \\to (X, x)$ where $U$ is a scheme, $U$ is geometrically reduced at $u$,\n\n3. for any \u00e9tale neighbourhood $(U, u) \\to (X, x)$ where $U$ is a scheme, $U$ is geometrically reduced at $u$.\n\nProof. Recall that the local ring $\\mathcal{O}_{X, \\overline{x}}$ is the strict henselization of $\\mathcal{O}_{U, u}$, see Properties of Spaces, Lemma 64.22.1. By Varieties, Lemma 33.6.2 we find that $U$ is geometrically reduced at $u$ if and only if $\\mathcal{O}_{U, u}$ is geometrically reduced over $k$. Thus we have to show: if $A$ is a local $k$-algebra, then $A$ is geometrically reduced over $k$ if and only if $A^{sh}$ is geometrically reduced over $k$. We check this using the definition of geometrically reduced algebras (Algebra, Definition 10.42.1). Let $K\/k$ be a field extension. Since $A \\to A^{sh}$ is faithfully flat (More on Algebra, Lemma 15.44.1) we see that $A \\otimes _ k K \\to A^{sh} \\otimes _ k K$ is faithfully flat (Algebra, Lemma 10.38.7). Hence if $A^{sh} \\otimes _ k K$ is reduced, so is $A \\otimes _ k K$ by Algebra, Lemma 10.162.2. Conversely, recall that $A^{sh}$ is a colimit of \u00e9tale $A$-algebra, see Algebra, Lemma 10.154.2. Thus $A^{sh} \\otimes _ k K$ is a filtered colimit of \u00e9tale $A \\otimes _ k K$-algebras. We conclude by Algebra, Lemma 10.161.7. $\\square$\n\nLemma 70.11.3. Let $k$ be a field. Let $X$ be an algebraic space over $k$. The following are equivalent\n\n1. $X$ is geometrically reduced,\n\n2. for some surjective \u00e9tale morphism $U \\to X$ where $U$ is a scheme, $U$ is geometrically reduced,\n\n3. for any \u00e9tale morphism $U \\to X$ where $U$ is a scheme, $U$ is geometrically reduced.\n\nProof. Immediate from the definitions and Lemma 70.11.2. $\\square$\n\nThe notion isn't interesting in characteristic zero.\n\nLemma 70.11.4. Let $X$ be an algebraic space over a perfect field $k$ (for example $k$ has characteristic zero).\n\n1. For $x \\in |X|$, if $\\mathcal{O}_{X, \\overline{x}}$ is reduced, then $X$ is geometrically reduced at $x$.\n\n2. If $X$ is reduced, then $X$ is geometrically reduced over $k$.\n\nProof. The first statement follows from Algebra, Lemma 10.42.6 and the definition of a perfect field (Algebra, Definition 10.44.1). The second statement follows from the first. $\\square$\n\nLemma 70.11.5. Let $k$ be a field of characteristic $p > 0$. Let $X$ be an algebraic space over $k$. The following are equivalent\n\n1. $X$ is geometrically reduced over $k$,\n\n2. $X_{k'}$ is reduced for every field extension $k'\/k$,\n\n3. $X_{k'}$ is reduced for every finite purely inseparable field extension $k'\/k$,\n\n4. $X_{k^{1\/p}}$ is reduced,\n\n5. $X_{k^{perf}}$ is reduced, and\n\n6. $X_{\\bar k}$ is reduced.\n\nProof. Choose a surjective \u00e9tale morphism $U \\to X$ where $U$ is a scheme. Via Lemma 70.11.3 the lemma follows from the result for $U$ over $k$. See Varieties, Lemma 33.6.4. $\\square$\n\nLemma 70.11.6. Let $k$ be a field. Let $X$ be an algebraic space over $k$. Let $k'\/k$ be a field extension. Let $x \\in |X|$ be a point and let $x' \\in |X_{k'}|$ be a point lying over $x$. The following are equivalent\n\n1. $X$ is geometrically reduced at $x$,\n\n2. $X_{k'}$ is geometrically reduced at $x'$.\n\nIn particular, $X$ is geometrically reduced over $k$ if and only if $X_{k'}$ is geometrically reduced over $k'$.\n\nProof. Choose an \u00e9tale morphism $U \\to X$ where $U$ is a scheme and a point $u \\in U$ mapping to $x \\in |X|$. By Properties of Spaces, Lemma 64.4.3 we may choose a point $u' \\in U_{k'} = U \\times _ X X_{k'}$ mapping to both $u$ and $x'$. By Lemma 70.11.2 the lemma follows from the lemma for $U, u, u'$ which is Varieties, Lemma 33.6.6. $\\square$\n\nLemma 70.11.7. Let $k$ be a field. Let $f : X \\to Y$ be a morphism of algebraic spaces over $k$. Let $x \\in |X|$ be a point with image $y \\in |Y|$.\n\n1. if $f$ is \u00e9tale at $x$, then $X$ is geometrically reduced at $x$ $\\Leftrightarrow$ $Y$ is geometrically reduced at $y$,\n\n2. if $f$ is surjective \u00e9tale, then $X$ is geometrically reduced $\\Leftrightarrow$ $Y$ is geometrically reduced.\n\nProof. Part (1) is clear because $\\mathcal{O}_{X, \\overline{x}} = \\mathcal{O}_{Y, \\overline{y}}$ if $f$ is \u00e9tale at $x$. Part (2) follows immediately from part (1). $\\square$\n\nIn your comment you can use Markdown and LaTeX style mathematics (enclose it like $\\pi$). A preview option is available if you wish to see how it works out (just click on the eye in the toolbar).","date":"2020-08-07 23:38:50","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 2, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.9868452548980713, \"perplexity\": 131.6711291527106}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2020-34\/segments\/1596439737233.51\/warc\/CC-MAIN-20200807231820-20200808021820-00038.warc.gz\"}"}
null
null
{"url":"https:\/\/proofwiki.org\/wiki\/Countable_Complement_Space_is_not_First-Countable","text":"# Countable Complement Space is not First-Countable\n\n## Theorem\n\nLet $T = \\struct {S, \\tau}$ be a countable complement topology on an uncountable set $S$.\n\nThen $T$ is not a first-countable space.\n\n## Proof\n\nAiming for\u00a0a contradiction, suppose some $x \\in S$ has a countable local basis.\n\nThat means:\n\nthere exists a countable set of sets $\\mathcal B_x \\subseteq \\tau$\n\nsuch that:\n\n$\\forall B \\in \\mathcal B_x: x \\in B$\n\nand such that:\n\nevery open neighborhood of $x$ contains some $B \\in \\mathcal B_x$.\n\nSo:\n\n $\\displaystyle \\bigcap \\mathcal B_x$ $=$ $\\displaystyle \\set x$ $\\displaystyle \\implies \\ \\$ $\\displaystyle S \\setminus \\set x$ $=$ $\\displaystyle S \\setminus \\bigcap \\mathcal B_x$ $\\displaystyle$ $=$ $\\displaystyle \\bigcup_{B \\mathop \\in \\mathcal B_x} \\paren {S \\setminus B}$ De Morgan's Laws: Difference with Intersection\n\nBy definition, each of $S \\setminus B$ is countable.\n\nFrom Countable Union of Countable Sets is Countable it follows that $\\displaystyle \\bigcup_{B \\mathop \\in \\mathcal B_x} \\paren {S \\setminus B}$ is also countable.\n\nSo $S \\setminus \\set x$ and therefore $S$ is also countable.\n\nFrom this contradiction (as we have specified that $S$ is uncountable) it follows that our assumption that $x \\in S$ has a countable local basis must be false.\n\nHence by definition $T$ can not be first-countable.\n\n$\\blacksquare$","date":"2020-01-19 16:17:40","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 2, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.9816339612007141, \"perplexity\": 184.5012985788228}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2020-05\/segments\/1579250594662.6\/warc\/CC-MAIN-20200119151736-20200119175736-00157.warc.gz\"}"}
null
null
\subsection*{Acknowledgements} We would like to thank M.~B\"uscher, D.~Grzonka, W.~Eyrich, J.~Ritman, \, E.~Roderburg, W.~Schroeder and Yu. Valdau for useful discussions. This work was partially supported by the Deutsche Forschungsgemeinschaft through funds provided to the SFB/TR 16 ``Subnuclear Structure of Matter''. This research is part of the EU Integrated Infrastructure Initiative Hadron Physics Project under contract number RII3-CT-2004-506078. A.S. acknowledges support by the COSY FFE grant 41760632 (COSY-085) and the JLab grant SURA-06-C0452.
{ "redpajama_set_name": "RedPajamaArXiv" }
4,299
{"url":"https:\/\/www.lil-help.com\/questions\/269877\/federalism-quizlet","text":"federalism quizlet\n\n# federalism quizlet\n\nS\n9.9k points\nFederalisma form of government in which power is divided between the federal government and the states\nSixteenth AmendmentThe constitutional amendment adopted in 1913 that explicitly permitted Congress to levy an income tax.\nFederal systema system of government in which power is divided between a central authority and a number of individual states\nSeventeenth Amendmentallowed americans to vote directly for U.S senators\nUnitary systema government that gives all key powers to the national or central government\nConfederate system (Confederation)a government that gives all key powers to the states\ncooperative federalismCooperation among federal, state, &local govts; \"marble cake\" federalism\nWeaknesses of the Articles of Confederationvery weak federal gov't, no power to tax,\nland grantsfirst form of grants-in-aid to the states by the federal govenrment were in this form\nNational powerscontrolling trade between states; creating army; coin and printing money; admiting new states; declaring war and peace; making laws for immagration\ncategorical grantsFederal grants that can be used only for specific purposes or \"categories,\" of state and local spending. They come with strings attached, such as nondiscrimination provisions.\nConcurrent powersPowers for both the national and state governments, such as the power to levy taxes.\nGreat Society1964, LBJ's policies of fighting poverty and racial injustice\nState powersControl public schools,Control local elections,Set up governments, Control trade in states, provide laws for safety,health, and welfare.\nRevenue sharingGiving money back to the state and local government with no strings attached\nEnumerated powers17 powers explicitly given to Congress in the Constitution\nNew Federalismsystem in which the national government restores greater authority back to the states\nImplied powerspowers that congress has that are not stated explicitly in the constitution\nblock grantsMoney from the national government that states can spend within broad guidelines\nReserve powerspowers granted ONLY to the states\nintergovernmental lobbyAn interest group made up of mayors, governors, and other state and local officials who depend on federal funds\nBill of attainderA legislative act that inflicts punishment without a court trial\nEx post facto lawsA law which punishes people for a crime that was not a crime when it was committed. Congress cannot pass these laws.\ndevolutionThe effort to transfer responsibility for many public programs and services from the federal government to the states.\n\"Full faith and credit\" clauseConstitution's requirement that each state accept the public acts, records, and judicial proceedings of every other state\npreemptionthe judicial principle asserting the supremacy of federal over state legislation on the same subject\ninterstate compactsAgreements btwn states to work together on common issues\nContract with Americarepublican plan for political reform [devolution]\nMcCulloch v. Maryland (1819)states did not have power to tax the national bank, reinforces supremacy clause\nNecessary and proper clauseConstitutional clause that gives congress the power to make all laws \"necessary and proper\" for executing its powers\nmandatesterms set by the national government that states must meet whether or not they accept federal grants\nSupremacy clauseThe constitutional provision that makes the Constitution and federal laws superior to all conflicting state and local laws.\nUS v. LopezThe Court held that Congress had exceeded its commerce clause power by prohibiting guns in a school zone.\nGibbons v. OgdenRegulating interstate commerce is a power reserved to the federal government\nCommerce clauseThe section of the Constitution in which Congress is given the power to regulate trade among the states and with foreign countries.\nDual federalismA system of government in which both the states and the national government remain supreme within their own spheres, each responsible for some policies.\nDred Scott v. SandfordSupreme Court case that supported slavery by saying slaves are property not citizens. (1857)\nTenth AmendmentAmendment stating that the powers not delegated to the federal gov. are reserved to the states\nfederalism quizlet\nstudybud\n\nSurround your text in *italics* or **bold**, to write a math equation use, for example, $x^2+2x+1=0$ or $$\\beta^2-1=0$$\n\nUse LaTeX to type formulas and markdown to format text. See example.","date":"2018-11-16 01:45:36","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 1, \"mathjax_asciimath\": 1, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.3203636407852173, \"perplexity\": 14716.137712861591}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2018-47\/segments\/1542039742968.18\/warc\/CC-MAIN-20181116004432-20181116030432-00323.warc.gz\"}"}
null
null
\section{Results and Discussion} \subsection{Structure of the Inverse Design Problem} We conceive of the ID problem as threefold, shown in Fig.~\ref{fig1}a. All relationships between the three representations of thin-film metamaterials---material structure, ellipsometric spectra and reflectance / transmittance spectra---consist of interconnected design problems. We seek to fully explore the ID problem for a given metamaterial structure by elucidating all relationships between the representations. Most thin-film optical engineering is represented by the structure ID problem, determining a specific stack of material layers which produces a particular spectral response. This involves determining the composition and thickness of each layer, and the ordering of the layers in the stack. In particular, most practical applications of metamaterials involve the structure ID of reflectance ($R$) / transmittance ($T$) spectra (left upward arrow in the Fig.~\ref{fig1}a triangle). We design CNNs to take all $R$ and $T$ spectra for both polarizations of incident light ($R_p$, $R_s$, $T_p$, $T_s$) at [25, 45, 65] degree incident angles and output individual layer parameters (material and thickness). The range of incident angles used in the training can be easily adapted for specific applications. Ellipsometry, another method of spectral analysis, provides optical information about metamaterial structure and composite materials by taking into account the phase relations in polarized reflected light.\cite{aspnes1981} Ellipsometry is a standard experimental method in nanophotonics, yielding two spectral variables ($\Psi$ and $\Delta$). $\Psi$ relates to the ratio in magnitude of the p- and s- polarized reflectance Fresnel coefficients while $\Delta$ relates to the phase shift between the same coefficients, where: \begin{equation} \frac{r_p}{r_s} = \tan(\Psi)e^{i \Delta} \end{equation} The analysis of metamaterials based on structure ID of $\Psi$ and $\Delta$ spectra is the primary purpose of most commercial ellipsometry software. However, the traditional methods of model fitting employed can be difficult due to generally requiring detailed prerequisite knowledge about the target structure including layer thicknesses and composite materials. In contrast, our CNN-based ellipsometric structure ID (right upward arrow in the Fig.~\ref{fig1}a triangle) attempts to solve this problem without such constraints, with a search occurring over the entire global design space. The designed CNN takes as input $\Psi$ and $\Delta$ spectra at [25, 45, 65] degree incident angles and outputs individual layer parameters. Note that the reverse of the structure ID problem left/right downward arrows in the Fig.~\ref{fig1}a triangle) is generally straightforward: if the system structure is completely known, both ellipsometry and reflectance / transmittance spectra are completely determined and can be easily calculated with the transfer matrix method.\cite{Chilwell1984} Finally, the third leg of the ID problem is the ability to reconstruct all ellipsometry spectra ($\Psi$, $\Delta$) from the complete reflectance / transmittance spectra ($R_p$, $R_s$, $T_p$, $T_s$), and vice versa, for nanophotonic structures residing in the design space (bottom arrows in the Fig.~\ref{fig1}a triangle). This spectral ID problem is non-trivial since it requires the reconstruction of phase or transmittance data, respectively, and can in principle be degenerate (multiple possible solutions in our global design space) without detailed knowledge of the underlying system structure. Despite these complexities, we show that these CNNs we can tackle this aspect of the problem as well. Throughout the text we will be using the terminology introduced here---structure ID for the upward arrows in the triangle, whose output is material structure, and spectral ID for the bottom arrows, where the output is a certain optical spectrum---to describe the different CNNs we developed. To define a concrete design space, we trained our CNNs on sample data from thin-film metamaterials of 1-5 layers, with layer thicknesses from 1 to 60 nm, and with a set of possible materials: Ag, Al$_2$O$_3$, ITO, Au and TiO$_2$. (Full details of the training, as well as the network structure of the CNNs, can be found in the Methods.) We treat the training/testing of each total layer number (1-5) subspace as a separate problem, so there is a different network trained for each layer number. Excluding degenerate cases where consecutive layers are the same material, the design space amounts to $\sim 10^{12}$ possible parameter combinations for the most complex case (for 5 layers, with thickness at 1 nm resolution, see Supporting Information for more discussion on the design parameter space). However the approach we present is not limited to this particular range of structural parameters and choice of material library. The training can readily be adapted to a different design space depending on the specific photonic problems of interest by altering the training dataset. \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{fig2.pdf} \caption{Performance metrics for the inverse design convolutional neural networks (CNNs). \textbf{a-c} Performance of the structure ID CNNs for both ellipsometry spectra (blue) and reflectance / transmittance spectra (red) as a function of total layer number. Networks are evaluated from an independent test dataset. Specific metrics are shown: \textbf{a} spectral RMSE between the input spectra and spectral response of the output structure averaged between all distinct spectral sub-types (ellipsometric structure ID ($\Psi$, $\Delta$)[deg] and reflectance / transmittance structure ID ($R_p$, $R_s$, $T_p$, $T_s$) [unit-less]), \textbf{b} average layer thickness RMSE [nm], and \textbf{c} average layer material accuracy [\%]. \textbf{d-e} Network performance for spectral ID in the design of both \textbf{d} ellipsometric spectra from reflectance / transmittance spectra ($\Psi$ and $\Delta$ output, [deg]) and \textbf{e} reflectance / transmittance spectra from ellipsometric spectra ($R_p$, $R_s$, $T_p$ and $T_s$ output, [unit-less]) spectra as a function of total layer number.} \label{fig2} \end{figure} \subsection{Prediction of Material Spectral Response} There are multiple ways of evaluating the effectiveness of structure and spectral ID CNNs. As a first step, we focus on the calculated spectral response from the network output structural predictions. In the case of the structure ID CNNs, whose output is a set of structural parameters (layer thicknesses, compositions), the calculated spectral response consists of the reflectance / transmission or ellipsometric ($\Psi$ and $\Delta$) spectra of the output structure, calculated using the transfer matrix method. These spectra can be compared to the input spectra that were design targets, and a root mean squared error (RMSE) calculated over the spectral range of interest (450 -- 950 nm) and for all angles([25, 45, 65] degrees). We refer to this metric as the spectral RMSE, coming in two types (reflectance / transmittance [unit-less] or ellipsometric [deg]) depending on the spectral type used. For the case of the spectral ID problem, we can also formulate a spectral RMSE metric, by comparing the output of the network (which in this case is directly a spectrum) to the ground truth from the system producing the input spectrum. All the evaluation results in this section and the subsequent ones are based on a testing set of systems consisting of previously unseen examples, drawn from the same design space as the training set (see Methods for details). Spectral RMSE is in many cases the most practical measure of ID performance, particularly in situations with degenerate solutions---different structural parameters that produce similar spectra. For example the target spectrum in the testing set may have been produced by a certain structure, but the network can find an alternative structure (different materials, different thicknesses) that yields a closely matching spectrum (and hence small spectral RMSE). This would still be a valid solution of the ID problem, fulfilling the intended spectral design task, however the predicted structure does not match the target design structure. Ideally we would like to minimize the spectral RMSE, while matching the target design structure. Balancing these two imperatives is a goal of our approach. The average spectral RMSEs in the structure ID problem for both ellipsometric and reflectance / transmittance spectra are shown in Fig.~\ref{fig2}a, evaluated over an independent test dataset. To understand the scale of the spectral RMSEs, note that the total output range for reflectance ($R$) and transmittance ($T$) is from 0 to 1, and for the ellipsometric variables ($\Psi$ and $\Delta$) this range is from 0 to 90 degrees and 0 to 360 degrees, respectively. For reflectance / transmittance spectra, observed spectral RMSE is low (less than $1\%$ of the total spectral output range) and increases with increasing total layer number to a maximum of $13\%$ of the output range for 4 layered systems. Ellipsometric spectral RMSE is observed to decrease with increasing total layer number, from $3\%$ of the spectral output range to $2\%$ for 1 and 5 layered systems, respectively. Tolerances for acceptable spectral RMSE are necessarily application dependent, however we consider these results good, especially for the systems with fewer layers. Notably, the effectiveness of the CNNs extends even to systems with many layers, where the design space is far larger. This is all the more remarkable because spectral RMSE is not used directly as part of the loss function for CNN training (see Methods for details of the loss function), and hence the performance in this regard is a byproduct rather than an explicit goal of the training process. This is an important feature of our implementation of the CNN methods, since we consider the training of networks to predict the underlying structure a major goal. This overcomes a deficiency in some traditional methods which solely minimize the spectral RMSE in the optimization loss, since these methods can be especially prone to encountering degeneracy within the design space. This can lead to solutions which locally minimize the spectral RMSE, but do not typically select the correct structure. Spectral RMSE results for the spectral ID CNNs are shown in Fig.~\ref{fig2}d-e as a function of total layer number. For both spectral ID problems, the spectral RMSE is observed to increase with increasing total layer number. This increase is expected with the exponentially increasing size of the parameter space, however the CNN responses maintain a low RMSE even for relatively high total layer number systems. The maximum average spectral RMSE occurs for 5 layer systems with $0.1\%$ and $1\%$ of the total output range for ellipsometric [deg] and reflectance / transmittance [unit-less] spectral types, respectively). This result demonstrates the ability of CNN models to accurately correlate spectral types for general classes of real systems. This result is impressive, since general relationships between reflectance / transmittance and ellipsometric spectra are not well defined analytically. It is notable that the CNN models perform comparably for both p and s polarization in transmittance. This is explained by relatively low transmittance for most systems above three layers, given that an average layer thickness of $30$ nm and three layers significantly increases the probability of optically opaque structures. We note that training a network to solve the spectral ID problem directly (correlating between the two distinct spectral types, following the bottom right arrow of the triangle) performs better than the indirect approach of first solving the structure ID problem from $R$, $T$ to material parameters, and then using the transfer matrix to get the $\Psi$, $\Delta$ spectra (structure ID spectral RMSE, the alternative path of following the left upward and right downward arrows). Comparing Figs.~\ref{fig2}a and e, the spectral RMSEs are typically an order of magnitude better for the direct path. This underlines the importance of having separate trained networks for all three legs of the ID triangle. Even though spectral ID yields smaller spectral RMSE values, in many design applications structure ID is essential, because we desire to explicitly predict the material parameters. We explore this point further in the next section. \subsection{Prediction of Material Structure Parameters} For the case of structure ID, since the network output consists of structural / material parameters, we can use these to formulate an alternative measure of CNN performance: how well does the network predict the correct material in each layer, and how well does it predict each layer thickness? These metrics are imperfect in the sense that by construction the predictive accuracy should tend to decrease as the layer number increases. This is because for larger layer numbers there may be many degenerate structures with similar optical response. But it is still interesting to measure the impact of this degeneracy issue on predictive performance. The results are shown in Fig.~\ref{fig2}b-c, as a function of total layer number. In both reflectance / transmittance and ellipsometric structure ID, trained CNN models are able to reproduce the correct materials and thickness for the corresponding input spectra with high precision ($>90\%$ materials accuracy, $<1$ nm thickness RMSE) in up to three total layers, averaged over the entire test dataset (see Supporting Information for more details on the network response to test data). For systems with higher total layer number the CNN models are still able predict structures with significantly correct materials and thicknesses. However, a decrease is observed in the material accuracy and consequently and increase in thickness RMSE for large total layer number systems. This decrease is attributed both to construction: the expected increase in degeneracy for much larger parameter spaces; and to network performance: a decreased ability of the CNN to generalize the greater complexity of higher order systems. In general, this vast increase in parameter space greatly increases the demand upon the CNN for generalization of the spectral response. The comparison with spectral RMSE is instructive: as seen in Fig.~\ref{fig2}a, reflectance / transmittance spectral RMSE increases by $0.11$ and ellipsometric spectral RMSE decreases by $1.57$ deg, with decreasing average layer material accuracy and increasing average layer thickness RMSE. The comparison of these two metrics is an indication of degeneracy within the included parameter space, since the CNN can more often come to predictions with a similar spectral response while utilizing physical structures with less correspondence to the target structure. \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{fig3.pdf} \caption{Examples of convolutional neural network (CNN) inverse design for structures within the training parameter space. Inverse design of \textbf{a-c} ground truth structure 1 shown in \textbf{c}, \textbf{d-f} ground truth structure 2 shown in \textbf{f}. Structures are drawn to scale with material colors in the figure legend. Simulated spectra (black) are plotted against structure inverse design (blue) and spectral inverse design (red) CNN prediction results. \textbf{a} Ellipsometry inverse design of structure 1, predicted structure is shown in the inset. \textbf{b} Reflectance / Transmittance inverse design of structure 1, predicted structure is shown in the inset. \textbf{d} Ellipsometry inverse design of structure 2, predicted structure is shown in the inset. \textbf{e} Reflectance / Transmittance inverse design of structure 2, predicted structure is shown in the inset.} \label{fig3} \end{figure} \subsection{Inverse Design of In-Library Structures} Two examples of structure ID and spectral ID performed with CNNs are shown in Fig.~\ref{fig3}, plotted against the corresponding input spectra. Both the target design structure and inverse designed structures are shown. Spectral comparisons are computed by operating directly with the transfer matrix code on the CNN structure output. In each case both the ellipsometric and reflectance/transmittance CNNs predict a structure which reproduces the spectral response to a high degree of accuracy. Remarkably, the CNN model is able to predict spectral response irrespective of sharp local features in the input spectra, as can be seen for both the relatively sharp and broad features (see Supporting Information for more discussion on this point). This feature of the CNN prediction is not equally represented in the spectral RMSE metric, and is affected by both the CNN feature extraction approach and an operation on a limited library of materials. An example 3-layer system is shown in Fig.~\ref{fig3}a-c, and the CNN model is seen to predict the correct materials subspace corresponding to the input spectra. Because of this, any error in the spectral response is then a result of fine-tuning individual layer thicknesses to optimize the spectra. For the 5-layer system shown in Fig.~\ref{fig3}d-f, the CNN does not predict the correct materials subspace for the ground truth structure. However, for both ellipsometric and reflectance/transmittance spectra, spectral response of the chosen structure closely matches that of the target spectra to within $0.1$ deg and $2\%$ R/T maximum error, respectively. This is an interesting property of the CNN based inverse design, that incorrect structures are often predicted which still produce a spectral response that closely mimics the target spectra. The existence of such structures is a known result of the spectral degeneracy for many layered systems, compounded by the finite CNN accuracy as discussed above.\cite{Liu2018} However, the solution types shown in Fig.~\ref{fig3}d-f reside in material subspaces which have been specifically excluded from the training data set because of the repeating Au layers. This means the CNN was not shown any examples of this type previous to the prediction of this structure. That the CNN can come to such solutions is a positive feature of the ID process, indicative of generalization to a set of physically realistic principles encoded within the CNN. Spectral ID results for the presented systems are shown on the same axes as the corresponding input spectra in Fig.~\ref{fig3}. In each case the respective spectral ID CNNs accurately predict the corresponding spectra given the physical input. This is clear evidence of generalization in the CNN, since the underlying relationship corresponds only to a correlation based on physical systems and is, in principle, highly degenerate with no clear analytic mapping between spectral types. \subsection{Creative Inverse Design of Synthetic Spectra} \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{fig4.pdf} \caption{Examples of convolutional neural network inverse design for structures outside the training parameter space with a-b for the first spectra and \textbf{c-d} for the second spectra. \textbf{a} Drawn spectra (black) are plotted against the 4-layer (blue) and 5-layer (red) CNN prediction results, with predicted structures inset. Structures are drawn to scale with material colors in the figure legend. \textbf{b} Histogram of spectral RMSE for all possible solutions to the inverse design problem within the design parameter space. The CNN predicted results are shown as plotted points on the histogram for comparison. \textbf{c} Drawn spectra (black) are plotted against the 4-layer (blue) and 3-layer (green) CNN prediction results, with predicted structures inset. \textbf{d} Histogram of spectral RMSE for all possible solutions to the inverse design problem within the design parameter space.} \label{fig4} \end{figure} In practical applications of structure ID, the desired spectral response for a multi-layer thin-film metamaterial is generally not exactly represented by a system contained in the design parameter space probed by the training library, since it is possible to conceive of arbitrary spectral features in the target design. In these cases, CNN structure predictions are purely a generalization of the input spectra to similar features from the in-library parameter space, as the CNN typically predicts outputs in this space. Two examples are provided in Fig.~\ref{fig4}, designed to illustrate the usefulness of this approach in practical design scenarios. The purpose of the CNN models implemented in this study is the exploration of a large, general parameter space. In this space, the availability of certain spectral responses is generally limited by the finite size of the parameter space. Thus the correspondence of the calculated spectral response from the network prediction with the design target will necessarily be limited. The true measure of network performance is not the absolute spectral RMSE in this case, but a comparison of this value with spectral responses from structures within the allowed parameter space, which is discussed below. In Fig.~\ref{fig4}a-b the input spectra mimic a reflectance filter with sharp cut-off at an arbitrary cut-off wavelength. This input spectra is not generated from any known metamaterial structure and is simply drawn from an appropriately scaled hyperbolic tangent function. Spectra corresponding to the predicted 4-layer and 5-layer structure ID CNN predictions are shown plotted against the drawn input spectra. In each case spectra from the predicted structures closely recreate the sharp edge in the reflectance and suppressed transmittance with non-negligible differences in the remainder of the spectra. The inability of the CNN to completely capture the input spectra is due to a limitation of possible structures in the design parameter space probed by the CNN, and not a deficiency in the predictive ability of the network. This is represented in Fig.~\ref{fig4}b, showing for each total layer number a histogram of spectral RMSE between the input structure and all possible structures within the design parameter space. Comparison spectra were obtained from structures with design parameters spanning the entire design parameter space, for a total of more than $6 \times 10^{10}$ and $3 \times 10^{13}$ structures (sampled at 0.5 nm thickness intervals) for 4 and 5 total layer number systems, respectively. The CNN predicted structures show a spectral RMSE in the top $95\%$ and $90\%$ of all possible structures for the 4-layer and 5-layer systems, respectively. These results are well above median, indicating the ability of the CNN to predict globally optimized structures. The prediction of very low spectral RMSE solutions is constrained by the non-existence of exact solutions in the finite parameter space. This is shown by the non-zero minimum in the spectral RMSE histogram. In general, completely matching solutions to drawn (not physically generated) spectra do not exist within this space. Also note that the spectral RMSE metric does not equally represent sharp features in the target spectra to which the CNN may have a modified response, as discussed above. Optimization of these features is varied and can be better evaluated on a case-to-case basis in line with the specific design objectives. The input spectra in Fig.~\ref{fig4}c-d are also drawn and not generated from a physical system. These are meant to represent a broadband anti-reflective coating for the glass substrate. Spectral responses corresponding to structures predicted by the 3-layer and 4-layer CNNs are shown. In each case the CNN predicts a structure with spectral characteristics similar to the input, although the CNN predicted structure is not able to reproduce the completely flat spectral response. As discussed above, a histogram of spectral RMSE with possible spectral responses from all structures within the parameter space is shown in Fig.~\ref{fig4}d. In this example the CNN produces highly optimized structures, with spectral RMSE in the top $98\%$ and $99\%$ of all possible structures for the 3-layer and 4-layer systems, respectively. The predicted structures show spectral behavior similar in magnitude to the input spectra, and evaluation of the full space histogram shows that spectral errors are a limitation of the design space and not of the CNN optimization. Notably, both of these examples feature arbitrarily engineered spectra, in the sense that they are drawn from appropriately scaled mathematical functions and not generated from any physical structure. This demonstrates the usefulness of CNN based structure ID in general design scenarios, and the ability of CNNs to produce globally optimized structures in a given parameter space. \subsection{Comparison with Other Methods} In response to the complexity of photonic structure ID, the optimized computational design of nanophotonic structures traditionally relies on optimization techniques employing forward electromagnetic solvers.\cite{Molesky2018} Generally the performance of these traditional methods in producing globally optimal solutions are limited by both the volume of parameter space being probed and the efficiency of generating forward solutions. Since optical spectra for thin-film nanophotonic systems can be generated at relatively low computational cost via the transfer matrix method, the comparison with traditional methods of optimization is an important insight into the practicality of CNNs as a design tool for general nanophotonic systems.\cite{Chilwell1984} Comparisons were made with least squares (Levenberg-Marquardt)\cite{Anzengruber2012} and genetic algorithms,\cite{Storn1997,Froemming2009} two common methods utilized in structure ID of nanophotonic systems. Since the general ID problem consists of a continuous basis of individual layer thickness within discrete material subspaces, the least squares algorithm was globalized by performing a brute force random global search of all material subspaces. The genetic algorithm is able to natively accommodate the discrete basis. All comparison algorithms were written in Python with common modules, optimized for evaluation time and evaluated on the same high performance computational resources as the CNN (see the Methods section for full details). \begin{figure}[t] \centering \includegraphics[width=1.0\linewidth]{fig5.pdf} \caption{Timing comparison results for structure ID convolutional neural networks and comparable optimization techniques. \textbf{a} Ellipsometric inverse design solution time (s) for the CNN (blue), least squares optimization (red) and genetic algorithms (green) as a function of total layer number. Dashed lines indicate projected results based on an exponential regression of observed results. \textbf{b} Similar results for reflectance / transmittance spectra inverse design as a function of total layer number. \textbf{c} Complexity (purple) of the general inverse design problem (size of the probed parameter space, discritized by 1 nm) as a function of total layer number. Total number of allowed materials choices are also shown, as number of distinct material subspaces (red). These values grow exponentially with layer number, complicating the inverse design problem. } \label{fig5} \end{figure} The observed solution times for both comparison methods and each system total layer number are shown in Fig.~\ref{fig5}a-b, along with the corresponding structure ID CNN solution time. For systems with many layers, some results have been predicted from an exponential regression of the observed solution times. These are indicated by dashed lines in Fig.~\ref{fig5}a-b. CNN training time has not been included in this analysis, since use of the CNN is in practice separated from training. Furthermore, the CNN models can be evaluated for many systems once the initial training has been completed, while the comparison methods require new initialization for each system. For every total layer number, in both structure ID of reflectance / transmittance and ellipsometric spectra, the CNN solution time is faster than the comparable optimization techniques by several orders of magnitude. Furthermore, the trend in system solution time is toward exponential growth with increasing total layer number for both of the comparison optimization techniques. The CNN solution time remains constant within an order of magnitude regardless of total layer number. This trend highlights the growing impracticality of conventional blind optimization solutions for general nanophotonic systems with high total layer number or high level of complexity. For five total layers least squares solution time is already 6 orders of magnitude greater than the CNN based optimization for both spectral types. This analysis accounts for inverse design accuracy by modifying the hyperparameters associated with each comparison method to minimize solution time while maintaining a layer materials accuracy and layer thickness RMSE similar to the CNN model prediction capabilities. The exponential increase in solution time for the traditional optimization is a result of the increase in total parameter space size as shown in Fig.~\ref{fig5}c. This is a product of the number of material subspaces (all permutations of available material combinations) with the allowed range of thicknesses for each layer (counted by discretizing the space in 1 nm thickness intervals). Although further optimizations of both methods are potentially possible, the increasing exponential trend clearly favors CNN efficiency when designing systems with higher total layer number. Globally optimal solutions require traditional optimization techniques to repeatedly probe the entire design space, which becomes increasingly costly as the size increases. However, CNNs provide a fundamentally different approach by modeling the space in a fixed number of pre-trained weight parameters, so the solution time at evaluation is dependent only upon the number of nodes contained in the model irrespective of the volume of underlying design space. This difference in method is reflected in the observed improvements in solution time for CNNs as compared to these traditional methods. The field of design in thin-film photonics has seen the introduction of many methods beyond those mentioned above. In particular traditional techniques such as the needle method have been shown to produce thin-film photonic structures with extremely high fidelity to defined design targets.\cite{Tikhonravov1996,Tikhonravov2007,Sullivan1996} To illustrate the abilities of our method with respect to this class of design algorithms, a comparison was made between a numerical implementation of the needle method and our CNN models, over the test dataset described above. The results of this comparison can be found in the Supporting Information. From this analysis, it can be concluded that while the numerical needle method does work to minimize the spectral RMSE in predicted structures, the resulting predictions are not typically correct with respect to the known structural parameters. In fact for 4 and 5 total layers, the needle method predicts the correct layer material less accurately than random chance, while producing a spectral RMSE much lower than random chance for the parameter space. The CNN methods, however, produce structures with both optimized spectral RMSE and structural parameters. This is a positive feature of our method, that designing the CNN models to maximize the accuracy of predicted structural parameters results in a corresponding decrease in the spectral RMSE. This is counter to traditional methods which just attempt to minimize the spectral RMSE, and are much more prone to degenerate solutions. In addition, many machine learning methods could in principle be substituted for the CNN methods implemented in this study since neural networks are essentially 'black-box' methods with different internal representations. The comparison between different network methods is relevant since the performance metrics shown above are directly influenced by the network representation efficiency.\cite{Kahn2020,He2016} To illustrate the ability of our CNN methods compared to other machine learning methods, two key comparisons have been considered. The results of these comparisons are shown in the Supporting Information. The two methods considered are more traditional fully-connected deep neural networks (FC-DNNs) and more recent ResNets. From this analysis, it is shown that our CNN method outperforms the FC-DNN method and performs similarly to the ResNet method (within $6\%$ spectral RMSE) for the reflectance / transmittance structure inverse design problem. This indicates that our CNN implementation performs well when compared to the breadth of possible single network machine learning methods for this specific problem. \section{Conclusions} We demonstrate the potential of convolutional neutral networks to solve the ID problem in thin film metamaterials for a completely general library, with multiple choices for both individual layer materials and thicknesses in systems with various total layer number. This problem is difficult due to the large input parameter space for systems with many layers. Furthermore, this convolutional machine learning approach is shown to solve the ID problem for all legs of the inverse design triangle. This includes the inverse design of physical structures based on both ellipsometric and reflectance / transmittance spectra individually, as well as the ability to translate between both spectral types for systems in the design parameter space. Using this method, inverse design is systematically applied to both real and synthetic spectra, allowing for the creative design of real physical systems based on arbitrarily drawn spectra. To illustrate the benefits of the machine learning approach to inverse design, these methods are then compared directly with common traditional methods of inverse design. The convolutional machine learning approach allows us to globally probe the design parameter space for a given library of materials and thicknesses, which can be difficult and costly with traditional methods. This illustrates the full generalizing ability of neural networks to produce systems with a desired spectral response for a wide range of input design parameters. The neural network based inverse design methods applied here are general in terms of the utilized design parameter library, in the sense that the choice of a specific design parameter space is not essential to the observed success of the method. The methods presented can be easily translated into specific inverse design problems based on the desired ranges of materials and thicknesses in the output structures. This is a possible extension of these results into practical implementations for real-life design scenarios. Another possible extension of this work includes increasing the possible range of spectral response by the addition of 2-D metamaterial structures into the existing framework. To overcome the major increase in parameter space associated with general 2-D structures as well as the burden of generating large numbers of structures and associated spectra, effective medium approximations of constrained structures could potentially be employed. Furthermore the role of machine learning in nanophotonics continues to be driven by the discovery and application of new techniques. The application of developing machine learning techniques always has the potential to increase the inverse design efficiency in future models. \section{Methods} \subsection{Generation of the Training Dataset} Training data for the CNNs was generated using the transfer matrix method for layered thin-film metamaterial structures.\cite{Chilwell1984} Samples were generated with total layer number in the range of 1 – 5 discrete material layers. Layer thicknesses were chosen uniformly in the continuous range of [1, 60] nm, with materials chosen from a library of [Ag, Al$_2$O$_3$, ITO, Au and TIO$_2$]. Degeneracy is common problem in photonic inverse design, and an inevitable feature of a large design library, due to the fact that multiple structures can have very similar spectral response. To limit degeneracy in the structural parameters, possible structures with consecutive layers of the same material were removed in the training dataset. Our method still achieves high material accuracy and low layer thickness RMSE despite any remaining degeneracy, in comparison to the needle method. All structures are simulated on an infinite glass substrate. Spectral response was calculated for 200 equally spaced points in the range of [450, 950] nm at the incident angles [25,45,65] deg. A training dataset of 200,000 sample structures was generated for each ID problem type, to be used in training the neural network models (see Supporting Information for more information on material optical properties and the generated dataset). This corresponds to a sampling rate of only about 600 examples per material subspace for four-layer systems and about 150 examples per material subspace for five layer systems. \subsection{Design and Tuning of the Convolutional Structure} The neural network models discussed in this work generally employ a convolutional architecture. This consists of a series of 1-D convolutional layers followed by downsampling with a max pooling layer. The convolutional layers operating on the input spectral types independently. This is followed by a series of several fully connected deep layers which are fully connected to the output nodes. All deep layers are Relu activation. Mixing of information from different spectral types is accomplished in deep fully connected layers following the convolutional layers by adding together parallel layers. Dropout regularization is included following each hidden layer in the model. Raw spectra are passed directly to the network input without further manipulation, except for dividing the ellipsometric spectra by 45 deg to better range the input values. A sample network structure can be seen in Fig.~\ref{fig1}b, for the structure ID of reflectance / transmittance spectra. Individual CNNs are trained independently for each leg of the inverse design triangle as shown in Fig.~\ref{fig1}a and independently for each total layer thickness, except the forward simulation (transfer matrix method) legs. This results in 20 individually trained networks (4 ID problems for each 1-5 layer system). Each CNN model architecture is individually optimized in terms of the total number of convolutional layers, dense layers, nodes per layer, dropout rate and a scaling factor of the learning decay rate. The variance in optimal CNN hyperparameters for different ID problems is plausible, since the design space can be drastically different between individual ID problems. The utilized network structure for each individual network can be found in the Supporting Information. \subsection{Network Training and Evaluation} CNN training is performed using Tensorflow and Keras software in a Python 3 environment. All models were trained for 300 epochs, with a set of 200,000 independent structures. The training learning rate decay is of the form $a/(\sqrt{t}+1)$, where $a$ is a scaling factor optimized for each individual network. All training was performed on a single high performance computing node with 10 cores and 64GB RAM, featuring an NVIDIA 2080 GPU. Full training of the CNN in this environment takes roughly three hours. The CNN evaluation was performed on an independent test set, consisting of 20,000 independent structures drawn from the same statistical range as the training set. For consistency, all networks and comparison optimization methods were evaluated on a high performance computing node with 24 cores and 64GB RAM on the same server and in the same environment as the network training. Comparison methods were fully parallelized to take full advantage of the available resources. Computational resource availability was consistent for all comparisons shown in this work. A full description of the python environment can be found in the Github repository associated with the paper (link given below). \subsection{Loss Function} The CNN training is guided by the loss function, which is a mathematical function providing a quantitative measure of the CNN efficiency by comparing the CNN output for known 'ground truth' examples. During training the CNN optimizes internal weight parameters by minimizing the total loss via the back-propagation algorithm. In structure ID, the loss function is the categorical cross-entropy of individual layer material predictions plus two times the mean squared error (MSE) in the predicted layer thicknesses. Note that layer thickness MSE is correlated with material loss, since the choice of predicted material in each layer necessarily influences the optimal thickness of that layer. In spectral ID, the training loss is simply the MSE in the output spectral response. \begin{acknowledgement} We acknowledge support from the Ohio Third Frontier Project "Research Cluster on Surfaces in Advanced Materials" (RC-SAM) at Case Western Reserve University. A.L., M.H. and G.S. acknowledge financial support from the NSF Grant no. 1904592 "Instrument Development: Multiplex Sensory Interfaces Between Photonic Nanostructures and Thin Film Ionic Liquids". This work made use of the High Performance Computing Resource in the Core Facility for Advanced Research Computing at Case Western Reserve University. \end{acknowledgement} \begin{suppinfo} Supporting information. Link to repository for source code, link to repository for CNN models, material parameters, dataset analysis, MSE landscapes, solution space analysis, CNN results analysis, impact of spectral features, details of the utilized CNN models, comparison with other machine learning methods, comparison with the needle method. \end{suppinfo}
{ "redpajama_set_name": "RedPajamaArXiv" }
2,358
{"url":"https:\/\/tex.stackexchange.com\/questions\/281173\/how-to-check-for-odd-even-pages-when-numbering-pages-by-chapter","text":"# How to check for odd\/even pages when numbering pages by chapter?\n\nAs described here I'm using chappg's \\pagenumbering{bychapter} (implicitly via the auto option) to have pages numbered in the style \\thechapter-\\thepage. But now a \\ifodd\\thepage fails horribly, as this MWE shows:\n\n\\documentclass{scrbook} % same for book, btw\n\\usepackage[auto]{chappg}\n\n\\newcommand*{\\whereami}{%\n\\ifodd\\thepage%\nodd page\n\\else\neven page\n\\fi\n}\n\n\\begin{document}\n\\whereami\\clearpage\\whereami\n\n\\chapter{new}\n\\whereami\\clearpage\\whereami\n\n\\chapter{again}\n\\whereami\\clearpage\\whereami\n\\end{document}\n\nWhile the first two pages (outside a chapter) correctly output \"odd page\" and \"even page\" respectively, the first actual chapter yields \"-1odd page\" and \"-2odd page\" for its two pages, and the second one \"even page\" twice.\n\nSo it seems chappg overrides \\thepage to become e.g. 1-2, and \\ifodd\\thepage only checks the chapter number's oddness, in which case the -2 becomes part of the then output.\n\nI already tried fixing this by using pageslts's \\theCurrentPage instead, but unfortunately that seems to mess around with \\thepage (or \\pagenumbering?) as well, since by merely including that package in addition I get the error\n\n! Argument of \\extract@ has an extra }.\n<inserted text>\n\\par\nl.18 \\whereami\\clearpage\n\\whereami\n\nSo, how can I fix this mess?\n\n\u2022 Isn't this kind of a duplicate of tex.stackexchange.com\/questions\/6143\/\u2026 Dec 2 '15 at 15:28\n\u2022 @clemens That shows how to get that page numbering style, not why my flawed \\ifodd\\thepage failed Dec 2 '15 at 15:31\n\u2022 That's why I said \u201ckind of\u201d and haven't voted to close (BTW: the answers here so far do the same: they show how to get the correct numbering and not where your error is). Since your question is: \u201chow can I fix this mess?\u201d the other question might still be a duplicate\u2026 Dec 2 '15 at 15:34\n\u2022 You are right that \\thepage is not a fixed quantity until page shipout. Thus, testing upon it can lead to spurious results. Dec 2 '15 at 15:48\n\u2022 \\thepage is indeed wrong for testing the page number since \\thepage might very well be \\roman{page} or something, i.e., it does not have to expand to a number so testing for \\value{page} would be better. But this is only a secondary problem. @StevenB.Segletes mentions the real problem: page numbers are only fixed when the page is shipped out \u2013 this is the reason for the various ways for checking even\/odd pages which in the end all fetch the information from the aux file. Dec 3 '15 at 10:46\n\n\\newcommand*{\\whereami}{%\n\\ifthispageodd{%\nodd page\n}{%\neven page\n}%\n}\n\nYou are not required to use a KOMA script class, you can also just \\usepackage{scrextend}.\n\nThe changepage package could be of use.\n\n\\documentclass{scrbook} % same for book, btw\n\n\\usepackage{changepage}\n\n\\newcommand\\whereami{\\checkoddpage\\ifoddpage odd\\else even\\fi}\n\n\\begin{document}\n\\whereami\\clearpage\\whereami\n\n\\chapter{new}\n\\whereami\\clearpage\\whereami\n\n\\chapter{again}\n\\whereami\\clearpage\\whereami\n\\end{document}\n\u2022 This one doesn't depend on KOMA, which is potentially good (though one can still use \\usepackage{scrextend} without a KOMA class). On the other hand, I'll most certainly forget to put the \\checkoddpage in place... Dec 2 '15 at 15:42\n\nYou can use zref for this, see this answer by Martin Scharrer:\n\n\\documentclass{scrbook} % same for book, btw\n\\usepackage[auto]{chappg}\n\\usepackage[user,abspage]{zref}\n\n\\newcounter{whereami}\n\\makeatletter\n\\newcommand*{\\whereami}{%\n\\refstepcounter{whereami}%\n\\zlabel{\\thewhereami @zref}%\n\\ifodd\\zref@extractdefault{\\thewhereami @zref}{abspage}{0}\\relax\nodd page\n\\else\neven page\n\\fi\n}\n\\makeatother\n\n\\begin{document}\n\\whereami\\clearpage\\whereami\n\n\\chapter{new}\n\\whereami\\clearpage\\whereami\n\n\\chapter{again}\n\\whereami\\clearpage\\whereami\n\\end{document}\n\nOf course this needs multiple passes, but using the aux file is the only reliable method for checking page numbers.\n\nI already tried fixing this by using pageslts's \\theCurrentPage instead, but unfortunately that seems to mess around with \\thepage (or \\pagenumbering?) as well, since by merely including that package in addition I get the error\n\nAfter adding \\usepackage{pageslts} and \\pagenumbering{arabic} before \\usepackage[auto]{chappg} and replacing \\thepage with \\theCurrentPage, i.e.\n\n\\documentclass{scrbook} % same for book, btw\n\\usepackage{pageslts}% <- changed\n\\pagenumbering{arabic}% <- changed\n\\usepackage[auto]{chappg}\n\n\\newcommand*{\\whereami}{%\n\\ifodd\\theCurrentPage% <- changed\nodd page\n\\else\neven page\n\\fi\n}\n\n\\begin{document}\n\\whereami\\clearpage\\whereami\n\n\\chapter{new}\n\\whereami\\clearpage\\whereami\n\n\\chapter{again}\n\\whereami\\clearpage\\whereami\n\\end{document}\n\nI do not have any problem compiling your MWE (current TeXLive 2015). Did you use another order of loading perhaps (or older versions of scrbook\/pageslts\/chappg)?\n\n\u2022 Hm, I'm not sure, but I think the problem was that I have a preamble, and \\mainmatter implicitly does \\pagenumberung{arabic} which overrides chappg's style then - so my MWE is too minimal... Feb 26 '16 at 12:05","date":"2021-12-06 10:52:05","metadata":"{\"extraction_info\": {\"found_math\": false, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.8981876373291016, \"perplexity\": 3827.4830837747677}, \"config\": {\"markdown_headings\": true, \"markdown_code\": false, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2021-49\/segments\/1637964363292.82\/warc\/CC-MAIN-20211206103243-20211206133243-00516.warc.gz\"}"}
null
null
{"url":"https:\/\/docs.healthcare.ai\/reference\/machine_learn.html","text":"Prepare data and train machine learning models.\n\nmachine_learn(\nd,\n...,\noutcome,\nmodels,\nmetric,\ntune = TRUE,\npositive_class,\nn_folds = 5,\ntune_depth = 10,\nimpute = TRUE,\nmodel_name = NULL,\nallow_parallel = FALSE\n)\n\n## Arguments\n\nd A data frame Columns to be ignored in model training, e.g. ID columns, unquoted. Name of the target column, i.e. what you want to predict. Unquoted. Must be named, i.e. you must specify outcome = Names of models to try. See get_supported_models for available models. Default is all available models. Which metric should be used to assess model performance? Options for classification: \"ROC\" (default) (area under the receiver operating characteristic curve) or \"PR\" (area under the precision-recall curve). Options for regression: \"RMSE\" (default) (root-mean-squared error, default), \"MAE\" (mean-absolute error), or \"Rsquared.\" Options for multiclass: \"Accuracy\" (default) or \"Kappa\" (accuracy, adjusted for class imbalance). If TRUE (default) models will be tuned via tune_models. If FALSE, models will be trained via flash_models which is substantially faster but produces less-predictively powerful models. For classification only, which outcome level is the \"yes\" case, i.e. should be associated with high probabilities? Defaults to \"Y\" or \"yes\" if present, otherwise is the first level of the outcome variable (first alphabetically if the training data outcome was not already a factor). How many folds to use to assess out-of-fold accuracy? Default = 5. Models are evaluated on out-of-fold predictions whether tune is TRUE or FALSE. How many hyperparameter combinations to try? Default = 10. Value is multiplied by 5 for regularized regression. Ignored if tune is FALSE. Logical, if TRUE (default) missing values will be filled by hcai_impute Quoted, name of the model. Defaults to the name of the outcome variable. Depreciated. Instead, control the number of cores though your parallel back end (e.g. with doMC).\n\n## Value\n\nA model_list object. You can call plot, summary, evaluate, or predict on a model_list.\n\n## Details\n\nThis is a high-level wrapper function. For finer control of data cleaning and preparation use prep_data or the functions it wraps. For finer control of model tuning use tune_models.\n\n## Examples\n\n# These examples take about 30 seconds to execute so aren't run automatically, # but you should be able to execute this code locally. if (FALSE) { # Split the data into training and test sets d <- split_train_test(d = pima_diabetes, outcome = diabetes, percent_train = .9) ### Classification ### # Clean and prep the training data, specifying that patient_id is an ID column, # and tune algorithms over hyperparameter values to predict diabetes diabetes_models <- machine_learn(d$train, patient_id, outcome = diabetes) # Inspect model specification and performance diabetes_models # Make predictions (predicted probability of diabetes) on test data predict(diabetes_models, d$test) ### Regression ### # If the outcome variable is numeric, regression models will be trained age_model <- machine_learn(d$train, patient_id, outcome = age) # Get detailed information about performance over tuning values summary(age_model) # Get available performance metrics evaluate(age_model) # Plot training performance on tuning metric (default = RMSE) plot(age_model) # If new data isn't specifed, get predictions on training data predict(age_model) ### Faster model training without tuning hyperparameters ### # Train models at set hyperparameter values by setting tune to FALSE. This is # faster (especially on larger datasets), but produces models with less # predictive power. machine_learn(d$train, patient_id, outcome = diabetes, tune = FALSE) ### Train models optimizing given metric ### machine_learn(d\\$train, patient_id, outcome = diabetes, metric = \"PR\") }","date":"2021-04-13 22:37:45","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.2042606770992279, \"perplexity\": 6876.727477667892}, \"config\": {\"markdown_headings\": true, \"markdown_code\": false, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2021-17\/segments\/1618038075074.29\/warc\/CC-MAIN-20210413213655-20210414003655-00154.warc.gz\"}"}
null
null
Man Who Cried Wolf? Yoichi Masuzoe's newly-launched party gets off to an unpromising start. Former Cabinet member and TV pundit Yoichi Masuzoe finally launched a 'new' party Friday, the third new political entity to emerge in a fractious month in Japanese politics. Opinion polls suggest Masuzoe has been the No. 1 choice among the public to be prime minister by a wide margin, but whether this latest move will impress the nation looks far from certain. Ridiculed by some members of the Liberal Democratic Party as the 'middle-aged man who cried "Wolf!'', Masuzoe is in danger of living up to that epithet and ultimately being ignored after talking endlessly about leaving the party. Having set up a study group within the LDP earlier this year to look into economic reforms along similar lines to those of former Prime Minister Junichiro Koizumi, Masuzoe, with his growing popularity, seemed set to create a solid support base with a clear agenda within the LDP either to mount a leadership bid after the summer's upper house election or to establish a new party with fellow travelers. As I mentioned in an earlier entry, the conventional tactic of the diehard politician would have been to play the waiting game and then have the LDP eating out of his hand after another poor showing by the party in the upcoming election. No doubt many LDP members were hoping he would play that role. But it seems his blistering criticism of the current LDP leadership alienated too many within the party, leaving him isolated and with no choice but to leave and look for allies to form a new political force. With so many new parties emerging this month with the aim of gaining a casting vote or influential coalition role in a divided post-election upper house, for Masuzoe to make a big impact, it was critical that he distinguished his new political movement from the others. He needed to show his party did have a fresh, vibrant political agenda, coherent policies and more than just the minimum number of Diet members to secure political subsidies. But he seems to have failed on all accounts. Instead of setting up an entirely new political party, he first joined the existing Kaikaku Club party and then renamed it Shinto Kaikaku. The advantage of this, as the conservative Yomiuri Shimbun daily pointed out in an editorial, is that Masuzoe will now have at his disposal a 30 million yen political subsidy just received by the Kaikaku Club. Practical, yes, but the impression of political convenience is one he would have been better to avoid. The new entity has only 6 members. While that's one more than the 5 deemed the necessary minimum for setting up a party and applying for those political subsidies, it's a far cry from the 44 Ichiro Ozawa left the LDP with back in 1993, as mentioned by the Asahi Shimbun today. And the image of political convenience is strengthened further on finding that all the members are from the upper house. That is to say, apart from Masuzoe, they were in danger of losing their seats in the upcoming election if they stayed in the LDP or in the marginalized Kaikaku Club as it was. Now, with Masuzoe's popularity to cling to, they at least can have some hope for the future. Then there's the political agenda. If economic reform was supposed to be the focus of Masuzoe's LDP study group, that looks less likely to be the main thrust of his new party given that the party's general secretary will be Hiroyuki Arai–one of the postal rebels who quit the LDP in opposition to Koziumi's postal privatization plans. Instead, tackling deflation, improving international competitiveness, cleaning up politics and halving the number of Diet members have been set forth as the agenda. Apart from cutting the number of parliamentary representatives, you could imagine every politician in Japan stating such aims. It remains to be seen whether Masuzoe can gain momentum through a more precise explanation of his proposed political vision, the garnering of more members and the forging of alliances with other small parties such as Yoshimi Watanabe's Your Party. But at this point, the prospects do not look as promising as they should have been. In other words, Masuzoe has stumbled just as he stepped up to take center stage. Japan's Safe Nuclear Myth The crisis at the Fukushima nuclear plant and radiation fears have blown a hole in the idea nuclear energy works in Japan. Japan's Quake and the Economy It would be a mistake to argue the earthquake that hit Japan doesn't have big implications for the global economy. Sympathy and Japan's Crisis Despite some insensitive comments, the international response to Japan's earthquake has been sympathetic. Fear and Japan's Nuclear Crisis Media hype around the Fukushima nuclear plant and the radiation danger to Tokyo made tough decisions harder.
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
33
{"url":"http:\/\/mathhelpforum.com\/algebra\/4273-complex-roots-multiplication-print.html","text":"Complex Roots\/Multiplication\n\nPrintable View\n\n\u2022 Jul 22nd 2006, 04:48 PM\nharold\nComplex Roots\/Multiplication\nI'm having trouble multiplying out the conjugates to obtain a quadratic for the following. Both quadratics should multiply to the polynomial $x^4 + 3$ when finished...any help??\n\n$\n\\left( x- \\sqrt[4]{3}[\\frac {\\sqrt{2}} {{2}} - i \\frac {\\sqrt {2}} {{2}}] \\right)\\cdot \\left(x-\\sqrt[4]{3}[\\frac {\\sqrt{2}} {{2}} + i \\frac {\\sqrt {2}} {{2}}]\\right)\n$\n\nsecond pair:\n\n$\n\\left( x- \\sqrt[4]{3}[-\\frac {\\sqrt{2}} {{2}} - i \\frac {\\sqrt {2}} {{2}}] \\right)\\cdot \\left( x-\\sqrt[4]{3}[-\\frac {\\sqrt{2}} {{2}} + i \\frac {\\sqrt {2}} {{2}}]\\right)\n$\n\u2022 Jul 22nd 2006, 06:14 PM\nThePerfectHacker\nRemember that,\n$(x-z_1)(x-z_2)=x^2-(z_1+z_2)x+z_1z_2$\nGiven,\n$\\left( x- \\sqrt[4]{3}[\\frac {\\sqrt{2}} {{2}} - i \\frac {\\sqrt {2}} {{2}}] \\right)$\nWhen expanded,\n$\\left( x - \\frac{\\sqrt{2}\\sqrt[4]{3}}{2}+\\frac{\\sqrt{2}\\sqrt[4]{3}i}{2} \\right)$\nNote, (and watch those signs :eek: ) that,\n$z_1=\\frac{\\sqrt{2}\\sqrt[4]{3}}{2}-\\frac{\\sqrt{2}\\sqrt[4]{3}i}{2}$\nIn the conjugate,\n$\\left(x-\\sqrt[4]{3}[\\frac {\\sqrt{2}} {{2}} + i \\frac {\\sqrt {2}} {{2}}]\\right)\n$\n\nWhen expanded,\n$\\left( x-\\frac{\\sqrt{2}\\sqrt[4]{3}}{2}-\\frac{\\sqrt{2}\\sqrt[4]{3}i}{2} \\right)$\nNote, (and watch those signs :eek: ) that,\n$z_2=\\frac{\\sqrt{2}\\sqrt[4]{3}}{2}+\\frac{\\sqrt{2}\\sqrt[4]{3}i}{2}$\nThus,\n$z_1+z_2=\\sqrt{2}\\sqrt[4]{3}$\nAnd,\n$z_1z_2=\\left( \\frac{\\sqrt{2}\\sqrt[4]{3}}{2} \\right)^2+\\left( \\frac{\\sqrt{2}\\sqrt[4]{3}}{2} \\right)^2=\\sqrt{3}$\n\u2022 Jul 23rd 2006, 09:44 AM\nSoroban\nHello, harold!\n\nRecall that: . $(a + b)(a - b)\\:=\\:a^2 - b^2$\n\nQuote:\n\nBoth quadratics should multiply to the polynomial $x^4 + 3$ when finished.\n\nFirst pair: . $\\left( x- \\sqrt[4]{3}\\left[\\frac {\\sqrt{2}} {{2}} - i \\frac {\\sqrt {2}} {{2}}\\right] \\right)\\cdot \\left(x-\\sqrt[4]{3}\\left[\\frac {\\sqrt{2}} {{2}} + i \\frac {\\sqrt {2}} {{2}}\\right]\\right)\n$\n\nSecond pair: . $\\left( x- \\sqrt[4]{3}\\left[-\\frac {\\sqrt{2}} {{2}} - i \\frac {\\sqrt {2}} {{2}}\\right] \\right)\\cdot \\left( x-\\sqrt[4]{3}\\left[-\\frac {\\sqrt{2}} {{2}} + i \\frac {\\sqrt {2}} {{2}}\\right]\\right)\n$\n\nNote that: $\\sqrt[4]{3}\\cdot\\sqrt{2}\\,=\\,\\sqrt[4]{12}$ .and $\\left(\\frac{\\sqrt[4]{12}}{2}\\right)^2 = \\frac{\\sqrt{12}}{4} = \\frac{2\\sqrt{3}}{4} = \\frac{\\sqrt{3}}{2}$\n\nFirst pair: . $\\left( x- \\sqrt[4]{3}\\left[\\frac {\\sqrt{2}} {{2}} - i \\frac {\\sqrt {2}} {{2}}\\right] \\right)\\cdot \\left(x-\\sqrt[4]{3}\\left[\\frac {\\sqrt{2}} {{2}} + i \\frac {\\sqrt {2}} {{2}}\\right]\\right)\n$\n\n. . $= \\;\\left( x- \\frac {\\sqrt[4]{12}} {{2}} + i \\frac {\\sqrt[4]{12}} {{2}}\\right)\\cdot \\left(x - \\frac {\\sqrt[4]{12}} {{2}} - i\\frac {\\sqrt[4]{12}} {{2}}\\right)$\n\n. . $= \\;\\left(\\left[ x- \\frac {\\sqrt[4]{12}} {{2}}\\right] + i \\frac {\\sqrt[4]{12}} {{2}}\\right)\\cdot$ $\\left(\\left[x - \\frac {\\sqrt[4]{12}} {{2}}\\right] - i\\frac {\\sqrt[4]{12}} {{2}}\\right)\\quad\\Leftarrow\\quad(a + b)(a - b)$\n\n. . $= \\;\\left(x- \\frac {\\sqrt[4]{12}} {{2}}\\right)^2 - \\left(i \\frac {\\sqrt[4]{12}} {{2}}\\right)^2\\quad\\Leftarrow\\quad a^2 - b^2$\n\n. . $= \\;\\left(x^2 - \\sqrt[4]{12}x + \\frac{\\sqrt{3}}{2}\\right) - \\left(-\\frac{\\sqrt{3}}{2}\\right)$\n\n. . $= \\;x^2 - \\sqrt[4]{12}x + \\sqrt{3}$\n\nSimilarly, the second pair becomes: . $x^2 + \\sqrt[4]{12}x + \\sqrt{3}$\n\nWe have: . $\\left(x^2 - \\sqrt[4]{12}x + \\sqrt{3}\\right)\\cdit\\left(x^2 + \\sqrt[4]{12}x + \\sqrt{3}\\right)$\n\n. . $=\\;\\left[(x^2 + \\sqrt{3}) - \\sqrt[4]{12}x\\right]\\cdot\\left[(x^2+\\sqrt{3}) + \\sqrt[4]{12}x\\right]\\quad\\Leftarrow$ $(a - b)(a + b)$\n\n. . $= \\;(x^2 + \\sqrt{3})^2 - (\\sqrt[4]{12}x)^2\\quad\\Leftarrow\\quad a^2 - b^2$\n\n. . $= \\;x^4 + 2\\sqrt{3}x^2 + 3 - \\sqrt{12}x^2$\n\n. . $= \\;x^4 + 2\\sqrt{3}x^2 + 3 - 2\\sqrt{3}x^2$\n\n. . $= \\;x^4 + 3$ . . . ta-DAA!","date":"2016-09-27 13:21:42","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 33, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.9927209615707397, \"perplexity\": 13911.912607127566}, \"config\": {\"markdown_headings\": false, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": false}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2016-40\/segments\/1474738661051.55\/warc\/CC-MAIN-20160924173741-00195-ip-10-143-35-109.ec2.internal.warc.gz\"}"}
null
null
JAY-Z, Yo Gotti & Roc Nation Set To Expose Mississippi Penitentiary With A&E Doc By Glen Eastwood On 24 February 2022 A&E Networks announced on Thursday (February 24) that they had greenlit an upcoming four-part docu-series titled Exposing Parchman. The series will follow JAY-Z, Yo Gotti and Roc Nation's philanthropic branch Team Roc after they spearheaded a civil rights lawsuit alongside the 29 inmates of Mississippi's notorious Parchman Prison. The doc will follow the inmates and rappers as they undergo lengthy efforts to reform the corrupt Mississippi Department of Corrections. The documentary comes after Parchman Prison made national headlines in December 2019 for its high death toll and rampant neglect of the inmate's basic human needs. The series will follow the developing legal case and will delve further into Parchman's longstanding history of corruption and abuse. Desiree Perez, the CEO of Roc Nation, said in a statement that Team Roc, "launched a fight to put a stop to the literal death sentences imposed on inmates through the inhumane, violent, and torturous conditions created by Parchman prison officials. We are honored to develop this series with A&E, Good Caper and ITV to continue to make sure the atrocities and history of Parchman are top of mind on a national stage." "A&E has the privilege to partner with Roc Nation to tell the truly urgent story of Parchman Prison as we continue our commitment to impactful programming," Elaine Frontain Bryant, Executive Vice President and Head of Programming for A&E, said in a statement. "The series is emblematic of larger issues within the U.S. criminal justice system, and we hope it spurs desperately needed awareness both at Parchman Prison, and nationwide." On behalf of Team Roc, Roc Nation attorney Alex Spiro filed their first suit against the Mississippi Department of Corrections in January of 2020, citing the recent deaths of multiple inmates as "a direct result of Mississippi's utter disregard for the people it has incarcerated and their constitutional rights." The second suit, filed in February 2020, represented 152 inmates and demanded the "barbaric" conditions at Parchman be addressed immediately. A release date for the docu-series has yet to be announced. GAP CEO Confirms That Yeezy GAP Partnership Has Ended "Sonic The Hedgehog" Isn't Terrifying Anymore In New Trailer 'Aladdin' Trailer Showcases A Lot More of Will Smith's Genie India.Arie Reveals "Worthy" Album Cover Art & Track List
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
9,528
{"url":"https:\/\/msp.org\/agt\/2009\/9-2\/b16.xhtml","text":"#### Volume 9, issue 2 (2009)\n\nThe first cohomology of the mapping class group with coefficients in algebraic functions on the $\\mathrm{SL}_2(\\mathbf{C})$ moduli space","date":"2019-07-24 07:12:58","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.4416716992855072, \"perplexity\": 245.29952188071164}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2019-30\/segments\/1563195531106.93\/warc\/CC-MAIN-20190724061728-20190724083728-00387.warc.gz\"}"}
null
null
Q: std::vector and VBOs render only the last shape I'm running through a weird problem. Basically I have Mesh class depending on a flag, I can draw a point, a line, or a triangle. For example, if I want to draw two lines, I can do the following Vertex vertices1[] = { Vertex(glm::vec3(-.5, -.5, 0)), Vertex(glm::vec3( 0, .5, 0)) }; Vertex vertices2[] = { Vertex(glm::vec3( .5, -.5, 0)), Vertex(glm::vec3( -.5, .5, 0)) }; Mesh mesh1(vertices1, sizeof(vertices1)/sizeof(vertices1[0]), 'L'); Mesh mesh2(vertices2, sizeof(vertices2)/sizeof(vertices2[0]), 'L'); // Rendering Loop: while( Window.isOpen() ){ ... //================( Rendering )========================= ourShader.Use(); mesh1.draw(); mesh2.draw(); //====================================================== ... } The result is Now I would like to use std::vector<Mesh> and loop through meshes. My attempt is as follows std::vector<Mesh> meshes; meshes.push_back(mesh1); meshes.push_back(mesh2); while( Window.isOpen() ){ ... //================( Rendering )========================= ourShader.Use(); for ( int i(0); i < meshes.size(); ++i ) meshes[i].draw(); //====================================================== ... } With the preceding approach, only the last line is drawn and this is the result Moreover, once I use .push_back() even if I don't loop through the vector, the last line is drawn. I don't understand why using std::vector deteriorates the rendering. I even tried meshes[0].draw() but with no luck. Any suggestions? Edit: This is the constructor of Mesh class #include <iostream> #include <vector> #include <glm/glm.hpp> #include <GL/glew.h> #include <GLFW/glfw3.h> #include "display.h" #include "keyboard.h" #include "shader.h" class Vertex { public: Vertex(const glm::vec3& p) : m_position(p) {} private: glm::vec3 m_position; }; class Mesh { public: Mesh(Vertex* vertices, unsigned int numVertices, const char& flag); ~Mesh(); void draw(); private: enum{ POSITION_VB, NUM_BUFFERS }; GLuint m_vertexArrayObject; GLuint m_vertexArrayBuffers[NUM_BUFFERS]; unsigned int m_drawCount; char m_flag; }; Mesh::Mesh(Vertex* vertices, unsigned int numVertices, const char& flag) : m_flag(flag), m_drawCount(numVertices) { glGenVertexArrays(1, &m_vertexArrayObject); glBindVertexArray(m_vertexArrayObject); glGenBuffers(NUM_BUFFERS, m_vertexArrayBuffers); glBindBuffer(GL_ARRAY_BUFFER, m_vertexArrayBuffers[POSITION_VB]); glBufferData(GL_ARRAY_BUFFER, numVertices*sizeof(vertices[0]), vertices, GL_STATIC_DRAW); glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindVertexArray(0); } Mesh::~Mesh() { glDeleteVertexArrays(1, &m_vertexArrayObject); glDeleteBuffers(1, m_vertexArrayBuffers); } void Mesh::draw() { switch(m_flag) { case 'P': glBindVertexArray(m_vertexArrayObject); glDrawArrays(GL_POINTS, 0, m_drawCount); glBindVertexArray(0); break; case 'L': glBindVertexArray(m_vertexArrayObject); glDrawArrays(GL_LINES, 0, m_drawCount); glBindVertexArray(0); break; case 'T': glBindVertexArray(m_vertexArrayObject); glDrawArrays(GL_TRIANGLES, 0, m_drawCount); glBindVertexArray(0); break; } } int main(void) { Display Window(800, 600, "OpenGL Window"); Keyboard myKeyboard( Window.getWindowPointer() ); Vertex vertices1[] = { Vertex(glm::vec3(-.5, -.5, 0)), Vertex(glm::vec3( 0, .5, 0)) }; Vertex vertices2[] = { Vertex(glm::vec3( .5, -.5, 0)), Vertex(glm::vec3( -.5, .5, 0)) }; Mesh mesh1(vertices1, sizeof(vertices1)/sizeof(vertices1[0]), 'L'); Mesh mesh2(vertices2, sizeof(vertices2)/sizeof(vertices2[0]), 'L'); std::vector<Mesh> meshes; meshes.emplace_back(mesh1); meshes.emplace_back(mesh2); std::cout << meshes.size() << std::endl; //*****************( SHADER )************************ Shader ourShader("shader.vs", "shader.frag"); glEnable(GL_PROGRAM_POINT_SIZE); while( Window.isOpen() ){ Window.PollEvents(); Window.clear(); //================( Rendering )========================= ourShader.Use(); //mesh1.draw(); //mesh2.draw(); for ( int i(0); i < meshes.size(); ++i ) meshes[i].draw(); //meshes[0].draw(); //meshes[1].draw(); //====================================================== Window.SwapBuffers(); } glfwTerminate(); return 0; } Shaders #version 330 core out vec4 color; void main() { color = vec4(1.0f,0.5f,0.2f,1.0f); } #version 330 core layout (location = 0) in vec3 position; void main() { gl_PointSize = 10.0; gl_Position = vec4(position, 1.0); } A: As I suspected, the problem is with the (lack of) copy constructor. The default one just copies all the members. As a result your VAOs and buffers get deleted multiple times, even before you manage to draw anything (vectors move during reallocation, and if they can't move they copy). As a rule of thumb: if you have a non-default destructor, you must implement also a copy constructor and an assignment operator, or explicitly delete them if your class is not meant to be copyable. For your concrete case the solutions are: * *Quick solution: store pointers to meshes in the vector: std::vector<Mesh*> meshes; meshes.emplace_back(&mesh1); meshes.emplace_back(&mesh2); *Correct solution: use proper RAII for resource management. Using the unique_ptr technique from here your MCVE code becomes: class Mesh { public: Mesh(Vertex* vertices, unsigned int numVertices, const char& flag); void draw(); private: //... GLvertexarray m_vertexArrayObject; GLbuffer m_vertexArrayBuffers[NUM_BUFFERS]; unsigned int m_drawCount; char m_flag; }; Mesh::Mesh(Vertex* vertices, unsigned int numVertices, const char& flag) : m_flag(flag), m_drawCount(numVertices) { GLuint id; glGenVertexArrays(1, &id); glBindVertexArray(id); m_vertexArrayObject.reset(id); for(int i = 0; i < NUM_BUFFERS; ++i) { glGenBuffers(1, &id); glBindBuffer(GL_ARRAY_BUFFER, id); m_vertexArrayBuffers[i].reset(id); glBufferData(GL_ARRAY_BUFFER, numVertices*sizeof(vertices[0]), vertices, GL_STATIC_DRAW); } glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindVertexArray(0); } void Mesh::draw() { switch(m_flag) { case 'P': glBindVertexArray(m_vertexArrayObject.get()); glDrawArrays(GL_POINTS, 0, m_drawCount); glBindVertexArray(0); break; case 'L': glBindVertexArray(m_vertexArrayObject.get()); glDrawArrays(GL_LINES, 0, m_drawCount); glBindVertexArray(0); break; case 'T': glBindVertexArray(m_vertexArrayObject.get()); glDrawArrays(GL_TRIANGLES, 0, m_drawCount); glBindVertexArray(0); break; } } int main() { //... Mesh mesh1(vertices1, sizeof(vertices1)/sizeof(vertices1[0]), 'L'); Mesh mesh2(vertices2, sizeof(vertices2)/sizeof(vertices2[0]), 'L'); std::vector<Mesh> meshes; meshes.emplace_back(std::move(mesh1)); meshes.emplace_back(std::move(mesh2)); // ... return 0; } Notice how there is no more need for defining a destructor, and your class automatically becomes movable but not copyable. Furthermore, if you have OpenGL 4.5 or ARB_direct_state_access then things get even simpler. A: EDIT The main problem is, that the destructor is called when you add the Mesh objects to the vector, therefore the underlying data gets cleaned up. Further reading: Why does my class's destructor get called when I add instances to a vector? | What is The Rule of Three? I'd personally create separate init_buffers and free_buffers methods to my Mesh class and use them appropriately. (Initialize buffers after the OpenGL context is obtained, free the buffers when the window is closed.) This way you can start building meshes (and add them to the scene) before actually having the OpenGL context. I've implemented the missing code parts and tried your code using GLFW using CLion. It works. See code / CLion project here: OpenGLSandbox/main.cpp The only code I've added are basically these, so it's your turn to figure out the difference / error. // Constants const size_t NUM_BUFFERS = 1; const size_t POSITION_VB = 0; // Vertex class class Vertex { private: glm::vec3 mCoords; public: Vertex(glm::vec3 coords) : mCoords(coords) {}; }; // Mesh class class Mesh { private: GLuint m_vertexArrayObject; char m_flag; unsigned int m_drawCount; GLuint m_vertexArrayBuffers[NUM_BUFFERS]; public: /* your ctor and draw method */ }
{ "redpajama_set_name": "RedPajamaStackExchange" }
4,147
Cristian Ludwig Brehm ( 24 de enero de 1787 - 23 de junio de 1864) fue un pastor alemán y ornitólogo. Era el padre de Alfred Brehm. Brehm nació en Gotha, y estudió en la Universidad de Jena. En 1813 se hizo ministro en Renthendorf, un pueblo a 100 km al sur de Leipzig donde permaneció hasta su muerte. Sus extensos escritos incluyeron el Beitrage zur Vogelkunde (1820-22) donde describió 104 especies de pájaros alemanes en detalle y Handbuch der Naturgeschichte aller Vogel Deutschlands (1831). Brehm hizo una colección de 15.000 pieles de pájaros. Se las ofreció al Museo Zoológico de Berlín, pero la venta no fue posible. Después de su muerte, permanecían en el ático de su casa dónde Otto Kleinschmidt los descubrió años después. Kleinschmidt persuadió Lord Rothschild para comprarlos, y la colección llegó a su Museo en Tring en 1900. Especies válidas descriptas por Brehm Obra Beiträge zur Vögelkunde. 3 vols., y el vol. 3 en colaboración con W. Schilling. Neustadt an der Orla 1820–1822 Lehrbuch der Naturgeschichte aller europäischen Vögel. 2 vols. Jena 1823–1824 Ornis oder das neueste und Wichtigste der Vögelkunde. Jena 1824–1827 (primera revista ornitológica en el mundo) Handbuch der Naturgeschichte alle Vögel Deutschlands. Ilmenau 1831 Handbuch für den Liebhaber der Stuben-, Haus- und aller der Zähmung werthen Vögel. Ilmenau 1832 Der Vogelfang. Leipzig 1836 Der vollständige Vogelfang. Weimar 1855 Die Kunst, Vögel als Bälge zu bereiten. Weimar 1842 Die Wartung, Pflege und Fortpflanzung der Canarienvögel. Weimar 1855, 2ª ed. Weimar 1865, 3ª ed. Weimar 1872, 4ª ed. Weimar 1883, 5ª ed. Weimar 1893 Die Naturgeschichte und Zucht der Tauben. Weimar 1857 E. Baldamus, C.L. Brehm, John Wilhelm von Müller & J.F. Naumann. Verzeichnis der Vögel Europa's. als Tausch-Catalog eingerichtet. Stuttgart 1852 Monographie der Papageien oder vollständige Naturgeschichte aller bis jetzt bekannten Papageien mit getreuen und ausgemalten Abbildungen, im Vereine mit anderen Naturforscher herausgegeben von C.L. Brehm. Jena/Paris 1842–1855 Referencias The Bird Collectors, de Barbara & Richard Mearns ISBN 0-12-487440-1 Enlaces externos Ministros religiosos protestantes Ornitólogos de Alemania del siglo XIX Escritores en alemán del siglo XIX Miembros de la Leopoldina
{ "redpajama_set_name": "RedPajamaWikipedia" }
4,265
Я́дерне горі́ння ки́сню (ядерне горіння Оксигену) — умовна назва ядерних реакцій злиття ядер в надрах зір, важчих від Сонця. Воно відбувається при температурі близько і густині порядку . Основні реакції «горіння» Оксигену: Реакції з двохчастинним кінцевим станом: ,  = 9,594 МеВ ,  = 7,678 МеВ ,  = 1,500 МеВ ,  = 2,409 МеВ ,  = 16,54 МеВ Реакції з трьохчастинним кінцевим станом: ,  = 0,381 МеВ ,  = 0,39 МеВ ,  = 1,99 МеВ Для масивних зір (понад 25 сонячних мас) тривалість горіння Оксигену оцінюється в 0,5 року, тобто, за астрономічними мірками воно відбувається дуже швидко. Див. також Зоряний нуклеосинтез Примітки Посилання Распадно-синтезное преобразование элементов Звездный нуклеосинтез — источник происхождения химических элементов Происхождение звёзд и химических элементов Arnett, W. D. Advanced evolution of massive stars. VI — Oxygen burning / Astrophysical Journal, vol. 194, Dec. 1, 1974, pt. 1, p. 373—383. Нуклеосинтез
{ "redpajama_set_name": "RedPajamaWikipedia" }
6,834
Zmarli Andrzej z Buku, polski teolog Ambrose Traversari, włoski teolog Kalendarium literatury
{ "redpajama_set_name": "RedPajamaWikipedia" }
1,760
ALS Symptoms in Women Amyotrophic Lateral Sclerosis (ALS) is a degenerative disease of motor neurons. ALS symptoms in women are hardly any different from those in men. Home / Women's Health / ALS Symptoms in Women Amyotrophic Lateral Sclerosis (ALS) is a degenerative disease of motor neurons. Did you know that about 20,000 people are affected with ALS in US alone? Every year 5000 new cases of ALS are diagnosed. It equally affects people of all origins, and geographic locations. Amyotrophic Lateral Sclerosis (ALS) is a disease that affects voluntary muscles in the body. The degeneration of motor neurons is responsible for this condition. It is basically a genetic disorder and about 5 to 10% of ALS cases are inherited. Earlier, it was believed that ALS is more prevalent in men than in women, however, studies have shown that women are equally susceptible to get this disease. Early ALS symptoms in women ALS is a slow invading disease which strikes people in the age group of 40 to 60, though it is not unusual to find younger patients. In this disease, the motor neurons present in the brain as well as in the spinal cord degenerate or die. This leads to impairment of the motor function in the entire body. ALS is also known as Lou Gehrig's Disease, after the name of legendary baseball player, who fell prey to this disease. However, ALS is more commonly known to masses due to its other victim, world famous physicist Stephen Hawking. Due to the slow onset of the disease, the diagnosis is often delayed which limits the treatment options. Some of the early symptoms of ALS are listed below. Since, the disease attacks motor neurons, which are responsible for the movement of the body, the first signs of disease are exhibited through the malfunctioning of muscles. The person experiences unusual muscle fatigue and weakness, sometimes accompanied with muscle pain. Muscle cramps are also common at this stage. The person is unable to move arms, which further degenerates the motor neurons. The person finds it increasingly difficult to perform daily tasks such as dressing, washing, etc. Difficulty in walking Imbalance, tripping, falling are some other symptoms of ALS which surface at an early stage. Since the muscles of leg become weak, they cannot support the body weight, which eventually results in falling or tripping. No control over expressions Since the voluntary muscles begin to slow down their function, the person loses control over her expressions such as laughing or crying. If she starts laughing at some point, she may be unable to stop it for a long time. Similarly, if the person starts crying, it will be some time before she can regain the control over her expressions. Dysphagia is difficulty in swallowing food or liquids. Dysphagia is also attributable to the weakness of voluntary muscles of throat and mouth. ALS symptoms that may surface at a later stage As the disease progresses to the later stages, the body begins to lose control over most of its voluntary functions. However, the noteworthy thing regarding ALS is that no matter how badly it affects the person physically, it rarely has any effect on the cognitive abilities of the person. The mind remains as sharp as ever unless there is an occurrence of Frontotemporal Dementia (FTD). In some cases, this disease is known to have contributed to depression or memory loss. The senses of sight, touch, hearing, taste, smell, muscles of the eyes and bladder are rarely affected. The following ALS disease symptoms become prominent in the later stages: As the disease affects the motor neurons responsible for speech, the person is unable to speak clearly. As a result, the speech is slurred. Complete loss of movements At this stage, the person completely loses her ability to move muscles. She is often bed ridden with a constant need of supervision. She becomes greatly dependent upon others to perform her daily tasks. As the muscles of lung start to weaken, the person experiences, shortness of breath. This may give rise to various respiratory infections, such as pneumonia. The person may have to be kept on ventilation for the rest of her life. This is usually the last stage of the progression of the disease. Even with the aid of ventilator, the person still finds it difficult to thrive and usually succumbs to death. ALS problems in women can only be discovered when the symptoms become more pronounced. Delayed ALS diagnosis in women may hamper the survival rate of an individual. There are no treatments for ALS that can completely cure the disease or reverse its effects on the body. However, palliative measures can be adopted to ease the symptoms and prolong the life of a patient. Disclaimer: This HerHaleness article is for information purpose only, hence should not be used as a substitute for medical practitioner's advice.
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
6,686
About IOCAG Home » About IOCAG » History The Institute of Oceanography and Global Change is one of the seven university research institutes hosted by the University of Las Palmas de Gran Canaria (ULPGC), whose constitution was approved in August 2011 (1). This research institute is the natural consequence of the research activities developed in the ULPGC for three decades in the field of marine science. The Marine Science Faculty pioneered these studies in Spain since the early 80's. Those first trained professionals joined the faculty members who had hitherto been their teachers, thus setting up a comprehensive research environment. The report published by the Foundation for Knowledge and Development in its 2011 edition (2) highlights that ULPGC ranks as the first Spanish University in the field of Earth Sciences, in regard to publications included in the first quartile (> 70%), which certainly reveals the high quality of research performed by IOCAG members. Furthermore, the creation of this new institute is part of the actions taken by the Canarian universities within the Tricontinental Atlantic Campus, seeking to convert the Canary Islands in a national and international reference in the field of marine research, leveraging its geostrategic location. IOCAG raises three objectives: 1) to enhace the Europe-Africa-America hub in the marine environment, 2) the internationalization of education, research, development and innovation and transfering the knowledge and information and communication technologies (ICT) of the marine environment, 3) intensify the sustanable exploitation model for marine resources to facilitate local economic development. More information about the Canarian Decree 257/2011, July 28th, about the creation of the IOCAG as a scientific and technical research centre of the University of Las Palmas de Gran Canaria here . More information about raking CYD of the Spanish universities here . Instituto de Oceanografía y Cambio Global - IOCAG We aim IOCAG to be the seed of a greater interdisciplinary Research Center for Global Change in the Canary Islands, where additional research groups addressing Global Change from different perspectives could also be integrated. Address: Universidad de Las Palmas de Gran Canaria. Parque Científico Tecnológico Marino de Taliarte, s/n.35214 Telde. Spain Email: gestor_iocag@ulpgc.es © Copyright 2020 by IOCAG. All Rights Reserved. Legal Note. Copyright © 2023, IOCAG. Theme by Devsaran.
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
1,825
Копыловы — дворянский род. Фамилии Копыловых, многие Российскому Престолу служили дворянские службы в разных чинах, и жалованы были в 1667 и других годах поместьями. Происхождение Родоначальник — сибирский казак Копылов, посланный царицей Екатериной II на освоении Сибири и Дальнего востока в XVIII веке. Основатель рода Дмитрий Епифанович Копылов, как свидетельствовал его внук, родом был из Москвы и пришёл в Томск (до 1626) и первоначально служил десятником конных казаков, пятидесятником (1630), затем атаманом (1635). Во главе отряда томских казаков отправился на восток для поиска новых земель (1636). На реке Алдан им основан Бутальский острог, из которого весной (1639) вышел отряд под началом Ивана Москвитина для "проведывания" моря, о котором рассказывали эвенки. В том же году томскими землепроходцами было основано первое русское поселение на побережье Тихого океана — в устье реки Ульи, впадающей в Охотское море. После разведки окрестных земель отряд Москвитина соединился с отрядом Копылова в Якутске, откуда они вместе вернулись в Томск (1641). За заслуги в этом походе он получил чин сына боярского (1643). Во время томского восстания (1648-1649) вместе с сыном Григорием поддерживал воеводу Осипа Щербатого и пострадал от восставших. В 1657 вместе с сыном боярским Юрием Едловским ему было поручено построить Сосновский острог южнее Томска. Сыновья Дмитрия Епифановича основали д. Копылово, в которой до сих пор проживают потомки знаменитого сибирского первопроходца, впрочем, как и по всему миру. Описание герба В щите, разделённом диагонально на две части, в верхней в правом голубом поле изображена золотая сабля. В нижней части в зелёном и красном шахматном поле золотой подсолнечник с листьями, прямо поставленный корнем вниз. Щит увенчан дворянским шлемом со страусовыми перьями. Намёт на щите голубой, подложенный красным. Герб внесён в Общий гербовник дворянских родов Российской империи, часть 3, стр. 104. Известные представители Копылов Семён Матвеевич - подьячий, дьяк (1629-1636), воевода на Ваге (1626-1627), на Белоозере (1631), в Тобольске (1632-1635). Копылов Григорий - воевода в Друе (1656). Литература Аврам Никитич Копылов, надворный советник и Федор Никитич Копылов, поручик, жалованы дипломом в подтверждение потомственного дворянского достоинства. РГИА, ф.1411, оп.1, д.250 Примечания Дворянские роды, на гербах которых изображены три страусовых пера
{ "redpajama_set_name": "RedPajamaWikipedia" }
8,955
Q: RegEx - reusing subexpressions Say I have a regex matching a hexadecimal 32 bit number: ([0-9a-fA-F]{1,8}) When I construct a regex where I need to match this multiple times, e.g. (?<from>[0-9a-fA-F]{1,8})\s*:\s*(?<to>[0-9a-fA-F]{1,8}) Do I have to repeat the subexpression definition every time, or is there a way to "name and reuse" it? I'd imagine something like (warning, invented syntax!) (?<from>{hexnum=[0-9a-fA-F]{1,8}})\s*:\s*(?<to>{=hexnum}) where hexnum= would define the subexpression "hexnum", and {=hexnum} would reuse it. Since I already learnt it matters: I'm using .NET's System.Text.RegularExpressions.Regex, but a general answer would be interesting, too. A: Why not do something like this, not really shorter but a bit more maintainable. String.Format("(?<from>{0})\s*:\s*(?<to>{0})", "[0-9a-zA-Z]{1,8}"); If you want more self documenting code i would assign the number regex string to a properly named const variable. A: .NET regex does not support pattern recursion, and if you can use (?<from>(?<hex>[0-9a-fA-F]{1,8}))\s*:\s*(?<to>(\g<hex>)) in Ruby and PHP/PCRE (where hex is a "technical" named capturing group whose name should not occur in the main pattern), in .NET, you may just define the block(s) as separate variables, and then use them to build a dynamic pattern. Starting with C#6, you may use an interpolated string literal that looks very much like a PCRE/Onigmo subpattern recursion, but is actually cleaner and has no potential bottleneck when the group is named identically to the "technical" capturing group: C# demo: using System; using System.Text.RegularExpressions; public class Test { public static void Main() { var block = "[0-9a-fA-F]{1,8}"; var pattern = $@"(?<from>{block})\s*:\s*(?<to>{block})"; Console.WriteLine(Regex.IsMatch("12345678 :87654321", pattern)); } } The $@"..." is a verbatim interpolated string literal, where escape sequences are treated as combinations of a literal backslash and a char after it. Make sure to define literal { with {{ and } with }} (e.g. $@"(?:{block}){{5}}" to repeat a block 5 times). For older C# versions, use string.Format: var pattern = string.Format(@"(?<from>{0})\s*:\s*(?<to>{0})", block); as is suggested in Mattias's answer. A: If I am understanding your question correctly, you want to reuse certain patterns to construct a bigger pattern? string f = @"fc\d+/"; string e = @"\d+"; Regex regexObj = new Regex(f+e); Other than this, using backreferences will only help if you are trying to match the exact same string that you have previously matched somewhere in your regex. e.g. /\b([a-z])\w+\1\b/ Will only match : text, spaces in the above text : This is a sample text which is not the title since it does not end with 2 spaces. A: RegEx Subroutines When you want to use a sub-expression multiple times without rewriting it, you can group it then call it as a subroutine. Subroutines may be called by name, index, or relative position. Subroutines are supported by PCRE, Perl, Ruby, PHP, Delphi, R, and others. Unfortunately, the .NET Framework is lacking, but there are some PCRE libraries for .NET that you can use instead (such as https://github.com/ltrzesniewski/pcre-net). Syntax Here's how subroutines work: let's say you have a sub-expression [abc] that you want to repeat three times in a row. Standard RegEx Any: [abc][abc][abc] Subroutine, by Name Perl:     (?'name'[abc])(?&name)(?&name) PCRE: (?P<name>[abc])(?P>name)(?P>name) Ruby:   (?<name>[abc])\g<name>\g<name> Subroutine, by Index Perl/PCRE: ([abc])(?1)(?1) Ruby:          ([abc])\g<1>\g<1> Subroutine, by Relative Position Perl:     ([abc])(?-1)(?-1) PCRE: ([abc])(?-1)(?-1) Ruby:   ([abc])\g<-1>\g<-1> Subroutine, Predefined This defines a subroutine without executing it. Perl/PCRE: (?(DEFINE)(?'name'[abc]))(?P>name)(?P>name)(?P>name) Examples Matches a valid IPv4 address string, from 0.0.0.0 to 255.255.255.255: ((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))\.(?1)\.(?1)\.(?1) Without subroutines: ((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))\.((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))\.((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9]))\.((?:25[0-5])|(?:2[0-4][0-9])|(?:[0-1]?[0-9]?[0-9])) And to solve the original posted problem: (?<from>(?P<hexnum>[0-9a-fA-F]{1,8}))\s*:\s*(?<to>(?P>hexnum)) More Info http://regular-expressions.info/subroutine.html http://regex101.com/ A: There is no such predefined class. I think you can simplify it using ignore-case option, e.g.: (?i)(?<from>[0-9a-z]{1,8})\s*:\s*(?<to>[0-9a-z]{1,8}) A: To reuse regex named capture group use this syntax: \k<name> or \k'name' So the answer is: (?<from>[0-9a-fA-F]{1,8})\s*:\s*\k<from> More info: http://www.regular-expressions.info/named.html
{ "redpajama_set_name": "RedPajamaStackExchange" }
3,207
Q: Why would you use TransactionScope for Read-Only Database Calls in NET C#? I've inherited a legacy system that's got a significant Memory leak caused by millions of allocated InternalTransaction objects on the heap. I've traced this to a database access class. In this class there are methods which read from the database which use TransactionScope. For example: public IEnumerable<IEvent> GetFullEventHistory() { using (new TransactionScope(TransactionScopeOption.RequiresNew, new TransactionOptions { Timeout = TimeSpan.Zero, IsolationLevel = IsolationLevel.ReadCommitted })) { var events = _store.GetFullEventHistory(); IList<IEvent> deserialisedEvents = GetEvents(events); return deserialisedEvents; } } My gut feel is to remove the using() block containing the TransactionScope. This is a Read-Only database call so the transaction doesn't do anything. Is this a correct assumption? Or is there something I am missing here? By the way... The Write DB calls have no TransactionScope specified. A: Firstly, in most relational databases, both read and write operations on database objects will always be executed inside a transaction. Even if you don't explicitly start a transaction, one will be started implicitly. This should at minimum answer the question of whether it makes sense to use transactions for read statements – in most cases you will end up with a transaction anyway. An example of a case where transactions are not implicitly created is a query like SELECT 2 * 3, that involves no database objects. When we talk about transactions, we must also talk about isolation levels. Transactions do matter for read statements, the same way they do for all other kinds of database operations. The isolation level controls in which consistency state data is read, and if read locks are placed. In your example, the isolation level of the transaction is set to READ COMMITTED, which could have been done on purpose. Imagine your database has its default transaction level set to READ UNCOMMITTED - using the wrong isolation level here could have undesired side effects, depending on what you are trying to achieve with that query. I would not remove the transaction scope, just because it's a read operation. You should first figure out how your database is configured and how the data is written to the table you are reading from. Regarding the memory leak: Your scope is apparently properly disposed, so I don't really see why the scope declaration itself would cause memory leaks. It could also be a bug in the version of the database driver you are using. More likely is, that the method is called very often, thus creating lots of transaction related objects. It's impossible for me to say what the correct approach is, as I don't know enough about your application and how the method is called. Nevertheless, here are a few things you could consider: 1) Use Required instead of RequiresNew. One of the methods in the call hierarchy, may already have a transaction scope declared. If you create a nested transaction scope using RequiresNew, like it is in your case, it will not reuse that existing transaction, but instead it will create a new one. Changing the scope option to Required will make it reuse the transaction from the parent scope, or create a new one, if there is no parent scope. 2) You could try to move the scope declaration a few levels up in the call hierarchy. The TransactionScope is ambient, so the transaction scope is "inherited" in subsequent method calls. That way you can potentially reduce the number of objects created. A: EDIT: This answer is wrong, but I'm leaving it here because I learnt something from it. @stuartd in comments: Err... you don't have to assign a using declaration to a variable. dotnetfiddle.net/U0PLBw ORIGINAL WRONG ANSWER: The using should ensure that the new TransactionScope object gets disposed, which should ensure that it doesn't get leaked. However, looking closer, the new TransactionScope doesn't get assigned to any local variable, and so probable isn't available for the Dispose to be called at the end of the using block. I would suggest you are right to remove the using entirely (as the TransactionScope doesn't get used anyway - it can't be); also I'd report this to Microsoft with a suggestion that such a construct should generate a compiler warning if it doesn't already.
{ "redpajama_set_name": "RedPajamaStackExchange" }
3,172
{"url":"https:\/\/www.mobilespedia.com\/upfile\/2D\/DTCM430-48-AL.pdf","text":"%PDF-1.7 2 0 obj [\/ICCBased 3 0 R] endobj 3 0 obj << \/Filter \/FlateDecode \/Length 2596 \/N 3 >> stream xwTS\u0016\u03fd7P\u0010khR\u0002H H.*1 \u0010J\"6DTpDQ\b2(C\"\u0001Q\u0004\u0019Dqp\u0014\u001bId\u0019\u07fcy\u035b\u001f~kg}\u05ba\u0005LX X\u0014\u0148g`\u0007\u0001 \u0003lpB\u0016F\u0002\u0002|\u060cl\u0013\u0017\u000e *?Y\"1P\\\u0019\u00178=W%O\u02584M0J\"Y2Vs,[|e\u000f92<\u0019se'9\u0012`\u0019\u0017\b2&ctI@o\u0019|N6(.sSdl-c(2-yH_\/X\u0013\u000fZ.\u0012\\$\u0019&\\S\u0013M0\u000e7#1\u0619\u0019Y\u001crfY\u0014ym\u0019\";8980m-m(]v^\u0019D\u001fW~ emi\u0015]\u0001P`\/u\u000e}q\u001e|^R,g+\\K\u0001k)\/\u000eC_|Rax8t1C^7nfzDp \u67c7\u001f\u0007u\u001e\u0016\u0011\\$\/ED\u02e6L L[\u0013\u0005B@\u000f\u0679\u0011\u0416X\u0002!\u001a@~\u001e(*\u0011 {d+} G\u0003\u034b\u0459\u03c2}WL\u0016\\$cGD2\u0012QZ\u00024 E@\u0003@\u001b\u0003\u0013\u0004\u0011\u000f\u0003\u0002A(\u0004q`1\u0014\u0001D \u0017\u0014\u0018`'\u0006u\u001146p\u0018tc48\u0007.`\u0004\u0001R0\u000e) @\u0010\u0010\u0015Rt C\u001cX\u001b\u0003\u0005C\u0011P\u001c\b%CBH\u0002\u0015@R\u001cf[(t\u001a CQh\u0012\u0015z\u0007#0 Z\u0011l\u0005`O8\b\u001728\u001f.p\u0003|\u0010O\u00d7\u0011X ?\u0011\u0010\u0011:0\u0011\u0016FBx\\$ \u0011!\u0012\u0002i@\u0690\u001e\u001fH[\u0014\u0006EE1PL \u001f\u0015\u2896V6Q\u0007P>U(j \u0011MFkt,:\u0019.FW\u001d\u00118\u0015\u0006c1\u0018L\u001c&\u0015\u0002\u0019\u001b\u04ce9\u0019\u018caX:\u001c rbl1 {\u0010{\u0012{\u0005;}#tp8_\\8\"Ey.,X\u0012%%G\u0012\u04491-9\u0006\u0480Kl.\u0013\u0007o\u0007o\/O\\$&'=JvM\u079e\u001ax\u01e5{\u001f=Vs\\x \u0089\u0013N\u67dc>ucKz\uf709=s\/ol|\u03dd?y \u0017^d]ps~\u0007\u001f:\u0006\u001d\u0006;\u001c\/;]\u00197|W\u0016pQoH!\u027bVsnYs\u0017}\u04bd\u001b~4] =>=:`;c\u0731'?e~!a\u0144D#G&}'\/?^xI\u0593?+\\wx20\u0015;5\\\u04ef_etW\u0019f^Qs-mw\u00133+?~\u0018\ue9ccO~\u0003 endstream endobj 4 0 obj << \/CA 1 \/Type \/ExtGState \/ca 1 >> endobj 5 0 obj << \/BitsPerComponent 8 \/ColorSpace 2 0 R \/Filter \/DCTDecode \/Height 424 \/Interpolate false \/Length 24371 \/Subtype \/Image \/Type \/XObject \/Width 2048 >> stream \u0010JFIF\u0001\u0001\u0001\u0001C\u0003\u0002\u0002\u0003\u0002\u0002\u0003\u0003\u0003\u0003\u0004\u0003\u0003\u0004\u0005\b\u0005\u0005\u0004\u0004\u0005 \u0007\u0007\u0006\b \u000e\u0012\u0010 \u000e\u0011\u000e \u0010\u0016\u0010\u0011\u0013\u0014\u0015\u0015\u0015 \u000f\u0017\u0018\u0016\u0014\u0018\u0012\u0014\u0015\u0014C\u0001\u0003\u0004\u0004\u0005\u0004\u0005 \u0005\u0005 \u0014 \u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0011\b\u0001\b\u0003\u0001\u0011\u0002\u0011\u0001\u0003\u0011\u0001\u001f\u0001\u0005\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b \u0010\u0002\u0001\u0003\u0003\u0002\u0004\u0003\u0005\u0005\u0004\u0004\u0001}\u0001\u0002\u0003\u0004\u0011\u0005\u0012!1A\u0006\u0013Qa\u0007\"q\u00142\b#B\u0015R\\$3br \u0016\u0017\u0018\u0019\u001a%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\u001f\u0001\u0003\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b \u0011\u0002\u0001\u0002\u0004\u0004\u0003\u0004\u0007\u0005\u0004\u0004\u0001\u0002w\u0001\u0002\u0003\u0011\u0004\u0005!1\u0006\u0012AQ\u0007aq\u0013\"2\b\u0014B #3R\u0015br \u0016\\$4%\u0017\u0018\u0019\u001a&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz \u0003\u0001\u0002\u0011\u0003\u0011?S\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0003 endstream endobj 6 0 obj << \/BitsPerComponent 8 \/ColorSpace 2 0 R \/Filter \/DCTDecode \/Height 512 \/Interpolate false \/Length 29299 \/Subtype \/Image \/Type \/XObject \/Width 2048 >> stream \u0010JFIF\u0001\u0001\u0001\u0001C\u0003\u0002\u0002\u0003\u0002\u0002\u0003\u0003\u0003\u0003\u0004\u0003\u0003\u0004\u0005\b\u0005\u0005\u0004\u0004\u0005 \u0007\u0007\u0006\b \u000e\u0012\u0010 \u000e\u0011\u000e \u0010\u0016\u0010\u0011\u0013\u0014\u0015\u0015\u0015 \u000f\u0017\u0018\u0016\u0014\u0018\u0012\u0014\u0015\u0014C\u0001\u0003\u0004\u0004\u0005\u0004\u0005 \u0005\u0005 \u0014 \u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0011\b\u0002\b\u0003\u0001\u0011\u0002\u0011\u0001\u0003\u0011\u0001\u001f\u0001\u0005\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b \u0010\u0002\u0001\u0003\u0003\u0002\u0004\u0003\u0005\u0005\u0004\u0004\u0001}\u0001\u0002\u0003\u0004\u0011\u0005\u0012!1A\u0006\u0013Qa\u0007\"q\u00142\b#B\u0015R\\$3br \u0016\u0017\u0018\u0019\u001a%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\u001f\u0001\u0003\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b \u0011\u0002\u0001\u0002\u0004\u0004\u0003\u0004\u0007\u0005\u0004\u0004\u0001\u0002w\u0001\u0002\u0003\u0011\u0004\u0005!1\u0006\u0012AQ\u0007aq\u0013\"2\b\u0014B #3R\u0015br \u0016\\$4%\u0017\u0018\u0019\u001a&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz \u0003\u0001\u0002\u0011\u0003\u0011?S\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0003 endstream endobj 7 0 obj << \/BitsPerComponent 8 \/ColorSpace 2 0 R \/Filter \/DCTDecode \/Height 512 \/Interpolate false \/Length 53742 \/Subtype \/Image \/Type \/XObject \/Width 2048 >> stream \u0010JFIF\u0001\u0001\u0001\u0001C\u0003\u0002\u0002\u0003\u0002\u0002\u0003\u0003\u0003\u0003\u0004\u0003\u0003\u0004\u0005\b\u0005\u0005\u0004\u0004\u0005 \u0007\u0007\u0006\b \u000e\u0012\u0010 \u000e\u0011\u000e \u0010\u0016\u0010\u0011\u0013\u0014\u0015\u0015\u0015 \u000f\u0017\u0018\u0016\u0014\u0018\u0012\u0014\u0015\u0014C\u0001\u0003\u0004\u0004\u0005\u0004\u0005 \u0005\u0005 \u0014 \u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0014\u0011\b\u0002\b\u0003\u0001\u0011\u0002\u0011\u0001\u0003\u0011\u0001\u001f\u0001\u0005\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b \u0010\u0002\u0001\u0003\u0003\u0002\u0004\u0003\u0005\u0005\u0004\u0004\u0001}\u0001\u0002\u0003\u0004\u0011\u0005\u0012!1A\u0006\u0013Qa\u0007\"q\u00142\b#B\u0015R\\$3br \u0016\u0017\u0018\u0019\u001a%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz\u001f\u0001\u0003\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b \u0011\u0002\u0001\u0002\u0004\u0004\u0003\u0004\u0007\u0005\u0004\u0004\u0001\u0002w\u0001\u0002\u0003\u0011\u0004\u0005!1\u0006\u0012AQ\u0007aq\u0013\"2\b\u0014B #3R\u0015br \u0016\\$4%\u0017\u0018\u0019\u001a&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz \u0003\u0001\u0002\u0011\u0003\u0011?S\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002X\u001aU\ue9e9m\/suyw* \u0011\"y\u001d\u0600 ,H\u0002M| C5gm'\u0010|^\u0018S4\u000e \u00191yY\u060e4\u0571V\u0003??V\/>>x\u001da|\/|H]OP\"!Iw\u0004lQyE?i4G\u000e?Ch xR \u001f\u0010Myt:K5 vf\u000f\u00048 \u0005vUp\u0016p|a \u06d7{}O\u0003#YfZ~\u001c\u0424\u001fxO58DvR,t\u000e\u0016Xw\u0018\u06fdWp\\G4\u0001\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005x\u000fWj|>4R|ewf:G,\u001bF+,\u0011'G.\u0151~CO]ig{ k.\u0007Y2*#FU\u0001(o\u0019\\$#W)@\u001eQ\u00156R\u0018\u0015'%cP>P\u0003^*\b\\$=\u0002@\u001a^\u0004\u01ca\u0011x\u001f\u0012\u001bZu\u0636\u0494\u0012dO,e F\u1476(\u0003w\\Xj\u001fo|\u0012\u017a5\u0230w\u0002\u0016u>\bQT\u001f^\u0016f [\u07b3E}GKKyF\"\u0012VSR:\u05a0\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u000f\u001f\u06ff 1}?\u0010O\u01a3n. {\u001eLw0i\u0005[X\\$\u0004n\u0005c\u0019L\u00197\u0018@?2}NT{^{JfGb;rI'<F@\u0011P\u0004m\u001dB\u0004\/\u0015V \u00059\u0506PA\u000fA\u001bI|Paw\u0017\u0016:sx~e-\u0019}7 \u03b0\u0019c(_]A\u000f?\u064f 4 kV?\u000eq2ZZ}lH.UK\u00101*YT<\u000f\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002?:?\u081fPK\u000fj\b>\u0010j|NGGta{[g\u001dnps\u02a9w4\u001f\u001afo\u0665lEc\u0713\u0005\u00b4\u00b4J#d\b:\b^\u001a%=\u0002\u079c\bU0\u0014\u0001\u0005\b2Zw?\u0010\u0005o\u0003B\u001an\u0004h}\u88fc+\u0018\u0006-@\u001d@?ZfGY\u0005^ n-(M\u71f5x>o\u0017\u0449 \")&'pda\u0005\u000fu\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0003)gsBU_?Wi.\/i\uc116C\u000f\"MgX8\u0003\u000f\u02ed\/H\u046c6\u01bc~\u001e,\u0006\u0015\u0006\u0006\u0015\u0006\u0006\u0015\b(\u00026J\b:\b\\$*n\u000fj\u0002z]iske){yQ# \u0004\u0010r\b\u0004s@\u001fxW\/\u0014|4 ].|oG]1UY\b7 #\u0004b|\u07fa& err\u0001\u2bc4>2xV\u000f\u0012x'zY\u0007IJz)B\u0205p\u0006:(\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 \u001fO\u04ffe\u001fzfZ'4+\u001f7\u00053@X\u00128XJ?\u0015 W\\5O\u0017T|aIGQ 1\b\/\u0288* \u0002P\u0015T\u0006\u0006\u0006\u0006\u0015\u0006\u0006\u0015\u0006\u0006\u0015\u0006\u0015\b(\u00026J MOv\u001akC4 1^{v\u0006ZZ mnp1\u0212N\u01ffP}@\bW(jNXE?\\$ \u02e0\u001f\\b7>\u001fx\u01bf\u0005U\u0007 \u000fq`\u001b\u0019LFT\u000eyR\/+,eB 6\u0478\u0011@\u001f\u0015\u001bB^\u0006a\u0007!j\u0013I \u056a5\u0006\u073eL1\u0014\u0018F,\u044dD}@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014\u0001SV\u056ct *Sm6\u0017b\bK<@UU\u0004\\$\u0001&?\u0003:oj:\u012dQ|*=o + i\\$1*6e>c\u0012\u0004 \u0001\u0011@ \u0002\u0015\u0006\u0006\u0015\u0006\u0006\u0006\u0015\u0006\u0006\u0015\u0006\u0015 ngE\u0016@\u000494\u0001}UT X\u000e\u001d\u000f'@\u001ag,\u0011,\u04cc\u00134w\u0019Z@\u0015J\"P\u00059@\u0019W(\\h\u0005%[.|oox\u0017\\$\u014eo:[I\u0001@2\"pX\u000e\u0018\u00036(m%\u0014j\u0011\u0006s\u0006 P\u0003P\u0003P\u0003(\u0001s@\u0005%!ZX4M:k\u001bG\u0204c\u001f_j\u0019)ar\u0007 {\u0010\u001c-s\u0004X!CfF\u0011@WY\u0758}@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014\u0001cw|W\u001f\u001blo\u0017-\u0018\u000fRIZY|\u001ceoqf3\u0016U[9P\u0002\u001b\\$ m#h 31u\\$\u0007\u0013T_]\u0013Mp_9\u0005\u051e\/h\u001e@=YG\u0004)\u0014QQ\"TAP8\u000e\u0080*m\u0580(M\u0007R\u001a\\$x G\\$x\b\u001d(\u0002@\u0015e)\u001eh\u0003:\u001cv?\u01fds\\\u02e2|BopEZH6 ?GRdH\u072bl'\/>\u0015\u047cI]}E,,n|\u0382T\u0012F\\\u0006\\\u0003\u0001 j(\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 7\u001fxL}K@v\u043c[I*+e%K \u0004\u0002\u000e3:\u0007qks\uda19\udc77g\u0003 P\u0006jxjxjxjxjpjpjp9\u0005\u000eK\u0017\u001a\ud7c743{{ Iv\u0013!\u0004\u38a9\u000fZ|-[i\u0220F\" `ns`t\u00024^,\u0005y`R93*O\u0014\u0001Fh(\u0002b+I\u001eh\u0002+f+\u0214\u0001Nh\u0002g4\u0001}l\u0019H#\"?S?\u001f\u7135\u000f\u001e!\u052dm.y\/3\u0014\u00170\u0010\u0006h1\uccfeH \u001f\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014\u0001W\u00157\u0017-\u0003Vu-~kM\u001a\u0019\u0015\u0019I'\u000f^\u001b\u06c8V]s)lvVQ{c8 A\u0001\u0001\u0001\u0001\u0001\u0001\u0001\u0002G\u0017 \u0012\/@:\u001cd3@ =\u07f5PEF[byd1^N2r# '\\5zjp9\u0006\u0003@\u0010I\u000e{P\u0005I:P\u0006m\u0161\u001d\u0005gM\u0007^(\u0002b*\u001eh\u0002+H\u0001ZDR>\u0001s\u000eA \u0005s_\u000eS}[ocsO \u0019X\"GPr;.ph\u00039U3C\u00de6hu(m:3\u0178|IDC\u001d\u0220\u000e (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u000f_-_-<+ i4_Y.\u001eD&Q%E\u0014j;v\u0015p*I*#\u0004\u0010\u000f%zxz5<5<5<5<585<5q\/W&~L31\u0001HN:\u0007!wqG{\u0016XZAk\u0002pB\u001civ\u0018\u0003'\u0001~9@\u0013@\u000f @\u0007\u0006#x g\\\u7820 \ud293P\u001cv \u015a\\$x %U<<]h\u0003\"peh\u06c3yp\u001c1;d{@\u001b)pGz\u0015:\u0005n@\u0017\" QP\u0005\u001e\u0001(9\u0002\u0018@\u0014-wv .P\u0006M\u0171^\u00011kXGu&Ku\u0004r=s@\u0019\u0016\u001e\u000ed'{\u44d4^I}G=\u0006\u0007^7\u0331(TQ0\u0014\u0001\u0004\u0003\u0680)Of\u001bj4\u001f4\u017f\u000fAq\u0010\\$2[\u001bxD',R+\\$\u001b\u000e\u0006Ta*\u00010Z|!m4\u001fP\/\u0015;D\/r\u001aDXr;\b\u032b\"}:e\u95f6{ \\ZJ\u0019\u05b5t6\u001dnn%\u0004FG\u0003\u0007\u001fZ'a{Jvm+\u001eH^i[KrOn\u0014c'kmZ '^\\$Y\/\u001f5e\u00109\u0001\u0004@s*\u0012|+VgA]FX\u03fdf)O:\u079d]z\u05ce[{]+SOiy+\u0012T)b\u0012D\u001ay\u0018N5\u00174]x-l\u001dOe^<>\u012d\u000eP\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002?\u001b?\u0b1f\u0014 >+\u000e\u000f\bxx\\$Covb\"USh2\u02d3(]\u0018\u0003\u1e2e\u0001@\u0016,\\$\u0001:K@\u0013,\u0001*@\u0012\u0007+gP\u0007b\\$\u0007 (\u0001\u0001JzEL\u0004P\u0004q@\u0013\u0001f+\u0002\u0017\u0001\u0006@\u001ei\u0017Uw|5\u001eR\u062c r[w8\u0001X\u0001\u0003-g\\$v\u02cf\u0015\u07dc7}Z<- ZjQ\\~\u001b\u0007iTHmKOu+V\u001e.L \u0016&\"uK\u0004H|\u2d39Qq\u0016ch\b],9_S\u0014w98y\\$?U\u0010@\u0005|_l~ ?%G\u001b]6\u0016SU2VU9z?E7(\u001a#P\u0007\u0005);m_\u0010lg \u0013\u0001pmo\u07c1R {y?XOw\u001eE^\u001a)7d\u001bSGN6\u0160i\u0003\\$\u000f?y+R\u0001\u0007\\$\u000f1Q|\u0019[N\u0660\u000f>W\u001f7q\u001azl\u0005,#n7K)lrA\u0013P\u0007[\\ZmK\u0013\u0011-\u0212\u001b#8h%n; n\\\u001e@\u0007G\u0005MOQ(4Yg r46\u001aGw*v7fUXI~x\u0003\u001d'\u015e\u0013\u056d\u000fj;bv\u0239 \b\u0005YX20 \u0001\u0004\u000e (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 >*32|8\u001f|I\u00074]rK+n\u001f,VQ,mDbk2(\u0003\u0017Zmso%\u0663\u000f8\/i\u01baai|Mh--NM];-\/\u0017(c\u0014((PU\u0003\u001d\u0005~j\u0724 5:\u0014JTc\u0014IY\\$I%Il\u001a;u-\u0005B\u000fb\b\u000eNiO-\u00fe^kJ\u0368o'o]\u2bafst\u001d zEd\u0018[@]\\$I\\$ \u0013*T\u075f>Mr\u001c\u0005,\u0006m\u0776\u06f5\\$s\\=g\u0013\u0014KM1Z\u0006\u0005\u0013#(;=1{9v\u0006X\u069e\u0016=~o|UKpm\u044aiT&J){8\u0276\u05ce_=\u0013{RYeK3\u001d=\u00061?\u04a5 0T\\$\u0007\u061c\u0013Y2L\u0006\u0007N\u0003G\u02a0\u0003\u02e0\u0004@\u0019:\u0006\u0013*\u0003}?\u0580)h\u0018rij\u0013 ?9r\u0001m\u001dB8cH^\u001f@(d\u00062P\u0005[\u06d8,a2JF;p=O\u001d(\u0003qvP\u0313\u0001\u05e0\u001f' \u05753l\u0001\\$3\u0017\u0710;v K_\u000489g3?@\u0013\u0017ZO}\u000f\b\ud8b6\ude0c(\u0018\u001eO(\u0003e_zzUl\u0011%<\u0014\u058414Q\u0002\u0279\u342a\u0003b>\u0018\u04dankjh>8\u0015k\bjr\ucece]\u0017X\u0019\u0001 Bm.}\u0011@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005s?\u0007~)7V4}s\u06ac&\u001d.A\u0004\u0010AVV C+*@ \u0003AEk\u0002&\u04df{xOXTam'p*9gp!\u03d9+>\u0014\u0003_\u0005:'}C\u056e\u03f4i0@7\u0001*#A\u001c\u001a+{\u0005 \u000fH,u;\\\u0010\u001b8'\u0004sP\u0007G\u00022\u0014I@\u000e\u0012Zp\u001e'\u0014(\u0007}\u0001jKvk,\u0006kE;s\\$r=\u0005u\u0001t\u001bh@ 2|AEA.|} >\u0012\u01a7\u001a\ua164f\u0012G 0\u0019\u0003>\u0003+@ +@ +@\u001cUo\u0016\u0007xW!\u0007OM\u001f \u0007\u0016\/b3)\u0007''\u0011\u000f\u001cztz\u0005[X.s~a\/\u001cwn\u0005o4t\u0001R\u001b\u0018L\u02b1F;\u0003\u04809k\u0018oEa\u0007K`4\u0770\u0014s\u0014\u0001 x\u0014I!13\u0010\u07e1\u0004R\u0216k\\$-h\u0002kK-_B\u052c=\/XK[%xe\bd7Su`\b#\u0004\u0011h\u0003\/ 3Rh\u0013l\u012f G\"-\u001eRg[6\\$\u0002I\u001d\u04c0(\u0003C7\u0015\/K\"6oC\u001cc\u0202Mg.\u0004wP&&\u001c\u0013}p\u0003\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u000f ?d\u07c5\u0196x0]i ^G\u052dY\u0002ys%Qw\u0011I\"\u0016F~A\u053fM\uf27f-.~\"x-wum\u001aEDH LC\u0012]\b2\u0003k{\b9\u0006)KMb ln'v?tBozp\u0780\u0014K@\u000e\u0013{\u0002h\u0001ZQ-8K==n=\u0003w\u001f\u0011i%\u0014\u001fp?P\u0007Y\u001c@\u0016\u0012j\u0004%LP\u0006-xFK=1 P8\u0004 \u001f}O6\u05f5\u04a08\u04e4d\\$\u0016\u0018p>S\u001cx _dX\u0015M}\u02e7\u07fbiU\u00159UA &~i{5&e\u0017\udbdf\uddb6\u0017\u0005d v\u0141~}9i\u0001@\u0006(\u00016\u0006v\u0163Y4`DHyOA@\u0018 xMWS\u000f,A3w#c\u0018\u060aR(\u0001h\u0001h\u0003_ek; \\.D\u0019\u001e?!\u04dep\u0001x\u0097~!L;VV9y=v\"=\u001aO\u0010B; xO\u3a60\u0007\u000eG[hL\u001fiJ![8\u001bF>ct@\u0014|\u001duo5I6(?\u001fx^s\u001cP\u0007Oi[i\u0454bS\u050eO'z{G@\u0019i.g+\u0011\u0018^\u07c7^\u0001:?_}MM-\u001aMP\\O7fnl\u000ed\u0746w_\u0001`\u0011\u0003oUCsg\u07ce6r,,zL\u0012\u0015fHhX\ue456Rd \u0019D(~x[\u015a\u001ft+]oz\u039f \u0016w\u001d..m\u001bdJ\u0019YN\u000f\u0005H(\u0003Z (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 h|6o_?\u000eh\u033ae\u001b[_;\\$yn:Sq\"92e@\u0003\u0007>'Yx\u0013i1_v\u06e4\u0011F\u0015bw\u0011IP.h\u0003\u0408_c;P\u0005?\u0780\u001c'\u0005\u0017\u001eh>s@ .M8]c8]P\u0003\u05fdfx2D>A\u0003=0(\u0003fP[D?+ \u0006W\u0019@\u0016c4\u0001a& Zkuye%,\u000e2\u0018 9\u001c \u0011? f(\/W\/{-!dT\u3afa; =^n1f5.`_x^6\u07cfh# `vz\u0019n\u000f\ub618 \/sx\u04c8\u057c2kIYS\u000fi\u06a4PK\u05ff\u0003Z\\?P\u00074P\u0001@\u0005Gss\u0015\u000f4#\u0006Yj4\u001e\u01da\u0117Rod\u0007ps\u000e\u0019p\b\u0007) k\u001a\"( \u0001\u0001@\u0001ZaZY\u0003x_=\u013f> ?\u0004>\u0017\u6ecfPt9cR\u0004,s\"FHi \u0004\"\u0016_\u0693g\u001d\u0007\\s?\u04fd\\ye\u0019+n@T\u0004@\u0006\u0011x vz O\u0011^o\\pFaJ:Kgq\u0778 \u00106dz\u000eC\u0012w\u001af\u0002\u0012U@y;UFO\u000e(\u0003\u0013\/\u01c8~qWX_\u0016\u001bC~LJ\u06c0c3g@\u001eo|4\u0004\u001e\u3fc6&m\u0018jLIuf\\$ o#I QQ\u02d4Gu`\u000f\u048f\u0013\u0017}]\u0161-\u01836\u0018|92\u0019Ju8\u0001#\u0018X\u001d?17}\u0015@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005dz\u001ft+\u0013\u011a6 \u0016o4R.m|n \u0019UG\u0005A(\u0003_7h\u03f78\u0006q@\u001d\u0007\u0098mF^gI\u000eIU\u001f~}9O\u0017\\$Y\/?|7,7\u000fQ5g79K8\u074aZv;hz\u001cOT\/u\u001b\u001d.7[Pd\u0017ne@\u0019\u00042 ?%9k}\u0016\u0017g#\u0018>WNZS\\\u65898qo[OK'O\u00046R]V\u06acp~QsW\u001fP\u000eh\u0001\u0001h\u000e3:\u01a3\u001e`+\u0006\u00ea\u0011\u001b>s\uf799\u000fE4t=6\u001bH\u0015pp1\u001f\u04f5^\u0004+@\u001c\u03cd|O\b\u0750)3\u0004P\u0007\u0007 mU5rO\\$\u0002z\ud71ez6\u0016\"1E}h+XYHb^#\u0005Q\u06e9\u000f:P\u05a5\u0002\u001cp=;3I6I\u01f9' \u0005h\u0003{\u0013pa?\u0003\u069e\"S,!+k \u0003\u013bp 1* :+}x#\u0012A\u043cMH>2}\u0ddaGHM> \u001bdVUT\u0565>Z\u012d8@\u000f\u001a\u08be#RO,kl h=Djb7rX%^>O^GA\"6<\u0002U\/6\u0012)bI jG\u0003\u23a7\u0006d\u0005Bm\u0011]\bhdd'\u0005 ?l\u000f|\u001f\u001f\u0010c?\u00179 a44\u000fG\u0560\u011f w}ib&aN Gs \u0770 \u000fFWnagA\\$sF\u0015taA\u0004\u0011\u0006>M\u0012?t\u0003H\u0236\u00176 \\$\u0391i\u0015JRY 3 \u0007\u00ff= >\u001dd\u0016\u0019\u032d\u0784S5\u0473c%Wzu\u001b]I(\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u000e+\u0005|zl\u0015E<\u070byhC\u001cm\u02f9\u0018\u0012r|Y\"\u008dnV~-O5+is\\$7\u0016Jd c\u0011\u0014I]BnE->g \u0001?\u0774\u00cedv\u0001\u000e9wZ@\u00078O-im\u001f?\u0774\u0001+\bK<_\u0017:g-\u001d\u0189\u0015 \u0175p)\u0012\u001c\u000e\u0001\u0004 \u0004\u000e\u001cO\u03c8?2:?\u001f\u0004l+\/C\u0004?ED\u0007\u00066?@\u001eq\b\u00e6^\u000e~\u000fxY 2J4O\u0013=0(V8\"\u00106& 1@Z% \u0001\u0002\u03ce|9x_\\q. A* \u001e?6'Z7 \"\u0016Fv\u0014\u0001\u0005`0h\u0002[eX_A4\u0001|9\u001b\u0005?cWf*oGw\u0002p\u001f#\u07bcW\u0013Xo|uY \u0018N '?\u001c(rj\u0016Wk\u0017c'\u03f1\\$\/c\u046d\u0166Cc* \u02dc\u01d3^&4s@ P\u0006wu_*Yf#xzry 6@\u012c\\$\u0014\u0019l\u0011l\u0001\u0001@\u0014u^\u001d\u000fMv\\ ;\u0010olpu@\u001eAaiyh+<\\L\u1957\u0019\u063d\u0003\u0018\u001f@;P\u0007id:E61 \\$O\u0512h\u0002\u0014\u0001^%'\u0016`\u0013IHV,1#r\u0019:^]\u001e=\u0013N\u001b#,\u0001v=I= h\u0003_\u00cf\u0016q\u0003\u001ax|Iz\u001f\u03a6mcolv\u05e6GZ\u000fM.9\u0017 Fl\u0001' cGP\u0007I@\u001c\u0007PH4}:B1q O\u00020G= \bV\/\u000f\u062bnA\u0019^\u0006;\u000f\u050c`\u0003xEix~&Gxg 6\u001dB\u0016f=jKXTYOqj6 r\"HPL\u0001?\u05e9|8TVE[u -r~{\u02e9\\$7n%Dy\u0003\u0280\u001c>1%o\u0001xFAww<(gX|4\\`?!,cwTe\u0011\u0006\u027c\u0015\b_\u06df\u0013!]^3D&bj6e2L\u0176n\u000160\u0007\u8dc2|{\u07ce^ Q\/O6\\$n6 \u0220 \u02b08*\u000f?cF7\u017f?.flt\u0019N\u073cS\u0015Q1Hh jF\u0017k\u0006j^\u0018\u001f|\\Xw\u001b}Iaa_-JWqjF\u0007\u0012?\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u001e\u0017K~ j{Y|gp:Dg\u0012\u0018\u0010\"0 *8_6BYP\u0007_;\u0003|Ea\u000f')`%*\u0012{8pT>Z3E}\u0015GC\u001fGO\/;v[\u000f\u0013\u0016P\\\u0010G\\AN\u000f4DYz\u06ef^4 9C[?\u0751VqrV\u05a7so&@-P\u0004\u0005-wR:f<@\u001bS\\$\u000f\u01ee:\u0680+5Yu)\u00076c\u0001Gq>\u0001\u06c6\u0007\u000eo\u01fe }\u001bH\u0011#Gurv#)U\u001fxp;\u001f#q\u000f4OMl\\8\u0016x\u000e \u000fZ \u0014kDAU\\$\\$H1\u01e0\u0004@\u001c}\u000eGiua\u001f\u1ee5U\u0003\u0011jhD\u0005[&5hp\u00143\u0012S,@\u0007\u01ef\u068bIy}S t]KEF%#,Q\u0015\u001b\u03d9F+\\3FV\u0400|]}\u0017\u00faOgj\u0016z1\u0004\u0001G1|?i[\u0007I 3c)\u0014\u00041\u001c\u03326enMC@\u001e)\u0016<\u0004\u001f@\u0012dM3\u0014\u0001\u0001j\u001b?\u001aG>\u001f^6(7&\u02a9\u0017R2\u0005\u000e\u0003|E =@VAoW\u4dad _v=A\u0019]Gb\u001d\u0017q\u001c8daA|?O\u000e\\\u0368\u074d7d|\u0016++CH3\u07a2s\u001b<\u0003i*X\u0003\"w~ {X\u00129!xmvY\u0003mm (@\u0004@\u001fjk\u001f\u0006L\u047f\u001aZ(\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 i6:{jvV{ ]Y\u0132\u050eOq\u0001@\u001dM\/\"`@n)0rI\u001f8f:\u0001r i Gm\u0019#\u0011\u0006\u0007#zf=>8\u00188R4\u0001UT`:(D6FT\u0001ff8\u000e \u0003>\u0018]\u0010][{Q\\Z31M\u001d\u046442-# !\u001b6P\u000f\u001fo\u0011Di\u001f\u0011I5AY\u02f73\u0006(b\u0004\u00a29gx1I8zw\/.5W#\u052dl|-\u001447Q,v1 4*\u0013(G\\$\u01020\u000eki*|;_ <6P4\u001dN \u00171\u0004;\u0011K BK*\u0001{\u001dmgckvq-\u0778<4kRwv\u0006X\\Y-|P\u000fph \u0003Dg6[o\u01376\/@yg\\%\ua659ri1,b \u000fhm2IO\u0016G'P\u0007CxS^,F#[\u000fx\u0007 \u0010\u001bAqT\u00baFnc@d:Y \u000e \u0019{e \\$VE9\u001c\u0011L\u050cm~\u0015g\u0477\u0005=\u000fah \u066bCk&]GZbU\u152b\u0014\u0019fw\u00042\u0777w\u0004<\u07f8^ \u0013[imC{ sMk\u00075RX^4FV;\\$a\u0004tEeI\u0010\u0001'|\/k\u000f'6rM,3x\u0006Pfa%\u03642\u0001>P0^\u0001NI K\u0012\u001f\u000fsn|>^>_\/f\u07d7\u0014\u0001\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0007?gkJk\u001dxbRHL65+@\u0016@'^YQw\u0011I\"\u0016F~*~_\u05c8b\u001a>j\\$\u07c8!wb\u00163\u0010M\u001covOeeHlD_\",P\u0007\/\"2kGQ\bGv@\u001e\u001a\u001e\u001a2<]6I\u001bLE\u00199=pGB\u0006H>8_\u0005}uKuNQ\u00168!]\u0001w `(\u0003K]s5o>)FL.?y\u06e68nh\u0003=mu\u001db2H:\u0002\u000f\u0001#99\u0014\u0001|=\u047fQp\u0013C:'\u0005\u0001\u0006\u000e7\u001dK\u03e38\u04a4X\u0018 Cw,2ii,k3FJe1Q\u0017k|\u03a5M\u0320\u001e\u0005 ?\u016f~ ~\u0016%oMH#\u0006WP\u0016VC |s\u0007\u0605@=k\u01da?G?AeIcf{\u0093i7;4*JR\u001f\u0001\u000fO6~#\u0002;?5'Cx\u0010<\u0002 \\$N\u001a>#_\u0013|O\\$~\\$\u0534\/nof]^9Va\u0019h^>GYm\u0132A\u5f25\u0017v\u001b \u001f>(|7]\u0004\u0015g\u0017XN\u000e\u0010\u0552 V)o\u0005c9`R~k\u0164xt+\u0004\u0014J\u0007^qz{> 1\u03a3t+lp\\$\u0010G%02F9\u0003\u00198#\u0014o_Y'1M\u0014\u022b\\$n 0`z=*\u0018\u001ek[+\u000fj%\u001eAO@Iy\u0004\u001dEsIY#.\/u\u001bo# \\$c\u000fH\u02a1v\u001b\u0019\u0004te\u001c?P\u0007|s!\u0005Y OJym\u0014 _d\u0016,Joh\\$y2xsj}}O\u001bH[p,\u0011Li\u001ch &vUQ\u0516rE}'\u026c|\u001b3F\u0018h\u0003h\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 \/ o\u0002g U\u0004\u0016#L2Nj\u0018]_g\u0010T4@YZD>k\u0014\u0019a={\u0001v0Z8=2\u0006h\u0003;\u0579Td\u0018%cW8\u0019,={\u0014\u0001\u0006\u0007\u0006\u000e\u000f6Y+eb_1~7\u001eP\u0006T\u0001{Y\u001bo4E}+L O~:P\u0007j*|eC NjGq\u01bfx3\u0004xP\u0007D k\u001cj\u0011\u0014\u0005UQ\u0006%. Hci\u0018\/R}X>(|T\u0004z 6i&wlZ*\u02a2\u0015\u0012HZ\u0014c@c y\u00128\/\u001934^\u0007\u057cOCoeh.\\$\u04edw\u0010\u0016Ak\u0015xd\u6e0e+iP\u0003zU|;o :\u001c\uaebc\u0017Fk]:5g[qw?4\u0007*g\u0017m\"54u\"H}\u0018}\b\u0004>\u000e\u0018Tw-N\u001cs6vb909F5 ho\u0017j)D|3[L%+2\\5GYDd.\\$\u001f)\/k4\u06fb\u0019 }{Vc<\u0640K ?\u0480=\u001bXaXl^\u0014Dl\u0001\\$\u052a#\u0004\u0001uQ@\u001fs_\u000f?cG6\/\u001fHEq\u001by\u000ea\u000eW\u000e5u\u0005> _~\u049f\u001b'\\&0\/-\u0003iwL\u0015\u00196ahzQ_ x:\u0015\u04fc\u001d\u0ec4:mcr-\b6X\u0011,[7\u0018\u0017VUrh\u0003j\u047c\u0015ob3AKH6:Ug9\u0012\u0007l#GvU\u0013#c3c\u000f<.kekhZ[a\u06a0m.\u401bV@\u001d@X\u0007\u001e\u001d7u?AV\\lEmq Y.me#\u04ec&2)\\$\u0597eE\u0d3d2o2vu\u0019G%#\u001a[}9\\$deS\u0016[ eR@:?\u0006]BC}iO498\\\u048ey\u06cc eJ \u0309>^O\u05da\\$\u00beC\u0003C\u0003\u052eqj 4_ z]\ucdb5F\u0016Vl \u0013N9\\$I%ddSyC\u0003.x<\u05364r^j\u0018\u029f ;\u0018|b\u5b52\u0016W1[lQ\u0631 *dfHlF\u0011xoIT\\Mt@VVUP\u000es\\$g[[e\u00011k\u0019\u0018\u001d'4\u0001\u0013#~#x!\u001f X #ss\u0015GGrq\u0e90 @><;dx\u0182+\u001b\/\u001e\u042dC]\u02aa&\u00126tv;[i`\u001fP\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0007? V?\u0012\u0001_\bjrAe\u0395u-*\u0311O\u0013D\uc155`H\\$\u0011d\u001e\u0001G\u00ff\u0012\\j\u001b.4m]\u0017 \\$ * \u001cc t P\u001e;HD 4,\u0014a\u001c(8\u0007ke;k \u02bb%dVu0HP\u0005\u001f\u0015|?wq\u001c[n6\u0019\u001b\u01f8\u0004@\u001e\u396cZ.5bF\u06712h\u0003\u00f4xQ 7\u000f\\$\u000ewbs\u05cch\u0003CP\u0006o\/\u000eUm2iw7\u0019\u0007r \u0001M?g{u\u0523o\u0011771}ezA%A\b \u05f7kn:,\u0001nOi\u0685\ud7a1|\u0006?.T&\u001cexLx\u0004\ufdf4\u001ee\u0017 f5ou\u0006fF \u0131Eej#R\u0001F{o hIxr|G,C~\u001eo=qmII\u0005ab9c\u00a8\u0006?\u00ff uLdL[\\F\u0277 @m*\u04f6\u0005 <\u00d6\u0007u=h^\u001a \u0004q\"\u001d\u02f5<\u001dr1\u001e\u000f\u0003={tQ[\\$z3t\u0012a]u\u000ez5 sz^j\u0019G+^\u0005\u000ep 'T1\u0017|?[={\u0197\u0005 \u001b \u001cc\u001a\u0010\b XFNbq\u000er(>(O?\u0018\u0266pm`x<\u0016n[k\u02dengiwu)r2Ih\u0003@\u04edg_Z[B\u0684W:1e\\$-\u0352)@\u045cc7*>l?<\u001f\/i^KBZeg+0d\u03bdxR\u001b\u0016\u046ctynw\u06a5q+\u0005\u021d 0' 3\u0005\u0018jXo}cB:\u0005W]\u0015n\ue858q\"R +\u0012\u0001\u000etQ\u0003i]\u03d81 :A :t\u001dV\u043d1\u00187]y`s}ye\u001c\u01a5y\u05da\u000775\u6feahzlFT\bw\u0004Uw\u0012\u00102N:\u0015e#\uf3cb\u019b5|\u0004\u0010\u021a\u0004\u04b4{Se \\$(\u000eG\u0005\u0006~tIoKrWi\" . y(\u0003\u0007\u00036e\u04deO3P\u0011ZGn \u0018 0z\u0007G\u000f I\u000ef vZOM7@pB\u0010H\u0017xF\u00058h\u0003Ilt *L,6\u0014b\bBhUU\u0005\u0002-\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005x.|g\u000f\u001dh=aIWRK\u06c4PV=?`\u03cbU}\ubeb5|3eivn\u074d\u0006q V]\u0359\u0018w}y``_]\u694d\u001c\u07a1{PrDt\u0004T63\u000f\u0603\u0011#\u0016E\u07a3CO \u00177*NX\u0017\u0019E?\/\u0278 #=\u001f\u0007m\u0014GO[ I\u001b\u0004yn6\u00030HZ\u0004\u04ee%=c\u0002\\$~\u001e+{?\u0010 V\u0010U\u0016S\u0006@\u000e\u0019fu\u07cdv\\$\"\u0005\u001fP\u0256~zl7m{t>5\u0651{y\u05da3K\u0019jvZG\u0003wolg~?9\/Y-9,`\u06e5WR<\u0003\u001bq\u00079U\u06fb6Q\u001f\u001374\u02ef\u0001K\u001bj65KU\u017c\u0012\u001e@^q#I,\u0006`W%\"\u0003DA\u04e4N{\u000e%\u001c\u0012\u0018\u001f#@;\u065f\u0015\u0017:DD\u0150umR\u0014\u001c1U\u0005IYv\/ FY\u0003\uf3fa\u0014\u001e_\u001f\u064b\u055e\u02ff\u0011OkjeteY\"Y\"Dna\u0017\u0014%Vp\u0001_? i~\u0006\u0012Z.e\u000ecm4L\u0011 4aT \\$MkP\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0007~_\u0001;I|#| +kvK]\/mF\u0010\u0003)\u001b6p\u0019wtc\u0010\u000f\u001f\u0004lC T\\$R\u0018dc\\$I9\u0007\u001c^@\u0005 \u0003Y;?\u028eC}GW\u056ffd=e8}\u0003\u0010\u0017m\u001fG\u0017p::\u001bI{s5{k\bUN }\u000eZ\u000fj>!\u0016i*j\u001e)\\\"2\u0019\u0005a@V\u0018B\u0002\u00033vc \u0001\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0007t\u0017\u000f\/\u01a3\u001an\u04ae\\$SDBYN\u0001 q\u0003vJ\u000e\b dfR\u0001R7~'~vo9e\u0574{)\u0016\u0012\u0011#wl7Q Kw@#\u02f4eH\u0007:KY c?J\u07b0\u00176\u0019!h\u0003=Z9 \\m9\u0018j]gy|\u0001\\_kx6S\u001aBzn^\u0016gpw,w\u0001@;n\u0007\u0375X\u0003O%-k%\u000f>\u0012|\u000fo\u0005+O\u0012\u0168M\u001dZ\b'[Y# (. ~\u0013\u0001T\u000f\u069e \u01ce-\\i7M_<6{7F9TD*7]pA8`\u000f\u0016\u23c6 \u001b?UZj\\^M5\u074c!g1t|,\u0017Uw\u001f,i.<#8*MKky>y H\u3e09\u00049\u0014r7\/3P\u0007e\u001exX\\\u07c5Bm\u0154\bT \u0011\"\u0003\u0011\u0610z\u0017\u001cz(]\u001bO\u001d+C\u01f65R``m+\u0003c\u0018\u000f>W\u01bf\u001aB{3r\u001aVk}8\u0018cq\u0007r\u0110TT\u04c1h\u0003h_&gu \u0007gw\u0019;?_ \/>,x\b+]\u0003B)&^UNj;0\u0006Gc\u0013p. \u0001O\u065b@ +\u0010A\u000ec@[\u000eTH_7Ud1\u017e 9\\$P\u00163l.\u001fR_\u000eu\u000f\u068b\u2395W\u0515\u0011vS}\u0001&]R\u001bv\u001cQ!d\u0005\u0015\u0143}@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005|mP.\u0017\u043am\u001e{7&kSM\u03f4==2b\u0016yY\u000f\u0004\u0003\u001fKZ\u059a\u001f\u001cbKo\"\\vKH\u0013\u02dd~P\ucc3b(NY\u00174\u0001''>rq\u001a\u057a?Fv=\u0003\u07bfb{|}5\u0016\u0011<%xRP\u00033[G%,\u0004\\1]\u00c2C(\u0007m\u0004_} \u000e3\u001e_m;\u05dccwp\u0001Gg \u000ey\u001aE Cc+Z:{c\u04eeHa\u0006@A\u001ee'k{!x:CC\u0684F\u001bI\ub702\bV\u0004\u0006V\u0004\u0015 \u0010A\u0007\u019f\u000f6\">\/\u0014Kxc\u0006mLi\u0012Nx\u0673laaW- `W_\u0012| ^Ek\u001d\u0531i\u06ac(u\u0018\u0321}\b\u000eUn!a\u0011v>z\u0003}\u0002\u0013I\u0003\u001cE\u001d= \u00121\u0011@\u000fHe\u0001 f#@ f\u0017SO 8 \u0003\u0080;+\u0015:%{|\u0001{\u001b35\u07a4 \u020bkk\u001eP\u0014nMU>d}g_+0\u000ftoc\b|t\u03ce|3\u0014\u0017lYr\u0003\u0463+36FK3=\u001f\u008f hUQe>XYf\u0017 u\u0004\u0012\u0019Y|}\u0002m'NK?? '4\u03a5a\bF_I>v\"l[#?.!g\bf'|Gv##ir\u0018wu|\u0011\u0018\u0003\u0018H\u0007_1C}s\u001eM\u0142Ho-\u01c92<`\u0444pF P\u0001's\u001f F\u017f\u001a1\\$kbpG\bu.\\$\u0007 \u000eBE 3mo( \u06c0\u0006^_\u0005\u001a <\u001fj\u03314>4Hu;c\":Y\u0018U\b&fYUW_)L^\u0012O.y\/t[\u0015,,qX #DV\by(Y\u0015\u00cf-\u0018{\u0007M j\u0004\u0012%o\u001d\u001bCq\u001bP3k`\u001cmU\u001e`RM\u001f\u0007~\u0016x7I}\u000fT\"\u001dI\\$Iff,K333\u0012I\\$\u0003\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002 (\u0002<\u001f\u001f\u0006\u001e\u0007z!R\u0016dfgB\u00f8\u001e\ud33b8\u000f\u028fO \u0019\u33c5:TNVK>oY*\bl)F\u0011;9M6\u0010\u0003{\u0013j\u000f4kMGL\/\\\bKIUx\\$bKmYV7\u0014\u0005 =\u001c\u0014\u0001\u0011|wKk;\ub667gUi\u0259N\u0004c3y\"Fws,hR?\u0003fXRg49dJ\u0006#-P:\u0015WMpA\u0003\u001b\u001b #\u0012G4l\bdu9 \u0012\b<\u0010h\u0003X_\u0011X3>0!\u0007\u0674^\u001bDF#R\u001c!60\u0014:fyt\u0018oT\\$b9t\u030cdw!!'\u0019Q2H\u0007q\u009f \u000f\u3fcdt%M\u0002y\u0016\u045e0\\Z\u0004SuT'*9Fn\u0001\u0006 \u000f[\u01fack\u073e->{8fku,\u0001YfTt\u0001@>t\u001d\u0003J4+};M-l\"X\\$P\u001a\"\u0015U@\u0001@ tP\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005\u0014P\u0001@\u0005 endstream endobj 23 0 obj << \/Filter \/FlateDecode \/Length 7360 >> stream xKl9RH|\\H7\u01d6\u001e\u001dX\u0010Ba\u0016|}\u001c\u000f;\"O\u056d[v\u000f\u05a8p\u000e~{\u00cf?-|\u000f\u001e9\u0005w[Kor?\u6ffb?_=\u001a)??n#\u07f7_\u0004Qd{FF\/7#\u0006\u0015\u001b y#\u001a\u00071\u001bSMkq\u0001'q\u00188s,Yj}=g\u0018\u0005HB\u0005X\u0001:kbr+ \u0007G\u0002m j@3!Q\u0006 U\u0003+dM `\u0005hi-\u0004\u0003d \u0014\u00192-\u04a0 W\u077af\u0017 F@O:;T!\u01cdb%\u0018f\u001dk'\u0003*nB -\u0018\/\u0018eWY0b ;\u0003%9Z tTt\u001a0PLH4h2d4\u00036dM\u03a0E_V|k4SG 4XKWM\bh^s5-(=7v\u001d5 U#- \u0015Kov5!\u0010-\u0018.yk+\u025aA>\u001b~j{\u0016^ YdC0 \u0017p&w\u001a\u0018\u0017\u0014\u00e0 DU#yjN\u0004\u02dc\u0006 s2PSS\u0225*@\u0002\u0010BQp ]\u0011]F&P\u0011dMjB@!.ZLK^^\u00c0j\u0014l;W4\u07c69iaN\u049e7i^`qE\u0018;I\u0019d`\u06dcx05 6\\:.)lA)fhsVH%(f\u0004\u0001pD:n` G7d(P\u0011\u075aBuA_^& 1iU&[ Xi\u0359\\$4q 4uw:j0\u00119\u0018(@5kn`\u050fd'g(n\u0264iV.V\u0003:4;\"\u001e'}tt \u001a7_LYBv\/\u0014\u0271\u0005tTJ}-rP3\u0515AAo\u0002T\u001dS*@W \u000fS@\u0006d{\u000e E pCP\u0001k-U\u0013\u0012du\u00150F\u001ai\u03d0 X\u0001I.L<\u0006\u0003VrPi%EM,\u001bqcNB \u0006z{)(h.[Ph6LX|h\u072e\u02f33\u000fR^7\u001d-Tws^ \\$L9D\\\u0003\u0016 R3@\u0004\\$k \u0001(|S*?\u001at\u0001L.@\u056cG\u60c1(\u02101\u0007o\u0013\u0019\u077a3!\bH^#&*[2!i5'V\u0003\u075fMX\u0001iMe1\u0615B\b5Ke\u0011Oa=>\u0327s\u3c84k}g+\u02fe\u0016Y^7\u0016YDM>\u0016&X\u001dZU\ua3b0(U\u0545B\u0018gu \u016c\u000fN\u0014KI\u0005!\u06bdYch:e\\'O2!'\u0003bK8\u001a5d( n\u0005 \u0001\u0019H!\u02321P\\$\u0018}g\u0003e#\u0003 2\u00064h\u0013cu]_!:#uO\u06408\u0011X\u00143\u0015P3\u0015vr\u3c12GGc5vc> <,e\u0003!9\u001d\u0005hx \u0006\u0004,35V9\bHEm\u0016,\u0003jQ\u06ee=\u0018Cw' \u06184[\u000f\u0015\u0015\u0019\u0013'CZGl7A\ue1a9Oj\u0004G\/+`8bO2O\u0014`^\u0006,^Zt\u0011\u0006H\u0005\b&d \u001f8\u00132 \/ ma\u000el\u0018fK004|\/l\u0018Qt (W7!MmR!?r)Mlx&M \u03f8C\u000fo\u0004<\u000fOsc<\u05fcsr+^1\u0017\u0638\u01adFNinS7\u0011\u0019\u0007vZ9;1h\\7 vy\u0007@\u001e\u012d; W{l\b, \u0197ok&D\u0265v2d# w7I\u0006\u0780I\u0003 f\"j\u000f\\\u0001=o\u013b[\\$!Im\u0002;\u000e^\u04a9Lc\u0007\u0007{zVt\u001fa5\u0679\u0018\u07a6\u0014}^Odg\u53deU7\u0007w}A\u001bBW\ud795aS>\u001f8+z\u9413m|\u04c5n\/o]tX~\u000fK~7G\u0007jQW2\u001fB\">\u001d\u0013GRXi,|VzKz}9\u001ay\u001de{tZknt\u001b\u0016\u0015\/\u0007(\\$\u001a^\u0012~ut:\u001fT1\b\/_>TtCt_i\u0018tW\u0005-Sdyuc~\u0018e?t6UCA#tZ-e_}\u0010z\u0013\u0015SNK\u03eb\u0012>k>[\u07583eV\u076c?!] >7O~\u001a\u0003{,=O\u0406\u071f]&]Yg_#X^+{\u001f Osn\u0001\u001c.\u001c\/.\/\\x);8\/ -JT>NTcr\u001eBK'\u0012\u0017yO ?#1'k\u0092,su\"\/N\u0743nFp:%q3\u001fU{eQ\u000fS;>#.|>|\u02495_rT\u072e\u0017\u0488]\u001a\u0696)HD=\u001c\u0013~\u00191*s\u04daUzV~\u0006\u0636FO#r\u001f5\/{yQj\u001fwwe\u0003Q\u001bvmh{]{ -\u07cd6\u0687{ ^+_*\u06e3{MubT\u0003\u0005 6n \u0019Uf!6[Q=\u02acv\u0005\u001d\u000fJ\u0232dvkt1^#]Zvchoa\u0019S@Se\/CG\u0019:rK\u0018.]btS]b\u0018EZ8\u06dch!kVcK\u0005t}z|up\u0018gXV\u06d3T{\bNTr'\u001f0l5\u000ej\u001c.8\\ux\u0197j\u001e.:\u054en#yK+\u0012\u01edk+\u0015?\/\u000fc\u0137eIj8\\$w]\u0012]_\u0016GIGz\u01af6S I4\u0236bN}x\u001fwu|q_[fa*9\u0007F3\"\u0013?3;cH\\\u001bQ\u001cat49bO<%cv CB\/eN 0u\u000f+|\u0019\u0245ibK\u001e!~ t,w\u0701QF Q,fhqy\u070e%f\/Pfn\u04e9S\u0013\u0014tN\\[Q8.U=.TEu\u00e3\u0015L\u0015\u0016Ap*\u001fB\u000e B#^~#a\u4294O55\u0013u1\u001cDQdD\u0004gHL4\u040f<\u0007qtw \/Zw,\u0006\u0001?1(yK%77RB&\u0006D5MU#0S@+\u00114`r)\"\\$\u0007z{]r\u0004\u049cy-\u0015:l%g\u0015ag\u05e3x\"i\u0002\u06dd\u000e~\u001e\/M`:NNnV~G~\u000e\\\u031d\u001b\u0688\u0011XV#'f\u001bw+;es3\\$]S_>] \u0011U6\u00100xQ\u0012\u72f6-2&=KCE~\u001d\/6H9\u01bb2\u0729\u001ctv\u001b~\\}~-?=Gk\u00181 *a\u0355v},3j^ \/`{AM\u06926\u01fd*Eh_0n24\u0019V%tg3@qgqa'2\u0004\u0006\u001f9^StpbFi>Q=\u0010\u05e2K\u19e1\u0006_\u0012wWFtsWVfH|o\u0012jJpw\u0019|3\u0003!\/w:\u000e\u014f1Gt2Fk^]\u04de\u0010\u0004+l*sF\u067e|!7%*a_u]-U\u0294*\u0012?1y Gt\u0346Vjwj~}+I3[\u0012}\u01c8L&k oK`_fw *f^S1\u000f~\u0019\\ Y\u0085CMMMs!\u0011DR'!xs8IR~va8S67\u0011FG~vw\u053b\u0007&q\u00186\u0019U2\u0777L:Wbw\u001dDJLFF \\2 7C1\u000e*UH7kFJ@WuiEYh]{5)p\u0011V\u0492b\u0007F `-n\u549f9_)@bp\u0556*3W^h3GWkW{fXRr;:;Y[6K'vG?%4\u0018Ngz\u00f7;\u00057&sS&\u0001ZBiV14J'=i\u02fdl\/M%s\u0005\u0608yXgm\u0012d\u0012-QeI2\u02e3Tfp~({\u000e+h6NY\u06e7}\u00074mp endstream endobj 24 0 obj << \/Contents 23 0 R \/MediaBox [0 0 841.889771 595.275574] \/Parent 1 0 R \/Resources <> \/Shading <<>> \/Pattern <<>> \/XObject <> \/ColorSpace <> \/ExtGState <> >> \/Type \/Page >> endobj 1 0 obj << \/Count 1 \/Kids [24 0 R ] \/Type \/Pages >> endobj 28 0 obj << \/Filter \/FlateDecode \/Length 12 >> stream x? \u0003 endstream endobj 25 0 obj << \/Ascent 859 \/CIDSet 28 0 R \/CapHeight 500 \/Descent -140 \/Flags 32 \/FontBBox [-7 -144 1000 859] \/FontFile2 10 0 R \/FontName \/FPENUF+SimSun \/ItalicAngle 0 \/StemV 80 \/Type \/FontDescriptor >> endobj 8 0 obj << \/BaseFont \/FPENUF+SimSun \/DescendantFonts [27 0 R] \/Encoding \/Identity-H \/Subtype \/Type0 \/ToUnicode 26 0 R \/Type \/Font >> endobj 27 0 obj << \/BaseFont \/FPENUF+SimSun \/CIDSystemInfo <> \/CIDToGIDMap \/Identity \/FontDescriptor 25 0 R \/Subtype \/CIDFontType2 \/Type \/Font \/W [0 0 1000 1 30 500 ] >> endobj 26 0 obj << \/Filter \/FlateDecode \/Length 372 >> stream x]n0\u0010E|,E\u0004H\b)Cb\u0447J\u0001\u0004\u000f)R1\u0210\u0005_\u0019GQu<3\\\u000fT \u001e gh;%5NM7\b\u0017v <\u0011\u0661=\u001eM}L3j\u0007s\u0004Y\/\u0005\u0012uTJTs7\/\u6cba\/!( \u062e[#v7\u07c7!k\u0019\u0011B\u0010T3H\u01baA]+\u0007f\u0015*C%g[OB H0\u0018\u01cc\u0218\u0012n\u00193B%L\u0019w\u0016\u0013\u37a2 E\u0003\u0003j\u0559DQbQ\u0011XeARW\u0014(DL(\u0018\u0013Jf#\u001b10d\\$uEz3Lz#\/HoS\u00107\u0018\u0778b\u0753uK\u063b\u01da^Vx78?+ endstream endobj 10 0 obj << \/Filter \/FlateDecode \/Length 6624 >> stream xY{tT\u7779G2df!3\u0013\u0012\b\u0002BnM**\u0015L\u0002D\u0002y\u0010\"]Z\uadb0mzlE\uc782H\\$\u000fEm-=-R\u001f[|6g\u06ed=;~w&\u0010vw9M~~{ \b!\u0005B4rm_oB)lY\u06dd\u0010x\u0012\u069a7@C\u0002 U\u0007Y\u001b6 ost\u0004oXPe\u000405A_!#\u000f\u0018H_Z\u001bd~\u0011n66rk0>z\u0004k7\u001b\u001b\u0019GFU\u0010\u0785\u0010e\b\u001d\u0018\u000e z'\u000fJ(\u0120B\u0007Q\u00169'\u001f{4F}wav\u026f_?(\u001dG%q\u001d+oG\u0752P\u016adY\\j\u001ay.?WnN.%\u6b96V&6&i<|l+\/X\u0295Uk\u0006\uea3c7pv\u0018W' cR q\u0017E)&M\\2U\u0003#,\u02e5ScX=\u030bIx<.m\u000fY\u01f1d\u0014\u012as\u0217adc\u000f\u05b2>akK\u001e{,GlF\u0015r|wN~ \u001f\u001c\u0013<\u0323N\u0006\u001dB n\u0002>4\u0001|Hfd3\/:bFd\u0015aQHkXU6:\u001ac:c\u0018\u001dx0\u0682m` -x`\u0001Q8\u0007Da.\u0006 s\u008dgQ< \u0253%(\u0018S!\u0012xP\u001b\\OTq:N\u0012|\"\u0558\u0006\u000f6|LjP,9s\u0016M3 a \u02a4Y\u0019Z);I\u0013\u07ea\u000e>\/%v_}zE\u0012\u0017TZB6P! \u009aL\u0004p>0\u0011 \u0001;f{\u01b0:ct \u001f\u001bc{`\u0011\u0015[\u001fO\u0798E\/09\u0001sp96\u0010`X.V=+YLa0L\bl+]\u022e\u0004\u0010vu3\u021cG'\u0011CQCi\u001e 0{CiarV+Xo\u0001PAQl\u0010E\"u`y\u0001h\"0'4,P`\u001eV\u0001h\u001eBU=*x\u0280B)\u0253\u0153\u000e\u0014\u000e[|O,5K.J\"zDEg\u000e+\b\u001c'\ba@\u0007\u0423(vo8cnn\ue93eN}\u000e-QMJVy\u0014\u0018Y\u001fNe,1;g\u001dvc\u000f\u0294*PQ+O\u0018\u000e\u0013\u00186\u001cI'DpL\u0018<\u0003Z=\u0017S\u0018;6yf 6\u0007JT%\u001aKb5\u0313 6e!.\u0018bu|\u0534\u0012E\u0002\u001bm\u001e*q\u0002\u00f2\u000fX\u001e\u0152+\u0012eTkFA2u\u00108!\u0004\u02a17'~JE1 w<,|+?xD]-\u0769i~.m&-\u000e\u05aa[BuE0 P\u0099\u0503uc\u247a\u001fg~)Y'\u017aJFSO\u0003Wm9 O\u001d]@\u0761\u0013u^c\u0017 \"-9:\u0015\u0014E\u001cV\u000e+ZR9O=dE\u02427mg){\u0004\u0004\u0175dJi\u000edE>GqjZ\u000487e)\uaa8a?j\u001a\u001e\u000e\u00faa\u001aaz_Q OW-I\u0014o8lUc*~A.>Y \u0611zGe\u0006'Z\u001aR|C\u04e7\u0005^\\, v\u0276\u0379<\u0007\u0017_\u000eo\u05ac^ Qlqe7\u001b3\u0015\/>\bDQ\/\u0508~!@`\u001dP\u0007\u052f{TjN\/VP]\u0014[3\u0004C\u0011t\u001065!Al\u0620B@`JH_d\u0019u\b,0\u0018\u0011%v\u001e(\u0010\u0010a?S\u03a9_\u001758\u0015: T.\u0007>\uf1d03qel\u0019\u0017[\u019d|N9#rRl:`>o\u0715\u05f87}\u0007\u000fS\/\u001b6~;L\b\u04ea\u0004\u001dQU-\\$^@Xql\u0004\u0007V'Si^6v!\u001c\u0003V*X\u001dE5y\u00165{\bm b@Q(\u001acuZk\u0001L\u000f(otV[\bLC|\u0014GM5b\u0012qa\u001a\u0004y\u000e\u0013\u0011\u001b\u001aG`H\\Es\u0018D^\u0001Du`\u0010(WIW \u015d Z\u0001_'S\bJmaYb\u0014(MD\"T,\u000e\u0004n\/*QDw\u00130Shei\u0012F\u0011aEaow?N\u0006F[^\u00afg\u001f? J~Se^6\u001ct\u001aQ\u0004)\u000f2(\u0004wp8a\u000eXQ,\u3cf6S J\u0013z\u0002\u03ca %z\\$\u04c0\u0014\u0016\\$I @34GAIx\/\u0001K&ZblB\u0489\u001c\u0016 \\$= \u0006@Y@@I\\$\u001d\u0007xq,zTWsS\u00057\u001cj%\u0006\u0002m.`Yn\u06b0gZ%IR(25] Na.IBi\u001ew\u0019\u001bB]- \u0012m\u0001'\u00147 W\u0018k\u0001ouY\u0014\b\u001dVY\u001a1BM\u0018\u3b73kB\u0001l,\u0004Dtf\u000e \u0015\u001e\u0010A\u0019k\u0012-\u0006+ \u0004qp \/v\u04ba'9s\u001e3L.\u04d6a:2g3;3{22\u00073d2bL\u0303\u000f\u0016evM-]KrXU\u001fY\u0439`\u0002zq\u0018\u02a2K@i\/\\$K\\$\\$^+T \u30c5\u0005BR^ \u0002\u00197]T< \u0014g%b\u0015^\u0004)\"2H) 2]\u0019\"M0E\u0004\u0011 &\u0005Cs\u001c\\.xY\u0016EIj\/+A) \u0595A;\u05a0\u0006tv2V7\u001a\u000fTe_\u02bc\u017epF+8uXHap\u0012 M1zz\u001e\u0005\\$\u0005@\u063b*VRAMgO\\$\u0019`\u000f\u0018VF0\u0003\u0011\/X:\u001d4E\u0006 a|\u001cx~\/pf\\$=@r\\\u064b\u0015JX\u4303NJ75\u001b\u0487TI{|h\u001aEUaG dV \u0018pU6eOU\\$U\u0018n\u0435\u0002- <\u001f\u0013u1^\u0004%l\u0018\u0540w:\u001b\\$n\u000f_\u001b~U\bbm5\u0486\u001bM=znkyzz:\u0012g*_gnd74h\b'\u001bp:d+t\b'}\u0018cr6BG26=\\7\u001fKC!\u0534\u0006Rw\u0006r8}J9\u001eWN\u0016TnK\u07d3~Dfe4n =&_!;\/Wh\u000f&\u0019QI;1\u02baeF%lc^{'L&\u001c+\u0433\u0017A\u0511CW\u0017\u0015upnp\\$vhE\u0004\u001f>o\u0014\u000e\u0017f7_D\u0005<\u0506\/\u00138\u0018\u04c6K7\u0002\u001co\u0127BF< '{M\u000f. i\u00157y\u0010oD?B*Q\u0011\u05cb}_ iSs\u39ccsR.Fmq].,G\\e\u0006\u0010Q\u001c3\u0014U+Mq2n\u0016jw\u00f8Ry\u0004|qg\u0694y~ie9X\\rs\u0011x\\$\u0019yWqW\u001f2\u0011N\u058eP4pWj:&\u0012l}\u0006\u0005}f\"\u0019a\u00118l\u0006,\u00040aB{!C\\ r3dN\\$tR5zpu Tp`\u0155\u001b!*DdX@|%\u0012 \u001aA1*\u038b_\u0014dOU\u0019\"> dR7X\u012a.HA? T56 I |\u0011LoY#_6'Q9p^` K\"7b\b\b!\u0005\u0011Fyy3\u001e\u00051}\\$bUz \" (Y\u0003ID\u0018g\u0004\u001b> >\u1000 (t\u0013t\b(\u001bP@_78-V~S0,{+\u0016\u0007LhE2\u001c\/\u072dsk A\/Ra rHg\u0001( p\bQ_T&*EK\\$-F\u0013|to \u0004yz\u0013 \u008bS\u001frXj\u0007\u00176HAEY0 Ae\u0002H\u0016\u0015x\/K_m\"\u0007v\u048c\\\u0002+\u0014U\u0010w\u001a\u001fb\u000fx\u001d\u03f2\/\/bm\u000f^Mf\u0010\u001eB#ndx)th .4\u001a*N\u971b\\$9Wt Ru3\u070byn\u001aF \u001a \u0006\"\u0003Ylm*\u02554\u046e(\u001cG\":.M<\u0007GD\u0016\u0016c8q\u0013l\u00d7Q% ss\u0013|g:1\u0360?Y9Js\ua1eb\u0016Y. \u001c\/z\/YiEU\u0014\u001a*=|j(s4}}>}5o(\u06c3jaM o\u000f0\u000f\u0794n[w;A\/Q\u0005\u796fV WI|&V^:(ErQr\u000f\bYT \u000e1rB\u061d\u0003!\u0688\u0010t\"\b`X:*\u0002|*C\u001c\u00074q&D4\\azV2zA\u0018 c\u0004 w9\u0010P}y\u008a-\b\"1@6bC(r\u0012\u000f[\u0005B\u048a\u07bbx\u0017y>{RgS\u0007qWN \u00068\u0018\u0019[-_bn. @.](\u0002E\"C\u0011_MM(:O\u01d5\u0019\uebeb\u00179\u001e(rPcJ{)\u0447W\u0018n(\u0017\/\u0013!: e\u02bb\b1@ q\b \u0010r|\u001a!A\u0014\u042f\u001eCH\u0003w\"dF\u0015|\u07c4\u0002C( \bY\u0016\u001aA(r..\"LK3\u0007n\u0013 \u0017\u0016\u015b\/,5ua%U)\u000294=A 2hZ\u001d\u0019\u0011jW2a2MAyL3\u0699\u00194,tLs3y L#2+\u0010Z\u0401>8e\u001a#^]\u0019 w\u0005\u06cb\u0017 \u00162\u0011g2e\u02b4B\u0003%\u0003\u06c7zo\u0018^q'm\/\u001a\u001e\u0005|~E\u0015[7_\u0673~k\u06a1kzo7e W \u0674vhc\u01fc`v|qO\uf37d\u05e3\u0003(~8oh\u0003dVq\u001a-G\u001d OkQ;\u0517LzP\u0017 0<3 9(\u000fh\u0005oV\u0018q%_\u000fT\u001fZ s\u0010\u0134^wv\u001c5 2\u03e50\u00067\u0177we\u0013\u0019=0{,eI+>j\u0007_u\u035f!#^ <]\ubfbfnhyoN\u0013~@=t\u04aeJ49\u0018pqw#e)O\u0011N\u00035.W\u0013@F`0p\u0001xvh\u0156aVt\u028e\u0015=\u0003]\u05af\b^W\u052d^Qt]g\u07f0k}nxOVty\uaebb:V|\u001e7_!1_r\u001f\u0355\/c{Ys\\ yn&\u0017{C!\u0006\u00049\u0012DV \u0007 C \u0003\u000e-\u001f\u000f#\u0013\u07ca\u000f9T\u001f5\u000e\u001a\"%>\u0007\u0005`C;\u03e1\u0010cn\u0012\u0019#\ud854\udc3b\u0006Rt\u000eg_~\u5aa5\u0695\u0017 xS\u001a\u001b\u1a57 V2x\u0006u\u0632t'\u001eS}\u0001E\u000e\u0341\u0017\u001e\u0015v sK7-q\u0018f\b\u0010uk\"UB\"UT)RI\u0015]EI\u0015*N\\3 \u0007m1 endstream endobj 32 0 obj << \/Filter \/FlateDecode \/Length 10 >> stream x\u0001\u0002\u0001 endstream endobj 29 0 obj << \/Ascent 859 \/CIDSet 32 0 R \/CapHeight 500 \/Descent -140 \/Flags 32 \/FontBBox [-7 -144 1000 859] \/FontFile2 13 0 R \/FontName \/FPENUF+SimSun \/ItalicAngle 0 \/StemV 80 \/Type \/FontDescriptor >> endobj 11 0 obj << \/BaseFont \/FPENUF+SimSun \/DescendantFonts [31 0 R] \/Encoding \/Identity-H \/Subtype \/Type0 \/ToUnicode 30 0 R \/Type \/Font >> endobj 31 0 obj << \/BaseFont \/FPENUF+SimSun \/CIDSystemInfo <> \/CIDToGIDMap \/Identity \/FontDescriptor 29 0 R \/Subtype \/CIDFontType2 \/Type \/Font \/W [0 0 1000 1 11 500 ] >> endobj 30 0 obj << \/Filter \/FlateDecode \/Length 276 >> stream x]n \u0010EY\b\u04a6e)uT\u024b>T\u001fa\"\u05400YKxDUY\u000es\b\u64ae?RX F\u0001-LBr\u00180,\\$dE \\0\u001fl\u001a2\u00f6Z\\z9)h\u001a\u12ab5\u001bN\\x\u0007p4B\u03b09J+.?8mtmB+]\u0010~ \\$F(E\u0011\u001e\u0014US\u0019!krZhj!C+\u001c'MMp\u0014\u0391u\u0006,=\u001e\u0012VZE\u0003#\u001e> stream x\u0017kpT|}qdd7\\$\u0007yh\u0016\\$*:%P1\u001d\bIHy,y\u0010E\u0001\u016aCL\u001fZv\bd\u058e\u03148S+\u040e4{7\u0004_~\uff3f[ `\u0011`!\u0673}SnK\u0014)\u0003{:Z92|\u0011\u001ai>\u0010X\u001e\u07a1mk\u0011`\u0019E<\u0005\/LRm:\u0005 `|O[UTZm57F~k\u0017\u078ew\u01c7\u0010 \u0636e(|l\u0005p\"?\u02a6lg;W\u07de\u001dT!`\u0007\u000e\u008ff\bv\u0552\u001a#dmMa}9\u0019)]d\u001dK-\u0007.2\u0011* (i\u06e4<\u0019\u000f\u0011\u01c9P\u001c'zZi 3!2\u001a:\u00130\u0106\u0003W\uad292~\u000e S\\$\u0003\u0006 RG|A\u047a\u036a> \u07aaU:],q<\u0016\u0010\u0011\u0005\u0016NC \u001c#*jc\u0012\u0018\u0710Sg\u000egm\u0016Kx\u0002\u0014Ls)D\uda14\udf2d#W5UkrQLbd \u00123NR5Qi\u0015 \u001dnyJWm\u0017dEVt#\u001c.J\u0012 \u0002Ey\u0010.R\u0006\u00061?VBg98Fq\\$9\u027f&fWXWVxWv3\u04b3D&\u0012q4+D\u001101NL cjtL2RTF\u0160\u07daT?MC\u000e\u001a8'r)C<\u0013\b\u001c,\u001f-+\/>Q\u0016K%\u0016,H\u0449Z26:\u001d_b!9\u0001T*]oebl\"w\u0663\u04d1%{Zzc \u0002\u03c7\u001c\u023b-\u001fqY(wV]\u0012h7\u0001g\u051dVuz*zlX[{ `\u001fVRT-\/b \\$H\u0002 \u0463GC\u0014d>\u001a\u0010cCE +866fe< \u0011.]\\\u000e\u001fk]Q5.'uvR'\b.%\u0010\u001fDAN`\u0492\u0004(\\$i:Y\u0011Q97HH\u0012\u001b_]qD\u0004\u0012S2!-VA[\u0010\u0147`\u001b2~x m \u00139{KeC3\u0003+B\"X0\"ziRb&%bf\\$FR=\u0003V^@~\u029eQ \u0013(\u001f>bd)j%S\u015c\u0019BZmy\u0017}|!e'\u0016\u0007>xO,\bg\u0001\u043b!h#=x #M\u0002\u0004Zo:f YYS3\u0011 \u001c7av\u000e\u0003j\u0013\u0016E4J\u0011NFl%0AM LC\u0012~zn\u011eD\u001f7ad\u0368Ac?PN*\u064bbkl~\u05bb +tovY:38\u0017:S\u000f|\u01ccxM\".kU\u0001 \u0703gu!\u0014\u0015|N8 q\u0014 a\u0003B\u0014efQ,E\u0019\u0014Y((PD\u0007\u066d\u0016 endstream endobj 36 0 obj << \/Filter \/FlateDecode \/Length 9 >> stream x\u0003 endstream endobj 33 0 obj << \/Ascent 859 \/CIDSet 36 0 R \/CapHeight 500 \/Descent -140 \/Flags 32 \/FontBBox [-7 -144 1000 859] \/FontFile2 16 0 R \/FontName \/FPENUF+SimSun \/ItalicAngle 0 \/StemV 80 \/Type \/FontDescriptor >> endobj 14 0 obj << \/BaseFont \/FPENUF+SimSun \/DescendantFonts [35 0 R] \/Encoding \/Identity-H \/Subtype \/Type0 \/ToUnicode 34 0 R \/Type \/Font >> endobj 35 0 obj << \/BaseFont \/FPENUF+SimSun \/CIDSystemInfo <> \/CIDToGIDMap \/Identity \/FontDescriptor 33 0 R \/Subtype \/CIDFontType2 \/Type \/Font \/W [0 0 1000 1 5 500 ] >> endobj 34 0 obj << \/Filter \/FlateDecode \/Length 248 >> stream x]n0 <\u0761 v8!14H\"\u0013\u000e\u0004i9\\$lvSsn >\u0229\u0016\u0003j\u0364\u0010:\u001c(A\u001b\u00156\u001aL]cc{\u0007U%>99\u0005Z`]O I#\u0019;h \u0007\u001f\u001c!k\u07db]\u0011AD~?%_G(SHRNBv@\u022aO \u001b\u001a21 ^\\$%A> stream xW]LSW\u001c[(-\u0014\u0004\u0010 ?\u0010\u0699\u0001\u0003!\u39b4 >5Kf,\u0012\u001f\u0016\u0013_[\u0016t\u0012&Kft\u0312\u001b\u00185\u04e2{[db;14[6{n\u0011d`df] \u0005\u0012t\u0006\u0010\u0018?J@\\$\u0361 Eg4,HwAWLaa>\u001f)cT fE\\$\udb39\udcf9\u000evtM\u001bA;bh\uad85\\$h?.' \/}=\u0005sW\/\u0017!_%\u0002Z\u05d3'\u001fB\u00122h.S!S#i\u001b\u0017Lm\u001d\u04ddBS)?\\zN:'~\u000ea1\u00141hU\u0006HhaF23+Y]!ds=YiumJF{{[WgGi[mgGW{lk--JU\u019a\u0686\u069aOZ\u001aZ(29i \"_T\u001e(ruc8h~`_.28Wp\u055dg\u07e1 \u001aSM&\u056cTX\\$&P ;Vmo\ud192lB0H*@\u0015]S7,E8nZ\u0005\u0017;\u0015Yu#\u001eVV\u0749vFQ\\1\u0017 fMrAU\u0015EUgd#zJ4MM7%v_6sx;L\\h\u000e\u04f6\u0017* k\u0017|}74\u0004\u0621\u0012e\u0005xY\u001aF=`\u016e.ADS)]\u0282L1Z\u05b6M3\"\u001a\u0013\u0011jEz\u001bN\u0015l\u03d9\u001e\u0003\u0012Y\u01c6<\u0229CJ\u001eDM -&\u000ePD u,\u0571!\/a#U]\u001d+y|\u0013\u001dG:..~\u001d[i3*?o\u027d:f\\$7u ly8W>\u0002[^c\u00c5(c_\\I\u0003\u001e;\u0012%\u0013X\u0607\u0016G:\u0012b\u00c1`*M\u001c \\$&\ud922\udcf3~8\u0007iG|9\u0006\u001c}p,H}\u0014'f(Aa R\u001d48\u0001\u019a\u0004\u0207\u0004c-\u0018\u0205_+\u001fE0@\u0011B\b\u0004laN\u8e68\u000e%?fB4x\u0003\b0\u001bSh1\u001d\u0005?\u0005.:1\u0005\u0001I\u0017\u0006v\u0007\u00148zk\"^\u016c\u001f&\ua495:\u0001 K- Z\u0006\u01bdFD\\k5j\u001c#,5-_?,e}\u0012\u0015Y[ \u0011\u0011\u000e\u0018y\u05f7\u001d\u0007?\u0001\"7\u02f26fC\/;O?)\u0013\u001bm\u0007}\u0003{Mpv{\u001e\u001dpo\u0011> stream x\u0007 endstream endobj 37 0 obj << \/Ascent 859 \/CIDSet 40 0 R \/CapHeight 500 \/Descent -140 \/Flags 32 \/FontBBox [-7 -144 1000 859] \/FontFile2 19 0 R \/FontName \/FPENUF+SimSun \/ItalicAngle 0 \/StemV 80 \/Type \/FontDescriptor >> endobj 17 0 obj << \/BaseFont \/FPENUF+SimSun \/DescendantFonts [39 0 R] \/Encoding \/Identity-H \/Subtype \/Type0 \/ToUnicode 38 0 R \/Type \/Font >> endobj 39 0 obj << \/BaseFont \/FPENUF+SimSun \/CIDSystemInfo <> \/CIDToGIDMap \/Identity \/FontDescriptor 37 0 R \/Subtype \/CIDFontType2 \/Type \/Font \/W [0 0 1000 1 6 500 ] >> endobj 38 0 obj << \/Filter \/FlateDecode \/Length 259 >> stream x]Qn \u0010+\u001e\"d!Ei+\u0407\u00030]\u001a\u0010\u0007}1(*E3\u0007OV\u001e\u02073C\u000fl\u0016'\u0010z\u001c@*3\u0004}\u001eV\u000f\u0006|\u0006rnE\u001e\u001f;N\u0011\u000eD_C[)`a3{O\b\\$j}JVPD\u0012Fl@P44<\u0006Kx ) Ap\u0004u\u0010PZ=\u0004O\u0011tsr6evd[X\u05f9|\"o\u01790uw6>\u0004o7F\u001ely endstream endobj 19 0 obj << \/Filter \/FlateDecode \/Length 1963 >> stream xWml[W\u0019~q|,_Ml'eY[M\\$4e]Z\u0575\u001d\u06db2#b\u0509\u001fHt9X\u0016\u0012\u0013N\u0012\u0015L\u001d\b\u000f~{%@\u000f}y\\\u001b\b`\u0005t\u0010M\u0017~\u001b+r>\u0002\u041d\u02e4;[1f\u0019\b+\u001e\u0001Z\/!z\u0006u\u001f38_|o ;%\u001ft|\/Q^\u0018t!OlU~\u001c@8SQ^u\u00050~\u000e|\u0005RCys*}uH[\u0018 \u001c0 \u07c9v?Ow^\u077fyg)\u0007\u0006`\u0391\/qK=5\u001a\u0014\u000fx\u0002\u07b6\u0007\u0002\u0001tDX {< ^%\u0016\u0018\u0002\u0017\u0005\u0003W {DkV1\\$rb0qs\u00faqsf\u001f\u000f\u00c1uR\u001c\u0018\u001f \u0018\u019cbgGw\\$<:2v9E=2<\u001a wwF\u0521\\w I~Rjco\u0006tV\u0002\/\u061c\u001e\u000e;|Nh0\u0004I']n[r,.Iu(e\u001e\u0012-\u0016\u000fgq}\u0001\u0018s'3#\u0011\u05c8G\u001a|C\/\u0019\u000e\u0019&6P\\$# %\u0509\u00136lAh\u0003#t\u0010?5x\u0001r0|j W(\u809b18\u0019\u001b 5\\$`\"6\\$A\u0018 \u0012FefHGo\b\u001aY\u0013j5rM.]7\u001a\u04cec\u0017\u0017s\u001f\u0010} i8EiI&.;n\b` s\u0006ZB\u0278\u0015l`8\u00076bc\u001d; 5\u00178\u001c\u0016ff\u03f7k@O(\u0017\"\u001e\u05e3\u0013\u001f;j_]q_}`g@.poW\u0017zd{*9o\u0016F)nKpB? 5\u04b2f2=\u0006 \u0743)X*\u0002\u00139j>}^+\u0588mL\u001fjrYq\\s.+\u0018z&P- *+z\u0010\u01c6-4\u0015kedj3\u0019\u001dm\u001emYl(\bD<\ub23fw\u034a Y8\u00049^h @o\u0004\u0010\u001c <%?70R\u0006\u000e\u0017[n\u001f\u000eT\u0001\u06afoC\u0017\/\u0018w\u001e1V`-`\u001d \u0628R\u0576\b{-H\u06ecC\u0014l\u0019l?\u03a8Mw I\\$\u0017vAC\u0010wUSBTO,V%R*>\u001c\u05307`\u0001s kXlKXmQ\"\u0001\u0019i\u001a\u0002\u001fhX\u001b\u0006\u0004O\u009f5l.I [\/\u0014y->a\u0002<~\u0011\u001a|\u0003lwu\u07f6chFxP5lxU9\\,-LE9qdv\u0445ie*JTB6\u0001e8\u0014\u001a\u7ac5t5\u0017\/?*\/e\u0005%\u0012\b\u001c+\u01d3|R\\\u0001P*tUP0\u0014\u0772 eB\u001a2PA 8\u0002\u0013\u0002L#={\u0004\u0395Q M303\u0004c_E(F8\u0797w_6Y \u001d \u001fJ\u001cK6\"yj\u0001+\u001b- ~\u02b9 \\$\u0004JIW}\u0001rls endstream endobj 44 0 obj << \/Filter \/FlateDecode \/Length 10 >> stream x\u0002\u0001 endstream endobj 41 0 obj << \/Ascent 859 \/CIDSet 44 0 R \/CapHeight 500 \/Descent -140 \/Flags 32 \/FontBBox [-7 -144 1000 859] \/FontFile2 22 0 R \/FontName \/FPENUF+SimSun \/ItalicAngle 0 \/StemV 80 \/Type \/FontDescriptor >> endobj 20 0 obj << \/BaseFont \/FPENUF+SimSun \/DescendantFonts [43 0 R] \/Encoding \/Identity-H \/Subtype \/Type0 \/ToUnicode 42 0 R \/Type \/Font >> endobj 43 0 obj << \/BaseFont \/FPENUF+SimSun \/CIDSystemInfo <> \/CIDToGIDMap \/Identity \/FontDescriptor 41 0 R \/Subtype \/CIDFontType2 \/Type \/Font \/W [0 0 1000 1 10 500 ] >> endobj 42 0 obj << \/Filter \/FlateDecode \/Length 274 >> stream x]n y \u001fC\u0005IvHQI9\uc3d6\u0001\b8\u0019\u0002C~\u0004H5\u0003g?rmZ%\u001dwy\u000e\u0006Y,Gq !0<|b\u000622;Z5h*\u14f3 \u001a{|f\u0005ZF\u0635\u0002nf\u000fN5\b\u001cf\/\u033c \u0004~]?%A(b Cq-p6ejD*O \u0573?5dFe?of\" JUb\u0011T\\$> stream xW}l\u001c\u0015\u07fb\u078b\u001dl\u001fw\u00171\u0001'w I\bTn \u05351mb\u058dJ\u0015Z\u0002\\$T\u0014IXi\u0015@\bWD\u001b!\u0151\u001a>Z?U}vi@Tg73o\u079b7c \\$\u001d8\u001bfa\u0001Hr=7.\u0001\u0213(\u0507?2H\u07ddkG\u001f=\u0001, {\\~KG\u0006Se\u0002^5C0\u0019|+ldnn6*Dd1\u0019\u0019\u1577\\$ \u0001BV'<\bDKk\u06a9^P * *tG\u033c9eN\u0019\u0014.crj9 \u0019\u0234Y Z7PN\bYB\u001bZ7nj\u0010\b\u0018>2v8\u0014*T\u001ej]TXWW\u001fO&Zp\u0002\u06bfg d6r{!r&Wg\u0018c+<\u0003&<\u0013Lk\\^ui\u0015u< PB\u0019h*M+U\u0002\u0019\u0016AYih\u0315vc!3 )dn\u079cZ\/\u0002\u02b4m%VFh \u00151\u0005J|P \u0004-'\u001c 2n^M5\u001b\\$ \u001c(+ i&bV\u0016\u000f}\u0015zxt\u0016jH5T\u0012 JOG\u0017E?6\u0005 u \u0014r\u00191;q\u04f1s b\u0018C\\$d\u00105.\u0001d hsTV}JxA\u0016X\u0010 !!B,h\u0339T93\u00192%F3m5fRt*\u001eQ+6bm&W\u00162de9\u0016S_,\u0006d\u0013^\u00159<\u0012eY\u06af\u001b<\u0188WWdIfJg0\u0014E\u0019\u000e\u0013\u00161q\u0004<\u001fsu4 ilc>^4\u001f3391\u0014:C ]\u0006_#\u0797#\u0012jlj# %2%MK\u00149~\u07b8j=:B+-\u0015##%.8\/5\u0006\u0003hF\u001d(\u00155M\\3 \u0016\u0016\u0003\uedb4\/Eq]*YY!\u0004Y\u0015}R[c\u03ed\u0007ow\u000e\u4ca3,v6\u001b\u0012dW`\\@wa_pxnmNY v\u0017\ued47~F{{^x\u0016l\u0005*7p?p\u0014e`7t'np\u001b;'9b_\u0001G\u000f\u022c;\u0019 {\u0013\u0018=](\u001fz GH @7\u0647\\\u0001a?mC+K`\u0013\u0403\u03b8{o\u0018;hDj;=Xp\u0743(\u001fC):\u0018v\u0014#m\u001aT\u02e8#\u001b\u01ba\u01d1\u0019\u06c3m\u07b1Kqd\u059dsnGS6F>:nG\u0007]:ZEq> %c\u000e\u001eqY\u07f1}\u03beX_\u001fCc\u0698c\u001e7Z\u0018p:\u001c_-\uefaf{?~U{\u001b\u001bgpcY\u0018\u0015C\u0012\u001fQ\\$E,zy\u01e6\u074e\"\u001e \u001fv\"s3ETEz Sn]\/#\u0007p\u0117Ps\u07a80qX4D1<\u0411t \u0019ED\u0014a1\u001a&PL{A9+\u000e%B{t\u053fO\u001ck=#wO{G;1YB\u0013 \u001d]\u05dcGz =_otLsl.\u001d\u000f~\/E\u0005y\u0015Y5|w\u000e ]\u001d \/\u0011_aJ\/ 1+F\u0011~\u0006[ 2;r#ss\u001caJAg\u000fu_{`X`\u0013\u0016!>b:b\u0010 3]\u001dV\u0157.l.!\u001f.O\\$3d\u001fBtz\u0003*\u001e!>w\u0010R\u001cxy\u0004)2k,CY eYZ\/PP\u0016(Kw\u0007\u000fVmL endstream endobj 45 0 obj << \/Pages 1 0 R \/Type \/Catalog >> endobj 46 0 obj << \/Author () \/CreationDate (D:20160421111855+08'00') \/Creator () \/Keywords () \/ModDate (D:20160421111855+08'00') \/Producer (yf\u0015PDFbSSpg: rHg, 7.2.0.0424) \/Subject () \/Title () >> endobj xref 0 47 0000000000 65536 f 0000118616 00000 n 0000000018 00000 n 0000000054 00000 n 0000002741 00000 n 0000002801 00000 n 0000027381 00000 n 0000056889 00000 n 0000119013 00000 n 0000000000 00000 f 0000119867 00000 n 0000126902 00000 n 0000000000 00000 f 0000127661 00000 n 0000131234 00000 n 0000000000 00000 f 0000131964 00000 n 0000133942 00000 n 0000000000 00000 f 0000134683 00000 n 0000137057 00000 n 0000000000 00000 f 0000137814 00000 n 0000110840 00000 n 0000118285 00000 n 0000118780 00000 n 0000119411 00000 n 0000119169 00000 n 0000118685 00000 n 0000126669 00000 n 0000127301 00000 n 0000127059 00000 n 0000126576 00000 n 0000131001 00000 n 0000131632 00000 n 0000131391 00000 n 0000130910 00000 n 0000133709 00000 n 0000134340 00000 n 0000134099 00000 n 0000133618 00000 n 0000136824 00000 n 0000137456 00000 n 0000137214 00000 n 0000136731 00000 n 0000140880 00000 n 0000140938 00000 n trailer <> startxref 141182 %%EOF","date":"2021-09-20 17:20:42","metadata":"{\"extraction_info\": {\"found_math\": false, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 0, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.9071966409683228, \"perplexity\": 203.66947550096918}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2021-39\/segments\/1631780057083.64\/warc\/CC-MAIN-20210920161518-20210920191518-00638.warc.gz\"}"}
null
null
Q: Placing code before/after calling super in viewDidLoad and viewWillAppear Due to the keywords "did" and "will" in UIViewController, I have am unsure where to put the code before/after calling super in viewDidLoad and viewWillAppear, in order to make the code run effectively. For example: - (void)viewDidLoad { [super viewDidLoad]; // Code is here because whatever // setup in super should been done first // before we can do anything } - (void)viewWillAppear:(BOOL)animated { // Code should be here to finish // whatever we want to do in our view // before calling super [super viewWillAppear:animated]; } This may be applied to didRotate and willRotate as well. Is this correct? A: Take a look at this answer from here - What does [super viewWillAppear] do, and when is it required?viewwillappear-do-and-when-is-it-required As a general rule, you should always call [super viewWillAppear:animated] first.
{ "redpajama_set_name": "RedPajamaStackExchange" }
9,701
Eptatretus strickrotti – gatunek bezszczękowca z rodziny śluzicowatych (Myxinidae). Zasięg występowania Płn-wsch. Pacyfik. Znana tylko z wyłowionego holotypu oraz kilku prawdopodobnych obserwacji. Cechy morfologiczne Osiąga 31,4 cm długości całkowitej. Nieco odmienna od innych przedstawicieli rodzaju. Ciało silnie wydłużone, o wysokości 2,9% długości całkowitej. 12 par otworów skrzelowych. 119 gruczoły śluzowe w tym 18 przedskrzelowych, 12 skrzelowych, 70 tułowiowych i 19 ogonowych. Plamek ocznych brak. Ubarwienie ciała różowe. Biologia i ekologia Występuje na głębokości 2100-2300 m (może nawet 2900 m). Jest pierwszą śluzicą znalezioną w pobliżu kominów hydrotermalnych, oraz jedną z 4 śluzic znalezionych na głębokości powyżej 2000 m. Przypisy Bibliografia Śluzice Gatunki i podgatunki zwierząt nazwane w 2007 roku
{ "redpajama_set_name": "RedPajamaWikipedia" }
5,202
Q: image border and regular border not working together? I have a div, with an image border repeated along y-axis from top. background:url(../shadow_left.png) repeat-y top left; border:1px solid black; the problem is, that my client DEMANDS a 1px border also, along with the background border image. If I simply add the 1px solid black border, it will appear AFTER the background-image border. Since the background-border is a shadow, I need the 1px regular border just before it, and not outside it. Currently it is appearing outside, which makes it ugly. Any ideas? Thanks A: Couple of options you could try. Firstly, you could just add a 1px border to the actual image file, on the right side. Secondly, you could add an inner DIV to your current DIV. The inner DIV will have the content and the 1px border and then the outer div has the background image. you will need to make the inner DIV have a left-margin equal to the same width as the image you are using for the shadow. Hope that makes sense Here is a sample A: You could try using the css3 property of box-shadow: -webkit-box-shadow: 0px 0px 4px 0px #ffffff; /* Saf3-4, iOS 4.0.2 - 4.2, Android 2.3+ */ -moz-box-shadow: 0px 0px 4px 0px #ffffff; /* FF3.5 - 3.6 */ box-shadow: 0px 0px 4px 0px #ffffff; /* Opera 10.5, IE9, FF4+, Chrome 6+, iOS 5 */ Taken from CSS3 Please! Or you should add the border to the shadow image.
{ "redpajama_set_name": "RedPajamaStackExchange" }
6,414
Posts Tagged 'Women's History Month' Get to Know an Artist: Helen Brooks, "Profile" Published March 24, 2020 American Art , Archive , Dallas , works of art 1 Comment Tags: Dallas, Dallas Museum of Art, DMA, Helen Brooks, Texas Art, Texas Artists, Texas History Month, Women's History Month Helen Brooks, Profile, about 1935, charcoal, Dallas Art League Purchase Prize, Seventh Annual Dallas Allied Arts Exhibition, 1935.13 Eighty-five years ago, on March 24, 1935, the Dallas Museum of Fine Arts opened its seventh annual Dallas Allied Arts Exhibition. That same day, an illustrated spread in the Dallas Morning News announced the show's 12 first-prize winners, all but two of which are now in the DMA's collection. Helen Brooks's Profile, the only self-portrait of the bunch, appears at bottom center, adding a touch of humanity to a roster of mostly landscapes and still lifes. Reviewing Dallas's 1934-1935 art season for the Dallas Morning News a few months later, artist, critic, and future Museum Director Jerry Bywaters called Brooks's work "one of the best drawings of the season." Clip from Dallas Morning News, "The Prize Winners," March 24, 1935; clip from Dallas Morning News, January 5, 1936 When a show of self-portraits by 27 local artists opened at the Dallas Museum of Fine Arts in January 1936, Bywaters again had nothing but praise for Brooks's contribution, declaring in the News, "It is hard to imagine a more thoroughly convincing likeness or better drawing than the small work by Helen Brooks." One can imagine Brooks appreciating Bywaters' complimentary words; however, she may have raised an eyebrow at an earlier section of the 1936 article, where Bywaters applauded what he saw as the exhibition artists' lack of vanity: "In most cases," he wrote, the self-portraits on display "attempt to make a good rendering of a person who may be considered detachedly as a personality or a lemon [something substandard, disappointing]." Ouch, Jerry. Bywaters' mixed messaging aside, Profile and the later, three-quarters-view portrait reveal Brooks to be both a talented artist and a woman with a keen sense of style. She skillfully captures distinctive facial features like her sharp cheekbones; bow-shaped, downturned lips; and receding chin. Her glossy black bob with short, blunt bangs and finger waves, as well as her thinly plucked, arched brows, wouldn't look out of place on a 1920s movie starlet—a photograph that accompanied news of Brooks's recent wedding in October 1936 could practically double as a Golden Age Hollywood headshot. #HaircutGoals Clip from Dallas Morning News, "Back from Wedding Trip," October 18, 1936 Melinda Narro is the McDermott Graduate Intern for American Art at the Dallas Museum of Art. Breaking the Mold: Three Women Artists Published March 25, 2019 European Art , Exhibitions , works of art Closed Tags: Adélaïde Labille-Guiard, Dallas Museum of Art, Dallas Museum of Art Collection, DMA, European Art, Eva Gonzales, French Art, Rosa Bonheur, women artists, Women in arts, Women's History Month A recent study surveying the permanent collections of 18 prominent art museums in the United States (including the DMA) found that out of over 10,000 artists, 87% are male. Although history has produced fewer female artists than male, women artists have always existed, and their work is currently available on the art market. In an effort to fix the gender discrepancy in the DMA's collection, we continue to collect work produced by innovative women artists from past to present. In 2017–2018, for example, the DMA's European Art Department acquired three masterworks by some of the most well known—yet still under-served—women artists in the history of French art: Adélaïde Labille Guiard (1749–1803), Eva Gonzalès (1849–1883), and Rosa Bonheur (1822–1899). All three works can be seen in the DMA's current exhibition Women Artists in Europe from the Monarchy to Modernism alongside other works by women artists from the DMA's permanent collection, private collectors, and nearby museums. The show is free and open to the public through June 9, 2019. In honor of Women's History Month, we'd like to introduce you to these newest arrivals! Adélaïde Labille-Guiard Adélaïde Labille-Guiard, Portrait of a Man, c. 1795, oil on canvas, Dallas Museum of Art, gift of Michael L. Rosenberg Foundation, 2017.18 Adélaïde Labille-Guiard was one of four women artists accepted to the French Royal Academy of Painting and Sculpture in the latter half of the 18th century. Women were banned from training as students in the Royal Academy at the time, but were occasionally accepted as members (somewhat akin to modern-day professors) with limited privileges if they could demonstrate exceptional talent. After her acceptance as a portrait painter in 1783, Labille-Guiard exhibited consistently at the Academy's Salon for the next nine years, received prestigious commissions, and was named the official painter of the "Mesdames de France" (King Louis XV's daughters) in 1787. During the French Revolution of 1789–99—a time when many members of the royal family fled France or were guillotined by revolutionaries—Labille-Guiard managed to distance herself from her aristocratic patrons. She adopted the revolutionary cause by exhibiting portraits of political leaders and government officials that featured the sober style associated with republican ideals. Portrait of a Man is from this period of Labille-Guiard's artistic output. The stark background, lack of props or accessories, and the sitter's expressive demeanor emphasize the man's individuality and psychology over material wealth. Eva Gonzalès Eva Gonzalès, Afternoon Tea, c. 1874, oil on canvas, Dallas Museum of Art, The Eugene and Margaret McDermott Art Fund, Inc., 2018.5.McD Like many of the artists in this exhibition, Eva Gonzalès came from an affluent family who could afford the cost of private education. The state-sponsored fine art school in Paris would not accept female students until 1897, so the precociously talented Gonzalès enrolled in Charles Chaplin's private studio for women in 1866. Three years later, she became the only official student of avant-garde artist Edouard Manet. Eventually, she developed her own Impressionistic style characterized by a bright palette, broken brushwork, and the depiction of everyday subjects. Like Berthe Morisot and Mary Cassatt—two of Gonzalès's contemporaries, whose work also appears in this exhibition—Gonzalès was restricted by her sex and elevated social class from depicting most modern urban sites. She instead presented bourgeois femininity and family life, which were cutting-edge subjects in the second half of the 19th century. In this unfinished painting, a woman (likely a nanny) prepares an afternoon meal for the young girl in the foreground. Gonzalès's use of oil paint—traditionally reserved for male artists—elevated her domestic subject matter to the level of high art. Gonzalès's life was tragically cut short in 1883 when she died from complications of childbirth at the age of 34, leaving behind only 124 paintings and pastels. Afternoon Tea is thus a rare example from the oeuvre of a young professional female artist who, though much admired by her contemporaries, remains relatively unknown in the history of art. Rosa Bonheur, Ewe in the Field, second half of the 19th century, oil on canvas, Dallas Museum of Art, gift of Dr. Alessandra Comini in honor of Charlotte Whaley, 2018.44 There are few artists, regardless of gender, who achieved the celebrity status and financial success of Rosa Bonheur. As a young girl, Bonheur was encouraged by her father, an artist, to sketch directly from life. She soon developed a profound talent and passion for the realistic portrayal of animals. This was a highly unconventional subject for women, who, like Labille-Guiard and Gonzalès before her, were encouraged to focus on portraiture, domestic genre scenes, or still lifes. To further develop her talent for rendering the texture and movement of animal fur, Bonheur petitioned the police to allow her to wear pants in order to visit stockyards, horse fairs, and slaughterhouses. These locales were generally off limits to women, or at least difficult to traverse with the billowing skirts women wore in the 19th century. Bonheur eventually achieved great acclaim for her best-known work, The Horse Fair (Metropolitan Museum of Art), which was exhibited at the 1853 Salon. Her notoriety skyrocketed due to her unconventional lifestyle, which included cross-dressing, cigarette smoking, and speaking her mind. Kelsey Martin is the Dedo and Barron Kidd McDermott Graduate Intern for European Art at the DMA. Pivotal Women Artists at the DMA Published March 8, 2018 Collections Closed Tags: Bridget Riley, Dallas Museum of Art, DMA, Raquel Forner, Renee Stout, Women in arts, Women's History Month March is Women's History Month—a designation that was nationally recognized in 1987 due to the hard work of five California-based women who started the National Women's History Project (NWHP) initiative. Each year, there has been an annual theme, with this year's being "Nevertheless She Persisted: Honoring Women Who Fight All Forms of Discrimination Against Women." This month is an opportune time to think about the pivotal women artists and movements that have affected my practice as an art historian and museum educator. Throughout Western art history, women artists have been under- and misrepresented in the art canon. These problematic biases against women of all racial and class backgrounds have been discussed by artists, art historians, and activists alike. Through collectives like the Combahee River Collective, organized by black and queer feminists, and the Guerrilla Girls, who produce on-going campaigns against male-dominated exhibitions (and many more!), women have fought and continue to fight for their existence to be known in spaces that downplay their contributions to the art world. Though there has been great work done by curators, art historians, and museum institutions to revise history and work toward a more equal representation of artists, there is still a copious amount of work to be done. The DMA's collection boasts a number of women artists, such as Julie Mehretu, Yayoi Kusama, Georgia O'Keeffe, Berthe Morisot, and others. Below are a few artists whose work is currently on view in the Museum who made innovative contributions to the art canon and the world at-large. Bridget Riley, Rise 2, 1970, acrylic on canvas, Dallas Museum of Art, Foundation for the Arts Collection, gift of Mr. and Mrs. James H. Clark, 1976.52.FA, © 1970 Bridget Riley Bridget Riley is a foundational artist for Op-Art, a style that transformed geometric shapes into optical illusions in order to create a sense of movement. Riley's name has become synonymous with Op-Art, as her original black-and-white works gained an incredible amount of followers and multiple art prizes in the early to mid-1960s. In the latter part of the decade, Riley explored using colors in her works of art, like Rise 2, to further add elements of instability and illusionistic movement. Riley's works of art inspired and infiltrated 1960s pop culture, most notably the fashion industry with the black-and-white houndstooth checkered print seen in the popular mod aesthetics of the time. Due to Riley's captivating work and popularity, this fashion trend continues to hold weight, as Vogue highlighted Riley in a editorial titled "Why 60s Op-Art Painter Bridget Riley Is the Secret Muse of the Fall 2014 Runway." Although her work influenced the style of the 1960s, Riley did not enjoy the commodification and commercialization of her art. Renee Stout, Fetish #1, 1987, monkey hair, nails, beads, cowrie shells, and coins, Dallas Museum of Art, gift of Roslyn and Brooks Fitch, Gary Houston, Pamela Ice, Sharon and Lazette Jackson, Maureen McKenna, Aaronetta and Joseph Pierce, Matilda and Hugh Robinson, and Rosalyn Story in honor of Virginia Wardlaw, 1989.128, © Renee Stout, Washington, D.C. Renee Stout's move to Washington, DC, in 1985 had a monumental affect on her artistic practice as she sought to understand her identity as a Black-American woman. Her time in DC exposed her to the arts of Western and Central Africa, particularly the Kongo peoples' nkisi nkondi power figures, an example of which is on view in our African galleries. Through these healing power figures, Stout explores the ritualistic and spiritualistic sides of a possible ancestral tie to the African continent, as seen in Fetish #1. Within this object there are many additive and textural components, as there are with nkisi nkondi figures; however, Stout's object lacks facial features, adding a mysterious quality that mirrors her feelings toward her personal ancestral past. Click here to learn more about Stout and this work of art in one of the DMA's Gallery Talks. Raquel Forner, Apocalypsis, 1955, oil on composition board, Dallas Museum of Art, Dallas Art Association Purchase, 1959.47 Although born in Buenos Aires, Raquel Forner spent a majority of her childhood in Spain due to her father's Spanish heritage. During this time, Forner became interested in the arts and began training back in her birth city. While briefly teaching at the National Academy of Fine Arts in Buenos Aires, she exhibited across the city, with her first solo show in 1928. After traveling back and forth between Europe and South America in the 1930s, she started to borrow ideas from the Surrealism movement, such as distorted perspectives and figures; however, Forner was not interested in interpreting her dreams like Surrealist artists—she wanted to apply these distorted forms to real world situations such as the 1936 Spanish Civil War and the 1955 Argentine social uprisings. The latter event influenced her Apocalypse painting, where she created abstract land forms and overlapping movement of figures to highlight the confusion and negative aspects human conflict creates. This painting was exhibited in the landmark 1959 exhibition South American Art Today at the Dallas Museum of Fine Arts, the predecessor of the DMA. Fifteen works of art from the exhibition were later purchased by the DMA, and nine of those works can currently be seen in the Latin American Gallery, including Forner's Apocalypse. Yohanna Tesfai is the McDermott Graduate Intern for Gallery and Community Teaching at the DMA. The Dallas Museum of Art's Founding Women Published March 12, 2012 Archive , Dallas , DFW Closed Tags: Dallas Art Association, Dallas Carnegie Library Board of Trustees, Dallas Museum of Art, Women's History Month In honor of Women's History Month, we would like to introduce you to the founder and first four women presidents of the Dallas Art Association from the first decade of the 20th century. The Dallas Art Association (DAA) was founded in 1903 to offer art interest and education through exhibitions and lectures; to purchase works of art on a regular basis and form a permanent collection; to sponsor the work of local artists; to solicit support of the arts from individuals and businesses; and to honor citizens who support the arts. The DAA, after a number of name changes, became the Dallas Museum of Art. Mrs. May Dickson Exall is considered to be the founder of the Dallas Art Association. In January 1903, Mrs. Exall, then president of the Dallas Carnegie Library Board of Trustees, invited all those interested to meet in the Art Room of the library to form a permanent art organization. About 80 people attended and the new organization was named the Dallas Art Association, and a 21-member board of trustee was established. Mrs. Grace Leake Dexter was the first president of the Dallas Art Assocation for 1903, and was a board member from 1903 to 1906. Mrs. Dexter was an amateur painter and a civic leader. From the Collection of the Texas/Dallas History and Archives Division, Dallas Public Library; Image #PA92-1/22 Mrs. Lulie Huey Lane was President in 1907. Mrs. Lane was a gifted musician with an unusually fine voice and also held leadership roles in a variety of other civic organizations. Mrs. Robbie Buckner Westerfield was DAA president in 1908. She was also a leader in religious and women's club work in Dallas. 1923.2 "Portrait of Mrs. George K. Meyer" by Francis Luis Mora. Dallas Museum of Art, Dallas Art Association Purchase Mrs. Sallie Griffis Meyer was president of the DAA from 1909 to 1926. Mrs. Meyer was one of Dallas's earliest and most prominent arts patrons. In addition to her long tenure as DAA president, she was also superintendent in charge of art for the State Fair of Texas. Discover more about the DMA's history on the Museum's web site. Hillary Bober is the Digital Archivist at the Dallas Museum of Art.
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
410
Helmbloem (Corydalis) is een geslacht van kruidachtige, eenjarige en overblijvende kruiden uit de papaverfamilie (Papaveraceae). Een aantal soorten van Corydalis worden beschouwd als synoniemen van soorten van Pseudofumaria (Muurhelmbloem). Het geslacht komt van nature voor in de gematigde streken van het noordelijk halfrond en ook in Zuid-Afrika. Het geslacht is nauw verwant aan het geslacht Fumaria; sommige botanici combineren de twee geslachten in één geslacht. De meeste soorten voelen zich thuis op schaduwrijke plekken. Corydalis soorten worden door de larven van verschillende vlinder-soorten gebruikt als waardplant, onder meer door de geoogde bandspanner (Xanthorhoe montanata), Parnassius ariadne, Parnassius imperator, zwarte apollovlinder (Parnassius mnemosyne), Parnassius stubbendorfi en Parnassius tenedius. enkele soorten Corydalis afghanica Corydalis aitchisonii Corydalis alpestris Corydalis angustifolia Corydalis aqua-gelidae Corydalis arctica Corydalis aurea Corydalis batesii Corydalis bracteata Corydalis buschii Corydalis caseana Corydalis cashmeriana Corydalis cava (Holwortel) Corydalis chaerophylla Corydalis cheilanthifolia (Varenhelmbloem) Corydalis chionophylla Corydalis clavibracteata Corydalis claviculata (Rankende helmbloem) Corydalis conorhiza Corydalis cornuta Corydalis darwasica Corydalis diphylla Corydalis elata Corydalis emmanuelii Corydalis flavula Corydalis flexuosa Corydalis glaucescens Corydalis gortschakovii Corydalis gotlandica Corydalis integra Corydalis intermedia Corydalis kushiroensis Corydalis latiflora Corydalis lineariloba Corydalis lutea (Gele helmbloem) Corydalis lydica Corydalis macrocentra Corydalis marschalliana Corydalis nariniana Corydalis nobilis Corydalis ochotensis Corydalis ochroleuca (Geelwitte helmbloem) Corydalis ophiocarpa Corydalis oppositifolia Corydalis pallida Corydalis parnassica Corydalis persica Corydalis pinnatibracteata Corydalis popovii Corydalis pumila Corydalis rosea Corydalis rupestris Corydalis rutifolia Corydalis saxicola Corydalis scouleri Corydalis seisumsiana Corydalis semenovii Corydalis sempervirens Corydalis shanginii Corydalis sibirica Corydalis solida (Vingerhelmbloem) Corydalis stenantha Corydalis tomentella Corydalis trilobipetala Corydalis vaginans Corydalis verticillaris Corydalis vesicaria Corydalis wendelboi Corydalis wilsonii Corydalis zeaensis Papaverfamilie
{ "redpajama_set_name": "RedPajamaWikipedia" }
5,234
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Enum2862688501.h" #include "AssemblyU2DCSharp_UnityStandardAssets_CrossPlatform430263918.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager/ActiveInputMethod struct ActiveInputMethod_t430263918 { public: // System.Int32 UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager/ActiveInputMethod::value__ int32_t ___value___1; public: inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(ActiveInputMethod_t430263918, ___value___1)); } inline int32_t get_value___1() const { return ___value___1; } inline int32_t* get_address_of_value___1() { return &___value___1; } inline void set_value___1(int32_t value) { ___value___1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
{ "redpajama_set_name": "RedPajamaGithub" }
4,264
using System; using System.Diagnostics; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Xml; using SIL.IO; using SIL.Xml; using TidyManaged; namespace Bloom { public static class XmlHtmlConverter { private static readonly Regex _selfClosingRegex = new Regex(@"<([ubi]|em|strong|span)(\s+[^><]+\s*)/>"); private static readonly Regex _emptySelfClosingElementsToRemoveRegex = new Regex(@"<([ubi]|em|strong|span)\s*/>"); private static readonly Regex _emptyElementsWithAttributesRegex = new Regex(@"<([ubi]|em|strong|span)(\s+[^><]+\s*)>(\s*)</\1>"); private static readonly Regex _emptyElementsToPreserveRegex = new Regex(@"<(p)\s*>(\s*)</\1>"); private static readonly Regex _selfClosingElementsToPreserveRegex = new Regex(@"<(p)(\s*[^><]*\s*)/>"); public static XmlDocument GetXmlDomFromHtmlFile(string path, bool includeXmlDeclaration = false) { return GetXmlDomFromHtml(RobustFile.ReadAllText(path), includeXmlDeclaration); } /// <summary></summary> /// <param name="content"></param> /// <param name="includeXmlDeclaration"></param> /// <exception>Throws if there are parsing errors</exception> /// <returns></returns> public static XmlDocument GetXmlDomFromHtml(string content, bool includeXmlDeclaration = false) { var dom = new XmlDocument(); content = AddFillerToKeepTidyFromRemovingEmptyElements(content); //in BL-2250, we found that in previous versions, this method would turn, for example, "<u> </u>" REMOVEWHITESPACE. //That is fixed now, but this is needed to give to clean up existing books. content = content.Replace(@"REMOVEWHITESPACE", ""); // It also likes to insert newlines before <b>, <u>, and <i>, and convert any existing whitespace // there to a space. content = new Regex(@"<([ubi]|em|strong)>").Replace(content, "REMOVEWHITESPACE<$1>"); // fix for <br></br> tag doubling content = content.Replace("<br></br>", "<br />"); // fix for > and similar in <style> element protected by CDATA. // At present we only need to account for this occurring once. // See Browser.SaveCustomizedCssRules. var startOfCdata = content.IndexOf(Browser.CdataPrefix, StringComparison.InvariantCulture); const string restoreCdataHere = "/****RestoreCDATAHere*****/"; var endOfCdata = content.IndexOf(Browser.CdataSuffix, StringComparison.InvariantCulture); var savedCdata = ""; if (startOfCdata >= 0 && endOfCdata >= startOfCdata) { endOfCdata += Browser.CdataSuffix.Length; savedCdata = content.Substring(startOfCdata, endOfCdata - startOfCdata); content = content.Substring(0, startOfCdata) + restoreCdataHere + content.Substring(endOfCdata, content.Length - endOfCdata); } //using (var temp = new TempFile()) var temp = new TempFile(); { RobustFile.WriteAllText(temp.Path, content, Encoding.UTF8); using (var tidy = RobustIO.DocumentFromFile(temp.Path)) { tidy.ShowWarnings = false; tidy.Quiet = true; tidy.WrapAt = 0; // prevents textarea wrapping. tidy.AddTidyMetaElement = false; tidy.OutputXml = true; tidy.CharacterEncoding = EncodingType.Utf8; tidy.InputCharacterEncoding = EncodingType.Utf8; tidy.OutputCharacterEncoding = EncodingType.Utf8; tidy.DocType = DocTypeMode.Omit; //when it supports html5, then we will let it out it //maybe try this? tidy.Markup = true; tidy.AddXmlDeclaration = includeXmlDeclaration; //NB: this does not prevent tidy from deleting <span data-libray='somethingImportant'></span> tidy.MergeSpans = AutoBool.No; tidy.DropEmptyParagraphs = false; tidy.MergeDivs = AutoBool.No; var errors = tidy.CleanAndRepair(); if (!string.IsNullOrEmpty(errors)) { throw new ApplicationException(errors); } var newContents = tidy.Save(); try { newContents = RemoveFillerInEmptyElements(newContents); newContents = newContents.Replace("&nbsp;", "&#160;"); //REVIEW: 1) are there others? &amp; and such are fine. 2) shoul we to convert back to &nbsp; on save? // The regex here is mainly for the \s as a convenient way to remove whatever whitespace TIDY // has inserted. It's a fringe benefit that we can use the[bi] to deal with both elements in one replace. newContents = Regex.Replace(newContents, @"REMOVEWHITESPACE\s*<([biu]|em|strong)>", "<$1>"); //In BL2250, we still had REMOVEWHITESPACE sticking around sometimes. The way we reproduced it was //with <u> </u>. That is, we started with //"REMOVEWHITESPACE <u> </u>", then libtidy (properly) removed the <u></u>, leaving us with only //"REMOVEWHITESPACE". newContents = Regex.Replace(newContents, @"REMOVEWHITESPACE", ""); // remove blank lines at the end of style blocks newContents = Regex.Replace(newContents, @"\s+<\/style>", "</style>"); // remove <br> elements immediately preceding </p> close tag (BL-2557) // These are apparently inserted by ckeditor as far as we can tell. They don't show up on // fields that have never had a ckeditor activated, and always show up on fields that have // received focus and activated an inline ckeditor. The ideal ckeditor use case appears // to be for data entry as part of a web page that get stored separately, with the data // obtained something like the following in javascript: // ckedit.on('blur', function(evt) { // var editor = evt['editor']; // var data = editor.getData(); // <at this point, the data looks okay, with any <br> element before the </p> tag.> // <store the data somewhere: the following lines have no effect, and may be silly.> // var div = mapCkeditDiv[editor.id]; // div.innerHTML = data; // }); // Examining the initial value of div.innerHTML shows the unwanted <br> element, but it is // not in the data returned by editor.getData(). Since assigning to div.innerHTML doesn't // affect what gets written to the file, this hack was implemented instead. newContents = Regex.Replace(newContents, @"(<br></br>|<br ?/>)[\r\n]*</p>", "</p>"); newContents = newContents.Replace(restoreCdataHere, savedCdata); // Don't let spaces between <strong>, <em>, or <u> elements be removed. (BL-2484) dom.PreserveWhitespace = true; dom.LoadXml(newContents); } catch (Exception e) { var exceptionWithHtmlContents = new Exception(string.Format("{0}{2}{2}{1}", e.Message, newContents, Environment.NewLine)); throw exceptionWithHtmlContents; } } } try { //It's a mystery but http://jira.palaso.org/issues/browse/BL-46 was reported by several people on Win XP, even though a look at html tidy dispose indicates that it does dispose (and thus close) the stream. // Therefore, I'm moving the dispose to an explict call so that I can catch the error and ignore it, leaving an extra file in Temp. temp.Dispose(); //enhance... could make a version of this which collects up any failed deletes and re-attempts them with each call to this } catch (Exception error) { //swallow Debug.Fail("Repro of http://jira.palaso.org/issues/browse/BL-46 "); } //this is a hack... each time we write the content, we add a new <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> //so for now, we remove it when we read it in. It'll get added again when we write it out RemoveAllContentTypesMetas(dom); return dom; } /// <summary> /// Tidy is over-zealous. This is a work-around. After running Tidy, then call RemoveFillerInEmptyElements() on the same text /// </summary> /// <returns></returns> private static string AddFillerToKeepTidyFromRemovingEmptyElements(string content) { // This handles empty elements in the form of XML contractions like <i some-important-attributes /> content = ConvertSelfClosingTags(content, "REMOVEME"); // hack. Tidy deletes <span data-libray='somethingImportant'></span> // and also (sometimes...apparently only the first child in a parent) <i some-important-attributes></i>. // $1 is the tag name. // $2 is the tag attributes. // $3 is the blank space between the opening and closing tags, if any. content = _emptyElementsWithAttributesRegex.Replace(content, "<$1$2>REMOVEME$3</$1>"); // Tidy deletes <p></p>, though that's obviously not something to delete! content = _emptyElementsToPreserveRegex.Replace(content, "<$1$2>REMOVEME</$1>"); // Prevent Tidy from deleting <p/> too content = _selfClosingElementsToPreserveRegex.Replace(content, "<$1$2>REMOVEME</$1>"); return content; } /// <summary> /// This is to be run after running tidy /// </summary> private static string RemoveFillerInEmptyElements(string contents) { return contents.Replace("REMOVEME", "").Replace("\0", ""); } private static string ConvertSelfClosingTags(string html, string innerHtml = "") { html = RemoveEmptySelfClosingTags(html); // $1 is the tag name. // $2 is the tag attributes. return _selfClosingRegex.Replace(html, "<$1$2>" + innerHtml + "</$1>"); } public static string RemoveEmptySelfClosingTags(string html) { return _emptySelfClosingElementsToRemoveRegex.Replace(html, ""); } /// <summary> /// Beware... htmltidy doesn't consider such things as a second <body> element to warrant any more than a "warning", so this won't throw! /// </summary> /// <param name="content"></param> public static void ThrowIfHtmlHasErrors(string content) { using (var tidy = Document.FromString(content)) { tidy.ShowWarnings = false; tidy.Quiet = true; tidy.AddTidyMetaElement = false; tidy.OutputXml = true; tidy.DocType = DocTypeMode.Omit; //when it supports html5, then we will let it out it using (var log = new MemoryStream()) { tidy.CleanAndRepair(log); string errors = ASCIIEncoding.ASCII.GetString(log.ToArray()); if (!string.IsNullOrEmpty(errors)) { throw new ApplicationException(errors); } } } } /// <summary> /// If an element has empty contents, like <textarea></textarea>, browsers will sometimes drop the end tag, so that now, when we read it back into xml, /// anything following the <textarea> will be interpreted as part of the <textarea>! This method makes sure such tags are never totally empty. /// </summary> /// <param name="dom"></param> public static void MakeXmlishTagsSafeForInterpretationAsHtml(XmlDocument dom) { foreach (XmlElement node in dom.SafeSelectNodes("//textarea")) { if (!node.HasChildNodes) { node.AppendChild(node.OwnerDocument.CreateTextNode("")); } } foreach (XmlElement node in dom.SafeSelectNodes("//div")) { if (!node.HasChildNodes) { node.AppendChild(node.OwnerDocument.CreateTextNode("")); } } foreach (XmlElement node in dom.SafeSelectNodes("//p")) //without this, an empty paragraph suddenly takes over the subsequent elements. Browser sees <p></p> and thinks... let's just make it <p>, shall we? Stupid optional-closing language, html is.... { if (!node.HasChildNodes) { node.AppendChild(node.OwnerDocument.CreateTextNode("")); } } foreach (XmlElement node in dom.SafeSelectNodes("//span")) { if (!node.HasChildNodes) { node.AppendChild(node.OwnerDocument.CreateTextNode("")); } } foreach (XmlElement node in dom.SafeSelectNodes("//script")) { if (string.IsNullOrEmpty(node.InnerText) && node.ChildNodes.Count == 0) { node.InnerText = " "; } } foreach (XmlElement node in dom.SafeSelectNodes("//style")) { if (string.IsNullOrEmpty(node.InnerText) && node.ChildNodes.Count == 0) { node.InnerText = " "; } } } /// <summary> /// Convert the DOM (which is expected to be XHTML5) to HTML5 /// </summary> public static string SaveDOMAsHtml5(XmlDocument dom, string targetPath) { // First we write the DOM out to string var settings = new XmlWriterSettings {Indent = true, CheckCharacters = true, OmitXmlDeclaration = true}; var xmlStringBuilder = new StringBuilder(); using (var writer = XmlWriter.Create(xmlStringBuilder, settings)) { dom.WriteContentTo(writer); writer.Close(); } // HTML Tidy will mess that xml up, so we have this work around to make it "safe from libtidy" var xml = xmlStringBuilder.ToString(); xml = AddFillerToKeepTidyFromRemovingEmptyElements(xml); // Now re-write as html, indented nicely string html; using (var tidy = Document.FromString(xml)) { tidy.ShowWarnings = false; tidy.Quiet = true; tidy.AddTidyMetaElement = false; tidy.OutputXml = false; tidy.OutputHtml = true; tidy.DocType = DocTypeMode.Html5; tidy.MergeDivs = AutoBool.No; tidy.MergeSpans = AutoBool.No; tidy.PreserveEntities = true; tidy.JoinStyles = false; tidy.IndentBlockElements = AutoBool.Auto; //instructions say avoid 'yes' tidy.WrapAt = 9999; tidy.IndentSpaces = 4; tidy.CharacterEncoding = EncodingType.Utf8; tidy.CleanAndRepair(); using (var stream = new MemoryStream()) { tidy.Save(stream); stream.Flush(); stream.Seek(0L, SeekOrigin.Begin); using (var sr = new StreamReader(stream, Encoding.UTF8)) html = sr.ReadToEnd(); } } // Now revert the stuff we did to make it "safe from libtidy" html = RemoveFillerInEmptyElements(html); RobustFile.WriteAllText(targetPath, html, Encoding.UTF8); return targetPath; } public static void RemoveAllContentTypesMetas(XmlDocument dom) { foreach (XmlElement n in dom.SafeSelectNodes("//head/meta[@http-equiv='Content-Type']")) { n.ParentNode.RemoveChild(n); } } } }
{ "redpajama_set_name": "RedPajamaGithub" }
9,528
Even after Obama, America's healthcare system is still broken, and it'll soon bankrupt us all. The solution: radical simplification. Now, leading healthcare expert and entrepreneur Dr. Doug Perednia reveals the system's shocking, unnecessary inefficiencies--and outlines a simple, logical, complete solution that offers greater security, enhances competition, and will save trillions. Overhauling America's Healthcare Machine: Stop the Bleeding and Save Trillions ePub (Adobe DRM) can be read on any device that can open ePub (Adobe DRM) files.
{ "redpajama_set_name": "RedPajamaC4" }
1,758
package org.qxp.ctrl.util; public class SRDBConstant { public static String INT = "integer"; public static String DOUBLE = "numeric"; public static String STRING = "character varying"; public static String DATE = "timestamp without time zone"; public static String LOWERCASES_DATE = "date"; public static String SMALL_INT = "smallint"; public static String TEXT = "text"; public static String BIG_INT = "bigint"; public static String WITH_DATE = "timestamp with time zone"; }
{ "redpajama_set_name": "RedPajamaGithub" }
6,887
Q: Making $66$ with $1,1,1,1,1$ How can one make $66$ with only $1,1,1,1,1$? You cannot combine these two numbers to make a new number, such as this: $66=11 \times (1+1+1)!$. This was inspired a game of dice that I used to play, where you were given $5$ numbers between $1$ and $6$ to make a two digit number between $11$ and $66$. My mother had once told me that no matter which numbers were given, you could use operations such as $\times$, $\div$,$+$,$-$, $!$, $x^y$, $\sqrt [ x ]{ y }$, $\sqrt { y }$, and %, ‰ to make a equation. So naturally I tried what seemed to most difficult to make: making $66$ with $1,1,1,1,1$. However, I was unable to find a solution. I initially thought that this would be impossible, but considering that it is possible to make $97$ from $0,0,0,0$ I suspect that there might be a way. Is there a possibly easy solution to this problem? (Note: Making $97$ with $0,0,0,0$, can be seen here, on the third comment to David Bevan`s Answer, by David Bevan.)
{ "redpajama_set_name": "RedPajamaStackExchange" }
518
module.exports = require('./lib/cashbox')({ 'memcached': require('./lib/stores/memcached'), 'memory': require('./lib/stores/memory'), 'redis': require('./lib/stores/redis') });
{ "redpajama_set_name": "RedPajamaGithub" }
1,746
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title><?=$titulo;?></title> <link rel="shortcut icon" href="<?=$this->config->base_url();?>fronted/img/favicon.ico" type="image/x-icon" /> <link rel="stylesheet" href="<?=$this->config->base_url();?>fronted/css/bootstrap-3/css/bootstrap.css"> <link rel="stylesheet" href="<?=$this->config->base_url();?>fronted/css/bootstrap-3/css/bootstrap.min.css"> <link rel="stylesheet" href="<?=$this->config->base_url();?>fronted/js/jquery-ui/css/smoothness/jquery-ui-1.9.2.custom.min.css"> <link rel="stylesheet" href="<?=$this->config->base_url();?>fronted/css/main.css"> <link rel="stylesheet" href="<?=$this->config->base_url();?>fronted/js/DataTables-1.10.4/media/css/jquery.dataTables.min.css"> <script src="<?=$this->config->base_url();?>fronted/js/jquery-2.1.1.min.js"></script> <script src="<?=$this->config->base_url();?>fronted/js/jquery-ui/js/jquery-ui.min.js"></script> <script src="<?=$this->config->base_url();?>fronted/css/bootstrap-3/js/bootstrap.js"></script> <script src="<?=$this->config->base_url();?>fronted/js/DataTables-1.10.4/media/js/jquery.dataTables.js"></script> <script src="<?=$this->config->base_url();?>fronted/js/jquery-count/jquery.jqEasyCharCounter.min.js"></script> </head>
{ "redpajama_set_name": "RedPajamaGithub" }
8,168
using System.Threading.Tasks; namespace Stocks.Interfaces { public interface IStockGrain : Orleans.IGrainWithStringKey { Task<string> GetPrice(); } }
{ "redpajama_set_name": "RedPajamaGithub" }
6,567
Iten Funeral Home Send Flowers for Douglas "Doug" Plant a Tree for Douglas "Doug" Douglas "Doug" DeWayne Sherman February 16, 1937 ~ January 12, 2023 (age 85) 85 Years Old Read more about the life story of Douglas "Doug" and share your memory. Doug Sherman of Osakis, passed away peacefully with his family by his side on Thursday, January 12, 2023 at the Alomere Hospital. Doug was 85 years old. A memorial service will take place on Saturday, January 21, 2023, at the Osakis Lutheran Church at 11:00 AM. Visitation will be one hour prior. Burial will take place later that day at the Pleasant Mound Cemetery in rural Clotho/Osakis. In lieu of flowers, memorials are preferred to the family. Doug's service will be viewable via zoom. See links below obituary. Doug was born on February 16th, 1937 in Osakis, the son of Leonard and Margaret (Bock) Sherman. Doug attended country school through 8 th grade in Leslie Township at Oak Hill School. He then attended Osakis Public School and graduated in 1955. In 1960 he joined the Army and served in Germany at the Berlin Wall until he was honorably discharged in 1962. When Doug came home from the Service, he helped his father for some time with custom Hay baling. In 1964 he started courting the love of his life Pamela Janine Anderson. On February 12, 1966 they were united in Marriage at the Osakis Lutheran Church. In June of 1966, they decided it was time to buy their first home together. They purchased an old country schoolhouse (where Pam went to country school) and started the process of making it into their lifetime home. Doug did much of the remodeling himself with the help of many friends. During this time, he worked at Withers Manufacturing in Osakis and then for many years at the Osakis Silo Company. In the early 70's Doug and Pam decided it was time to grow their family, they became fosters parent in Todd County and loved and cared for over 100 children over 25 years. On November 17th, 1977- Unbeknown to them their daughter was born. On February 15, 978 Doug received the BEST Birthday gift ever- they adopted a beautiful baby girl, Stacy Janine Sherman. Stacy was the missing piece in their life and Doug loved her with all his heart. They enjoyed bringing Stacy to their friend and family's homes to show her off. Throughout his 85 years of life, Doug became known as a man of many trades and talents including fishing, hunting, snowmobiling, camping, and a love for tractors, especially fond of those orange Allis Chalmers. He enjoyed life and spent much of his time tinkering with any project that he could get his hands on. He was a man of many traits, always welcoming to others, caring, patient and above all, a role model, making him and Pam the perfect couple to help care for children. Doug was an avid cribbage player and spent many hours enjoying the game with family and friends. On March 21 st 1996- Doug and Pam welcomed their 1 st granddaughter Hailey-Rose Janine Sherman. On February 17 th 1998- Doug received a late birthday gift, his 2 nd grandchild Johnathan Douglas Betsinger. In September of 1998- Doug proudly gave his daughter Stacy away in Marriage to his favorite son-in-law John Betsinger. After Doug retired, he did daycare for the grandkids 5 days a week and loved it dearly. After 8 years John and Stacy decided to add a couple more children to Doug's daycare plan and on December 22, 2005- Logan Robert Lee Betsinger was born, and shortly after on March 23 rd 2008- Carter Christopher was born. The kids kept Doug busy and will always be known to them as their "Bompa" Doug and Pam spent many summers taking their grandchildren on Vacation and enjoyed showing them new places. His caring heart, smile, and frequently a silly face, will be greatly missed by all who knew him. Doug is survived by his loving wife, Pam; daughter, Stacy (husband John Betsinger); grandchildren, Hailey Rose, Johnathan (fiancé Mikayla Carver), Logan and Carter; Sister Linda Stowe; many nieces and nephews and many past foster children; Maria (Roy) Gilman, Debra (Bill) Gray Linda (Pat Jones), Jeni (Byron Jones) He is preceded in death by his parents; sister, Betty Sherman; brother, Ronald; several aunts and uncles and mother in law Naomi Anderson. Heidi Iten is inviting you to a scheduled Zoom meeting. Topic: Doug Sherman Memorial Service Time: Jan 21, 2023 11:00 AM Central Time (US and Canada) https://us06web.zoom.us/j/85715925429?pwd=enpObzVTcXhJUGtQOWJGNmZUVEJRQT09 +16465588656,,85715925429#,,,,*937164# US (New York) +1 720 707 2699 US (Denver) Find your local number: https://us06web.zoom.us/u/kmxwDhujk To send flowers to the family or plant a tree in memory of Douglas "Doug" DeWayne Sherman, please visit our floral store. Osakis Lutheran Church 310 First Avenue East Osakis, MN 56360 Pleasant Mound Cemetery - Clotho Rural Clotho Clotho, MN 56347 Douglas "Doug" Sherman February 16, 1937-January 12, 2023
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
2,344
package org.waveprotocol.wave.model.supplement; import org.waveprotocol.wave.model.adt.ObservableMonotonicMap; import org.waveprotocol.wave.model.adt.ObservableMonotonicValue; import org.waveprotocol.wave.model.adt.docbased.DocumentBasedMonotonicMap; import org.waveprotocol.wave.model.adt.docbased.DocumentBasedMonotonicValue; import org.waveprotocol.wave.model.document.util.DocumentEventRouter; import org.waveprotocol.wave.model.id.WaveletId; import org.waveprotocol.wave.model.supplement.ObservablePrimitiveSupplement.Listener; import org.waveprotocol.wave.model.util.Serializer; /** * Implements the per-wavelet read state, using the * {@link DocumentBasedMonotonicValue} embedding for the participants and * wavelet-override last-read versions, and the * {@link DocumentBasedMonotonicMap} embedding for per-blip last-read versions. * * @param <E> element type of the document implementation */ class DocumentBasedWaveletReadState<E> implements WaveletReadState { private final ObservableMonotonicMap<String, Integer> blips; private final ObservableMonotonicValue<Integer> participants; private final ObservableMonotonicValue<Integer> tags; private final ObservableMonotonicValue<Integer> wavelet; private final DocumentEventRouter<? super E, E, ?> router; private final E container; DocumentBasedWaveletReadState(DocumentEventRouter<? super E, E, ?> router, E container) { this.router = router; this.container = container; blips = DocumentBasedMonotonicMap.create(router, container, Serializer.STRING, Serializer.INTEGER, WaveletBasedSupplement.BLIP_READ_TAG, WaveletBasedSupplement.ID_ATTR, WaveletBasedSupplement.VERSION_ATTR); participants = DocumentBasedMonotonicValue.create(router, container, Serializer.INTEGER, WaveletBasedSupplement.PARTICIPANTS_READ_TAG, WaveletBasedSupplement.VERSION_ATTR); tags = DocumentBasedMonotonicValue.create(router, container, Serializer.INTEGER, WaveletBasedSupplement.TAGS_READ_TAG, WaveletBasedSupplement.VERSION_ATTR); wavelet = DocumentBasedMonotonicValue.create(router, container, Serializer.INTEGER, WaveletBasedSupplement.WAVELET_READ_TAG, WaveletBasedSupplement.VERSION_ATTR); } /** * Creates * * @param router router * @param container element in which the read state is contained * @param id wavelet id being tracked * @param listener listener for read-state changes * @return a new read-state tracker. */ public static <E> DocumentBasedWaveletReadState<E> create( DocumentEventRouter<? super E, E, ?> router, E container, WaveletId id, Listener listener) { DocumentBasedWaveletReadState<E> x = new DocumentBasedWaveletReadState<E>(router, container); x.installListeners(id, listener); return x; } /** * Injects listeners into the underlying ADTs that translate their events * into primitive-supplement events. * * @param wid * @param listener */ private void installListeners(final WaveletId wid, final Listener listener) { blips.addListener(new ObservableMonotonicMap.Listener<String, Integer>() { @Override public void onEntrySet(String key, Integer oldValue, Integer newValue) { listener.onLastReadBlipVersionChanged(wid, key, valueOf(oldValue), valueOf(newValue)); } }); participants.addListener(new ObservableMonotonicValue.Listener<Integer>() { @Override public void onSet(Integer oldValue, Integer newValue) { listener.onLastReadParticipantsVersionChanged(wid, valueOf(oldValue), valueOf(newValue)); } }); tags.addListener(new ObservableMonotonicValue.Listener<Integer>() { @Override public void onSet(Integer oldValue, Integer newValue) { listener.onLastReadTagsVersionChanged(wid, valueOf(oldValue), valueOf(newValue)); } }); wavelet.addListener(new ObservableMonotonicValue.Listener<Integer>() { @Override public void onSet(Integer oldValue, Integer newValue) { listener.onLastReadWaveletVersionChanged(wid, valueOf(oldValue), valueOf(newValue)); } }); } private static int valueOf(Integer version) { return version != null ? version : PrimitiveSupplement.NO_VERSION; } @Override public void setBlipLastReadVersion(String blipId, int version) { blips.put(blipId, version); } @Override public int getBlipLastReadVersion(String id) { return valueOf(blips.get(id)); } @Override public void setParticipantsLastReadVersion(int version) { participants.set(version); } @Override public int getParticipantsLastReadVersion() { return valueOf(participants.get()); } @Override public int getTagsLastReadVersion() { return valueOf(tags.get()); } @Override public void setTagsLastReadVersion(int version) { tags.set(version); } @Override public void setWaveletLastReadVersion(int version) { wavelet.set(version); } @Override public int getWaveletLastReadVersion() { return valueOf(wavelet.get()); } @Override public Iterable<String> getReadBlips() { return blips.keySet(); } @Override public void remove() { router.getDocument().deleteNode(container); } @Override public void clearBlipReadState(String blipId) { blips.remove(blipId); } }
{ "redpajama_set_name": "RedPajamaGithub" }
8,789
The Ballad of Bantry Bay: How This Irish Oil Terminal Took Centre Stage Amid Covid-19 July 20, 2020 [Offshore Technology] – The recent arrival of the first US oil at Zenith's Bantry Bay terminal cemented the reputation of the facility on the Irish coast as a strategic location serving key trade routes. We talk to Zenith CCO Jay Reynolds about the oil storage shortage, Covid-19, and the rise of West Texas Intermediate. Bantry Bay, on Ireland's ruggedly beautiful south-west coast, has borne witness to its fair share of conflict and tragedy over the past two centuries. Irish revolutionary Wolfe Tone led an aborted attempt at a rebellion there in December 1796; the square in Bantry is still named after him. More recently, in 1979, the oil tanker Betelgeuse, owned by Total S.A., exploded in Bantry Bay, at the offshore jetty for the oil terminal at Whiddy Island. The explosion and resulting fire claimed the lives of 50 people. Bantry Bay's relationship with the oil and gas industry stretches back to the opening of the Whiddy terminal in May 1969. Half a century on, the deepwater facility – with a capacity of 1,400,000 cbm (8.8 million barrels) and a deep 30m draft – remains a critical commercial link in north-west Europe for crude and refined products, and an important part of Ireland's strategic petroleum reserve. "Bantry Bay provides logistical advantages and optionality to distribute crude because the terminal is able to receive very large crude carriers and is close to all of the major European refining centres in the UK, ARA, Germany, and the Mediterranean," states Jay Reynolds, chief commercial officer at Zenith Energy Management LLC, which acquired the terminal from Phillips 66 in February 2015. "The terminal was constructed in 1968 for the express purpose of importing large cargoes of foreign (AG) crude and has a long history of supporting European refining. It has almost two million barrels of tankage in crude service, plus we have the ability to swing tanks between crude and products." Crude awakening: US oil supplies and the contango market As a key distribution point for foreign and local oil into the European refining system, Bantry Bay is equipped to handle multiple types of crude, including both North Sea and West African grades. In April, four tankers – two of which were originally bound for the Netherlands and the UK – carrying a total of 2.4 million barrels docked in Bantry Bay, the first time US oil had been delivered to the terminal. According to Energy Information Administration data, US crude exports to Ireland peaked at 2.4 million in January and the trend of diverting supplies to lower-profile locations is likely to continue, with global demand for oil having plummeted in the wake of the Covid-19 crisis and crude storage at a premium. "While Bantry Bay recently received its first US crude cargo, we see this as a natural extension of US crude oil in the international trade flow and being driven by market fundamentals," says Reynolds. "It is a logical destination for US crude, given its capabilities and offerings including deep draft, large tank sizes, mixing capabilities, laboratory testing, and proximity to all the major European refining centres, making it exceptionally well-suited to store and distribute crude oil and products. It is also one of only two independent terminals in western Europe that can handle ultra-large crude vessels." The curnent contango market, where the price of oil in the spot market trades below the price for future delivery, means investors with access to offshore storage facilities are willing to pay tanker owners well to receive oil at a later date, locking in profits for themselves and their shareholders. Go west: why WTI is displacing other forms of crude Bantry Bay's popularity also speaks to the rise of West Texas Intermediate (WTI), which is gaining traction in Europe compared with Brent crude. According to Reynolds, when it comes to the WTI trend, Zenith saw it early and saw it whole, investing in Bantry Bay to serve this burgeoning market. "When we acquired the terminal in 2015, there had been discussions about the US lifting its crude export restrictions; however, it was not a certainty," says Reynolds. "However, we had conviction that Bantry Bay would attract strong interest in the crude trade and since acquiring the terminal we have consistently had crude tanks leased to customers. "WTI and other US crude grades are steadily displacing other crude grades in European refining and because of this, WTI is naturally seeking additional distribution points in order to satisfy demand. "Prior to the coronavirus pandemic, the US was exporting over three million barrels a day (b/d), with refineries in north-western Europe as the top importer of US crude at more than 300,000 b/d. "As WTI and other US crudes gain further acceptance by European refiners, we expect growth in export volumes to Europe through the Covid-19 recovery phase and beyond. This should result in an increased need for segregated storage for these grades and these flows fit well into Bantry Bay. "At Zenith, we believe the facility will continue to receive US crude." A full tank: demand for oil storage set to continue At the time of writing, the shortage of oil storage facilities remains a significant issue for the global industry, as oil prices slipped again thanks to record high US crude inventories and concerns among investors and analysts that a resurgence in Covid-19 cases could curtail a revival in fuel demand. On 25 June, WTI crude futures dropped 57 cents to $37.43 per barrel, having dropped $2.36 on the previous day. Brent crude futures fell 43 cents to $39.88 per barrel, after falling $2.32 the day before. With a capacity of more than 2.5 million cbm, Zenith Europe is well-positioned to cater for crude surpluses. Since 2015, the company has invested more than €120m in upgrading its terminals' tanks, piping, and marine and truck-loading infrastructure. Around half of its storage is in Amsterdam, the ARA's key hub for gasoline and gasoil blending and trading, with the balance located at Bantry Bay. "As a growth-orientated company, we are always evaluating acquisition opportunities," Reynolds says. "Since our start in 2014, we have demonstrated an ability to work collaboratively with asset owners of all types – super-majors, public and private operators, and financial sponsors – in order to conclude win-win deals." The only frustration for Zenith is that all of its storage capacity at Bantry Bay is already contracted. "Depressed demand caused by Covid 19 has moved the market into a contango structure where the future price of oil is higher than the prompt price; when this happens, storage tanks become highly sought after," says Reynolds. "However, even though market forces have increased demand for storage, all of our tankage is fully contracted. Since our ownership of Bantry Bay, we have had commercial utilisation of over 95% and this has limited our ability to participate in the current contango-driven market. "Frankly, I wish we had more tanks available."
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
7,672
Prob. Died Young, Or How Pat Ryan Lost His Eye (As a Union Soldier) (1) March 14, 2018 April 13, 2018 William D. (Dennis) Lindsey Pine Bluff [Arkansas] Daily Graphic, 19 Oct. 1893, p. 1, col. 3. I've just shared postings tracing all I've been able to discover about an elusive Ulster Scots ancestor, David Dinsmore, who came from Ireland to South Carolina with his wife Margaret not long before the Revolution, took the British side during that war, and found himself exiled to Nova Scotia, leaving his wife and children behind in South Carolina. The backstory to those postings is that, for many years, my FGS for this family had neatly written, in the slot next to David's date and place of death, the statement, "Prob. died young." In researching this family in the records of Ninety Six District and Spartanburg County, South Carolina, I had, of course, quickly discovered that David dropped out of South Carolina records around the time of the Revolution — and I had assumed that he was not to be found in those records or Revolutionary muster or payment lists of his area because "Prob. died young." I never entertained the possibility I might have had a Loyalist ancestor who was sent packing to Canada from South Carolina. I'd have welcomed learning that I had such an intriguing ancestor: it simply never entered my mind that the reason David "Prob. died young" was that he was exiled to Nova Scotia during the Revolution. Imagine my surprise when someone who knew I was working on this line emailed me some years back and sent me a summary of David's Loyalist land claim in Nova Scotia, asking, "Isn't this the same David Dinsmore on whom you've been working?" "Couldn't be," I told her. "I think he probably died young." And: "How would a man down in South Carolina end up in Nova Scotia?" I asked myself as I raised my eyebrows at the suggestion that the Nova Scotia settler about whom she had information was David Dinsmore of South Carolina. She then sent me a copy of David's Loyalist land claim in Nova Scotia, stating that he had lost 250 acres on Jamey's Creek in Ninety Six District, South Carolina (the application reads "James' Creek," but the usual usage in Spartanburg County was "Jamey's Creek of the Tyger River"), and I realized I had do something about that "Prob. died young" tag in my FGS chart for David. This surprising discovery about David Dinsmore's Loyalist record: it was precisely parallel to the discovery that two of my direct ancestors, Zachariah Simms Simpson[1] and Elizabeth Ann Winn Braselton, from slaveholding families in Tuscaloosa County, Alabama, had filed claims with the Southern Claims Commission following the Civil War, testifying to their Union sympathies during the war. I had grown up hearing story after story about precisely those families, about their commitment to the glorious Confederate cause. Big houses. Happy slaves. Unionists? How could that possibly have been? I plan to tell these two stories in detail in subsequent postings. I was schooled, you see, in a south Arkansas-flavored version of the Georgia world that Olive Ann Burns describes in her novel Cold Sassy Tree — and my presuppositions about what was historically probable reflected that schooling and its patent biases. Burns writes, Cold Sassy is the kind of town where schoolteachers spend two months every fall drilling on Greek and Roman Gods, the kings and queens of England, the Crusades, the Spanish Inquisition, Marco Polo, Magellan, Columbus, the first Thanksgiving, Oglethorpe settling Georgia, and how happy the slaves were before the War. A good teacher could cover the history of the whole world in two months and spend the rest of the school year on the War of the Sixties and how the Union ground its heel in our faces after it knocked us down . . . . In Cold Sassy, nobody ever made or waved an American flag.[2] In my experience, genealogical research worth its salt inevitably leads to surprising discoveries that tags on FGS charts of the "Prob. died young" ilk are often based on flatly incorrect assumptions, assumptions shattered when unexpected documentary evidence turns up to illuminate lacunae in our data about people in our family trees (no, the reason James. R. Brooks suddenly drops from records in Lawrence County, Alabama, in the 1840s is not that he "Prob. died young," but — as I discovered when I read the loose-papers estate file of his father Thomas Brooks in Morgan County — he had gone to California to pan for gold, and is on the 1850 census living in a mining camp in El Dorado County). As historian Diarmaid MacCulloch reminds us in his study entitled Silence: A Christian History, a primary reason such lacunae occur in historical accounts is that people forget what's convenient to forget about their history: MacCulloch writes, The history of Christianity is full of things casually or deliberately forgotten, or left unsaid, in order to shape the future of a Church or Churches. Institutions religious or secular create their own silences, by exclusions and by shared assumptions, which change over time. Such silences are often at the expense of many of the people who could be thought of as actually constituting the Church; institutional needs outweigh individual needs. Some are conscious silences of shame and fear at the institution of the Church not living up to its own standards of truth and compassion; and there has often been a particular pain meted out to those who make the silences end. Life is rarely comfortable for the little boy who says that the emperor has no clothes.[3] All Americans descended from colonial settlers of course had Revolutionary ancestors. All Southern families, especially those holding slaves, were of course Confederates. Real history, what actually happened, is often inconvenient to remember for one reason or another. So we flatten our historical narratives, mythologize the past, and when real history stares us in the face in those inconvenient documentary sources we did not ever expect to find, it often has the unsettling effect of demythologizing and unflattening what we had imagined we knew about the past. Baptismal record, Pat Ryan, son of Val Ryan and Biddy Tobin, 14 April 1846, Register of Kilbeacon Catholic Parish, Mullinavat, Co., Kilkenny, Ireland, April – July 1846, p. 25. And now on to the story of an uncle of my maternal grandmother, Hattie Batchelor Simpson, a man about whom I heard numerous stories as I was growing up: Patrick Ryan was born about 14 April 1846 (the date of his baptism) in Buckstown, a "suburb" of Mullinavat in County Kilkenny, Ireland, and died 18 October 1893 in the Orion community of Grant County, Arkansas. He's buried there in the cemetery of Orion Baptist church. My grandmother was five years old when this uncle died, but she spoke as if she had a vivid memory of him, as did her brothers Pat, Monroe, and Ed, her three siblings who were still alive as I was growing up. Pat and Monroe had, in fact, known their uncle Pat fairly well, since they were older than my grandmother. Tombstone of Patrick Ryan, Orion Baptist Cemetery, Grant County, Arkansas. Inscription reads: "Patrick Ryan, Born 1846, Died 18 Oct. 1893. In Paradise thou / sharest bliss, / Ne'er to be found in / a world like this." Among the stories my grandmother and her brothers told about their uncle was that he had lost an eye and wore a patch over the missing eye. The mysterious patch — How did he lose that eye? — figured in every story told about Pat, including ones about his legendary kindness to beggars. They would come to his door and ask for money, the story goes, undeterred when the man opening the door to them turned out to have only one eye. He would never turn a beggar from his door. He'd drop coins into their hands and say, "Faith and beJasus, keep this money and ye'll nivver be a poor man again." At some point in my childhood, I'm fairly certain one of those story-telling elders told me that they understood their uncle had lost his eye during the Civil War, but didn't know particulars about what had happened. I seem to recall that as I was told this, I also asked whether he had been a Confederate or a Union soldier: no one seemed to know the answer to that question. Or if they did know, they weren't talking. Fast forward to the mid-1970s when I decided to begin writing down all the family stories I'd been told as a child, and to gather all the documents I could find, especially the brittle old bible registers that were already falling apart by those years. I was heading off to Toronto to do graduate studies, and thought someone in my family should try to save all of this information and documentation before it was lost. I decided I'd try to record all my family knew about relatives of the past including Pat Ryan, his parents Valentine Ryan and Bridget Tobin, and his siblings Catherine Ryan Batchelor, my great-grandmother, and Margaret Ryan Sumrall. Close-up, Patrick Ryan's Tombstone. Since there was that tantalizing supposition that someone — my grandmother or one of her brothers — had offered, that Pat Ryan had lost his eye serving in the Civil War, I decided to dig for a Civil War service record. For a Confederate record…. Since Grant County is in the southern half of Arkansas…. Where I understood Confederate sympathies had been stronger than Union ones…. (Never mind that it was named for Ulysses S. Grant when it was formed in 1869). Southern Arkansas, Southern sympathies: that was the embarrassingly simplistic rubric I applied as I outlined the parameters of my search for a Civil War service record for Patrick Ryan when I began doing formal genealogical research in the mid-1970s. When I launched this line of inquiry, I immediately found there was, indeed, a handful of CSA soldiers in Arkansas who had been called Patrick/Pat Ryan. I combed through the service records of each of these men. Nothing in them leapt out at me. Nothing clearly matched what my family knew about my grandmother's uncle Pat. In fact, none of these records seemed to fit the facts of his life in any way at all. At this point, I dropped that search, turned to my graduate work, then started a full-time teaching and administrative career, and forgot about Pat Ryan and why his eye might have gone missing. I did, however, spend some time in these years searching diligently for the precise place of origin of my Ryan family in County Kilkenny (we had always known that this was the county from which the family emigrated to New Orleans and then to Mississippi and Arkansas), made several trips to Ireland, and had the fabulous fortune to meet a retired teacher and writer living in County Kilkenny, John Ryan, who generously offered to help me in this search. John located my family in the records of their Catholic parish in Mullinavat in the archival holdings of the county historical society at Rothe House in County Kilkenny — the first concrete evidence we had had of their precise place of origin in Ireland. Then roll the reel forward another several years to 2017, around this very time of year — as St. Patrick's day approaches — and it occurs to me, "You know, years ago when you searched for a Civil War service record for Pat Ryan, you didn't even think to look for a Union record, did you?" And so I did just that, with the 21st-century magic of the internet making that search so much easier than it would have been in the 1970s, and here's what I immediately found: on 8 November 1863 in Little Rock, a young Irish-born man named Patrick Ryan enlisted in the 3rd Regiment of the Arkansas Cavalry, Co. K. Of the Union Army…. His service papers state that he was 18 years old when he enlisted, born in Ireland, a farmer, 5'5″ in height with light hair and blue eyes. He was the wagoner of his company, and a teamster. Since this was clearly my grandmother's uncle Pat, I realized as I scanned the service packet that, as with many young men joining the military, his age at enlishtment was off by a year because he had fudged it slightly and made himself a year older than he actually was. Index listing, pension of Patrick Ryan, Co. K, Arkansas Cavalry, NARA, General Index to Civil War and Later Pension Files, RG 15, Records of the Department of Veterans Affairs, 1773 – 2007, series T288, U.S., Civil War Pension Index: General Index to Pension Files, 1861-1934. And then I found that he had filed a pension claim for his Civil War service, a claim his widow Delilah Rinehart Ryan continued following her husband's death, and I sent off to the National Archives for that set of papers. When it arrived, I learned at last from the rich cache of documents it comprised — I learned in vivid detail — exactly how Pat Ryan lost that eye. As a Union soldier…. And part of a hand and an arm…. And I learned, too, an amazing amount of other information of which no one in my family had had any inkling, including that Pat had had a wife prior to Delilah, the widow of one of his comrades in arms who died during or soon after the war — stories I'll save for the next installments in this series. This is the first posting in a nine-part series about this topic. The next posting in the series is here. That posting will end with a link taking you to the next in the series, if you're interested in following this series to the end. [1] Z.S. Simpson and his wife both died in 1869; the claim was filed on behalf of their estate by son-in-law Thomas Clements, and supported by affidavits of a number of family members who testified that Z.S. Simpson was a Unionist. [2] Olive Ann Burns, Cold Sassy Tree (NY: Dell, 1984), p. 61. [3] Diarmaid MacCulloch, Silence: A Christian History (NY: Penguin, 2013), p. 191. Tagged 3d Regt. Arkansas Cavalry, Arkansas, Bridget Tobin, Catherine Ryan Batchelor, Civil War, Co. Kilkenny Ireland, Confederate Army, Delilah Rinehart Ryan, Elizabeth Ann Winn Braselton, Grant Co. Arkansas, Margaret Ryan Sumrall, Mullinavat Co. Kilkenny Ireland, Orion Baptist Cemetery, Patrick Ryan, Southern Claims Commission, Tuscaloosa Co. Alabama, Union Army, Unionists, Valentine Ryan, Zachariah Simms Simpson Previous postDavid Dinsmore, Ulster-Scots Loyalist in South Carolina and Nova Scotia Exile: Every Life Worth a Novel (7) Next postProb. Died Young, Or How Pat Ryan Lost His Eye (As a Union Soldier) (2) One thought on "Prob. Died Young, Or How Pat Ryan Lost His Eye (As a Union Soldier) (1)" Pingback: "In Memory of Valentine Ryan, Born in Co. Kilkenny, Ireland, Feb. 23, 1810, Died Feb. 22, 1881. Erected by his son Patrick Ryan": Irish Roots of Ryan Family, Grant County, Arkansas (3) – Begats and Bequeathals
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
5,837
{"url":"https:\/\/maslinandco.com\/6063026","text":"Calculate: -6 y = 36\n\nExpression: $$- 6 y = 36$$\n\nDivide both sides by $-6$.\n\n$$y=\\frac{36}{-6}$$\n\nDivide $36$ by $-6$ to get $-6$.\n\n$$y=-6$$\n\nRandom Posts\nRandom Articles","date":"2023-01-28 11:13:55","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 1, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.564620852470398, \"perplexity\": 5874.677805378286}, \"config\": {\"markdown_headings\": false, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2023-06\/segments\/1674764499541.63\/warc\/CC-MAIN-20230128090359-20230128120359-00210.warc.gz\"}"}
null
null
Marketing is more prone to variables than secure in some quaint equation. We market from the variables and what they do. We sell in how we react to the variables. Building business is Art and Psych' more than any kind of science. And yes, 'Art' and 'Psych'' are capitalized intentionally. They're at the epicenter.. they're the engine and the wheels, and we as business owners are at the wheel navigating artfully, building our brand's collective Psychology while we respond to the consumers'. I'm learning from building my business that there's never too much to learn. There are several types of consumers, millions of reaction sets, so we need be quick and irrevocably clever. That's what feeds the wheels and sets the fire in its colorful code. If you want to sell, dance with the reactions of consumers…. Again, just a thought.
{ "redpajama_set_name": "RedPajamaC4" }
5,331
Q: I installed this extension algoliasearch for Catalog Search and use this like default search bug when running reindex, it shows a bug I want to use Algolia search like the default search and disable Elasticsearch but when I run reindex, it shows a bug like this: Catalog Search index process error during indexation process: Could not ping search engine: No alive nodes found in your cluster https://prnt.sc/gfXB_ZLXJ_Pm I use Magento 2.4.5. Do I need to worry about it? Thank you so much! A: 1). Please ensure that configuration of indexing queue as per the document https://www.algolia.com/doc/integration/magento-2/how-it-works/indexing-queue/?client=php 2). Can you please try to reindex with algolia cli commands and check for reindex A: Yes, of course. Catalog Search index is at least used for product listing in both backend and frontend, so you should fix this issue by config the Elasticsearch. Related documents: * *https://experienceleague.adobe.com/docs/commerce-operations/configuration-guide/search/overview-search.html *https://experienceleague.adobe.com/docs/commerce-operations/installation-guide/prerequisites/search-engine/configure-nginx.html
{ "redpajama_set_name": "RedPajamaStackExchange" }
4,657
EPICENTER XL to be held in Moscow! EPICENTER XL International EPICENTER Dota 2 tournament with $1,000,000 prize pool to be held in Moscow from April 27 to May 6. Epic Esports Events will hold the final stage of the tournament in Moscow from April 27 to May 6. At EPICENTER XL, teams will compete for a prize pool of $1,000,000. This is the largest prize pool in the history of single-discipline esports events held in Russia. EPICENTER XL Moscow will also be the first-ever Russian-hosted esports tournament to hold Major status. Valve will provide support for the event, and the winning teams of EPICENTER XL in Dota 2 will earn qualification points, which count towards their chances of receiving a direct invite to The International 2018. The playoff stage of the tournament will be held at Moscow's VTB Ice Palace sports arena on May 4–6. Once again, Epic Esports Events will organize a majestic show and a large number of activities for spectators coming to see the world's strongest esports squads in play. Starting January 20, open and closed qualifiers for EPIСENTER XL will be held in the following regions: CIS, Europe, North America, South America, China, and South-East Asia. A total of 12 of the world's best teams will be eligible for the LAN finals in Moscow, via both the qualifiers and direct invites. Two of the participating teams are already known: one is Team Liquid, two-time EPICENTER XL winners and current world champions; the other is Virtus.pro. Registration forms for regional open qualifiers and details about the tournament are available at the following links: EPICENTER XL EU QUALIFIER #1 EPICENTER XL CIS QUALIFIER #1 SEA: EPICENTER XL SEA QUALIFIER #1 South America: EPICENTER XL SA QUALIFIER #1 EPICENTER XL NA QUALIFIER #1 The nationwide mobile carrier Yota traditionally will be title partner of the tournament. Yota was among the first Russian brand to actively support esports as it joined the EPICENTER project in 2016. Four EPICENTER tournaments, in Dota 2 and Counter-Strike: Global Offensive, have already been organized in partnership with the mobile carrier in Moscow and Saint Petersburg. The company's products with a basis in an unlimited mobile 4G internet and SIM cards for smartphones and tablets with Russia-wide access free of roaming fees, will allow all fans to watch the tournament from virtually anywhere in the country. Epic Esports Events specializes in organizing international competitions, and was the organizer for the EPICENTER Dota 2 and CS:GO tournaments held in Moscow and St. Petersburg in 2016–17. Over 24 million viewers around the world followed the first EPICENTER: Moscow tournament. At Europe's leading EuBEA awards in 2016, that tournament got the prize for the best event in Europe in the Live Entertainment industry. The second EPICENTER: Moscow, Russia's first world-class CS:GO tournament, received ample coverage in domestic as well as international media. The finals the EPICENTER: St. Petersburg CS:GO tournament in October 2017 were attended by over 12 thousand spectators, and the total number of online viewers exceeded 30 million. ESforce Holding is one of the world's largest esports organizations, and the leader in electronic sports in Russia. ESforce is a holding company that integrates all key areas of the esports business, from organizing international tournaments and professional content creation to publishing and advertising activities, as well as online retail sales of esports-themed merchandise. ESforce owns over 220 popular online resources with a combined audience of 12 million followers and 114 million annual unique visitors, which provide a 90-percent reach to esports broadcast viewers in Russia and the CIS, as well as access to a significant share of relevant international audiences. Additional information is available to media representatives from the ESforce Holding press service at pr@esforce.org
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
3,379
Obum Ekeke Obum Ekeke MBE Global Lead, University Relations and Educational Partnerships, DeepMind Obum joined DeepMind in September 2019 and currently leads educational programs and partnerships aimed at significantly increasing access to Artificial Intelligence (AI) education globally and building a more diverse and inclusive AI community. Before DeepMind, Obum spent over 12 years at Google managing education programs across many countries and with a range of partners from universities to NGOs and governments. Most recently, Obum was leading Google's computer science (CS) and digital skills education programs in EMEA to ensure that every student has access to the collaborative, coding, and technical skills that unlock opportunities in the classroom and beyond–no matter what their future goals may be. Obum is on the management board of Computing At School – a UK organisation that provides leadership and strategic guidance to all those involved in computing in schools. Obum is also a member of the Digital Skills Partnership Computing in Schools delivery group – set up by the UK Department for Digital, Culture, Media & Sports to support teachers to gain the knowledge and skills to teach the new computing curriculum in England effectively. Obum Ekeke holds a Higher National Diploma from Yaba College of Technology, Lagos; a Master of Science degree from City, University of London; and an MBA from Imperial College Business School, London.
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
4,872
{"url":"https:\/\/lavalldebo.org\/43xcagqf\/3c3493-formamide-bond-angles","text":"=99.5% (GC), liquid. In formamide, the nitrogens appear to be s p X 3 hybridized, implying tetrahedral geometry. Couldn't this also help with achieving the 120 degree bond angles? To learn more, see our tips on writing great answers. Thanks for contributing an answer to Chemistry Stack Exchange! & MathJax reference. The N atom is also bonded to two H atoms. 60100-09-6. The N atom is also bonded to two H atoms. Why can't antiaromatic compounds just escape planarity and become non-aromatic to avoid destabilization? The C atom is bonded to two H atoms, a terminal O atom, and the N atom. Use MathJax to format equations. Couldn't there be a hydrogen bond between the peripheral hydrogen on the nitrogen and the oxygen? Naturally one would assume the nitrogen to be $\\ce{sp^3}$ hybridised, which is the case for most amines. rev\u00a02020.11.24.38066, The best answers are voted up and rise to the top, Chemistry Stack Exchange works best with JavaScript enabled, Start here for a quick overview of the site, Detailed answers to any questions you might have, Discuss the workings and policies of this site, Learn more about Stack Overflow the company, Learn more about hiring developers or posting ads with us, What strikes me as weird is your suggestion that O-H hydrogen bonding might be involved: none of the hydrogens are, MAINTENANCE WARNING: Possible downtime early morning Dec 2\/4\/9 UTC (8:30PM\u2026, \u201cQuestion closed\u201d notifications experiment results and graduation, Molecular orbitals and \u201cgeneralized\u201d aufbau principle for heteronuclear molecular configurations. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. How do smaller capacitors filter out higher frequencies than larger values? to the molecular plain. What are the correct resonance structures of nitrous oxide? Pi bonds are formed through the above and below electron-pairing in p-orbitals; effective bonding is achieved when these p-orbitals are parallel with respect to each other. How can I deal with claims of technical difficulties for an online exam? Describe the structure of the formamide molecule, H_2CONH_2, in terms of hybrid orbitals, bond angles, and sigma- and pi-bonds. | Asking for help, clarification, or responding to other answers. Lovecraft (?) Why were there only 531 electoral votes in the US Presidential Election 2016? The following scheme considers the most common ones and adds a third, that might explain delocalisation (in a non-traditional Lewis way) up to a certain visual point. This is the standard answer. The molecule formamide, HCONH 2, has the approximate bond angles H\u2212C \u2212 0,,123\u00b0; H\u2212C\u2212N, 113\u00b0; N\u2212C \u2212O, 124\u00b0; C\u2212N\u2212H, 119\u00b0; H\u2212N\u2212H, 119\u00b0. (The HOMO is an in-plane lone pair of oxygen.). The C atom is bonded to two H atoms, a terminal O atom, and the N atom. Terms Formamide, >=99.5% (GC), BioReagent, for molecular biology. Why is only one lone pair in imidazole delocalised? Why did mainframes have big conspicuous power-off buttons? Privacy Using of the rocket propellant for engine cooling. In your chart, that refers to entry 2. It only takes a minute to sign up. If you choose this plane to be $xy$ then the contributing orbitals will be $\\ce{p_{$z$}}$. Formamide solution, NMR reference standard, 45% in DMSO-d6 (99.9 atom % D), NMR tube size 5 mm x 8 in. The C \u2212 N bond length is 138 pm. OOP implementation of Rock Paper Scissors game logic in Java. Formamide solution, NMR reference standard, 45% in DMSO-d6 (99.9 atom % D), NMR tube size 3 mm x 8 in. Orbital Electronegativity Considerations in Resonance Structures, Draw a simplified MO diagram for the pi system of Methyl vinyl ether. However, the inversion barrier for these molecules is (depending on the substituents) very low. \u00a9 2003-2020 Chegg Inc. All rights reserved. How do we get to know the total mass of an atmosphere? This causes the nitrogen to most likely be of $\\ce{sp^2}$ hybridisation and the lone pair of entry one would be in a $\\ce{p}$ orbital. But I will not go into detail about that, because it would involve breaking away from the very handy hybridisation concept. Why is the battery turned off for checking the voltage on the A320? EDIT: as suggested by Martin and another poster, hybridization is a rough concept. The conjugation happens as stated in you chart by the overlap of that orbital with the antibonding $\\pi^*~\\ce{C-O}$ orbital. What is the meaning of \u201ccharge separation\u201d in resonance? Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. Where should small utility programs store their preferences? So perhaps the hybridization of nitrogen upon further analysis should best be described as somewhere inbetween $\\ce{sp^3}$ and $\\ce{sp^2}$. However, analysis shows that the molecule is actually very nearly planar with bond angles close to 120 degrees. Calories In One Peanut, Cumulative Distribution Function Excel, Pulsar Thermion Reticles, Ap Calculus Ab Formula Sheet 2020, Romans 5:6-10 Esv, Describe The Four Typical Types Of Loss Exposure, Chat Partner Apk Huawei Y7p, \" \/>\nMaking statements based on opinion; back them up with references or personal experience. Is planarity really necessary for conjugation? This causes the $\\ce{N-C}$ bond order to increase, while the $\\ce{C-O}$ BO has to decrease. While there is certainly no intra molecular hydrogen bond ($d(\\ce{O-H}\\approx 2.57$ same level), there will also most certainly be an attraction between the $\\ce{C-O}$ and $\\ce{N-H}$ bond helping to stabilize the planarity. This however would still necessitate planarity, correct? Why is the concept of injective functions difficult for my students? Looking up values in one table and outputting it into another using join\/awk, How do rationalists justify the scientific method. The C \u2212 N bond length is 138 pm. I'm thinking this has to do with the partial double bond character in the molecule (also appears to be some ionic character to the molecule - likely due to electron-withdrawing effects of the nitrogen and the oxygen). Why is Soulknife's second attack not Two-Weapon Fighting? How to get a smooth transition between startpoint and endpoint of a line in QGIS? View desktop site. So perhaps the hybridization of nitrogen upon further analysis should best be described as somewhere inbetween s p \u2026 Is a software open source if its source code is published by its copyright owner but cannot be used without a commercial license? By using our site, you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. site design \/ logo \u00a9 2020 Stack Exchange Inc; user contributions licensed under cc by-sa. Describe the structure of the formamide molecule, H_2CONH_2, in terms of hybrid orbitals, bond angles, and sigma- and pi-bonds. All those resonance structures are only descriptions of extreme states, the truth lies between them. The carbon is obviously $\\ce{sp^2}$ hybridised (as this concept is very well applicable here), hence organising it's ligands in one plane with roughly $120^\\circ$ angles. However, analysis shows that the molecule is actually very nearly planar with bond angles close to 120 degrees. Can you have a Clarketech artifact that you can replicate but cannot comprehend? What is the most \u201cimportant\u201d resonance structure of SCN\u207b? $$\\ce{[NH3]^{pyr-top} <=> [NH3]^{TS-plan} <=> [NH3]^{pyr-bot}}$$ For the nitrogen that means going from $\\ce{sp^3}$ to $\\ce{sp^2}$ and back again. \"To come back to Earth...it can be five times the force of gravity\" - video editor's mistake? EDIT: as suggested by Martin and another poster, hybridization is a rough concept. Most of the amides are planar (due to steric reasons the restriction may be lifted) and so is also formamide. In molecular orbital theory you can form 3-centre orbitals from all molecules perpendicular Is it too late for me to get into competitive chess? Chemistry Stack Exchange is a question and answer site for scientists, academics, teachers, and students in the field of chemistry. By clicking \u201cPost Your Answer\u201d, you agree to our terms of service, privacy policy and cookie policy. The following scheme may support this claim, the dipicted orbitals were obtained by a BP86\/cc-PVTZ calculation. In formamide, the nitrogens appear to be $\\ce{sp^3}$ hybridized, implying tetrahedral geometry. You can now stabilise the intermediated structure with conjugation, and that is exactley the case here. story about man trapped in dream. However, would intramolecular hydrogen bonding also play a role? Formamide, for molecular biology, >=99.5% (GC), liquid. In formamide, the nitrogens appear to be s p X 3 hybridized, implying tetrahedral geometry. Couldn't this also help with achieving the 120 degree bond angles? To learn more, see our tips on writing great answers. Thanks for contributing an answer to Chemistry Stack Exchange! & MathJax reference. The N atom is also bonded to two H atoms. 60100-09-6. The N atom is also bonded to two H atoms. Why can't antiaromatic compounds just escape planarity and become non-aromatic to avoid destabilization? The C atom is bonded to two H atoms, a terminal O atom, and the N atom. Use MathJax to format equations. Couldn't there be a hydrogen bond between the peripheral hydrogen on the nitrogen and the oxygen? Naturally one would assume the nitrogen to be $\\ce{sp^3}$ hybridised, which is the case for most amines. rev\u00a02020.11.24.38066, The best answers are voted up and rise to the top, Chemistry Stack Exchange works best with JavaScript enabled, Start here for a quick overview of the site, Detailed answers to any questions you might have, Discuss the workings and policies of this site, Learn more about Stack Overflow the company, Learn more about hiring developers or posting ads with us, What strikes me as weird is your suggestion that O-H hydrogen bonding might be involved: none of the hydrogens are, MAINTENANCE WARNING: Possible downtime early morning Dec 2\/4\/9 UTC (8:30PM\u2026, \u201cQuestion closed\u201d notifications experiment results and graduation, Molecular orbitals and \u201cgeneralized\u201d aufbau principle for heteronuclear molecular configurations. To subscribe to this RSS feed, copy and paste this URL into your RSS reader. How do smaller capacitors filter out higher frequencies than larger values? to the molecular plain. What are the correct resonance structures of nitrous oxide? Pi bonds are formed through the above and below electron-pairing in p-orbitals; effective bonding is achieved when these p-orbitals are parallel with respect to each other. How can I deal with claims of technical difficulties for an online exam? Describe the structure of the formamide molecule, H_2CONH_2, in terms of hybrid orbitals, bond angles, and sigma- and pi-bonds. | Asking for help, clarification, or responding to other answers. Lovecraft (?) Why were there only 531 electoral votes in the US Presidential Election 2016? The following scheme considers the most common ones and adds a third, that might explain delocalisation (in a non-traditional Lewis way) up to a certain visual point. This is the standard answer. The molecule formamide, HCONH 2, has the approximate bond angles H\u2212C \u2212 0,,123\u00b0; H\u2212C\u2212N, 113\u00b0; N\u2212C \u2212O, 124\u00b0; C\u2212N\u2212H, 119\u00b0; H\u2212N\u2212H, 119\u00b0. (The HOMO is an in-plane lone pair of oxygen.). The C atom is bonded to two H atoms, a terminal O atom, and the N atom. Terms Formamide, >=99.5% (GC), BioReagent, for molecular biology. Why is only one lone pair in imidazole delocalised? Why did mainframes have big conspicuous power-off buttons? Privacy Using of the rocket propellant for engine cooling. In your chart, that refers to entry 2. It only takes a minute to sign up. If you choose this plane to be $xy$ then the contributing orbitals will be $\\ce{p_{$z$}}$. Formamide solution, NMR reference standard, 45% in DMSO-d6 (99.9 atom % D), NMR tube size 5 mm x 8 in. The C \u2212 N bond length is 138 pm. OOP implementation of Rock Paper Scissors game logic in Java. Formamide solution, NMR reference standard, 45% in DMSO-d6 (99.9 atom % D), NMR tube size 3 mm x 8 in. Orbital Electronegativity Considerations in Resonance Structures, Draw a simplified MO diagram for the pi system of Methyl vinyl ether. However, the inversion barrier for these molecules is (depending on the substituents) very low. \u00a9 2003-2020 Chegg Inc. All rights reserved. How do we get to know the total mass of an atmosphere? This causes the nitrogen to most likely be of $\\ce{sp^2}$ hybridisation and the lone pair of entry one would be in a $\\ce{p}$ orbital. But I will not go into detail about that, because it would involve breaking away from the very handy hybridisation concept. Why is the battery turned off for checking the voltage on the A320? EDIT: as suggested by Martin and another poster, hybridization is a rough concept. The conjugation happens as stated in you chart by the overlap of that orbital with the antibonding $\\pi^*~\\ce{C-O}$ orbital. What is the meaning of \u201ccharge separation\u201d in resonance? Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers. Where should small utility programs store their preferences? So perhaps the hybridization of nitrogen upon further analysis should best be described as somewhere inbetween $\\ce{sp^3}$ and $\\ce{sp^2}$. However, analysis shows that the molecule is actually very nearly planar with bond angles close to 120 degrees.","date":"2022-08-16 09:30:17","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 1, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.1736321896314621, \"perplexity\": 2818.5956450905196}, \"config\": {\"markdown_headings\": false, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2022-33\/segments\/1659882572286.44\/warc\/CC-MAIN-20220816090541-20220816120541-00004.warc.gz\"}"}
null
null
Home US News God, man and the Scriptures (second part) God, man and the Scriptures (second part) "Therefore, any interpretation of Scripture must be wrong if it causes us to fail in our duty to love God or our neighbor," as "Augustine rightly reasoned," Catholic theology professor James L. Papandrea notes in a new book. from Sophia Institute Press. your perception Reading the Scriptures Like the Early Church: Seven Insights from the Church Fathers to Help You Understand the Bible interprets the Bible through a law of love, in contrast to the often morally problematic biblical literalism of Islamic doctrine. As discussed above, Papandrea reads the Bible in a scholarly and nuanced way. By contrast, any fundamentalism "tends toward an anti-intellectualism that often assumes that education is really an obstacle to correct interpretation," he observes. This stems from the "idea that Scripture can be interpreted only from within itself", or write onlya "major component of the Protestant Reformation", having no basis in the Jewish faith of Jesus and the apostles. write only recalls the Qur'anic proclamation that Muslims should emulate Islam's Prophet Muhammad in everything. The canonical example of him thus establishes the Qur'an, the biography of him (Mrs) and recorded sayings about his life (hadith) narratives as the doctrinal basis of Islam, which received the Islamic orthodoxy interpreted literally. This has led to outrage such as that of Georgetown University professor Jonathan Brown, a Muslim convert, who refuses to condemn slavery outright, as slavery is historically Islamic, given that Muhammad himself owned slaves. Whether in Islam or Christianity, Papandrea will have none of this, as indicated during a Conservative Casual Friday podcast interview with this author. The "doctrine of write only it is self-contradictory, because it claims that everything should be in the Bible, but the concept itself is not in the Bible," he writes. John 21:24–25, for example, indicates that the "Bible does not contain everything that Jesus said and did." In particular, the "Bible doesn't tell us which books should be included in the Bible," Papandrea observes. "The question of which documents were to be included in the collection of Scriptures that the Christian Church would consider authoritative was a question that took hundreds of years to answer definitively," she notes. Consequently, a "good way to think about all of this is that Scripture is really a part of Tradition." Such a rational approach to revelation is particularly important, because believing that "everything anyone needs to understand God's revelation is within the pages of the Bible" morally "creates several problems," Papandrea notes. "If the Bible were 'complete' in this way, we would be forced to conclude that polygamy is acceptable because we see it tolerated in the Old Testament and find no prohibition in the New Testament," he writes. . However, as you discussed with this author, rational analysis of polygamy, both in the real world and as presented in the biblical text, where conflicts always arise between polygamous households, reveals the many problems of polygamy. Consequently, modern Jews find almost no justification in Jewish scripture or the Old Testament for polygamy, in contrast to still contemporary Islamic doctrines of polygamy. Especially the horrors of slavery evoke the Biblical perspective of Papandrea: "Love is the key. The correct interpretation of Scripture will always lead to love of God and neighbor." As Saint Augustine had pointed out, "the greatest commandment of Jesus is to love God, and the second greatest is to love your neighbor (Matthew 22:37-40; Mark 12:29-31)", an imperative that no biblical interpretation can contradict. "This idea alone should have been a sufficient indication that any interpretation condoning slavery could never be correct," Papandrea notes in examining historical debates on slavery among Christians. Rather, the "very anti-abolitionists who tried to use Scripture to justify slavery were the forerunners of the fundamentalist movement that uses this same limited methodology to interpret Scripture," Papendrea recalls. However, as others have pointed out when comparing Biblical and Islamic scriptures, the historical references to slavery in the Bible are merely descriptive. They are not prescriptive in the form of an eternal standard, in the way that jihadists have interpreted Islamic canons to justify holy war. "It turns out that slavery was a very established practice in the ancient world. Few, if any, human cultures existed without some form of slavery," Papandrea notes. The Apostle Paul in his New Testament writings "assumes that it is so embedded in the culture that he cannot even imagine a world without it." But Papandrea does not grant any absolute value to the contingent circumstances of Paul's life: Thus, for example, although we can read in the epistles of Saint Paul that women must cover their heads, or that it is shameful for a man to have long hair (1 Cor. 11:5-15), or that women may not speaking in church (1 Cor. 14:34; cf. 1 Tim. 2:9-12), we recognize that this is advice that is specific to a particular time, in a particular place, to a particular culture… Therefore, there is nothing wrong with lectors or teachers, and we do not need to require that women in the church wear head coverings. The cultural context also applies to Psalm 137, one biblical passage among others that falsely suggests to some that the Bible is just as violent as the Koran. Here, the exiled Hebrews under Babylonian captivity proclaim a "call for vengeance, and not only for vengeance on those who destroyed their city and captured them, but for vengeance on future generations of their enemies." However, Papandrea does not extract any divine mandate from the Hebrew authors of the psalm, for even if really believed that it was God's will that some babies be killed, that doesn't mean it was actually God's will. In other words, the historical significance of this text is that the true Hebrew people harbored real hatred and resentment—and a desire for revenge—against their Babylonian captors. "Remember that the Old Testament sometimes tells us more about the people who wrote it and their understanding of God than it actually tells us about God," Papandrea concludes. "But God reserves the right of revenge only for himself (see Rom. 12: 17-21)" and Christians must "give priority to the New Testament, where we are told to love even our enemies." This reflects another idea of ​​Papandrea's about hermeneutics: "The earlier Scripture is clarified by the later Scripture. Also, lighter texts are used to interpret darker texts.." Contrary to the Islamic doctrine of abrogation, in which, chronologically, later verses of the Qur'an can override earlier verses, Papandrea describes a consistent message that runs throughout the Bible: When we say that revelation is progressive, we mean that in the great trajectory of Scripture, God has ordained that meaning become clear over time. On the other hand, disclosure is also conservative, in the sense that what is revealed always preserves what was revealed in the past and builds on what was revealed before. Throughout human history, God's revelation improves with time. "Scriptures written earlier in time had the disadvantage of a limited perspective on the part of the human author, and from God's perspective, they were given information on a sort of need-to-know basis," Papandrea says. Therefore, he takes a broad view of the interpretation of Scripture, because "it is very important to let the clearer passages, the majority of the passages, and the entire consensus of Scriptures interpret the darker and fewer passages." Such logic and love exhibited by Papandrea make the understanding of God's revealed relationship with man far more convincing than that received by Islamic orthodoxy. These doctrinal differences, in turn, repel Western secularists who, in their desire to overthrow traditional Western Judeo-Christian norms, dismiss all Biblical traditions as equally spurious. Judging by the God-given human conscience, not all scripture is sacred. Previous articleThe Winds of Winter: George RR Martin reveals how many more pages he has left to write Next article"Low-cost" cosmetics to show off skin like Queen Letizia's
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
3,502
Page 332 of 1452 « First < 232 282 322 328 329 330 331 332 333 334 335 336 342 382 432 832 1332 > Last » I think they just need to figure out how they are going to cover the costs. Recent history shows that any major (or minor, for that matter) national administrative venture runs wildly over budget, zooms past its deadline and ends up getting shelved or scrapped. Maybe the 30,000 new staff is a conservative estimate (easier to round down again rather than round up after the fact) but if that is the figure they are working on, the budget must be astronomical. I can see it being farmed out to private companies who will do their best to draw it out and squeeze out more funds. Never mind - 350 million a week for the NHS, right..? Looks like the Govt. is squeezing NHS funding to find the extra money to pay for Brexit, this is a top irony day! Seems there will be a statement in the Autumn budget about money for Brexit work but I doubt they will have the balls to state the real amount! I heard on the (radio) news this morning that they wouldn't be announcing anything this year as regards budgets for Brexit. I'll try to find the right link. Location: Aargau This is in most UK newspapers; Guardian, ft, Telegraph for alternate reports.. It has been obvious for some time that there is no single agreed Brexit plan. It's gonna be a good step in creating another 30,000 jobs which surely will decrease unemployment rate by 0.0000xx %, never mind to drain NHS funds. It seems like it was unsolicited document leaked by private firm ... Government 'doesn't recognise' Brexit memo Cata1yst Location: Zugish Sharks these consultants as soon as they can smell blood they see pound signs. Bill as much as you can deliver as little as possible is the constant message with consultants and the UK government projects over the last 10 years or so. Added to this, you never know how many MPs might be on the boards and/or shareholders of these consulting companies. What goes around, comes around. Location: canton ZH If you cast a vote aned thereby participate in an a vote, you are effectively approving the voting system. If you don't approve of the way votes are counted, or don't approve of the question being asked or the terms under which it ius being asked, the right thing to do is to not vote or spoil your ballot. If I recall correctly, voter turnout was over 50%. If "spoil the ballot" means handing it in yet not voting: I do that sometimes to make sure the "Wahlbeteiligung" (voter participation) shows my statement of refusing both options (well, I know one only won't show but even that droplet in the sea makes me feel better). For example if 40% of the population actually votes and 30% of those vote for SVP-initiatives, they do not have 30% of the Swiss population on their side .... no matter how loud they claim they do. As to <<If you cast a vote and thereby participate in an a vote, you are effectively approving the voting system>> I've been wondering about this with Brexit as well as the US-elections: All these protests, riats and calling the other side stupid afterwards. It's weird to me: If one can't live with it one has to aim at changing the system. We seem to know that here, they've tried it too (more signatures for a people initiative etc. etc.) And since I learnt that the English vote is only advisory I definitely think the Brits should change their system - or forever hold their peace bigblue2 Location: Glarus 10 years?? I worked on uk gov projects 20 years ago and it was the same then, the standard of work was laughably low even then, any normal business would never accept it, the stories I could tell you The following 2 users would like to thank bigblue2 for this useful post: Cata1yst, marton Having also been involved in such Govt. projects a long time ago my guess would be that this memo was a response to a Govt. question sent to a number of consultancies already intimately involved with a number of departments. The question would be along the lines of "assuming we will need support to complete Brexit then give us your ideas on the way forward to help us formulate our strategy. Your contacts for questions are ....". Edit: basically it is sales document We do need politicians. Whose going to turn the street lights on at night? Whose going to allocate funds for education, health care, the military, etc... Whose going to deal with World leaders when they begin sabre rattling? The list is endless, and I doubt you have the time, wit, knowledge or guile to do all of those tasks and make it home for dinner. The only role for politicians should be to merely administrate and execute the will of the people. It works here, why shouldn't it work elsewhere? Cata1yst, curley Does not really work like that here. There is a lot of stuff that was never the subject of a referendum and politicians have to make their own policies. For example, almost all foreign policy outside of EU links, education, culture, sport, communications, etc. Yes, but for the major issues (and many minor ones too) there normally are referendums. I remember a few years back there was a referendum in Zürich for whether there should be mixed age group classes in Primary schools or not. Take away the power from politicians, reduce them to administrators. Cata1yst, JagWaugh There are between 8 and 10 national referendums per year. There seven Bundesrat members, two hundred Nationalrat members, forty six Standerat members. So you believe these two hundred and fifty three politicians are just administrators because we have 10 national referendums per year? I also like the referendum system but it in no way replaces politicians, it is also a very slow and clumsy system. If, for example, there were threats from Trump or Putin we could not wait a year or two before formulating a response. Blueangel, Urs Max Location: Küsnacht, Switzerland For anyone who thinks the NHS may be dismantled in the future, this surely signals that our esteemed, revered Empress has already begun... Controversial £700m Virgin Care contract for adult social care approved Unison said: 'Employees need clear recognition from Virgin that a well-run health service means investment in staff' http://www.independent.co.uk/news/uk...-a7411386.html This user would like to thank Blueangel for this useful post: Ok, I get that you prefer direct democracy. It has many advantages, but how to introduce it the UK with a populace whose nearest experience to that is voting in reality tv shows? One referendum and they haven't shut up since. One! Can you begin to imagine the backlash if it were 8-10 compulsory referendums per year? No doubt some would relish the opportunity, but do you really think the majority would? We're a politically lazy nation. It may happen, but not in our lifetime. I expect there were people who thought like that when democracy was first introduced. Change takes time but you've got to start somewhere. Yes, i agree, the first dabbling into referendums was a bit problematic. Maybe they should have started with a less fundamental question and built it up. A political culture of the type we have in Switzerland doesn't spring up overnight but gets to be that way because people take an appropriate interest in politics and understand how things work. If you look at Swiss history you will see things weren't always the way they are now. Referendums are OK for setting policies or answering specific questions but they are useless as a way to quickly respond to external influences or emergencies. The Brexit vote was hardly a response to an emergency though, was it? A political culture of the type we have in Switzerland doesn't spring up overnight but gets to be that way because people take an appropriate interest in politics and understand how things work. If you look at Swiss history you will see things weren't always the way they are now. I've read quite a bit about Swiss history, politics and culture over the past year...for obvious reasons...and finally know more than my OH who lived in Switzerland for 2yrs previously. The Swiss people know their value and their place in the World. They're not expansionists. They do their national service without question and are overly prepared for outside aggression, but they're also neutral and I think that's the deciding factor which allows direct democracy to thrive here. Honestly, I feel a system like that in the UK wouldn't be like herding cats, it would be like juggling with cats. I think the world might be a better place if more countries strived to be a little more like Switzerland. Our expansionist attitudes in the recent and more distant past have brought out the worst in us rather than the best. The following 4 users would like to thank amogles for this useful post: Blueangel, Cata1yst Phos Quite relevant, actually. If you look at Deutsche Bank, Merkel is unable to bail it out because of Germany's EU membership. Same with Monte Dei Pasche. EU State Aid laws prevents governments from protecting their largest economic engines. Outside the EU, the UK government can service its industries. So it would untie the country's hands in dealing with its problems. This is an EU law that prevents such assistance. Seems that Deutsche Bank loaned Trump owned companies at least a third of a billion. Consequently DB is delaying talks with the U.S. Justice Department officials working on a mortgage securities investigation of Deutsche Bank AG in the hope that when Trump is President he will intervene to reduce the proposed 14 Billion fine. Of course Trump is an honourable man who would never do this. Edit: According to this source Trump companies also borrowed money from Goldman Sachs and Bank of China. How Trump will distance himself from all this is not yet published so he can avoid any allegations of undue influence. Of course Trump is the candidate who was not in the pocket of large corporations! Last edited by marton; 15.11.2016 at 19:00.
{ "redpajama_set_name": "RedPajamaCommonCrawl" }
9,374
Tool ==== Installation ------------ Copy the source to a local directory and add 'bin' to PATH. In order to use AWS related commands, you will need to create a directory ${HOME}/.tool and add your AWS private key and cert files to it. If such a directory by some other name already exists, you could also set an environment variable TOOL_DIR to point to it. Usage ----- This command line intends to be self documenting. To begin, simply type "tool". Example: $ tool Usage: tool aws ... $ tool aws Usage: tool aws database ... tool aws instance ... tool aws role ...
{ "redpajama_set_name": "RedPajamaGithub" }
7,145
{"url":"https:\/\/mathsgee.com\/11928\/diagram-below-drawn-scale-models-above-situation-cartesian","text":"Institutions: Global | Authors |Cars | Courseware |Ekurhuleni Libraries | Joburg Libraries | Startups | Tools |Tshwane Libraries | Math Worksheets | Visual Statistics\n\nMathsGee is Zero-Rated (You do not need data to access) on: Telkom |Dimension Data | Rain | MWEB\n\n0 like 0 dislike\n66 views\n\nThe diagram below, NOT drawn to scale, models the above situation in a Cartesian plane.\n\n$\\triangle{ABD}$ has vertices $A(1;4), B(-3;1)$ and $D(5;-2)$. The angle formed by the x-axis and $AE$ is $\\alpha$ and the angle formed by the x-axis and $AD$ is $\\beta$\n\n2. The coordinates of $M$, the midpoint of $AD$\n3. The equation of straight line $MC$ (in the form $ax+by+c=0$) if $MC \\parallel AB$\n4. The size of $\\alpha$\n5. The size of $B\\hat{A}D$\n| 66 views\n\n0 like 0 dislike\n\n1.\u00a0AD =\u00a0\u221a[(5-1)^2 + (-2-4)^2]\n\n=\u00a0\u221a52\n\n= 2\u221a13\n\n2. M = ( 1+5)\/2 ; ( 4-2)\/2\n\n= (3;1)\n\n= 3\/4\n\ngrad MC = 3\/4, since its parallel to AB\n\ny-1 = 3\/4 (x-3)\n\n3x-4y-5 = 0\n\n4. tanx = 3\/4\u00a0 (alpha)\n\n= 36.87 degrees\n\ntanB = -3\/2\n\nB = 123.69 degrees\n\nBAD =\u00a0123.69- 36.87, ext < of triangle\n\n= 86.82 degrees\n\nby Diamond (42,470 points)\n\n0 like 0 dislike","date":"2021-04-20 21:56:28","metadata":"{\"extraction_info\": {\"found_math\": true, \"script_math_tex\": 0, \"script_math_asciimath\": 0, \"math_annotations\": 0, \"math_alttext\": 0, \"mathml\": 0, \"mathjax_tag\": 0, \"mathjax_inline_tex\": 1, \"mathjax_display_tex\": 0, \"mathjax_asciimath\": 0, \"img_math\": 0, \"codecogs_latex\": 0, \"wp_latex\": 0, \"mimetex.cgi\": 0, \"\/images\/math\/codecogs\": 0, \"mathtex.cgi\": 0, \"katex\": 0, \"math-container\": 0, \"wp-katex-eq\": 0, \"align\": 0, \"equation\": 0, \"x-ck12\": 0, \"texerror\": 0, \"math_score\": 0.6597802042961121, \"perplexity\": 6420.734758202693}, \"config\": {\"markdown_headings\": true, \"markdown_code\": true, \"boilerplate_config\": {\"ratio_threshold\": 0.18, \"absolute_threshold\": 10, \"end_threshold\": 15, \"enable\": true}, \"remove_buttons\": true, \"remove_image_figures\": true, \"remove_link_clusters\": true, \"table_config\": {\"min_rows\": 2, \"min_cols\": 3, \"format\": \"plain\"}, \"remove_chinese\": true, \"remove_edit_buttons\": true, \"extract_latex\": true}, \"warc_path\": \"s3:\/\/commoncrawl\/crawl-data\/CC-MAIN-2021-17\/segments\/1618039491784.79\/warc\/CC-MAIN-20210420214346-20210421004346-00258.warc.gz\"}"}
null
null