Sunday, December 5, 2010

Dante's Inferno

Playthrough time: ~9 hrs

Lo que me gustó: El sistema de habilidades y combos.

Lo que no me gustó: Muy corto. Aún cuando en varios pedazos sentía "ya está a punto de acabarse" pero en realidad me faltaba todavía un rato. Although... how long can you make a hack-and-slash?

Overall: Entretenido. Tal vez no valía los 30 dólares que pagué por él.

Monday, November 29, 2010

Neil Gaiman & Terry Pratchett - Good Omens: The Nice and Accurate Prophecies of Agnes Nutter, Witch



Leído entre: Nov 23, 2010 – Nov 29, 2010 (7 días).

Lo que me gustó: El hecho de haber regresado un poco a la fantasía cómica. Leer los comentarios de Neil Gaiman acerca de Terry Pratchett y viceversa.

Lo que no me gustó: Nada en especial.

En general: Entertaining. Not required in a collection though.

Amazon lo tiene aquí.

Notas y citas:

God does not play dice with the universe; He plays an ineffable game of His own devising, which might be compared, from the perspective of any of the other players, to being involved in an obscure and complex version of poker in a pitch-dark room, with blank cards, for infinite stakes, with a dealer who won't tell you the rules and who smiles all the time. (p.14)



It may help to understand human affairs to be clear that most of the great triumphs and tragedies of history are caused, not by people being fundamentally good or fundamentally bad, but by people being fundamentally people. (p.30)



The ducks in St. James' Park are so used to being fed bread by secret agents meeting clandestinely that they have developed their own Pavlovian reaction. Put a St. James' Park duck in a laboratory cage and show it a picture of two men —one usually wearing a coat with a fur collar, the other something somber with a scarf— and it'll look up expectantly. The Russian cultural attaché's black beard is particularly sought after by the more discerning duck, while the head of MI9's soggy Hovis with Marmite is relished by the connoisseurs. (p.45)



Yet he seemed cheerful, enthusiastic, and as well-balanced as a gyroscope. (p.149)



[Discussing the burning, and subsequent explosion, of Agnes Nutter for being considered a witch] Thirty seconds later an explosion took out the village green, scythed the valley clean of every living thing, and was seen as far away as Halifax. There was much subsequent debate as to whether this had been sent by God or by Satan, but a note later found in Agnes Nutter's cottage indicated that any divine or devilish intervention had been materially helped by the contents of Agnes' petticoats, wherein she had with some foresight concealed eighty pounds of gunpowder and forty pounds of roofing nails (p.202)



You start thinking: it can't be a great cosmic game of chess, it has to be just very complicated Solitaire. (p.389)



[Neil Gaiman on Terry Pratchett] Then again, Terry is that rarity, the kind of author who likes Writing, not Having Written, or Being a Writer, but the actual sitting there and making things up in front of a screen. (p.404)


J.R.R. Tolkien - The Lord Of The Rings



Re-leído entre: Nov 13, 2010 – Nov 22, 2010 (10 días).

Lo que me gustó: Recordar todos los detalles de la historia de los que ya no me acordaba, porque el libro lo había leído hace mucho y/o porque en la película no los pasan.

Lo que no me gustó: Tolkien? LoTR? What's not to like? Ok, really, nothing in particular.

En general: A good book.

Amazon lo tiene (junto con "The Hobbit") aquí.

Notas y citas:

'And it is also said', answered Frodo: 'Go not to the Elves for council, for they will say both no and yes.'.


'Is it indeed?' laughed Gildor. 'Elves seldom give unguarded advice, for advice is a dangerous gift, even from the wise to the wise, and all courses may run ill. (p.83)



'We shall see', said Éomer. 'So many strange things have chanced that to learn the praise of a fair lady under the loving strokes of a Dwarf's axe will seem no great wonder. Farewell!' (p.429)


Eleanor Arnason - Ring of Swords



Leído entre: Oct 23, 2010 – Oct 30, 2010 (7 días).

Lo que me gustó: Nothing in particular.

Lo que no me gustó: Nothing in particular either.

En general: Para matar el tiempo... a bit on the boring side, I guess.

Amazon lo tiene aquí.

Notas y citas:

One of the things I really like about the hwarhath is you can break almost any rule, so long as you are willing to commit suicide afterward. They feel that this keeps people from developing bad habits. (p.129)


Thursday, October 21, 2010

Headphone-less... =(

Hoy se reventó uno de los 2 cables de mi audífono izquierdo. Tuve que aventarme todo el día en la oficina con música en 1 solo canal.

Llegando a la casa obviamente intenté arreglarlo. Tuve que abrirlo/semi-destruirlo, cinceleando la carcasa con un desarmador, y después de un rato logré exponer el cable que se había reventado. Intenté resoldarlo pero no tenía metal expuesto, estaba muy corto, y terminé arrancándolo del otro extremo sin querer.

Siguiente idea: reemplazarlo con cualquier otro cable. Conseguí uno, soldé el primero de los 2 extremos, y en eso se reventó el otro cable original ¬¬. Whatever, supuse que también podría reemplazarlo con cualquier otro cable. Terminé de soldar los 2 nuevos cables (llevándome de paso un poco de plástico de la carcasa), lo probé... y nada. Revisé la soldadura y no parecía haber cortos, así que supuse que el calor se había echado algún circuito (estaba soldando muy cerca del audífono en sí) y mejor cedí ante mi curiosidad de terminar de desarmar todo y ver cómo es en realidad un audífono. A mitad de eso, ya valiéndome madre los destrozos que hacía, vi que había otra terminal donde podría haber conectado alguno de los 2 cables. Ya a esas alturas intentar otra vez no era tan complicado, en vez de soldar sólo había que meter los cables en 2 agujeros del audífono y esperar que estuvieran haciendo buen contacto adentro. So I did... y otra vez nada. En ese punto ya estaban más allá de cualquier arreglo posible, así que tendré que ir buscando otros.

Sin mi cámara oficial, pero guardé un poco de evidencia. Señoras y señores, les presento... un audífono (de un par que costó 40dlls, en oferta):

[caption id="attachment_807" align="aligncenter" width="500" caption="Mi dedo. Un audífono. Una bolita de estaño."][/caption]

Tuesday, October 19, 2010

[TILAM] Dream Theater - Another Day

TILAM: Things I love about music. La nueva categoría de posts del blog.


  • Cómo conecta la voz de LaBrie con la guitarra de Petrucci en 2:57.

  • El silencio detrás de la primera nota del solo.

  • El solo.

  • El sax a lo largo de la rola.



Here. Pensaba embeberlo en la pag, pero YouTube dice Embedding disabled by request. Sidenote: que gay se ve LaBrie =S.

Monday, October 18, 2010

When Word goes Yoda on you...



"The next step was to determine why this happening was." ?????? Seriously????

Finalmente usé "The next step was to determine why this was happening", pero ¿qué tiene de malo mi versión original?

Sunday, October 17, 2010

Festival Santa Lucía - Maudits Sonnants

Ayer fui con Rafa y Lucio a ver "Maudits Sonnants" de la compañía de teatro francesa Transe Express, que se presentó como parte del Festival Santa Lucía. Estuvo bastante bien, incluso sin tomar en cuenta que era gratuito.

El setup: al centro una estructura bastante grande, como uno de esos juegos de feria con sillas voladoras y que giran, pero en vez de sillas sostenidas con cables, "stands" para 1 persona, con algún instrumento (campanas y/o tambores), en la punta de unas estructuras (que parecían) fijas; la estructura completa colgando de una grúa, pero al principio descansando en el piso. Alrededor, varias estructuras de metal que parecían plataformas para que una persona diera anuncios públicos en la época medieval.

Primero varios de los artistas se subían cada uno a una de las plataformas, prendían unos contenedores con carbón, alcohol, o alguna otra cosa flamable, que servían como antorchas para iluminar a cada uno, y se ponían a dar un mini-espectáculo: cantar, bailar, un performance de un pirata... Cada cierto tiempo otro artista en la estructura del centro tocaba una campana bajo la que estaba colgando, y los artistas alrededor cambiaban de plataforma y hacían otra vez su (u otro?) show. Esa parte se sintió muy medieval, como si fuéramos la plebe en 1700, viendo un espectáculo público jeje.













Después de 3 o 4 repeticiones de eso, en vez de cambiar de plataforma todos fueron hacia el centro y cada uno se subió a uno de los stands que ya mencioné. Ya con todos ahí, y 3 otras artistas subidas en unos trapecios que colgaban de la estructura, la grúa empezó a subirlos, y ellos empezaron a tocar sus instrumentos. A veces las luces se sincronizaban con la música, la estructura completa giraba, y las estructuras que sostenían a cada stand subían y bajaban todas al mismo tiempo, haciendo ver a la estructura como una flor enorme, con músicos en las puntas de los pétalos.















Me gustó que en esta realmente se aprecia la forma de flor.





Cerca del final, las 3 artistas en los trapecios (de hecho 2 trapecios y una cuerda elástica) hacían también un show, cada una en donde estaba (o sea, nada de intercambiar trapecios entre ellas).

Google tiene mejores fotos y videos del espectáculo que las que pude tomar yo.

Goran Petrovic - La Mano de la Buena Fortuna



Leído entre: Oct 11, 2010 – Oct 15, 2010 (4 días).

Lo que me gustó: La partida de Natalia Dimitrijevic, al comienzo y al final de la primera lectura. El uso que le da Sreten Pokimica a su habilidad, explicado en la séptima lectura. La idea de la interacción que puede llegar a tener un buen lector (y un editor) con un texto.

Lo que no me gustó: Nada en especial.

En general: Recomendable. Como dijo Rafa, "traen todo el beat los serbios".

Librerías Gandhi lo tiene aquí.

Notas y citas:

Incluso el mismo acto de abrir las tapas era precedido por el complicado cálculo de la amplitud del ángulo ideal que formarían las páginas; para algunos libros bastaba el ángulo agudo de menos de treinta grados, otros servían sólo bajo el ángulo recto, para terceros esa relación variaba de noventa y ocho a ciento catorce grados y para algunos no valía la pena abrir ni los trescientos sesenta grados. (p.56)



Con la señora Natalia Dimitrijevic iba aprendiendo que los personajes y tramas literarios no eran todo lo que se ofrecía a un lector verdadero, es decir, no eran lo más interesante. Si en algún lugar se indicaba alguna calle, de hecho, si apenas se mencionaba, Natalia Dimitrijevic sabía desviarse a alguna plaza de la que no había ni una palabra siquiera, de allí a otro callejón y luego podía entrar en un edificio y según sus ganas subir a un desván ajeno, lleno de ropa húmeda recién tendida, luego al azar hasta el primer parque, lo adivinaría inequívocamente por la frescura del aire, donde pasaría el tiempo alimentando a las tórtolas que llegaban quién sabe de dónde o simplemente se quedaría sentada junto a su dama de compañía, alejadas de los renglones usuales... (p.56)



— Bueno, qué más da. —La mujer se encogió de hombros—. Veamos lo que sabe. Observe con cuidado esa pérgola. Jamás me ha gustado. Sería tan amable de eliminarla; por supuesto, de modo que no quede un vacío.


No obstante, la pérgola de rosas tardías en plena flor era de una belleza deslumbrante. Adam sintió que cometería un pecado imperdonable si simplemente la "eliminara". Por otro lado, la orden era explícita. La señora era el cliente, si él quería conservar este trabajo, tendría que satisfacer sus exigencias...


De nuevo, no pudo calcular cuánto tiempo había pasado. Su temperatura probablemente había ido subiendo. El resfriado lo privaba hasta del aroma de las rosas. En su mente, Adam abordaba el lugar del cambio exigido desde varios ángulos, evaluaba la intervención final y lo que iba a pasar con las frases aledañas. Al fin, decidió dónde y cómo intervenir, clavó la punta de su lápiz como si fuera un escalpelo, más precisamente, la clavó como si fuera una azada, en la mera raíz de la descripción, empezó a tachar, a cambiar el orden de las palabras, a permutar las oraciones, agregó una conjunción, arrancó toda una imagen y, finalmente, juntó dos párrafos. Estaba todo sudoroso, desagradablemente sudoroso a causa de su conciencia intranquila, la pérgola con las rosas tardías había desaparecido como si jamás hubiera existido, la herida apenas se notaba, y una vez que las matas de hierba trocadas echaran raíces, no se vería ni una pizca de la triste cicatriz. (p. 73)



Con respecto al arte supremo, capaz de unir lo incombinable hasta el punto de fusión, teniendo en cuenta que en la espaciosa sala de música o, a su vez, pequeña sala de baile, había sólo un arpa, Anastas Branica no se perdía los pocos conciertos de este instrumento, intentando después recrear con palabras la gracilidad de las composiciones que allí había escuchado. A pesar de todo el esfuerzo, de las selectas expresiones líricas, aliteraciones y eufonías, de las figuras estilísticas adecuadas, del ritmo sintáctico apropiado y las pausas oportunas, a pesar de las noches de charlas con Stanislav Marzik, el ciego afinador oficial de la Orquesta de la Ópera y del Ballet de Belgrado, no lograba conseguirlo, y su trama acústica seguramente habría quedado tristemente muda si por azar no se hubiera mostrado que el arpa podía sonar por sí sola al abrir las altas ventanas del cuarto de música en los días en que soplaba el viento de oriente. En función del número de hojas abiertas de par en par, o apenas entreabiertas, se obtenía el tejido melodioso de latitudes remotas o apenas un glissando infinito de lejanos territorios. (p. 187)



En otra ocasión vi a una persona con guantes de hilo beige y una pamela parecida a la suya, con un vestido de seda cruda, a unas cincuenta páginas de distancia más adelante, junto al gran río que atravesaba el valle; me apresuré, no encontré a nadie, pero la corriente aún no se había llevado la imagen del agua junto a la orilla; me agaché, tomé el reflejo con mis dos manos juntas y sumergí mi rostro en la imagen de Natalia Dimitrijevic, con mi mejilla pegada a la suya, hasta que me atraganté (p. 277)


Friday, October 8, 2010

Things I must learn to do

La entrada que hace Sam Rockwell, como desde el segundo 15:



And improvising something like this:

Monday, September 6, 2010

Do I have to fall asleep with roses in my hands?



When you're dreaming with a broken heart
Then waking up is the hardest part
You roll outta bed and down on your knees
And for a moment you can hardly breathe
Wondering was she really here?
Is she standing in my room?
No she's not, 'cause she's gone, gone, gone, gone, gone....

When you're dreaming with a broken heart
The giving up is the hardest part
She takes you in with her crying eyes
Then all at once you have to say goodbye
Wondering could you stay my love?
Will you wake up by my side?
No she can't, 'cause she's gone, gone, gone, gone, gone....

Now do I have to fall asleep with roses in my hands
Do I have to fall asleep with roses in my hands?
Do I have to fall asleep with roses in my hands?
Do I have to fall asleep with roses in my, roses in my hands?

Would you get them if i did?
No you won't, 'cause you're gone, gone, gone, gone, gone....

When you're dreaming with a broken heart
The waking up is the hardest part

Saturday, August 14, 2010

Wii-mote project: part 1

El primer paso para hacer algún proyecto con la idea y el software de Johnny Lee está lista =D. Me tomó como 4 horas... Nada mal considerando cuánto tiempo llevaba sin usar LEDs o soldar cosas. Tuve que acordarme de que los LEDs tienen polaridad... Y no le puse resistencia, pero teniendo nada más 1.5V de entrada espero que no le pase nada... pronto.




[caption id="attachment_677" align="aligncenter" width="520" caption="Pluma infrarroja home-made"]Pluma infrarroja[/caption]

[caption id="attachment_678" align="aligncenter" width="520" caption="Pluma infrarroja home-made (detalle)"]Pluma infrarroja (zoom)[/caption]

[caption id="attachment_682" align="aligncenter" width="480" caption="Pluma infrarroja apagada"]Pluma infrarroja apagada[/caption]

[caption id="attachment_683" align="aligncenter" width="480" caption="Pluma infrarroja prendida"]Pluma infrarroja prendida[/caption]

Friday, July 2, 2010

Baño voyeurista

A falta de servicio de agua en la casa... la naturaleza (lluvia), la arquitectura y la tecnología juntos hacen un buen sustituto:

[caption id="attachment_666" align="aligncenter" width="560" caption="Baño voyeurista"]Baño alternativo[/caption]

Jane Austen and Seth Grahame-Smith – Pride and Prejudice and Zombies: The Graphic Novel

Leído entre: Jul 2, 2010  – Jul 2, 2010 (1 día... lo que causa el Huracán Alex jeje).

Lo que me gustó: zombies =D. Katana-wielding, deadly girls =D.

Lo que no me gustó: nada en especial.

En general: resulta que compré la novela gráfica (a.k.a. comic), basada en el libro. Lo cual fue bueno, porque los zombies y las peleas se disfrutan más con imágenes. Entretenido, como para leerse en una sentada esperando un avión o algo similar.

Amazon lo tiene aquí.

Notas y citas:
[Lydia Bennet... I think] — They're going to Brighton — I do so want papa to take us there for the summer! What a miserable summer else we will have! With hardly any balls to be had in Meryton!

[Elizabeth Bennet... again, I think] — Yes — a summer with so few balls would be miserable indeed — for a girl who thinks of little else.

Hay uno que otro sexual innuendo por ahí, pero ese fue tan explícito e inesperado... hasta que recapacité y me di cuenta de que hablan de balls, y no de balls. ¿O tal vez no?

Thursday, July 1, 2010

Sir James Jeans – Science & Music



Leído entre: Jun 5, 2010  – Jul 1, 2010 (26 días).

Lo que me gustó: la primera mitad, cuando habla de teoría musical, los procesos físicos detrás de los sonidos y la música, el análisis de los sonidos producidos por diferentes instrumentos. Un poco dentro de la segunda mitad, cuando habla de la relación entre el sonido y el cuarto donde se genera (reverberación, cómo la afectan los materiales y dimensiones, y las consecuencias de cambiarlos).

Lo que no me gustó: la segunda mitad, donde empieza a dar muchos números y tablas con poca utilidad para personas que no son ingenieros acústicos, donde habla de mediciones de sonido (que no es inherentemente aburrido, pero no me gustó cómo lo trata). Tampoco me gustó que le dio muy poco espacio al oído en sí, y a la transmisión del sonido al cerebro una vez que está en el oído (pero como el autor bien menciona, no es algo que se entienda muy detalladamente). Y el final... simplemente no se siente como final.

En general: recomendable para personas que disfrutan de la música y que gustan de entender los por qués de las cosas (aunque no culparía a nadie de dejarlo inconcluso después de la mitad). Recordar las clases de física de la prepa/carrera (ondas, vibraciones en cuerdas, ondas estacionarias en tubos, etc.) ayuda bastante a entender y apreciar los primeros capítulos.

Amazon lo tiene aquí.

Notas y citas:
Cases such as those just mentioned, in which there are only two or four beats to the second, do not usually produce an unpleasant sound. Indeed certain registers of the organ, such as the "voix celeste" and the "unda maris", produce the effect deliberately by the device of each note having two pipes, which are purposely put sufficiently out of tune with one another to give two or three beats a second. The voix celeste is usually constructed of string-toned pipes. Its fantastic name notwithstanding, it attempts to represent the slightly undulating sound heard when the strings of an orchestra play in unison; the undulations arise in part from the "beats" which must necessarily occur since the instruments can never be in perfect tune with one another, but in still greater part from a more subtle cause which we shall discover when we study violin tone in detail. The still more fantastically named unda maris usually consists of flute-toned pipes, and bears some resemblance to voices singing in attempted but imperfect unison. These undulations of sound endow organ tone with a certain quality of life and motion which is otherwise wanting. (p48-49)

Indeed it is a general rule that beats sound unpleasant when the number of beats per second is comparable with the frequency of the main tone. (p49)

-

Los nombres de los harmónicos de una nota (incluyendo 2 hacia abajo): Sub-octave, Quint, Fundamental, Octave, Twelfth, Fifteenth, Seventeenth, Nineteenth, Twenty-second

-
The timbre depends only on the relative energies of the various harmonics and not on their phase-differences. Differences of phase produce no effect on the ear. This is known as Ohm's law, having been discovered by G. S. Ohm (1787-1854), the discoverer of the still better known electrical law.

The second harmonic adds clearness and brilliance but nothing else, it being a general principle that the addition of the octave can introduce no difference of timbre or characteristic musical quality.

The third harmonic again adds a certain amount of brilliance because of its high pitch, but it also introduces a difference of timbre, thickening the tone, and adding to it a certain hollow, throaty or nasal quality, which we may recognise as one of the main ingredients of the clarinet tone [...].

The fourth harmonic, being two octaves above the fundamental, adds yet more brilliance, and perhaps even shrillness, but nothing more, for the reason already explained. The fifth harmonic, apart from adding yet more brilliance, adds a rich, somewhat horn-like quality to the tone, while the sixth adds a delicate shrillness of nasal quality.

As the table on p.73 shews, all these six harmonics form parts of the common chord of the fundamental note, and so are concordant with this note and with one another. The seventh harmonic, however, introduces an element of discord; if the fundamental note is c', its pitch is approximately b[flat]''', which forms a dissonance with c. The same is true of the ninth, eleventh, thirteenth, and all higher odd-numbered harmonics; thees add dissonance as well as shrillness to the fundamental tone, and so introduce a roughness or harshness into the composite sounde. The resultant quality of tone is often described as "metallic", since a piece of metal, when struck, emits a sound which is rich in discordant high tones. (p87)

-
We found that when a stretched string is plucked at its middle point, the second and fourth harmonics are absent from the sound produced, whereas if it is plucked at some other point, these harmonics are present.

The second and fourth are, however, the harmonics which above all others impart clearness and brilliance to the tone, so that the note given out by the plucked string will be deficient in these qualities. It will have a rather hollow, nasal quality, reminiscent perhaps of the tone of a clarinet or a stopped organ-pipe, since the tones of both of these consist mainly of odd-numbered harmonics. This seems to suggest that the quality of tone emitted by a string depends on the point at which we pluck or strike the string, and harmonic analysis (p.78) proves that this is so.

The middle point of a string is a node for all even-numbered harmonics and a loop for all odd-numbered harmonics, so that if we excite a string at its middle point, all the even-numbered harmonics, including the octave, super-octave and all higher octaves, will be missing from the sound produced (the result already obtained), while all the odd-numbered harmonics will be present in their maximum strength. In the same way we see that if we excite a string at a point a third way along its length, the third harmonic will be missing, but the second (octave) and fourth (super-octave) will be fairly strong, giving a clear brilliant tone. If we excite the string a quarter way along, the second harmonic will be heard in full strength but the fourth will be entirely missing, while the third and fifth will appear, but weakly. (p89)

-

Talking about violin playing and how the bow pulls the string, until it cannot hold it anymore and the string goes back to its position, overshoots, and is again trapped by the bow that keeps pulling in the original direction:
Each time that the bow loses its grips on the string, as well as each time that it resumes this grip, the vibration of the string undergoes a sudden change in phase. Thus, if two violins are playing in unison, the difference in phase of their two vibrations changes repeatedly, so that the sounds they emit may reinforce one another at one instant, but enfeeble one another at the next (p.39). Thees frequent alternations of loudness cause the "beating" or undulating effect which is characteristic of string playing in unison, even when they are perfectly in tune with one another. (p102)

-
Helmholts shewed that the strength of the various harmonics must always be in the ratio od 1:1/4:1/9:1/16:etc, whatever the point at which the string is bowed.

...

No matter where the string is bowed, the first, third, fifth and other odd-numbered harmonics occur in the same strength as in a string plucked at its middle point, but the second, fourth, sixth and other even-numbered harmonics, instead of being completely absent, are present in full strength, with the result that the bowed string has a fuller, more brilliant and richer tone than the plucked string. (p102-103)

-
The string may be bowed anywhere from a seventh to a fifteenth, but is usually bowed at a ninth or tenth, of its length from the bridge —more in piano passages, and less in forte passages. If it is bowed sul ponticello —i.e. close up to the bridge— the bow does not lie over any nodes except those of very high harmonics, so that moderately high harmonics are produced in full strength, and the note has a metallic sound. (p103-104)

-

Talking about the body of the violin:
Its free vibrations are of high pitch, and as many of them coincide in frequency with harmonics of the notes produced by the strings, these particular vibrations may be much reinforced by resonance. It is their presence that gives the instrument its peculiar tone or timbre. Such a group of frequencies is known as a "formant". (p104)

-
Backhaus has examined the frequencies of the body vibrations of a first-class Stradivarius, and finds that the majority are fairly evenly distributed between 3200 and 5200. In other violins the frequencies are usually lower and also less evenly distributed. (p104)

-
The fact that the speed of sound varies with the temperature entails important practical consequences. We have seen that the period of vibration of a column of air is proportional to the time sound takes to travel over the length of the column. If the air is warmed, sound travels faster and the period becomes less. It follows that the pitch of all wind instruments is raised when temperature rises, or when they are taken into a warmer atmosphere. This explains why the instruments of an orchestra must be tuned afresh each time the temperature changes. Before a concert the tuning is performed in the concert hall itself, so that the various instruments will be in tune with one another in the actual air in which they are to be played, and, for the same reason, the players of wind instruments breathe into their instruments before tuning them. (p120)

-
When the wind or a blast of air encounters a small obstacle, little whirlwinds are formed which are the exact counterparts of the whirlpools which are formed when a stream of water strikes a rock. There is a steady flow of air in front of the obstacle, and a steady train of whirlwinds behind it. These whirlwinds are formed on the two sides of the obstacle alternately; as soon as one comes into existence, it begins to drift away in the general current of air, thus making place for others which are formed in turn behind it.
...
When whirlwinds are formed by the wind streaming past an obstacle of any kind, the formation of each little whirlwind gives a slight shock, both to the obstacle and to the air in its neighborhood. If the wind blows in a continuous steady stream, these shocks are given to the air at perfectly regular intervals. We may then hear a musical note — it is what is often described as the "whistling of the wind", or the "wind whistle". Its pitch is of course determined by the frequency of the shocks to the air, and this is the number of whirlwinds formed per second. (p126)

-
Then Helmholtz (1862) developed a theory of consonance and dissonance in terms of beats — a theory which has been much discussed and criticised [sic], but still holds the field to-day. We have already seen that C and C# sound badly together because they make unpleasant beats. In the case of wider intervals, such as C and F# there are no beats to be heard, either pleasant or unpleasant, but Helmholtz asserted that C and F# sound badly together because certain of their harmonics (e.g. g' and f'#) make unpleasant beats. On the other hand C and G sound well together because few of their harmonics beat badly: [...] indeed many harmonics are common to both notes. (p157)

-
In time, however, the idea must have occurred to sing or play two or more notes at once — possibly because it was impossible for men and boys to sing together in the same pitch, or possibly because on-part music began to pall. [...] from now on it was important that two or more notes of the scale could be sounded together without undue dissonance. Even to-day, many of the races which have not advanced beyond homophonic music —as for instance the Arabs, Persians and Javanese— use scales whose notes are not at all consonant; the dissonance is harmless because two notes are never heard together. On the other hand, even primitive races whose music is polyphonic use scales in which most intervals are consonant. (p161)

-

La secuencia de la que habla (F-C-G-D-A...) es la de "perfect fifths".
By stopping at different places in the sequence F-C-G-D-A-..., we obtain the various scales which have figured in the music of practically all those races which have advanced beyond the one-part music of primitive man.

The first three notes of the sequence C, F and G formed the main tones of the scale of ancient Greece. If we proceed as far as five notes C, D, F, G, A we have the pentatonic scale in which a considerable amount of Chinese and ancient Scottish music is written, as well as much of the music of primitive peoples in Southern Asia, East Africa and elsewhere; transpose it a semitone up, and we have the scale provided by the black keys of the piano — hence the fact, beloved of school-children, that many Scottish melodies, "Auld Lang Syne", etc., can be played without touching the white keys at all, and that almost any sequence of notes strummed on the black keys sounds like a Scottish melody. On taking the first seven notes, we have the ordinary diatonic scale, which seems to have been introduced into Greece in the middle of the sixth century B.C., was standardised [sic] by Pythagoras, and has remained the normal scale for western music ever since. (p164)

-
Plato tells us, for instance, that the Lydian mode (our modern major mode!) was specially associated with sorrow; it and the closely associated Ionian mode, which only differed from it in b[flat] replacing b, were also the modes of softness, relaxation, self-indulgence, and even drunkenness. The Dorian and Phrygian modes on the other hand were —so he tell us— associated with courage, the military spirit, temperance and endurance. Because of this association, Plato would have permitted only the Dorian and Phrygian modes to be employed in his ideal republic, the Lydian and Ionian modes being prohibited. (p180)

-
When we compare two scales in major keys with one another, we find that, unless the tuning is that of equal temperament, the octave is still divided into its seven intervals by slightly different steps, and the question is whether this slight difference is perceptible to the trained musical ear, and if so, whether it has an appreciable influence on the emotional qualities of the music.

Many musicians, including Berlioz, Schuman and Beethoven, seem to have believed that both questions must be answered in the affirmative. We find Beethoven writing of B minor as a "schwarze tonart", describing Klopstock as "always maestoso — Db major", changing the key of a song in an effort to make it sound amoroso in place of barbaresco, and so forth.

Sunday, June 13, 2010

Hearing test

Realmente solo lo estoy posteando para futura referencia. Es un buen test para hacer una prueba muy básica de la calidad de equipos de audio (incluyendo audífonos). And to boot, como comprobante de que mi rango auditivo sigue intacto en 20Hz-20kHz =D.

http://www.rhintek.com/tutorial/Frequency/index.php

Friday, June 11, 2010

Random pictures

Las cositas de plástico molestas que trae la ropa nueva, tienen nombre:




[caption id="attachment_638" align="aligncenter" width="576" caption="Plastiflechas"]LPlastiflechas[/caption]

Porque nunca se puede especificar demasiado lo grande que es un burrito (tomada en El Taco Tote — que sorprendentemente tiene tacos bastante decentes para estar allá — durante el viaje familiar a San Antonio):




[caption id="attachment_639" align="aligncenter" width="432" caption="Burrotote Huge - because you can never be too big"]Burrotote Huge[/caption]

Wednesday, June 9, 2010

Porcupine Tree - Drown with me

Canción que acabo de sacar en la guitarra. Completely by ear, I'm gettin better at it =P.



For the record: como la saqué originalmente, el intro y las estrofas van acompañados de B - F#m - G - C - F#; lo que se podría decir que es el coro (Tyre tracks fresh...) va con E - C - G - D - A (2 tiempos) - C - F#. Los tiempos están fáciles de sacar a partir de la canción.

Luego de tenerla completa, la busqué en internet y vi que hay una forma más fácil de tocarla, que además suena un poco más parecida a lo que toca PT, así que me quedé con esa versión. [Paréntesis... acorde Hsus4 ? H? WTF?]

Y para terminar, la letra:

So you have been of use
And you have been abused

You know you look pale today
Your lipstick has gone astray

You sold out and lost your looks
You gave away all your books

(You should drown with me)

Your coil has been wound up tight
Unwind it with me tonight

(You should drown with me)

Tyre* tracks fresh on the ground
Where she will be found
Held under the water
Resting there in a stream
View from the cold water
Buried in green
Orange filter sky

Your drowning in family there
When will you come up for air

(You should drown with me)

Don't feel you let 'em down
Cos they have already drowned

(You should drown with me)

*Tyre (british for tire)

Monday, June 7, 2010

Zombie-based business idea

Gisel B. says (10:44 PM):
*they are just right behinf russians
alejandro says (10:44 PM):
*los rusos sí son zombies?
Gisel B. says (10:45 PM):
*f course
*but they have plenty of space to wander
*and you cant notice the body temperature drop
alejandro says (10:45 PM):
*jajajajaja
alejandro says (10:46 PM):
*me convenciste :P
Gisel B. says (10:46 PM):
*since everyone is already forzen
alejandro says (10:46 PM):
*sí, very true
*atravesar rusia a velocidad zombie..... debe de tomar un buueeeeeeeen rato jaja
Gisel B. says (10:47 PM):
*aparte
*it is cold and snowy
*that makes them slower
*so
*it is easy to kill them
*it is actually a sport
Gisel B. says (10:48 PM):
*like
*it is zombie season
*lets go kill some and stuff like that
alejandro says (10:48 PM):
*jajajajajajajaj
*we must go on vacation then :D
*sería como un real-life adventure theme park.... "sobrevive a los zombies"
Gisel B. says (10:48 PM):
*it is a Xtreme sport
alejandro says (10:48 PM):
*"live your own 28 days later"

I've got the best girlfriend ever =D

Saturday, May 15, 2010

Mi nueva adquisición

Muy cool, suena conmadre y me gustó bastante el diseño =D

Guitarra (1)


Guitarra (2)

Wednesday, May 5, 2010

Aprendiendo teoría musical, Vol. 1

Ok, ahora sí un intento para realmente aprender algo de teoría musical. Empecé con esto. Me puse a entenderlo, y experimentar con ese conocimiento. Parte de lo que deduje/aprendí está reflejado en este post.

La "posición básica" para una triada mayor con raíz en la 5ta cuerda es:

[caption id="attachment_584" align="aligncenter" width="437" caption="Posición básica para triada mayor con raíz en la 5ta cuerda"]Posición básica[/caption]

Esta posición puede irse recorriendo sobre las mismas 3 cuerdas para tocar todas las triadas mayores. Limitándonos al rango de los primeros 12 trastes, la única que no se puede tocar es "si" (de aquí en adelante, a la posición mostrada arriba le voy a decir "forma canónica" de una triada mayor):

[caption id="attachment_596" align="aligncenter" width="547" caption="Forma canónica de las triadas mayores (do -> la)"]Triadas mayores[/caption]

Esto se deduce recorriendo la raíz desde Do —en el 3er traste— hasta la nota que nos interesa como raíz, siguiendo la escala cromática (las 7 notas con sus respectivos sostenidos/bemoles, 12 notas en total). Así se pueden tocar incluso Do# mayor, Re# mayor, etc.

Ahora la idea es buscar todas las posibles formas de tocar la triada mayor de cada nota en los primeros 12 trastes de la guitarra, con la restricción de no usar inversiones; es decir, el orden de las notas, al tocarse "ascendentemente" (de la más grave a la más aguda) debe ser el mismo que el de la triada canónica (Do-Mi-Sol, en el caso de Do; nada de Do-Sol-Mi, o Sol-Mi-Do). Además, descartamos posiciones que requieran 2 notas en la misma cuerda. Esto nos lleva a:

[caption id="attachment_586" align="aligncenter" width="562" caption="Triadas canónicas de Do"]Triadas canónicas Do[/caption]

[caption id="attachment_587" align="aligncenter" width="562" caption="Triadas canónicas de Re"]Triadas canónicas de Re[/caption]

[caption id="attachment_588" align="aligncenter" width="562" caption="Triadas canónicas de Mi"]Triadas canónicas de Mi[/caption]

[caption id="attachment_589" align="aligncenter" width="562" caption="Triadas canónicas de Fa"]Triadas canónicas de Fa[/caption]

[caption id="attachment_590" align="aligncenter" width="562" caption="Triadas canónicas de Sol"]Triadas canónicas de Sol[/caption]

[caption id="attachment_591" align="aligncenter" width="562" caption="Triadas canónicas de La"]Triadas canónicas de La[/caption]

[caption id="attachment_592" align="aligncenter" width="562" caption="Triadas canónicas de Si"]Triadas canónicas de Si[/caption]

Está bastante claro que todo simplemente se está recorriendo, y cuando se "sale" del rango de trastes 1-12, luego reaparece del otro lado.

Partiendo de estas formas canónicas posibles, con un poco de imaginación se puede ver que de aquí salen las formas populares de casi todos los acordes mayores (o al revés, que casi todas las formas populares de los acordes mayores tienen embebida la forma canónica de la triada mayor correspondiente):




[caption id="attachment_586" align="aligncenter" width="562" caption="Triadas canónicas de Do"]Triadas canónicas Do[/caption]

[caption id="attachment_618" align="aligncenter" width="562" caption="Triadas mayores convertidas a formas populares de acordes mayores"]Conversión triadas a acordes[/caption]

Las formas populares de Fa y de Si son corrimientos de las de Mi y La, respectivamente. Entonces ya están cubiertos Do, Mi, Fa, Sol, La, Si. El que falta, Re, lo veré en otro post.

Tuesday, April 13, 2010

New song I'm working on learning



Around... 80% now. Pero una de las cuerdas de mi guitarra tronó mientras la afinaba ¬¬, así que tengo que conseguir otro juego para poder seguir practicando.

Sunday, April 11, 2010

Quote

Seen in the series "Broken Saints", which I bought one time just-because.
The very powerful and the very stupid have one thing in common: they don't alter their views to fit the facts, they alter the facts to fit their views... which can be uncomfortable, if you happen to be one of the facts that needs altering.

- Doctor Who.

Sunday, April 4, 2010

Precaución!

Camioneta con letrero de "Exceso de dimensiones"


"Nuestros vehículos viajan en cinco dimensiones espaciales y dos temporales para su mayor comodidad."

Saturday, April 3, 2010

La versión original de "What a wonderful world"



Lo mejor es cómo las expresiones SÍ coinciden con el feeling de la canción jajaja.

Via Gran Angular.

Friday, April 2, 2010

Quote

And the wild regrets and the bloody sweats
None knew so well as I...
Than he who lives more lives than one,
More deaths that one shall die.

Oscar Wilde

Monday, March 29, 2010

Fixing the blog remotely

First use of cygwin and ssh to connect to my computer remotely and fix the blog =D. Just had to restart mysql... yet again, something happened with its socket file.

Sunday, March 28, 2010

Learning Apache's minutiae

When using mod_userdir (to allow/disallow each/some user(s) to expose files through requests like http://myDomain.com/~myTestUser/exposedFile.txt), Apache needs --x permissions on the /home/myTestUser directory (directory in accordance with the example) in order to serve the requests. Otherwise you will get a 403 Forbidden error when trying to access them.

Related to this, if UserDir is disabled for a user (or the user doesn't exits), Apache will return a 404 Not Found error, instead of a 403 Forbidden.

Back to Linux

Después de descubrir que la versión más reciente de Arch (Linux) por default trae un kernel que tiene un problema para cargar mi tarjeta de red, antier tuve que re-aprender cómo se compilaba e instalaba un kernel de Linux from scratch. Tuve que bajarlo en otra computadora, y luego pasarlo por USB a la nueva, porque pues sin tarjeta de red cómo lo bajo ¬¬.

Pero ya quedó instalado, ya le instalé el ambiente gráfico, VirtualBox para instalar Windows adentro de Linux, ya logré instalar Windows, hacer que se comunique con el SO host... Lo único malo hasta ahorita es que parece que TightVnc no se lleva bien con KDE 4 cuando quiero iniciar una sesión remota. ¿Conseguir otro server/cliente de VNC? ¿Cambiar KDE por Gnome?

Saturday, March 20, 2010

Adventures of a developer

It's amazing how much one can learn from very short texts.

I read this post that I had put in my "to read [when you have time to really pay attention and think about what you're reading]" list a long time ago, and was surprised by the amount of content and learning that can be obtained from it. This is a sample of what I'm talking about:

  • Backpropagation algorithms: term taken from Artificial Intelligence, used in this context to trace who clicked on ads, to monitor their effectiveness.

  • Firebug: Firefox extension that allows the user to see and edit (seeing the results in realtime) the HTML, CSS, javascript, etc, of a webpage. You can also monitor requests made by the page, including their response times and responses. Extremely useful for web developers.

  • XMLHttpRequest (also referred to in the post as XHR): type of request used in AJAX to allow for dynamic retrieval of content (without the need to refresh the page).

  • 204 http responses: "No Content" responses for web requests.

  • Accepts header: part of an http request that specifies what does the request expect as a response (if I request an image, I wouldn't expect to receive text content in response).

  • Pixel tagging: one of many ways of monitoring webpage views and user behavior in websites.

  • "Or"-ing functions in javascript: I'm not even sure of how this works, but it seems to be combining 2 functions into one that will be later used to apply both at the same time (a=encodeURIComponent||escape).

  • Regular expressions: (/#.*/, matching "#[whatever]" and /\+/g, matching "+[whatever is in parameter g]", if I'm not mistaken).


Developers who analyze code written by others can also relate to the post because of the way in which Ryan (the author) writes how he arrived at his discoveries:
So I cracked open Firebug, did a search and watched the Console tab while I clicked a link. I was expecting to see a nice little XMLHttpRequest go across the screen… and didn’t.

The always useful trial and error.
A call to clk() in the console tab just returned true, so off to the source for clk() I went. Cmd+U… Cmd+F… ‘clk’…:

More trial and error. "Exploring" a function with quick & easy calls to it. Look for the actual code to understand what it's doing. A bit of developer background to know that he 1) conjured up the source code of the webpage (Cmd + U), 2) wanted to find something in it (Cmd + F) and 3) typed it ('clk'). Also, that he's a Mac user, as evidenced by Cmd and not Ctrl.

Even without understanding the fine details of what Google's doing there, I understand the overall idea, and I'm a bit impressed of how something that looks so "hackish" is at the heart of their ad-monitoring system (I think?).

Sunday, March 14, 2010

David S. Richeson - Euler's Gem

Read from-to: Feb 19, 2010  - Mar 14, 2010 (24 days).

Liked: ...it's math, what's not to like?


Didn't like: al final se pone un poco denso y pierde un poco las ayudas visuales (que es entendible, hablando de n-dimensiones no sirven de mucho, pero hay algunas que no son tan triviales de entender con la poca explicación que da).

Overall: nice book =D.

Get it here.

Notes & Quotes:
"Mathematical folklore says that he [Euler] could write mathematics papers while bouncing a baby on his knee, and that he could compose a treatise between the first and second calls to dinner" (p.16)

"Later he [Pythagoras] settled in the Greek city of Croton in what is now southern Italy" (p.37).

Italia? Interesting...
"I hope that posterity will judge me kindly, not only as to the things which I have explained, but also to those which I have intentionally omitted, so as to leave to others the pleasure of discovery" - Rene Descartes (quoted in p.81).

Riiiiiiiight jaja.
There is a oft-repeated quip that "objects in mathematics are named after the first person after Euler to discover them" (p.86)

Jaja THAT's fame.

La prueba de Legendre [JAJAJA la caricatura en wikipedia =P] de la fórmula de Euler, en el capítulo 10 (pp.87-99)... wow. Beautiful. Too long to transcribe though.
G. H. Hardy wrote "Reductio ad absurdum, which Euclid loved so much, is one of a mathematician's finest weapons. It is a far finer gambit than any chess gambit; a chess player may offer the sacrifice of a pawn or even a piece, but a mathematician offers the game" (p.123).

"Ok, you win, it is false. But HA! That means it's true! IN YOUR FACE!"
Any knot can be obtained as the boundary of an orientable surface with one boundary component (p.185).

Mathematicians work in a store that makes and sells tools. Occasionally they take special orders from their scientific customers, but most of the day they toil away making elegant tools, the uses for which have not yet been invented. Scientists visit this tool shop and browse the shelves in hopes that one of the tools fits their needs (p.201).

Nice description.
Poincaré had a restless curiosity that kept him moving from topic to topic. He would attack a new area of mathematics, make an indelible mark, then move on the the next. A contemporary called him "a conqueror, not a colonist" (p.212).

Otra buena descripción.

Saturday, March 13, 2010

Back to learning music

Hace un buen rato que no aprendía a tocar alguna canción nueva. Cuando estoy cerca de un instrumento —a veces es mi guitarra, a veces el piano en casa de mi tía— y traigo alguna melodía en la cabeza, me da por intentar "transcribirla" y tocarla, pero por lo general no pasan de ser sesiones de 5 min o menos, que terminan sin importar si tuve o no éxito en mi intento.

A diferencia de eso, hoy busqué el tab de Trains (Porcupine Tree), que tenía finta de no ser muy complicada, y efectivamente el 90% de la canción salió sin problemas tocando del tab a primera vista. El solo y un bridge fueron lo único que tuve que ponerme a sacar de oído, pero después de un rato salieron (wu! =D) and now I'm happy to say there's a new song in my repertoire! Una que disfruto mucho escuchar, y ahora también tocar. Great way to end the day.

When the evening reaches here, you're tying me up... I'm dying of love... it's ok...

Monday, March 8, 2010

Learning about my limitations

Hoy leí el post Hearing the Uncertainty Principle, que aparte de estar interesante me dio la excusa... ejem... explicación, perfecta, de por qué me es mucho más difícil sacar de oído melodías rápidas que melodías lentas. Y dejando al ego de lado, por qué es más difícil sacar de oído melodías rápidas que melodías lentas. It seems obvious enough, pero tener un por qué siempre es bueno. Entre más larga sea una onda en el tiempo, más angosta su representación en frecuencia, y entonces se parece más a una nota pura. Notas muy cortas en el tiempo implican un espectro de frecuencias mucho más amplio, que hace bastante más complicado determinar cuál es la frecuencia (nota) principal del sonido.

Ta-ran!

Saturday, March 6, 2010

Analogy on software engineering & PEBKAC

Leyendo los comentarios de un post de reddit donde Peter Norvig (director de investigación en Google) contesta preguntas hechas por la comunidad me encontré este (contexto: Norvig habla de la diferencia entre Civil Engineering y Software Engineering, y construir puentes VS construir programas):
Imagine that one day, one of your users (a driver) decides to drive off the bridge. In civil engineering, it isn't your fault, it's his. In Software, it is your fault. You would have to have thought about a way of preventing that. Thats akin to saying that when a driver is about to drive off a bridge, a huge rubber wall should instantly appear bouncing him into the bridge again. This wall should have the message "The operation you tried to do is not allowed".

En otras palabras, el problema del desarrollo de software es que en caso de PEBKAC (Problem Exists Between Keyboard And Chair), la culpa recae sobre el programador en vez de sobre el Between-Keyboard-And-Chair. Maldito mundo injusto =P.

La "entrevista" completa de Norvig está aquí. El comentario original acá.

Thursday, March 4, 2010

Definición de "fama"

There is a oft-repeated quip that "objects in mathematics are named after the first person after Euler to discover them".

Need I say more?

Saturday, February 20, 2010

Neil Gaiman - The Graveyard Book

First post in the "Books I've read" series/category.

Read from-to: Feb 4, 2010 (aprox) - Feb 18, 2010 (14 days).

Liked: the Macabray related verses (Time to work and time to play, time to dance the macabray; step and turn and walk and stay, now we dance the macabray)

Didn't like: it's much more like a child's story than I expected (especially after reading Sandman... awesome comic).

Overall: not too long, finished half the book in one chunk... mildly entertaining. Didn't meet my expectations.

Friday, February 19, 2010

Video. Just sharing.

Entre mis feeds encontré este video, que está largo pero entretenido e interesante, sobre todo la parte que empieza en el 20:57 aprox.

Thursday, February 18, 2010

Kiss a lover, dance a measure...

find your name,
and buried treasure...

- from Neil Gaiman's The Graveyard Book

Tuesday, February 16, 2010

Friday, February 5, 2010

Poetry

Brilliant. Sublime. So much emotion.

Enjoy.

Alguien debería escribir un libro así.

Sunday, January 31, 2010

Notes on SQL 9

Previous related posts:

XML

FOR XML _____:

  • RAW: returns each row as an XML element and each column as an XML attribute (<row ClientID="13" Name="Fake client name" />). Aliases can be used for columns, using RAW('element_type') causes the rows to be "named" element_type (instead of "row" in the example), adding ROOT('root_name') wraps everything in <root_name> </root_name> tags, and adding ELEMENTS causes each column to be listed as its own element instead of an attribute. By default, NULL values are not included as attributes in the XML element (or as XML elements if the ELEMENTS directive is used), but adding the XSINIL directve to the ELEMENTS directive adds an "xsi:nil="true"" attribute for elements whose corresponding columns have NULL. As a side-effect, a namespace is added to the root element in the XML, since that's where the nil attribute is declared.

  • AUTO: supports basic ("single-child") hierarchies. The hierarchy is created based on the order of the columns in the SELECT statement (not the order in which the tables are referenced). Each table referenced, though, gets its object in the hierarchy, named after the alias used for the table. The order of the rows in the result determines how the hierarchy is built, so ORDER BY clauses are important when using this mode.

  • EXPLICIT: the ELEMENTS and XSINIL directives do not exist for this mode. ORDER BY is important to construct the result, just as in AUTO mode. Any XML structure (even some not supported by the PATH mode) can be created, by using specific aliases for the columns (e.g. "Parent", "Customers!1!!element", "Customer!2!Id", "Order!3!OrderDate"). A tag and a parent column are necessary; the first one uniquely identifies an XML element in the result, and the second specifies the tag of the parent element (or NULL).

  • PATH: the ELEMENTS and XSINIL directives do not exist for this mode. Preferred mode. Using certain syntax in the column aliases, you can generate XML structures:


SELECT
c.ClientID as "@Id"
,c.Name as "@ClientName"
,c.RowGuid as "comment()"
,CAST('<Test/>' as XML) as "node()"
,c.ClientType as "AdditionalInfo/@Type"
,c.ModifiedDate as "AdditionalInfo/text()"
FROM dbo.Customer AS c
FOR XML PATH('Customer'), ROOT('Customers')


Results in:

<Customers>
<Customer Id="1" ClientName="Fake client 1">
<!-- 3ACB432D-B87D-4AED-95B4-C3019DA348B1-->
<Test />
<AdditionalInfo Type="S">2007-10-10T10:00:00.123</AdditionalInfo>
</Customer>
</Customers>


When nesting FOR XML queries, the TYPE declarative must be added at the end of each subquery, so the XML is not interpreted as a string.

A custom namespace can be included by preceding the query with a WITH XMLNAMESPACES clause.

XML Data Type

Typed XML attaches a schema collection to a column to verify its contents. You create a schema collection with the CREATE XML SCHEMA COLLECTION statement. When declaring XML columns for a table, just "XML" means untyped, or a schema collection can be indicated in parenthesis. Also inside those parenthesis, the DOCUMENT option forces the column to support only XML documents (not fragments).

A disadvantage of typed XML columns is that if a modification must be done to the schema, all columns that use it must be changed to use untyped XML (costly due to differences in internal representation) and updated so they comply with the new schema, the schema dropped and recreated, and then the columns converted back to it (costly again).

The XML data types provide methods to use them:

  • EXIST: obvious.

  • VALUE: retrieves a single, scalar value from somewhere in the XML.

  • NODES: converts XML into a tabular form.

  • QUERY: used to return an XML fragment.


CLR

Usage of CLR within the database requires that the SQL Server instance allows CLR code to run (EXEC sp_configure 'clr enabled', 1; RECONFIGURE;). Once the (VB.NET/C#) code is compiled into an assembly, the assembly must be loaded into SQL Server and a database object must be created and pointed to the loaded assembly using DDL.

The SqlContext and SqlPipe classes (in the Microsoft.SqlServer.Server namespace) must be used for command execution, since they are used to communicate to the SQL Server session within which the code will execute.

To load a compiled assembly (dll) into the database, the CREATE ASSEMBLY statement is used (CREATE ASSEMBLY AssemblyNameInDB FROM 'assembly_path_in_the_filesystem'). The dll file is no longer needed since the assembly is copied into the DB (the sys.assemblies catalog view contains information about existing assemblies).

An example of a SP that calls a CLR assembly is the following:

CREATE PROCEDURE ExampleSP @Parameter1 INT AS EXTERNAL NAME AssemblyName.[ClassNameWithNamespace].MethodName

ClassNameWithNamespace is enclosed in brackets (it could have been quotes) because it probably contains periods, which are not part of a valid identifier in SQL Server.

Source code can also be stored in the DB, like this:

ALTER ASSEMBLY AssemblyNameInDB ADD FILE FROM 'source_code_path_in_the_filesystem'

CLR Scalar UDFs

The SqlFunction attribute is required on the method. You can specify IsDeterministic, and IsPrecise (if it uses any floating point arithmetic, then this is false).

CLR Table-valued UDFs

2 methods are needed: the one that is called from SQL Server (decorated with an attribute like [SqlFunction(FillRowMethodName = "OtherMethodName", TableDefinition = "Column1 INT, Column2 NVARCHAR(100)" )]), which uses yield return to "generate" each row in the result, and the one that fills each row that gets returned ("OtherMethodName"). The second method always receives one object parameter (which is whatever the "yield return" statement was called for in the first method), and the same amount of OUT parameters as columns in the output table definition (these will be the actual column values).

CLR triggers

Similar to CLR SPs, but you can use the TriggerContext class in SqlContext. to perform trigger-specific checks.

CLR User-Defined aggregates

An entire CLR type (class/struct) must be created, so the aggregate can accomplish this:

  • Initialize: by using the Init method of the defined CLR type.

  • Add another value to the calculation: with the Accumulate method.

  • Combine itself with another instance of the same aggregate: with the Merge method.

  • Return its result: with the Terminate method.


The decorating attribute SqlUserDefinedAggregate can specify if serialization should be handled automatically or by the user (that creates the code), if an empty input returns NULL, if duplicates matter, if NULLs matter, if order matters, and the maximum size of the serialized structure.

CLR User-Defined Types

The attribute SqlUserDefinedType can define who handles serialization (see CLR User-Defined Aggregates), a method to Validate integrity when a binary type is casted to the UDT, if the type is byte-ordered (SQL Server only supports byte sorting, so you should be VERY CAREFUL when implementing this), if it is of fixed length, and its max size. It must implement the INullable interface. Parse and ToString methods are required. More details here.

The following permission sets can be used for CLR assemblies:

  • SAFE: not allowed access to any resources outside the DB to which it is deployed.

  • EXTERNAL ACCESS: allowed to access resources outside the local SQL Server instance, such as another instance, the file system, or even a network resource.

  • UNSAFE: allowed to execute non-CLR code (e.g. Win32 API or a COM component).


Filestream

Option for columns of the varbinary(max) data type. Allows SQL Server to store data for those columns in separate files in the file system. To enable filestream usage, use EXEC sp_configure 'sp_filestream_access', (1|2|3). 1 allows only T-SQL access to the filestream data; 2 allows direct file-system access; 3 allows access through a network share. A filegroup that contains a Filestream database is also required.

Usage requires the table to have a UNIQUEIDENTIFIER column with the ROWGUIDOL property and a Unique constraint on it.

Deleting of filestream data is done with a garbage collector, not necessarily at the moment when the UPDATE/DELETE statement is executed.

Notes on SQL 8

Previous related posts:

Query performance and tuning

Main performance metrics: Query Cost, Page Reads, Query execution time.

Theoretical execution order of a query without UNION clause:

  1. FROM, JOIN, APPLY, ON

  2. WHERE

  3. GROUP BY and aggregate functions

  4. HAVING

  5. SELECT

  6. ORDER BY

  7. TOP

  8. FOR XML


For queries with a UNION clause, the theoretical execution order is:

  1. FROM, JOIN, APPLY, ON

  2. WHERE

  3. GROUP BY and aggregate functions

  4. HAVING

  5. TOP (note that in this case it is executed BEFORE the ORDER BY clause)

  6. UNION and SELECT

  7. ORDER BY

  8. FOR XML


The reason for the difference is that TOP is not ANSI/ISO SQL standard-compliant. This can cause a query to return incorrect results if care is not taken.

General ideas for query tuning:

  • Try not to apply UDFs to columns since this prevents indexes from being used (a table scan must be performed so the UDF is applied to every row).

  • Correlated subqueries can normally perform faster if substituted with CTEs (WITH (<blabla>) as A, SELECT * FROM A).

  • Scalar-valued UDFs can perform faster if defined inline in the query (instead of being function calls), because in that case they can be optimized.

  • Inline table-valued UDFs are just like views with parameters, so they're optimized; multi-statement table-valued UDFs are like SPs that populate temporary tables for the query, and they must be executed fully before the outer query can use the results. CLR table-valued UDFs stream their results (by using yield return statements).

  • Avoid cursors whenever possible.


Indexes

A covered index is one that contains all the columns referenced in a query (in any SELECT, JOIN, WHERE, GROUP BY, HAVING, etc, clauses). When this is the case, the index can be used and no further lookups need to be done to the actual rows (in the case of a non-clustered index). Since a clustered index contains all the columns, it is by default a covered index.

When defining an index, columns can be specified as part of the index's key, or as included columns. The latter cannot be used for tasks such as filtering or sorting, they're useful only if they need to be displayed in a query which makes use of the index based on its key.

Partitioning

Requires a partition function, that defines the values where each partition ends, and a partition scheme, which defines on which file group each partition goes.

When creating partition functions (CREATE PARTITION FUNCTION), you specify if the partition values are to stay in the left group, or the right one (<= or <). When creating partition schemes (CREATE PARTITION SCHEME), you define to which filegroup does each partition goes to. You know how many partitions there are because the partition function's name is used in the statement. You can assign all partitions to the same file group in one go.

Existing tables are moved to a partition with ALTRE TABLE SourceTable SWITCH TO PartitionedTable PARTITION n. A check constraint must be added first to guarantee that the partitioned column satisfies the values accepted in this partition.

Notes on SQL 7

Previous related posts:

Triggers

DML VS DDL triggers.

The order of trigger execution (when several are defined) can be modified with the sp_settriggerorder system SP.

A trigger only executes once regardless of the number of rows affected (e.g. DELETE FROM TableName deletes all rows in the table, but only causes a FOR DELETE trigger to execute once).

The affected rows (inserted/deleted) are available in the inserted and deleted special tables inside the trigger definition.

DDL triggers can be specified at the instance (ON ALL SERVER) or database (ON DATABASE) levels. The events on which DDL triggers can be defined (e.g. ALTER_TABLE, CREATE_DATABASE) are grouped (e.g. DDL_TABLE_EVENTS), so some triggers can be written more concisely. DDL triggers have access to the EVENTDATA function, which returns an XML with information about the event type, the time it happened, the SPID, ServerName, LoginName, UserName, DatabaseName, SchemaName, ObjectName, ObjectType, and TSQLCommand that caused it to fire. Each event has a different XML schema.

LOGON triggers can also be defined, but they cannot show messages to the user, since they execute before the session is established. A ROLLBACK inside a LOGON trigger causes the connection to terminate.

Views

Besides being able to use the ENCRYPTION and SCHEMABINDING options when creating a view, you can specify VIEW_METADATA, which is used for updatable views, so SQL Server returns metadata about it to client applications (instead of metadata about the underlying tables).

Data modifications through a view can only happen if:

  • It references exactly one table

  • Columns in the view reference columns in a table directly

  • The column is not derived from an aggregate

  • The column is not computed as a result of a UNION (ALL), CROSSJOIN, EXCEPT or INTERSECT.

  • The column is not affected by the DISTINCT, GROUP BY, or HAVING clause.

  • The TOP operator is not used


Also, the WITH CHECK OPTION clause (when creating a view) means that the only data manipulation that can occur through the view must also be retrievable when you select from it.

An exception to the previous restrictions are partitioned views (created with UNION ALL statements), which have a somewhat restrictive set of conditions. Broadly speaking, they need to ensure that the result set in each of the member tables (which must be all equally defined) are unique.

Indexed views also have a special list of requirements because data is materialized and physically stored (aka materialized views). Among these requirements are:

  • The SELECT statement cannot reference other views

  • All functions must be deterministic

  • AVG, MIN, MAX, STDEV, STDEVP, VAR, VARP are not allowed

  • The index must be both clustered and unique

  • ANSI_NULLS must have been set to ON when the view and any tables referenced by it were created

  • It must be created with the SCHEMABINDING option

  • The SELECT statement must not contain subqueries, outer joins, EXCEPT, INTERSECT, TOP, UNION, ORDER BY, DISTINCT, COMPUT/COMPUTE BY, CROSS/OUTER APPLY, PIVOT or UNPIVOT.

Saturday, January 30, 2010

Notes on SQL 6

Previous related posts:

Stored procedures

These statements cannot be used in an SP: USE <database_name>, SET SHOWPLAN_TEXT, SET SHOWPLAN_ALL, SET PARSEONLY, SET SHOWPLAN_XML, CREATE AGGREGATE, CREATE RULE, CREATE DEFAULT, CREATE SCHEMA, CREATE/ALTER FUNCTION, CREATE/ALTER TRIGER, CREATE/ALTER PROCEDURE, CREATE/ALTER VIEW. In other words, you cannot define what database to use, cannot ask the server for information for each executed statement, cannot ask the server to only parse the SP, and cannot create/alter objects.

The ENCRYPTION option when creating an SP is not really encryption, and is easily reversed.

WAITFOR:

  • WAITFOR DELAY: obvious. WAITFOR DELAY '00:00:02'.

  • WAITFOR TIME: waits for a specified time to occurr.

  • WAITFOR RECEIVE: used in conjunction with Service Broker.


Query (or execution) plans are created when an SP is going to be executed, and then reused when it gets re-executed. If the SP behaves differently due to conditions inside it (control flow constructs), it might be better to re-generate the execution plan each time to avoid using non-optimal plans in some cases. This can be done by creating the SP with the RECOMPILE option. Optionally, different SPs can be created for each block of code in the conditions, so the "master" execution plan is simple but always the same, and each "sub-SP" has its own execution plan created when it is needed.

The EXECUTE AS clause can be used to run a SP under a specific security context:

  • LOGIN

  • USER

  • CALLER


Variables

If you assign the results of a SELECT statement that returns several rows, to a variable, the last value (row) is assigned, and the rest discarded.

The +=, -=, *= and /= operators are new to SQL Server 2008 (2005 and older require @var = @var + 1 instead of @var += 1).

Errors


Severity levels go from 0 to 25. 16 and up is logged automatically to the SQL Server error log and the Windows Application Event Log. 19 to 25 can only be specified by members of the sysadmin role. 20 to 25 are considered fatal and cause the connection to be terminated, and any open transactions to be rolled back.

In the CATCH part of a TRY-CATCH block, you can use the ERROR_NUMBER(), ERROR_MESSAGE(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), ERROR_LINE() functions for error handling. Also, the XACT_STATE function returns 1 if there are open transactions that can be committed or rolled back, 0 if there are no open transactions, and -1 if transactions that can only be rolled back (due to the type of error) exist. If you use SET XACT_ABORT ON before a TRY-CATCH block, any error passes control to the CATCH block but XACT_STATE always returns -1.

Cursors

You need to DECLARE, OPEN, FETCH, CLOSE, and DEALLOCATE a cursor (CLOSE and DEALLOCATE are performed automatically when an SP terminates). FETCHs are normally done together with with a WHILE @@FETCH_STATUS = 0

Cursor options:

  • FAST_FORWARD: can only move forward one row at a time, and scrolling is not supported. You cannot modify the underlying table.

  • STATIC: the result set is stored in tempdb, so changes to the tables are not seen by the cursor. Modifications are not supported.

  • KEYSET: the keys for the rows in the result set are stored, so modifications to these rows are seen by the cursor. Inserts into the source table are not. Accessing a row that has been deleted causes @@FETCH_STATUS to return -2.

  • DYNAMIC: all changes to the underlying table (including inserts) are reflected in the cursor. You cannot use FETCH ABSOLUTE with these.


Updates/deletes to the source tables can be done by an UPDATE/DELETE statement with the WHERE CURRENT OF <cursor name> clause. If modifications are not necessary, the cursor should be declared as READ_ONLY.

Instead of FORWARD_ONLY, you can declare a cursor as SCROLL, in which case you can:

  • FETCH FIRST

  • FETCH LAST

  • FETCH NEXT: equivalent to FETCH

  • FETCH PRIOR

  • FETCH ABSOLUTE n: fetches the n'th row.

  • FETCH RELATIVE n: n rows forward.


Concurrency options for cursors are:

  • READ_ONLY: no lock acquired.

  • SCROLL_LOCKS: locks acquired as each row is read into the cursor.

  • OPTIMISTIC: uses timestamps or checksums instead of locks, and if the data has changed when a modification through the cursor is attempted, it fails.


User-defined Functions

THey cannot:

  • Perform an action that changes the state of an instance or database

  • Modify data in a table

  • Call a function that has an external effect, such as the RAND function

  • Create or access temporary tables

  • Execute code dynamically


Scalar-valued functions are straightforward, table-valued functions can be inline (treated like views), or multi-statement (with a BEGIN-END block which does calculations and returns a table.

Can be created with:

  • SCHEMABINDING: if specified, prevents dropping of objects on which the function depends (e.g. tables).

  • EXECUTE AS: same as for SPs

  • ENCRYPTION: same as for SPs

  • RETURNS NULL ON NULL INPUT/CALLED ON NULL INPUT: the former causes NULL to be returned immediately if a NULL parameter is passed to the function; the latter lets the function code execute with a NULL parameter.


Random notes:

A GO inside a comment is STILL considered as a batch delimiter in T-SQL. Careful.

SPs allow GOTO statements. Discouraged.

The @@IDENTITY global variable contains the last identity inserted by any statement in the current connection. If an INSERT activates triggers that insert other rows, @@IDENTITY contains the ID of the last row inserted by the trigger(s). The SCOPE_IDENTITY() function should be used to retrieve just-inserted IDs instead.

Cool optical illusion

Another one for the collection. One of the best ones I've seen.

Notes on SQL 5

Previous related posts:

Common Table Expressions (CTEs)

Basic CTE:

WITH TableName As (<Any SELECT statement that generates a valid table>)
<SELECT statement that references TableName>

Recursive CTE:

WITH TableName As (<Any SELECT statement that produces the anchor result> UNION ALL <SELECT statement that references TableName>)
<SELECT statement that references TableName>

Use OPTION(MAXRECURSION = <number>) in the outer query to determine the max amount of recursive calls.

More details on CTEs here.

Note: since the WITH keyword has several possible meanings in different contexts, the statements preceding the WITH keyword are required to be terminated with a semicolon.

Ranking data functions


ROW_NUMBER: specifies the row number for each row in the resultset. Could be use to paginate in SPs (WHERE RowNumber BETWEEN @min AND @max). Syntax: ROW_NUMBER() OVER ([ <partition_by_clause> ] <order_by_clause>). The partition separates the result set into subsets to which the ROW_NUMBER() function applies independently (row numbering is restarted for each subset). The order by specifies the order in which to number rows. DOES NOT WORK WELL WITH TIES (of the order_by_clause), since it could return different row numberings when executing the same query.

RANK: same as ROW_NUMBER, but if there are ties the same value is assigned to all rows in a tie, and skips the corresponding amount of values for the next assignment. E.g. 1, 2, 3, 3, 5, 5, 5, 8, 9, etc.

DENSE_RANK: same as RANK but does not skip values. E.g. 1, 2, 3, 3, 4, 4, 4, 5, 6, etc.

NTILE(integer_expression): partitions the result set into  a specified number of groups, and rows in each group are assigned a number that indicates to which group they pertain. (Note: "If the number of rows in a partition is not divisible by integer_expression, this will cause groups of two sizes that differ by one member. Larger groups come before smaller groups in the order specified by the OVER clause").