Saturday, September 3, 2022

The Last Days of Sigmund Freud

Although he lived more than a century ago, Sigmund Freud abides. Despite the magazine features and nonfiction bestsellers that regularly proclaim him a charlatan, a reactionary, an intellectual dead end, or simply “dead,” we live in a world fundamentally shaped by his legacy. We accuse one another of “projecting”; we laugh—uncomfortably or with knowing glee—when someone else’s speech slips; we read novels and speculate about the author’s childhood, love life, and traumas; and we struggle not to think too hard about our more embarrassing dreams. If anything, the anxious protests (“I don’t believe in Freud, but …”), like the apparently inexhaustible need to ritually slay Freud the Bad Intellectual Patriarch in print, reflect his durability, and our anxieties, in a quintessentially Freudian way. Why would people feel so compelled to disavow him, after all, if Freud, like the repressed, didn’t always return?

Freud is dead, as more than a few have quipped, because Freud is everywhere. Or as W.H. Auden put it, in an obituary poem, “to us he is no more a person / now but a whole climate of opinion.” As a stand-in for a body of work (the English Standard Edition of his writings—which doesn’t include his letters—runs 24 volumes), as the Father of Psychoanalysis, and as a metonymy for a suite of still-disquieting claims about aggression, sexuality, and the unconscious dimensions of human behavior in general, “Freud” endures, overdetermined, signifying far more than just a name.



from Hacker News https://ift.tt/vbu2QDR

Myths About CGI Scalability



Myth or Fact?

If 300 people happen to be at your site at the same time, there will be 300 copies of your program running simultaneously, right? And with Perl CGI, that means 300 copies of the Perl interpreter open, right? And without Perl CGI, just using plain old binary native executable CGI (which Powtils offers), it will still be 300 copies of that binary CGI, right?

Answer

It is only partly true. Windows NT for example will load the code segment of your exe or elf only once and share it even if multiple copies of the same exe or dll are loaded. Each user has it's own private data segment, but the code segment is shared! Unix is similar. Executables are like libraries in a way on both operating systems.

Trivia: In fact a Windows EXE can even be launched as a DLL:

  loadlibrary('program.exe')

There was a rumor spread around after the Windows 3.1 days which caused people to believe the code segment of multiple copies of the same exe running isn't shared. Other times, it isn't even because of a myth being spread.. it is simply due to lack of research/education about operating systems.

More Speed Built in to OS

Operating systems are also smarter than we think (unix, windows, etc), and we can't make assumptions or premature conclusions about CGI without knowing the deep inner workings of the operating system.

Have you ever launched a program such as Notepad on windows, or say a bigger program such as internet explorer the first time upon bootup? It takes a while to load the program (well notepad not so much, but still not super instant). Whereas if you immediately launch the program again, after you've already opened it once, it opens faster!

This is another operating system trick that acts like caching and speeds up CGI without you having to do any work.. it is just built in to the OS magically. You have to remember that most operating systems were designed and based around slow computers at that time (windows NT, unix).

Guess what happens with CGI programs? Many people are launching the same CGI program open again and again on busy websites - and the operating system loves when this happens. It is like a caching system without you having to code the caching yourself. It is much easier for the OS to repeatedly open the same cgi program over and over again than it is to open several different programs such as web browsers, excel, word, wordperfect, openoffice, etc.

This is all partly because modern operating systems were designed on the days when 100Mhz computers with 64MB or ram were popular.

There is actually sort of a built in "fastcgi" system in the operating system.

Now I'm not arguing that a fastcgi website couldn't be made to run faster than a regular cgi website in all cases or some cases or many cases - it could (with more memory leak hazards) - my point is more that people make false assumptions and assume that operating systems are stupid idiotic pieces of software that have no built in performance intelligence for cloned processes.

File System Caching, OS Caching

Actually, the same false assumptions are sometimes made with caching. Sometimes the operating system is doing caching behind your back - and programming the caching into your application may be battling what the operating system has already done for you!

File caching tricks and virtual memory are also used in operating systems behind our back. So some people start worrying about using files for storage because they will be slower since they are hard disk based.. but in fact many times the operating system uses file caching tricks to make files operated faster, especially when being accessed repeatedly.

Database queries are similar. Many people make assumptions and over-design their programs with their own caching code when the server has already done a lot of the work for them (or can be set up in the database configuration, or indexes and other settings can be tweaked, etc.).

With ISAPI, you have a DLL with the same code shared between all the clients and with a private data set for each client. It's actually similar to regular CGI in some ways, ironically. Of course, again, I'm not arguing that an ISAPI web application couldn't be used to build a fast website, and I'm not arguing that CGI is perfect.. I'm just trying to show you that CGI isn't all that bad. I've written other articles about how CGI offers free garbage collection since each process is killed, whereas in ISAPI/FastCGI you are more prone to big memory leaks. The fact that humans make mistakes, especially in languages like delphi/fpc/C++, makes CGI advantageous here.

All that stuff you've read about shared libraries.. did you know executables do similar? most people assume exe's are all launched with separate code segments. Exe's are in fact kind of like libraries themselves.

I really do need to scale?

Okay, so I've already ranted about and warned you about premature optimization in other areas of this wiki.. but let's pretend you've actually got a huge website like Ebay or OkCupid and you really do wish to start worrying a bit about performance of your CGI programs.

You can use the CGI helper technique: write helper program that is forked open once and restarted every so many weeks. The little CGI programs will connect to this helper executable (through inter process communication or sockets or piping) and this helper executable will handle Database Pooling, will have a state, and will talk to the web server. That way, all your code is constantly loaded into memory and your little cgi programs just talk to it. Or, you build apache modules or an apache handler. Or you keep several (about 10) cgi instances pegged open ahead of time. Or you build thread manager. Reusing most of your old code from 5 years ago back when you were using CGI. So how scalable is that for reusing your existing code?

Is this reinventing FastCGI? Well, this is better than FastCGI in some ways because this can be run on any server with CGI, not just fastcgi capable servers. One can launch a separate process using a cron job or a ShellExec to get the program running initially, and then have the program restarted every 1000 requests or every 25 days or something similar (to prevent memory leaking issues as after 1000 requests even a small memory leak will waste more and more memory). However, FastCGI can also just be used and you can reuse many your CGI algorithms and code in fastcgi.

Theory, or fact?

Is this really possible, or just a theory that one can have a CGI program talk to a program that is running for several days? I've done this myself on a typical CPanel account, so don't take my word for it, take my experience for it!

Instead of building a helper program to help me scale, I needed to run a few programs that I didn't want to launch with cron jobs. I didn't want them to run inside my web browser either.. I wanted them to run as true separate programs. Solution? My CGI program could launch the programs initially, as a bootstrap.. easily! Only a few lines of code. The CGI program would immediately exit, but leave external programs running after exiting.

The extrenal processes would report back to a log file saying how far they had gotten (I was grabbing over 20,000 websites and didn't want to sit there watching my web browser). So I wrote a CGI program to launch new processes in the background without it being a child of the main CGI. As soon as the CGI ran, the CGI launched the process, and then the CGI killed itself, but only itself.. not the processes it launched (separate parent processes were launched, not children).

The programs ran for a few hours until they were done. I was cooking, eating, cleaning, sleeping, while waiting - and I didn't have to sit there watching my web browser waiting for the 300 second CGI timeout.. because the processes were launched separately and there was no 300 second timeout limitation.

The same technique could be used to launch a CGI helper program that takes care of database pooling and that takes care of preserving some of the code state (keeping code libraries in memory, keeping database connections open, etc.). The helper program would run for several days. For robustness, you could have 3 helper programs.. in case one of the helper program fails. Kind of like rocket ship programming where they have dummy backups in case the rocket ship software fails and has a fatal exception.

But still, stop worrying so much

I've warned you, the operating system is pretty smart - and you might not need to do any of these tricks in 98 percent of your applications. Don't prematurely optimize.. but know that optimization is available to you! More is available to you with CGI than with Ruby, Python, or PHP! Don't be afraid, forget the FUD about CGI. In Ruby you have to write code in C to speed things up. With powerful web utilities you don't mix and match ..you just use one language. (Actually you could launch a PHP interpreter or PascalScript interpreter from within a Powtils program if you really wanted, but I'm not sure what purpose that would serve).

Knowing that optimization is available to you, is healthier than trying to program the optimization into the code from day one (such as choosing C for your entire website on day one, since C is fast). At the same time, programming in Ruby from day one and saying you'll optimize the Ruby later isn't so smart.. but saying that your current Powtils program is fast but not super fast.. is smart.. because you CAN optimize it later, with more Pascal code and helper Pascal programs.. whereas in Ruby you can't really optimize Ruby significantly.. you more have to resort to using C. That's not so nice, because you have to switch and intermingle two languages.. and most people just end up throwing more money at hardware and using more and more ruby.

So my point is not that optimization is evil.. I think that knowing you have options, and knowing you have potential for optimization.. is much healthier than not having any potential for optimization. Some algorithms, for example, need to be optimized from day 1.. and trying to optimize them 2 years down the road won't work - they need to be rewritten from scratch. Well that isn't the case with CGI - CGI is scalable, and it is fast from day one, and can be even faster (but with risk of more memory leaks just like fastcgi) with the cgi Helper Program technique.

Did I mention that Google use C++ for their template system that displays the google search pages? They don't use some fancy JSP/ASP/PERL/PHP solution. You can bet that google probably uses some of the "helper program techniques" to make the google experience faster than fast! But are you google? Remember, you may not need to go faster than fast.. but the fact that going faster than fast is available to you, is a bonus over all the other technologies. You don't even have to use fastcgi to go faster than fast.. you can use your own helper program technique. If you want to use fastcgi at some point, at least all your modern Pascal algorithms are available to you in fastcgi too.

If you Decide FastCGI is For You

The fastcgi program layout needs to be changed compared to a regular CGI program.. but your data structures and algorithms that you have written for the past 5 or 10 years in fpc/delphi can obviously still be used inside the program. That is easier than say choosing Ruby or PHP, where none of your fpc/delphi code can be used in Ruby or PHP.

Some Advantages Over Ruby/Python

The only way of optimizing Ruby is not to use Ruby.. use Cee, which means mixing two languages and a whole bunch of messes. Same idea with Python.. extend Python with Cee and make fast code in Cee. Why is this an advantage, over just using something like Powtils where you use one language to do the logic, and use templates or powtils widgets for design?
References:
"Multiple instances of the same application or .dll use the same code segment, but each has its own data segment."
--http://msdn2.microsoft.com/en-us/library/ms633574.aspx




from Hacker News https://ift.tt/bmaE6GP

The Rise and Fall of Vibes-Based Literacy

In the first spring of the pandemic, as families across the country were acclimating to remote learning and countless other upheavals, I sat down on the living-room sofa with my daughter, who was in kindergarten, to go over a daily item on her academic schedule called Reading Workshop. She had selected a beginner-level book about the alliterative habitués of a back-yard garden: birds and butterflies, cats and caterpillars. Her decoding skills, at that stage, were limited to the starting letter of each word, and all else was hurried guesswork—pointing at “butterfly,” she might ask, “Bird?” and start to turn the page. I coaxed her to look at how the letters worked together, to sound them out, starting by taking apart the first few phonemes: bh-uh-tih, butt. She didn’t appear to be familiar with this approach. She seemed to find it frankly outrageous.

Our subsequent reading workshops followed the same script. She would pick out a book, flip around, guess, bluff, and try to match words to pictures, while I plodded along behind her, grunting phonemes, until her patience frayed. I ascribed our ongoing failure to any number of factors—I wasn’t a teacher, for starters. (My kid wasn’t the only one bluffing.) She perhaps wasn’t ready to read. There were ambulance sirens wailing outside, forever.

I looked online for help, and learned that our Brooklyn public school’s main reading-and-writing curriculum, Units of Study, is rooted in a method known as balanced literacy. Early readers are encouraged to choose books from an in-classroom library and read silently on their own. They figure out unfamiliar words based on a “cueing” strategy: the reader asks herself if the word looks right, sounds right, and makes sense in context. My daughter was taught to use “picture power”—guessing words based on the accompanying illustrations. She memorized high-frequency “sight words” using a stack of laminated flash cards: “and,” “the,” “who,” et cetera.

It seemed to me that, rather than learning to decode a word using phonics, by matching sounds to letters with close adult guidance, a reader following this method is conditioned to look away from the word, in favor of the surrounding words or the accompanying illustrations—to make a quasi-educated guess, perhaps all on her own. It seemed possible that my kid’s scattered, self-directed reading style wasn’t entirely a product of her age or her temperament. To some extent, it had been taught to her.

Units of Study was developed by the education professor Lucy Calkins, the founding director of Columbia’s Teachers College Reading and Writing Project, which she started in 1981. Calkins trained thousands of teachers in Units of Study, becoming so synonymous with the curriculum that educators often refer to it—and even to balanced literacy itself—by the shorthand “Teachers College” or simply “Lucy Calkins.” The curriculum has dominated New York City’s approach to early reading for nearly twenty years. But literacy rates remain dismal: as of 2019, only about forty-seven per cent of the city’s students in grades three through eight were considered proficient in reading, according to state exams, including just thirty-five per cent of Black students and less than thirty-seven per cent of Hispanic students. “Lucy Calkins’ work, if you will, has not been as impactful as we had expected and thought and hoped that it would have been,” David Banks, the New York City schools chancellor, told reporters in the spring. (Calkins declined my requests for an on-the-record interview.)

Children now entering kindergarten in New York City may be taught differently. As of this school year, which starts on September 8th, the Department of Education (D.O.E.) will add a mandatory dyslexia screener for students in kindergarten through eighth grade and require elementary schools to include a phonics component in their reading-and-writing curricula at least through second grade. (Calkins’s Units of Study in Phonics supplement, which was first published in 2018, is excluded from the list of approved phonics curricula, according to a D.O.E. spokesperson.)

These developments reflect a long-standing consensus among researchers that intensive phonics and vocabulary-building instruction—an approach often referred to, nowadays, as the “science of reading”—are essential. Although an estimated sixty per cent of early readers in kindergarten through second grade in the United States are enrolled in schools that use programs aligned with balanced literacy, in the past two years, eighteen states have passed laws that mandate training for teachers in phonics-based instruction.

There has never been much peer-reviewed research to support Units of Study or other balanced-literacy curricula. In 2020, the education nonprofit Student Achievement Partners published a meticulous vivisection of Calkins’s program: “there are constantly missed opportunities to build new vocabulary and knowledge about the world or learn about how written English works,” the authors noted. “The impact is most severe for children who do not come to school already possessing what they need to know to make sense of written and academic English.” Last year, the curriculum-review nonprofit EdReports came to similar conclusions, and gave its lowest rating (“Does Not Meet Expectations”) to Units of Study and another popular balanced-literacy program, Fountas & Pinnell Classroom, which, according to one survey, is used in some forty-three per cent of classrooms nationwide.

Both reports bore down hard on the programs’ inattention to phonics. Last spring, Calkins announced that she would revise the main Units of Study programs for kindergarten through second grade in order to add daily phonics instruction. (A spokesperson for Calkins wrote, in an e-mail, “We must always work—together—towards constant improvement. This is why we are incredibly excited for the publication of the new edition of the Units of Study curriculum as this extends our proven approach by incorporating also our latest learnings and research.”)

It’s startling to realize that panels of experts had to argue the case that teaching children to read involves careful attention to the relationships between sounds and letters, or enhancing their vocabulary and knowledge of various subjects. It’s stranger still that, in many school systems and for many years, this was the losing argument.

The reading wars in America date back at least as far as the nineteenth century, when progressive education reformers “believed that children would find it far more interesting and pleasurable to memorize words and read short sentences and stories without having to bother to learn the names of the letters,” as the education historian Diane Ravitch writes in her book “Left Back: A Century of Battles Over School Reform.” Alphabet and phonics instruction, the thinking went, was enervating and, in the long run, unnecessary. The education crusader Horace Mann, who sparred with the phonics-fixated schoolmasters of Boston, went so far as to claim that children were frightened by the alphabet, which he described as a horde of “skeleton-shaped, bloodless, ghostly apparitions.” (In fact, the brain of a very young child does perceive letters differently than an adult brain: not as fixed, flat symbols but as three-dimensional objects rotating in space. That’s why kids who are learning to write so commonly exchange “b” and “d,” for example, or “p” and “q.”)

An under-acknowledged irritant in the reading wars is the fact that written English is deranged—haunted by Mann’s apparitions, perhaps. Why isn’t “bread” or “said” spelled like “red”? Why can’t “move,” “love,” and “stove” come to an agreement on their pronunciation? Why don’t “daughter” and “laughter” rhyme? Given its brotherhood with “what” and “where,” why isn’t “who” pronounced “woo”? What, exactly, is “enough”? In 1906, Andrew Carnegie funded the Simplified Spelling Board, an organization that advocated for the standardization of English-language spelling; the group included an Ivy League college president, a sitting Supreme Court Justice, and Mark Twain. Soon after, another Simplified Spelling Board supporter, President Theodore Roosevelt, published “The Roosevelt Fonetic Spelling Book,” which included rationalizations such as “fixt,” “kist,” “surprize,” and “thoro.” The project was doomed, owing largely to Congress’s disapproval. Yet the idea that young readers shouldn’t have to learn to decrypt such an inconsistent phonics code took hold, and endured.

The alternative was what came to be called the “whole word” or “look-say” method, exemplified in the notorious Dick-and-Jane primers that were first published in the nineteen-thirties. (“Oh, Mother. Oh, Father. Jane can play.”) “The pedagogical approach underlying these primers assumed that beginning readers learned new words best by associating them with pictures and memorizing them through dutiful repetition,” I-Huei Go wrote, in The New Yorker, in 2019. By the fifties, Go noted, this “method was just starting to face pushback from proponents of phonics-based instruction, most visibly in Rudolf Flesch’s influential polemic ‘Why Johnny Can’t Read.’ ” Flesch argued that look-say didn’t really teach reading at all. “Books are put in front of the children and they are told to guess at the words or wait until Teacher tells them,” he wrote. “But they are not taught to read.” What’s more, Flesch pointed out, the books that the children were guessing at weren’t any good—they were “meaningless, stupid, totally uninteresting to a six-year-old child or anyone else.” (“See Dick. See, see. Oh, see. See Dick.”) Flesch’s book, published in 1955, stayed on the national-best-seller lists for thirty weeks.

In the sixties, a psychologist at the Harvard Graduate School of Education named Jeanne Chall spent years compiling a painstaking analysis of historical and contemporary approaches to literacy in American schools, which became the influential book “Learning to Read: The Great Debate.” Chall concluded that phonics instruction was far superior to look-say, especially for students from underprivileged families. But she was more evenhanded than Flesch, proposing that phonics be set aside as early as possible in a child’s literacy education in order to focus more intently on introducing her to great books—to move through the mechanics of reading with some dispatch so that the joys and pleasures of it could be revealed all the more swiftly. “Jeanne Chall settled the argument in 1967,” Ravitch told me. “But the argument never stopped.”

By the early nineteen-eighties, the literacy pendulum was swinging back toward what was then known as the whole-language movement, which, in the U.S., was led by a pugilistic University of Arizona professor named Kenneth Goodman. Goodman believed that, ideally, learning to read was a self-directed and self-willed act; he posited whole language as a rejection of “negative, elitist, racist views of linguistic purity” and compared advocates of phonics to flat-Earthers. But, throughout the eighties and nineties, researchers compiled evidence that rigorous instruction in phonics was superior to early-reading programs that did not emphasize phonics. The National Reading Panel (a commission formed by the National Institutes of Health, at the request of Congress) and the National Academy of Sciences published reports to that effect. “Whole language proponents could no longer deny the importance of phonics,” the education reporter Emily Hanford has written. “But they didn’t give up their core belief that learning to read is a natural process.” Whole language was rebranded as balanced literacy, in which, according to Hanford, “phonics is treated a bit like salt on a meal: a little here and there, but not too much, because it could be bad for you.”

The pivotal National Reading Report appeared in 2000, the same year that Calkins published “The Art of Teaching Reading,” which extends to nearly six hundred pages and where much of her philosophy of literacy—honed by the decades she spent providing professional-development services to educators through the Teachers College Reading and Writing Project—can be found. In the book, Calkins walks her audience through a typical reading workshop, beginning with teacher-led “minilessons,” which are guided by questions such as “How can we choose ‘just right’ books?” or “How can we make more time for reading in our lives?” Even very young students are sometimes asked to deduce an author’s thoughts and intentions: why she chose a particular descriptive word; how she might personally feel toward her characters.

Then, the class moves on to independent reading, which is generally meant to last for at least thirty minutes, although “emergent and beginning readers may not be able to sustain reading” for that long. “This—actual reading time—is the most important part of the reading workshop,” Calkins writes, adding, “Children can’t learn to swim without swimming, to write without writing, to sing without singing, or to read without reading.” As the students page through books that they have individually selected from the classroom’s mini-library, the teacher moves among them, checking in on their progress or gathering small groups “for a strategy session around a shared text.”

What Calkins was proposing, it seems to me, was literacy by vibes. Her reading workshops bet that a youngster could, to a great extent, guide herself toward reading fluency through proximity or osmosis, eventually achieving what my colleague Kyle Chayka has called “the kind of abstract understanding that comes before words put a name to experience.” Even the chapter about phonics in “The Art of Teaching Reading” contains a vibes-y digression on high-frequency words, in which Calkins notes that “children who are thriving as readers and writers at the end of first grade usually seem to ‘just know’ ” these words.

For many teachers, balanced literacy was a welcome turn away from lesson plans in which all children at a certain grade level read the same stories and answered the same predetermined questions, leaving teachers with less room for creativity and spontaneity. “It used books that kids would actually read, which made it more meaningful for them,” Nadine Bryce, an associate professor of literacy at Hunter College and a Teachers College alumnus, told me. “It was new and refreshing and innovative.”

A major proponent of balanced literacy was Carmen Fariña, who was the New York City schools chancellor under Mayor Bill de Blasio until 2018. Fariña logged twenty-two years as an elementary- and middle-school teacher in the public schools, including a legendary stint at P.S. 29, in Brooklyn, where she turned empty washing-machine boxes into cozy independent-reading nooks and kept a “forbidden” cache of titles by Judy Blume and other provocative authors that kids could read by special request. For Fariña’s students, reading wasn’t a chore or a drill—it was a treat. “The last twenty minutes of most school days is wasted time in a classroom, so we used it for free reading,” Fariña told me. “The kids leave the school gentler, quieter, and if they’re reading a good book they want to go home and finish it.” The novelist Jonathan Lethem, who was Fariña’s fourth-grade student at P.S. 29, in the early nineteen-seventies, dedicated his first novel to Fariña; “The Art of Teaching Reading” includes Calkins’s reverent account of Fariña’s tenure in the nineties, as principal at P.S. 6, in Manhattan, where she dramatically raised reading scores using a balanced-literacy approach.



from Hacker News https://ift.tt/9feNxPj

I often have to cut into the brain (2012)

Our New Voices series highlights the most exciting emerging talents on granta.com. The latest in the series is Henry Marsh, a brain surgeon turned memoirist, whose piece here describes an operation on the deeply buried pineal gland. You can also read an interview with the author here.

 

I often have to cut into the brain and it is something I hate doing. With a pair of short-wave diathermy forceps I coagulate a few millimetres of the brain’s surface, turning the living, glittering pia arachnoid – the transparent membrane that covers the brain – along with its minute and elegant blood vessels, into an ugly scab. With a pair of microscopic scissors I then cut the blood vessels and dig downwards with a fine sucker. I look down the operating microscope, feeling my way through the soft white substance of the brain, trying to find the tumour. The idea that I am cutting and pushing through thought itself, that memories, dreams and reflections should have the consistency of soft white jelly, is simply too strange to understand and all I can see in front of me is matter. Nevertheless, I know that if I stray into the wrong area, into what neurosurgeons call eloquent brain, I will be faced with a damaged and disabled patient afterwards. The brain does not come with helpful labels saying ‘Cut here’ or ‘Don’t cut there’. Eloquent brain looks no different from any other area of the brain, so when I go round to the Recovery Ward after the operation to see what I have achieved, I am always anxious.

There are various ways in which the risk of doing damage can be reduced. There is a form of GPS for brain surgery called Computer Navigation where, instead of satellites orbiting the Earth, there are infrared cameras around the patient’s head which show the surgeon on a computer screen where his instruments are on the patient’s brain scan. You can operate with the patient awake under local anaesthetic: the eloquent areas of the brain can then be identified by stimulating the brain with an electrode and by giving the patient simple tasks to perform so that one can see if one is causing any damage as the operation proceeds. And then there is skill and experience and knowing when to stop. Quite often one must decide that it is better not to start in the first place and declare the tumour inoperable. Despite these methods, however, much still depends on luck, both good and bad. As I become more and more experienced, it seems that luck becomes ever more important.

I had a patient who had a tumour of the pineal gland. The dualist philosopher Descartes, who argued that mind and brain are entirely separate entities, placed the human soul in the pineal gland. It was here, he said, that the material brain in some magical and mysterious way communicated with the mind and with the immaterial soul. I wonder what he would have said if he could have seen my patients looking at their own brains on a video monitor, as some of them do when I operate under local anaesthetic.

Pineal tumours are very rare. They can be benign and they can be malignant. The benign ones do not necessarily need treatment. The malignant ones are treated with radiotherapy and chemotherapy but can prove fatal nevertheless. In the past they were considered to be inoperable but with modern microscopic neurosurgery this is no longer the case: it is usually now considered necessary to operate at least to obtain a biopsy – to remove a small part of the tumour for a precise diagnosis of the type so that you can then decide how best to treat it. The biopsy result will tell you whether to remove all of the tumour or whether to leave most of it in place, and whether the patient needs radiotherapy and chemotherapy. Since the pineal is buried deep in the middle of the brain the operation is, as surgeons say, a technical challenge; neurosurgeons look with awe and excitement at brain scans showing pineal tumours, like mountaineers looking up at a great peak that they hope to climb. To make matters worse, this particular patient – a very fit and athletic man in his thirties who had developed severe headaches as the tumour obstructed the normal circulation of cerebro-spinal fluid around his brain – had found it very hard to accept that he had a life-threatening illness and that his life was now out of his control. I had had many anxious conversations and phone calls with him over the days before the operation. I explained that the risks of the surgery, which included death or a major stroke, were ultimately less than the risks of not operating. He laboriously typed everything I said into his smartphone, as if taking down the long words – obstructive hydrocephalus, endoscopic ventriculostomy, pineocytoma, pineoblastoma – would somehow put him back in charge and save him. Anxiety is contagious – it is one of the reasons surgeons must distance themselves from their patients – and his anxiety, combined with my feeling of profound failure about an operation I had carried out a week earlier meant that I faced the prospect of operating upon him with dread. I had seen him the night before the operation. When I see my patients the night before surgery I try not to dwell on the risks of the operation ahead, which I will already have discussed in detail at an earlier meeting. His wife was sitting beside him, looking quite sick with fear.

‘This is a straightforward operation,’ I said, with false optimism.

‘But the tumour could be cancerous, couldn’t it?’ she asked.

‘Well, it’s possible,’ I replied. ‘That’s why we’ll get a biopsy – it’s called a frozen section – during the op. If the pathologist says it’s not cancerous I don’t have to try to get every last little bit of tumour out. And if it’s a tumour called a germinoma I don’t have to remove the tumour at all and he can be treated with radiotherapy.’

‘So if it’s not cancer, and not a germinoma, then the operation is safe,’ she said, her voice tailing off uncertainly.

I hesitated, not wanting to frighten her but reluctant to make false promises. ‘Yes – it makes it a lot less dangerous if I don’t try to take it all out,’ I said, choosing my words carefully.

We talked for a little longer and then I wished them goodnight and went home.

 

*

 

I woke early on the morning of the operation and lay in bed thinking about the young mother I had operated on the previous week. I had operated on a tumour deep in the right side of her brain and somehow – I do not know how since the operation had seemed to proceed uneventfully – I had caused a major stroke, so that she awoke from the operation paralysed down the left side of her body. I had probably tried to take too much of the tumour out. I had probably strayed too deeply into her brain. I must have been too self-confident. I had been insufficiently fearful. I longed for this next operation, the operation on the pineal tumour, to go well – that there should be a happy ending, that everybody would live happily ever after, and that I could feel at peace with myself once again. But I knew that however bitter my regret, and however well the pineal operation went, there was nothing that I could do to undo the damage I had done to the young woman. I also knew that any unhappiness on my part was nothing compared to what she and her family were going through. I knew too that there was no reason why the next operation should go well just because I hoped so desperately that it would, or because the previous operation had gone so badly. The outcome of the pineal operation – whether the tumour was malignant or not, whether I could remove the tumour or whether it was hopelessly stuck to the brain and everything went horribly wrong – was largely outside my control. I also knew, however, that as time went by the grief I felt at what I had done to the young woman would fade. The memory of her lying in her hospital bed, her mother sitting beside her with her daughter’s newborn baby on her lap, would become a scar rather than a painful wound. She would be added to the list of my disasters – another headstone in that cemetery which the French surgeon Leriche once said all surgeons carry within themselves.

As soon as an operation begins, however, the surgeon usually finds that any morbid fear disappears. You take up the scalpel – no longer from the scrub nurse’s hand but, in accordance with some Health and Safety protocol, from a metal dish – and full of surgical self-confidence, press it precisely into the patient’s flesh. As the blood rises from the wound the thrill and excitement of the chase take over and you feel, more or less, in control of what’s happening. At least that is how it seems as the operation starts, and you operate in the blind faith that that is how the operation will continue, although you know that it may not.

My assistant and I stood behind the patient, who was propped upright in the sitting position, as we opened the back of his head, splitting the neck muscles apart and then drilling through the bone of his skull.

‘Really cool. Exciting,’ my registrar said.

‘Well,’ I replied, unable to deny my own excitement. ‘It’s like mountaineering – although it’s mountaineering for cowards since it’s not our lives that are at risk.’

 

*

 

The man’s head opened, the muscles retracted, the meninges incised and reflected – surgery has it own ancient descriptive language – I had the operating microscope brought in and I settled down in the operating chair. With this particular operation you are looking along a narrow crevice that separates the upper part of the brain – the cerebral hemispheres – from the lower part of the brainstem and cerebellum. You feel as though you are crawling through a long tunnel. At about three inches’ depth – although it feels a hundred times longer because of the microscope’s magnification – you will find the tumour. You are looking directly into the centre of the brain, a secret and mysterious place where all the most vital functions that keep us alive and conscious are to be found. Above you, like the great vault of a cathedral roof, are the deep veins of the brain – the Internal Cerebral Veins, and beyond them the basal veins of Rosenthal and then in the midline the Great Vein of Galen, dark blue and glittering in the light of the microscope, names that inspire awe in neurosurgeons, veins that carry huge volumes of venous blood away from the brain, and vessels which, if damaged, will result in the patient’s death.

In front of you is the granular red tumour and beneath it the tectal plate of the brainstem, where damage can produce permanent coma.

On either side are the posterior cerebral arteries that supply the parts of the brain responsible for vision. In the distance ahead, beyond the tumour, a door opened into a distant white-walled corridor once the tumour has been removed, is the third ventricle.

There is a fine, surgical poetry to these names which, combined with the beautiful optics of a modern, counter-balanced microscope, makes this one of the most wonderful neurosurgical operations – if all goes well, that is. The disastrous operation of the preceding week, however, had destroyed much of my surgical self-confidence and I was as nervous as I had been when I had first become a surgeon. As I approached the tumour there were several blood vessels in the way that had to be cut – one needs to know which can be sacrificed and which cannot. It was as though I had lost all my knowledge and experience, and every time I divided a blood vessel I shook with fright. And yet as a neurosurgeon you learn at an early stage of your career to accept intense anxiety as a normal part of the day’s work and to carry on despite it – so eventually I reached the tumour. I removed a minute fragment of it which was then sent off to the pathology laboratory and I sat back in my operating chair.

‘We’ll now have to wait,’ I said to my assistant with a sigh. It is not easy to break off in the middle of an operation and I sat slumped in my chair, full of nervous excitement: longing to get on with the operation, hoping that my pathology colleague would report the tumour to be both benign and operable, hoping that the patient would live, hoping that I would be able to tell his wife after the operation that all would be well.

 

*

 

After forty-five minutes of waiting I couldn’t stand the delay any longer and, pushing my chair away from the operating table, leapt out of it and went to the nearest phone – still in my sterile gown and gloves. I rang the path lab and demanded to speak to the pathologist. There was a brief delay and then he came to the phone.

‘The frozen,’ I shouted. ‘What’s happening?’

‘Ah,’ he said imperturbably. ‘So sorry about the delay. I was in another part of the building.’

‘What the hell is it?’ I asked.

‘Yes. Well, I’m looking at it now. Ah! Yes, it looks like a straightforward benign pineocytoma . . . ’

‘Wonderful!’ I cried, forgiving him instantly. I went back to the operating table where everyone was patiently waiting.

‘Let’s get on with it!’ I said.

 

*

 

I scrubbed up again and climbed back into my operating chair, rested my elbows on the armrests and got back to work on the tumour. Each brain tumour is different – some are as hard as rock, some as soft as jelly. Some are completely dry, some pour with blood – sometimes to such an extent that the patient can bleed to death during the operation. Some shell out like peas from a pod, some are hopelessly stuck to the brain and its blood vessels. You can never know for certain from a brain scan exactly how a tumour will behave until you start to remove it. This man’s tumour was, as surgeons say, co-operative, and with a good surgical plane – in other words, it was not stuck to the brain. I slowly cored it out, collapsing the tumour in on itself away from the surrounding brain. After three hours it looked as though I had got most of it out.

 

*

 

Since pineal tumours are rare and exciting cases, one of my colleagues came into my theatre from his own operating theatre, to see how the operation was going. He was probably a little jealous. He peered over my shoulder.

The operation continued uneventfully and by the end it seemed that I had removed all, or almost all of the tumour without injuring any of the surrounding vital architecture of the brain. Since the tumour was a benign pineocytoma it probably would not matter even if post-operative scans showed I had left a small fragment of it behind. I left my assistant to close the wound and, leaving the operating theatres, walked the short distance to the wards.

I had only a few inpatients, one of them the young mother I had left paralysed one week earlier. I found her on her own in a side-room. Approaching a patient you have damaged makes the handle of the door behind which the patient is lying feel as though it is made of lead. There is a force-field pushing you away from the patient’s bed, resisting your attempts to raise a hesitant smile on your face. You are a villain and perpetrator, or at best incompetent, no longer heroic and all-powerful. It is difficult to know what role you now should play. It is much easier to hurry past the patient, looking busy and important, without saying anything at all.

I went into the room and sat down in the chair beside her.

‘How are you?’ I asked lamely.

She grimaced.

‘Not too good,’ she replied, pointing with her good right arm to her paralysed left arm and then lifting it up to let it fall lifeless onto the bed.

‘I’ve seen this happen before,’ I said. ‘And the patients got better, although it took months. I really do believe you will get largely better.’

‘I trusted you before the operation,’ she said. ‘Why should I trust you now?’

I had no immediate reply to this and could only look uncomfortably at my feet.

‘But I believe you,’ she said after a while, although I think she spoke out of pity.

 

*

 

I went back to the theatres. The pineal patient had been transferred from the table to a bed and was already awake. He lay with his head on a pillow, looking blearily around himself while one of the nurses washed blood and bone dust left from the operation out of his hair. The anaesthetists and theatre staff were laughing and chatting as they busied themselves around him, rearranging the many tubes and cables attached to him, in preparation for wheeling him round to the ITU. If he had not woken up so well they would have been working in silence.

‘He’s fine,’ my assistant happily shouted to me across the room.

I went to find his wife. She was waiting in the corridor outside the ITU, her face rigid with fear and hope as she watched me approach her.

‘It went as well we could hope,’ I said, in a formal and matter-of-fact voice, playing the role of a detached and brilliant brain surgeon – but then I could not help but reach out to her, to put my hands on her shoulders, and as she put her hands on mine and we looked into each others’ eyes, and I saw her tears, and had to struggle for a moment to control my own, I allowed myself a brief moment of celebration.

‘I think everything’s going to be all right,’ I said.

 

Photograph © Alex E. Proimos



from Hacker News https://ift.tt/PX7iEhD

Friday, September 2, 2022

Witnesses, drone expert react to mysterious lights captured in Texas sky

UFO sighting or drones? Strange lights captured in the sky in Round Rock area

FOX 7's Rudy Koski spoke with witnesses and a drone expert to discuss what was seen in the night sky.

ROUND ROCK, Texas - Mysterious lights were spotted Thursday night, north of Austin over Brushy Creek and Cat Hallow. 

Video was sent to FOX 7 by Gus McGiven. He was out walking with his friend Kyle Gomez near Cat Hallow in Round Rock.

"In real life when you see it, it's a lot brighter than it actually is," said Kyle Gomez.

RELATED: UFO sighting? Mysterious lights caught on camera in Round Rock

Emily White says she and a friend were near Brushy Creek, close to Cedar Park, at the time. They also recorded a video clip of the lights.

"It was mesmerizing, honestly. It was so silent because if it was one light, then I would have maybe thought, ‘Oh, a helicopter, a plane, something like that.' But like there was so many of them together," said White.

RELATED STORIES:

FOX 7 asked White if she wondered if she was having a close encounter. 

"I'll be honest, kind of. I don't know if I believe in all that, but, I don't know. Maybe, I hear a lot of it in like America that that kind of things happens. I think it's just because of like it didn't make any noise at all, which I just thought was really odd. But, yeah, definitely, definitely felt like it was like the alien invasion or something on the way," said White.

Gus McGiven and Kyle Gomez were also left with questions.

"I've never believed in UFO's or anything like that, but I mean, I might, I might now. I don't know, I'm not sure," said McGiven.

UFO spotted in Hays County

Photos and videos have been captured of so-called UFOs for years. A recent, local sighting has caught the eye of multiple witnesses.

The "UFOs" may actually have been UAVs, Unmanned Aerial Vehicles.

"I would have to say there's nothing extraterrestrial involved with this. But I am not to say that that couldn't be a possibility," said drone expert Gene Robinson.

Robinson, who lives in Wimberley, trains drone pilots and flies several types of UAV platforms. He reviewed the video sent to FOX 7.

"My initial take on this is that it is very likely a drone based phenomena," said Robinson.

At one point, the lights in one video clip zoomed off. Some people assume that what was in the air was projected by a laser. But Robinson noted it doesn't seem like there was anything for a laser to reflect off of.

"That's pretty unlikely. So, I'm still thinking that this may be someone testing their do-it-yourself drone swarm," said Robinson.

A drone swarm is a big light show. They started taking flight about 2 years ago. Drone swarms can fill the sky, like those that flew over Shanghai in 2020. Galveston had one for a Fourth of July event. In March, at SXSW, a drone swarm generated lots of buzz.

"Pretty much expect this to be the future of night light shows, is these drones are going to be swarmed in as we've seen 100, 200, 300 drones," said Robinson.

Gus and Kyle, after watching the SkyFOX Drone fly Friday afternoon, say what they saw was probably UAVs, but are not totally dismissing the UFO idea either.

"It was mesmerizing, honestly. It was so silent," said White.

The FAA requires a waiver to fly at night, especially in a swarm configuration. Officials with the agency say they are checking to see if a waiver was granted.

Round Rock police say they did not get any calls about the lights.



from Hacker News https://ift.tt/CmLRBc4

Profile Picture: Stories of diplomatic portraiture

A curious anecdote, part romantic tragedy, part macabre art history, is recorded in Xijing zaji (Miscellanies of the Western Capital), referring to events during the Early, or Western, Han dynasty (206 bc–9):

Since there were many girls in Emperor Yuan’s harem whom he had not been able to meet, he ordered artists to sketch them. According to these sketches he summoned them to be favored. All the palace girls bribed the artists: some gave as much as 100,000 cash, and none less than 50,000. Only Wang Qiang [Wang Zhaojun] was unwilling to give. Therefore, she was not able to meet the emperor. Later a Xiongnu envoy came to court seeking a beauty for his queen. Thereupon the emperor, basing his opinion upon the sketches, selected [Wang] Zhaojun to go. When she was about to leave, he summoned her and saw that her beauty was foremost in the harem. Her replies and deportment were genteel and decorous. The emperor regretted her selection, but since the list of names was already set and the emperor felt it important to maintain credibility with foreigners, he did not change girls. The matter was then thoroughly investigated, and the artists were all sentenced to be executed and to have their corpses exposed in the marketplace. Their confiscated homes and properties all were worth millions. Among the artists there was a Mao Yanshou of Duling who painted human portraits. Whether ugly or beautiful, old or young, he always attained a true likeness…They were all executed and their corpses exposed in the marketplace on the same day. Thus the number of artists in the capital dwindled.

This account is drawn from a text that may have been compiled only in the early sixth century, but it includes figures recorded in earlier official histories, including Emperor Yuan (r. 48 bc–33 bc) and Wang Qiang, or Zhaojun (53 bc–18), who was married to a foreign Xiongnu ruler and bore him children. The story of the neglected woman in the imperial harem whose beauty was only recognized after she had been promised to a nomadic ruler was mixed with fictional elements in popular culture and literature. Whether historical or fictional, these narratives point to some recurrent elements in the cultural status of portraiture in China involving both gender and foreign relations.

Like Bridal Du in the Peony Pavilion, Wang Zhaojun, sequestered in the imperial harem, was in some ways invisible without her portrait, but rather than fashioning her own image she relied on a portraitist’s mediation. The truth of and in portraiture is centrally at issue, as the narrative suggests that her portrait was disfigured or made unflattering by the painter Mao Yanshou. Portraits as substitutes for firsthand experience of the harem women held a crucial image-making power that could be manipulated by court portraitists to enhance their own or the subject’s fortunes, or distorted with tragic consequences for all. Beyond the personal level, portraiture could impact matters of state in terms of imperial bloodlines and succession, or alter the course of foreign relations, since Wang Zhaojun bore two sons to the ruler of the northern rival Xiongnu regime, though neither succeeded him. The extreme punishments suffered by the court painters who participated in the extortion and bribery scheme recorded in the anecdote further illustrate the gravity of their offense and the value placed on truthful representation in court relationships.

Handscroll of Wang Zhaojun’s convoy showing men and women on horseback.

Wang Zhaojun was often represented pictorially in much later times as a tragic exile from her homeland, traveling mournfully to her new life across the harsh conditions of the northern frontier. Other imaginary portrayals suggest her political role and imagistic place in intercultural and foreign relations. A twelfth- or thirteenth-century woodblock print of Four Beauties, with a caption suggesting their capacity to overturn empires, includes a labeled image of Wang Zhaojun, who alone holds a brush and scroll as if she might be writing to request a return to China, as she was reputed to have done without success. A cartouche identifies the print as the product of the Ji family of printer-publishers, active under the Jurchen Jin regime that conquered and occupied north China in the twelfth and early thirteenth centuries. The print was archaeologically recovered in Khara-Khoto in western Inner Mongolia, a region ruled in that twelfth- to thirteenth-century era by the Tanguts as the Xi Xia empire. The discovery of the print in this location, within that historical context, is thus evidence of the broad circulation of print images as carriers of Chinese popular culture into neighboring regions.

Spring Morning in the Han Palace (detail), copy after Qiu Ying, seventeenth century.

The Wang Zhaojun story remained popular in Ming dynasty (1368–1644) publications and performance culture based on more recent operatic versions that emphasized Zhaojun’s loyalty to Han mores and her rejection of nomadic customs. In a long handscroll known as Spring Dawn in the Han Palace the Suzhou professional painter Qiu Ying (c. 1494–1552) visualized an opulent imaginary court life that evokes some elements of the Wang Zhaojun narrative in its depiction of a court painter portraying aristocratic women. Qiu’s unusually detailed description of the portrait process includes the facing positions of the portraitist and a high-ranking consort who is framed by a painted screen, along with pigment dishes and an inkstone on the artist’s table. The portrait emerging beneath the painter’s brush on a framed panel in this case faithfully mirrors the subject’s appearance. Groups of palace women at either side are bracketed by columns into further screen-like arrangements, and all the figures are open to visibility and displayed on a raised platform suggestive of a theatrical stage.

Spring Morning in the Han Palace (detail), copy after Qiu Ying, seventeenth century.

In an adjacent scene to the right a palace woman standing in the center of a similarly framed and elevated hall inspects the bust-length portrait held up before her as if confronting her mirror image. The interplay of faces and gazes of the attendants and companions surrounding the portrait image and the blank side of another painting panel further confuse the status of the “real” and the represented. The vignettes to either side, of women playing a board game and ironing a length of silk cloth, are reproductions of a different order, as visual quotations from famous early figure paintings from earlier dynasties. Still another kind of reproduction is implied by the male children playing near their mothers, who might be understood as the products of the emperor’s selection of a partner based on her portrait.

Marriage alliances as instruments of foreign relations also figure in The Imperial Sedan Chair, a horizontal scroll attributed to the seventh-century Tang dynasty court painter Yan Liben (c. 600–673). It depicts an envoy sent from Tibet in 634 to negotiate a marriage alliance with the Tang emperor Taizong, who agreed to give his adopted daughter Princess Wencheng to the Tibetan ruler in a marriage realized in 641. The extant painting is likely an eleventh-century copy that preserves iconographic and stylistic features of an original Tang dynasty work. The composition stages the encounter between the Tibetan emissary Ludongzan, dressed in a distinctive, richly patterned long brocade robe, with Taizong (r. 626–49), who is seated on a sedan seat carried by a retinue of palace women, while others carry large fans and a parasol-like canopy held above the emperor as portable signs of rank. The presentation of Taizong’s figure in three-quarter view is consistent with other imperial portraits attributed to Yan Liben, who was recorded as having painted portraits of Taizong and of foreign kings and envoys who sent offerings to his court in 642. The unseen focus of the event is Princess Wencheng, who like Wang Zhaojun remains hidden while still acting as the bridge between Chinese and Tibetan regimes and cultures. The group portrait served as visual authentication of the diplomatic audience that initiated the alliance, as a kind of pictorial marriage contract.

Women in a Palace, China, seventeenth century. The Metropolitan Museum of Art, purchase, Vincent Astor Foundation gift, 2001.

Marriage, diplomacy, power, portraiture, and piety were at times densely intertwined at the Mogao Grottoes, the Buddhist cave temple complex at Dunhuang in present-day northwest China. Dunhuang was a crossroads for merchants and pilgrims traveling the overland Silk Road routes between China and central and western Asia. The region also had a complex political and cultural history, including a period of independent rule of powerful local generals and families with little more than nominal allegiance to Chinese dynastic authority. Under such circumstances strategic alliances with neighboring regimes were all the more important, as documented in caves sponsored by Cao Yijin, who took power in the Dunhuang region in 914 as commander of a “Return to Righteousness” army. A mural painting in Cave 98 in part commemorates the alliance marriage in 934 of Cao’s second daughter to the king of Khotan, Li Shengtian (also known as Viśa’ Sambhava), ruler of that prosperous center of jade mining and trade from 912 to 966. The portrait of the Khotanese king, who bears a gilded incense burner and flower as if leading a pious procession, was painted over an earlier mural sometime after 940 as a way of asserting his status as donor of the cave, in place of the actual sponsor Cao Yijin, who died in 935. The imposing figure of Li Shengtian is almost ten feet high, including a tall openwork crown encrusted with nephrite jade stones in gold settings surmounted by a parasol borne by celestial children, while goddesses support his feet, all signs of the Khotanese king’s semi-divine status. He wears robes decorated with dragon designs in the Chinese imperial pattern and a massive sword as symbols of his terrestrial power. As with most donor portraits from Dunhuang his face seems more generally idealized than specific, but his thin nose and long eyes may have been marks of his ethnic identity. His bride’s similarly ornate crown with pendant jade branches and her ropes of jade necklaces also reference the mineral source of Khotan’s wealth and influence. Her face is obscured by damage to the wall surface, but both portraits were likely painted by members of a local Dunhuang painting academy established by her ruler-father Cao Yijin. Other portrait figures in the cave wear Uyghur costumes, reflecting Cao Yijin’s own earlier alliance marriage to a princess of that neighboring regime.

Li Shengtian and the daughter of Cao Yijin, from Cave 98.

Portraits could serve other diplomatic purposes beyond documenting or facilitating alliance marriages. The founding emperor of the Song dynasty, known as Taizu (r. 960–76), dispatched his court painter and portrait specialist Wang Ai to Nanjing (then called Jinling) to secretly sketch the portraits of three leaders of the remnant Southern Tang regime based there, which held out against Song pressure for some sixteen years before finally surrendering in 976. The subjects of the secret portraits included Han Xizai, also surreptitiously, and more famously depicted by the Southern Tang court painter Gu Hongzhong at the behest of his own ruler. In 988 the founding Song emperor’s brother and successor Taizong (r. 976–97) ordered Mou Gu, another portrait specialist, to accompany envoys to the region of modern Vietnam, an independent state since 939, where he remained for several years and painted portraits of the local king and his ministers. In 1053 Emperor Xingzong (r. 1031–55) of the Khitan Liao empire, a northern neighboring and rival regime contemporary with the Northern Song, sent portraits of three Liao rulers to the court of the Song emperor Renzong, with a request that a portrait of Renzong be exchanged in return.

Although Xingzong died before the Song court could fulfill his request, the Song court asked that a portrait of the Liao ruler’s successor be sent to them immediately. The new Liao ruler asked the Song court to first fulfill their part of the bargain, but the Song argued that the relationship between the two regimes, although designated by their joint treaty of Shanyuan in 1004 as between equals, should be seen as equivalent to that between (Song) uncle and (Liao) nephew rather than one of full equality. The episode suggests that possession of a foreign imperial portrait, beyond questions of reciprocal gift exchange and attendant contests of higher and lower status, may have carried the aura of a talismanic object conferring power over the portrayed subject.

 

Reprinted with permission from Facing China: Truth and Memory in Portraiture by Richard Vinograd, published by Reaktion Books Ltd. Copyright © Richard Vinograd 2022. All rights reserved.



from Hacker News https://ift.tt/E4yQoFu

Everyone quotes command line arguments the wrong way

Everyone quotes command line arguments the wrong way

  • Article
  • 9 minutes to read

Background

At one time or another, we all need to pass arbitrary command line arguments to some program. These arguments could be filenames, debugging flags, hostnames, or any other kind of information: the point is that we are to take a string and make sure some child program receives exactly that string in its argv array no matter what this string contains. The task is harder than it appears.

For better or for worse1, Windows knows about only one command line string for each process. Because one string is not terribly useful, libraries conspire to provide the illusion of multiple command line arguments: before creating a subprocess, a program combines all argument strings into one command line string, and the newly-born subprocess, before calling main, splits this string into arguments and passes the arguments as argv. In principle, each program can parse the command line string differently, but most use the convetion that CommandLineToArgvW and the Microsoft C library understand. This convention is a good one because it provides a way to encode any command line argument as part of a command line string without losing information.

The problem is that there is no ArgvToCommandLineW. How do we construct an argument string understood by CommandLineToArgvW?

Test program

For exposition's sake, we'll be using this small program to generate the example output below:

 
#include <stdio.h>
int __cdecl
wmain(int, wchar_t** argv)
{
    for (int arg = 0; argv[arg]; ++arg) {
        wprintf (L"%d: [%s]\n", arg, argv[arg]);
    }
}

Popular solutions: clear, simple, and wrong

The C runtime library is useless

Our first instinct should be look for a library function that's already solved the problem. Were we to conduct this search, we would quickly find functions provided by the C runtime specifically for running subprocesses: the _exec and _spawn families. These functions appear to be precisely what we need: they take an arbitrary number of distinct command line arguments and promise to launch a subprocess. Unfortunately and counter-intuitively, these functions do not quote or process these arguments: instead, they're all concatenated into a single string, with arguments separated spaces, and this string is then passed to the child, where it's eventually interpreted by CommandLineToArgvW. This approach works only for arguments that do not themselves contain spaces.

Thus, if we run child.exe like this:

 _spawnlp (_P_WAIT, L"child.exe", L"child.exe", L"argument 1", L"argument 2", NULL)

child.exe receives five command line parameters:

 
0: [child.exe]
1: [argument]
2: [1]
3: [argument]
4: [2]

That's not what we want! So, while the C runtime process-launching functions appear to be what we need, they're actually useless for solving the command line argument problem.

Adding quotation marks is insufficient

Having seen the problems with the previous approach, one might suggest that we heed the advice provided in the the C runtime documentation and surround arguments containing spaces with double-quote characters. This solution is also wrong.

Recall2 that the CommandLineToArgV convention3 stipulates that arguments containing spaces be surrounded by double quotation marks. Following the above approach and surrounding arguments with quotation marks produces good results for simple cases, and many people stop here.

 
child.exe argument1 "argument 2"  "\some\path with\spaces"

Is correctly interpreted as:

 
0: [child.exe]
1: [argument1]
2: [argument 2]
3: [\some\path with\spaces]

So far, so good: but what if our arguments are more complex? Bear in mind that our convention also stipulates that we precede a double quotation mark that is part of an argument with a backslash, and that we precede with another backslash a backslash that precedes a quotation mark which itself actually terminates the argument and is not included as part of that argument4. So, if we follow our simplistic approach above and use this as our command line:

 
child.exe argument1 "she said, "you had me at hello""  "\some\path with\spaces"

then the child sees:

 
0: [child.exe]
1: [argument1]
2: [she said, you]
3: [had]
4: [me]
5: [at]
6: [hello]
7: [\some\path with\spaces]

We don't want that either! The problem becomes more insidious when quotes are unbalanced:

 
child.exe argument1 "argument"2" argument3 argument4
0: [child.exe]
1: [argument1]
2: [argument2 argument3 argument4]

Arguments ending with backslashes also lead to undesired interpretations:

 
child.exe "\some\directory with\spaces\" argument2

0: [child.exe]
1: [\some\directory with\spaces" argument2]

Many popular programs (including command shells, the authors of which really should know better) use this simple approach. Developers test only with simple argument strings, leaving users confused and puzzled when their command lines are occasionally mangled.

The correct solution

We've seen that properly quoting an arbitrary command line argument is non-trivial, and that doing it incorrectly causes subtle and maddening problems. The function below properly quotes an argument; translate it into your language and coding style of choice.

 
void
ArgvQuote (
    const std::wstring& Argument,
    std::wstring& CommandLine,
    bool Force
    )
    
/*++
    
Routine Description:
    
    This routine appends the given argument to a command line such
    that CommandLineToArgvW will return the argument string unchanged.
    Arguments in a command line should be separated by spaces; this
    function does not add these spaces.
    
Arguments:
    
    Argument - Supplies the argument to encode.

    CommandLine - Supplies the command line to which we append the encoded argument string.

    Force - Supplies an indication of whether we should quote
            the argument even if it does not contain any characters that would
            ordinarily require quoting.
    
Return Value:
    
    None.
    
Environment:
    
    Arbitrary.
    
--*/
    
{
    //
    // Unless we're told otherwise, don't quote unless we actually
    // need to do so --- hopefully avoid problems if programs won't
    // parse quotes properly
    //
    
    if (Force == false &&
        Argument.empty () == false &&
        Argument.find_first_of (L" \t\n\v\"") == Argument.npos)
    {
        CommandLine.append (Argument);
    }
    else {
        CommandLine.push_back (L'"');
        
        for (auto It = Argument.begin () ; ; ++It) {
            unsigned NumberBackslashes = 0;
        
            while (It != Argument.end () && *It == L'\\') {
                ++It;
                ++NumberBackslashes;
            }
        
            if (It == Argument.end ()) {
                
                //
                // Escape all backslashes, but let the terminating
                // double quotation mark we add below be interpreted
                // as a metacharacter.
                //
                
                CommandLine.append (NumberBackslashes * 2, L'\\');
                break;
            }
            else if (*It == L'"') {

                //
                // Escape all backslashes and the following
                // double quotation mark.
                //
                
                CommandLine.append (NumberBackslashes * 2 + 1, L'\\');
                CommandLine.push_back (*It);
            }
            else {
                
                //
                // Backslashes aren't special here.
                //
                
                CommandLine.append (NumberBackslashes, L'\\');
                CommandLine.push_back (*It);
            }
        }
    
        CommandLine.push_back (L'"');
    }
}

To construct a command line string for a program from arbitrary arguments, we encode each argument (including the program name) with the above function and follow all but the last with a single space. We can then pass the resulting string as the lpCommandLine parameter to CreateProcess and be confident that the child process will decode each argument to exactly the arguments we were initially given.

cmd.exe

One might conclude that we're done: after all, we now understand how to send arbitrary strings through CreateProcess so that they emerge unchanged on the other side --- but life is not that simple. Often, we can't directly supply our command line CreateProcess, but instead must pass it through a level of indirection before reaching our intended child process. The most common indirection is a trip trough the venerable cmd.exe, which we encounter when we use the system function, construct a script for later execution, write a makefile for nmake, and do many other things. Because the quoting rules for CommandLineToArgvWcmd's differ from those of cmd, we cannot give a command line intended for the former to the latter and and expect our arguments to survive the trip. Because this difference is subtle, it's easy to forget about it and leave latent bugs in programs that interact with cmd.

cmd is essentially a text preprocessor: given a command line, it makes a series of textual transformations, then hands the transformed command line to CreateProcess. Some transformations replace environment variable names with their values. Some transformations, such as IO redirection, have useful side effects. Some transformations, such as those triggered by the &, ||, && operators, split command lines into several parts. It's important to note that cmd doesn't know or care about command line arguments per se: to cmd, the world is made up of whole command lines. Like the post office delivering postcards, cmd doesn't try to understand what is handles: it merely does its limited job (via these transformations), then leaves it another program to figure out what the final command line means.

All of cmd's transformations are triggered by the presence of one of the metacharacters (, ), %, !, ^, ", <, >, &, and |. " is particularly interesting: when cmd is transforming a command line and sees a ", it copies a " to the new command line, then begins copying characters from the old command line to the new one without seeing whether any of these characters is a metacharacter. This copying continues until cmd either reaches the end of the command line, runs into a variable substitution, or sees another ". In the last case, cmd copies a " to the new command line and resumes normal processing. This behavior is almost, but not quite like what CommandLineFromArgvW does with the same character4; the difference is that cmd does not know about the \" sequence and begins interpreting metacharacters earlier than we would expect. It should be apparent why the commands below produce the indicated output:

 
C:\> child "hello world" >\\.\nul

C:\> child "hello"world" >\\.\nul
0: [child]
1: [helloworld >\\.\nul]

C:\> child "hello\"world" >\\.\nul
0: [child]
1: [hello"world]
2: [>\\.\nul]

C:\>

If we relying on cmd's "-behavior to protect arguments, quotation marks will produce unexpected behavior. If we pass untrusted data as command line parameters, then the bugs caused by this convention mismatch become a security issues:

 
C:\> child "malicious argument\" &whoami"
0: [child]
1: [malicious-argument"]
ntdev\dancol

Here, cmd is interpreting the & metacharacter as a command separator because, from its point of view, the & character lies outside the quoted region. whoami, of course, can be replaced by any number of harmful commands. Note that this command is properly formatted for use with CreateProcess: it's the passing through cmd that causes trouble.

A better method of quoting

While the " metacharacter cannot fully protect metacharacters in our command lines against unintended shell interpretation, the ^ metacharacter can. When cmd transforms a command line and sees a ^, it ignores the ^ character itself and copies the next character to the new command line literally, metacharacter or not. That's why ^ works as the line continuation character: it tells cmd to copy a subsequent newline as itself instead of regarding that newline as a command terminator. If we prefix with ^ every metacharacter in an argument string, cmd will transform that string into the one we mean to use.

 
C:\> child ^"malicious argument\^"^&whoami^"
0: [child]
1: [malicious argument"&whoami]

It's important to also ^-escape " characters: otherwise, cmd would literally copy ^ characters appearing between " pairs, mangling the argument string in the process:

 
C:\> child "malicious-argument\^"^&whoami"
0: [child]
1: [malicious-argument\^&whoami]

In effect, because cmd's " handling is useless for our purposes, we use ^ to tell cmd to not attempt to be smart about quote detection.

Conclusion

In general, we can safely pass arbitrary command line arguments to programs, provided we take a few basic precautions.

Do:

  1. Always escape all arguments so that they will be decoded properly by CommandLineToArgvW, perhaps using my ArgvQuote function above.
  2. After step 1, then if and only if the command line produced will be interpreted by cmd, prefix each shell metacharacter (or each character) with a ^ character.

Do not:

  1. Simply add quotes around command line argument arguments without any further processing.
  2. Allow cmd to ever see an unescaped " character.

Notes

1 Worse.
2 You did follow my links above, yes?
3 I know you didn't.
4 Just to be clear: CommandLineFromArgvW neither knows nor cares about cmd's metacharacters and looks only for " and \.



from Hacker News https://ift.tt/68c1bfQ